sqlite3.c 7.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231184232184233184234184235184236184237184238184239184240184241184242184243184244184245184246184247184248184249184250184251184252184253184254184255184256184257184258184259184260184261184262184263184264184265184266184267184268184269184270184271184272184273184274184275184276184277184278184279184280184281184282184283184284184285184286184287184288184289184290184291184292184293184294184295184296184297184298184299184300184301184302184303184304184305184306184307184308184309184310184311184312184313184314184315184316184317184318184319184320184321184322184323184324184325184326184327184328184329184330184331184332184333184334184335184336184337184338184339184340184341184342184343184344184345184346184347184348184349184350184351184352184353184354184355184356184357184358184359184360184361184362184363184364184365184366184367184368184369184370184371184372184373184374184375184376184377184378184379184380184381184382184383184384184385184386184387184388184389184390184391184392184393184394184395184396184397184398184399184400184401184402184403184404184405184406184407184408184409184410184411184412184413184414184415184416184417184418184419184420184421184422184423184424184425184426184427184428184429184430184431184432184433184434184435184436184437184438184439184440184441184442184443184444184445184446184447184448184449184450184451184452184453184454184455184456184457184458184459184460184461184462184463184464184465184466184467184468184469184470184471184472184473184474184475184476184477184478184479184480184481184482184483184484184485184486184487184488184489184490184491184492184493184494184495184496184497184498184499184500184501184502184503184504184505184506184507184508184509184510184511184512184513184514184515184516184517184518184519184520184521184522184523184524184525184526184527184528184529184530184531184532184533184534184535184536184537184538184539184540184541184542184543184544184545184546184547184548184549184550184551184552184553184554184555184556184557184558184559184560184561184562184563184564184565184566184567184568184569184570184571184572184573184574184575184576184577184578184579184580184581184582184583184584184585184586184587184588184589184590184591184592184593184594184595184596184597184598184599184600184601184602184603184604184605184606184607184608184609184610184611184612184613184614184615184616184617184618184619184620184621184622184623184624184625184626184627184628184629184630184631184632184633184634184635184636184637184638184639184640184641184642184643184644184645184646184647184648184649184650184651184652184653184654184655184656184657184658184659184660184661184662184663184664184665184666184667184668184669184670184671184672184673184674184675184676184677184678184679184680184681184682184683184684184685184686184687184688184689184690184691184692184693184694184695184696184697184698184699184700184701184702184703184704184705184706184707184708184709184710184711184712184713184714184715184716184717184718184719184720184721184722184723184724184725184726184727184728184729184730184731184732184733184734184735184736184737184738184739184740184741184742184743184744184745184746184747184748184749184750184751184752184753184754184755184756184757184758184759184760184761184762184763184764184765184766184767184768184769184770184771184772184773184774184775184776184777184778184779184780184781184782184783184784184785184786184787184788184789184790184791184792184793184794184795184796184797184798184799184800184801184802184803184804184805184806184807184808184809184810184811184812184813184814184815184816184817184818184819184820184821184822184823184824184825184826184827184828184829184830184831184832184833184834184835184836184837184838184839184840184841184842184843184844184845184846184847184848184849184850184851184852184853184854184855184856184857184858184859184860184861184862184863184864184865184866184867184868184869184870184871184872184873184874184875184876184877184878184879184880184881184882184883184884184885184886184887184888184889184890184891184892184893184894184895184896184897184898184899184900184901184902184903184904184905184906184907184908184909184910184911184912184913184914184915184916184917184918184919184920184921184922184923184924184925184926184927184928184929184930184931184932184933184934184935184936184937184938184939184940184941184942184943184944184945184946184947184948184949184950184951184952184953184954184955184956184957184958184959184960184961184962184963184964184965184966184967184968184969184970184971184972184973184974184975184976184977184978184979184980184981184982184983184984184985184986184987184988184989184990184991184992184993184994184995184996184997184998184999185000185001185002185003185004185005185006185007185008185009185010185011185012185013185014185015185016185017185018185019185020185021185022185023185024185025185026185027185028185029185030185031185032185033185034185035185036185037185038185039185040185041185042185043185044185045185046185047185048185049185050185051185052185053185054185055185056185057185058185059185060185061185062185063185064185065185066185067185068185069185070185071185072185073185074185075185076185077185078185079185080185081185082185083185084185085185086185087185088185089185090185091185092185093185094185095185096185097185098185099185100185101185102185103185104185105185106185107185108185109185110185111185112185113185114185115185116185117185118185119185120185121185122185123185124185125185126185127185128185129185130185131185132185133185134185135185136185137185138185139185140185141185142185143185144185145185146185147185148185149185150185151185152185153185154185155185156185157185158185159185160185161185162185163185164185165185166185167185168185169185170185171185172185173185174185175185176185177185178185179185180185181185182185183185184185185185186185187185188185189185190185191185192185193185194185195185196185197185198185199185200185201185202185203185204185205185206185207185208185209185210185211185212185213185214185215185216185217185218185219185220185221185222185223185224185225185226185227185228185229185230185231185232185233185234185235185236185237185238185239185240185241185242185243185244185245185246185247185248185249185250185251185252185253185254185255185256185257185258185259185260185261185262185263185264185265185266185267185268185269185270185271185272185273185274185275185276185277185278185279185280185281185282185283185284185285185286185287185288185289185290185291185292185293185294185295185296185297185298185299185300185301185302185303185304185305185306185307185308185309185310185311185312185313185314185315185316185317185318185319185320185321185322185323185324185325185326185327185328185329185330185331185332185333185334185335185336185337185338185339185340185341185342185343185344185345185346185347185348185349185350185351185352185353185354185355185356185357185358185359185360185361185362185363185364185365185366185367185368185369185370185371185372185373185374185375185376185377185378185379185380185381185382185383185384185385185386185387185388185389185390185391185392185393185394185395185396185397185398185399185400185401185402185403185404185405185406185407185408185409185410185411185412185413185414185415185416185417185418185419185420185421185422185423185424185425185426185427185428185429185430185431185432185433185434185435185436185437185438185439185440185441185442185443185444185445185446185447185448185449185450185451185452185453185454185455185456185457185458185459185460185461185462185463185464185465185466185467185468185469185470185471185472185473185474185475185476185477185478185479185480185481185482185483185484185485185486185487185488185489185490185491185492185493185494185495185496185497185498185499185500185501185502185503185504185505185506185507185508185509185510185511185512185513185514185515185516185517185518185519185520185521185522185523185524185525185526185527185528185529185530185531185532185533185534185535185536185537185538185539185540185541185542185543185544185545185546185547185548185549185550185551185552185553185554185555185556185557185558185559185560185561185562185563185564185565185566185567185568185569185570185571185572185573185574185575185576185577185578185579185580185581185582185583185584185585185586185587185588185589185590185591185592185593185594185595185596185597185598185599185600185601185602185603185604185605185606185607185608185609185610185611185612185613185614185615185616185617185618185619185620185621185622185623185624185625185626185627185628185629185630185631185632185633185634185635185636185637185638185639185640185641185642185643185644185645185646185647185648185649185650185651185652185653185654185655185656185657185658185659185660185661185662185663185664185665185666185667185668185669185670185671185672185673185674185675185676185677185678185679185680185681185682185683185684185685185686185687185688185689185690185691185692185693185694185695185696185697185698185699185700185701185702185703185704185705185706185707185708185709185710185711185712185713185714185715185716185717185718185719185720185721185722185723185724185725185726185727185728185729185730185731185732185733185734185735185736185737185738185739185740185741185742185743185744185745185746185747185748185749185750185751185752185753185754185755185756185757185758185759185760185761185762185763185764185765185766185767185768185769185770185771185772185773185774185775185776185777185778185779185780185781185782185783185784185785185786185787185788185789185790185791185792185793185794185795185796185797185798185799185800185801185802185803185804185805185806185807185808185809185810185811185812185813185814185815185816185817185818185819185820185821185822185823185824185825185826185827185828185829185830185831185832185833185834185835185836185837185838185839185840185841185842185843185844185845185846185847185848185849185850185851185852185853185854185855185856185857185858185859185860185861185862185863185864185865185866185867185868185869185870185871185872185873185874185875185876185877185878185879185880185881185882185883185884185885185886185887185888185889185890185891185892185893185894185895185896185897185898185899185900185901185902185903185904185905185906185907185908185909185910185911185912185913185914185915185916185917185918185919185920185921185922185923185924185925185926185927185928185929185930185931185932185933185934185935185936185937185938185939185940185941185942185943185944185945185946185947185948185949185950185951185952185953185954185955185956185957185958185959185960185961185962185963185964185965185966185967185968185969185970185971185972185973185974185975185976185977185978185979185980185981185982185983185984185985185986185987185988185989185990185991185992185993185994185995185996185997185998185999186000186001186002186003186004186005186006186007186008186009186010186011186012186013186014186015186016186017186018186019186020186021186022186023186024186025186026186027186028186029186030186031186032186033186034186035186036186037186038186039186040186041186042186043186044186045186046186047186048186049186050186051186052186053186054186055186056186057186058186059186060186061186062186063186064186065186066186067186068186069186070186071186072186073186074186075186076186077186078186079186080186081186082186083186084186085186086186087186088186089186090186091186092186093186094186095186096186097186098186099186100186101186102186103186104186105186106186107186108186109186110186111186112186113186114186115186116186117186118186119186120186121186122186123186124186125186126186127186128186129186130186131186132186133186134186135186136186137186138186139186140186141186142186143186144186145186146186147186148186149186150186151186152186153186154186155186156186157186158186159186160186161186162186163186164186165186166186167186168186169186170186171186172186173186174186175186176186177186178186179186180186181186182186183186184186185186186186187186188186189186190186191186192186193186194186195186196186197186198186199186200186201186202186203186204186205186206186207186208186209186210186211186212186213186214186215186216186217186218186219186220186221186222186223186224186225186226186227186228186229186230186231186232186233186234186235186236186237186238186239186240186241186242186243186244186245186246186247186248186249186250186251186252186253186254186255186256186257186258186259186260186261186262186263186264186265186266186267186268186269186270186271186272186273186274186275186276186277186278186279186280186281186282186283186284186285186286186287186288186289186290186291186292186293186294186295186296186297186298186299186300186301186302186303186304186305186306186307186308186309186310186311186312186313186314186315186316186317186318186319186320186321186322186323186324186325186326186327186328186329186330186331186332186333186334186335186336186337186338186339186340186341186342186343186344186345186346186347186348186349186350186351186352186353186354186355186356186357186358186359186360186361186362186363186364186365186366186367186368186369186370186371186372186373186374186375186376186377186378186379186380186381186382186383186384186385186386186387186388186389186390186391186392186393186394186395186396186397186398186399186400186401186402186403186404186405186406186407186408186409186410186411186412186413186414186415186416186417186418186419186420186421186422186423186424186425186426186427186428186429186430186431186432186433186434186435186436186437186438186439186440186441186442186443186444186445186446186447186448186449186450186451186452186453186454186455186456186457186458186459186460186461186462186463186464186465186466186467186468186469186470186471186472186473186474186475186476186477186478186479186480186481186482186483186484186485186486186487186488186489186490186491186492186493186494186495186496186497186498186499186500186501186502186503186504186505186506186507186508186509186510186511186512186513186514186515186516186517186518186519186520186521186522186523186524186525186526186527186528186529186530186531186532186533186534186535186536186537186538186539186540186541186542186543186544186545186546186547186548186549186550186551186552186553186554186555186556186557186558186559186560186561186562186563186564186565186566186567186568186569186570186571186572186573186574186575186576186577186578186579186580186581186582186583186584186585186586186587186588186589186590186591186592186593186594186595186596186597186598186599186600186601186602186603186604186605186606186607186608186609186610186611186612186613186614186615186616186617186618186619186620186621186622186623186624186625186626186627186628186629186630186631186632186633186634186635186636186637186638186639186640186641186642186643186644186645186646186647186648186649186650186651186652186653186654186655186656186657186658186659186660186661186662186663186664186665186666186667186668186669186670186671186672186673186674186675186676186677186678186679186680186681186682186683186684186685186686186687186688186689186690186691186692186693186694186695186696186697186698186699186700186701186702186703186704186705186706186707186708186709186710186711186712186713186714186715186716186717186718186719186720186721186722186723186724186725186726186727186728186729186730186731186732186733186734186735186736186737186738186739186740186741186742186743186744186745186746186747186748186749186750186751186752186753186754186755186756186757186758186759186760186761186762186763186764186765186766186767186768186769186770186771186772186773186774186775186776186777186778186779186780186781186782186783186784186785186786186787186788186789186790186791186792186793186794186795186796186797186798186799186800186801186802186803186804186805186806186807186808186809186810186811186812186813186814186815186816186817186818186819186820186821186822186823186824186825186826186827186828186829186830186831186832186833186834186835186836186837186838186839186840186841186842186843186844186845186846186847186848186849186850186851186852186853186854186855186856186857186858186859186860186861186862186863186864186865186866186867186868186869186870186871186872186873186874186875186876186877186878186879186880186881186882186883186884186885186886186887186888186889186890186891186892186893186894186895186896186897186898186899186900186901186902186903186904186905186906186907186908186909186910186911186912186913186914186915186916186917186918186919186920186921186922186923186924186925186926186927186928186929186930186931186932186933186934186935186936186937186938186939186940186941186942186943186944186945186946186947186948186949186950186951186952186953186954186955186956186957186958186959186960186961186962186963186964186965186966186967186968186969186970186971186972186973186974186975186976186977186978186979186980186981186982186983186984186985186986186987186988186989186990186991186992186993186994186995186996186997186998186999187000187001187002187003187004187005187006187007187008187009187010187011187012187013187014187015187016187017187018187019187020187021187022187023187024187025187026187027187028187029187030187031187032187033187034187035187036187037187038187039187040187041187042187043187044187045187046187047187048187049187050187051187052187053187054187055187056187057187058187059187060187061187062187063187064187065187066187067187068187069187070187071187072187073187074187075187076187077187078187079187080187081187082187083187084187085187086187087187088187089187090187091187092187093187094187095187096187097187098187099187100187101187102187103187104187105187106187107187108187109187110187111187112187113187114187115187116187117187118187119187120187121187122187123187124187125187126187127187128187129187130187131187132187133187134187135187136187137187138187139187140187141187142187143187144187145187146187147187148187149187150187151187152187153187154187155187156187157187158187159187160187161187162187163187164187165187166187167187168187169187170187171187172187173187174187175187176187177187178187179187180187181187182187183187184187185187186187187187188187189187190187191187192187193187194187195187196187197187198187199187200187201187202187203187204187205187206187207187208187209187210187211187212187213187214187215187216187217187218187219187220187221187222187223187224187225187226187227187228187229187230187231187232187233187234187235187236187237187238187239187240187241187242187243187244187245187246187247187248187249187250187251187252187253187254187255187256187257187258187259187260187261187262187263187264187265187266187267187268187269187270187271187272187273187274187275187276187277187278187279187280187281187282187283187284187285187286187287187288187289187290187291187292187293187294187295187296187297187298187299187300187301187302187303187304187305187306187307187308187309187310187311187312187313187314187315187316187317187318187319187320187321187322187323187324187325187326187327187328187329187330187331187332187333187334187335187336187337187338187339187340187341187342187343187344187345187346187347187348187349187350187351187352187353187354187355187356187357187358187359187360187361187362187363187364187365187366187367187368187369187370187371187372187373187374187375187376187377187378187379187380187381187382187383187384187385187386187387187388187389187390187391187392187393187394187395187396187397187398187399187400187401187402187403187404187405187406187407187408187409187410187411187412187413187414187415187416187417187418187419187420187421187422187423187424187425187426187427187428187429187430187431187432187433187434187435187436187437187438187439187440187441187442187443187444187445187446187447187448187449187450187451187452187453187454187455187456187457187458187459187460187461187462187463187464187465187466187467187468187469187470187471187472187473187474187475187476187477187478187479187480187481187482187483187484187485187486187487187488187489187490187491187492187493187494187495187496187497187498187499187500187501187502187503187504187505187506187507187508187509187510187511187512187513187514187515187516187517187518187519187520187521187522187523187524187525187526187527187528187529187530187531187532187533187534187535187536187537187538187539187540187541187542187543187544187545187546187547187548187549187550187551187552187553187554187555187556187557187558187559187560187561187562187563187564187565187566187567187568187569187570187571187572187573187574187575187576187577187578187579187580187581187582187583187584187585187586187587187588187589187590187591187592187593187594187595187596187597187598187599187600187601187602187603187604187605187606187607187608187609187610187611187612187613187614187615187616187617187618187619187620187621187622187623187624187625187626187627187628187629187630187631187632187633187634187635187636187637187638187639187640187641187642187643187644187645187646187647187648187649187650187651187652187653187654187655187656187657187658187659187660187661187662187663187664187665187666187667187668187669187670187671187672187673187674187675187676187677187678187679187680187681187682187683187684187685187686187687187688187689187690187691187692187693187694187695187696187697187698187699187700187701187702187703187704187705187706187707187708187709187710187711187712187713187714187715187716187717187718187719187720187721187722187723187724187725187726187727187728187729187730187731187732187733187734187735187736187737187738187739187740187741187742187743187744187745187746187747187748187749187750187751187752187753187754187755187756187757187758187759187760187761187762187763187764187765187766187767187768187769187770187771187772187773187774187775187776187777187778187779187780187781187782187783187784187785187786187787187788187789187790187791187792187793187794187795187796187797187798187799187800187801187802187803187804187805187806187807187808187809187810187811187812187813187814187815187816187817187818187819187820187821187822187823187824187825187826187827187828187829187830187831187832187833187834187835187836187837187838187839187840187841187842187843187844187845187846187847187848187849187850187851187852187853187854187855187856187857187858187859187860187861187862187863187864187865187866187867187868187869187870187871187872187873187874187875187876187877187878187879187880187881187882187883187884187885187886187887187888187889187890187891187892187893187894187895187896187897187898187899187900187901187902187903187904187905187906187907187908187909187910187911187912187913187914187915187916187917187918187919187920187921187922187923187924187925187926187927187928187929187930187931187932187933187934187935187936187937187938187939187940187941187942187943187944187945187946187947187948187949187950187951187952187953187954187955187956187957187958187959187960187961187962187963187964187965187966187967187968187969187970187971187972187973187974187975187976187977187978187979187980187981187982187983187984187985187986187987187988187989187990187991187992187993187994187995187996187997187998187999188000188001188002188003188004188005188006188007188008188009188010188011188012188013188014188015188016188017188018188019188020188021188022188023188024188025188026188027188028188029188030188031188032188033188034188035188036188037188038188039188040188041188042188043188044188045188046188047188048188049188050188051188052188053188054188055188056188057188058188059188060188061188062188063188064188065188066188067188068188069188070188071188072188073188074188075188076188077188078188079188080188081188082188083188084188085188086188087188088188089188090188091188092188093188094188095188096188097188098188099188100188101188102188103188104188105188106188107188108188109188110188111188112188113188114188115188116188117188118188119188120188121188122188123188124188125188126188127188128188129188130188131188132188133188134188135188136188137188138188139188140188141188142188143188144188145188146188147188148188149188150188151188152188153188154188155188156188157188158188159188160188161188162188163188164188165188166188167188168188169188170188171188172188173188174188175188176188177188178188179188180188181188182188183188184188185188186188187188188188189188190188191188192188193188194188195188196188197188198188199188200188201188202188203188204188205188206188207188208188209188210188211188212188213188214188215188216188217188218188219188220188221188222188223188224188225188226188227188228188229188230188231188232188233188234188235188236188237188238188239188240188241188242188243188244188245188246188247188248188249188250188251188252188253188254188255188256188257188258188259188260188261188262188263188264188265188266188267188268188269188270188271188272188273188274188275188276188277188278188279188280188281188282188283188284188285188286188287188288188289188290188291188292188293188294188295188296188297188298188299188300188301188302188303188304188305188306188307188308188309188310188311188312188313188314188315188316188317188318188319188320188321188322188323188324188325188326188327188328188329188330188331188332188333188334188335188336188337188338188339188340188341188342188343188344188345188346188347188348188349188350188351188352188353188354188355188356188357188358188359188360188361188362188363188364188365188366188367188368188369188370188371188372188373188374188375188376188377188378188379188380188381188382188383188384188385188386188387188388188389188390188391188392188393188394188395188396188397188398188399188400188401188402188403188404188405188406188407188408188409188410188411188412188413188414188415188416188417188418188419188420188421188422188423188424188425188426188427188428188429188430188431188432188433188434188435188436188437188438188439188440188441188442188443188444188445188446188447188448188449188450188451188452188453188454188455188456188457188458188459188460188461188462188463188464188465188466188467188468188469188470188471188472188473188474188475188476188477188478188479188480188481188482188483188484188485188486188487188488188489188490188491188492188493188494188495188496188497188498188499188500188501188502188503188504188505188506188507188508188509188510188511188512188513188514188515188516188517188518188519188520188521188522188523188524188525188526188527188528188529188530188531188532188533188534188535188536188537188538188539188540188541188542188543188544188545188546188547188548188549188550188551188552188553188554188555188556188557188558188559188560188561188562188563188564188565188566188567188568188569188570188571188572188573188574188575188576188577188578188579188580188581188582188583188584188585188586188587188588188589188590188591188592188593188594188595188596188597188598188599188600188601188602188603188604188605188606188607188608188609188610188611188612188613188614188615188616188617188618188619188620188621188622188623188624188625188626188627188628188629188630188631188632188633188634188635188636188637188638188639188640188641188642188643188644188645188646188647188648188649188650188651188652188653188654188655188656188657188658188659188660188661188662188663188664188665188666188667188668188669188670188671188672188673188674188675188676188677188678188679188680188681188682188683188684188685188686188687188688188689188690188691188692188693188694188695188696188697188698188699188700188701188702188703188704188705188706188707188708188709188710188711188712188713188714188715188716188717188718188719188720188721188722188723188724188725188726188727188728188729188730188731188732188733188734188735188736188737188738188739188740188741188742188743188744188745188746188747188748188749188750188751188752188753188754188755188756188757188758188759188760188761188762188763188764188765188766188767188768188769188770188771188772188773188774188775188776188777188778188779188780188781188782188783188784188785188786188787188788188789188790188791188792188793188794188795188796188797188798188799188800188801188802188803188804188805188806188807188808188809188810188811188812188813188814188815188816188817188818188819188820188821188822188823188824188825188826188827188828188829188830188831188832188833188834188835188836188837188838188839188840188841188842188843188844188845188846188847188848188849188850188851188852188853188854188855188856188857188858188859188860188861188862188863188864188865188866188867188868188869188870188871188872188873188874188875188876188877188878188879188880188881188882188883188884188885188886188887188888188889188890188891188892188893188894188895188896188897188898188899188900188901188902188903188904188905188906188907188908188909188910188911188912188913188914188915188916188917188918188919188920188921188922188923188924188925188926188927188928188929188930188931188932188933188934188935188936188937188938188939188940188941188942188943188944188945188946188947188948188949188950188951188952188953188954188955188956188957188958188959188960188961188962188963188964188965188966188967188968188969188970188971188972188973188974188975188976188977188978188979188980188981188982188983188984188985188986188987188988188989188990188991188992188993188994188995188996188997188998188999189000189001189002189003189004189005189006189007189008189009189010189011189012189013189014189015189016189017189018189019189020189021189022189023189024189025189026189027189028189029189030189031189032189033189034189035189036189037189038189039189040189041189042189043189044189045189046189047189048189049189050189051189052189053189054189055189056189057189058189059189060189061189062189063189064189065189066189067189068189069189070189071189072189073189074189075189076189077189078189079189080189081189082189083189084189085189086189087189088189089189090189091189092189093189094189095189096189097189098189099189100189101189102189103189104189105189106189107189108189109189110189111189112189113189114189115189116189117189118189119189120189121189122189123189124189125189126189127189128189129189130189131189132189133189134189135189136189137189138189139189140189141189142189143189144189145189146189147189148189149189150189151189152189153189154189155189156189157189158189159189160189161189162189163189164189165189166189167189168189169189170189171189172189173189174189175189176189177189178189179189180189181189182189183189184189185189186189187189188189189189190189191189192189193189194189195189196189197189198189199189200189201189202189203189204189205189206189207189208189209189210189211189212189213189214189215189216189217189218189219189220189221189222189223189224189225189226189227189228189229189230189231189232189233189234189235189236189237189238189239189240189241189242189243189244189245189246189247189248189249189250189251189252189253189254189255189256189257189258189259189260189261189262189263189264189265189266189267189268189269189270189271189272189273189274189275189276189277189278189279189280189281189282189283189284189285189286189287189288189289189290189291189292189293189294189295189296189297189298189299189300189301189302189303189304189305189306189307189308189309189310189311189312189313189314189315189316189317189318189319189320189321189322189323189324189325189326189327189328189329189330189331189332189333189334189335189336189337189338189339189340189341189342189343189344189345189346189347189348189349189350189351189352189353189354189355189356189357189358189359189360189361189362189363189364189365189366189367189368189369189370189371189372189373189374189375189376189377189378189379189380189381189382189383189384189385189386189387189388189389189390189391189392189393189394189395189396189397189398189399189400189401189402189403189404189405189406189407189408189409189410189411189412189413189414189415189416189417189418189419189420189421189422189423189424189425189426189427189428189429189430189431189432189433189434189435189436189437189438189439189440189441189442189443189444189445189446189447189448189449189450189451189452189453189454189455189456189457189458189459189460189461189462189463189464189465189466189467189468189469189470189471189472189473189474189475189476189477189478189479189480189481189482189483189484189485189486189487189488189489189490189491189492189493189494189495189496189497189498189499189500189501189502189503189504189505189506189507189508189509189510189511189512189513189514189515189516189517189518189519189520189521189522189523189524189525189526189527189528189529189530189531189532189533189534189535189536189537189538189539189540189541189542189543189544189545189546189547189548189549189550189551189552189553189554189555189556189557189558189559189560189561189562189563189564189565189566189567189568189569189570189571189572189573189574189575189576189577189578189579189580189581189582189583189584189585189586189587189588189589189590189591189592189593189594189595189596189597189598189599189600189601189602189603189604189605189606189607189608189609189610189611189612189613189614189615189616189617189618189619189620189621189622189623189624189625189626189627189628189629189630189631189632189633189634189635189636189637189638189639189640189641189642189643189644189645189646189647189648189649189650189651189652189653189654189655189656189657189658189659189660189661189662189663189664189665189666189667189668189669189670189671189672189673189674189675189676189677189678189679189680189681189682189683189684189685189686189687189688189689189690189691189692189693189694189695189696189697189698189699189700189701189702189703189704189705189706189707189708189709189710189711189712189713189714189715189716189717189718189719189720189721189722189723189724189725189726189727189728189729189730189731189732189733189734189735189736189737189738189739189740189741189742189743189744189745189746189747189748189749189750189751189752189753189754189755189756189757189758189759189760189761189762189763189764189765189766189767189768189769189770189771189772189773189774189775189776189777189778189779189780189781189782189783189784189785189786189787189788189789189790189791189792189793189794189795189796189797189798189799189800189801189802189803189804189805189806189807189808189809189810189811189812189813189814189815189816189817189818189819189820189821189822189823189824189825189826189827189828189829189830189831189832189833189834189835189836189837189838189839189840189841189842189843189844189845189846189847189848189849189850189851189852189853189854189855189856189857189858189859189860189861189862189863189864189865189866189867189868189869189870189871189872189873189874189875189876189877189878189879189880189881189882189883189884189885189886189887189888189889189890189891189892189893189894189895189896189897189898189899189900189901189902189903189904189905189906189907189908189909189910189911189912189913189914189915189916189917189918189919189920189921189922189923189924189925189926189927189928189929189930189931189932189933189934189935189936189937189938189939189940189941189942189943189944189945189946189947189948189949189950189951189952189953189954189955189956189957189958189959189960189961189962189963189964189965189966189967189968189969189970189971189972189973189974189975189976189977189978189979189980189981189982189983189984189985189986189987189988189989189990189991189992189993189994189995189996189997189998189999190000190001190002190003190004190005190006190007190008190009190010190011190012190013190014190015190016190017190018190019190020190021190022190023190024190025190026190027190028190029190030190031190032190033190034190035190036190037190038190039190040190041190042190043190044190045190046190047190048190049190050190051190052190053190054190055190056190057190058190059190060190061190062190063190064190065190066190067190068190069190070190071190072190073190074190075190076190077190078190079190080190081190082190083190084190085190086190087190088190089190090190091190092190093190094190095190096190097190098190099190100190101190102190103190104190105190106190107190108190109190110190111190112190113190114190115190116190117190118190119190120190121190122190123190124190125190126190127190128190129190130190131190132190133190134190135190136190137190138190139190140190141190142190143190144190145190146190147190148190149190150190151190152190153190154190155190156190157190158190159190160190161190162190163190164190165190166190167190168190169190170190171190172190173190174190175190176190177190178190179190180190181190182190183190184190185190186190187190188190189190190190191190192190193190194190195190196190197190198190199190200190201190202190203190204190205190206190207190208190209190210190211190212190213190214190215190216190217190218190219190220190221190222190223190224190225190226190227190228190229190230190231190232190233190234190235190236190237190238190239190240190241190242190243190244190245190246190247190248190249190250190251190252190253190254190255190256190257190258190259190260190261190262190263190264190265190266190267190268190269190270190271190272190273190274190275190276190277190278190279190280190281190282190283190284190285190286190287190288190289190290190291190292190293190294190295190296190297190298190299190300190301190302190303190304190305190306190307190308190309190310190311190312190313190314190315190316190317190318190319190320190321190322190323190324190325190326190327190328190329190330190331190332190333190334190335190336190337190338190339190340190341190342190343190344190345190346190347190348190349190350190351190352190353190354190355190356190357190358190359190360190361190362190363190364190365190366190367190368190369190370190371190372190373190374190375190376190377190378190379190380190381190382190383190384190385190386190387190388190389190390190391190392190393190394190395190396190397190398190399190400190401190402190403190404190405190406190407190408190409190410190411190412190413190414190415190416190417190418190419190420190421190422190423190424190425190426190427190428190429190430190431190432190433190434190435190436190437190438190439190440190441190442190443190444190445190446190447190448190449190450190451190452190453190454190455190456190457190458190459190460190461190462190463190464190465190466190467190468190469190470190471190472190473190474190475190476190477190478190479190480190481190482190483190484190485190486190487190488190489190490190491190492190493190494190495190496190497190498190499190500190501190502190503190504190505190506190507190508190509190510190511190512190513190514190515190516190517190518190519190520190521190522190523190524190525190526190527190528190529190530190531190532190533190534190535190536190537190538190539190540190541190542190543190544190545190546190547190548190549190550190551190552190553190554190555190556190557190558190559190560190561190562190563190564190565190566190567190568190569190570190571190572190573190574190575190576190577190578190579190580190581190582190583190584190585190586190587190588190589190590190591190592190593190594190595190596190597190598190599190600190601190602190603190604190605190606190607190608190609190610190611190612190613190614190615190616190617190618190619190620190621190622190623190624190625190626190627190628190629190630190631190632190633190634190635190636190637190638190639190640190641190642190643190644190645190646190647190648190649190650190651190652190653190654190655190656190657190658190659190660190661190662190663190664190665190666190667190668190669190670190671190672190673190674190675190676190677190678190679190680190681190682190683190684190685190686190687190688190689190690190691190692190693190694190695190696190697190698190699190700190701190702190703190704190705190706190707190708190709190710190711190712190713190714190715190716190717190718190719190720190721190722190723190724190725190726190727190728190729190730190731190732190733190734190735190736190737190738190739190740190741190742190743190744190745190746190747190748190749190750190751190752190753190754190755190756190757190758190759190760190761190762190763190764190765190766190767190768190769190770190771190772190773190774190775190776190777190778190779190780190781190782190783190784190785190786190787190788190789190790190791190792190793190794190795190796190797190798190799190800190801190802190803190804190805190806190807190808190809190810190811190812190813190814190815190816190817190818190819190820190821190822190823190824190825190826190827190828190829190830190831190832190833190834190835190836190837190838190839190840190841190842190843190844190845190846190847190848190849190850190851190852190853190854190855190856190857190858190859190860190861190862190863190864190865190866190867190868190869190870190871190872190873190874190875190876190877190878190879190880190881190882190883190884190885190886190887190888190889190890190891190892190893190894190895190896190897190898190899190900190901190902190903190904190905190906190907190908190909190910190911190912190913190914190915190916190917190918190919190920190921190922190923190924190925190926190927190928190929190930190931190932190933190934190935190936190937190938190939190940190941190942190943190944190945190946190947190948190949190950190951190952190953190954190955190956190957190958190959190960190961190962190963190964190965190966190967190968190969190970190971190972190973190974190975190976190977190978190979190980190981190982190983190984190985190986190987190988190989190990190991190992190993190994190995190996190997190998190999191000191001191002191003191004191005191006191007191008191009191010191011191012191013191014191015191016191017191018191019191020191021191022191023191024191025191026191027191028191029191030191031191032191033191034191035191036191037191038191039191040191041191042191043191044191045191046191047191048191049191050191051191052191053191054191055191056191057191058191059191060191061191062191063191064191065191066191067191068191069191070191071191072191073191074191075191076191077191078191079191080191081191082191083191084191085191086191087191088191089191090191091191092191093191094191095191096191097191098191099191100191101191102191103191104191105191106191107191108191109191110191111191112191113191114191115191116191117191118191119191120191121191122191123191124191125191126191127191128191129191130191131191132191133191134191135191136191137191138191139191140191141191142191143191144191145191146191147191148191149191150191151191152191153191154191155191156191157191158191159191160191161191162191163191164191165191166191167191168191169191170191171191172191173191174191175191176191177191178191179191180191181191182191183191184191185191186191187191188191189191190191191191192191193191194191195191196191197191198191199191200191201191202191203191204191205191206191207191208191209191210191211191212191213191214191215191216191217191218191219191220191221191222191223191224191225191226191227191228191229191230191231191232191233191234191235191236191237191238191239191240191241191242191243191244191245191246191247191248191249191250191251191252191253191254191255191256191257191258191259191260191261191262191263191264191265191266191267191268191269191270191271191272191273191274191275191276191277191278191279191280191281191282191283191284191285191286191287191288191289191290191291191292191293191294191295191296191297191298191299191300191301191302191303191304191305191306191307191308191309191310191311191312191313191314191315191316191317191318191319191320191321191322191323191324191325191326191327191328191329191330191331191332191333191334191335191336191337191338191339191340191341191342191343191344191345191346191347191348191349191350191351191352191353191354191355191356191357191358191359191360191361191362191363191364191365191366191367191368191369191370191371191372191373191374191375191376191377191378191379191380191381191382191383191384191385191386191387191388191389191390191391191392191393191394191395191396191397191398191399191400191401191402191403191404191405191406191407191408191409191410191411191412191413191414191415191416191417191418191419191420191421191422191423191424191425191426191427191428191429191430191431191432191433191434191435191436191437191438191439191440191441191442191443191444191445191446191447191448191449191450191451191452191453191454191455191456191457191458191459191460191461191462191463191464191465191466191467191468191469191470191471191472191473191474191475191476191477191478191479191480191481191482191483191484191485191486191487191488191489191490191491191492191493191494191495191496191497191498191499191500191501191502191503191504191505191506191507191508191509191510191511191512191513191514191515191516191517191518191519191520191521191522191523191524191525191526191527191528191529191530191531191532191533191534191535191536191537191538191539191540191541191542191543191544191545191546191547191548191549191550191551191552191553191554191555191556191557191558191559191560191561191562191563191564191565191566191567191568191569191570191571191572191573191574191575191576191577191578191579191580191581191582191583191584191585191586191587191588191589191590191591191592191593191594191595191596191597191598191599191600191601191602191603191604191605191606191607191608191609191610191611191612191613191614191615191616191617191618191619191620191621191622191623191624191625191626191627191628191629191630191631191632191633191634191635191636191637191638191639191640191641191642191643191644191645191646191647191648191649191650191651191652191653191654191655191656191657191658191659191660191661191662191663191664191665191666191667191668191669191670191671191672191673191674191675191676191677191678191679191680191681191682191683191684191685191686191687191688191689191690191691191692191693191694191695191696191697191698191699191700191701191702191703191704191705191706191707191708191709191710191711191712191713191714191715191716191717191718191719191720191721191722191723191724191725191726191727191728191729191730191731191732191733191734191735191736191737191738191739191740191741191742191743191744191745191746191747191748191749191750191751191752191753191754191755191756191757191758191759191760191761191762191763191764191765191766191767191768191769191770191771191772191773191774191775191776191777191778191779191780191781191782191783191784191785191786191787191788191789191790191791191792191793191794191795191796191797191798191799191800191801191802191803191804191805191806191807191808191809191810191811191812191813191814191815191816191817191818191819191820191821191822191823191824191825191826191827191828191829191830191831191832191833191834191835191836191837191838191839191840191841191842191843191844191845191846191847191848191849191850191851191852191853191854191855191856191857191858191859191860191861191862191863191864191865191866191867191868191869191870191871191872191873191874191875191876191877191878191879191880191881191882191883191884191885191886191887191888191889191890191891191892191893191894191895191896191897191898191899191900191901191902191903191904191905191906191907191908191909191910191911191912191913191914191915191916191917191918191919191920191921191922191923191924191925191926191927191928191929191930191931191932191933191934191935191936191937191938191939191940191941191942191943191944191945191946191947191948191949191950191951191952191953191954191955191956191957191958191959191960191961191962191963191964191965191966191967191968191969191970191971191972191973191974191975191976191977191978191979191980191981191982191983191984191985191986191987191988191989191990191991191992191993191994191995191996191997191998191999192000192001192002192003192004192005192006192007192008192009192010192011192012192013192014192015192016192017192018192019192020192021192022192023192024192025192026192027192028192029192030192031192032192033192034192035192036192037192038192039192040192041192042192043192044192045192046192047192048192049192050192051192052192053192054192055192056192057192058192059192060192061192062192063192064192065192066192067192068192069192070192071192072192073192074192075192076192077192078192079192080192081192082192083192084192085192086192087192088192089192090192091192092192093192094192095192096192097192098192099192100192101192102192103192104192105192106192107192108192109192110192111192112192113192114192115192116192117192118192119192120192121192122192123192124192125192126192127192128192129192130192131192132192133192134192135192136192137192138192139192140192141192142192143192144192145192146192147192148192149192150192151192152192153192154192155192156192157192158192159192160192161192162192163192164192165192166192167192168192169192170192171192172192173192174192175192176192177192178192179192180192181192182192183192184192185192186192187192188192189192190192191192192192193192194192195192196192197192198192199192200192201192202192203192204192205192206192207192208192209192210192211192212192213192214192215192216192217192218192219192220192221192222192223192224192225192226192227192228192229192230192231192232192233192234192235192236192237192238192239192240192241192242192243192244192245192246192247192248192249192250192251192252192253192254192255192256192257192258192259192260192261192262192263192264192265192266192267192268192269192270192271192272192273192274192275192276192277192278192279192280192281192282192283192284192285192286192287192288192289192290192291192292192293192294192295192296192297192298192299192300192301192302192303192304192305192306192307192308192309192310192311192312192313192314192315192316192317192318192319192320192321192322192323192324192325192326192327192328192329192330192331192332192333192334192335192336192337192338192339192340192341192342192343192344192345192346192347192348192349192350192351192352192353192354192355192356192357192358192359192360192361192362192363192364192365192366192367192368192369192370192371192372192373192374192375192376192377192378192379192380192381192382192383192384192385192386192387192388192389192390192391192392192393192394192395192396192397192398192399192400192401192402192403192404192405192406192407192408192409192410192411192412192413192414192415192416192417192418192419192420192421192422192423192424192425192426192427192428192429192430192431192432192433192434192435192436192437192438192439192440192441192442192443192444192445192446192447192448192449192450192451192452192453192454192455192456192457192458192459192460192461192462192463192464192465192466192467192468192469192470192471192472192473192474192475192476192477192478192479192480192481192482192483192484192485192486192487192488192489192490192491192492192493192494192495192496192497192498192499192500192501192502192503192504192505192506192507192508192509192510192511192512192513192514192515192516192517192518192519192520192521192522192523192524192525192526192527192528192529192530192531192532192533192534192535192536192537192538192539192540192541192542192543192544192545192546192547192548192549192550192551192552192553192554192555192556192557192558192559192560192561192562192563192564192565192566192567192568192569192570192571192572192573192574192575192576192577192578192579192580192581192582192583192584192585192586192587192588192589192590192591192592192593192594192595192596192597192598192599192600192601192602192603192604192605192606192607192608192609192610192611192612192613192614192615192616192617192618192619192620192621192622192623192624192625192626192627192628192629192630192631192632192633192634192635192636192637192638192639192640192641192642192643192644192645192646192647192648192649192650192651192652192653192654192655192656192657192658192659192660192661192662192663192664192665192666192667192668192669192670192671192672192673192674192675192676192677192678192679192680192681192682192683192684192685192686192687192688192689192690192691192692192693192694192695192696192697192698192699192700192701192702192703192704192705192706192707192708192709192710192711192712192713192714192715192716192717192718192719192720192721192722192723192724192725192726192727192728192729192730192731192732192733192734192735192736192737192738192739192740192741192742192743192744192745192746192747192748192749192750192751192752192753192754192755192756192757192758192759192760192761192762192763192764192765192766192767192768192769192770192771192772192773192774192775192776192777192778192779192780192781192782192783192784192785192786192787192788192789192790192791192792192793192794192795192796192797192798192799192800192801192802192803192804192805192806192807192808192809192810192811192812192813192814192815192816192817192818192819192820192821192822192823192824192825192826192827192828192829192830192831192832192833192834192835192836192837192838192839192840192841192842192843192844192845192846192847192848192849192850192851192852192853192854192855192856192857192858192859192860192861192862192863192864192865192866192867192868192869192870192871192872192873192874192875192876192877192878192879192880192881192882192883192884192885192886192887192888192889192890192891192892192893192894192895192896192897192898192899192900192901192902192903192904192905192906192907192908192909192910192911192912192913192914192915192916192917192918192919192920192921192922192923192924192925192926192927192928192929192930192931192932192933192934192935192936192937192938192939192940192941192942192943192944192945192946192947192948192949192950192951192952192953192954192955192956192957192958192959192960192961192962192963192964192965192966192967192968192969192970192971192972192973192974192975192976192977192978192979192980192981192982192983192984192985192986192987192988192989192990192991192992192993192994192995192996192997192998192999193000193001193002193003193004193005193006193007193008193009193010193011193012193013193014193015193016193017193018193019193020193021193022193023193024193025193026193027193028193029193030193031193032193033193034193035193036193037193038193039193040193041193042193043193044193045193046193047193048193049193050193051193052193053193054193055193056193057193058193059193060193061193062193063193064193065193066193067193068193069193070193071193072193073193074193075193076193077193078193079193080193081193082193083193084193085193086193087193088193089193090193091193092193093193094193095193096193097193098193099193100193101193102193103193104193105193106193107193108193109193110193111193112193113193114193115193116193117193118193119193120193121193122193123193124193125193126193127193128193129193130193131193132193133193134193135193136193137193138193139193140193141193142193143193144193145193146193147193148193149193150193151193152193153193154193155193156193157193158193159193160193161193162193163193164193165193166193167193168193169193170193171193172193173193174193175193176193177193178193179193180193181193182193183193184193185193186193187193188193189193190193191193192193193193194193195193196193197193198193199193200193201193202193203193204193205193206193207193208193209193210193211193212193213193214193215193216193217193218193219193220193221193222193223193224193225193226193227193228193229193230193231193232193233193234193235193236193237193238193239193240193241193242193243193244193245193246193247193248193249193250193251193252193253193254193255193256193257193258193259193260193261193262193263193264193265193266193267193268193269193270193271193272193273193274193275193276193277193278193279193280193281193282193283193284193285193286193287193288193289193290193291193292193293193294193295193296193297193298193299193300193301193302193303193304193305193306193307193308193309193310193311193312193313193314193315193316193317193318193319193320193321193322193323193324193325193326193327193328193329193330193331193332193333193334193335193336193337193338193339193340193341193342193343193344193345193346193347193348193349193350193351193352193353193354193355193356193357193358193359193360193361193362193363193364193365193366193367193368193369193370193371193372193373193374193375193376193377193378193379193380193381193382193383193384193385193386193387193388193389193390193391193392193393193394193395193396193397193398193399193400193401193402193403193404193405193406193407193408193409193410193411193412193413193414193415193416193417193418193419193420193421193422193423193424193425193426193427193428193429193430193431193432193433193434193435193436193437193438193439193440193441193442193443193444193445193446193447193448193449193450193451193452193453193454193455193456193457193458193459193460193461193462193463193464193465193466193467193468193469193470193471193472193473193474193475193476193477193478193479193480193481193482193483193484193485193486193487193488193489193490193491193492193493193494193495193496193497193498193499193500193501193502193503193504193505193506193507193508193509193510193511193512193513193514193515193516193517193518193519193520193521193522193523193524193525193526193527193528193529193530193531193532193533193534193535193536193537193538193539193540193541193542193543193544193545193546193547193548193549193550193551193552193553193554193555193556193557193558193559193560193561193562193563193564193565193566193567193568193569193570193571193572193573193574193575193576193577193578193579193580193581193582193583193584193585193586193587193588193589193590193591193592193593193594193595193596193597193598193599193600193601193602193603193604193605193606193607193608193609193610193611193612193613193614193615193616193617193618193619193620193621193622193623193624193625193626193627193628193629193630193631193632193633193634193635193636193637193638193639193640193641193642193643193644193645193646193647193648193649193650193651193652193653193654193655193656193657193658193659193660193661193662193663193664193665193666193667193668193669193670193671193672193673193674193675193676193677193678193679193680193681193682193683193684193685193686193687193688193689193690193691193692193693193694193695193696193697193698193699193700193701193702193703193704193705193706193707193708193709193710193711193712193713193714193715193716193717193718193719193720193721193722193723193724193725193726193727193728193729193730193731193732193733193734193735193736193737193738193739193740193741193742193743193744193745193746193747193748193749193750193751193752193753193754193755193756193757193758193759193760193761193762193763193764193765193766193767193768193769193770193771193772193773193774193775193776193777193778193779193780193781193782193783193784193785193786193787193788193789193790193791193792193793193794193795193796193797193798193799193800193801193802193803193804193805193806193807193808193809193810193811193812193813193814193815193816193817193818193819193820193821193822193823193824193825193826193827193828193829193830193831193832193833193834193835193836193837193838193839193840193841193842193843193844193845193846193847193848193849193850193851193852193853193854193855193856193857193858193859193860193861193862193863193864193865193866193867193868193869193870193871193872193873193874193875193876193877193878193879193880193881193882193883193884193885193886193887193888193889193890193891193892193893193894193895193896193897193898193899193900193901193902193903193904193905193906193907193908193909193910193911193912193913193914193915193916193917193918193919193920193921193922193923193924193925193926193927193928193929193930193931193932193933193934193935193936193937193938193939193940193941193942193943193944193945193946193947193948193949193950193951193952193953193954193955193956193957193958193959193960193961193962193963193964193965193966193967193968193969193970193971193972193973193974193975193976193977193978193979193980193981193982193983193984193985193986193987193988193989193990193991193992193993193994193995193996193997193998193999194000194001194002194003194004194005194006194007194008194009194010194011194012194013194014194015194016194017194018194019194020194021194022194023194024194025194026194027194028194029194030194031194032194033194034194035194036194037194038194039194040194041194042194043194044194045194046194047194048194049194050194051194052194053194054194055194056194057194058194059194060194061194062194063194064194065194066194067194068194069194070194071194072194073194074194075194076194077194078194079194080194081194082194083194084194085194086194087194088194089194090194091194092194093194094194095194096194097194098194099194100194101194102194103194104194105194106194107194108194109194110194111194112194113194114194115194116194117194118194119194120194121194122194123194124194125194126194127194128194129194130194131194132194133194134194135194136194137194138194139194140194141194142194143194144194145194146194147194148194149194150194151194152194153194154194155194156194157194158194159194160194161194162194163194164194165194166194167194168194169194170194171194172194173194174194175194176194177194178194179194180194181194182194183194184194185194186194187194188194189194190194191194192194193194194194195194196194197194198194199194200194201194202194203194204194205194206194207194208194209194210194211194212194213194214194215194216194217194218194219194220194221194222194223194224194225194226194227194228194229194230194231194232194233194234194235194236194237194238194239194240194241194242194243194244194245194246194247194248194249194250194251194252194253194254194255194256194257194258194259194260194261194262194263194264194265194266194267194268194269194270194271194272194273194274194275194276194277194278194279194280194281194282194283194284194285194286194287194288194289194290194291194292194293194294194295194296194297194298194299194300194301194302194303194304194305194306194307194308194309194310194311194312194313194314194315194316194317194318194319194320194321194322194323194324194325194326194327194328194329194330194331194332194333194334194335194336194337194338194339194340194341194342194343194344194345194346194347194348194349194350194351194352194353194354194355194356194357194358194359194360194361194362194363194364194365194366194367194368194369194370194371194372194373194374194375194376194377194378194379194380194381194382194383194384194385194386194387194388194389194390194391194392194393194394194395194396194397194398194399194400194401194402194403194404194405194406194407194408194409194410194411194412194413194414194415194416194417194418194419194420194421194422194423194424194425194426194427194428194429194430194431194432194433194434194435194436194437194438194439194440194441194442194443194444194445194446194447194448194449194450194451194452194453194454194455194456194457194458194459194460194461194462194463194464194465194466194467194468194469194470194471194472194473194474194475194476194477194478194479194480194481194482194483194484194485194486194487194488194489194490194491194492194493194494194495194496194497194498194499194500194501194502194503194504194505194506194507194508194509194510194511194512194513194514194515194516194517194518194519194520194521194522194523194524194525194526194527194528194529194530194531194532194533194534194535194536194537194538194539194540194541194542194543194544194545194546194547194548194549194550194551194552194553194554194555194556194557194558194559194560194561194562194563194564194565194566194567194568194569194570194571194572194573194574194575194576194577194578194579194580194581194582194583194584194585194586194587194588194589194590194591194592194593194594194595194596194597194598194599194600194601194602194603194604194605194606194607194608194609194610194611194612194613194614194615194616194617194618194619194620194621194622194623194624194625194626194627194628194629194630194631194632194633194634194635194636194637194638194639194640194641194642194643194644194645194646194647194648194649194650194651194652194653194654194655194656194657194658194659194660194661194662194663194664194665194666194667194668194669194670194671194672194673194674194675194676194677194678194679194680194681194682194683194684194685194686194687194688194689194690194691194692194693194694194695194696194697194698194699194700194701194702194703194704194705194706194707194708194709194710194711194712194713194714194715194716194717194718194719194720194721194722194723194724194725194726194727194728194729194730194731194732194733194734194735194736194737194738194739194740194741194742194743194744194745194746194747194748194749194750194751194752194753194754194755194756194757194758194759194760194761194762194763194764194765194766194767194768194769194770194771194772194773194774194775194776194777194778194779194780194781194782194783194784194785194786194787194788194789194790194791194792194793194794194795194796194797194798194799194800194801194802194803194804194805194806194807194808194809194810194811194812194813194814194815194816194817194818194819194820194821194822194823194824194825194826194827194828194829194830194831194832194833194834194835194836194837194838194839194840194841194842194843194844194845194846194847194848194849194850194851194852194853194854194855194856194857194858194859194860194861194862194863194864194865194866194867194868194869194870194871194872194873194874194875194876194877194878194879194880194881194882194883194884194885194886194887194888194889194890194891194892194893194894194895194896194897194898194899194900194901194902194903194904194905194906194907194908194909194910194911194912194913194914194915194916194917194918194919194920194921194922194923194924194925194926194927194928194929194930194931194932194933194934194935194936194937194938194939194940194941194942194943194944194945194946194947194948194949194950194951194952194953194954194955194956194957194958194959194960194961194962194963194964194965194966194967194968194969194970194971194972194973194974194975194976194977194978194979194980194981194982194983194984194985194986194987194988194989194990194991194992194993194994194995194996194997194998194999195000195001195002195003195004195005195006195007195008195009195010195011195012195013195014195015195016195017195018195019195020195021195022195023195024195025195026195027195028195029195030195031195032195033195034195035195036195037195038195039195040195041195042195043195044195045195046195047195048195049195050195051195052195053195054195055195056195057195058195059195060195061195062195063195064195065195066195067195068195069195070195071195072195073195074195075195076195077195078195079195080195081195082195083195084195085195086195087195088195089195090195091195092195093195094195095195096195097195098195099195100195101195102195103195104195105195106195107195108195109195110195111195112195113195114195115195116195117195118195119195120195121195122195123195124195125195126195127195128195129195130195131195132195133195134195135195136195137195138195139195140195141195142195143195144195145195146195147195148195149195150195151195152195153195154195155195156195157195158195159195160195161195162195163195164195165195166195167195168195169195170195171195172195173195174195175195176195177195178195179195180195181195182195183195184195185195186195187195188195189195190195191195192195193195194195195195196195197195198195199195200195201195202195203195204195205195206195207195208195209195210195211195212195213195214195215195216195217195218195219195220195221195222195223195224195225195226195227195228195229195230195231195232195233195234195235195236195237195238195239195240195241195242195243195244195245195246195247195248195249195250195251195252195253195254195255195256195257195258195259195260195261195262195263195264195265195266195267195268195269195270195271195272195273195274195275195276195277195278195279195280195281195282195283195284195285195286195287195288195289195290195291195292195293195294195295195296195297195298195299195300195301195302195303195304195305195306195307195308195309195310195311195312195313195314195315195316195317195318195319195320195321195322195323195324195325195326195327195328195329195330195331195332195333195334195335195336195337195338195339195340195341195342195343195344195345195346195347195348195349195350195351195352195353195354195355195356195357195358195359195360195361195362195363195364195365195366195367195368195369195370195371195372195373195374195375195376195377195378195379195380195381195382195383195384195385195386195387195388195389195390195391195392195393195394195395195396195397195398195399195400195401195402195403195404195405195406195407195408195409195410195411195412195413195414195415195416195417195418195419195420195421195422195423195424195425195426195427195428195429195430195431195432195433195434195435195436195437195438195439195440195441195442195443195444195445195446195447195448195449195450195451195452195453195454195455195456195457195458195459195460195461195462195463195464195465195466195467195468195469195470195471195472195473195474195475195476195477195478195479195480195481195482195483195484195485195486195487195488195489195490195491195492195493195494195495195496195497195498195499195500195501195502195503195504195505195506195507195508195509195510195511195512195513195514195515195516195517195518195519195520195521195522195523195524195525195526195527195528195529195530195531195532195533195534195535195536195537195538195539195540195541195542195543195544195545195546195547195548195549195550195551195552195553195554195555195556195557195558195559195560195561195562195563195564195565195566195567195568195569195570195571195572195573195574195575195576195577195578195579195580195581195582195583195584195585195586195587195588195589195590195591195592195593195594195595195596195597195598195599195600195601195602195603195604195605195606195607195608195609195610195611195612195613195614195615195616195617195618195619195620195621195622195623195624195625195626195627195628195629195630195631195632195633195634195635195636195637195638195639195640195641195642195643195644195645195646195647195648195649195650195651195652195653195654195655195656195657195658195659195660195661195662195663195664195665195666195667195668195669195670195671195672195673195674195675195676195677195678195679195680195681195682195683195684195685195686195687195688195689195690195691195692195693195694195695195696195697195698195699195700195701195702195703195704195705195706195707195708195709195710195711195712195713195714195715195716195717195718195719195720195721195722195723195724195725195726195727195728195729195730195731195732195733195734195735195736195737195738195739195740195741195742195743195744195745195746195747195748195749195750195751195752195753195754195755195756195757195758195759195760195761195762195763195764195765195766195767195768195769195770195771195772195773195774195775195776195777195778195779195780195781195782195783195784195785195786195787195788195789195790195791195792195793195794195795195796195797195798195799195800195801195802195803195804195805195806195807195808195809195810195811195812195813195814195815195816195817195818195819195820195821195822195823195824195825195826195827195828195829195830195831195832195833195834195835195836195837195838195839195840195841195842195843195844195845195846195847195848195849195850195851195852195853195854195855195856195857195858195859195860195861195862195863195864195865195866195867195868195869195870195871195872195873195874195875195876195877195878195879195880195881195882195883195884195885195886195887195888195889195890195891195892195893195894195895195896195897195898195899195900195901195902195903195904195905195906195907195908195909195910195911195912195913195914195915195916195917195918195919195920195921195922195923195924195925195926195927195928195929195930195931195932195933195934195935195936195937195938195939195940195941195942195943195944195945195946195947195948195949195950195951195952195953195954195955195956195957195958195959195960195961195962195963195964195965195966195967195968195969195970195971195972195973195974195975195976195977195978195979195980195981195982195983195984195985195986195987195988195989195990195991195992195993195994195995195996195997195998195999196000196001196002196003196004196005196006196007196008196009196010196011196012196013196014196015196016196017196018196019196020196021196022196023196024196025196026196027196028196029196030196031196032196033196034196035196036196037196038196039196040196041196042196043196044196045196046196047196048196049196050196051196052196053196054196055196056196057196058196059196060196061196062196063196064196065196066196067196068196069196070196071196072196073196074196075196076196077196078196079196080196081196082196083196084196085196086196087196088196089196090196091196092196093196094196095196096196097196098196099196100196101196102196103196104196105196106196107196108196109196110196111196112196113196114196115196116196117196118196119196120196121196122196123196124196125196126196127196128196129196130196131196132196133196134196135196136196137196138196139196140196141196142196143196144196145196146196147196148196149196150196151196152196153196154196155196156196157196158196159196160196161196162196163196164196165196166196167196168196169196170196171196172196173196174196175196176196177196178196179196180196181196182196183196184196185196186196187196188196189196190196191196192196193196194196195196196196197196198196199196200196201196202196203196204196205196206196207196208196209196210196211196212196213196214196215196216196217196218196219196220196221196222196223196224196225196226196227196228196229196230196231196232196233196234196235196236196237196238196239196240196241196242196243196244196245196246196247196248196249196250196251196252196253196254196255196256196257196258196259196260196261196262196263196264196265196266196267196268196269196270196271196272196273196274196275196276196277196278196279196280196281196282196283196284196285196286196287196288196289196290196291196292196293196294196295196296196297196298196299196300196301196302196303196304196305196306196307196308196309196310196311196312196313196314196315196316196317196318196319196320196321196322196323196324196325196326196327196328196329196330196331196332196333196334196335196336196337196338196339196340196341196342196343196344196345196346196347196348196349196350196351196352196353196354196355196356196357196358196359196360196361196362196363196364196365196366196367196368196369196370196371196372196373196374196375196376196377196378196379196380196381196382196383196384196385196386196387196388196389196390196391196392196393196394196395196396196397196398196399196400196401196402196403196404196405196406196407196408196409196410196411196412196413196414196415196416196417196418196419196420196421196422196423196424196425196426196427196428196429196430196431196432196433196434196435196436196437196438196439196440196441196442196443196444196445196446196447196448196449196450196451196452196453196454196455196456196457196458196459196460196461196462196463196464196465196466196467196468196469196470196471196472196473196474196475196476196477196478196479196480196481196482196483196484196485196486196487196488196489196490196491196492196493196494196495196496196497196498196499196500196501196502196503196504196505196506196507196508196509196510196511196512196513196514196515196516196517196518196519196520196521196522196523196524196525196526196527196528196529196530196531196532196533196534196535196536196537196538196539196540196541196542196543196544196545196546196547196548196549196550196551196552196553196554196555196556196557196558196559196560196561196562196563196564196565196566196567196568196569196570196571196572196573196574196575196576196577196578196579196580196581196582196583196584196585196586196587196588196589196590196591196592196593196594196595196596196597196598196599196600196601196602196603196604196605196606196607196608196609196610196611196612196613196614196615196616196617196618196619196620196621196622196623196624196625196626196627196628196629196630196631196632196633196634196635196636196637196638196639196640196641196642196643196644196645196646196647196648196649196650196651196652196653196654196655196656196657196658196659196660196661196662196663196664196665196666196667196668196669196670196671196672196673196674196675196676196677196678196679196680196681196682196683196684196685196686196687196688196689196690196691196692196693196694196695196696196697196698196699196700196701196702196703196704196705196706196707196708196709196710196711196712196713196714196715196716196717196718196719196720196721196722196723196724196725196726196727196728196729196730196731196732196733196734196735196736196737196738196739196740196741196742196743196744196745196746196747196748196749196750196751196752196753196754196755196756196757196758196759196760196761196762196763196764196765196766196767196768196769196770196771196772196773196774196775196776196777196778196779196780196781196782196783196784196785196786196787196788196789196790196791196792196793196794196795196796196797196798196799196800196801196802196803196804196805196806196807196808196809196810196811196812196813196814196815196816196817196818196819196820196821196822196823196824196825196826196827196828196829196830196831196832196833196834196835196836196837196838196839196840196841196842196843196844196845196846196847196848196849196850196851196852196853196854196855196856196857196858196859196860196861196862196863196864196865196866196867196868196869196870196871196872196873196874196875196876196877196878196879196880196881196882196883196884196885196886196887196888196889196890196891196892196893196894196895196896196897196898196899196900196901196902196903196904196905196906196907196908196909196910196911196912196913196914196915196916196917196918196919196920196921196922196923196924196925196926196927196928196929196930196931196932196933196934196935196936196937196938196939196940196941196942196943196944196945196946196947196948196949196950196951196952196953196954196955196956196957196958196959196960196961196962196963196964196965196966196967196968196969196970196971196972196973196974196975196976196977196978196979196980196981196982196983196984196985196986196987196988196989196990196991196992196993196994196995196996196997196998196999197000197001197002197003197004197005197006197007197008197009197010197011197012197013197014197015197016197017197018197019197020197021197022197023197024197025197026197027197028197029197030197031197032197033197034197035197036197037197038197039197040197041197042197043197044197045197046197047197048197049197050197051197052197053197054197055197056197057197058197059197060197061197062197063197064197065197066197067197068197069197070197071197072197073197074197075197076197077197078197079197080197081197082197083197084197085197086197087197088197089197090197091197092197093197094197095197096197097197098197099197100197101197102197103197104197105197106197107197108197109197110197111197112197113197114197115197116197117197118197119197120197121197122197123197124197125197126197127197128197129197130197131197132197133197134197135197136197137197138197139197140197141197142197143197144197145197146197147197148197149197150197151197152197153197154197155197156197157197158197159197160197161197162197163197164197165197166197167197168197169197170197171197172197173197174197175197176197177197178197179197180197181197182197183197184197185197186197187197188197189197190197191197192197193197194197195197196197197197198197199197200197201197202197203197204197205197206197207197208197209197210197211197212197213197214197215197216197217197218197219197220197221197222197223197224197225197226197227197228197229197230197231197232197233197234197235197236197237197238197239197240197241197242197243197244197245197246197247197248197249197250197251197252197253197254197255197256197257197258197259197260197261197262197263197264197265197266197267197268197269197270197271197272197273197274197275197276197277197278197279197280197281197282197283197284197285197286197287197288197289197290197291197292197293197294197295197296197297197298197299197300197301197302197303197304197305197306197307197308197309197310197311197312197313197314197315197316197317197318197319197320197321197322197323197324197325197326197327197328197329197330197331197332197333197334197335197336197337197338197339197340197341197342197343197344197345197346197347197348197349197350197351197352197353197354197355197356197357197358197359197360197361197362197363197364197365197366197367197368197369197370197371197372197373197374197375197376197377197378197379197380197381197382197383197384197385197386197387197388197389197390197391197392197393197394197395197396197397197398197399197400197401197402197403197404197405197406197407197408197409197410197411197412197413197414197415197416197417197418197419197420197421197422197423197424197425197426197427197428197429197430197431197432197433197434197435197436197437197438197439197440197441197442197443197444197445197446197447197448197449197450197451197452197453197454197455197456197457197458197459197460197461197462197463197464197465197466197467197468197469197470197471197472197473197474197475197476197477197478197479197480197481197482197483197484197485197486197487197488197489197490197491197492197493197494197495197496197497197498197499197500197501197502197503197504197505197506197507197508197509197510197511197512197513197514197515197516197517197518197519197520197521197522197523197524197525197526197527197528197529197530197531197532197533197534197535197536197537197538197539197540197541197542197543197544197545197546197547197548197549197550197551197552197553197554197555197556197557197558197559197560197561197562197563197564197565197566197567197568197569197570197571197572197573197574197575197576197577197578197579197580197581197582197583197584197585197586197587197588197589197590197591197592197593197594197595197596197597197598197599197600197601197602197603197604197605197606197607197608197609197610197611197612197613197614197615197616197617197618197619197620197621197622197623197624197625197626197627197628197629197630197631197632197633197634197635197636197637197638197639197640197641197642197643197644197645197646197647197648197649197650197651197652197653197654197655197656197657197658197659197660197661197662197663197664197665197666197667197668197669197670197671197672197673197674197675197676197677197678197679197680197681197682197683197684197685197686197687197688197689197690197691197692197693197694197695197696197697197698197699197700197701197702197703197704197705197706197707197708197709197710197711197712197713197714197715197716197717197718197719197720197721197722197723197724197725197726197727197728197729197730197731197732197733197734197735197736197737197738197739197740197741197742197743197744197745197746197747197748197749197750197751197752197753197754197755197756197757197758197759197760197761197762197763197764197765197766197767197768197769197770197771197772197773197774197775197776197777197778197779197780197781197782197783197784197785197786197787197788197789197790197791197792197793197794197795197796197797197798197799197800197801197802197803197804197805197806197807197808197809197810197811197812197813197814197815197816197817197818197819197820197821197822197823197824197825197826197827197828197829197830197831197832197833197834197835197836197837197838197839197840197841197842197843197844197845197846197847197848197849197850197851197852197853197854197855197856197857197858197859197860197861197862197863197864197865197866197867197868197869197870197871197872197873197874197875197876197877197878197879197880197881197882197883197884197885197886197887197888197889197890197891197892197893197894197895197896197897197898197899197900197901197902197903197904197905197906197907197908197909197910197911197912197913197914197915197916197917197918197919197920197921197922197923197924197925197926197927197928197929197930197931197932197933197934197935197936197937197938197939197940197941197942197943197944197945197946197947197948197949197950197951197952197953197954197955197956197957197958197959197960197961197962197963197964197965197966197967197968197969197970197971197972197973197974197975197976197977197978197979197980197981197982197983197984197985197986197987197988197989197990197991197992197993197994197995197996197997197998197999198000198001198002198003198004198005198006198007198008198009198010198011198012198013198014198015198016198017198018198019198020198021198022198023198024198025198026198027198028198029198030198031198032198033198034198035198036198037198038198039198040198041198042198043198044198045198046198047198048198049198050198051198052198053198054198055198056198057198058198059198060198061198062198063198064198065198066198067198068198069198070198071198072198073198074198075198076198077198078198079198080198081198082198083198084198085198086198087198088198089198090198091198092198093198094198095198096198097198098198099198100198101198102198103198104198105198106198107198108198109198110198111198112198113198114198115198116198117198118198119198120198121198122198123198124198125198126198127198128198129198130198131198132198133198134198135198136198137198138198139198140198141198142198143198144198145198146198147198148198149198150198151198152198153198154198155198156198157198158198159198160198161198162198163198164198165198166198167198168198169198170198171198172198173198174198175198176198177198178198179198180198181198182198183198184198185198186198187198188198189198190198191198192198193198194198195198196198197198198198199198200198201198202198203198204198205198206198207198208198209198210198211198212198213198214198215198216198217198218198219198220198221198222198223198224198225198226198227198228198229198230198231198232198233198234198235198236198237198238198239198240198241198242198243198244198245198246198247198248198249198250198251198252198253198254198255198256198257198258198259198260198261198262198263198264198265198266198267198268198269198270198271198272198273198274198275198276198277198278198279198280198281198282198283198284198285198286198287198288198289198290198291198292198293198294198295198296198297198298198299198300198301198302198303198304198305198306198307198308198309198310198311198312198313198314198315198316198317198318198319198320198321198322198323198324198325198326198327198328198329198330198331198332198333198334198335198336198337198338198339198340198341198342198343198344198345198346198347198348198349198350198351198352198353198354198355198356198357198358198359198360198361198362198363198364198365198366198367198368198369198370198371198372198373198374198375198376198377198378198379198380198381198382198383198384198385198386198387198388198389198390198391198392198393198394198395198396198397198398198399198400198401198402198403198404198405198406198407198408198409198410198411198412198413198414198415198416198417198418198419198420198421198422198423198424198425198426198427198428198429198430198431198432198433198434198435198436198437198438198439198440198441198442198443198444198445198446198447198448198449198450198451198452198453198454198455198456198457198458198459198460198461198462198463198464198465198466198467198468198469198470198471198472198473198474198475198476198477198478198479198480198481198482198483198484198485198486198487198488198489198490198491198492198493198494198495198496198497198498198499198500198501198502198503198504198505198506198507198508198509198510198511198512198513198514198515198516198517198518198519198520198521198522198523198524198525198526198527198528198529198530198531198532198533198534198535198536198537198538198539198540198541198542198543198544198545198546198547198548198549198550198551198552198553198554198555198556198557198558198559198560198561198562198563198564198565198566198567198568198569198570198571198572198573198574198575198576198577198578198579198580198581198582198583198584198585198586198587198588198589198590198591198592198593198594198595198596198597198598198599198600198601198602198603198604198605198606198607198608198609198610198611198612198613198614198615198616198617198618198619198620198621198622198623198624198625198626198627198628198629198630198631198632198633198634198635198636198637198638198639198640198641198642198643198644198645198646198647198648198649198650198651198652198653198654198655198656198657198658198659198660198661198662198663198664198665198666198667198668198669198670198671198672198673198674198675198676198677198678198679198680198681198682198683198684198685198686198687198688198689198690198691198692198693198694198695198696198697198698198699198700198701198702198703198704198705198706198707198708198709198710198711198712198713198714198715198716198717198718198719198720198721198722198723198724198725198726198727198728198729198730198731198732198733198734198735198736198737198738198739198740198741198742198743198744198745198746198747198748198749198750198751198752198753198754198755198756198757198758198759198760198761198762198763198764198765198766198767198768198769198770198771198772198773198774198775198776198777198778198779198780198781198782198783198784198785198786198787198788198789198790198791198792198793198794198795198796198797198798198799198800198801198802198803198804198805198806198807198808198809198810198811198812198813198814198815198816198817198818198819198820198821198822198823198824198825198826198827198828198829198830198831198832198833198834198835198836198837198838198839198840198841198842198843198844198845198846198847198848198849198850198851198852198853198854198855198856198857198858198859198860198861198862198863198864198865198866198867198868198869198870198871198872198873198874198875198876198877198878198879198880198881198882198883198884198885198886198887198888198889198890198891198892198893198894198895198896198897198898198899198900198901198902198903198904198905198906198907198908198909198910198911198912198913198914198915198916198917198918198919198920198921198922198923198924198925198926198927198928198929198930198931198932198933198934198935198936198937198938198939198940198941198942198943198944198945198946198947198948198949198950198951198952198953198954198955198956198957198958198959198960198961198962198963198964198965198966198967198968198969198970198971198972198973198974198975198976198977198978198979198980198981198982198983198984198985198986198987198988198989198990198991198992198993198994198995198996198997198998198999199000199001199002199003199004199005199006199007199008199009199010199011199012199013199014199015199016199017199018199019199020199021199022199023199024199025199026199027199028199029199030199031199032199033199034199035199036199037199038199039199040199041199042199043199044199045199046199047199048199049199050199051199052199053199054199055199056199057199058199059199060199061199062199063199064199065199066199067199068199069199070199071199072199073199074199075199076199077199078199079199080199081199082199083199084199085199086199087199088199089199090199091199092199093199094199095199096199097199098199099199100199101199102199103199104199105199106199107199108199109199110199111199112199113199114199115199116199117199118199119199120199121199122199123199124199125199126199127199128199129199130199131199132199133199134199135199136199137199138199139199140199141199142199143199144199145199146199147199148199149199150199151199152199153199154199155199156199157199158199159199160199161199162199163199164199165199166199167199168199169199170199171199172199173199174199175199176199177199178199179199180199181199182199183199184199185199186199187199188199189199190199191199192199193199194199195199196199197199198199199199200199201199202199203199204199205199206199207199208199209199210199211199212199213199214199215199216199217199218199219199220199221199222199223199224199225199226199227199228199229199230199231199232199233199234199235199236199237199238199239199240199241199242199243199244199245199246199247199248199249199250199251199252199253199254199255199256199257199258199259199260199261199262199263199264199265199266199267199268199269199270199271199272199273199274199275199276199277199278199279199280199281199282199283199284199285199286199287199288199289199290199291199292199293199294199295199296199297199298199299199300199301199302199303199304199305199306199307199308199309199310199311199312199313199314199315199316199317199318199319199320199321199322199323199324199325199326199327199328199329199330199331199332199333199334199335199336199337199338199339199340199341199342199343199344199345199346199347199348199349199350199351199352199353199354199355199356199357199358199359199360199361199362199363199364199365199366199367199368199369199370199371199372199373199374199375199376199377199378199379199380199381199382199383199384199385199386199387199388199389199390199391199392199393199394199395199396199397199398199399199400199401199402199403199404199405199406199407199408199409199410199411199412199413199414199415199416199417199418199419199420199421199422199423199424199425199426199427199428199429199430199431199432199433199434199435199436199437199438199439199440199441199442199443199444199445199446199447199448199449199450199451199452199453199454199455199456199457199458199459199460199461199462199463199464199465199466199467199468199469199470199471199472199473199474199475199476199477199478199479199480199481199482199483199484199485199486199487199488199489199490199491199492199493199494199495199496199497199498199499199500199501199502199503199504199505199506199507199508199509199510199511199512199513199514199515199516199517199518199519199520199521199522199523199524199525199526199527199528199529199530199531199532199533199534199535199536199537199538199539199540199541199542199543199544199545199546199547199548199549199550199551199552199553199554199555199556199557199558199559199560199561199562199563199564199565199566199567199568199569199570199571199572199573199574199575199576199577199578199579199580199581199582199583199584199585199586199587199588199589199590199591199592199593199594199595199596199597199598199599199600199601199602199603199604199605199606199607199608199609199610199611199612199613199614199615199616199617199618199619199620199621199622199623199624199625199626199627199628199629199630199631199632199633199634199635199636199637199638199639199640199641199642199643199644199645199646199647199648199649199650199651199652199653199654199655199656199657199658199659199660199661199662199663199664199665199666199667199668199669199670199671199672199673199674199675199676199677199678199679199680199681199682199683199684199685199686199687199688199689199690199691199692199693199694199695199696199697199698199699199700199701199702199703199704199705199706199707199708199709199710199711199712199713199714199715199716199717199718199719199720199721199722199723199724199725199726199727199728199729199730199731199732199733199734199735199736199737199738199739199740199741199742199743199744199745199746199747199748199749199750199751199752199753199754199755199756199757199758199759199760199761199762199763199764199765199766199767199768199769199770199771199772199773199774199775199776199777199778199779199780199781199782199783199784199785199786199787199788199789199790199791199792199793199794199795199796199797199798199799199800199801199802199803199804199805199806199807199808199809199810199811199812199813199814199815199816199817199818199819199820199821199822199823199824199825199826199827199828199829199830199831199832199833199834199835199836199837199838199839199840199841199842199843199844199845199846199847199848199849199850199851199852199853199854199855199856199857199858199859199860199861199862199863199864199865199866199867199868199869199870199871199872199873199874199875199876199877199878199879199880199881199882199883199884199885199886199887199888199889199890199891199892199893199894199895199896199897199898199899199900199901199902199903199904199905199906199907199908199909199910199911199912199913199914199915199916199917199918199919199920199921199922199923199924199925199926199927199928199929199930199931199932199933199934199935199936199937199938199939199940199941199942199943199944199945199946199947199948199949199950199951199952199953199954199955199956199957199958199959199960199961199962199963199964199965199966199967199968199969199970199971199972199973199974199975199976199977199978199979199980199981199982199983199984199985199986199987199988199989199990199991199992199993199994199995199996199997199998199999200000200001200002200003200004200005200006200007200008200009200010200011200012200013200014200015200016200017200018200019200020200021200022200023200024200025200026200027200028200029200030200031200032200033200034200035200036200037200038200039200040200041200042200043200044200045200046200047200048200049200050200051200052200053200054200055200056200057200058200059200060200061200062200063200064200065200066200067200068200069200070200071200072200073200074200075200076200077200078200079200080200081200082200083200084200085200086200087200088200089200090200091200092200093200094200095200096200097200098200099200100200101200102200103200104200105200106200107200108200109200110200111200112200113200114200115200116200117200118200119200120200121200122200123200124200125200126200127200128200129200130200131200132200133200134200135200136200137200138200139200140200141200142200143200144200145200146200147200148200149200150200151200152200153200154200155200156200157200158200159200160200161200162200163200164200165200166200167200168200169200170200171200172200173200174200175200176200177200178200179200180200181200182200183200184200185200186200187200188200189200190200191200192200193200194200195200196200197200198200199200200200201200202200203200204200205200206200207200208200209200210200211200212200213200214200215200216200217200218200219200220200221200222200223200224200225200226200227200228200229200230200231200232200233200234200235200236200237200238200239200240200241200242200243200244200245200246200247200248200249200250200251200252200253200254200255200256200257200258200259200260200261200262200263200264200265200266200267200268200269200270200271200272200273200274200275200276200277200278200279200280200281200282200283200284200285200286200287200288200289200290200291200292200293200294200295200296200297200298200299200300200301200302200303200304200305200306200307200308200309200310200311200312200313200314200315200316200317200318200319200320200321200322200323200324200325200326200327200328200329200330200331200332200333200334200335200336200337200338200339200340200341200342200343200344200345200346200347200348200349200350200351200352200353200354200355200356200357200358200359200360200361200362200363200364200365200366200367200368200369200370200371200372200373200374200375200376200377200378200379200380200381200382200383200384200385200386200387200388200389200390200391200392200393200394200395200396200397200398200399200400200401200402200403200404200405200406200407200408200409200410200411200412200413200414200415200416200417200418200419200420200421200422200423200424200425200426200427200428200429200430200431200432200433200434200435200436200437200438200439200440200441200442200443200444200445200446200447200448200449200450200451200452200453200454200455200456200457200458200459200460200461200462200463200464200465200466200467200468200469200470200471200472200473200474200475200476200477200478200479200480200481200482200483200484200485200486200487200488200489200490200491200492200493200494200495200496200497200498200499200500200501200502200503200504200505200506200507200508200509200510200511200512200513200514200515200516200517200518200519200520200521200522200523200524200525200526200527200528200529200530200531200532200533200534200535200536200537200538200539200540200541200542200543200544200545200546200547200548200549200550200551200552200553200554200555200556200557200558200559200560200561200562200563200564200565200566200567200568200569200570200571200572200573200574200575200576200577200578200579200580200581200582200583200584200585200586200587200588200589200590200591200592200593200594200595200596200597200598200599200600200601200602200603200604200605200606200607200608200609200610200611200612200613200614200615200616200617200618200619200620200621200622200623200624200625200626200627200628200629200630200631200632200633200634200635200636200637200638200639200640200641200642200643200644200645200646200647200648200649200650200651200652200653200654200655200656200657200658200659200660200661200662200663200664200665200666200667200668200669200670200671200672200673200674200675200676200677200678200679200680200681200682200683200684200685200686200687200688200689200690200691200692200693200694200695200696200697200698200699200700200701200702200703200704200705200706200707200708200709200710200711200712200713200714200715200716200717200718200719200720200721200722200723200724200725200726200727200728200729200730200731200732200733200734200735200736200737200738200739200740200741200742200743200744200745200746200747200748200749200750200751200752200753200754200755200756200757200758200759200760200761200762200763200764200765200766200767200768200769200770200771200772200773200774200775200776200777200778200779200780200781200782200783200784200785200786200787200788200789200790200791200792200793200794200795200796200797200798200799200800200801200802200803200804200805200806200807200808200809200810200811200812200813200814200815200816200817200818200819200820200821200822200823200824200825200826200827200828200829200830200831200832200833200834200835200836200837200838200839200840200841200842200843200844200845200846200847200848200849200850200851200852200853200854200855200856200857200858200859200860200861200862200863200864200865200866200867200868200869200870200871200872200873200874200875200876200877200878200879200880200881200882200883200884200885200886200887200888200889200890200891200892200893200894200895200896200897200898200899200900200901200902200903200904200905200906200907200908200909200910200911200912200913200914200915200916200917200918200919200920200921200922200923200924200925200926200927200928200929200930200931200932200933200934200935200936200937200938200939200940200941200942200943200944200945200946200947200948200949200950200951200952200953200954200955200956200957200958200959200960200961200962200963200964200965200966200967200968200969200970200971200972200973200974200975200976200977200978200979200980200981200982200983200984200985200986200987200988200989200990200991200992200993200994200995200996200997200998200999201000201001201002201003201004201005201006201007201008201009201010201011201012201013201014201015201016201017201018201019201020201021201022201023201024201025201026201027201028201029201030201031201032201033201034201035201036201037201038201039201040201041201042201043201044201045201046201047201048201049201050201051201052201053201054201055201056201057201058201059201060201061201062201063201064201065201066201067201068201069201070201071201072201073201074201075201076201077201078201079201080201081201082201083201084201085201086201087201088201089201090201091201092201093201094201095201096201097201098201099201100201101201102201103201104201105201106201107201108201109201110201111201112201113201114201115201116201117201118201119201120201121201122201123201124201125201126201127201128201129201130201131201132201133201134201135201136201137201138201139201140201141201142201143201144201145201146201147201148201149201150201151201152201153201154201155201156201157201158201159201160201161201162201163201164201165201166201167201168201169201170201171201172201173201174201175201176201177201178201179201180201181201182201183201184201185201186201187201188201189201190201191201192201193201194201195201196201197201198201199201200201201201202201203201204201205201206201207201208201209201210201211201212201213201214201215201216201217201218201219201220201221201222201223201224201225201226201227201228201229201230201231201232201233201234201235201236201237201238201239201240201241201242201243201244201245201246201247201248201249201250201251201252201253201254201255201256201257201258201259201260201261201262201263201264201265201266201267201268201269201270201271201272201273201274201275201276201277201278201279201280201281201282201283201284201285201286201287201288201289201290201291201292201293201294201295201296201297201298201299201300201301201302201303201304201305201306201307201308201309201310201311201312201313201314201315201316201317201318201319201320201321201322201323201324201325201326201327201328201329201330201331201332201333201334201335201336201337201338201339201340201341201342201343201344201345201346201347201348201349201350201351201352201353201354201355201356201357201358201359201360201361201362201363201364201365201366201367201368201369201370201371201372201373201374201375201376201377201378201379201380201381201382201383201384201385201386201387201388201389201390201391201392201393201394201395201396201397201398201399201400201401201402201403201404201405201406201407201408201409201410201411201412201413201414201415201416201417201418201419201420201421201422201423201424201425201426201427201428201429201430201431201432201433201434201435201436201437201438201439201440201441201442201443201444201445201446201447201448201449201450201451201452201453201454201455201456201457201458201459201460201461201462201463201464201465201466201467201468201469201470201471201472201473201474201475201476201477201478201479201480201481201482201483201484201485201486201487201488201489201490201491201492201493201494201495201496201497201498201499201500201501201502201503201504201505201506201507201508201509201510201511201512201513201514201515201516201517201518201519201520201521201522201523201524201525201526201527201528201529201530201531201532201533201534201535201536201537201538201539201540201541201542201543201544201545201546201547201548201549201550201551201552201553201554201555201556201557201558201559201560201561201562201563201564201565201566201567201568201569201570201571201572201573201574201575201576201577201578201579201580201581201582201583201584201585201586201587201588201589201590201591201592201593201594201595201596201597201598201599201600201601201602201603201604201605201606201607201608201609201610201611201612201613201614201615201616201617201618201619201620201621201622201623201624201625201626201627201628201629201630201631201632201633201634201635201636201637201638201639201640201641201642201643201644201645201646201647201648201649201650201651201652201653201654201655201656201657201658201659201660201661201662201663201664201665201666201667201668201669201670201671201672201673201674201675201676201677201678201679201680201681201682201683201684201685201686201687201688201689201690201691201692201693201694201695201696201697201698201699201700201701201702201703201704201705201706201707201708201709201710201711201712201713201714201715201716201717201718201719201720201721201722201723201724201725201726201727201728201729201730201731201732201733201734201735201736201737201738201739201740201741201742201743201744201745201746201747201748201749201750201751201752201753201754201755201756201757201758201759201760201761201762201763201764201765201766201767201768201769201770201771201772201773201774201775201776201777201778201779201780201781201782201783201784201785201786201787201788201789201790201791201792201793201794201795201796201797201798201799201800201801201802201803201804201805201806201807201808201809201810201811201812201813201814201815201816201817201818201819201820201821201822201823201824201825201826201827201828201829201830201831201832201833201834201835201836201837201838201839201840201841201842201843201844201845201846201847201848201849201850201851201852201853201854201855201856201857201858201859201860201861201862201863201864201865201866201867201868201869201870201871201872201873201874201875201876201877201878201879201880201881201882201883201884201885201886201887201888201889201890201891201892201893201894201895201896201897201898201899201900201901201902201903201904201905201906201907201908201909201910201911201912201913201914201915201916201917201918201919201920201921201922201923201924201925201926201927201928201929201930201931201932201933201934201935201936201937201938201939201940201941201942201943201944201945201946201947201948201949201950201951201952201953201954201955201956201957201958201959201960201961201962201963201964201965201966201967201968201969201970201971201972201973201974201975201976201977201978201979201980201981201982201983201984201985201986201987201988201989201990201991201992201993201994201995201996201997201998201999202000202001202002202003202004202005202006202007202008202009202010202011202012202013202014202015202016202017202018202019202020202021202022202023202024202025202026202027202028202029202030202031202032202033202034202035202036202037202038202039202040202041202042202043202044202045202046202047202048202049202050202051202052202053202054202055202056202057202058202059202060202061202062202063202064202065202066202067202068202069202070202071202072202073202074202075202076202077202078202079202080202081202082202083202084202085202086202087202088202089202090202091202092202093202094202095202096202097202098202099202100202101202102202103202104202105202106202107202108202109202110202111202112202113202114202115202116202117202118202119202120202121202122202123202124202125202126202127202128202129202130202131202132202133202134202135202136202137202138202139202140202141202142202143202144202145202146202147202148202149202150202151202152202153202154202155202156202157202158202159202160202161202162202163202164202165202166202167202168202169202170202171202172202173202174202175202176202177202178202179202180202181202182202183202184202185202186202187202188202189202190202191202192202193202194202195202196202197202198202199202200202201202202202203202204202205202206202207202208202209202210202211202212202213202214202215202216202217202218202219202220202221202222202223202224202225202226202227202228202229202230202231202232202233202234202235202236202237202238202239202240202241202242202243202244202245202246202247202248202249202250202251202252202253202254202255202256202257202258202259202260202261202262202263202264202265202266202267202268202269202270202271202272202273202274202275202276202277202278202279202280202281202282202283202284202285202286202287202288202289202290202291202292202293202294202295202296202297202298202299202300202301202302202303202304202305202306202307202308202309202310202311202312202313202314202315202316202317202318202319202320202321202322202323202324202325202326202327202328202329202330202331202332202333202334202335202336202337202338202339202340202341202342202343202344202345202346202347202348202349202350202351202352202353202354202355202356202357202358202359202360202361202362202363202364202365202366202367202368202369202370202371202372202373202374202375202376202377202378202379202380202381202382202383202384202385202386202387202388202389202390202391202392202393202394202395202396202397202398202399202400202401202402202403202404202405202406202407202408202409202410202411202412202413202414202415202416202417202418202419202420202421202422202423202424202425202426202427202428202429202430202431202432202433202434202435202436202437202438202439202440202441202442202443202444202445202446202447202448202449202450202451202452202453202454202455202456202457202458202459202460202461202462202463202464202465202466202467202468202469202470202471202472202473202474202475202476202477202478202479202480202481202482202483202484202485202486202487202488202489202490202491202492202493202494202495202496202497202498202499202500202501202502202503202504202505202506202507202508202509202510202511202512202513202514202515202516202517202518202519202520202521202522202523202524202525202526202527202528202529202530202531202532202533202534202535202536202537202538202539202540202541202542202543202544202545202546202547202548202549202550202551202552202553202554202555202556202557202558202559202560202561202562202563202564202565202566202567202568202569202570202571202572202573202574202575202576202577202578202579202580202581202582202583202584202585202586202587202588202589202590202591202592202593202594202595202596202597202598202599202600202601202602202603202604202605202606202607202608202609202610202611202612202613202614202615202616202617202618202619202620202621202622202623202624202625202626202627202628202629202630202631202632202633202634202635202636202637202638202639202640202641202642202643202644202645202646202647202648202649202650202651202652202653202654202655202656202657202658202659202660202661202662202663202664202665202666202667202668202669202670202671202672202673202674202675202676202677202678202679202680202681202682202683202684202685202686202687202688202689202690202691202692202693202694202695202696202697202698202699202700202701202702202703202704202705202706202707202708202709202710202711202712202713202714202715202716202717202718202719202720202721202722202723202724202725202726202727202728202729202730202731202732202733202734202735202736202737202738202739202740202741202742202743202744202745202746202747202748202749202750202751202752202753202754202755202756202757202758202759202760202761202762202763202764202765202766202767202768202769202770202771202772202773202774202775202776202777202778202779202780202781202782202783202784202785202786202787202788202789202790202791202792202793202794202795202796202797202798202799202800202801202802202803202804202805202806202807202808202809202810202811202812202813202814202815202816202817202818202819202820202821202822202823202824202825202826202827202828202829202830202831202832202833202834202835202836202837202838202839202840202841202842202843202844202845202846202847202848202849202850202851202852202853202854202855202856202857202858202859202860202861202862202863202864202865202866202867202868202869202870202871202872202873202874202875202876202877202878202879202880202881202882202883202884202885202886202887202888202889202890202891202892202893202894202895202896202897202898202899202900202901202902202903202904202905202906202907202908202909202910202911202912202913202914202915202916202917202918202919202920202921202922202923202924202925202926202927202928202929202930202931202932202933202934202935202936202937202938202939202940202941202942202943202944202945202946202947202948202949202950202951202952202953202954202955202956202957202958202959202960202961202962202963202964202965202966202967202968202969202970202971202972202973202974202975202976202977202978202979202980202981202982202983202984202985202986202987202988202989202990202991202992202993202994202995202996202997202998202999203000203001203002203003203004203005203006203007203008203009203010203011203012203013203014203015203016203017203018203019203020203021203022203023203024203025203026203027203028203029203030203031203032203033203034203035203036203037203038203039203040203041203042203043203044203045203046203047203048203049203050203051203052203053203054203055203056203057203058203059203060203061203062203063203064203065203066203067203068203069203070203071203072203073203074203075203076203077203078203079203080203081203082203083203084203085203086203087203088203089203090203091203092203093203094203095203096203097203098203099203100203101203102203103203104203105203106203107203108203109203110203111203112203113203114203115203116203117203118203119203120203121203122203123203124203125203126203127203128203129203130203131203132203133203134203135203136203137203138203139203140203141203142203143203144203145203146203147203148203149203150203151203152203153203154203155203156203157203158203159203160203161203162203163203164203165203166203167203168203169203170203171203172203173203174203175203176203177203178203179203180203181203182203183203184203185203186203187203188203189203190203191203192203193203194203195203196203197203198203199203200203201203202203203203204203205203206203207203208203209203210203211203212203213203214203215203216203217203218203219203220203221203222203223203224203225203226203227203228203229203230203231203232203233203234203235203236203237203238203239203240203241203242203243203244203245203246203247203248203249203250203251203252203253203254203255203256203257203258203259203260203261203262203263203264203265203266203267203268203269203270203271203272203273203274203275203276203277203278203279203280203281203282203283203284203285203286203287203288203289203290203291203292203293203294203295203296203297203298203299203300203301203302203303203304203305203306203307203308203309203310203311203312203313203314203315203316203317203318203319203320203321203322203323203324203325203326203327203328203329203330203331203332203333203334203335203336203337203338203339203340203341203342203343203344203345203346203347203348203349203350203351203352203353203354203355203356203357203358203359203360203361203362203363203364203365203366203367203368203369203370203371203372203373203374203375203376203377203378203379203380203381203382203383203384203385203386203387203388203389203390203391203392203393203394203395203396203397203398203399203400203401203402203403203404203405203406203407203408203409203410203411203412203413203414203415203416203417203418203419203420203421203422203423203424203425203426203427203428203429203430203431203432203433203434203435203436203437203438203439203440203441203442203443203444203445203446203447203448203449203450203451203452203453203454203455203456203457203458203459203460203461203462203463203464203465203466203467203468203469203470203471203472203473203474203475203476203477203478203479203480203481203482203483203484203485203486203487203488203489203490203491203492203493203494203495203496203497203498203499203500203501203502203503203504203505203506203507203508203509203510203511203512203513203514203515203516203517203518203519203520203521203522203523203524203525203526203527203528203529203530203531203532203533203534203535203536203537203538203539203540203541203542203543203544203545203546203547203548203549203550203551203552203553203554203555203556203557203558203559203560203561203562203563203564203565203566203567203568203569203570203571203572203573203574203575203576203577203578203579203580203581203582203583203584203585203586203587203588203589203590203591203592203593203594203595203596203597203598203599203600203601203602203603203604203605203606203607203608203609203610203611203612203613203614203615203616203617203618203619203620203621203622203623203624203625203626203627203628203629203630203631203632203633203634203635203636203637203638203639203640203641203642203643203644203645203646203647203648203649203650203651203652203653203654203655203656203657203658203659203660203661203662203663203664203665203666203667203668203669203670203671203672203673203674203675203676203677203678203679203680203681203682203683203684203685203686203687203688203689203690203691203692203693203694203695203696203697203698203699203700203701203702203703203704203705203706203707203708203709203710203711203712203713203714203715203716203717203718203719203720203721203722203723203724203725203726203727203728203729203730203731203732203733203734203735203736203737203738203739203740203741203742203743203744203745203746203747203748203749203750203751203752203753203754203755203756203757203758203759203760203761203762203763203764203765203766203767203768203769203770203771203772203773203774203775203776203777203778203779203780203781203782203783203784203785203786203787203788203789203790203791203792203793203794203795203796203797203798203799203800203801203802203803203804203805203806203807203808203809203810203811203812203813203814203815203816203817203818203819203820203821203822203823203824203825203826203827203828203829203830203831203832203833203834203835203836203837203838203839203840203841203842203843203844203845203846203847203848203849203850203851203852203853203854203855203856203857203858203859203860203861203862203863203864203865203866203867203868203869203870203871203872203873203874203875203876203877203878203879203880203881203882203883203884203885203886203887203888203889203890203891203892203893203894203895203896203897203898203899203900203901203902203903203904203905203906203907203908203909203910203911203912203913203914203915203916203917203918203919203920203921203922203923203924203925203926203927203928203929203930203931203932203933203934203935203936203937203938203939203940203941203942203943203944203945203946203947203948203949203950203951203952203953203954203955203956203957203958203959203960203961203962203963203964203965203966203967203968203969203970203971203972203973203974203975203976203977203978203979203980203981203982203983203984203985203986203987203988203989203990203991203992203993203994203995203996203997203998203999204000204001204002204003204004204005204006204007204008204009204010204011204012204013204014204015204016204017204018204019204020204021204022204023204024204025204026204027204028204029204030204031204032204033204034204035204036204037204038204039204040204041204042204043204044204045204046204047204048204049204050204051204052204053204054204055204056204057204058204059204060204061204062204063204064204065204066204067204068204069204070204071204072204073204074204075204076204077204078204079204080204081204082204083204084204085204086204087204088204089204090204091204092204093204094204095204096204097204098204099204100204101204102204103204104204105204106204107204108204109204110204111204112204113204114204115204116204117204118204119204120204121204122204123204124204125204126204127204128204129204130204131204132204133204134204135204136204137204138204139204140204141204142204143204144204145204146204147204148204149204150204151204152204153204154204155204156204157204158204159204160204161204162204163204164204165204166204167204168204169204170204171204172204173204174204175204176204177204178204179204180204181204182204183204184204185204186204187204188204189204190204191204192204193204194204195204196204197204198204199204200204201204202204203204204204205204206204207204208204209204210204211204212204213204214204215204216204217204218204219204220204221204222204223204224204225204226204227204228204229204230204231204232204233204234204235204236204237204238204239204240204241204242204243204244204245204246204247204248204249204250204251204252204253204254204255204256204257204258204259204260204261204262204263204264204265204266204267204268204269204270204271204272204273204274204275204276204277204278204279204280204281204282204283204284204285204286204287204288204289204290204291204292204293204294204295204296204297204298204299204300204301204302204303204304204305204306204307204308204309204310204311204312204313204314204315204316204317204318204319204320204321204322204323204324204325204326204327204328204329204330204331204332204333204334204335204336204337204338204339204340204341204342204343204344204345204346204347204348204349204350204351204352204353204354204355204356204357204358204359204360204361204362204363204364204365204366204367204368204369204370204371204372204373204374204375204376204377204378204379204380204381204382204383204384204385204386204387204388204389204390204391204392204393204394204395204396204397204398204399204400204401204402204403204404204405204406204407204408204409204410204411204412204413204414204415204416204417204418204419204420204421204422204423204424204425204426204427204428204429204430204431204432204433204434204435204436204437204438204439204440204441204442204443204444204445204446204447204448204449204450204451204452204453204454204455204456204457204458204459204460204461204462204463204464204465204466204467204468204469204470204471204472204473204474204475204476204477204478204479204480204481204482204483204484204485204486204487204488204489204490204491204492204493204494204495204496204497204498204499204500204501204502204503204504204505204506204507204508204509204510204511204512204513204514204515204516204517204518204519204520204521204522204523204524204525204526204527204528204529204530204531204532204533204534204535204536204537204538204539204540204541204542204543204544204545204546204547204548204549204550204551204552204553204554204555204556204557204558204559204560204561204562204563204564204565204566204567204568204569204570204571204572204573204574204575204576204577204578204579204580204581204582204583204584204585204586204587204588204589204590204591204592204593204594204595204596204597204598204599204600204601204602204603204604204605204606204607204608204609204610204611204612204613204614204615204616204617204618204619204620204621204622204623204624204625204626204627204628204629204630204631204632204633204634204635204636204637204638204639204640204641204642204643204644204645204646204647204648204649204650204651204652204653204654204655204656204657204658204659204660204661204662204663204664204665204666204667204668204669204670204671204672204673204674204675204676204677204678204679204680204681204682204683204684204685204686204687204688204689204690204691204692204693204694204695204696204697204698204699204700204701204702204703204704204705204706204707204708204709204710204711204712204713204714204715204716204717204718204719204720204721204722204723204724204725204726204727204728204729204730204731204732204733204734204735204736204737204738204739204740204741204742204743204744204745204746204747204748204749204750204751204752204753204754204755204756204757204758204759204760204761204762204763204764204765204766204767204768204769204770204771204772204773204774204775204776204777204778204779204780204781204782204783204784204785204786204787204788204789204790204791204792204793204794204795204796204797204798204799204800204801204802204803204804204805204806204807204808204809204810204811204812204813204814204815204816204817204818204819204820204821204822204823204824204825204826204827204828204829204830204831204832204833204834204835204836204837204838204839204840204841204842204843204844204845204846204847204848204849204850204851204852204853204854204855204856204857204858204859204860204861204862204863204864204865204866204867204868204869204870204871204872204873204874204875204876204877204878204879204880204881204882204883204884204885204886204887204888204889204890204891204892204893204894204895204896204897204898204899204900204901204902204903204904204905204906204907204908204909204910204911204912204913204914204915204916204917204918204919204920204921204922204923204924204925204926204927204928204929204930204931204932204933204934204935204936204937204938204939204940204941204942204943204944204945204946204947204948204949204950204951204952204953204954204955204956204957204958204959204960204961204962204963204964204965204966204967204968204969204970204971204972204973204974204975204976204977204978204979204980204981204982204983204984204985204986204987204988204989204990204991204992204993204994204995204996204997204998204999205000205001205002205003205004205005205006205007205008205009205010205011205012205013205014205015205016205017205018205019205020205021205022205023205024205025205026205027205028205029205030205031205032205033205034205035205036205037205038205039205040205041205042205043205044205045205046205047205048205049205050205051205052205053205054205055205056205057205058205059205060205061205062205063205064205065205066205067205068205069205070205071205072205073205074205075205076205077205078205079205080205081205082205083205084205085205086205087205088205089205090205091205092205093205094205095205096205097205098205099205100205101205102205103205104205105205106205107205108205109205110205111205112205113205114205115205116205117205118205119205120205121205122205123205124205125205126205127205128205129205130205131205132205133205134205135205136205137205138205139205140205141205142205143205144205145205146205147205148205149205150205151205152205153205154205155205156205157205158205159205160205161205162205163205164205165205166205167205168205169205170205171205172205173205174205175205176205177205178205179205180205181205182205183205184205185205186205187205188205189205190205191205192205193205194205195205196205197205198205199205200205201205202205203205204205205205206205207205208205209205210205211205212205213205214205215205216205217205218205219205220205221205222205223205224205225205226205227205228205229205230205231205232205233205234205235205236205237205238205239205240205241205242205243205244205245205246205247205248205249205250205251205252205253205254205255205256205257205258205259205260205261205262205263205264205265205266205267205268205269205270205271205272205273205274205275205276205277205278205279205280205281205282205283205284205285205286205287205288205289205290205291205292205293205294205295205296205297205298205299205300205301205302205303205304205305205306205307205308205309205310205311205312205313205314205315205316205317205318205319205320205321205322205323205324205325205326205327205328205329205330205331205332205333205334205335205336205337205338205339205340205341205342205343205344205345205346205347205348205349205350205351205352205353205354205355205356205357205358205359205360205361205362205363205364205365205366205367205368205369205370205371205372205373205374205375205376205377205378205379205380205381205382205383205384205385205386205387205388205389205390205391205392205393205394205395205396205397205398205399205400205401205402205403205404205405205406205407205408205409205410205411205412205413205414205415205416205417205418205419205420205421205422205423205424205425205426205427205428205429205430205431205432205433205434205435205436205437205438205439205440205441205442205443205444205445205446205447205448205449205450205451205452205453205454205455205456205457205458205459205460205461205462205463205464205465205466205467205468205469205470205471205472205473205474205475205476205477205478205479205480205481205482205483205484205485205486205487205488205489205490205491205492205493205494205495205496205497205498205499205500205501205502205503205504205505205506205507205508205509205510205511205512205513205514205515205516205517205518205519205520205521205522205523205524205525205526205527205528205529205530205531205532205533205534205535205536205537205538205539205540205541205542205543205544205545205546205547205548205549205550205551205552205553205554205555205556205557205558205559205560205561205562205563205564205565205566205567205568205569205570205571205572205573205574205575205576205577205578205579205580205581205582205583205584205585205586205587205588205589205590205591205592205593205594205595205596205597205598205599205600205601205602205603205604205605205606205607205608205609205610205611205612205613205614205615205616205617205618205619205620205621205622205623205624205625205626205627205628205629205630205631205632205633205634205635205636205637205638205639205640205641205642205643205644205645205646205647205648205649205650205651205652205653205654205655205656205657205658205659205660205661205662205663205664205665205666205667205668205669205670205671205672205673205674205675205676205677205678205679205680205681205682205683205684205685205686205687205688205689205690205691205692205693205694205695205696205697205698205699205700205701205702205703205704205705205706205707205708205709205710205711205712205713205714205715205716205717205718205719205720205721205722205723205724205725205726205727205728205729205730205731205732205733205734205735205736205737205738205739205740205741205742205743205744205745205746205747205748205749205750205751205752205753205754205755205756205757205758205759205760205761205762205763205764205765205766205767205768205769205770205771205772205773205774205775205776205777205778205779205780205781205782205783205784205785205786205787205788205789205790205791205792205793205794205795205796205797205798205799205800205801205802205803205804205805205806205807205808205809205810205811205812205813205814205815205816205817205818205819205820205821205822205823205824205825205826205827205828205829205830205831205832205833205834205835205836205837205838205839205840205841205842205843205844205845205846205847205848205849205850205851205852205853205854205855205856205857205858205859205860205861205862205863205864205865205866205867205868205869205870205871205872205873205874205875205876205877205878205879205880205881205882205883205884205885205886205887205888205889205890205891205892205893205894205895205896205897205898205899205900205901205902205903205904205905205906205907205908205909205910205911205912205913205914205915205916205917205918205919205920205921205922205923205924205925205926205927205928205929205930205931205932205933205934205935205936205937205938205939205940205941205942205943205944205945205946205947205948205949205950205951205952205953205954205955205956205957205958205959205960205961205962205963205964205965205966205967205968205969205970205971205972205973205974205975205976205977205978205979205980205981205982205983205984205985205986205987205988205989205990205991205992205993205994205995205996205997205998205999206000206001206002206003206004206005206006206007206008206009206010206011206012206013206014206015206016206017206018206019206020206021206022206023206024206025206026206027206028206029206030206031206032206033206034206035206036206037206038206039206040206041206042206043206044206045206046206047206048206049206050206051206052206053206054206055206056206057206058206059206060206061206062206063206064206065206066206067206068206069206070206071206072206073206074206075206076206077206078206079206080206081206082206083206084206085206086206087206088206089206090206091206092206093206094206095206096206097206098206099206100206101206102206103206104206105206106206107206108206109206110206111206112206113206114206115206116206117206118206119206120206121206122206123206124206125206126206127206128206129206130206131206132206133206134206135206136206137206138206139206140206141206142206143206144206145206146206147206148206149206150206151206152206153206154206155206156206157206158206159206160206161206162206163206164206165206166206167206168206169206170206171206172206173206174206175206176206177206178206179206180206181206182206183206184206185206186206187206188206189206190206191206192206193206194206195206196206197206198206199206200206201206202206203206204206205206206206207206208206209206210206211206212206213206214206215206216206217206218206219206220206221206222206223206224206225206226206227206228206229206230206231206232206233206234206235206236206237206238206239206240206241206242206243206244206245206246206247206248206249206250206251206252206253206254206255206256206257206258206259206260206261206262206263206264206265206266206267206268206269206270206271206272206273206274206275206276206277206278206279206280206281206282206283206284206285206286206287206288206289206290206291206292206293206294206295206296206297206298206299206300206301206302206303206304206305206306206307206308206309206310206311206312206313206314206315206316206317206318206319206320206321206322206323206324206325206326206327206328206329206330206331206332206333206334206335206336206337206338206339206340206341206342206343206344206345206346206347206348206349206350206351206352206353206354206355206356206357206358206359206360206361206362206363206364206365206366206367206368206369206370206371206372206373206374206375206376206377206378206379206380206381206382206383206384206385206386206387206388206389206390206391206392206393206394206395206396206397206398206399206400206401206402206403206404206405206406206407206408206409206410206411206412206413206414206415206416206417206418206419206420206421206422206423206424206425206426206427206428206429206430206431206432206433206434206435206436206437206438206439206440206441206442206443206444206445206446206447206448206449206450206451206452206453206454206455206456206457206458206459206460206461206462206463206464206465206466206467206468206469206470206471206472206473206474206475206476206477206478206479206480206481206482206483206484206485206486206487206488206489206490206491206492206493206494206495206496206497206498206499206500206501206502206503206504206505206506206507206508206509206510206511206512206513206514206515206516206517206518206519206520206521206522206523206524206525206526206527206528206529206530206531206532206533206534206535206536206537206538206539206540206541206542206543206544206545206546206547206548206549206550206551206552206553206554206555206556206557206558206559206560206561206562206563206564206565206566206567206568206569206570206571206572206573206574206575206576206577206578206579206580206581206582206583206584206585206586206587206588206589206590206591206592206593206594206595206596206597206598206599206600206601206602206603206604206605206606206607206608206609206610206611206612206613206614206615206616206617206618206619206620206621206622206623206624206625206626206627206628206629206630206631206632206633206634206635206636206637206638206639206640206641206642206643206644206645206646206647206648206649206650206651206652206653206654206655206656206657206658206659206660206661206662206663206664206665206666206667206668206669206670206671206672206673206674206675206676206677206678206679206680206681206682206683206684206685206686206687206688206689206690206691206692206693206694206695206696206697206698206699206700206701206702206703206704206705206706206707206708206709206710206711206712206713206714206715206716206717206718206719206720206721206722206723206724206725206726206727206728206729206730206731206732206733206734206735206736206737206738206739206740206741206742206743206744206745206746206747206748206749206750206751206752206753206754206755206756206757206758206759206760206761206762206763206764206765206766206767206768206769206770206771206772206773206774206775206776206777206778206779206780206781206782206783206784206785206786206787206788206789206790206791206792206793206794206795206796206797206798206799206800206801206802206803206804206805206806206807206808206809206810206811206812206813206814206815206816206817206818206819206820206821206822206823206824206825206826206827206828206829206830206831206832206833206834206835206836206837206838206839206840206841206842206843206844206845206846206847206848206849206850206851206852206853206854206855206856206857206858206859206860206861206862206863206864206865206866206867206868206869206870206871206872206873206874206875206876206877206878206879206880206881206882206883206884206885206886206887206888206889206890206891206892206893206894206895206896206897206898206899206900206901206902206903206904206905206906206907206908206909206910206911206912206913206914206915206916206917206918206919206920206921206922206923206924206925206926206927206928206929206930206931206932206933206934206935206936206937206938206939206940206941206942206943206944206945206946206947206948206949206950206951206952206953206954206955206956206957206958206959206960206961206962206963206964206965206966206967206968206969206970206971206972206973206974206975206976206977206978206979206980206981206982206983206984206985206986206987206988206989206990206991206992206993206994206995206996206997206998206999207000207001207002207003207004207005207006207007207008207009207010207011207012207013207014207015207016207017207018207019207020207021207022207023207024207025207026207027207028207029207030207031207032207033207034207035207036207037207038207039207040207041207042207043207044207045207046207047207048207049207050207051207052207053207054207055207056207057207058207059207060207061207062207063207064207065207066207067207068207069207070207071207072207073207074207075207076207077207078207079207080207081207082207083207084207085207086207087207088207089207090207091207092207093207094207095207096207097207098207099207100207101207102207103207104207105207106207107207108207109207110207111207112207113207114207115207116207117207118207119207120207121207122207123207124207125207126207127207128207129207130207131207132207133207134207135207136207137207138207139207140207141207142207143207144207145207146207147207148207149207150207151207152207153207154207155207156207157207158207159207160207161207162207163207164207165207166207167207168207169207170207171207172207173207174207175207176207177207178207179207180207181207182207183207184207185207186207187207188207189207190207191207192207193207194207195207196207197207198207199207200207201207202207203207204207205207206207207207208207209207210207211207212207213207214207215207216207217207218207219207220207221207222207223207224207225207226207227207228207229207230207231207232207233207234207235207236207237207238207239207240207241207242207243207244207245207246207247207248207249207250207251207252207253207254207255207256207257207258207259207260207261207262207263207264207265207266207267207268207269207270207271207272207273207274207275207276207277207278207279207280207281207282207283207284207285207286207287207288207289207290207291207292207293207294207295207296207297207298207299207300207301207302207303207304207305207306207307207308207309207310207311207312207313207314207315207316207317207318207319207320207321207322207323207324207325207326207327207328207329207330207331207332207333207334207335207336207337207338207339207340207341207342207343207344207345207346207347207348207349207350207351207352207353207354207355207356207357207358207359207360207361207362207363207364207365207366207367207368207369207370207371207372207373207374207375207376207377207378207379207380207381207382207383207384207385207386207387207388207389207390207391207392207393207394207395207396207397207398207399207400207401207402207403207404207405207406207407207408207409207410207411207412207413207414207415207416207417207418207419207420207421207422207423207424207425207426207427207428207429207430207431207432207433207434207435207436207437207438207439207440207441207442207443207444207445207446207447207448207449207450207451207452207453207454207455207456207457207458207459207460207461207462207463207464207465207466207467207468207469207470207471207472207473207474207475207476207477207478207479207480207481207482207483207484207485207486207487207488207489207490207491207492207493207494207495207496207497207498207499207500207501207502207503207504207505207506207507207508207509207510207511207512207513207514207515207516207517207518207519207520207521207522207523207524207525207526207527207528207529207530207531207532207533207534207535207536207537207538207539207540207541207542207543207544207545207546207547207548207549207550207551207552207553207554207555207556207557207558207559207560207561207562207563207564207565207566207567207568207569207570207571207572207573207574207575207576207577207578207579207580207581207582207583207584207585207586207587207588207589207590207591207592207593207594207595207596207597207598207599207600207601207602207603207604207605207606207607207608207609207610207611207612207613207614207615207616207617207618207619207620207621207622207623207624207625207626207627207628207629207630207631207632207633207634207635207636207637207638207639207640207641207642207643207644207645207646207647207648207649207650207651207652207653207654207655207656207657207658207659207660207661207662207663207664207665207666207667207668207669207670207671207672207673207674207675207676207677207678207679207680207681207682207683207684207685207686207687207688207689207690207691207692207693207694207695207696207697207698207699207700207701207702207703207704207705207706207707207708207709207710207711207712207713207714207715207716207717207718207719207720207721207722207723207724207725207726207727207728207729207730207731207732207733207734207735207736207737207738207739207740207741207742207743207744207745207746207747207748207749207750207751207752207753207754207755207756207757207758207759207760207761207762207763207764207765207766207767207768207769207770207771207772207773207774207775207776207777207778207779207780207781207782207783207784207785207786207787207788207789207790207791207792207793207794207795207796207797207798207799207800207801207802207803207804207805207806207807207808207809207810207811207812207813207814207815207816207817207818207819207820207821207822207823207824207825207826207827207828207829207830207831207832207833207834207835207836207837207838207839207840207841207842207843207844207845207846207847207848207849207850207851207852207853207854207855207856207857207858207859207860207861207862207863207864207865207866207867207868207869207870207871207872207873207874207875207876207877207878207879207880207881207882207883207884207885207886207887207888207889207890207891207892207893207894207895207896207897207898207899207900207901207902207903207904207905207906207907207908207909207910207911207912207913207914207915207916207917207918207919207920207921207922207923207924207925207926207927207928207929207930207931207932207933207934207935207936207937207938207939207940207941207942207943207944207945207946207947207948207949207950207951207952207953207954207955207956207957207958207959207960207961207962207963207964207965207966207967207968207969207970207971207972207973207974207975207976207977207978207979207980207981207982207983207984207985207986207987207988207989207990207991207992207993207994207995207996207997207998207999208000208001208002208003208004208005208006208007208008208009208010208011208012208013208014208015208016208017208018208019208020208021208022208023208024208025208026208027208028208029208030208031208032208033208034208035208036208037208038208039208040208041208042208043208044208045208046208047208048208049208050208051208052208053208054208055208056208057208058208059208060208061208062208063208064208065208066208067208068208069208070208071208072208073208074208075208076208077208078208079208080208081208082208083208084208085208086208087208088208089208090208091208092208093208094208095208096208097208098208099208100208101208102208103208104208105208106208107208108208109208110208111208112208113208114208115208116208117208118208119208120208121208122208123208124208125208126208127208128208129208130208131208132208133208134208135208136208137208138208139208140208141208142208143208144208145208146208147208148208149208150208151208152208153208154208155208156208157208158208159208160208161208162208163208164208165208166208167208168208169208170208171208172208173208174208175208176208177208178208179208180208181208182208183208184208185208186208187208188208189208190208191208192208193208194208195208196208197208198208199208200208201208202208203208204208205208206208207208208208209208210208211208212208213208214208215208216208217208218208219208220208221208222208223208224208225208226208227208228208229208230208231208232208233208234208235208236208237208238208239208240208241208242208243208244208245208246208247208248208249208250208251208252208253208254208255208256208257208258208259208260208261208262208263208264208265208266208267208268208269208270208271208272208273208274208275208276208277208278208279208280208281208282208283208284208285208286208287208288208289208290208291208292208293208294208295208296208297208298208299208300208301208302208303208304208305208306208307208308208309208310208311208312208313208314208315208316208317208318208319208320208321208322208323208324208325208326208327208328208329208330208331208332208333208334208335208336208337208338208339208340208341208342208343208344208345208346208347208348208349208350208351208352208353208354208355208356208357208358208359208360208361208362208363208364208365208366208367208368208369208370208371208372208373208374208375208376208377208378208379208380208381208382208383208384208385208386208387208388208389208390208391208392208393208394208395208396208397208398208399208400208401208402208403208404208405208406208407208408208409208410208411208412208413208414208415208416208417208418208419208420208421208422208423208424208425208426208427208428208429208430208431208432208433208434208435208436208437208438208439208440208441208442208443208444208445208446208447208448208449208450208451208452208453208454208455208456208457208458208459208460208461208462208463208464208465208466208467208468208469208470208471208472208473208474208475208476208477208478208479208480208481208482208483208484208485208486208487208488208489208490208491208492208493208494208495208496208497208498208499208500208501208502208503208504208505208506208507208508208509208510208511208512208513208514208515208516208517208518208519208520208521208522208523208524208525208526208527208528208529208530208531208532208533208534208535208536208537208538208539208540208541208542208543208544208545208546208547208548208549208550208551208552208553208554208555208556208557208558208559208560208561208562208563208564208565208566208567208568208569208570208571208572208573208574208575208576208577208578208579208580208581208582208583208584208585208586208587208588208589208590208591208592208593208594208595208596208597208598208599208600208601208602208603208604208605208606208607208608208609208610208611208612208613208614208615208616208617208618208619208620208621208622208623208624208625208626208627208628208629208630208631208632208633208634208635208636208637208638208639208640208641208642208643208644208645208646208647208648208649208650208651208652208653208654208655208656208657208658208659208660208661208662208663208664208665208666208667208668208669208670208671208672208673208674208675208676208677208678208679208680208681208682208683208684208685208686208687208688208689208690208691208692208693208694208695208696208697208698208699208700208701208702208703208704208705208706208707208708208709208710208711208712208713208714208715208716208717208718208719208720208721208722208723208724208725208726208727208728208729208730208731208732208733208734208735208736208737208738208739208740208741208742208743208744208745208746208747208748208749208750208751208752208753208754208755208756208757208758208759208760208761208762208763208764208765208766208767208768208769208770208771208772208773208774208775208776208777208778208779208780208781208782208783208784208785208786208787208788208789208790208791208792208793208794208795208796208797208798208799208800208801208802208803208804208805208806208807208808208809208810208811208812208813208814208815208816208817208818208819208820208821208822208823208824208825208826208827208828208829208830208831208832208833208834208835208836208837208838208839208840208841208842208843208844208845208846208847208848208849208850208851208852208853208854208855208856208857208858208859208860208861208862208863208864208865208866208867208868208869208870208871208872208873208874208875208876208877208878208879208880208881208882208883208884208885208886208887208888208889208890208891208892208893208894208895208896208897208898208899208900208901208902208903208904208905208906208907208908208909208910208911208912208913208914208915208916208917208918208919208920208921208922208923208924208925208926208927208928208929208930208931208932208933208934208935208936208937208938208939208940208941208942208943208944208945208946208947208948208949208950208951208952208953208954208955208956208957208958208959208960208961208962208963208964208965208966208967208968208969208970208971208972208973208974208975208976208977208978208979208980208981208982208983208984208985208986208987208988208989208990208991208992208993208994208995208996208997208998208999209000209001209002209003209004209005209006209007209008209009209010209011209012209013209014209015209016209017209018209019209020209021209022209023209024209025209026209027209028209029209030209031209032209033209034209035209036209037209038209039209040209041209042209043209044209045209046209047209048209049209050209051209052209053209054209055209056209057209058209059209060209061209062209063209064209065209066209067209068209069209070209071209072209073209074209075209076209077209078209079209080209081209082209083209084209085209086209087209088209089209090209091209092209093209094209095209096209097209098209099209100209101209102209103209104209105209106209107209108209109209110209111209112209113209114209115209116209117209118209119209120209121209122209123209124209125209126209127209128209129209130209131209132209133209134209135209136209137209138209139209140209141209142209143209144209145209146209147209148209149209150209151209152209153209154209155209156209157209158209159209160209161209162209163209164209165209166209167209168209169209170209171209172209173209174209175209176209177209178209179209180209181209182209183209184209185209186209187209188209189209190209191209192209193209194209195209196209197209198209199209200209201209202209203209204209205209206209207209208209209209210209211209212209213209214209215209216209217209218209219209220209221209222209223209224209225209226209227209228209229209230209231209232209233209234209235209236209237209238209239209240209241209242209243209244209245209246209247209248209249209250209251209252209253209254209255209256209257209258209259209260209261209262209263209264209265209266209267209268209269209270209271209272209273209274209275209276209277209278209279209280209281209282209283209284209285209286209287209288209289209290209291209292209293209294209295209296209297209298209299209300209301209302209303209304209305209306209307209308209309209310209311209312209313209314209315209316209317209318209319209320209321209322209323209324209325209326209327209328209329209330209331209332209333209334209335209336209337209338209339209340209341209342209343209344209345209346209347209348209349209350209351209352209353209354209355209356209357209358209359209360209361209362209363209364209365209366209367209368209369209370209371209372209373209374209375209376209377209378209379209380209381209382209383209384209385209386209387209388209389209390209391209392209393209394209395209396209397209398209399209400209401209402209403209404209405209406209407209408209409209410209411209412209413209414209415209416209417209418209419209420209421209422209423209424209425209426209427209428209429209430209431209432209433209434209435209436209437209438209439209440209441209442209443209444209445209446209447209448209449209450209451209452209453209454209455209456209457209458209459209460209461209462209463209464209465209466209467209468209469209470209471209472209473209474209475209476209477209478209479209480209481209482209483209484209485209486209487209488209489209490209491209492209493209494209495209496209497209498209499209500209501209502209503209504209505209506209507209508209509209510209511209512209513209514209515209516209517209518209519209520209521209522209523209524209525209526209527209528209529209530209531209532209533209534209535209536209537209538209539209540209541209542209543209544209545209546209547209548209549209550209551209552209553209554209555209556209557209558209559209560209561209562209563209564209565209566209567209568209569209570209571209572209573209574209575209576209577209578209579209580209581209582209583209584209585209586209587209588209589209590209591209592209593209594209595209596209597209598209599209600209601209602209603209604209605209606209607209608209609209610209611209612209613209614209615209616209617209618209619209620209621209622209623209624209625209626209627209628209629209630209631209632209633209634209635209636209637209638209639209640209641209642209643209644209645209646209647209648209649209650209651209652209653209654209655209656209657209658209659209660209661209662209663209664209665209666209667209668209669209670209671209672209673209674209675209676209677209678209679209680209681209682209683209684209685209686209687209688209689209690209691209692209693209694209695209696209697209698209699209700209701209702209703209704209705209706209707209708209709209710209711209712209713209714209715209716209717209718209719209720209721209722209723209724209725209726209727209728209729209730209731209732209733209734209735209736209737209738209739209740209741209742209743209744209745209746209747209748209749209750209751209752209753209754209755209756209757209758209759209760209761209762209763209764209765209766209767209768209769209770209771209772209773209774209775209776209777209778209779209780209781209782209783209784209785209786209787209788209789209790209791209792209793209794209795209796209797209798209799209800209801209802209803209804209805209806209807209808209809209810209811209812209813209814209815209816209817209818209819209820209821209822209823209824209825209826209827209828209829209830209831209832209833209834209835209836209837209838209839209840209841209842209843209844209845209846209847209848209849209850209851209852209853209854209855209856209857209858209859209860209861209862209863209864209865209866209867209868209869209870209871209872209873209874209875209876209877209878209879209880209881209882209883209884209885209886209887209888209889209890209891209892209893209894209895209896209897209898209899209900209901209902209903209904209905209906209907209908209909209910209911209912209913209914209915209916209917209918209919209920209921209922209923209924209925209926209927209928209929209930209931209932209933209934209935209936209937209938209939209940209941
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.23.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 ctime.c *******************************************/
  26. /*
  27. ** 2010 February 23
  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. **
  38. ** This file implements routines used to report what compile-time options
  39. ** SQLite was built with.
  40. */
  41. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  42. /*
  43. ** Include the configuration header output by 'configure' if we're using the
  44. ** autoconf-based build
  45. */
  46. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  47. #include "config.h"
  48. #define SQLITECONFIG_H 1
  49. #endif
  50. /* These macros are provided to "stringify" the value of the define
  51. ** for those options in which the value is meaningful. */
  52. #define CTIMEOPT_VAL_(opt) #opt
  53. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  54. /*
  55. ** An array of names of all compile-time options. This array should
  56. ** be sorted A-Z.
  57. **
  58. ** This array looks large, but in a typical installation actually uses
  59. ** only a handful of compile-time options, so most times this array is usually
  60. ** rather short and uses little memory space.
  61. */
  62. static const char * const sqlite3azCompileOpt[] = {
  63. /*
  64. ** BEGIN CODE GENERATED BY tool/mkctime.tcl
  65. */
  66. #if SQLITE_32BIT_ROWID
  67. "32BIT_ROWID",
  68. #endif
  69. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  70. "4_BYTE_ALIGNED_MALLOC",
  71. #endif
  72. #if SQLITE_64BIT_STATS
  73. "64BIT_STATS",
  74. #endif
  75. #if SQLITE_ALLOW_COVERING_INDEX_SCAN
  76. "ALLOW_COVERING_INDEX_SCAN",
  77. #endif
  78. #if SQLITE_ALLOW_URI_AUTHORITY
  79. "ALLOW_URI_AUTHORITY",
  80. #endif
  81. #ifdef SQLITE_BITMASK_TYPE
  82. "BITMASK_TYPE=" CTIMEOPT_VAL(SQLITE_BITMASK_TYPE),
  83. #endif
  84. #if SQLITE_BUG_COMPATIBLE_20160819
  85. "BUG_COMPATIBLE_20160819",
  86. #endif
  87. #if SQLITE_CASE_SENSITIVE_LIKE
  88. "CASE_SENSITIVE_LIKE",
  89. #endif
  90. #if SQLITE_CHECK_PAGES
  91. "CHECK_PAGES",
  92. #endif
  93. #if defined(__clang__) && defined(__clang_major__)
  94. "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
  95. CTIMEOPT_VAL(__clang_minor__) "."
  96. CTIMEOPT_VAL(__clang_patchlevel__),
  97. #elif defined(_MSC_VER)
  98. "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
  99. #elif defined(__GNUC__) && defined(__VERSION__)
  100. "COMPILER=gcc-" __VERSION__,
  101. #endif
  102. #if SQLITE_COVERAGE_TEST
  103. "COVERAGE_TEST",
  104. #endif
  105. #if SQLITE_DEBUG
  106. "DEBUG",
  107. #endif
  108. #if SQLITE_DEFAULT_AUTOMATIC_INDEX
  109. "DEFAULT_AUTOMATIC_INDEX",
  110. #endif
  111. #if SQLITE_DEFAULT_AUTOVACUUM
  112. "DEFAULT_AUTOVACUUM",
  113. #endif
  114. #ifdef SQLITE_DEFAULT_CACHE_SIZE
  115. "DEFAULT_CACHE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_CACHE_SIZE),
  116. #endif
  117. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  118. "DEFAULT_CKPTFULLFSYNC",
  119. #endif
  120. #ifdef SQLITE_DEFAULT_FILE_FORMAT
  121. "DEFAULT_FILE_FORMAT=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_FORMAT),
  122. #endif
  123. #ifdef SQLITE_DEFAULT_FILE_PERMISSIONS
  124. "DEFAULT_FILE_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_FILE_PERMISSIONS),
  125. #endif
  126. #if SQLITE_DEFAULT_FOREIGN_KEYS
  127. "DEFAULT_FOREIGN_KEYS",
  128. #endif
  129. #ifdef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  130. "DEFAULT_JOURNAL_SIZE_LIMIT=" CTIMEOPT_VAL(SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT),
  131. #endif
  132. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  133. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  134. #endif
  135. #ifdef SQLITE_DEFAULT_LOOKASIDE
  136. "DEFAULT_LOOKASIDE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOOKASIDE),
  137. #endif
  138. #if SQLITE_DEFAULT_MEMSTATUS
  139. "DEFAULT_MEMSTATUS",
  140. #endif
  141. #ifdef SQLITE_DEFAULT_MMAP_SIZE
  142. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  143. #endif
  144. #ifdef SQLITE_DEFAULT_PAGE_SIZE
  145. "DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_PAGE_SIZE),
  146. #endif
  147. #ifdef SQLITE_DEFAULT_PCACHE_INITSZ
  148. "DEFAULT_PCACHE_INITSZ=" CTIMEOPT_VAL(SQLITE_DEFAULT_PCACHE_INITSZ),
  149. #endif
  150. #ifdef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  151. "DEFAULT_PROXYDIR_PERMISSIONS=" CTIMEOPT_VAL(SQLITE_DEFAULT_PROXYDIR_PERMISSIONS),
  152. #endif
  153. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  154. "DEFAULT_RECURSIVE_TRIGGERS",
  155. #endif
  156. #ifdef SQLITE_DEFAULT_ROWEST
  157. "DEFAULT_ROWEST=" CTIMEOPT_VAL(SQLITE_DEFAULT_ROWEST),
  158. #endif
  159. #ifdef SQLITE_DEFAULT_SECTOR_SIZE
  160. "DEFAULT_SECTOR_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_SECTOR_SIZE),
  161. #endif
  162. #ifdef SQLITE_DEFAULT_SYNCHRONOUS
  163. "DEFAULT_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_SYNCHRONOUS),
  164. #endif
  165. #ifdef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  166. "DEFAULT_WAL_AUTOCHECKPOINT=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_AUTOCHECKPOINT),
  167. #endif
  168. #ifdef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  169. "DEFAULT_WAL_SYNCHRONOUS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WAL_SYNCHRONOUS),
  170. #endif
  171. #ifdef SQLITE_DEFAULT_WORKER_THREADS
  172. "DEFAULT_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_DEFAULT_WORKER_THREADS),
  173. #endif
  174. #if SQLITE_DIRECT_OVERFLOW_READ
  175. "DIRECT_OVERFLOW_READ",
  176. #endif
  177. #if SQLITE_DISABLE_DIRSYNC
  178. "DISABLE_DIRSYNC",
  179. #endif
  180. #if SQLITE_DISABLE_FTS3_UNICODE
  181. "DISABLE_FTS3_UNICODE",
  182. #endif
  183. #if SQLITE_DISABLE_FTS4_DEFERRED
  184. "DISABLE_FTS4_DEFERRED",
  185. #endif
  186. #if SQLITE_DISABLE_INTRINSIC
  187. "DISABLE_INTRINSIC",
  188. #endif
  189. #if SQLITE_DISABLE_LFS
  190. "DISABLE_LFS",
  191. #endif
  192. #if SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  193. "DISABLE_PAGECACHE_OVERFLOW_STATS",
  194. #endif
  195. #if SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  196. "DISABLE_SKIPAHEAD_DISTINCT",
  197. #endif
  198. #ifdef SQLITE_ENABLE_8_3_NAMES
  199. "ENABLE_8_3_NAMES=" CTIMEOPT_VAL(SQLITE_ENABLE_8_3_NAMES),
  200. #endif
  201. #if SQLITE_ENABLE_API_ARMOR
  202. "ENABLE_API_ARMOR",
  203. #endif
  204. #if SQLITE_ENABLE_ATOMIC_WRITE
  205. "ENABLE_ATOMIC_WRITE",
  206. #endif
  207. #if SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  208. "ENABLE_BATCH_ATOMIC_WRITE",
  209. #endif
  210. #if SQLITE_ENABLE_CEROD
  211. "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
  212. #endif
  213. #if SQLITE_ENABLE_COLUMN_METADATA
  214. "ENABLE_COLUMN_METADATA",
  215. #endif
  216. #if SQLITE_ENABLE_COLUMN_USED_MASK
  217. "ENABLE_COLUMN_USED_MASK",
  218. #endif
  219. #if SQLITE_ENABLE_COSTMULT
  220. "ENABLE_COSTMULT",
  221. #endif
  222. #if SQLITE_ENABLE_CURSOR_HINTS
  223. "ENABLE_CURSOR_HINTS",
  224. #endif
  225. #if SQLITE_ENABLE_DBSTAT_VTAB
  226. "ENABLE_DBSTAT_VTAB",
  227. #endif
  228. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  229. "ENABLE_EXPENSIVE_ASSERT",
  230. #endif
  231. #if SQLITE_ENABLE_FTS1
  232. "ENABLE_FTS1",
  233. #endif
  234. #if SQLITE_ENABLE_FTS2
  235. "ENABLE_FTS2",
  236. #endif
  237. #if SQLITE_ENABLE_FTS3
  238. "ENABLE_FTS3",
  239. #endif
  240. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  241. "ENABLE_FTS3_PARENTHESIS",
  242. #endif
  243. #if SQLITE_ENABLE_FTS3_TOKENIZER
  244. "ENABLE_FTS3_TOKENIZER",
  245. #endif
  246. #if SQLITE_ENABLE_FTS4
  247. "ENABLE_FTS4",
  248. #endif
  249. #if SQLITE_ENABLE_FTS5
  250. "ENABLE_FTS5",
  251. #endif
  252. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  253. "ENABLE_HIDDEN_COLUMNS",
  254. #endif
  255. #if SQLITE_ENABLE_ICU
  256. "ENABLE_ICU",
  257. #endif
  258. #if SQLITE_ENABLE_IOTRACE
  259. "ENABLE_IOTRACE",
  260. #endif
  261. #if SQLITE_ENABLE_JSON1
  262. "ENABLE_JSON1",
  263. #endif
  264. #if SQLITE_ENABLE_LOAD_EXTENSION
  265. "ENABLE_LOAD_EXTENSION",
  266. #endif
  267. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  268. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  269. #endif
  270. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  271. "ENABLE_MEMORY_MANAGEMENT",
  272. #endif
  273. #if SQLITE_ENABLE_MEMSYS3
  274. "ENABLE_MEMSYS3",
  275. #endif
  276. #if SQLITE_ENABLE_MEMSYS5
  277. "ENABLE_MEMSYS5",
  278. #endif
  279. #if SQLITE_ENABLE_MULTIPLEX
  280. "ENABLE_MULTIPLEX",
  281. #endif
  282. #if SQLITE_ENABLE_NULL_TRIM
  283. "ENABLE_NULL_TRIM",
  284. #endif
  285. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  286. "ENABLE_OVERSIZE_CELL_CHECK",
  287. #endif
  288. #if SQLITE_ENABLE_PREUPDATE_HOOK
  289. "ENABLE_PREUPDATE_HOOK",
  290. #endif
  291. #if SQLITE_ENABLE_QPSG
  292. "ENABLE_QPSG",
  293. #endif
  294. #if SQLITE_ENABLE_RBU
  295. "ENABLE_RBU",
  296. #endif
  297. #if SQLITE_ENABLE_RTREE
  298. "ENABLE_RTREE",
  299. #endif
  300. #if SQLITE_ENABLE_SELECTTRACE
  301. "ENABLE_SELECTTRACE",
  302. #endif
  303. #if SQLITE_ENABLE_SESSION
  304. "ENABLE_SESSION",
  305. #endif
  306. #if SQLITE_ENABLE_SNAPSHOT
  307. "ENABLE_SNAPSHOT",
  308. #endif
  309. #if SQLITE_ENABLE_SQLLOG
  310. "ENABLE_SQLLOG",
  311. #endif
  312. #if defined(SQLITE_ENABLE_STAT4)
  313. "ENABLE_STAT4",
  314. #elif defined(SQLITE_ENABLE_STAT3)
  315. "ENABLE_STAT3",
  316. #endif
  317. #if SQLITE_ENABLE_STMTVTAB
  318. "ENABLE_STMTVTAB",
  319. #endif
  320. #if SQLITE_ENABLE_STMT_SCANSTATUS
  321. "ENABLE_STMT_SCANSTATUS",
  322. #endif
  323. #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  324. "ENABLE_UNKNOWN_SQL_FUNCTION",
  325. #endif
  326. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  327. "ENABLE_UNLOCK_NOTIFY",
  328. #endif
  329. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  330. "ENABLE_UPDATE_DELETE_LIMIT",
  331. #endif
  332. #if SQLITE_ENABLE_URI_00_ERROR
  333. "ENABLE_URI_00_ERROR",
  334. #endif
  335. #if SQLITE_ENABLE_VFSTRACE
  336. "ENABLE_VFSTRACE",
  337. #endif
  338. #if SQLITE_ENABLE_WHERETRACE
  339. "ENABLE_WHERETRACE",
  340. #endif
  341. #if SQLITE_ENABLE_ZIPVFS
  342. "ENABLE_ZIPVFS",
  343. #endif
  344. #if SQLITE_EXPLAIN_ESTIMATED_ROWS
  345. "EXPLAIN_ESTIMATED_ROWS",
  346. #endif
  347. #if SQLITE_EXTRA_IFNULLROW
  348. "EXTRA_IFNULLROW",
  349. #endif
  350. #ifdef SQLITE_EXTRA_INIT
  351. "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
  352. #endif
  353. #ifdef SQLITE_EXTRA_SHUTDOWN
  354. "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
  355. #endif
  356. #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
  357. "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
  358. #endif
  359. #if SQLITE_FTS5_ENABLE_TEST_MI
  360. "FTS5_ENABLE_TEST_MI",
  361. #endif
  362. #if SQLITE_FTS5_NO_WITHOUT_ROWID
  363. "FTS5_NO_WITHOUT_ROWID",
  364. #endif
  365. #if SQLITE_HAS_CODEC
  366. "HAS_CODEC",
  367. #endif
  368. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  369. "HAVE_ISNAN",
  370. #endif
  371. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  372. "HOMEGROWN_RECURSIVE_MUTEX",
  373. #endif
  374. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  375. "IGNORE_AFP_LOCK_ERRORS",
  376. #endif
  377. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  378. "IGNORE_FLOCK_LOCK_ERRORS",
  379. #endif
  380. #if SQLITE_INLINE_MEMCPY
  381. "INLINE_MEMCPY",
  382. #endif
  383. #if SQLITE_INT64_TYPE
  384. "INT64_TYPE",
  385. #endif
  386. #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  387. "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
  388. #endif
  389. #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
  390. "LIKE_DOESNT_MATCH_BLOBS",
  391. #endif
  392. #if SQLITE_LOCK_TRACE
  393. "LOCK_TRACE",
  394. #endif
  395. #if SQLITE_LOG_CACHE_SPILL
  396. "LOG_CACHE_SPILL",
  397. #endif
  398. #ifdef SQLITE_MALLOC_SOFT_LIMIT
  399. "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
  400. #endif
  401. #ifdef SQLITE_MAX_ATTACHED
  402. "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
  403. #endif
  404. #ifdef SQLITE_MAX_COLUMN
  405. "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
  406. #endif
  407. #ifdef SQLITE_MAX_COMPOUND_SELECT
  408. "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
  409. #endif
  410. #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
  411. "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
  412. #endif
  413. #ifdef SQLITE_MAX_EXPR_DEPTH
  414. "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
  415. #endif
  416. #ifdef SQLITE_MAX_FUNCTION_ARG
  417. "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
  418. #endif
  419. #ifdef SQLITE_MAX_LENGTH
  420. "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
  421. #endif
  422. #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
  423. "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
  424. #endif
  425. #ifdef SQLITE_MAX_MEMORY
  426. "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
  427. #endif
  428. #ifdef SQLITE_MAX_MMAP_SIZE
  429. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  430. #endif
  431. #ifdef SQLITE_MAX_MMAP_SIZE_
  432. "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
  433. #endif
  434. #ifdef SQLITE_MAX_PAGE_COUNT
  435. "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
  436. #endif
  437. #ifdef SQLITE_MAX_PAGE_SIZE
  438. "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
  439. #endif
  440. #ifdef SQLITE_MAX_SCHEMA_RETRY
  441. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  442. #endif
  443. #ifdef SQLITE_MAX_SQL_LENGTH
  444. "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
  445. #endif
  446. #ifdef SQLITE_MAX_TRIGGER_DEPTH
  447. "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
  448. #endif
  449. #ifdef SQLITE_MAX_VARIABLE_NUMBER
  450. "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
  451. #endif
  452. #ifdef SQLITE_MAX_VDBE_OP
  453. "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
  454. #endif
  455. #ifdef SQLITE_MAX_WORKER_THREADS
  456. "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
  457. #endif
  458. #if SQLITE_MEMDEBUG
  459. "MEMDEBUG",
  460. #endif
  461. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  462. "MIXED_ENDIAN_64BIT_FLOAT",
  463. #endif
  464. #if SQLITE_MMAP_READWRITE
  465. "MMAP_READWRITE",
  466. #endif
  467. #if SQLITE_MUTEX_NOOP
  468. "MUTEX_NOOP",
  469. #endif
  470. #if SQLITE_MUTEX_NREF
  471. "MUTEX_NREF",
  472. #endif
  473. #if SQLITE_MUTEX_OMIT
  474. "MUTEX_OMIT",
  475. #endif
  476. #if SQLITE_MUTEX_PTHREADS
  477. "MUTEX_PTHREADS",
  478. #endif
  479. #if SQLITE_MUTEX_W32
  480. "MUTEX_W32",
  481. #endif
  482. #if SQLITE_NEED_ERR_NAME
  483. "NEED_ERR_NAME",
  484. #endif
  485. #if SQLITE_NOINLINE
  486. "NOINLINE",
  487. #endif
  488. #if SQLITE_NO_SYNC
  489. "NO_SYNC",
  490. #endif
  491. #if SQLITE_OMIT_ALTERTABLE
  492. "OMIT_ALTERTABLE",
  493. #endif
  494. #if SQLITE_OMIT_ANALYZE
  495. "OMIT_ANALYZE",
  496. #endif
  497. #if SQLITE_OMIT_ATTACH
  498. "OMIT_ATTACH",
  499. #endif
  500. #if SQLITE_OMIT_AUTHORIZATION
  501. "OMIT_AUTHORIZATION",
  502. #endif
  503. #if SQLITE_OMIT_AUTOINCREMENT
  504. "OMIT_AUTOINCREMENT",
  505. #endif
  506. #if SQLITE_OMIT_AUTOINIT
  507. "OMIT_AUTOINIT",
  508. #endif
  509. #if SQLITE_OMIT_AUTOMATIC_INDEX
  510. "OMIT_AUTOMATIC_INDEX",
  511. #endif
  512. #if SQLITE_OMIT_AUTORESET
  513. "OMIT_AUTORESET",
  514. #endif
  515. #if SQLITE_OMIT_AUTOVACUUM
  516. "OMIT_AUTOVACUUM",
  517. #endif
  518. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  519. "OMIT_BETWEEN_OPTIMIZATION",
  520. #endif
  521. #if SQLITE_OMIT_BLOB_LITERAL
  522. "OMIT_BLOB_LITERAL",
  523. #endif
  524. #if SQLITE_OMIT_BTREECOUNT
  525. "OMIT_BTREECOUNT",
  526. #endif
  527. #if SQLITE_OMIT_CAST
  528. "OMIT_CAST",
  529. #endif
  530. #if SQLITE_OMIT_CHECK
  531. "OMIT_CHECK",
  532. #endif
  533. #if SQLITE_OMIT_COMPLETE
  534. "OMIT_COMPLETE",
  535. #endif
  536. #if SQLITE_OMIT_COMPOUND_SELECT
  537. "OMIT_COMPOUND_SELECT",
  538. #endif
  539. #if SQLITE_OMIT_CONFLICT_CLAUSE
  540. "OMIT_CONFLICT_CLAUSE",
  541. #endif
  542. #if SQLITE_OMIT_CTE
  543. "OMIT_CTE",
  544. #endif
  545. #if SQLITE_OMIT_DATETIME_FUNCS
  546. "OMIT_DATETIME_FUNCS",
  547. #endif
  548. #if SQLITE_OMIT_DECLTYPE
  549. "OMIT_DECLTYPE",
  550. #endif
  551. #if SQLITE_OMIT_DEPRECATED
  552. "OMIT_DEPRECATED",
  553. #endif
  554. #if SQLITE_OMIT_DISKIO
  555. "OMIT_DISKIO",
  556. #endif
  557. #if SQLITE_OMIT_EXPLAIN
  558. "OMIT_EXPLAIN",
  559. #endif
  560. #if SQLITE_OMIT_FLAG_PRAGMAS
  561. "OMIT_FLAG_PRAGMAS",
  562. #endif
  563. #if SQLITE_OMIT_FLOATING_POINT
  564. "OMIT_FLOATING_POINT",
  565. #endif
  566. #if SQLITE_OMIT_FOREIGN_KEY
  567. "OMIT_FOREIGN_KEY",
  568. #endif
  569. #if SQLITE_OMIT_GET_TABLE
  570. "OMIT_GET_TABLE",
  571. #endif
  572. #if SQLITE_OMIT_HEX_INTEGER
  573. "OMIT_HEX_INTEGER",
  574. #endif
  575. #if SQLITE_OMIT_INCRBLOB
  576. "OMIT_INCRBLOB",
  577. #endif
  578. #if SQLITE_OMIT_INTEGRITY_CHECK
  579. "OMIT_INTEGRITY_CHECK",
  580. #endif
  581. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  582. "OMIT_LIKE_OPTIMIZATION",
  583. #endif
  584. #if SQLITE_OMIT_LOAD_EXTENSION
  585. "OMIT_LOAD_EXTENSION",
  586. #endif
  587. #if SQLITE_OMIT_LOCALTIME
  588. "OMIT_LOCALTIME",
  589. #endif
  590. #if SQLITE_OMIT_LOOKASIDE
  591. "OMIT_LOOKASIDE",
  592. #endif
  593. #if SQLITE_OMIT_MEMORYDB
  594. "OMIT_MEMORYDB",
  595. #endif
  596. #if SQLITE_OMIT_OR_OPTIMIZATION
  597. "OMIT_OR_OPTIMIZATION",
  598. #endif
  599. #if SQLITE_OMIT_PAGER_PRAGMAS
  600. "OMIT_PAGER_PRAGMAS",
  601. #endif
  602. #if SQLITE_OMIT_PARSER_TRACE
  603. "OMIT_PARSER_TRACE",
  604. #endif
  605. #if SQLITE_OMIT_POPEN
  606. "OMIT_POPEN",
  607. #endif
  608. #if SQLITE_OMIT_PRAGMA
  609. "OMIT_PRAGMA",
  610. #endif
  611. #if SQLITE_OMIT_PROGRESS_CALLBACK
  612. "OMIT_PROGRESS_CALLBACK",
  613. #endif
  614. #if SQLITE_OMIT_QUICKBALANCE
  615. "OMIT_QUICKBALANCE",
  616. #endif
  617. #if SQLITE_OMIT_REINDEX
  618. "OMIT_REINDEX",
  619. #endif
  620. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  621. "OMIT_SCHEMA_PRAGMAS",
  622. #endif
  623. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  624. "OMIT_SCHEMA_VERSION_PRAGMAS",
  625. #endif
  626. #if SQLITE_OMIT_SHARED_CACHE
  627. "OMIT_SHARED_CACHE",
  628. #endif
  629. #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  630. "OMIT_SHUTDOWN_DIRECTORIES",
  631. #endif
  632. #if SQLITE_OMIT_SUBQUERY
  633. "OMIT_SUBQUERY",
  634. #endif
  635. #if SQLITE_OMIT_TCL_VARIABLE
  636. "OMIT_TCL_VARIABLE",
  637. #endif
  638. #if SQLITE_OMIT_TEMPDB
  639. "OMIT_TEMPDB",
  640. #endif
  641. #if SQLITE_OMIT_TEST_CONTROL
  642. "OMIT_TEST_CONTROL",
  643. #endif
  644. #if SQLITE_OMIT_TRACE
  645. "OMIT_TRACE",
  646. #endif
  647. #if SQLITE_OMIT_TRIGGER
  648. "OMIT_TRIGGER",
  649. #endif
  650. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  651. "OMIT_TRUNCATE_OPTIMIZATION",
  652. #endif
  653. #if SQLITE_OMIT_UTF16
  654. "OMIT_UTF16",
  655. #endif
  656. #if SQLITE_OMIT_VACUUM
  657. "OMIT_VACUUM",
  658. #endif
  659. #if SQLITE_OMIT_VIEW
  660. "OMIT_VIEW",
  661. #endif
  662. #if SQLITE_OMIT_VIRTUALTABLE
  663. "OMIT_VIRTUALTABLE",
  664. #endif
  665. #if SQLITE_OMIT_WAL
  666. "OMIT_WAL",
  667. #endif
  668. #if SQLITE_OMIT_WSD
  669. "OMIT_WSD",
  670. #endif
  671. #if SQLITE_OMIT_XFER_OPT
  672. "OMIT_XFER_OPT",
  673. #endif
  674. #if SQLITE_PCACHE_SEPARATE_HEADER
  675. "PCACHE_SEPARATE_HEADER",
  676. #endif
  677. #if SQLITE_PERFORMANCE_TRACE
  678. "PERFORMANCE_TRACE",
  679. #endif
  680. #if SQLITE_POWERSAFE_OVERWRITE
  681. "POWERSAFE_OVERWRITE",
  682. #endif
  683. #if SQLITE_PREFER_PROXY_LOCKING
  684. "PREFER_PROXY_LOCKING",
  685. #endif
  686. #if SQLITE_PROXY_DEBUG
  687. "PROXY_DEBUG",
  688. #endif
  689. #if SQLITE_REVERSE_UNORDERED_SELECTS
  690. "REVERSE_UNORDERED_SELECTS",
  691. #endif
  692. #if SQLITE_RTREE_INT_ONLY
  693. "RTREE_INT_ONLY",
  694. #endif
  695. #if SQLITE_SECURE_DELETE
  696. "SECURE_DELETE",
  697. #endif
  698. #if SQLITE_SMALL_STACK
  699. "SMALL_STACK",
  700. #endif
  701. #ifdef SQLITE_SORTER_PMASZ
  702. "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
  703. #endif
  704. #if SQLITE_SOUNDEX
  705. "SOUNDEX",
  706. #endif
  707. #ifdef SQLITE_STAT4_SAMPLES
  708. "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
  709. #endif
  710. #ifdef SQLITE_STMTJRNL_SPILL
  711. "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
  712. #endif
  713. #if SQLITE_SUBSTR_COMPATIBILITY
  714. "SUBSTR_COMPATIBILITY",
  715. #endif
  716. #if SQLITE_SYSTEM_MALLOC
  717. "SYSTEM_MALLOC",
  718. #endif
  719. #if SQLITE_TCL
  720. "TCL",
  721. #endif
  722. #ifdef SQLITE_TEMP_STORE
  723. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  724. #endif
  725. #if SQLITE_TEST
  726. "TEST",
  727. #endif
  728. #if defined(SQLITE_THREADSAFE)
  729. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  730. #elif defined(THREADSAFE)
  731. "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
  732. #else
  733. "THREADSAFE=1",
  734. #endif
  735. #if SQLITE_UNLINK_AFTER_CLOSE
  736. "UNLINK_AFTER_CLOSE",
  737. #endif
  738. #if SQLITE_UNTESTABLE
  739. "UNTESTABLE",
  740. #endif
  741. #if SQLITE_USER_AUTHENTICATION
  742. "USER_AUTHENTICATION",
  743. #endif
  744. #if SQLITE_USE_ALLOCA
  745. "USE_ALLOCA",
  746. #endif
  747. #if SQLITE_USE_FCNTL_TRACE
  748. "USE_FCNTL_TRACE",
  749. #endif
  750. #if SQLITE_USE_URI
  751. "USE_URI",
  752. #endif
  753. #if SQLITE_VDBE_COVERAGE
  754. "VDBE_COVERAGE",
  755. #endif
  756. #if SQLITE_WIN32_MALLOC
  757. "WIN32_MALLOC",
  758. #endif
  759. #if SQLITE_ZERO_MALLOC
  760. "ZERO_MALLOC",
  761. #endif
  762. /*
  763. ** END CODE GENERATED BY tool/mkctime.tcl
  764. */
  765. };
  766. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
  767. *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
  768. return (const char**)sqlite3azCompileOpt;
  769. }
  770. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  771. /************** End of ctime.c ***********************************************/
  772. /************** Begin file sqliteInt.h ***************************************/
  773. /*
  774. ** 2001 September 15
  775. **
  776. ** The author disclaims copyright to this source code. In place of
  777. ** a legal notice, here is a blessing:
  778. **
  779. ** May you do good and not evil.
  780. ** May you find forgiveness for yourself and forgive others.
  781. ** May you share freely, never taking more than you give.
  782. **
  783. *************************************************************************
  784. ** Internal interface definitions for SQLite.
  785. **
  786. */
  787. #ifndef SQLITEINT_H
  788. #define SQLITEINT_H
  789. /* Special Comments:
  790. **
  791. ** Some comments have special meaning to the tools that measure test
  792. ** coverage:
  793. **
  794. ** NO_TEST - The branches on this line are not
  795. ** measured by branch coverage. This is
  796. ** used on lines of code that actually
  797. ** implement parts of coverage testing.
  798. **
  799. ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
  800. ** and the correct answer is still obtained,
  801. ** though perhaps more slowly.
  802. **
  803. ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
  804. ** and the correct answer is still obtained,
  805. ** though perhaps more slowly.
  806. **
  807. ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
  808. ** that would be harmless and undetectable
  809. ** if it did occur.
  810. **
  811. ** In all cases, the special comment must be enclosed in the usual
  812. ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
  813. ** asterisks and the comment text.
  814. */
  815. /*
  816. ** Make sure the Tcl calling convention macro is defined. This macro is
  817. ** only used by test code and Tcl integration code.
  818. */
  819. #ifndef SQLITE_TCLAPI
  820. # define SQLITE_TCLAPI
  821. #endif
  822. /*
  823. ** Include the header file used to customize the compiler options for MSVC.
  824. ** This should be done first so that it can successfully prevent spurious
  825. ** compiler warnings due to subsequent content in this file and other files
  826. ** that are included by this file.
  827. */
  828. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  829. /************** Begin file msvc.h ********************************************/
  830. /*
  831. ** 2015 January 12
  832. **
  833. ** The author disclaims copyright to this source code. In place of
  834. ** a legal notice, here is a blessing:
  835. **
  836. ** May you do good and not evil.
  837. ** May you find forgiveness for yourself and forgive others.
  838. ** May you share freely, never taking more than you give.
  839. **
  840. ******************************************************************************
  841. **
  842. ** This file contains code that is specific to MSVC.
  843. */
  844. #ifndef SQLITE_MSVC_H
  845. #define SQLITE_MSVC_H
  846. #if defined(_MSC_VER)
  847. #pragma warning(disable : 4054)
  848. #pragma warning(disable : 4055)
  849. #pragma warning(disable : 4100)
  850. #pragma warning(disable : 4127)
  851. #pragma warning(disable : 4130)
  852. #pragma warning(disable : 4152)
  853. #pragma warning(disable : 4189)
  854. #pragma warning(disable : 4206)
  855. #pragma warning(disable : 4210)
  856. #pragma warning(disable : 4232)
  857. #pragma warning(disable : 4244)
  858. #pragma warning(disable : 4305)
  859. #pragma warning(disable : 4306)
  860. #pragma warning(disable : 4702)
  861. #pragma warning(disable : 4706)
  862. #endif /* defined(_MSC_VER) */
  863. #endif /* SQLITE_MSVC_H */
  864. /************** End of msvc.h ************************************************/
  865. /************** Continuing where we left off in sqliteInt.h ******************/
  866. /*
  867. ** Special setup for VxWorks
  868. */
  869. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  870. /************** Begin file vxworks.h *****************************************/
  871. /*
  872. ** 2015-03-02
  873. **
  874. ** The author disclaims copyright to this source code. In place of
  875. ** a legal notice, here is a blessing:
  876. **
  877. ** May you do good and not evil.
  878. ** May you find forgiveness for yourself and forgive others.
  879. ** May you share freely, never taking more than you give.
  880. **
  881. ******************************************************************************
  882. **
  883. ** This file contains code that is specific to Wind River's VxWorks
  884. */
  885. #if defined(__RTP__) || defined(_WRS_KERNEL)
  886. /* This is VxWorks. Set up things specially for that OS
  887. */
  888. #include <vxWorks.h>
  889. #include <pthread.h> /* amalgamator: dontcache */
  890. #define OS_VXWORKS 1
  891. #define SQLITE_OS_OTHER 0
  892. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  893. #define SQLITE_OMIT_LOAD_EXTENSION 1
  894. #define SQLITE_ENABLE_LOCKING_STYLE 0
  895. #define HAVE_UTIME 1
  896. #else
  897. /* This is not VxWorks. */
  898. #define OS_VXWORKS 0
  899. #define HAVE_FCHOWN 1
  900. #define HAVE_READLINK 1
  901. #define HAVE_LSTAT 1
  902. #endif /* defined(_WRS_KERNEL) */
  903. /************** End of vxworks.h *********************************************/
  904. /************** Continuing where we left off in sqliteInt.h ******************/
  905. /*
  906. ** These #defines should enable >2GB file support on POSIX if the
  907. ** underlying operating system supports it. If the OS lacks
  908. ** large file support, or if the OS is windows, these should be no-ops.
  909. **
  910. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  911. ** system #includes. Hence, this block of code must be the very first
  912. ** code in all source files.
  913. **
  914. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  915. ** on the compiler command line. This is necessary if you are compiling
  916. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  917. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  918. ** without this option, LFS is enable. But LFS does not exist in the kernel
  919. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  920. ** portability you should omit LFS.
  921. **
  922. ** The previous paragraph was written in 2005. (This paragraph is written
  923. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  924. ** you should probably leave LFS enabled. But some embedded platforms might
  925. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  926. **
  927. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  928. */
  929. #ifndef SQLITE_DISABLE_LFS
  930. # define _LARGE_FILE 1
  931. # ifndef _FILE_OFFSET_BITS
  932. # define _FILE_OFFSET_BITS 64
  933. # endif
  934. # define _LARGEFILE_SOURCE 1
  935. #endif
  936. /* The GCC_VERSION and MSVC_VERSION macros are used to
  937. ** conditionally include optimizations for each of these compilers. A
  938. ** value of 0 means that compiler is not being used. The
  939. ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
  940. ** optimizations, and hence set all compiler macros to 0
  941. **
  942. ** There was once also a CLANG_VERSION macro. However, we learn that the
  943. ** version numbers in clang are for "marketing" only and are inconsistent
  944. ** and unreliable. Fortunately, all versions of clang also recognize the
  945. ** gcc version numbers and have reasonable settings for gcc version numbers,
  946. ** so the GCC_VERSION macro will be set to a correct non-zero value even
  947. ** when compiling with clang.
  948. */
  949. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  950. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  951. #else
  952. # define GCC_VERSION 0
  953. #endif
  954. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  955. # define MSVC_VERSION _MSC_VER
  956. #else
  957. # define MSVC_VERSION 0
  958. #endif
  959. /* Needed for various definitions... */
  960. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  961. # define _GNU_SOURCE
  962. #endif
  963. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  964. # define _BSD_SOURCE
  965. #endif
  966. /*
  967. ** For MinGW, check to see if we can include the header file containing its
  968. ** version information, among other things. Normally, this internal MinGW
  969. ** header file would [only] be included automatically by other MinGW header
  970. ** files; however, the contained version information is now required by this
  971. ** header file to work around binary compatibility issues (see below) and
  972. ** this is the only known way to reliably obtain it. This entire #if block
  973. ** would be completely unnecessary if there was any other way of detecting
  974. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  975. ** some MinGW-specific macros). When compiling for MinGW, either the
  976. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  977. ** defined; otherwise, detection of conditions specific to MinGW will be
  978. ** disabled.
  979. */
  980. #if defined(_HAVE_MINGW_H)
  981. # include "mingw.h"
  982. #elif defined(_HAVE__MINGW_H)
  983. # include "_mingw.h"
  984. #endif
  985. /*
  986. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  987. ** define is required to maintain binary compatibility with the MSVC runtime
  988. ** library in use (e.g. for Windows XP).
  989. */
  990. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  991. defined(_WIN32) && !defined(_WIN64) && \
  992. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  993. defined(__MSVCRT__)
  994. # define _USE_32BIT_TIME_T
  995. #endif
  996. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  997. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  998. ** MinGW.
  999. */
  1000. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  1001. /************** Begin file sqlite3.h *****************************************/
  1002. /*
  1003. ** 2001-09-15
  1004. **
  1005. ** The author disclaims copyright to this source code. In place of
  1006. ** a legal notice, here is a blessing:
  1007. **
  1008. ** May you do good and not evil.
  1009. ** May you find forgiveness for yourself and forgive others.
  1010. ** May you share freely, never taking more than you give.
  1011. **
  1012. *************************************************************************
  1013. ** This header file defines the interface that the SQLite library
  1014. ** presents to client programs. If a C-function, structure, datatype,
  1015. ** or constant definition does not appear in this file, then it is
  1016. ** not a published API of SQLite, is subject to change without
  1017. ** notice, and should not be referenced by programs that use SQLite.
  1018. **
  1019. ** Some of the definitions that are in this file are marked as
  1020. ** "experimental". Experimental interfaces are normally new
  1021. ** features recently added to SQLite. We do not anticipate changes
  1022. ** to experimental interfaces but reserve the right to make minor changes
  1023. ** if experience from use "in the wild" suggest such changes are prudent.
  1024. **
  1025. ** The official C-language API documentation for SQLite is derived
  1026. ** from comments in this file. This file is the authoritative source
  1027. ** on how SQLite interfaces are supposed to operate.
  1028. **
  1029. ** The name of this file under configuration management is "sqlite.h.in".
  1030. ** The makefile makes some minor changes to this file (such as inserting
  1031. ** the version number) and changes its name to "sqlite3.h" as
  1032. ** part of the build process.
  1033. */
  1034. #ifndef SQLITE3_H
  1035. #define SQLITE3_H
  1036. #include <stdarg.h> /* Needed for the definition of va_list */
  1037. /*
  1038. ** Make sure we can call this stuff from C++.
  1039. */
  1040. #if 0
  1041. extern "C" {
  1042. #endif
  1043. /*
  1044. ** Provide the ability to override linkage features of the interface.
  1045. */
  1046. #ifndef SQLITE_EXTERN
  1047. # define SQLITE_EXTERN extern
  1048. #endif
  1049. #ifndef SQLITE_API
  1050. # define SQLITE_API
  1051. #endif
  1052. #ifndef SQLITE_CDECL
  1053. # define SQLITE_CDECL
  1054. #endif
  1055. #ifndef SQLITE_APICALL
  1056. # define SQLITE_APICALL
  1057. #endif
  1058. #ifndef SQLITE_STDCALL
  1059. # define SQLITE_STDCALL SQLITE_APICALL
  1060. #endif
  1061. #ifndef SQLITE_CALLBACK
  1062. # define SQLITE_CALLBACK
  1063. #endif
  1064. #ifndef SQLITE_SYSAPI
  1065. # define SQLITE_SYSAPI
  1066. #endif
  1067. /*
  1068. ** These no-op macros are used in front of interfaces to mark those
  1069. ** interfaces as either deprecated or experimental. New applications
  1070. ** should not use deprecated interfaces - they are supported for backwards
  1071. ** compatibility only. Application writers should be aware that
  1072. ** experimental interfaces are subject to change in point releases.
  1073. **
  1074. ** These macros used to resolve to various kinds of compiler magic that
  1075. ** would generate warning messages when they were used. But that
  1076. ** compiler magic ended up generating such a flurry of bug reports
  1077. ** that we have taken it all out and gone back to using simple
  1078. ** noop macros.
  1079. */
  1080. #define SQLITE_DEPRECATED
  1081. #define SQLITE_EXPERIMENTAL
  1082. /*
  1083. ** Ensure these symbols were not defined by some previous header file.
  1084. */
  1085. #ifdef SQLITE_VERSION
  1086. # undef SQLITE_VERSION
  1087. #endif
  1088. #ifdef SQLITE_VERSION_NUMBER
  1089. # undef SQLITE_VERSION_NUMBER
  1090. #endif
  1091. /*
  1092. ** CAPI3REF: Compile-Time Library Version Numbers
  1093. **
  1094. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  1095. ** evaluates to a string literal that is the SQLite version in the
  1096. ** format "X.Y.Z" where X is the major version number (always 3 for
  1097. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  1098. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  1099. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  1100. ** numbers used in [SQLITE_VERSION].)^
  1101. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  1102. ** be larger than the release from which it is derived. Either Y will
  1103. ** be held constant and Z will be incremented or else Y will be incremented
  1104. ** and Z will be reset to zero.
  1105. **
  1106. ** Since [version 3.6.18] ([dateof:3.6.18]),
  1107. ** SQLite source code has been stored in the
  1108. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  1109. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  1110. ** a string which identifies a particular check-in of SQLite
  1111. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  1112. ** string contains the date and time of the check-in (UTC) and a SHA1
  1113. ** or SHA3-256 hash of the entire source tree. If the source code has
  1114. ** been edited in any way since it was last checked in, then the last
  1115. ** four hexadecimal digits of the hash may be modified.
  1116. **
  1117. ** See also: [sqlite3_libversion()],
  1118. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1119. ** [sqlite_version()] and [sqlite_source_id()].
  1120. */
  1121. #define SQLITE_VERSION "3.23.1"
  1122. #define SQLITE_VERSION_NUMBER 3023001
  1123. #define SQLITE_SOURCE_ID "2018-04-10 17:39:29 4bb2294022060e61de7da5c227a69ccd846ba330e31626ebcd59a94efd148b3b"
  1124. /*
  1125. ** CAPI3REF: Run-Time Library Version Numbers
  1126. ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1127. **
  1128. ** These interfaces provide the same information as the [SQLITE_VERSION],
  1129. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  1130. ** but are associated with the library instead of the header file. ^(Cautious
  1131. ** programmers might include assert() statements in their application to
  1132. ** verify that values returned by these interfaces match the macros in
  1133. ** the header, and thus ensure that the application is
  1134. ** compiled with matching library and header files.
  1135. **
  1136. ** <blockquote><pre>
  1137. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  1138. ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
  1139. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  1140. ** </pre></blockquote>)^
  1141. **
  1142. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  1143. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  1144. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  1145. ** function is provided for use in DLLs since DLL users usually do not have
  1146. ** direct access to string constants within the DLL. ^The
  1147. ** sqlite3_libversion_number() function returns an integer equal to
  1148. ** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
  1149. ** a pointer to a string constant whose value is the same as the
  1150. ** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
  1151. ** using an edited copy of [the amalgamation], then the last four characters
  1152. ** of the hash might be different from [SQLITE_SOURCE_ID].)^
  1153. **
  1154. ** See also: [sqlite_version()] and [sqlite_source_id()].
  1155. */
  1156. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  1157. SQLITE_API const char *sqlite3_libversion(void);
  1158. SQLITE_API const char *sqlite3_sourceid(void);
  1159. SQLITE_API int sqlite3_libversion_number(void);
  1160. /*
  1161. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  1162. **
  1163. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  1164. ** indicating whether the specified option was defined at
  1165. ** compile time. ^The SQLITE_ prefix may be omitted from the
  1166. ** option name passed to sqlite3_compileoption_used().
  1167. **
  1168. ** ^The sqlite3_compileoption_get() function allows iterating
  1169. ** over the list of options that were defined at compile time by
  1170. ** returning the N-th compile time option string. ^If N is out of range,
  1171. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  1172. ** prefix is omitted from any strings returned by
  1173. ** sqlite3_compileoption_get().
  1174. **
  1175. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  1176. ** and sqlite3_compileoption_get() may be omitted by specifying the
  1177. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  1178. **
  1179. ** See also: SQL functions [sqlite_compileoption_used()] and
  1180. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  1181. */
  1182. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  1183. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  1184. SQLITE_API const char *sqlite3_compileoption_get(int N);
  1185. #endif
  1186. /*
  1187. ** CAPI3REF: Test To See If The Library Is Threadsafe
  1188. **
  1189. ** ^The sqlite3_threadsafe() function returns zero if and only if
  1190. ** SQLite was compiled with mutexing code omitted due to the
  1191. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  1192. **
  1193. ** SQLite can be compiled with or without mutexes. When
  1194. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  1195. ** are enabled and SQLite is threadsafe. When the
  1196. ** [SQLITE_THREADSAFE] macro is 0,
  1197. ** the mutexes are omitted. Without the mutexes, it is not safe
  1198. ** to use SQLite concurrently from more than one thread.
  1199. **
  1200. ** Enabling mutexes incurs a measurable performance penalty.
  1201. ** So if speed is of utmost importance, it makes sense to disable
  1202. ** the mutexes. But for maximum safety, mutexes should be enabled.
  1203. ** ^The default behavior is for mutexes to be enabled.
  1204. **
  1205. ** This interface can be used by an application to make sure that the
  1206. ** version of SQLite that it is linking against was compiled with
  1207. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  1208. **
  1209. ** This interface only reports on the compile-time mutex setting
  1210. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  1211. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  1212. ** can be fully or partially disabled using a call to [sqlite3_config()]
  1213. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  1214. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  1215. ** sqlite3_threadsafe() function shows only the compile-time setting of
  1216. ** thread safety, not any run-time changes to that setting made by
  1217. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  1218. ** is unchanged by calls to sqlite3_config().)^
  1219. **
  1220. ** See the [threading mode] documentation for additional information.
  1221. */
  1222. SQLITE_API int sqlite3_threadsafe(void);
  1223. /*
  1224. ** CAPI3REF: Database Connection Handle
  1225. ** KEYWORDS: {database connection} {database connections}
  1226. **
  1227. ** Each open SQLite database is represented by a pointer to an instance of
  1228. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  1229. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  1230. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  1231. ** and [sqlite3_close_v2()] are its destructors. There are many other
  1232. ** interfaces (such as
  1233. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  1234. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  1235. ** sqlite3 object.
  1236. */
  1237. typedef struct sqlite3 sqlite3;
  1238. /*
  1239. ** CAPI3REF: 64-Bit Integer Types
  1240. ** KEYWORDS: sqlite_int64 sqlite_uint64
  1241. **
  1242. ** Because there is no cross-platform way to specify 64-bit integer types
  1243. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  1244. **
  1245. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  1246. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  1247. ** compatibility only.
  1248. **
  1249. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  1250. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  1251. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  1252. ** between 0 and +18446744073709551615 inclusive.
  1253. */
  1254. #ifdef SQLITE_INT64_TYPE
  1255. typedef SQLITE_INT64_TYPE sqlite_int64;
  1256. # ifdef SQLITE_UINT64_TYPE
  1257. typedef SQLITE_UINT64_TYPE sqlite_uint64;
  1258. # else
  1259. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  1260. # endif
  1261. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  1262. typedef __int64 sqlite_int64;
  1263. typedef unsigned __int64 sqlite_uint64;
  1264. #else
  1265. typedef long long int sqlite_int64;
  1266. typedef unsigned long long int sqlite_uint64;
  1267. #endif
  1268. typedef sqlite_int64 sqlite3_int64;
  1269. typedef sqlite_uint64 sqlite3_uint64;
  1270. /*
  1271. ** If compiling for a processor that lacks floating point support,
  1272. ** substitute integer for floating-point.
  1273. */
  1274. #ifdef SQLITE_OMIT_FLOATING_POINT
  1275. # define double sqlite3_int64
  1276. #endif
  1277. /*
  1278. ** CAPI3REF: Closing A Database Connection
  1279. ** DESTRUCTOR: sqlite3
  1280. **
  1281. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  1282. ** for the [sqlite3] object.
  1283. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  1284. ** the [sqlite3] object is successfully destroyed and all associated
  1285. ** resources are deallocated.
  1286. **
  1287. ** ^If the database connection is associated with unfinalized prepared
  1288. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  1289. ** will leave the database connection open and return [SQLITE_BUSY].
  1290. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  1291. ** and/or unfinished sqlite3_backups, then the database connection becomes
  1292. ** an unusable "zombie" which will automatically be deallocated when the
  1293. ** last prepared statement is finalized or the last sqlite3_backup is
  1294. ** finished. The sqlite3_close_v2() interface is intended for use with
  1295. ** host languages that are garbage collected, and where the order in which
  1296. ** destructors are called is arbitrary.
  1297. **
  1298. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  1299. ** [sqlite3_blob_close | close] all [BLOB handles], and
  1300. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  1301. ** with the [sqlite3] object prior to attempting to close the object. ^If
  1302. ** sqlite3_close_v2() is called on a [database connection] that still has
  1303. ** outstanding [prepared statements], [BLOB handles], and/or
  1304. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  1305. ** of resources is deferred until all [prepared statements], [BLOB handles],
  1306. ** and [sqlite3_backup] objects are also destroyed.
  1307. **
  1308. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  1309. ** the transaction is automatically rolled back.
  1310. **
  1311. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  1312. ** must be either a NULL
  1313. ** pointer or an [sqlite3] object pointer obtained
  1314. ** from [sqlite3_open()], [sqlite3_open16()], or
  1315. ** [sqlite3_open_v2()], and not previously closed.
  1316. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  1317. ** argument is a harmless no-op.
  1318. */
  1319. SQLITE_API int sqlite3_close(sqlite3*);
  1320. SQLITE_API int sqlite3_close_v2(sqlite3*);
  1321. /*
  1322. ** The type for a callback function.
  1323. ** This is legacy and deprecated. It is included for historical
  1324. ** compatibility and is not documented.
  1325. */
  1326. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  1327. /*
  1328. ** CAPI3REF: One-Step Query Execution Interface
  1329. ** METHOD: sqlite3
  1330. **
  1331. ** The sqlite3_exec() interface is a convenience wrapper around
  1332. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  1333. ** that allows an application to run multiple statements of SQL
  1334. ** without having to use a lot of C code.
  1335. **
  1336. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  1337. ** semicolon-separate SQL statements passed into its 2nd argument,
  1338. ** in the context of the [database connection] passed in as its 1st
  1339. ** argument. ^If the callback function of the 3rd argument to
  1340. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  1341. ** coming out of the evaluated SQL statements. ^The 4th argument to
  1342. ** sqlite3_exec() is relayed through to the 1st argument of each
  1343. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  1344. ** is NULL, then no callback is ever invoked and result rows are
  1345. ** ignored.
  1346. **
  1347. ** ^If an error occurs while evaluating the SQL statements passed into
  1348. ** sqlite3_exec(), then execution of the current statement stops and
  1349. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  1350. ** is not NULL then any error message is written into memory obtained
  1351. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  1352. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  1353. ** on error message strings returned through the 5th parameter of
  1354. ** sqlite3_exec() after the error message string is no longer needed.
  1355. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  1356. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  1357. ** NULL before returning.
  1358. **
  1359. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  1360. ** routine returns SQLITE_ABORT without invoking the callback again and
  1361. ** without running any subsequent SQL statements.
  1362. **
  1363. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  1364. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  1365. ** callback is an array of pointers to strings obtained as if from
  1366. ** [sqlite3_column_text()], one for each column. ^If an element of a
  1367. ** result row is NULL then the corresponding string pointer for the
  1368. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  1369. ** sqlite3_exec() callback is an array of pointers to strings where each
  1370. ** entry represents the name of corresponding result column as obtained
  1371. ** from [sqlite3_column_name()].
  1372. **
  1373. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  1374. ** to an empty string, or a pointer that contains only whitespace and/or
  1375. ** SQL comments, then no SQL statements are evaluated and the database
  1376. ** is not changed.
  1377. **
  1378. ** Restrictions:
  1379. **
  1380. ** <ul>
  1381. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  1382. ** is a valid and open [database connection].
  1383. ** <li> The application must not close the [database connection] specified by
  1384. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  1385. ** <li> The application must not modify the SQL statement text passed into
  1386. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  1387. ** </ul>
  1388. */
  1389. SQLITE_API int sqlite3_exec(
  1390. sqlite3*, /* An open database */
  1391. const char *sql, /* SQL to be evaluated */
  1392. int (*callback)(void*,int,char**,char**), /* Callback function */
  1393. void *, /* 1st argument to callback */
  1394. char **errmsg /* Error msg written here */
  1395. );
  1396. /*
  1397. ** CAPI3REF: Result Codes
  1398. ** KEYWORDS: {result code definitions}
  1399. **
  1400. ** Many SQLite functions return an integer result code from the set shown
  1401. ** here in order to indicate success or failure.
  1402. **
  1403. ** New error codes may be added in future versions of SQLite.
  1404. **
  1405. ** See also: [extended result code definitions]
  1406. */
  1407. #define SQLITE_OK 0 /* Successful result */
  1408. /* beginning-of-error-codes */
  1409. #define SQLITE_ERROR 1 /* Generic error */
  1410. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  1411. #define SQLITE_PERM 3 /* Access permission denied */
  1412. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  1413. #define SQLITE_BUSY 5 /* The database file is locked */
  1414. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  1415. #define SQLITE_NOMEM 7 /* A malloc() failed */
  1416. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  1417. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  1418. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  1419. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  1420. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  1421. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  1422. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  1423. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  1424. #define SQLITE_EMPTY 16 /* Internal use only */
  1425. #define SQLITE_SCHEMA 17 /* The database schema changed */
  1426. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  1427. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  1428. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  1429. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  1430. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  1431. #define SQLITE_AUTH 23 /* Authorization denied */
  1432. #define SQLITE_FORMAT 24 /* Not used */
  1433. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  1434. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  1435. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  1436. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  1437. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  1438. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  1439. /* end-of-error-codes */
  1440. /*
  1441. ** CAPI3REF: Extended Result Codes
  1442. ** KEYWORDS: {extended result code definitions}
  1443. **
  1444. ** In its default configuration, SQLite API routines return one of 30 integer
  1445. ** [result codes]. However, experience has shown that many of
  1446. ** these result codes are too coarse-grained. They do not provide as
  1447. ** much information about problems as programmers might like. In an effort to
  1448. ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  1449. ** and later) include
  1450. ** support for additional result codes that provide more detailed information
  1451. ** about errors. These [extended result codes] are enabled or disabled
  1452. ** on a per database connection basis using the
  1453. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  1454. ** the most recent error can be obtained using
  1455. ** [sqlite3_extended_errcode()].
  1456. */
  1457. #define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
  1458. #define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
  1459. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  1460. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  1461. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  1462. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  1463. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  1464. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  1465. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  1466. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  1467. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  1468. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  1469. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  1470. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  1471. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  1472. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  1473. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  1474. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  1475. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  1476. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  1477. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  1478. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  1479. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  1480. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  1481. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  1482. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  1483. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  1484. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  1485. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  1486. #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  1487. #define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
  1488. #define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
  1489. #define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
  1490. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  1491. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  1492. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  1493. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  1494. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  1495. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  1496. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  1497. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  1498. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  1499. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  1500. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  1501. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  1502. #define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
  1503. #define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
  1504. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  1505. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  1506. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  1507. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  1508. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  1509. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  1510. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  1511. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  1512. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  1513. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  1514. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  1515. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  1516. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  1517. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  1518. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  1519. #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
  1520. /*
  1521. ** CAPI3REF: Flags For File Open Operations
  1522. **
  1523. ** These bit values are intended for use in the
  1524. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  1525. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  1526. */
  1527. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  1528. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  1529. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  1530. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  1531. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  1532. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  1533. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  1534. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  1535. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  1536. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  1537. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  1538. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  1539. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  1540. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  1541. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  1542. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  1543. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  1544. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  1545. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  1546. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  1547. /* Reserved: 0x00F00000 */
  1548. /*
  1549. ** CAPI3REF: Device Characteristics
  1550. **
  1551. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1552. ** object returns an integer which is a vector of these
  1553. ** bit values expressing I/O characteristics of the mass storage
  1554. ** device that holds the file that the [sqlite3_io_methods]
  1555. ** refers to.
  1556. **
  1557. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1558. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1559. ** mean that writes of blocks that are nnn bytes in size and
  1560. ** are aligned to an address which is an integer multiple of
  1561. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1562. ** that when data is appended to a file, the data is appended
  1563. ** first then the size of the file is extended, never the other
  1564. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1565. ** information is written to disk in the same order as calls
  1566. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1567. ** after reboot following a crash or power loss, the only bytes in a
  1568. ** file that were written at the application level might have changed
  1569. ** and that adjacent bytes, even bytes within the same sector are
  1570. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  1571. ** flag indicates that a file cannot be deleted when open. The
  1572. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  1573. ** read-only media and cannot be changed even by processes with
  1574. ** elevated privileges.
  1575. **
  1576. ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
  1577. ** filesystem supports doing multiple write operations atomically when those
  1578. ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
  1579. ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
  1580. */
  1581. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1582. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1583. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1584. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1585. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1586. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1587. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1588. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1589. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1590. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1591. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1592. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  1593. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  1594. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  1595. #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
  1596. /*
  1597. ** CAPI3REF: File Locking Levels
  1598. **
  1599. ** SQLite uses one of these integer values as the second
  1600. ** argument to calls it makes to the xLock() and xUnlock() methods
  1601. ** of an [sqlite3_io_methods] object.
  1602. */
  1603. #define SQLITE_LOCK_NONE 0
  1604. #define SQLITE_LOCK_SHARED 1
  1605. #define SQLITE_LOCK_RESERVED 2
  1606. #define SQLITE_LOCK_PENDING 3
  1607. #define SQLITE_LOCK_EXCLUSIVE 4
  1608. /*
  1609. ** CAPI3REF: Synchronization Type Flags
  1610. **
  1611. ** When SQLite invokes the xSync() method of an
  1612. ** [sqlite3_io_methods] object it uses a combination of
  1613. ** these integer values as the second argument.
  1614. **
  1615. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1616. ** sync operation only needs to flush data to mass storage. Inode
  1617. ** information need not be flushed. If the lower four bits of the flag
  1618. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1619. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1620. ** to use Mac OS X style fullsync instead of fsync().
  1621. **
  1622. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1623. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1624. ** settings. The [synchronous pragma] determines when calls to the
  1625. ** xSync VFS method occur and applies uniformly across all platforms.
  1626. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1627. ** energetic or rigorous or forceful the sync operations are and
  1628. ** only make a difference on Mac OSX for the default SQLite code.
  1629. ** (Third-party VFS implementations might also make the distinction
  1630. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1631. ** operating systems natively supported by SQLite, only Mac OSX
  1632. ** cares about the difference.)
  1633. */
  1634. #define SQLITE_SYNC_NORMAL 0x00002
  1635. #define SQLITE_SYNC_FULL 0x00003
  1636. #define SQLITE_SYNC_DATAONLY 0x00010
  1637. /*
  1638. ** CAPI3REF: OS Interface Open File Handle
  1639. **
  1640. ** An [sqlite3_file] object represents an open file in the
  1641. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1642. ** implementations will
  1643. ** want to subclass this object by appending additional fields
  1644. ** for their own use. The pMethods entry is a pointer to an
  1645. ** [sqlite3_io_methods] object that defines methods for performing
  1646. ** I/O operations on the open file.
  1647. */
  1648. typedef struct sqlite3_file sqlite3_file;
  1649. struct sqlite3_file {
  1650. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1651. };
  1652. /*
  1653. ** CAPI3REF: OS Interface File Virtual Methods Object
  1654. **
  1655. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1656. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1657. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1658. ** This object defines the methods used to perform various operations
  1659. ** against the open file represented by the [sqlite3_file] object.
  1660. **
  1661. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  1662. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1663. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  1664. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1665. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1666. ** to NULL.
  1667. **
  1668. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1669. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1670. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1671. ** flag may be ORed in to indicate that only the data of the file
  1672. ** and not its inode needs to be synced.
  1673. **
  1674. ** The integer values to xLock() and xUnlock() are one of
  1675. ** <ul>
  1676. ** <li> [SQLITE_LOCK_NONE],
  1677. ** <li> [SQLITE_LOCK_SHARED],
  1678. ** <li> [SQLITE_LOCK_RESERVED],
  1679. ** <li> [SQLITE_LOCK_PENDING], or
  1680. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1681. ** </ul>
  1682. ** xLock() increases the lock. xUnlock() decreases the lock.
  1683. ** The xCheckReservedLock() method checks whether any database connection,
  1684. ** either in this process or in some other process, is holding a RESERVED,
  1685. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1686. ** if such a lock exists and false otherwise.
  1687. **
  1688. ** The xFileControl() method is a generic interface that allows custom
  1689. ** VFS implementations to directly control an open file using the
  1690. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1691. ** integer opcode. The third argument is a generic pointer intended to
  1692. ** point to a structure that may contain arguments or space in which to
  1693. ** write return values. Potential uses for xFileControl() might be
  1694. ** functions to enable blocking locks with timeouts, to change the
  1695. ** locking strategy (for example to use dot-file locks), to inquire
  1696. ** about the status of a lock, or to break stale locks. The SQLite
  1697. ** core reserves all opcodes less than 100 for its own use.
  1698. ** A [file control opcodes | list of opcodes] less than 100 is available.
  1699. ** Applications that define a custom xFileControl method should use opcodes
  1700. ** greater than 100 to avoid conflicts. VFS implementations should
  1701. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1702. ** recognize.
  1703. **
  1704. ** The xSectorSize() method returns the sector size of the
  1705. ** device that underlies the file. The sector size is the
  1706. ** minimum write that can be performed without disturbing
  1707. ** other bytes in the file. The xDeviceCharacteristics()
  1708. ** method returns a bit vector describing behaviors of the
  1709. ** underlying device:
  1710. **
  1711. ** <ul>
  1712. ** <li> [SQLITE_IOCAP_ATOMIC]
  1713. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1714. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1715. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1716. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1717. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1718. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1719. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1720. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1721. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1722. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1723. ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  1724. ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  1725. ** <li> [SQLITE_IOCAP_IMMUTABLE]
  1726. ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
  1727. ** </ul>
  1728. **
  1729. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1730. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1731. ** mean that writes of blocks that are nnn bytes in size and
  1732. ** are aligned to an address which is an integer multiple of
  1733. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1734. ** that when data is appended to a file, the data is appended
  1735. ** first then the size of the file is extended, never the other
  1736. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1737. ** information is written to disk in the same order as calls
  1738. ** to xWrite().
  1739. **
  1740. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1741. ** in the unread portions of the buffer with zeros. A VFS that
  1742. ** fails to zero-fill short reads might seem to work. However,
  1743. ** failure to zero-fill short reads will eventually lead to
  1744. ** database corruption.
  1745. */
  1746. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1747. struct sqlite3_io_methods {
  1748. int iVersion;
  1749. int (*xClose)(sqlite3_file*);
  1750. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1751. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1752. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1753. int (*xSync)(sqlite3_file*, int flags);
  1754. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1755. int (*xLock)(sqlite3_file*, int);
  1756. int (*xUnlock)(sqlite3_file*, int);
  1757. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1758. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1759. int (*xSectorSize)(sqlite3_file*);
  1760. int (*xDeviceCharacteristics)(sqlite3_file*);
  1761. /* Methods above are valid for version 1 */
  1762. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1763. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1764. void (*xShmBarrier)(sqlite3_file*);
  1765. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1766. /* Methods above are valid for version 2 */
  1767. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1768. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1769. /* Methods above are valid for version 3 */
  1770. /* Additional methods may be added in future releases */
  1771. };
  1772. /*
  1773. ** CAPI3REF: Standard File Control Opcodes
  1774. ** KEYWORDS: {file control opcodes} {file control opcode}
  1775. **
  1776. ** These integer constants are opcodes for the xFileControl method
  1777. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1778. ** interface.
  1779. **
  1780. ** <ul>
  1781. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1782. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1783. ** opcode causes the xFileControl method to write the current state of
  1784. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1785. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1786. ** into an integer that the pArg argument points to. This capability
  1787. ** is used during testing and is only available when the SQLITE_TEST
  1788. ** compile-time option is used.
  1789. **
  1790. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1791. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1792. ** layer a hint of how large the database file will grow to be during the
  1793. ** current transaction. This hint is not guaranteed to be accurate but it
  1794. ** is often close. The underlying VFS might choose to preallocate database
  1795. ** file space based on this hint in order to help writes to the database
  1796. ** file run faster.
  1797. **
  1798. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1799. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1800. ** extends and truncates the database file in chunks of a size specified
  1801. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1802. ** point to an integer (type int) containing the new chunk-size to use
  1803. ** for the nominated database. Allocating database file space in large
  1804. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1805. ** improve performance on some systems.
  1806. **
  1807. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1808. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1809. ** to the [sqlite3_file] object associated with a particular database
  1810. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1811. **
  1812. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1813. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1814. ** to the [sqlite3_file] object associated with the journal file (either
  1815. ** the [rollback journal] or the [write-ahead log]) for a particular database
  1816. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  1817. **
  1818. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1819. ** No longer in use.
  1820. **
  1821. ** <li>[[SQLITE_FCNTL_SYNC]]
  1822. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1823. ** sent to the VFS immediately before the xSync method is invoked on a
  1824. ** database file descriptor. Or, if the xSync method is not invoked
  1825. ** because the user has configured SQLite with
  1826. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  1827. ** of the xSync method. In most cases, the pointer argument passed with
  1828. ** this file-control is NULL. However, if the database file is being synced
  1829. ** as part of a multi-database commit, the argument points to a nul-terminated
  1830. ** string containing the transactions master-journal file name. VFSes that
  1831. ** do not need this signal should silently ignore this opcode. Applications
  1832. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  1833. ** disrupt the operation of the specialized VFSes that do require it.
  1834. **
  1835. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1836. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1837. ** and sent to the VFS after a transaction has been committed immediately
  1838. ** but before the database is unlocked. VFSes that do not need this signal
  1839. ** should silently ignore this opcode. Applications should not call
  1840. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1841. ** operation of the specialized VFSes that do require it.
  1842. **
  1843. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1844. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1845. ** retry counts and intervals for certain disk I/O operations for the
  1846. ** windows [VFS] in order to provide robustness in the presence of
  1847. ** anti-virus programs. By default, the windows VFS will retry file read,
  1848. ** file write, and file delete operations up to 10 times, with a delay
  1849. ** of 25 milliseconds before the first retry and with the delay increasing
  1850. ** by an additional 25 milliseconds with each subsequent retry. This
  1851. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1852. ** to be adjusted. The values are changed for all database connections
  1853. ** within the same process. The argument is a pointer to an array of two
  1854. ** integers where the first integer is the new retry count and the second
  1855. ** integer is the delay. If either integer is negative, then the setting
  1856. ** is not changed but instead the prior value of that setting is written
  1857. ** into the array entry, allowing the current retry settings to be
  1858. ** interrogated. The zDbName parameter is ignored.
  1859. **
  1860. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1861. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1862. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1863. ** write ahead log and shared memory files used for transaction control
  1864. ** are automatically deleted when the latest connection to the database
  1865. ** closes. Setting persistent WAL mode causes those files to persist after
  1866. ** close. Persisting the files is useful when other processes that do not
  1867. ** have write permission on the directory containing the database file want
  1868. ** to read the database file, as the WAL and shared memory files must exist
  1869. ** in order for the database to be readable. The fourth parameter to
  1870. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1871. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1872. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1873. ** WAL persistence setting.
  1874. **
  1875. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1876. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1877. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1878. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1879. ** xDeviceCharacteristics methods. The fourth parameter to
  1880. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1881. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1882. ** mode. If the integer is -1, then it is overwritten with the current
  1883. ** zero-damage mode setting.
  1884. **
  1885. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1886. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1887. ** a write transaction to indicate that, unless it is rolled back for some
  1888. ** reason, the entire database file will be overwritten by the current
  1889. ** transaction. This is used by VACUUM operations.
  1890. **
  1891. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1892. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1893. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1894. ** final bottom-level VFS are written into memory obtained from
  1895. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1896. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1897. ** The caller is responsible for freeing the memory when done. As with
  1898. ** all file-control actions, there is no guarantee that this will actually
  1899. ** do anything. Callers should initialize the char* variable to a NULL
  1900. ** pointer in case this file-control is not implemented. This file-control
  1901. ** is intended for diagnostic use only.
  1902. **
  1903. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1904. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1905. ** [VFSes] currently in use. ^(The argument X in
  1906. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1907. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1908. ** to a pointer to the top-level VFS.)^
  1909. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1910. ** upper-most shim only.
  1911. **
  1912. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1913. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1914. ** file control is sent to the open [sqlite3_file] object corresponding
  1915. ** to the database file to which the pragma statement refers. ^The argument
  1916. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1917. ** pointers to strings (char**) in which the second element of the array
  1918. ** is the name of the pragma and the third element is the argument to the
  1919. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1920. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1921. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1922. ** or the equivalent and that string will become the result of the pragma or
  1923. ** the error message if the pragma fails. ^If the
  1924. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1925. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1926. ** file control returns [SQLITE_OK], then the parser assumes that the
  1927. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1928. ** prepared statement if result string is NULL, or that returns a copy
  1929. ** of the result string if the string is non-NULL.
  1930. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1931. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1932. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1933. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1934. ** file control occurs at the beginning of pragma statement analysis and so
  1935. ** it is able to override built-in [PRAGMA] statements.
  1936. **
  1937. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1938. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1939. ** file-control may be invoked by SQLite on the database file handle
  1940. ** shortly after it is opened in order to provide a custom VFS with access
  1941. ** to the connections busy-handler callback. The argument is of type (void **)
  1942. ** - an array of two (void *) values. The first (void *) actually points
  1943. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1944. ** busy-handler, this function should be invoked with the second (void *) in
  1945. ** the array as the only argument. If it returns non-zero, then the operation
  1946. ** should be retried. If it returns zero, the custom VFS should abandon the
  1947. ** current operation.
  1948. **
  1949. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1950. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1951. ** to have SQLite generate a
  1952. ** temporary filename using the same algorithm that is followed to generate
  1953. ** temporary filenames for TEMP tables and other internal uses. The
  1954. ** argument should be a char** which will be filled with the filename
  1955. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1956. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1957. **
  1958. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1959. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1960. ** maximum number of bytes that will be used for memory-mapped I/O.
  1961. ** The argument is a pointer to a value of type sqlite3_int64 that
  1962. ** is an advisory maximum number of bytes in the file to memory map. The
  1963. ** pointer is overwritten with the old value. The limit is not changed if
  1964. ** the value originally pointed to is negative, and so the current limit
  1965. ** can be queried by passing in a pointer to a negative number. This
  1966. ** file-control is used internally to implement [PRAGMA mmap_size].
  1967. **
  1968. ** <li>[[SQLITE_FCNTL_TRACE]]
  1969. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1970. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1971. ** This file control is used by some VFS activity tracing [shims].
  1972. ** The argument is a zero-terminated string. Higher layers in the
  1973. ** SQLite stack may generate instances of this file control if
  1974. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1975. **
  1976. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1977. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1978. ** pointer to an integer and it writes a boolean into that integer depending
  1979. ** on whether or not the file has been renamed, moved, or deleted since it
  1980. ** was first opened.
  1981. **
  1982. ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  1983. ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  1984. ** underlying native file handle associated with a file handle. This file
  1985. ** control interprets its argument as a pointer to a native file handle and
  1986. ** writes the resulting value there.
  1987. **
  1988. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1989. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1990. ** opcode causes the xFileControl method to swap the file handle with the one
  1991. ** pointed to by the pArg argument. This capability is used during testing
  1992. ** and only needs to be supported when SQLITE_TEST is defined.
  1993. **
  1994. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  1995. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  1996. ** be advantageous to block on the next WAL lock if the lock is not immediately
  1997. ** available. The WAL subsystem issues this signal during rare
  1998. ** circumstances in order to fix a problem with priority inversion.
  1999. ** Applications should <em>not</em> use this file-control.
  2000. **
  2001. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  2002. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  2003. ** VFS should return SQLITE_NOTFOUND for this opcode.
  2004. **
  2005. ** <li>[[SQLITE_FCNTL_RBU]]
  2006. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  2007. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  2008. ** this opcode.
  2009. **
  2010. ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
  2011. ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
  2012. ** the file descriptor is placed in "batch write mode", which
  2013. ** means all subsequent write operations will be deferred and done
  2014. ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
  2015. ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
  2016. ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
  2017. ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
  2018. ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
  2019. ** no VFS interface calls on the same [sqlite3_file] file descriptor
  2020. ** except for calls to the xWrite method and the xFileControl method
  2021. ** with [SQLITE_FCNTL_SIZE_HINT].
  2022. **
  2023. ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
  2024. ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
  2025. ** operations since the previous successful call to
  2026. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
  2027. ** This file control returns [SQLITE_OK] if and only if the writes were
  2028. ** all performed successfully and have been committed to persistent storage.
  2029. ** ^Regardless of whether or not it is successful, this file control takes
  2030. ** the file descriptor out of batch write mode so that all subsequent
  2031. ** write operations are independent.
  2032. ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
  2033. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2034. **
  2035. ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
  2036. ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
  2037. ** operations since the previous successful call to
  2038. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
  2039. ** ^This file control takes the file descriptor out of batch write mode
  2040. ** so that all subsequent write operations are independent.
  2041. ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
  2042. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2043. **
  2044. ** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
  2045. ** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode causes attempts to obtain
  2046. ** a file lock using the xLock or xShmLock methods of the VFS to wait
  2047. ** for up to M milliseconds before failing, where M is the single
  2048. ** unsigned integer parameter.
  2049. ** </ul>
  2050. */
  2051. #define SQLITE_FCNTL_LOCKSTATE 1
  2052. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  2053. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  2054. #define SQLITE_FCNTL_LAST_ERRNO 4
  2055. #define SQLITE_FCNTL_SIZE_HINT 5
  2056. #define SQLITE_FCNTL_CHUNK_SIZE 6
  2057. #define SQLITE_FCNTL_FILE_POINTER 7
  2058. #define SQLITE_FCNTL_SYNC_OMITTED 8
  2059. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  2060. #define SQLITE_FCNTL_PERSIST_WAL 10
  2061. #define SQLITE_FCNTL_OVERWRITE 11
  2062. #define SQLITE_FCNTL_VFSNAME 12
  2063. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  2064. #define SQLITE_FCNTL_PRAGMA 14
  2065. #define SQLITE_FCNTL_BUSYHANDLER 15
  2066. #define SQLITE_FCNTL_TEMPFILENAME 16
  2067. #define SQLITE_FCNTL_MMAP_SIZE 18
  2068. #define SQLITE_FCNTL_TRACE 19
  2069. #define SQLITE_FCNTL_HAS_MOVED 20
  2070. #define SQLITE_FCNTL_SYNC 21
  2071. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  2072. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  2073. #define SQLITE_FCNTL_WAL_BLOCK 24
  2074. #define SQLITE_FCNTL_ZIPVFS 25
  2075. #define SQLITE_FCNTL_RBU 26
  2076. #define SQLITE_FCNTL_VFS_POINTER 27
  2077. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  2078. #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
  2079. #define SQLITE_FCNTL_PDB 30
  2080. #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
  2081. #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
  2082. #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
  2083. #define SQLITE_FCNTL_LOCK_TIMEOUT 34
  2084. /* deprecated names */
  2085. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  2086. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  2087. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  2088. /*
  2089. ** CAPI3REF: Mutex Handle
  2090. **
  2091. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  2092. ** abstract type for a mutex object. The SQLite core never looks
  2093. ** at the internal representation of an [sqlite3_mutex]. It only
  2094. ** deals with pointers to the [sqlite3_mutex] object.
  2095. **
  2096. ** Mutexes are created using [sqlite3_mutex_alloc()].
  2097. */
  2098. typedef struct sqlite3_mutex sqlite3_mutex;
  2099. /*
  2100. ** CAPI3REF: Loadable Extension Thunk
  2101. **
  2102. ** A pointer to the opaque sqlite3_api_routines structure is passed as
  2103. ** the third parameter to entry points of [loadable extensions]. This
  2104. ** structure must be typedefed in order to work around compiler warnings
  2105. ** on some platforms.
  2106. */
  2107. typedef struct sqlite3_api_routines sqlite3_api_routines;
  2108. /*
  2109. ** CAPI3REF: OS Interface Object
  2110. **
  2111. ** An instance of the sqlite3_vfs object defines the interface between
  2112. ** the SQLite core and the underlying operating system. The "vfs"
  2113. ** in the name of the object stands for "virtual file system". See
  2114. ** the [VFS | VFS documentation] for further information.
  2115. **
  2116. ** The VFS interface is sometimes extended by adding new methods onto
  2117. ** the end. Each time such an extension occurs, the iVersion field
  2118. ** is incremented. The iVersion value started out as 1 in
  2119. ** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
  2120. ** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
  2121. ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
  2122. ** may be appended to the sqlite3_vfs object and the iVersion value
  2123. ** may increase again in future versions of SQLite.
  2124. ** Note that the structure
  2125. ** of the sqlite3_vfs object changes in the transition from
  2126. ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
  2127. ** and yet the iVersion field was not modified.
  2128. **
  2129. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  2130. ** structure used by this VFS. mxPathname is the maximum length of
  2131. ** a pathname in this VFS.
  2132. **
  2133. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  2134. ** the pNext pointer. The [sqlite3_vfs_register()]
  2135. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  2136. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  2137. ** searches the list. Neither the application code nor the VFS
  2138. ** implementation should use the pNext pointer.
  2139. **
  2140. ** The pNext field is the only field in the sqlite3_vfs
  2141. ** structure that SQLite will ever modify. SQLite will only access
  2142. ** or modify this field while holding a particular static mutex.
  2143. ** The application should never modify anything within the sqlite3_vfs
  2144. ** object once the object has been registered.
  2145. **
  2146. ** The zName field holds the name of the VFS module. The name must
  2147. ** be unique across all VFS modules.
  2148. **
  2149. ** [[sqlite3_vfs.xOpen]]
  2150. ** ^SQLite guarantees that the zFilename parameter to xOpen
  2151. ** is either a NULL pointer or string obtained
  2152. ** from xFullPathname() with an optional suffix added.
  2153. ** ^If a suffix is added to the zFilename parameter, it will
  2154. ** consist of a single "-" character followed by no more than
  2155. ** 11 alphanumeric and/or "-" characters.
  2156. ** ^SQLite further guarantees that
  2157. ** the string will be valid and unchanged until xClose() is
  2158. ** called. Because of the previous sentence,
  2159. ** the [sqlite3_file] can safely store a pointer to the
  2160. ** filename if it needs to remember the filename for some reason.
  2161. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  2162. ** must invent its own temporary name for the file. ^Whenever the
  2163. ** xFilename parameter is NULL it will also be the case that the
  2164. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  2165. **
  2166. ** The flags argument to xOpen() includes all bits set in
  2167. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  2168. ** or [sqlite3_open16()] is used, then flags includes at least
  2169. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  2170. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  2171. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  2172. **
  2173. ** ^(SQLite will also add one of the following flags to the xOpen()
  2174. ** call, depending on the object being opened:
  2175. **
  2176. ** <ul>
  2177. ** <li> [SQLITE_OPEN_MAIN_DB]
  2178. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  2179. ** <li> [SQLITE_OPEN_TEMP_DB]
  2180. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  2181. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  2182. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  2183. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  2184. ** <li> [SQLITE_OPEN_WAL]
  2185. ** </ul>)^
  2186. **
  2187. ** The file I/O implementation can use the object type flags to
  2188. ** change the way it deals with files. For example, an application
  2189. ** that does not care about crash recovery or rollback might make
  2190. ** the open of a journal file a no-op. Writes to this journal would
  2191. ** also be no-ops, and any attempt to read the journal would return
  2192. ** SQLITE_IOERR. Or the implementation might recognize that a database
  2193. ** file will be doing page-aligned sector reads and writes in a random
  2194. ** order and set up its I/O subsystem accordingly.
  2195. **
  2196. ** SQLite might also add one of the following flags to the xOpen method:
  2197. **
  2198. ** <ul>
  2199. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  2200. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  2201. ** </ul>
  2202. **
  2203. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  2204. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  2205. ** will be set for TEMP databases and their journals, transient
  2206. ** databases, and subjournals.
  2207. **
  2208. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  2209. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  2210. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  2211. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  2212. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  2213. ** be created, and that it is an error if it already exists.
  2214. ** It is <i>not</i> used to indicate the file should be opened
  2215. ** for exclusive access.
  2216. **
  2217. ** ^At least szOsFile bytes of memory are allocated by SQLite
  2218. ** to hold the [sqlite3_file] structure passed as the third
  2219. ** argument to xOpen. The xOpen method does not have to
  2220. ** allocate the structure; it should just fill it in. Note that
  2221. ** the xOpen method must set the sqlite3_file.pMethods to either
  2222. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  2223. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  2224. ** element will be valid after xOpen returns regardless of the success
  2225. ** or failure of the xOpen call.
  2226. **
  2227. ** [[sqlite3_vfs.xAccess]]
  2228. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  2229. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  2230. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  2231. ** to test whether a file is at least readable. The file can be a
  2232. ** directory.
  2233. **
  2234. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  2235. ** output buffer xFullPathname. The exact size of the output buffer
  2236. ** is also passed as a parameter to both methods. If the output buffer
  2237. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  2238. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  2239. ** to prevent this by setting mxPathname to a sufficiently large value.
  2240. **
  2241. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  2242. ** interfaces are not strictly a part of the filesystem, but they are
  2243. ** included in the VFS structure for completeness.
  2244. ** The xRandomness() function attempts to return nBytes bytes
  2245. ** of good-quality randomness into zOut. The return value is
  2246. ** the actual number of bytes of randomness obtained.
  2247. ** The xSleep() method causes the calling thread to sleep for at
  2248. ** least the number of microseconds given. ^The xCurrentTime()
  2249. ** method returns a Julian Day Number for the current date and time as
  2250. ** a floating point value.
  2251. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  2252. ** Day Number multiplied by 86400000 (the number of milliseconds in
  2253. ** a 24-hour day).
  2254. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  2255. ** date and time if that method is available (if iVersion is 2 or
  2256. ** greater and the function pointer is not NULL) and will fall back
  2257. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  2258. **
  2259. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  2260. ** are not used by the SQLite core. These optional interfaces are provided
  2261. ** by some VFSes to facilitate testing of the VFS code. By overriding
  2262. ** system calls with functions under its control, a test program can
  2263. ** simulate faults and error conditions that would otherwise be difficult
  2264. ** or impossible to induce. The set of system calls that can be overridden
  2265. ** varies from one VFS to another, and from one version of the same VFS to the
  2266. ** next. Applications that use these interfaces must be prepared for any
  2267. ** or all of these interfaces to be NULL or for their behavior to change
  2268. ** from one release to the next. Applications must not attempt to access
  2269. ** any of these methods if the iVersion of the VFS is less than 3.
  2270. */
  2271. typedef struct sqlite3_vfs sqlite3_vfs;
  2272. typedef void (*sqlite3_syscall_ptr)(void);
  2273. struct sqlite3_vfs {
  2274. int iVersion; /* Structure version number (currently 3) */
  2275. int szOsFile; /* Size of subclassed sqlite3_file */
  2276. int mxPathname; /* Maximum file pathname length */
  2277. sqlite3_vfs *pNext; /* Next registered VFS */
  2278. const char *zName; /* Name of this virtual file system */
  2279. void *pAppData; /* Pointer to application-specific data */
  2280. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  2281. int flags, int *pOutFlags);
  2282. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  2283. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  2284. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  2285. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  2286. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  2287. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  2288. void (*xDlClose)(sqlite3_vfs*, void*);
  2289. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  2290. int (*xSleep)(sqlite3_vfs*, int microseconds);
  2291. int (*xCurrentTime)(sqlite3_vfs*, double*);
  2292. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  2293. /*
  2294. ** The methods above are in version 1 of the sqlite_vfs object
  2295. ** definition. Those that follow are added in version 2 or later
  2296. */
  2297. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  2298. /*
  2299. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  2300. ** Those below are for version 3 and greater.
  2301. */
  2302. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  2303. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  2304. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  2305. /*
  2306. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  2307. ** New fields may be appended in future versions. The iVersion
  2308. ** value will increment whenever this happens.
  2309. */
  2310. };
  2311. /*
  2312. ** CAPI3REF: Flags for the xAccess VFS method
  2313. **
  2314. ** These integer constants can be used as the third parameter to
  2315. ** the xAccess method of an [sqlite3_vfs] object. They determine
  2316. ** what kind of permissions the xAccess method is looking for.
  2317. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  2318. ** simply checks whether the file exists.
  2319. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  2320. ** checks whether the named directory is both readable and writable
  2321. ** (in other words, if files can be added, removed, and renamed within
  2322. ** the directory).
  2323. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  2324. ** [temp_store_directory pragma], though this could change in a future
  2325. ** release of SQLite.
  2326. ** With SQLITE_ACCESS_READ, the xAccess method
  2327. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  2328. ** currently unused, though it might be used in a future release of
  2329. ** SQLite.
  2330. */
  2331. #define SQLITE_ACCESS_EXISTS 0
  2332. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  2333. #define SQLITE_ACCESS_READ 2 /* Unused */
  2334. /*
  2335. ** CAPI3REF: Flags for the xShmLock VFS method
  2336. **
  2337. ** These integer constants define the various locking operations
  2338. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  2339. ** following are the only legal combinations of flags to the
  2340. ** xShmLock method:
  2341. **
  2342. ** <ul>
  2343. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  2344. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  2345. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  2346. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  2347. ** </ul>
  2348. **
  2349. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  2350. ** was given on the corresponding lock.
  2351. **
  2352. ** The xShmLock method can transition between unlocked and SHARED or
  2353. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  2354. ** and EXCLUSIVE.
  2355. */
  2356. #define SQLITE_SHM_UNLOCK 1
  2357. #define SQLITE_SHM_LOCK 2
  2358. #define SQLITE_SHM_SHARED 4
  2359. #define SQLITE_SHM_EXCLUSIVE 8
  2360. /*
  2361. ** CAPI3REF: Maximum xShmLock index
  2362. **
  2363. ** The xShmLock method on [sqlite3_io_methods] may use values
  2364. ** between 0 and this upper bound as its "offset" argument.
  2365. ** The SQLite core will never attempt to acquire or release a
  2366. ** lock outside of this range
  2367. */
  2368. #define SQLITE_SHM_NLOCK 8
  2369. /*
  2370. ** CAPI3REF: Initialize The SQLite Library
  2371. **
  2372. ** ^The sqlite3_initialize() routine initializes the
  2373. ** SQLite library. ^The sqlite3_shutdown() routine
  2374. ** deallocates any resources that were allocated by sqlite3_initialize().
  2375. ** These routines are designed to aid in process initialization and
  2376. ** shutdown on embedded systems. Workstation applications using
  2377. ** SQLite normally do not need to invoke either of these routines.
  2378. **
  2379. ** A call to sqlite3_initialize() is an "effective" call if it is
  2380. ** the first time sqlite3_initialize() is invoked during the lifetime of
  2381. ** the process, or if it is the first time sqlite3_initialize() is invoked
  2382. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  2383. ** of sqlite3_initialize() does any initialization. All other calls
  2384. ** are harmless no-ops.)^
  2385. **
  2386. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  2387. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  2388. ** an effective call to sqlite3_shutdown() does any deinitialization.
  2389. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  2390. **
  2391. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  2392. ** is not. The sqlite3_shutdown() interface must only be called from a
  2393. ** single thread. All open [database connections] must be closed and all
  2394. ** other SQLite resources must be deallocated prior to invoking
  2395. ** sqlite3_shutdown().
  2396. **
  2397. ** Among other things, ^sqlite3_initialize() will invoke
  2398. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  2399. ** will invoke sqlite3_os_end().
  2400. **
  2401. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  2402. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  2403. ** the library (perhaps it is unable to allocate a needed resource such
  2404. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  2405. **
  2406. ** ^The sqlite3_initialize() routine is called internally by many other
  2407. ** SQLite interfaces so that an application usually does not need to
  2408. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  2409. ** calls sqlite3_initialize() so the SQLite library will be automatically
  2410. ** initialized when [sqlite3_open()] is called if it has not be initialized
  2411. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  2412. ** compile-time option, then the automatic calls to sqlite3_initialize()
  2413. ** are omitted and the application must call sqlite3_initialize() directly
  2414. ** prior to using any other SQLite interface. For maximum portability,
  2415. ** it is recommended that applications always invoke sqlite3_initialize()
  2416. ** directly prior to using any other SQLite interface. Future releases
  2417. ** of SQLite may require this. In other words, the behavior exhibited
  2418. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  2419. ** default behavior in some future release of SQLite.
  2420. **
  2421. ** The sqlite3_os_init() routine does operating-system specific
  2422. ** initialization of the SQLite library. The sqlite3_os_end()
  2423. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  2424. ** performed by these routines include allocation or deallocation
  2425. ** of static resources, initialization of global variables,
  2426. ** setting up a default [sqlite3_vfs] module, or setting up
  2427. ** a default configuration using [sqlite3_config()].
  2428. **
  2429. ** The application should never invoke either sqlite3_os_init()
  2430. ** or sqlite3_os_end() directly. The application should only invoke
  2431. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  2432. ** interface is called automatically by sqlite3_initialize() and
  2433. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  2434. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  2435. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  2436. ** When [custom builds | built for other platforms]
  2437. ** (using the [SQLITE_OS_OTHER=1] compile-time
  2438. ** option) the application must supply a suitable implementation for
  2439. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  2440. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  2441. ** must return [SQLITE_OK] on success and some other [error code] upon
  2442. ** failure.
  2443. */
  2444. SQLITE_API int sqlite3_initialize(void);
  2445. SQLITE_API int sqlite3_shutdown(void);
  2446. SQLITE_API int sqlite3_os_init(void);
  2447. SQLITE_API int sqlite3_os_end(void);
  2448. /*
  2449. ** CAPI3REF: Configuring The SQLite Library
  2450. **
  2451. ** The sqlite3_config() interface is used to make global configuration
  2452. ** changes to SQLite in order to tune SQLite to the specific needs of
  2453. ** the application. The default configuration is recommended for most
  2454. ** applications and so this routine is usually not necessary. It is
  2455. ** provided to support rare applications with unusual needs.
  2456. **
  2457. ** <b>The sqlite3_config() interface is not threadsafe. The application
  2458. ** must ensure that no other SQLite interfaces are invoked by other
  2459. ** threads while sqlite3_config() is running.</b>
  2460. **
  2461. ** The sqlite3_config() interface
  2462. ** may only be invoked prior to library initialization using
  2463. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  2464. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  2465. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  2466. ** Note, however, that ^sqlite3_config() can be called as part of the
  2467. ** implementation of an application-defined [sqlite3_os_init()].
  2468. **
  2469. ** The first argument to sqlite3_config() is an integer
  2470. ** [configuration option] that determines
  2471. ** what property of SQLite is to be configured. Subsequent arguments
  2472. ** vary depending on the [configuration option]
  2473. ** in the first argument.
  2474. **
  2475. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  2476. ** ^If the option is unknown or SQLite is unable to set the option
  2477. ** then this routine returns a non-zero [error code].
  2478. */
  2479. SQLITE_API int sqlite3_config(int, ...);
  2480. /*
  2481. ** CAPI3REF: Configure database connections
  2482. ** METHOD: sqlite3
  2483. **
  2484. ** The sqlite3_db_config() interface is used to make configuration
  2485. ** changes to a [database connection]. The interface is similar to
  2486. ** [sqlite3_config()] except that the changes apply to a single
  2487. ** [database connection] (specified in the first argument).
  2488. **
  2489. ** The second argument to sqlite3_db_config(D,V,...) is the
  2490. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  2491. ** that indicates what aspect of the [database connection] is being configured.
  2492. ** Subsequent arguments vary depending on the configuration verb.
  2493. **
  2494. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  2495. ** the call is considered successful.
  2496. */
  2497. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  2498. /*
  2499. ** CAPI3REF: Memory Allocation Routines
  2500. **
  2501. ** An instance of this object defines the interface between SQLite
  2502. ** and low-level memory allocation routines.
  2503. **
  2504. ** This object is used in only one place in the SQLite interface.
  2505. ** A pointer to an instance of this object is the argument to
  2506. ** [sqlite3_config()] when the configuration option is
  2507. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  2508. ** By creating an instance of this object
  2509. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  2510. ** during configuration, an application can specify an alternative
  2511. ** memory allocation subsystem for SQLite to use for all of its
  2512. ** dynamic memory needs.
  2513. **
  2514. ** Note that SQLite comes with several [built-in memory allocators]
  2515. ** that are perfectly adequate for the overwhelming majority of applications
  2516. ** and that this object is only useful to a tiny minority of applications
  2517. ** with specialized memory allocation requirements. This object is
  2518. ** also used during testing of SQLite in order to specify an alternative
  2519. ** memory allocator that simulates memory out-of-memory conditions in
  2520. ** order to verify that SQLite recovers gracefully from such
  2521. ** conditions.
  2522. **
  2523. ** The xMalloc, xRealloc, and xFree methods must work like the
  2524. ** malloc(), realloc() and free() functions from the standard C library.
  2525. ** ^SQLite guarantees that the second argument to
  2526. ** xRealloc is always a value returned by a prior call to xRoundup.
  2527. **
  2528. ** xSize should return the allocated size of a memory allocation
  2529. ** previously obtained from xMalloc or xRealloc. The allocated size
  2530. ** is always at least as big as the requested size but may be larger.
  2531. **
  2532. ** The xRoundup method returns what would be the allocated size of
  2533. ** a memory allocation given a particular requested size. Most memory
  2534. ** allocators round up memory allocations at least to the next multiple
  2535. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  2536. ** Every memory allocation request coming in through [sqlite3_malloc()]
  2537. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  2538. ** that causes the corresponding memory allocation to fail.
  2539. **
  2540. ** The xInit method initializes the memory allocator. For example,
  2541. ** it might allocate any require mutexes or initialize internal data
  2542. ** structures. The xShutdown method is invoked (indirectly) by
  2543. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  2544. ** by xInit. The pAppData pointer is used as the only parameter to
  2545. ** xInit and xShutdown.
  2546. **
  2547. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  2548. ** the xInit method, so the xInit method need not be threadsafe. The
  2549. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  2550. ** not need to be threadsafe either. For all other methods, SQLite
  2551. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  2552. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  2553. ** it is by default) and so the methods are automatically serialized.
  2554. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  2555. ** methods must be threadsafe or else make their own arrangements for
  2556. ** serialization.
  2557. **
  2558. ** SQLite will never invoke xInit() more than once without an intervening
  2559. ** call to xShutdown().
  2560. */
  2561. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  2562. struct sqlite3_mem_methods {
  2563. void *(*xMalloc)(int); /* Memory allocation function */
  2564. void (*xFree)(void*); /* Free a prior allocation */
  2565. void *(*xRealloc)(void*,int); /* Resize an allocation */
  2566. int (*xSize)(void*); /* Return the size of an allocation */
  2567. int (*xRoundup)(int); /* Round up request size to allocation size */
  2568. int (*xInit)(void*); /* Initialize the memory allocator */
  2569. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  2570. void *pAppData; /* Argument to xInit() and xShutdown() */
  2571. };
  2572. /*
  2573. ** CAPI3REF: Configuration Options
  2574. ** KEYWORDS: {configuration option}
  2575. **
  2576. ** These constants are the available integer configuration options that
  2577. ** can be passed as the first argument to the [sqlite3_config()] interface.
  2578. **
  2579. ** New configuration options may be added in future releases of SQLite.
  2580. ** Existing configuration options might be discontinued. Applications
  2581. ** should check the return code from [sqlite3_config()] to make sure that
  2582. ** the call worked. The [sqlite3_config()] interface will return a
  2583. ** non-zero [error code] if a discontinued or unsupported configuration option
  2584. ** is invoked.
  2585. **
  2586. ** <dl>
  2587. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  2588. ** <dd>There are no arguments to this option. ^This option sets the
  2589. ** [threading mode] to Single-thread. In other words, it disables
  2590. ** all mutexing and puts SQLite into a mode where it can only be used
  2591. ** by a single thread. ^If SQLite is compiled with
  2592. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2593. ** it is not possible to change the [threading mode] from its default
  2594. ** value of Single-thread and so [sqlite3_config()] will return
  2595. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  2596. ** configuration option.</dd>
  2597. **
  2598. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  2599. ** <dd>There are no arguments to this option. ^This option sets the
  2600. ** [threading mode] to Multi-thread. In other words, it disables
  2601. ** mutexing on [database connection] and [prepared statement] objects.
  2602. ** The application is responsible for serializing access to
  2603. ** [database connections] and [prepared statements]. But other mutexes
  2604. ** are enabled so that SQLite will be safe to use in a multi-threaded
  2605. ** environment as long as no two threads attempt to use the same
  2606. ** [database connection] at the same time. ^If SQLite is compiled with
  2607. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2608. ** it is not possible to set the Multi-thread [threading mode] and
  2609. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2610. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  2611. **
  2612. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  2613. ** <dd>There are no arguments to this option. ^This option sets the
  2614. ** [threading mode] to Serialized. In other words, this option enables
  2615. ** all mutexes including the recursive
  2616. ** mutexes on [database connection] and [prepared statement] objects.
  2617. ** In this mode (which is the default when SQLite is compiled with
  2618. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  2619. ** to [database connections] and [prepared statements] so that the
  2620. ** application is free to use the same [database connection] or the
  2621. ** same [prepared statement] in different threads at the same time.
  2622. ** ^If SQLite is compiled with
  2623. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2624. ** it is not possible to set the Serialized [threading mode] and
  2625. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2626. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  2627. **
  2628. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  2629. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  2630. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  2631. ** The argument specifies
  2632. ** alternative low-level memory allocation routines to be used in place of
  2633. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  2634. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  2635. ** before the [sqlite3_config()] call returns.</dd>
  2636. **
  2637. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  2638. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  2639. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  2640. ** The [sqlite3_mem_methods]
  2641. ** structure is filled with the currently defined memory allocation routines.)^
  2642. ** This option can be used to overload the default memory allocation
  2643. ** routines with a wrapper that simulations memory allocation failure or
  2644. ** tracks memory usage, for example. </dd>
  2645. **
  2646. ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
  2647. ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
  2648. ** type int, interpreted as a boolean, which if true provides a hint to
  2649. ** SQLite that it should avoid large memory allocations if possible.
  2650. ** SQLite will run faster if it is free to make large memory allocations,
  2651. ** but some application might prefer to run slower in exchange for
  2652. ** guarantees about memory fragmentation that are possible if large
  2653. ** allocations are avoided. This hint is normally off.
  2654. ** </dd>
  2655. **
  2656. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  2657. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  2658. ** interpreted as a boolean, which enables or disables the collection of
  2659. ** memory allocation statistics. ^(When memory allocation statistics are
  2660. ** disabled, the following SQLite interfaces become non-operational:
  2661. ** <ul>
  2662. ** <li> [sqlite3_memory_used()]
  2663. ** <li> [sqlite3_memory_highwater()]
  2664. ** <li> [sqlite3_soft_heap_limit64()]
  2665. ** <li> [sqlite3_status64()]
  2666. ** </ul>)^
  2667. ** ^Memory allocation statistics are enabled by default unless SQLite is
  2668. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  2669. ** allocation statistics are disabled by default.
  2670. ** </dd>
  2671. **
  2672. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  2673. ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
  2674. ** </dd>
  2675. **
  2676. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  2677. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  2678. ** that SQLite can use for the database page cache with the default page
  2679. ** cache implementation.
  2680. ** This configuration option is a no-op if an application-define page
  2681. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  2682. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  2683. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  2684. ** and the number of cache lines (N).
  2685. ** The sz argument should be the size of the largest database page
  2686. ** (a power of two between 512 and 65536) plus some extra bytes for each
  2687. ** page header. ^The number of extra bytes needed by the page header
  2688. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  2689. ** ^It is harmless, apart from the wasted memory,
  2690. ** for the sz parameter to be larger than necessary. The pMem
  2691. ** argument must be either a NULL pointer or a pointer to an 8-byte
  2692. ** aligned block of memory of at least sz*N bytes, otherwise
  2693. ** subsequent behavior is undefined.
  2694. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  2695. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  2696. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  2697. ** is exhausted.
  2698. ** ^If pMem is NULL and N is non-zero, then each database connection
  2699. ** does an initial bulk allocation for page cache memory
  2700. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  2701. ** of -1024*N bytes if N is negative, . ^If additional
  2702. ** page cache memory is needed beyond what is provided by the initial
  2703. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  2704. ** additional cache line. </dd>
  2705. **
  2706. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  2707. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  2708. ** that SQLite will use for all of its dynamic memory allocation needs
  2709. ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
  2710. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  2711. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  2712. ** [SQLITE_ERROR] if invoked otherwise.
  2713. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  2714. ** An 8-byte aligned pointer to the memory,
  2715. ** the number of bytes in the memory buffer, and the minimum allocation size.
  2716. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  2717. ** to using its default memory allocator (the system malloc() implementation),
  2718. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  2719. ** memory pointer is not NULL then the alternative memory
  2720. ** allocator is engaged to handle all of SQLites memory allocation needs.
  2721. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  2722. ** boundary or subsequent behavior of SQLite will be undefined.
  2723. ** The minimum allocation size is capped at 2**12. Reasonable values
  2724. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2725. **
  2726. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2727. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  2728. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  2729. ** The argument specifies alternative low-level mutex routines to be used
  2730. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  2731. ** the content of the [sqlite3_mutex_methods] structure before the call to
  2732. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2733. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2734. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2735. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2736. ** return [SQLITE_ERROR].</dd>
  2737. **
  2738. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2739. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  2740. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  2741. ** [sqlite3_mutex_methods]
  2742. ** structure is filled with the currently defined mutex routines.)^
  2743. ** This option can be used to overload the default mutex allocation
  2744. ** routines with a wrapper used to track mutex usage for performance
  2745. ** profiling or testing, for example. ^If SQLite is compiled with
  2746. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2747. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2748. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2749. ** return [SQLITE_ERROR].</dd>
  2750. **
  2751. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2752. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  2753. ** the default size of lookaside memory on each [database connection].
  2754. ** The first argument is the
  2755. ** size of each lookaside buffer slot and the second is the number of
  2756. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  2757. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2758. ** option to [sqlite3_db_config()] can be used to change the lookaside
  2759. ** configuration on individual connections.)^ </dd>
  2760. **
  2761. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2762. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  2763. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  2764. ** the interface to a custom page cache implementation.)^
  2765. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  2766. **
  2767. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2768. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  2769. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  2770. ** the current page cache implementation into that object.)^ </dd>
  2771. **
  2772. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2773. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  2774. ** global [error log].
  2775. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2776. ** function with a call signature of void(*)(void*,int,const char*),
  2777. ** and a pointer to void. ^If the function pointer is not NULL, it is
  2778. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  2779. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2780. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2781. ** passed through as the first parameter to the application-defined logger
  2782. ** function whenever that function is invoked. ^The second parameter to
  2783. ** the logger function is a copy of the first parameter to the corresponding
  2784. ** [sqlite3_log()] call and is intended to be a [result code] or an
  2785. ** [extended result code]. ^The third parameter passed to the logger is
  2786. ** log message after formatting via [sqlite3_snprintf()].
  2787. ** The SQLite logging interface is not reentrant; the logger function
  2788. ** supplied by the application must not invoke any SQLite interface.
  2789. ** In a multi-threaded application, the application-defined logger
  2790. ** function must be threadsafe. </dd>
  2791. **
  2792. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2793. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  2794. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  2795. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  2796. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  2797. ** [sqlite3_open16()] or
  2798. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2799. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2800. ** connection is opened. ^If it is globally disabled, filenames are
  2801. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2802. ** database connection is opened. ^(By default, URI handling is globally
  2803. ** disabled. The default value may be changed by compiling with the
  2804. ** [SQLITE_USE_URI] symbol defined.)^
  2805. **
  2806. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2807. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2808. ** argument which is interpreted as a boolean in order to enable or disable
  2809. ** the use of covering indices for full table scans in the query optimizer.
  2810. ** ^The default setting is determined
  2811. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2812. ** if that compile-time option is omitted.
  2813. ** The ability to disable the use of covering indices for full table scans
  2814. ** is because some incorrectly coded legacy applications might malfunction
  2815. ** when the optimization is enabled. Providing the ability to
  2816. ** disable the optimization allows the older, buggy application code to work
  2817. ** without change even with newer versions of SQLite.
  2818. **
  2819. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2820. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2821. ** <dd> These options are obsolete and should not be used by new code.
  2822. ** They are retained for backwards compatibility but are now no-ops.
  2823. ** </dd>
  2824. **
  2825. ** [[SQLITE_CONFIG_SQLLOG]]
  2826. ** <dt>SQLITE_CONFIG_SQLLOG
  2827. ** <dd>This option is only available if sqlite is compiled with the
  2828. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2829. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2830. ** The second should be of type (void*). The callback is invoked by the library
  2831. ** in three separate circumstances, identified by the value passed as the
  2832. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2833. ** passed as the second argument has just been opened. The third argument
  2834. ** points to a buffer containing the name of the main database file. If the
  2835. ** fourth parameter is 1, then the SQL statement that the third parameter
  2836. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2837. ** the connection being passed as the second parameter is being closed. The
  2838. ** third parameter is passed NULL In this case. An example of using this
  2839. ** configuration option can be seen in the "test_sqllog.c" source file in
  2840. ** the canonical SQLite source tree.</dd>
  2841. **
  2842. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2843. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2844. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2845. ** that are the default mmap size limit (the default setting for
  2846. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2847. ** ^The default setting can be overridden by each database connection using
  2848. ** either the [PRAGMA mmap_size] command, or by using the
  2849. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  2850. ** will be silently truncated if necessary so that it does not exceed the
  2851. ** compile-time maximum mmap size set by the
  2852. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2853. ** ^If either argument to this option is negative, then that argument is
  2854. ** changed to its compile-time default.
  2855. **
  2856. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  2857. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  2858. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  2859. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  2860. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  2861. ** that specifies the maximum size of the created heap.
  2862. **
  2863. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  2864. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  2865. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  2866. ** is a pointer to an integer and writes into that integer the number of extra
  2867. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  2868. ** The amount of extra space required can change depending on the compiler,
  2869. ** target platform, and SQLite version.
  2870. **
  2871. ** [[SQLITE_CONFIG_PMASZ]]
  2872. ** <dt>SQLITE_CONFIG_PMASZ
  2873. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  2874. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2875. ** sorter to that integer. The default minimum PMA Size is set by the
  2876. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  2877. ** to help with sort operations when multithreaded sorting
  2878. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2879. ** to be sorted exceeds the page size times the minimum of the
  2880. ** [PRAGMA cache_size] setting and this value.
  2881. **
  2882. ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  2883. ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  2884. ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2885. ** becomes the [statement journal] spill-to-disk threshold.
  2886. ** [Statement journals] are held in memory until their size (in bytes)
  2887. ** exceeds this threshold, at which point they are written to disk.
  2888. ** Or if the threshold is -1, statement journals are always held
  2889. ** exclusively in memory.
  2890. ** Since many statement journals never become large, setting the spill
  2891. ** threshold to a value such as 64KiB can greatly reduce the amount of
  2892. ** I/O required to support statement rollback.
  2893. ** The default value for this setting is controlled by the
  2894. ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2895. ** </dl>
  2896. */
  2897. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  2898. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  2899. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  2900. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  2901. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  2902. #define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
  2903. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  2904. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  2905. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  2906. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  2907. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  2908. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  2909. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  2910. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  2911. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  2912. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  2913. #define SQLITE_CONFIG_URI 17 /* int */
  2914. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  2915. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  2916. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  2917. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  2918. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  2919. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  2920. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  2921. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  2922. #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
  2923. #define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
  2924. /*
  2925. ** CAPI3REF: Database Connection Configuration Options
  2926. **
  2927. ** These constants are the available integer configuration options that
  2928. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  2929. **
  2930. ** New configuration options may be added in future releases of SQLite.
  2931. ** Existing configuration options might be discontinued. Applications
  2932. ** should check the return code from [sqlite3_db_config()] to make sure that
  2933. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  2934. ** non-zero [error code] if a discontinued or unsupported configuration option
  2935. ** is invoked.
  2936. **
  2937. ** <dl>
  2938. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2939. ** <dd> ^This option takes three additional arguments that determine the
  2940. ** [lookaside memory allocator] configuration for the [database connection].
  2941. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2942. ** pointer to a memory buffer to use for lookaside memory.
  2943. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2944. ** may be NULL in which case SQLite will allocate the
  2945. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2946. ** size of each lookaside buffer slot. ^The third argument is the number of
  2947. ** slots. The size of the buffer in the first argument must be greater than
  2948. ** or equal to the product of the second and third arguments. The buffer
  2949. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2950. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2951. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2952. ** configuration for a database connection can only be changed when that
  2953. ** connection is not currently using lookaside memory, or in other words
  2954. ** when the "current value" returned by
  2955. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2956. ** Any attempt to change the lookaside memory configuration when lookaside
  2957. ** memory is in use leaves the configuration unchanged and returns
  2958. ** [SQLITE_BUSY].)^</dd>
  2959. **
  2960. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2961. ** <dd> ^This option is used to enable or disable the enforcement of
  2962. ** [foreign key constraints]. There should be two additional arguments.
  2963. ** The first argument is an integer which is 0 to disable FK enforcement,
  2964. ** positive to enable FK enforcement or negative to leave FK enforcement
  2965. ** unchanged. The second parameter is a pointer to an integer into which
  2966. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2967. ** following this call. The second parameter may be a NULL pointer, in
  2968. ** which case the FK enforcement setting is not reported back. </dd>
  2969. **
  2970. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2971. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2972. ** There should be two additional arguments.
  2973. ** The first argument is an integer which is 0 to disable triggers,
  2974. ** positive to enable triggers or negative to leave the setting unchanged.
  2975. ** The second parameter is a pointer to an integer into which
  2976. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2977. ** following this call. The second parameter may be a NULL pointer, in
  2978. ** which case the trigger setting is not reported back. </dd>
  2979. **
  2980. ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  2981. ** <dd> ^This option is used to enable or disable the two-argument
  2982. ** version of the [fts3_tokenizer()] function which is part of the
  2983. ** [FTS3] full-text search engine extension.
  2984. ** There should be two additional arguments.
  2985. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  2986. ** positive to enable fts3_tokenizer() or negative to leave the setting
  2987. ** unchanged.
  2988. ** The second parameter is a pointer to an integer into which
  2989. ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  2990. ** following this call. The second parameter may be a NULL pointer, in
  2991. ** which case the new setting is not reported back. </dd>
  2992. **
  2993. ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  2994. ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  2995. ** interface independently of the [load_extension()] SQL function.
  2996. ** The [sqlite3_enable_load_extension()] API enables or disables both the
  2997. ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  2998. ** There should be two additional arguments.
  2999. ** When the first argument to this interface is 1, then only the C-API is
  3000. ** enabled and the SQL function remains disabled. If the first argument to
  3001. ** this interface is 0, then both the C-API and the SQL function are disabled.
  3002. ** If the first argument is -1, then no changes are made to state of either the
  3003. ** C-API or the SQL function.
  3004. ** The second parameter is a pointer to an integer into which
  3005. ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  3006. ** is disabled or enabled following this call. The second parameter may
  3007. ** be a NULL pointer, in which case the new setting is not reported back.
  3008. ** </dd>
  3009. **
  3010. ** <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  3011. ** <dd> ^This option is used to change the name of the "main" database
  3012. ** schema. ^The sole argument is a pointer to a constant UTF8 string
  3013. ** which will become the new schema name in place of "main". ^SQLite
  3014. ** does not make a copy of the new main schema name string, so the application
  3015. ** must ensure that the argument passed into this DBCONFIG option is unchanged
  3016. ** until after the database connection closes.
  3017. ** </dd>
  3018. **
  3019. ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  3020. ** <dd> Usually, when a database in wal mode is closed or detached from a
  3021. ** database handle, SQLite checks if this will mean that there are now no
  3022. ** connections at all to the database. If so, it performs a checkpoint
  3023. ** operation before closing the connection. This option may be used to
  3024. ** override this behaviour. The first parameter passed to this operation
  3025. ** is an integer - positive to disable checkpoints-on-close, or zero (the
  3026. ** default) to enable them, and negative to leave the setting unchanged.
  3027. ** The second parameter is a pointer to an integer
  3028. ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  3029. ** have been disabled - 0 if they are not disabled, 1 if they are.
  3030. ** </dd>
  3031. **
  3032. ** <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
  3033. ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
  3034. ** the [query planner stability guarantee] (QPSG). When the QPSG is active,
  3035. ** a single SQL query statement will always use the same algorithm regardless
  3036. ** of values of [bound parameters].)^ The QPSG disables some query optimizations
  3037. ** that look at the values of bound parameters, which can make some queries
  3038. ** slower. But the QPSG has the advantage of more predictable behavior. With
  3039. ** the QPSG active, SQLite will always use the same query plan in the field as
  3040. ** was used during testing in the lab.
  3041. ** The first argument to this setting is an integer which is 0 to disable
  3042. ** the QPSG, positive to enable QPSG, or negative to leave the setting
  3043. ** unchanged. The second parameter is a pointer to an integer into which
  3044. ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
  3045. ** following this call.
  3046. ** </dd>
  3047. **
  3048. ** <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
  3049. ** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
  3050. ** include output for any operations performed by trigger programs. This
  3051. ** option is used to set or clear (the default) a flag that governs this
  3052. ** behavior. The first parameter passed to this operation is an integer -
  3053. ** positive to enable output for trigger programs, or zero to disable it,
  3054. ** or negative to leave the setting unchanged.
  3055. ** The second parameter is a pointer to an integer into which is written
  3056. ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
  3057. ** it is not disabled, 1 if it is.
  3058. ** </dd>
  3059. ** </dl>
  3060. */
  3061. #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
  3062. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  3063. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  3064. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  3065. #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3066. #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3067. #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
  3068. #define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
  3069. #define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */
  3070. #define SQLITE_DBCONFIG_MAX 1008 /* Largest DBCONFIG */
  3071. /*
  3072. ** CAPI3REF: Enable Or Disable Extended Result Codes
  3073. ** METHOD: sqlite3
  3074. **
  3075. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3076. ** [extended result codes] feature of SQLite. ^The extended result
  3077. ** codes are disabled by default for historical compatibility.
  3078. */
  3079. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  3080. /*
  3081. ** CAPI3REF: Last Insert Rowid
  3082. ** METHOD: sqlite3
  3083. **
  3084. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  3085. ** has a unique 64-bit signed
  3086. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  3087. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  3088. ** names are not also used by explicitly declared columns. ^If
  3089. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  3090. ** is another alias for the rowid.
  3091. **
  3092. ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  3093. ** the most recent successful [INSERT] into a rowid table or [virtual table]
  3094. ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  3095. ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
  3096. ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
  3097. ** zero.
  3098. **
  3099. ** As well as being set automatically as rows are inserted into database
  3100. ** tables, the value returned by this function may be set explicitly by
  3101. ** [sqlite3_set_last_insert_rowid()]
  3102. **
  3103. ** Some virtual table implementations may INSERT rows into rowid tables as
  3104. ** part of committing a transaction (e.g. to flush data accumulated in memory
  3105. ** to disk). In this case subsequent calls to this function return the rowid
  3106. ** associated with these internal INSERT operations, which leads to
  3107. ** unintuitive results. Virtual table implementations that do write to rowid
  3108. ** tables in this way can avoid this problem by restoring the original
  3109. ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
  3110. ** control to the user.
  3111. **
  3112. ** ^(If an [INSERT] occurs within a trigger then this routine will
  3113. ** return the [rowid] of the inserted row as long as the trigger is
  3114. ** running. Once the trigger program ends, the value returned
  3115. ** by this routine reverts to what it was before the trigger was fired.)^
  3116. **
  3117. ** ^An [INSERT] that fails due to a constraint violation is not a
  3118. ** successful [INSERT] and does not change the value returned by this
  3119. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  3120. ** and INSERT OR ABORT make no changes to the return value of this
  3121. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  3122. ** encounters a constraint violation, it does not fail. The
  3123. ** INSERT continues to completion after deleting rows that caused
  3124. ** the constraint problem so INSERT OR REPLACE will always change
  3125. ** the return value of this interface.)^
  3126. **
  3127. ** ^For the purposes of this routine, an [INSERT] is considered to
  3128. ** be successful even if it is subsequently rolled back.
  3129. **
  3130. ** This function is accessible to SQL statements via the
  3131. ** [last_insert_rowid() SQL function].
  3132. **
  3133. ** If a separate thread performs a new [INSERT] on the same
  3134. ** database connection while the [sqlite3_last_insert_rowid()]
  3135. ** function is running and thus changes the last insert [rowid],
  3136. ** then the value returned by [sqlite3_last_insert_rowid()] is
  3137. ** unpredictable and might not equal either the old or the new
  3138. ** last insert [rowid].
  3139. */
  3140. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  3141. /*
  3142. ** CAPI3REF: Set the Last Insert Rowid value.
  3143. ** METHOD: sqlite3
  3144. **
  3145. ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  3146. ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
  3147. ** without inserting a row into the database.
  3148. */
  3149. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  3150. /*
  3151. ** CAPI3REF: Count The Number Of Rows Modified
  3152. ** METHOD: sqlite3
  3153. **
  3154. ** ^This function returns the number of rows modified, inserted or
  3155. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  3156. ** statement on the database connection specified by the only parameter.
  3157. ** ^Executing any other type of SQL statement does not modify the value
  3158. ** returned by this function.
  3159. **
  3160. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  3161. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  3162. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  3163. **
  3164. ** Changes to a view that are intercepted by
  3165. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  3166. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  3167. ** DELETE statement run on a view is always zero. Only changes made to real
  3168. ** tables are counted.
  3169. **
  3170. ** Things are more complicated if the sqlite3_changes() function is
  3171. ** executed while a trigger program is running. This may happen if the
  3172. ** program uses the [changes() SQL function], or if some other callback
  3173. ** function invokes sqlite3_changes() directly. Essentially:
  3174. **
  3175. ** <ul>
  3176. ** <li> ^(Before entering a trigger program the value returned by
  3177. ** sqlite3_changes() function is saved. After the trigger program
  3178. ** has finished, the original value is restored.)^
  3179. **
  3180. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  3181. ** statement sets the value returned by sqlite3_changes()
  3182. ** upon completion as normal. Of course, this value will not include
  3183. ** any changes performed by sub-triggers, as the sqlite3_changes()
  3184. ** value will be saved and restored after each sub-trigger has run.)^
  3185. ** </ul>
  3186. **
  3187. ** ^This means that if the changes() SQL function (or similar) is used
  3188. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  3189. ** returns the value as set when the calling statement began executing.
  3190. ** ^If it is used by the second or subsequent such statement within a trigger
  3191. ** program, the value returned reflects the number of rows modified by the
  3192. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  3193. **
  3194. ** See also the [sqlite3_total_changes()] interface, the
  3195. ** [count_changes pragma], and the [changes() SQL function].
  3196. **
  3197. ** If a separate thread makes changes on the same database connection
  3198. ** while [sqlite3_changes()] is running then the value returned
  3199. ** is unpredictable and not meaningful.
  3200. */
  3201. SQLITE_API int sqlite3_changes(sqlite3*);
  3202. /*
  3203. ** CAPI3REF: Total Number Of Rows Modified
  3204. ** METHOD: sqlite3
  3205. **
  3206. ** ^This function returns the total number of rows inserted, modified or
  3207. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  3208. ** since the database connection was opened, including those executed as
  3209. ** part of trigger programs. ^Executing any other type of SQL statement
  3210. ** does not affect the value returned by sqlite3_total_changes().
  3211. **
  3212. ** ^Changes made as part of [foreign key actions] are included in the
  3213. ** count, but those made as part of REPLACE constraint resolution are
  3214. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  3215. ** are not counted.
  3216. **
  3217. ** See also the [sqlite3_changes()] interface, the
  3218. ** [count_changes pragma], and the [total_changes() SQL function].
  3219. **
  3220. ** If a separate thread makes changes on the same database connection
  3221. ** while [sqlite3_total_changes()] is running then the value
  3222. ** returned is unpredictable and not meaningful.
  3223. */
  3224. SQLITE_API int sqlite3_total_changes(sqlite3*);
  3225. /*
  3226. ** CAPI3REF: Interrupt A Long-Running Query
  3227. ** METHOD: sqlite3
  3228. **
  3229. ** ^This function causes any pending database operation to abort and
  3230. ** return at its earliest opportunity. This routine is typically
  3231. ** called in response to a user action such as pressing "Cancel"
  3232. ** or Ctrl-C where the user wants a long query operation to halt
  3233. ** immediately.
  3234. **
  3235. ** ^It is safe to call this routine from a thread different from the
  3236. ** thread that is currently running the database operation. But it
  3237. ** is not safe to call this routine with a [database connection] that
  3238. ** is closed or might close before sqlite3_interrupt() returns.
  3239. **
  3240. ** ^If an SQL operation is very nearly finished at the time when
  3241. ** sqlite3_interrupt() is called, then it might not have an opportunity
  3242. ** to be interrupted and might continue to completion.
  3243. **
  3244. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  3245. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  3246. ** that is inside an explicit transaction, then the entire transaction
  3247. ** will be rolled back automatically.
  3248. **
  3249. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  3250. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  3251. ** that are started after the sqlite3_interrupt() call and before the
  3252. ** running statements reaches zero are interrupted as if they had been
  3253. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  3254. ** that are started after the running statement count reaches zero are
  3255. ** not effected by the sqlite3_interrupt().
  3256. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  3257. ** SQL statements is a no-op and has no effect on SQL statements
  3258. ** that are started after the sqlite3_interrupt() call returns.
  3259. */
  3260. SQLITE_API void sqlite3_interrupt(sqlite3*);
  3261. /*
  3262. ** CAPI3REF: Determine If An SQL Statement Is Complete
  3263. **
  3264. ** These routines are useful during command-line input to determine if the
  3265. ** currently entered text seems to form a complete SQL statement or
  3266. ** if additional input is needed before sending the text into
  3267. ** SQLite for parsing. ^These routines return 1 if the input string
  3268. ** appears to be a complete SQL statement. ^A statement is judged to be
  3269. ** complete if it ends with a semicolon token and is not a prefix of a
  3270. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  3271. ** string literals or quoted identifier names or comments are not
  3272. ** independent tokens (they are part of the token in which they are
  3273. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  3274. ** and comments that follow the final semicolon are ignored.
  3275. **
  3276. ** ^These routines return 0 if the statement is incomplete. ^If a
  3277. ** memory allocation fails, then SQLITE_NOMEM is returned.
  3278. **
  3279. ** ^These routines do not parse the SQL statements thus
  3280. ** will not detect syntactically incorrect SQL.
  3281. **
  3282. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  3283. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  3284. ** automatically by sqlite3_complete16(). If that initialization fails,
  3285. ** then the return value from sqlite3_complete16() will be non-zero
  3286. ** regardless of whether or not the input SQL is complete.)^
  3287. **
  3288. ** The input to [sqlite3_complete()] must be a zero-terminated
  3289. ** UTF-8 string.
  3290. **
  3291. ** The input to [sqlite3_complete16()] must be a zero-terminated
  3292. ** UTF-16 string in native byte order.
  3293. */
  3294. SQLITE_API int sqlite3_complete(const char *sql);
  3295. SQLITE_API int sqlite3_complete16(const void *sql);
  3296. /*
  3297. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  3298. ** KEYWORDS: {busy-handler callback} {busy handler}
  3299. ** METHOD: sqlite3
  3300. **
  3301. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  3302. ** that might be invoked with argument P whenever
  3303. ** an attempt is made to access a database table associated with
  3304. ** [database connection] D when another thread
  3305. ** or process has the table locked.
  3306. ** The sqlite3_busy_handler() interface is used to implement
  3307. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  3308. **
  3309. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  3310. ** is returned immediately upon encountering the lock. ^If the busy callback
  3311. ** is not NULL, then the callback might be invoked with two arguments.
  3312. **
  3313. ** ^The first argument to the busy handler is a copy of the void* pointer which
  3314. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  3315. ** the busy handler callback is the number of times that the busy handler has
  3316. ** been invoked previously for the same locking event. ^If the
  3317. ** busy callback returns 0, then no additional attempts are made to
  3318. ** access the database and [SQLITE_BUSY] is returned
  3319. ** to the application.
  3320. ** ^If the callback returns non-zero, then another attempt
  3321. ** is made to access the database and the cycle repeats.
  3322. **
  3323. ** The presence of a busy handler does not guarantee that it will be invoked
  3324. ** when there is lock contention. ^If SQLite determines that invoking the busy
  3325. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  3326. ** to the application instead of invoking the
  3327. ** busy handler.
  3328. ** Consider a scenario where one process is holding a read lock that
  3329. ** it is trying to promote to a reserved lock and
  3330. ** a second process is holding a reserved lock that it is trying
  3331. ** to promote to an exclusive lock. The first process cannot proceed
  3332. ** because it is blocked by the second and the second process cannot
  3333. ** proceed because it is blocked by the first. If both processes
  3334. ** invoke the busy handlers, neither will make any progress. Therefore,
  3335. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  3336. ** will induce the first process to release its read lock and allow
  3337. ** the second process to proceed.
  3338. **
  3339. ** ^The default busy callback is NULL.
  3340. **
  3341. ** ^(There can only be a single busy handler defined for each
  3342. ** [database connection]. Setting a new busy handler clears any
  3343. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  3344. ** or evaluating [PRAGMA busy_timeout=N] will change the
  3345. ** busy handler and thus clear any previously set busy handler.
  3346. **
  3347. ** The busy callback should not take any actions which modify the
  3348. ** database connection that invoked the busy handler. In other words,
  3349. ** the busy handler is not reentrant. Any such actions
  3350. ** result in undefined behavior.
  3351. **
  3352. ** A busy handler must not close the database connection
  3353. ** or [prepared statement] that invoked the busy handler.
  3354. */
  3355. SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  3356. /*
  3357. ** CAPI3REF: Set A Busy Timeout
  3358. ** METHOD: sqlite3
  3359. **
  3360. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  3361. ** for a specified amount of time when a table is locked. ^The handler
  3362. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  3363. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  3364. ** the handler returns 0 which causes [sqlite3_step()] to return
  3365. ** [SQLITE_BUSY].
  3366. **
  3367. ** ^Calling this routine with an argument less than or equal to zero
  3368. ** turns off all busy handlers.
  3369. **
  3370. ** ^(There can only be a single busy handler for a particular
  3371. ** [database connection] at any given moment. If another busy handler
  3372. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  3373. ** this routine, that other busy handler is cleared.)^
  3374. **
  3375. ** See also: [PRAGMA busy_timeout]
  3376. */
  3377. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  3378. /*
  3379. ** CAPI3REF: Convenience Routines For Running Queries
  3380. ** METHOD: sqlite3
  3381. **
  3382. ** This is a legacy interface that is preserved for backwards compatibility.
  3383. ** Use of this interface is not recommended.
  3384. **
  3385. ** Definition: A <b>result table</b> is memory data structure created by the
  3386. ** [sqlite3_get_table()] interface. A result table records the
  3387. ** complete query results from one or more queries.
  3388. **
  3389. ** The table conceptually has a number of rows and columns. But
  3390. ** these numbers are not part of the result table itself. These
  3391. ** numbers are obtained separately. Let N be the number of rows
  3392. ** and M be the number of columns.
  3393. **
  3394. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  3395. ** There are (N+1)*M elements in the array. The first M pointers point
  3396. ** to zero-terminated strings that contain the names of the columns.
  3397. ** The remaining entries all point to query results. NULL values result
  3398. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  3399. ** string representation as returned by [sqlite3_column_text()].
  3400. **
  3401. ** A result table might consist of one or more memory allocations.
  3402. ** It is not safe to pass a result table directly to [sqlite3_free()].
  3403. ** A result table should be deallocated using [sqlite3_free_table()].
  3404. **
  3405. ** ^(As an example of the result table format, suppose a query result
  3406. ** is as follows:
  3407. **
  3408. ** <blockquote><pre>
  3409. ** Name | Age
  3410. ** -----------------------
  3411. ** Alice | 43
  3412. ** Bob | 28
  3413. ** Cindy | 21
  3414. ** </pre></blockquote>
  3415. **
  3416. ** There are two column (M==2) and three rows (N==3). Thus the
  3417. ** result table has 8 entries. Suppose the result table is stored
  3418. ** in an array names azResult. Then azResult holds this content:
  3419. **
  3420. ** <blockquote><pre>
  3421. ** azResult&#91;0] = "Name";
  3422. ** azResult&#91;1] = "Age";
  3423. ** azResult&#91;2] = "Alice";
  3424. ** azResult&#91;3] = "43";
  3425. ** azResult&#91;4] = "Bob";
  3426. ** azResult&#91;5] = "28";
  3427. ** azResult&#91;6] = "Cindy";
  3428. ** azResult&#91;7] = "21";
  3429. ** </pre></blockquote>)^
  3430. **
  3431. ** ^The sqlite3_get_table() function evaluates one or more
  3432. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  3433. ** string of its 2nd parameter and returns a result table to the
  3434. ** pointer given in its 3rd parameter.
  3435. **
  3436. ** After the application has finished with the result from sqlite3_get_table(),
  3437. ** it must pass the result table pointer to sqlite3_free_table() in order to
  3438. ** release the memory that was malloced. Because of the way the
  3439. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  3440. ** function must not try to call [sqlite3_free()] directly. Only
  3441. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  3442. **
  3443. ** The sqlite3_get_table() interface is implemented as a wrapper around
  3444. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  3445. ** to any internal data structures of SQLite. It uses only the public
  3446. ** interface defined here. As a consequence, errors that occur in the
  3447. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  3448. ** reflected in subsequent calls to [sqlite3_errcode()] or
  3449. ** [sqlite3_errmsg()].
  3450. */
  3451. SQLITE_API int sqlite3_get_table(
  3452. sqlite3 *db, /* An open database */
  3453. const char *zSql, /* SQL to be evaluated */
  3454. char ***pazResult, /* Results of the query */
  3455. int *pnRow, /* Number of result rows written here */
  3456. int *pnColumn, /* Number of result columns written here */
  3457. char **pzErrmsg /* Error msg written here */
  3458. );
  3459. SQLITE_API void sqlite3_free_table(char **result);
  3460. /*
  3461. ** CAPI3REF: Formatted String Printing Functions
  3462. **
  3463. ** These routines are work-alikes of the "printf()" family of functions
  3464. ** from the standard C library.
  3465. ** These routines understand most of the common formatting options from
  3466. ** the standard library printf()
  3467. ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
  3468. ** See the [built-in printf()] documentation for details.
  3469. **
  3470. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  3471. ** results into memory obtained from [sqlite3_malloc64()].
  3472. ** The strings returned by these two routines should be
  3473. ** released by [sqlite3_free()]. ^Both routines return a
  3474. ** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
  3475. ** memory to hold the resulting string.
  3476. **
  3477. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  3478. ** the standard C library. The result is written into the
  3479. ** buffer supplied as the second parameter whose size is given by
  3480. ** the first parameter. Note that the order of the
  3481. ** first two parameters is reversed from snprintf().)^ This is an
  3482. ** historical accident that cannot be fixed without breaking
  3483. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  3484. ** returns a pointer to its buffer instead of the number of
  3485. ** characters actually written into the buffer.)^ We admit that
  3486. ** the number of characters written would be a more useful return
  3487. ** value but we cannot change the implementation of sqlite3_snprintf()
  3488. ** now without breaking compatibility.
  3489. **
  3490. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  3491. ** guarantees that the buffer is always zero-terminated. ^The first
  3492. ** parameter "n" is the total size of the buffer, including space for
  3493. ** the zero terminator. So the longest string that can be completely
  3494. ** written will be n-1 characters.
  3495. **
  3496. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  3497. **
  3498. ** See also: [built-in printf()], [printf() SQL function]
  3499. */
  3500. SQLITE_API char *sqlite3_mprintf(const char*,...);
  3501. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  3502. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  3503. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  3504. /*
  3505. ** CAPI3REF: Memory Allocation Subsystem
  3506. **
  3507. ** The SQLite core uses these three routines for all of its own
  3508. ** internal memory allocation needs. "Core" in the previous sentence
  3509. ** does not include operating-system specific VFS implementation. The
  3510. ** Windows VFS uses native malloc() and free() for some operations.
  3511. **
  3512. ** ^The sqlite3_malloc() routine returns a pointer to a block
  3513. ** of memory at least N bytes in length, where N is the parameter.
  3514. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  3515. ** memory, it returns a NULL pointer. ^If the parameter N to
  3516. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  3517. ** a NULL pointer.
  3518. **
  3519. ** ^The sqlite3_malloc64(N) routine works just like
  3520. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  3521. ** of a signed 32-bit integer.
  3522. **
  3523. ** ^Calling sqlite3_free() with a pointer previously returned
  3524. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  3525. ** that it might be reused. ^The sqlite3_free() routine is
  3526. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  3527. ** to sqlite3_free() is harmless. After being freed, memory
  3528. ** should neither be read nor written. Even reading previously freed
  3529. ** memory might result in a segmentation fault or other severe error.
  3530. ** Memory corruption, a segmentation fault, or other severe error
  3531. ** might result if sqlite3_free() is called with a non-NULL pointer that
  3532. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  3533. **
  3534. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  3535. ** prior memory allocation X to be at least N bytes.
  3536. ** ^If the X parameter to sqlite3_realloc(X,N)
  3537. ** is a NULL pointer then its behavior is identical to calling
  3538. ** sqlite3_malloc(N).
  3539. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  3540. ** negative then the behavior is exactly the same as calling
  3541. ** sqlite3_free(X).
  3542. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  3543. ** of at least N bytes in size or NULL if insufficient memory is available.
  3544. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  3545. ** of the prior allocation are copied into the beginning of buffer returned
  3546. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  3547. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  3548. ** prior allocation is not freed.
  3549. **
  3550. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  3551. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  3552. ** of a 32-bit signed integer.
  3553. **
  3554. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  3555. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  3556. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  3557. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  3558. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  3559. ** sqlite3_msize(X) returns zero. If X points to something that is not
  3560. ** the beginning of memory allocation, or if it points to a formerly
  3561. ** valid memory allocation that has now been freed, then the behavior
  3562. ** of sqlite3_msize(X) is undefined and possibly harmful.
  3563. **
  3564. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  3565. ** sqlite3_malloc64(), and sqlite3_realloc64()
  3566. ** is always aligned to at least an 8 byte boundary, or to a
  3567. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  3568. ** option is used.
  3569. **
  3570. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  3571. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  3572. ** implementation of these routines to be omitted. That capability
  3573. ** is no longer provided. Only built-in memory allocators can be used.
  3574. **
  3575. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  3576. ** the system malloc() and free() directly when converting
  3577. ** filenames between the UTF-8 encoding used by SQLite
  3578. ** and whatever filename encoding is used by the particular Windows
  3579. ** installation. Memory allocation errors were detected, but
  3580. ** they were reported back as [SQLITE_CANTOPEN] or
  3581. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  3582. **
  3583. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  3584. ** must be either NULL or else pointers obtained from a prior
  3585. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  3586. ** not yet been released.
  3587. **
  3588. ** The application must not read or write any part of
  3589. ** a block of memory after it has been released using
  3590. ** [sqlite3_free()] or [sqlite3_realloc()].
  3591. */
  3592. SQLITE_API void *sqlite3_malloc(int);
  3593. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  3594. SQLITE_API void *sqlite3_realloc(void*, int);
  3595. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  3596. SQLITE_API void sqlite3_free(void*);
  3597. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  3598. /*
  3599. ** CAPI3REF: Memory Allocator Statistics
  3600. **
  3601. ** SQLite provides these two interfaces for reporting on the status
  3602. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  3603. ** routines, which form the built-in memory allocation subsystem.
  3604. **
  3605. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  3606. ** of memory currently outstanding (malloced but not freed).
  3607. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  3608. ** value of [sqlite3_memory_used()] since the high-water mark
  3609. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  3610. ** [sqlite3_memory_highwater()] include any overhead
  3611. ** added by SQLite in its implementation of [sqlite3_malloc()],
  3612. ** but not overhead added by the any underlying system library
  3613. ** routines that [sqlite3_malloc()] may call.
  3614. **
  3615. ** ^The memory high-water mark is reset to the current value of
  3616. ** [sqlite3_memory_used()] if and only if the parameter to
  3617. ** [sqlite3_memory_highwater()] is true. ^The value returned
  3618. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  3619. ** prior to the reset.
  3620. */
  3621. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  3622. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  3623. /*
  3624. ** CAPI3REF: Pseudo-Random Number Generator
  3625. **
  3626. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  3627. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  3628. ** already uses the largest possible [ROWID]. The PRNG is also used for
  3629. ** the build-in random() and randomblob() SQL functions. This interface allows
  3630. ** applications to access the same PRNG for other purposes.
  3631. **
  3632. ** ^A call to this routine stores N bytes of randomness into buffer P.
  3633. ** ^The P parameter can be a NULL pointer.
  3634. **
  3635. ** ^If this routine has not been previously called or if the previous
  3636. ** call had N less than one or a NULL pointer for P, then the PRNG is
  3637. ** seeded using randomness obtained from the xRandomness method of
  3638. ** the default [sqlite3_vfs] object.
  3639. ** ^If the previous call to this routine had an N of 1 or more and a
  3640. ** non-NULL P then the pseudo-randomness is generated
  3641. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  3642. ** method.
  3643. */
  3644. SQLITE_API void sqlite3_randomness(int N, void *P);
  3645. /*
  3646. ** CAPI3REF: Compile-Time Authorization Callbacks
  3647. ** METHOD: sqlite3
  3648. ** KEYWORDS: {authorizer callback}
  3649. **
  3650. ** ^This routine registers an authorizer callback with a particular
  3651. ** [database connection], supplied in the first argument.
  3652. ** ^The authorizer callback is invoked as SQL statements are being compiled
  3653. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  3654. ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
  3655. ** and [sqlite3_prepare16_v3()]. ^At various
  3656. ** points during the compilation process, as logic is being created
  3657. ** to perform various actions, the authorizer callback is invoked to
  3658. ** see if those actions are allowed. ^The authorizer callback should
  3659. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  3660. ** specific action but allow the SQL statement to continue to be
  3661. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  3662. ** rejected with an error. ^If the authorizer callback returns
  3663. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  3664. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  3665. ** the authorizer will fail with an error message.
  3666. **
  3667. ** When the callback returns [SQLITE_OK], that means the operation
  3668. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  3669. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  3670. ** authorizer will fail with an error message explaining that
  3671. ** access is denied.
  3672. **
  3673. ** ^The first parameter to the authorizer callback is a copy of the third
  3674. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  3675. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  3676. ** the particular action to be authorized. ^The third through sixth parameters
  3677. ** to the callback are either NULL pointers or zero-terminated strings
  3678. ** that contain additional details about the action to be authorized.
  3679. ** Applications must always be prepared to encounter a NULL pointer in any
  3680. ** of the third through the sixth parameters of the authorization callback.
  3681. **
  3682. ** ^If the action code is [SQLITE_READ]
  3683. ** and the callback returns [SQLITE_IGNORE] then the
  3684. ** [prepared statement] statement is constructed to substitute
  3685. ** a NULL value in place of the table column that would have
  3686. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  3687. ** return can be used to deny an untrusted user access to individual
  3688. ** columns of a table.
  3689. ** ^When a table is referenced by a [SELECT] but no column values are
  3690. ** extracted from that table (for example in a query like
  3691. ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  3692. ** is invoked once for that table with a column name that is an empty string.
  3693. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  3694. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  3695. ** [truncate optimization] is disabled and all rows are deleted individually.
  3696. **
  3697. ** An authorizer is used when [sqlite3_prepare | preparing]
  3698. ** SQL statements from an untrusted source, to ensure that the SQL statements
  3699. ** do not try to access data they are not allowed to see, or that they do not
  3700. ** try to execute malicious statements that damage the database. For
  3701. ** example, an application may allow a user to enter arbitrary
  3702. ** SQL queries for evaluation by a database. But the application does
  3703. ** not want the user to be able to make arbitrary changes to the
  3704. ** database. An authorizer could then be put in place while the
  3705. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  3706. ** disallows everything except [SELECT] statements.
  3707. **
  3708. ** Applications that need to process SQL from untrusted sources
  3709. ** might also consider lowering resource limits using [sqlite3_limit()]
  3710. ** and limiting database size using the [max_page_count] [PRAGMA]
  3711. ** in addition to using an authorizer.
  3712. **
  3713. ** ^(Only a single authorizer can be in place on a database connection
  3714. ** at a time. Each call to sqlite3_set_authorizer overrides the
  3715. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  3716. ** The authorizer is disabled by default.
  3717. **
  3718. ** The authorizer callback must not do anything that will modify
  3719. ** the database connection that invoked the authorizer callback.
  3720. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3721. ** database connections for the meaning of "modify" in this paragraph.
  3722. **
  3723. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  3724. ** statement might be re-prepared during [sqlite3_step()] due to a
  3725. ** schema change. Hence, the application should ensure that the
  3726. ** correct authorizer callback remains in place during the [sqlite3_step()].
  3727. **
  3728. ** ^Note that the authorizer callback is invoked only during
  3729. ** [sqlite3_prepare()] or its variants. Authorization is not
  3730. ** performed during statement evaluation in [sqlite3_step()], unless
  3731. ** as stated in the previous paragraph, sqlite3_step() invokes
  3732. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  3733. */
  3734. SQLITE_API int sqlite3_set_authorizer(
  3735. sqlite3*,
  3736. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  3737. void *pUserData
  3738. );
  3739. /*
  3740. ** CAPI3REF: Authorizer Return Codes
  3741. **
  3742. ** The [sqlite3_set_authorizer | authorizer callback function] must
  3743. ** return either [SQLITE_OK] or one of these two constants in order
  3744. ** to signal SQLite whether or not the action is permitted. See the
  3745. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  3746. ** information.
  3747. **
  3748. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  3749. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  3750. */
  3751. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  3752. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  3753. /*
  3754. ** CAPI3REF: Authorizer Action Codes
  3755. **
  3756. ** The [sqlite3_set_authorizer()] interface registers a callback function
  3757. ** that is invoked to authorize certain SQL statement actions. The
  3758. ** second parameter to the callback is an integer code that specifies
  3759. ** what action is being authorized. These are the integer action codes that
  3760. ** the authorizer callback may be passed.
  3761. **
  3762. ** These action code values signify what kind of operation is to be
  3763. ** authorized. The 3rd and 4th parameters to the authorization
  3764. ** callback function will be parameters or NULL depending on which of these
  3765. ** codes is used as the second parameter. ^(The 5th parameter to the
  3766. ** authorizer callback is the name of the database ("main", "temp",
  3767. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  3768. ** is the name of the inner-most trigger or view that is responsible for
  3769. ** the access attempt or NULL if this access attempt is directly from
  3770. ** top-level SQL code.
  3771. */
  3772. /******************************************* 3rd ************ 4th ***********/
  3773. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  3774. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  3775. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  3776. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  3777. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  3778. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  3779. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  3780. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  3781. #define SQLITE_DELETE 9 /* Table Name NULL */
  3782. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  3783. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  3784. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  3785. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  3786. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  3787. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  3788. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  3789. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  3790. #define SQLITE_INSERT 18 /* Table Name NULL */
  3791. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  3792. #define SQLITE_READ 20 /* Table Name Column Name */
  3793. #define SQLITE_SELECT 21 /* NULL NULL */
  3794. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  3795. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  3796. #define SQLITE_ATTACH 24 /* Filename NULL */
  3797. #define SQLITE_DETACH 25 /* Database Name NULL */
  3798. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  3799. #define SQLITE_REINDEX 27 /* Index Name NULL */
  3800. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  3801. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  3802. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  3803. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  3804. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  3805. #define SQLITE_COPY 0 /* No longer used */
  3806. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  3807. /*
  3808. ** CAPI3REF: Tracing And Profiling Functions
  3809. ** METHOD: sqlite3
  3810. **
  3811. ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  3812. ** instead of the routines described here.
  3813. **
  3814. ** These routines register callback functions that can be used for
  3815. ** tracing and profiling the execution of SQL statements.
  3816. **
  3817. ** ^The callback function registered by sqlite3_trace() is invoked at
  3818. ** various times when an SQL statement is being run by [sqlite3_step()].
  3819. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  3820. ** SQL statement text as the statement first begins executing.
  3821. ** ^(Additional sqlite3_trace() callbacks might occur
  3822. ** as each triggered subprogram is entered. The callbacks for triggers
  3823. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  3824. **
  3825. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  3826. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  3827. **
  3828. ** ^The callback function registered by sqlite3_profile() is invoked
  3829. ** as each SQL statement finishes. ^The profile callback contains
  3830. ** the original statement text and an estimate of wall-clock time
  3831. ** of how long that statement took to run. ^The profile callback
  3832. ** time is in units of nanoseconds, however the current implementation
  3833. ** is only capable of millisecond resolution so the six least significant
  3834. ** digits in the time are meaningless. Future versions of SQLite
  3835. ** might provide greater resolution on the profiler callback. The
  3836. ** sqlite3_profile() function is considered experimental and is
  3837. ** subject to change in future versions of SQLite.
  3838. */
  3839. SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  3840. void(*xTrace)(void*,const char*), void*);
  3841. SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  3842. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  3843. /*
  3844. ** CAPI3REF: SQL Trace Event Codes
  3845. ** KEYWORDS: SQLITE_TRACE
  3846. **
  3847. ** These constants identify classes of events that can be monitored
  3848. ** using the [sqlite3_trace_v2()] tracing logic. The M argument
  3849. ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
  3850. ** the following constants. ^The first argument to the trace callback
  3851. ** is one of the following constants.
  3852. **
  3853. ** New tracing constants may be added in future releases.
  3854. **
  3855. ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  3856. ** ^The T argument is one of the integer type codes above.
  3857. ** ^The C argument is a copy of the context pointer passed in as the
  3858. ** fourth argument to [sqlite3_trace_v2()].
  3859. ** The P and X arguments are pointers whose meanings depend on T.
  3860. **
  3861. ** <dl>
  3862. ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  3863. ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  3864. ** first begins running and possibly at other times during the
  3865. ** execution of the prepared statement, such as at the start of each
  3866. ** trigger subprogram. ^The P argument is a pointer to the
  3867. ** [prepared statement]. ^The X argument is a pointer to a string which
  3868. ** is the unexpanded SQL text of the prepared statement or an SQL comment
  3869. ** that indicates the invocation of a trigger. ^The callback can compute
  3870. ** the same text that would have been returned by the legacy [sqlite3_trace()]
  3871. ** interface by using the X argument when X begins with "--" and invoking
  3872. ** [sqlite3_expanded_sql(P)] otherwise.
  3873. **
  3874. ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  3875. ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  3876. ** information as is provided by the [sqlite3_profile()] callback.
  3877. ** ^The P argument is a pointer to the [prepared statement] and the
  3878. ** X argument points to a 64-bit integer which is the estimated of
  3879. ** the number of nanosecond that the prepared statement took to run.
  3880. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  3881. **
  3882. ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  3883. ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  3884. ** statement generates a single row of result.
  3885. ** ^The P argument is a pointer to the [prepared statement] and the
  3886. ** X argument is unused.
  3887. **
  3888. ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  3889. ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  3890. ** connection closes.
  3891. ** ^The P argument is a pointer to the [database connection] object
  3892. ** and the X argument is unused.
  3893. ** </dl>
  3894. */
  3895. #define SQLITE_TRACE_STMT 0x01
  3896. #define SQLITE_TRACE_PROFILE 0x02
  3897. #define SQLITE_TRACE_ROW 0x04
  3898. #define SQLITE_TRACE_CLOSE 0x08
  3899. /*
  3900. ** CAPI3REF: SQL Trace Hook
  3901. ** METHOD: sqlite3
  3902. **
  3903. ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  3904. ** function X against [database connection] D, using property mask M
  3905. ** and context pointer P. ^If the X callback is
  3906. ** NULL or if the M mask is zero, then tracing is disabled. The
  3907. ** M argument should be the bitwise OR-ed combination of
  3908. ** zero or more [SQLITE_TRACE] constants.
  3909. **
  3910. ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
  3911. ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  3912. **
  3913. ** ^The X callback is invoked whenever any of the events identified by
  3914. ** mask M occur. ^The integer return value from the callback is currently
  3915. ** ignored, though this may change in future releases. Callback
  3916. ** implementations should return zero to ensure future compatibility.
  3917. **
  3918. ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  3919. ** ^The T argument is one of the [SQLITE_TRACE]
  3920. ** constants to indicate why the callback was invoked.
  3921. ** ^The C argument is a copy of the context pointer.
  3922. ** The P and X arguments are pointers whose meanings depend on T.
  3923. **
  3924. ** The sqlite3_trace_v2() interface is intended to replace the legacy
  3925. ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  3926. ** are deprecated.
  3927. */
  3928. SQLITE_API int sqlite3_trace_v2(
  3929. sqlite3*,
  3930. unsigned uMask,
  3931. int(*xCallback)(unsigned,void*,void*,void*),
  3932. void *pCtx
  3933. );
  3934. /*
  3935. ** CAPI3REF: Query Progress Callbacks
  3936. ** METHOD: sqlite3
  3937. **
  3938. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  3939. ** function X to be invoked periodically during long running calls to
  3940. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  3941. ** database connection D. An example use for this
  3942. ** interface is to keep a GUI updated during a large query.
  3943. **
  3944. ** ^The parameter P is passed through as the only parameter to the
  3945. ** callback function X. ^The parameter N is the approximate number of
  3946. ** [virtual machine instructions] that are evaluated between successive
  3947. ** invocations of the callback X. ^If N is less than one then the progress
  3948. ** handler is disabled.
  3949. **
  3950. ** ^Only a single progress handler may be defined at one time per
  3951. ** [database connection]; setting a new progress handler cancels the
  3952. ** old one. ^Setting parameter X to NULL disables the progress handler.
  3953. ** ^The progress handler is also disabled by setting N to a value less
  3954. ** than 1.
  3955. **
  3956. ** ^If the progress callback returns non-zero, the operation is
  3957. ** interrupted. This feature can be used to implement a
  3958. ** "Cancel" button on a GUI progress dialog box.
  3959. **
  3960. ** The progress handler callback must not do anything that will modify
  3961. ** the database connection that invoked the progress handler.
  3962. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3963. ** database connections for the meaning of "modify" in this paragraph.
  3964. **
  3965. */
  3966. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  3967. /*
  3968. ** CAPI3REF: Opening A New Database Connection
  3969. ** CONSTRUCTOR: sqlite3
  3970. **
  3971. ** ^These routines open an SQLite database file as specified by the
  3972. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  3973. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  3974. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  3975. ** returned in *ppDb, even if an error occurs. The only exception is that
  3976. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  3977. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  3978. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  3979. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  3980. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  3981. ** an English language description of the error following a failure of any
  3982. ** of the sqlite3_open() routines.
  3983. **
  3984. ** ^The default encoding will be UTF-8 for databases created using
  3985. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  3986. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  3987. **
  3988. ** Whether or not an error occurs when it is opened, resources
  3989. ** associated with the [database connection] handle should be released by
  3990. ** passing it to [sqlite3_close()] when it is no longer required.
  3991. **
  3992. ** The sqlite3_open_v2() interface works like sqlite3_open()
  3993. ** except that it accepts two additional parameters for additional control
  3994. ** over the new database connection. ^(The flags parameter to
  3995. ** sqlite3_open_v2() can take one of
  3996. ** the following three values, optionally combined with the
  3997. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  3998. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  3999. **
  4000. ** <dl>
  4001. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  4002. ** <dd>The database is opened in read-only mode. If the database does not
  4003. ** already exist, an error is returned.</dd>)^
  4004. **
  4005. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  4006. ** <dd>The database is opened for reading and writing if possible, or reading
  4007. ** only if the file is write protected by the operating system. In either
  4008. ** case the database must already exist, otherwise an error is returned.</dd>)^
  4009. **
  4010. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  4011. ** <dd>The database is opened for reading and writing, and is created if
  4012. ** it does not already exist. This is the behavior that is always used for
  4013. ** sqlite3_open() and sqlite3_open16().</dd>)^
  4014. ** </dl>
  4015. **
  4016. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  4017. ** combinations shown above optionally combined with other
  4018. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  4019. ** then the behavior is undefined.
  4020. **
  4021. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  4022. ** opens in the multi-thread [threading mode] as long as the single-thread
  4023. ** mode has not been set at compile-time or start-time. ^If the
  4024. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  4025. ** in the serialized [threading mode] unless single-thread was
  4026. ** previously selected at compile-time or start-time.
  4027. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  4028. ** eligible to use [shared cache mode], regardless of whether or not shared
  4029. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  4030. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  4031. ** participate in [shared cache mode] even if it is enabled.
  4032. **
  4033. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  4034. ** [sqlite3_vfs] object that defines the operating system interface that
  4035. ** the new database connection should use. ^If the fourth parameter is
  4036. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  4037. **
  4038. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  4039. ** is created for the connection. ^This in-memory database will vanish when
  4040. ** the database connection is closed. Future versions of SQLite might
  4041. ** make use of additional special filenames that begin with the ":" character.
  4042. ** It is recommended that when a database filename actually does begin with
  4043. ** a ":" character you should prefix the filename with a pathname such as
  4044. ** "./" to avoid ambiguity.
  4045. **
  4046. ** ^If the filename is an empty string, then a private, temporary
  4047. ** on-disk database will be created. ^This private database will be
  4048. ** automatically deleted as soon as the database connection is closed.
  4049. **
  4050. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  4051. **
  4052. ** ^If [URI filename] interpretation is enabled, and the filename argument
  4053. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  4054. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  4055. ** set in the third argument to sqlite3_open_v2(), or if it has
  4056. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  4057. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  4058. ** URI filename interpretation is turned off
  4059. ** by default, but future releases of SQLite might enable URI filename
  4060. ** interpretation by default. See "[URI filenames]" for additional
  4061. ** information.
  4062. **
  4063. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  4064. ** authority, then it must be either an empty string or the string
  4065. ** "localhost". ^If the authority is not an empty string or "localhost", an
  4066. ** error is returned to the caller. ^The fragment component of a URI, if
  4067. ** present, is ignored.
  4068. **
  4069. ** ^SQLite uses the path component of the URI as the name of the disk file
  4070. ** which contains the database. ^If the path begins with a '/' character,
  4071. ** then it is interpreted as an absolute path. ^If the path does not begin
  4072. ** with a '/' (meaning that the authority section is omitted from the URI)
  4073. ** then the path is interpreted as a relative path.
  4074. ** ^(On windows, the first component of an absolute path
  4075. ** is a drive specification (e.g. "C:").)^
  4076. **
  4077. ** [[core URI query parameters]]
  4078. ** The query component of a URI may contain parameters that are interpreted
  4079. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  4080. ** SQLite and its built-in [VFSes] interpret the
  4081. ** following query parameters:
  4082. **
  4083. ** <ul>
  4084. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  4085. ** a VFS object that provides the operating system interface that should
  4086. ** be used to access the database file on disk. ^If this option is set to
  4087. ** an empty string the default VFS object is used. ^Specifying an unknown
  4088. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  4089. ** present, then the VFS specified by the option takes precedence over
  4090. ** the value passed as the fourth parameter to sqlite3_open_v2().
  4091. **
  4092. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  4093. ** "rwc", or "memory". Attempting to set it to any other value is
  4094. ** an error)^.
  4095. ** ^If "ro" is specified, then the database is opened for read-only
  4096. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  4097. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  4098. ** "rw", then the database is opened for read-write (but not create)
  4099. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  4100. ** been set. ^Value "rwc" is equivalent to setting both
  4101. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  4102. ** set to "memory" then a pure [in-memory database] that never reads
  4103. ** or writes from disk is used. ^It is an error to specify a value for
  4104. ** the mode parameter that is less restrictive than that specified by
  4105. ** the flags passed in the third parameter to sqlite3_open_v2().
  4106. **
  4107. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  4108. ** "private". ^Setting it to "shared" is equivalent to setting the
  4109. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  4110. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  4111. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  4112. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  4113. ** a URI filename, its value overrides any behavior requested by setting
  4114. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  4115. **
  4116. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  4117. ** [powersafe overwrite] property does or does not apply to the
  4118. ** storage media on which the database file resides.
  4119. **
  4120. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  4121. ** which if set disables file locking in rollback journal modes. This
  4122. ** is useful for accessing a database on a filesystem that does not
  4123. ** support locking. Caution: Database corruption might result if two
  4124. ** or more processes write to the same database and any one of those
  4125. ** processes uses nolock=1.
  4126. **
  4127. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  4128. ** parameter that indicates that the database file is stored on
  4129. ** read-only media. ^When immutable is set, SQLite assumes that the
  4130. ** database file cannot be changed, even by a process with higher
  4131. ** privilege, and so the database is opened read-only and all locking
  4132. ** and change detection is disabled. Caution: Setting the immutable
  4133. ** property on a database file that does in fact change can result
  4134. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  4135. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  4136. **
  4137. ** </ul>
  4138. **
  4139. ** ^Specifying an unknown parameter in the query component of a URI is not an
  4140. ** error. Future versions of SQLite might understand additional query
  4141. ** parameters. See "[query parameters with special meaning to SQLite]" for
  4142. ** additional information.
  4143. **
  4144. ** [[URI filename examples]] <h3>URI filename examples</h3>
  4145. **
  4146. ** <table border="1" align=center cellpadding=5>
  4147. ** <tr><th> URI filenames <th> Results
  4148. ** <tr><td> file:data.db <td>
  4149. ** Open the file "data.db" in the current directory.
  4150. ** <tr><td> file:/home/fred/data.db<br>
  4151. ** file:///home/fred/data.db <br>
  4152. ** file://localhost/home/fred/data.db <br> <td>
  4153. ** Open the database file "/home/fred/data.db".
  4154. ** <tr><td> file://darkstar/home/fred/data.db <td>
  4155. ** An error. "darkstar" is not a recognized authority.
  4156. ** <tr><td style="white-space:nowrap">
  4157. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  4158. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  4159. ** C:. Note that the %20 escaping in this example is not strictly
  4160. ** necessary - space characters can be used literally
  4161. ** in URI filenames.
  4162. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  4163. ** Open file "data.db" in the current directory for read-only access.
  4164. ** Regardless of whether or not shared-cache mode is enabled by
  4165. ** default, use a private cache.
  4166. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  4167. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  4168. ** that uses dot-files in place of posix advisory locking.
  4169. ** <tr><td> file:data.db?mode=readonly <td>
  4170. ** An error. "readonly" is not a valid option for the "mode" parameter.
  4171. ** </table>
  4172. **
  4173. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  4174. ** query components of a URI. A hexadecimal escape sequence consists of a
  4175. ** percent sign - "%" - followed by exactly two hexadecimal digits
  4176. ** specifying an octet value. ^Before the path or query components of a
  4177. ** URI filename are interpreted, they are encoded using UTF-8 and all
  4178. ** hexadecimal escape sequences replaced by a single byte containing the
  4179. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  4180. ** the results are undefined.
  4181. **
  4182. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  4183. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  4184. ** codepage is currently defined. Filenames containing international
  4185. ** characters must be converted to UTF-8 prior to passing them into
  4186. ** sqlite3_open() or sqlite3_open_v2().
  4187. **
  4188. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4189. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  4190. ** features that require the use of temporary files may fail.
  4191. **
  4192. ** See also: [sqlite3_temp_directory]
  4193. */
  4194. SQLITE_API int sqlite3_open(
  4195. const char *filename, /* Database filename (UTF-8) */
  4196. sqlite3 **ppDb /* OUT: SQLite db handle */
  4197. );
  4198. SQLITE_API int sqlite3_open16(
  4199. const void *filename, /* Database filename (UTF-16) */
  4200. sqlite3 **ppDb /* OUT: SQLite db handle */
  4201. );
  4202. SQLITE_API int sqlite3_open_v2(
  4203. const char *filename, /* Database filename (UTF-8) */
  4204. sqlite3 **ppDb, /* OUT: SQLite db handle */
  4205. int flags, /* Flags */
  4206. const char *zVfs /* Name of VFS module to use */
  4207. );
  4208. /*
  4209. ** CAPI3REF: Obtain Values For URI Parameters
  4210. **
  4211. ** These are utility routines, useful to VFS implementations, that check
  4212. ** to see if a database file was a URI that contained a specific query
  4213. ** parameter, and if so obtains the value of that query parameter.
  4214. **
  4215. ** If F is the database filename pointer passed into the xOpen() method of
  4216. ** a VFS implementation when the flags parameter to xOpen() has one or
  4217. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  4218. ** P is the name of the query parameter, then
  4219. ** sqlite3_uri_parameter(F,P) returns the value of the P
  4220. ** parameter if it exists or a NULL pointer if P does not appear as a
  4221. ** query parameter on F. If P is a query parameter of F
  4222. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  4223. ** a pointer to an empty string.
  4224. **
  4225. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  4226. ** parameter and returns true (1) or false (0) according to the value
  4227. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  4228. ** value of query parameter P is one of "yes", "true", or "on" in any
  4229. ** case or if the value begins with a non-zero number. The
  4230. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  4231. ** query parameter P is one of "no", "false", or "off" in any case or
  4232. ** if the value begins with a numeric zero. If P is not a query
  4233. ** parameter on F or if the value of P is does not match any of the
  4234. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  4235. **
  4236. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  4237. ** 64-bit signed integer and returns that integer, or D if P does not
  4238. ** exist. If the value of P is something other than an integer, then
  4239. ** zero is returned.
  4240. **
  4241. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  4242. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  4243. ** is not a database file pathname pointer that SQLite passed into the xOpen
  4244. ** VFS method, then the behavior of this routine is undefined and probably
  4245. ** undesirable.
  4246. */
  4247. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  4248. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  4249. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  4250. /*
  4251. ** CAPI3REF: Error Codes And Messages
  4252. ** METHOD: sqlite3
  4253. **
  4254. ** ^If the most recent sqlite3_* API call associated with
  4255. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  4256. ** returns the numeric [result code] or [extended result code] for that
  4257. ** API call.
  4258. ** If the most recent API call was successful,
  4259. ** then the return value from sqlite3_errcode() is undefined.
  4260. ** ^The sqlite3_extended_errcode()
  4261. ** interface is the same except that it always returns the
  4262. ** [extended result code] even when extended result codes are
  4263. ** disabled.
  4264. **
  4265. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  4266. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  4267. ** ^(Memory to hold the error message string is managed internally.
  4268. ** The application does not need to worry about freeing the result.
  4269. ** However, the error string might be overwritten or deallocated by
  4270. ** subsequent calls to other SQLite interface functions.)^
  4271. **
  4272. ** ^The sqlite3_errstr() interface returns the English-language text
  4273. ** that describes the [result code], as UTF-8.
  4274. ** ^(Memory to hold the error message string is managed internally
  4275. ** and must not be freed by the application)^.
  4276. **
  4277. ** When the serialized [threading mode] is in use, it might be the
  4278. ** case that a second error occurs on a separate thread in between
  4279. ** the time of the first error and the call to these interfaces.
  4280. ** When that happens, the second error will be reported since these
  4281. ** interfaces always report the most recent result. To avoid
  4282. ** this, each thread can obtain exclusive use of the [database connection] D
  4283. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  4284. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  4285. ** all calls to the interfaces listed here are completed.
  4286. **
  4287. ** If an interface fails with SQLITE_MISUSE, that means the interface
  4288. ** was invoked incorrectly by the application. In that case, the
  4289. ** error code and message may or may not be set.
  4290. */
  4291. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  4292. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  4293. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  4294. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  4295. SQLITE_API const char *sqlite3_errstr(int);
  4296. /*
  4297. ** CAPI3REF: Prepared Statement Object
  4298. ** KEYWORDS: {prepared statement} {prepared statements}
  4299. **
  4300. ** An instance of this object represents a single SQL statement that
  4301. ** has been compiled into binary form and is ready to be evaluated.
  4302. **
  4303. ** Think of each SQL statement as a separate computer program. The
  4304. ** original SQL text is source code. A prepared statement object
  4305. ** is the compiled object code. All SQL must be converted into a
  4306. ** prepared statement before it can be run.
  4307. **
  4308. ** The life-cycle of a prepared statement object usually goes like this:
  4309. **
  4310. ** <ol>
  4311. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  4312. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  4313. ** interfaces.
  4314. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  4315. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  4316. ** to step 2. Do this zero or more times.
  4317. ** <li> Destroy the object using [sqlite3_finalize()].
  4318. ** </ol>
  4319. */
  4320. typedef struct sqlite3_stmt sqlite3_stmt;
  4321. /*
  4322. ** CAPI3REF: Run-time Limits
  4323. ** METHOD: sqlite3
  4324. **
  4325. ** ^(This interface allows the size of various constructs to be limited
  4326. ** on a connection by connection basis. The first parameter is the
  4327. ** [database connection] whose limit is to be set or queried. The
  4328. ** second parameter is one of the [limit categories] that define a
  4329. ** class of constructs to be size limited. The third parameter is the
  4330. ** new limit for that construct.)^
  4331. **
  4332. ** ^If the new limit is a negative number, the limit is unchanged.
  4333. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  4334. ** [limits | hard upper bound]
  4335. ** set at compile-time by a C preprocessor macro called
  4336. ** [limits | SQLITE_MAX_<i>NAME</i>].
  4337. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  4338. ** ^Attempts to increase a limit above its hard upper bound are
  4339. ** silently truncated to the hard upper bound.
  4340. **
  4341. ** ^Regardless of whether or not the limit was changed, the
  4342. ** [sqlite3_limit()] interface returns the prior value of the limit.
  4343. ** ^Hence, to find the current value of a limit without changing it,
  4344. ** simply invoke this interface with the third parameter set to -1.
  4345. **
  4346. ** Run-time limits are intended for use in applications that manage
  4347. ** both their own internal database and also databases that are controlled
  4348. ** by untrusted external sources. An example application might be a
  4349. ** web browser that has its own databases for storing history and
  4350. ** separate databases controlled by JavaScript applications downloaded
  4351. ** off the Internet. The internal databases can be given the
  4352. ** large, default limits. Databases managed by external sources can
  4353. ** be given much smaller limits designed to prevent a denial of service
  4354. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  4355. ** interface to further control untrusted SQL. The size of the database
  4356. ** created by an untrusted script can be contained using the
  4357. ** [max_page_count] [PRAGMA].
  4358. **
  4359. ** New run-time limit categories may be added in future releases.
  4360. */
  4361. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  4362. /*
  4363. ** CAPI3REF: Run-Time Limit Categories
  4364. ** KEYWORDS: {limit category} {*limit categories}
  4365. **
  4366. ** These constants define various performance limits
  4367. ** that can be lowered at run-time using [sqlite3_limit()].
  4368. ** The synopsis of the meanings of the various limits is shown below.
  4369. ** Additional information is available at [limits | Limits in SQLite].
  4370. **
  4371. ** <dl>
  4372. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  4373. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  4374. **
  4375. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  4376. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  4377. **
  4378. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  4379. ** <dd>The maximum number of columns in a table definition or in the
  4380. ** result set of a [SELECT] or the maximum number of columns in an index
  4381. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  4382. **
  4383. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  4384. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  4385. **
  4386. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  4387. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  4388. **
  4389. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  4390. ** <dd>The maximum number of instructions in a virtual machine program
  4391. ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
  4392. ** the equivalent tries to allocate space for more than this many opcodes
  4393. ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  4394. **
  4395. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  4396. ** <dd>The maximum number of arguments on a function.</dd>)^
  4397. **
  4398. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  4399. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  4400. **
  4401. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  4402. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  4403. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  4404. ** [GLOB] operators.</dd>)^
  4405. **
  4406. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  4407. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  4408. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  4409. **
  4410. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  4411. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  4412. **
  4413. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  4414. ** <dd>The maximum number of auxiliary worker threads that a single
  4415. ** [prepared statement] may start.</dd>)^
  4416. ** </dl>
  4417. */
  4418. #define SQLITE_LIMIT_LENGTH 0
  4419. #define SQLITE_LIMIT_SQL_LENGTH 1
  4420. #define SQLITE_LIMIT_COLUMN 2
  4421. #define SQLITE_LIMIT_EXPR_DEPTH 3
  4422. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  4423. #define SQLITE_LIMIT_VDBE_OP 5
  4424. #define SQLITE_LIMIT_FUNCTION_ARG 6
  4425. #define SQLITE_LIMIT_ATTACHED 7
  4426. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  4427. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  4428. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  4429. #define SQLITE_LIMIT_WORKER_THREADS 11
  4430. /*
  4431. ** CAPI3REF: Prepare Flags
  4432. **
  4433. ** These constants define various flags that can be passed into
  4434. ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
  4435. ** [sqlite3_prepare16_v3()] interfaces.
  4436. **
  4437. ** New flags may be added in future releases of SQLite.
  4438. **
  4439. ** <dl>
  4440. ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
  4441. ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
  4442. ** that the prepared statement will be retained for a long time and
  4443. ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
  4444. ** and [sqlite3_prepare16_v3()] assume that the prepared statement will
  4445. ** be used just once or at most a few times and then destroyed using
  4446. ** [sqlite3_finalize()] relatively soon. The current implementation acts
  4447. ** on this hint by avoiding the use of [lookaside memory] so as not to
  4448. ** deplete the limited store of lookaside memory. Future versions of
  4449. ** SQLite may act on this hint differently.
  4450. ** </dl>
  4451. */
  4452. #define SQLITE_PREPARE_PERSISTENT 0x01
  4453. /*
  4454. ** CAPI3REF: Compiling An SQL Statement
  4455. ** KEYWORDS: {SQL statement compiler}
  4456. ** METHOD: sqlite3
  4457. ** CONSTRUCTOR: sqlite3_stmt
  4458. **
  4459. ** To execute an SQL statement, it must first be compiled into a byte-code
  4460. ** program using one of these routines. Or, in other words, these routines
  4461. ** are constructors for the [prepared statement] object.
  4462. **
  4463. ** The preferred routine to use is [sqlite3_prepare_v2()]. The
  4464. ** [sqlite3_prepare()] interface is legacy and should be avoided.
  4465. ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
  4466. ** for special purposes.
  4467. **
  4468. ** The use of the UTF-8 interfaces is preferred, as SQLite currently
  4469. ** does all parsing using UTF-8. The UTF-16 interfaces are provided
  4470. ** as a convenience. The UTF-16 interfaces work by converting the
  4471. ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
  4472. **
  4473. ** The first argument, "db", is a [database connection] obtained from a
  4474. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  4475. ** [sqlite3_open16()]. The database connection must not have been closed.
  4476. **
  4477. ** The second argument, "zSql", is the statement to be compiled, encoded
  4478. ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
  4479. ** and sqlite3_prepare_v3()
  4480. ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
  4481. ** and sqlite3_prepare16_v3() use UTF-16.
  4482. **
  4483. ** ^If the nByte argument is negative, then zSql is read up to the
  4484. ** first zero terminator. ^If nByte is positive, then it is the
  4485. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  4486. ** statement is generated.
  4487. ** If the caller knows that the supplied string is nul-terminated, then
  4488. ** there is a small performance advantage to passing an nByte parameter that
  4489. ** is the number of bytes in the input string <i>including</i>
  4490. ** the nul-terminator.
  4491. **
  4492. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  4493. ** past the end of the first SQL statement in zSql. These routines only
  4494. ** compile the first statement in zSql, so *pzTail is left pointing to
  4495. ** what remains uncompiled.
  4496. **
  4497. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  4498. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  4499. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  4500. ** string or a comment) then *ppStmt is set to NULL.
  4501. ** The calling procedure is responsible for deleting the compiled
  4502. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  4503. ** ppStmt may not be NULL.
  4504. **
  4505. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  4506. ** otherwise an [error code] is returned.
  4507. **
  4508. ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
  4509. ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
  4510. ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
  4511. ** are retained for backwards compatibility, but their use is discouraged.
  4512. ** ^In the "vX" interfaces, the prepared statement
  4513. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  4514. ** original SQL text. This causes the [sqlite3_step()] interface to
  4515. ** behave differently in three ways:
  4516. **
  4517. ** <ol>
  4518. ** <li>
  4519. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  4520. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  4521. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  4522. ** retries will occur before sqlite3_step() gives up and returns an error.
  4523. ** </li>
  4524. **
  4525. ** <li>
  4526. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  4527. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  4528. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  4529. ** and the application would have to make a second call to [sqlite3_reset()]
  4530. ** in order to find the underlying cause of the problem. With the "v2" prepare
  4531. ** interfaces, the underlying reason for the error is returned immediately.
  4532. ** </li>
  4533. **
  4534. ** <li>
  4535. ** ^If the specific value bound to [parameter | host parameter] in the
  4536. ** WHERE clause might influence the choice of query plan for a statement,
  4537. ** then the statement will be automatically recompiled, as if there had been
  4538. ** a schema change, on the first [sqlite3_step()] call following any change
  4539. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  4540. ** ^The specific value of WHERE-clause [parameter] might influence the
  4541. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  4542. ** or [GLOB] operator or if the parameter is compared to an indexed column
  4543. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  4544. ** </li>
  4545. ** </ol>
  4546. **
  4547. ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
  4548. ** the extra prepFlags parameter, which is a bit array consisting of zero or
  4549. ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
  4550. ** sqlite3_prepare_v2() interface works exactly the same as
  4551. ** sqlite3_prepare_v3() with a zero prepFlags parameter.
  4552. */
  4553. SQLITE_API int sqlite3_prepare(
  4554. sqlite3 *db, /* Database handle */
  4555. const char *zSql, /* SQL statement, UTF-8 encoded */
  4556. int nByte, /* Maximum length of zSql in bytes. */
  4557. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4558. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4559. );
  4560. SQLITE_API int sqlite3_prepare_v2(
  4561. sqlite3 *db, /* Database handle */
  4562. const char *zSql, /* SQL statement, UTF-8 encoded */
  4563. int nByte, /* Maximum length of zSql in bytes. */
  4564. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4565. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4566. );
  4567. SQLITE_API int sqlite3_prepare_v3(
  4568. sqlite3 *db, /* Database handle */
  4569. const char *zSql, /* SQL statement, UTF-8 encoded */
  4570. int nByte, /* Maximum length of zSql in bytes. */
  4571. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4572. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4573. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4574. );
  4575. SQLITE_API int sqlite3_prepare16(
  4576. sqlite3 *db, /* Database handle */
  4577. const void *zSql, /* SQL statement, UTF-16 encoded */
  4578. int nByte, /* Maximum length of zSql in bytes. */
  4579. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4580. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4581. );
  4582. SQLITE_API int sqlite3_prepare16_v2(
  4583. sqlite3 *db, /* Database handle */
  4584. const void *zSql, /* SQL statement, UTF-16 encoded */
  4585. int nByte, /* Maximum length of zSql in bytes. */
  4586. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4587. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4588. );
  4589. SQLITE_API int sqlite3_prepare16_v3(
  4590. sqlite3 *db, /* Database handle */
  4591. const void *zSql, /* SQL statement, UTF-16 encoded */
  4592. int nByte, /* Maximum length of zSql in bytes. */
  4593. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  4594. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4595. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  4596. );
  4597. /*
  4598. ** CAPI3REF: Retrieving Statement SQL
  4599. ** METHOD: sqlite3_stmt
  4600. **
  4601. ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  4602. ** SQL text used to create [prepared statement] P if P was
  4603. ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
  4604. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4605. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  4606. ** string containing the SQL text of prepared statement P with
  4607. ** [bound parameters] expanded.
  4608. **
  4609. ** ^(For example, if a prepared statement is created using the SQL
  4610. ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  4611. ** and parameter :xyz is unbound, then sqlite3_sql() will return
  4612. ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  4613. ** will return "SELECT 2345,NULL".)^
  4614. **
  4615. ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  4616. ** is available to hold the result, or if the result would exceed the
  4617. ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  4618. **
  4619. ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  4620. ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
  4621. ** option causes sqlite3_expanded_sql() to always return NULL.
  4622. **
  4623. ** ^The string returned by sqlite3_sql(P) is managed by SQLite and is
  4624. ** automatically freed when the prepared statement is finalized.
  4625. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  4626. ** is obtained from [sqlite3_malloc()] and must be free by the application
  4627. ** by passing it to [sqlite3_free()].
  4628. */
  4629. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  4630. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  4631. /*
  4632. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  4633. ** METHOD: sqlite3_stmt
  4634. **
  4635. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  4636. ** and only if the [prepared statement] X makes no direct changes to
  4637. ** the content of the database file.
  4638. **
  4639. ** Note that [application-defined SQL functions] or
  4640. ** [virtual tables] might change the database indirectly as a side effect.
  4641. ** ^(For example, if an application defines a function "eval()" that
  4642. ** calls [sqlite3_exec()], then the following SQL statement would
  4643. ** change the database file through side-effects:
  4644. **
  4645. ** <blockquote><pre>
  4646. ** SELECT eval('DELETE FROM t1') FROM t2;
  4647. ** </pre></blockquote>
  4648. **
  4649. ** But because the [SELECT] statement does not change the database file
  4650. ** directly, sqlite3_stmt_readonly() would still return true.)^
  4651. **
  4652. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  4653. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  4654. ** since the statements themselves do not actually modify the database but
  4655. ** rather they control the timing of when other statements modify the
  4656. ** database. ^The [ATTACH] and [DETACH] statements also cause
  4657. ** sqlite3_stmt_readonly() to return true since, while those statements
  4658. ** change the configuration of a database connection, they do not make
  4659. ** changes to the content of the database files on disk.
  4660. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  4661. ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  4662. ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  4663. ** sqlite3_stmt_readonly() returns false for those commands.
  4664. */
  4665. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  4666. /*
  4667. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  4668. ** METHOD: sqlite3_stmt
  4669. **
  4670. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  4671. ** [prepared statement] S has been stepped at least once using
  4672. ** [sqlite3_step(S)] but has neither run to completion (returned
  4673. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  4674. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  4675. ** interface returns false if S is a NULL pointer. If S is not a
  4676. ** NULL pointer and is not a pointer to a valid [prepared statement]
  4677. ** object, then the behavior is undefined and probably undesirable.
  4678. **
  4679. ** This interface can be used in combination [sqlite3_next_stmt()]
  4680. ** to locate all prepared statements associated with a database
  4681. ** connection that are in need of being reset. This can be used,
  4682. ** for example, in diagnostic routines to search for prepared
  4683. ** statements that are holding a transaction open.
  4684. */
  4685. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  4686. /*
  4687. ** CAPI3REF: Dynamically Typed Value Object
  4688. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  4689. **
  4690. ** SQLite uses the sqlite3_value object to represent all values
  4691. ** that can be stored in a database table. SQLite uses dynamic typing
  4692. ** for the values it stores. ^Values stored in sqlite3_value objects
  4693. ** can be integers, floating point values, strings, BLOBs, or NULL.
  4694. **
  4695. ** An sqlite3_value object may be either "protected" or "unprotected".
  4696. ** Some interfaces require a protected sqlite3_value. Other interfaces
  4697. ** will accept either a protected or an unprotected sqlite3_value.
  4698. ** Every interface that accepts sqlite3_value arguments specifies
  4699. ** whether or not it requires a protected sqlite3_value. The
  4700. ** [sqlite3_value_dup()] interface can be used to construct a new
  4701. ** protected sqlite3_value from an unprotected sqlite3_value.
  4702. **
  4703. ** The terms "protected" and "unprotected" refer to whether or not
  4704. ** a mutex is held. An internal mutex is held for a protected
  4705. ** sqlite3_value object but no mutex is held for an unprotected
  4706. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  4707. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  4708. ** or if SQLite is run in one of reduced mutex modes
  4709. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  4710. ** then there is no distinction between protected and unprotected
  4711. ** sqlite3_value objects and they can be used interchangeably. However,
  4712. ** for maximum code portability it is recommended that applications
  4713. ** still make the distinction between protected and unprotected
  4714. ** sqlite3_value objects even when not strictly required.
  4715. **
  4716. ** ^The sqlite3_value objects that are passed as parameters into the
  4717. ** implementation of [application-defined SQL functions] are protected.
  4718. ** ^The sqlite3_value object returned by
  4719. ** [sqlite3_column_value()] is unprotected.
  4720. ** Unprotected sqlite3_value objects may only be used as arguments
  4721. ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
  4722. ** [sqlite3_value_dup()].
  4723. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  4724. ** interfaces require protected sqlite3_value objects.
  4725. */
  4726. typedef struct sqlite3_value sqlite3_value;
  4727. /*
  4728. ** CAPI3REF: SQL Function Context Object
  4729. **
  4730. ** The context in which an SQL function executes is stored in an
  4731. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  4732. ** is always first parameter to [application-defined SQL functions].
  4733. ** The application-defined SQL function implementation will pass this
  4734. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  4735. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  4736. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  4737. ** and/or [sqlite3_set_auxdata()].
  4738. */
  4739. typedef struct sqlite3_context sqlite3_context;
  4740. /*
  4741. ** CAPI3REF: Binding Values To Prepared Statements
  4742. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  4743. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  4744. ** METHOD: sqlite3_stmt
  4745. **
  4746. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  4747. ** literals may be replaced by a [parameter] that matches one of following
  4748. ** templates:
  4749. **
  4750. ** <ul>
  4751. ** <li> ?
  4752. ** <li> ?NNN
  4753. ** <li> :VVV
  4754. ** <li> @VVV
  4755. ** <li> $VVV
  4756. ** </ul>
  4757. **
  4758. ** In the templates above, NNN represents an integer literal,
  4759. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  4760. ** parameters (also called "host parameter names" or "SQL parameters")
  4761. ** can be set using the sqlite3_bind_*() routines defined here.
  4762. **
  4763. ** ^The first argument to the sqlite3_bind_*() routines is always
  4764. ** a pointer to the [sqlite3_stmt] object returned from
  4765. ** [sqlite3_prepare_v2()] or its variants.
  4766. **
  4767. ** ^The second argument is the index of the SQL parameter to be set.
  4768. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  4769. ** SQL parameter is used more than once, second and subsequent
  4770. ** occurrences have the same index as the first occurrence.
  4771. ** ^The index for named parameters can be looked up using the
  4772. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  4773. ** for "?NNN" parameters is the value of NNN.
  4774. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  4775. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  4776. **
  4777. ** ^The third argument is the value to bind to the parameter.
  4778. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4779. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  4780. ** is ignored and the end result is the same as sqlite3_bind_null().
  4781. **
  4782. ** ^(In those routines that have a fourth argument, its value is the
  4783. ** number of bytes in the parameter. To be clear: the value is the
  4784. ** number of <u>bytes</u> in the value, not the number of characters.)^
  4785. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  4786. ** is negative, then the length of the string is
  4787. ** the number of bytes up to the first zero terminator.
  4788. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  4789. ** the behavior is undefined.
  4790. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  4791. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  4792. ** that parameter must be the byte offset
  4793. ** where the NUL terminator would occur assuming the string were NUL
  4794. ** terminated. If any NUL characters occur at byte offsets less than
  4795. ** the value of the fourth parameter then the resulting string value will
  4796. ** contain embedded NULs. The result of expressions involving strings
  4797. ** with embedded NULs is undefined.
  4798. **
  4799. ** ^The fifth argument to the BLOB and string binding interfaces
  4800. ** is a destructor used to dispose of the BLOB or
  4801. ** string after SQLite has finished with it. ^The destructor is called
  4802. ** to dispose of the BLOB or string even if the call to bind API fails.
  4803. ** ^If the fifth argument is
  4804. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  4805. ** information is in static, unmanaged space and does not need to be freed.
  4806. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  4807. ** SQLite makes its own private copy of the data immediately, before
  4808. ** the sqlite3_bind_*() routine returns.
  4809. **
  4810. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  4811. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  4812. ** to specify the encoding of the text in the third parameter. If
  4813. ** the sixth argument to sqlite3_bind_text64() is not one of the
  4814. ** allowed values shown above, or if the text encoding is different
  4815. ** from the encoding specified by the sixth parameter, then the behavior
  4816. ** is undefined.
  4817. **
  4818. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  4819. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  4820. ** (just an integer to hold its size) while it is being processed.
  4821. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  4822. ** content is later written using
  4823. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  4824. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  4825. **
  4826. ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
  4827. ** [prepared statement] S to have an SQL value of NULL, but to also be
  4828. ** associated with the pointer P of type T. ^D is either a NULL pointer or
  4829. ** a pointer to a destructor function for P. ^SQLite will invoke the
  4830. ** destructor D with a single argument of P when it is finished using
  4831. ** P. The T parameter should be a static string, preferably a string
  4832. ** literal. The sqlite3_bind_pointer() routine is part of the
  4833. ** [pointer passing interface] added for SQLite 3.20.0.
  4834. **
  4835. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  4836. ** for the [prepared statement] or with a prepared statement for which
  4837. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  4838. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  4839. ** routine is passed a [prepared statement] that has been finalized, the
  4840. ** result is undefined and probably harmful.
  4841. **
  4842. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  4843. ** ^Unbound parameters are interpreted as NULL.
  4844. **
  4845. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  4846. ** [error code] if anything goes wrong.
  4847. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  4848. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  4849. ** [SQLITE_MAX_LENGTH].
  4850. ** ^[SQLITE_RANGE] is returned if the parameter
  4851. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  4852. **
  4853. ** See also: [sqlite3_bind_parameter_count()],
  4854. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  4855. */
  4856. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  4857. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  4858. void(*)(void*));
  4859. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  4860. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  4861. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  4862. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  4863. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  4864. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  4865. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  4866. void(*)(void*), unsigned char encoding);
  4867. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  4868. SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
  4869. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  4870. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  4871. /*
  4872. ** CAPI3REF: Number Of SQL Parameters
  4873. ** METHOD: sqlite3_stmt
  4874. **
  4875. ** ^This routine can be used to find the number of [SQL parameters]
  4876. ** in a [prepared statement]. SQL parameters are tokens of the
  4877. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  4878. ** placeholders for values that are [sqlite3_bind_blob | bound]
  4879. ** to the parameters at a later time.
  4880. **
  4881. ** ^(This routine actually returns the index of the largest (rightmost)
  4882. ** parameter. For all forms except ?NNN, this will correspond to the
  4883. ** number of unique parameters. If parameters of the ?NNN form are used,
  4884. ** there may be gaps in the list.)^
  4885. **
  4886. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4887. ** [sqlite3_bind_parameter_name()], and
  4888. ** [sqlite3_bind_parameter_index()].
  4889. */
  4890. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  4891. /*
  4892. ** CAPI3REF: Name Of A Host Parameter
  4893. ** METHOD: sqlite3_stmt
  4894. **
  4895. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  4896. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  4897. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  4898. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  4899. ** respectively.
  4900. ** In other words, the initial ":" or "$" or "@" or "?"
  4901. ** is included as part of the name.)^
  4902. ** ^Parameters of the form "?" without a following integer have no name
  4903. ** and are referred to as "nameless" or "anonymous parameters".
  4904. **
  4905. ** ^The first host parameter has an index of 1, not 0.
  4906. **
  4907. ** ^If the value N is out of range or if the N-th parameter is
  4908. ** nameless, then NULL is returned. ^The returned string is
  4909. ** always in UTF-8 encoding even if the named parameter was
  4910. ** originally specified as UTF-16 in [sqlite3_prepare16()],
  4911. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  4912. **
  4913. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4914. ** [sqlite3_bind_parameter_count()], and
  4915. ** [sqlite3_bind_parameter_index()].
  4916. */
  4917. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  4918. /*
  4919. ** CAPI3REF: Index Of A Parameter With A Given Name
  4920. ** METHOD: sqlite3_stmt
  4921. **
  4922. ** ^Return the index of an SQL parameter given its name. ^The
  4923. ** index value returned is suitable for use as the second
  4924. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  4925. ** is returned if no matching parameter is found. ^The parameter
  4926. ** name must be given in UTF-8 even if the original statement
  4927. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
  4928. ** [sqlite3_prepare16_v3()].
  4929. **
  4930. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  4931. ** [sqlite3_bind_parameter_count()], and
  4932. ** [sqlite3_bind_parameter_name()].
  4933. */
  4934. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  4935. /*
  4936. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  4937. ** METHOD: sqlite3_stmt
  4938. **
  4939. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  4940. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  4941. ** ^Use this routine to reset all host parameters to NULL.
  4942. */
  4943. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  4944. /*
  4945. ** CAPI3REF: Number Of Columns In A Result Set
  4946. ** METHOD: sqlite3_stmt
  4947. **
  4948. ** ^Return the number of columns in the result set returned by the
  4949. ** [prepared statement]. ^If this routine returns 0, that means the
  4950. ** [prepared statement] returns no data (for example an [UPDATE]).
  4951. ** ^However, just because this routine returns a positive number does not
  4952. ** mean that one or more rows of data will be returned. ^A SELECT statement
  4953. ** will always have a positive sqlite3_column_count() but depending on the
  4954. ** WHERE clause constraints and the table content, it might return no rows.
  4955. **
  4956. ** See also: [sqlite3_data_count()]
  4957. */
  4958. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  4959. /*
  4960. ** CAPI3REF: Column Names In A Result Set
  4961. ** METHOD: sqlite3_stmt
  4962. **
  4963. ** ^These routines return the name assigned to a particular column
  4964. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  4965. ** interface returns a pointer to a zero-terminated UTF-8 string
  4966. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  4967. ** UTF-16 string. ^The first parameter is the [prepared statement]
  4968. ** that implements the [SELECT] statement. ^The second parameter is the
  4969. ** column number. ^The leftmost column is number 0.
  4970. **
  4971. ** ^The returned string pointer is valid until either the [prepared statement]
  4972. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  4973. ** reprepared by the first call to [sqlite3_step()] for a particular run
  4974. ** or until the next call to
  4975. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  4976. **
  4977. ** ^If sqlite3_malloc() fails during the processing of either routine
  4978. ** (for example during a conversion from UTF-8 to UTF-16) then a
  4979. ** NULL pointer is returned.
  4980. **
  4981. ** ^The name of a result column is the value of the "AS" clause for
  4982. ** that column, if there is an AS clause. If there is no AS clause
  4983. ** then the name of the column is unspecified and may change from
  4984. ** one release of SQLite to the next.
  4985. */
  4986. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  4987. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  4988. /*
  4989. ** CAPI3REF: Source Of Data In A Query Result
  4990. ** METHOD: sqlite3_stmt
  4991. **
  4992. ** ^These routines provide a means to determine the database, table, and
  4993. ** table column that is the origin of a particular result column in
  4994. ** [SELECT] statement.
  4995. ** ^The name of the database or table or column can be returned as
  4996. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  4997. ** the database name, the _table_ routines return the table name, and
  4998. ** the origin_ routines return the column name.
  4999. ** ^The returned string is valid until the [prepared statement] is destroyed
  5000. ** using [sqlite3_finalize()] or until the statement is automatically
  5001. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5002. ** or until the same information is requested
  5003. ** again in a different encoding.
  5004. **
  5005. ** ^The names returned are the original un-aliased names of the
  5006. ** database, table, and column.
  5007. **
  5008. ** ^The first argument to these interfaces is a [prepared statement].
  5009. ** ^These functions return information about the Nth result column returned by
  5010. ** the statement, where N is the second function argument.
  5011. ** ^The left-most column is column 0 for these routines.
  5012. **
  5013. ** ^If the Nth column returned by the statement is an expression or
  5014. ** subquery and is not a column value, then all of these functions return
  5015. ** NULL. ^These routine might also return NULL if a memory allocation error
  5016. ** occurs. ^Otherwise, they return the name of the attached database, table,
  5017. ** or column that query result column was extracted from.
  5018. **
  5019. ** ^As with all other SQLite APIs, those whose names end with "16" return
  5020. ** UTF-16 encoded strings and the other functions return UTF-8.
  5021. **
  5022. ** ^These APIs are only available if the library was compiled with the
  5023. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  5024. **
  5025. ** If two or more threads call one or more of these routines against the same
  5026. ** prepared statement and column at the same time then the results are
  5027. ** undefined.
  5028. **
  5029. ** If two or more threads call one or more
  5030. ** [sqlite3_column_database_name | column metadata interfaces]
  5031. ** for the same [prepared statement] and result column
  5032. ** at the same time then the results are undefined.
  5033. */
  5034. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  5035. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  5036. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  5037. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  5038. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  5039. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  5040. /*
  5041. ** CAPI3REF: Declared Datatype Of A Query Result
  5042. ** METHOD: sqlite3_stmt
  5043. **
  5044. ** ^(The first parameter is a [prepared statement].
  5045. ** If this statement is a [SELECT] statement and the Nth column of the
  5046. ** returned result set of that [SELECT] is a table column (not an
  5047. ** expression or subquery) then the declared type of the table
  5048. ** column is returned.)^ ^If the Nth column of the result set is an
  5049. ** expression or subquery, then a NULL pointer is returned.
  5050. ** ^The returned string is always UTF-8 encoded.
  5051. **
  5052. ** ^(For example, given the database schema:
  5053. **
  5054. ** CREATE TABLE t1(c1 VARIANT);
  5055. **
  5056. ** and the following statement to be compiled:
  5057. **
  5058. ** SELECT c1 + 1, c1 FROM t1;
  5059. **
  5060. ** this routine would return the string "VARIANT" for the second result
  5061. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  5062. **
  5063. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  5064. ** is declared to contain a particular type does not mean that the
  5065. ** data stored in that column is of the declared type. SQLite is
  5066. ** strongly typed, but the typing is dynamic not static. ^Type
  5067. ** is associated with individual values, not with the containers
  5068. ** used to hold those values.
  5069. */
  5070. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  5071. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  5072. /*
  5073. ** CAPI3REF: Evaluate An SQL Statement
  5074. ** METHOD: sqlite3_stmt
  5075. **
  5076. ** After a [prepared statement] has been prepared using any of
  5077. ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
  5078. ** or [sqlite3_prepare16_v3()] or one of the legacy
  5079. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  5080. ** must be called one or more times to evaluate the statement.
  5081. **
  5082. ** The details of the behavior of the sqlite3_step() interface depend
  5083. ** on whether the statement was prepared using the newer "vX" interfaces
  5084. ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
  5085. ** [sqlite3_prepare16_v2()] or the older legacy
  5086. ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  5087. ** new "vX" interface is recommended for new applications but the legacy
  5088. ** interface will continue to be supported.
  5089. **
  5090. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  5091. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  5092. ** ^With the "v2" interface, any of the other [result codes] or
  5093. ** [extended result codes] might be returned as well.
  5094. **
  5095. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  5096. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  5097. ** or occurs outside of an explicit transaction, then you can retry the
  5098. ** statement. If the statement is not a [COMMIT] and occurs within an
  5099. ** explicit transaction then you should rollback the transaction before
  5100. ** continuing.
  5101. **
  5102. ** ^[SQLITE_DONE] means that the statement has finished executing
  5103. ** successfully. sqlite3_step() should not be called again on this virtual
  5104. ** machine without first calling [sqlite3_reset()] to reset the virtual
  5105. ** machine back to its initial state.
  5106. **
  5107. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  5108. ** is returned each time a new row of data is ready for processing by the
  5109. ** caller. The values may be accessed using the [column access functions].
  5110. ** sqlite3_step() is called again to retrieve the next row of data.
  5111. **
  5112. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  5113. ** violation) has occurred. sqlite3_step() should not be called again on
  5114. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  5115. ** ^With the legacy interface, a more specific error code (for example,
  5116. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  5117. ** can be obtained by calling [sqlite3_reset()] on the
  5118. ** [prepared statement]. ^In the "v2" interface,
  5119. ** the more specific error code is returned directly by sqlite3_step().
  5120. **
  5121. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  5122. ** Perhaps it was called on a [prepared statement] that has
  5123. ** already been [sqlite3_finalize | finalized] or on one that had
  5124. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  5125. ** be the case that the same database connection is being used by two or
  5126. ** more threads at the same moment in time.
  5127. **
  5128. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  5129. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  5130. ** other than [SQLITE_ROW] before any subsequent invocation of
  5131. ** sqlite3_step(). Failure to reset the prepared statement using
  5132. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  5133. ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
  5134. ** sqlite3_step() began
  5135. ** calling [sqlite3_reset()] automatically in this circumstance rather
  5136. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  5137. ** break because any application that ever receives an SQLITE_MISUSE error
  5138. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  5139. ** can be used to restore the legacy behavior.
  5140. **
  5141. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  5142. ** API always returns a generic error code, [SQLITE_ERROR], following any
  5143. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  5144. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  5145. ** specific [error codes] that better describes the error.
  5146. ** We admit that this is a goofy design. The problem has been fixed
  5147. ** with the "v2" interface. If you prepare all of your SQL statements
  5148. ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
  5149. ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
  5150. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  5151. ** then the more specific [error codes] are returned directly
  5152. ** by sqlite3_step(). The use of the "vX" interfaces is recommended.
  5153. */
  5154. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  5155. /*
  5156. ** CAPI3REF: Number of columns in a result set
  5157. ** METHOD: sqlite3_stmt
  5158. **
  5159. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  5160. ** current row of the result set of [prepared statement] P.
  5161. ** ^If prepared statement P does not have results ready to return
  5162. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  5163. ** interfaces) then sqlite3_data_count(P) returns 0.
  5164. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  5165. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  5166. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  5167. ** will return non-zero if previous call to [sqlite3_step](P) returned
  5168. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  5169. ** where it always returns zero since each step of that multi-step
  5170. ** pragma returns 0 columns of data.
  5171. **
  5172. ** See also: [sqlite3_column_count()]
  5173. */
  5174. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  5175. /*
  5176. ** CAPI3REF: Fundamental Datatypes
  5177. ** KEYWORDS: SQLITE_TEXT
  5178. **
  5179. ** ^(Every value in SQLite has one of five fundamental datatypes:
  5180. **
  5181. ** <ul>
  5182. ** <li> 64-bit signed integer
  5183. ** <li> 64-bit IEEE floating point number
  5184. ** <li> string
  5185. ** <li> BLOB
  5186. ** <li> NULL
  5187. ** </ul>)^
  5188. **
  5189. ** These constants are codes for each of those types.
  5190. **
  5191. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  5192. ** for a completely different meaning. Software that links against both
  5193. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  5194. ** SQLITE_TEXT.
  5195. */
  5196. #define SQLITE_INTEGER 1
  5197. #define SQLITE_FLOAT 2
  5198. #define SQLITE_BLOB 4
  5199. #define SQLITE_NULL 5
  5200. #ifdef SQLITE_TEXT
  5201. # undef SQLITE_TEXT
  5202. #else
  5203. # define SQLITE_TEXT 3
  5204. #endif
  5205. #define SQLITE3_TEXT 3
  5206. /*
  5207. ** CAPI3REF: Result Values From A Query
  5208. ** KEYWORDS: {column access functions}
  5209. ** METHOD: sqlite3_stmt
  5210. **
  5211. ** <b>Summary:</b>
  5212. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5213. ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
  5214. ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
  5215. ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
  5216. ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
  5217. ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
  5218. ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
  5219. ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
  5220. ** [sqlite3_value|unprotected sqlite3_value] object.
  5221. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5222. ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
  5223. ** or a UTF-8 TEXT result in bytes
  5224. ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
  5225. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5226. ** TEXT in bytes
  5227. ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
  5228. ** datatype of the result
  5229. ** </table></blockquote>
  5230. **
  5231. ** <b>Details:</b>
  5232. **
  5233. ** ^These routines return information about a single column of the current
  5234. ** result row of a query. ^In every case the first argument is a pointer
  5235. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  5236. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  5237. ** and the second argument is the index of the column for which information
  5238. ** should be returned. ^The leftmost column of the result set has the index 0.
  5239. ** ^The number of columns in the result can be determined using
  5240. ** [sqlite3_column_count()].
  5241. **
  5242. ** If the SQL statement does not currently point to a valid row, or if the
  5243. ** column index is out of range, the result is undefined.
  5244. ** These routines may only be called when the most recent call to
  5245. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  5246. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  5247. ** If any of these routines are called after [sqlite3_reset()] or
  5248. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  5249. ** something other than [SQLITE_ROW], the results are undefined.
  5250. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  5251. ** are called from a different thread while any of these routines
  5252. ** are pending, then the results are undefined.
  5253. **
  5254. ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
  5255. ** each return the value of a result column in a specific data format. If
  5256. ** the result column is not initially in the requested format (for example,
  5257. ** if the query returns an integer but the sqlite3_column_text() interface
  5258. ** is used to extract the value) then an automatic type conversion is performed.
  5259. **
  5260. ** ^The sqlite3_column_type() routine returns the
  5261. ** [SQLITE_INTEGER | datatype code] for the initial data type
  5262. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  5263. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
  5264. ** The return value of sqlite3_column_type() can be used to decide which
  5265. ** of the first six interface should be used to extract the column value.
  5266. ** The value returned by sqlite3_column_type() is only meaningful if no
  5267. ** automatic type conversions have occurred for the value in question.
  5268. ** After a type conversion, the result of calling sqlite3_column_type()
  5269. ** is undefined, though harmless. Future
  5270. ** versions of SQLite may change the behavior of sqlite3_column_type()
  5271. ** following a type conversion.
  5272. **
  5273. ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
  5274. ** or sqlite3_column_bytes16() interfaces can be used to determine the size
  5275. ** of that BLOB or string.
  5276. **
  5277. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  5278. ** routine returns the number of bytes in that BLOB or string.
  5279. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  5280. ** the string to UTF-8 and then returns the number of bytes.
  5281. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  5282. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  5283. ** the number of bytes in that string.
  5284. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  5285. **
  5286. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  5287. ** routine returns the number of bytes in that BLOB or string.
  5288. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  5289. ** the string to UTF-16 and then returns the number of bytes.
  5290. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  5291. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  5292. ** the number of bytes in that string.
  5293. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  5294. **
  5295. ** ^The values returned by [sqlite3_column_bytes()] and
  5296. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  5297. ** of the string. ^For clarity: the values returned by
  5298. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  5299. ** bytes in the string, not the number of characters.
  5300. **
  5301. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  5302. ** even empty strings, are always zero-terminated. ^The return
  5303. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  5304. **
  5305. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  5306. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  5307. ** an unprotected sqlite3_value object may only be used safely with
  5308. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  5309. ** If the [unprotected sqlite3_value] object returned by
  5310. ** [sqlite3_column_value()] is used in any other way, including calls
  5311. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  5312. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  5313. ** Hence, the sqlite3_column_value() interface
  5314. ** is normally only useful within the implementation of
  5315. ** [application-defined SQL functions] or [virtual tables], not within
  5316. ** top-level application code.
  5317. **
  5318. ** The these routines may attempt to convert the datatype of the result.
  5319. ** ^For example, if the internal representation is FLOAT and a text result
  5320. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  5321. ** conversion automatically. ^(The following table details the conversions
  5322. ** that are applied:
  5323. **
  5324. ** <blockquote>
  5325. ** <table border="1">
  5326. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  5327. **
  5328. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  5329. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  5330. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  5331. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  5332. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  5333. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  5334. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  5335. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  5336. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  5337. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  5338. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  5339. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  5340. ** <tr><td> TEXT <td> BLOB <td> No change
  5341. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  5342. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  5343. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  5344. ** </table>
  5345. ** </blockquote>)^
  5346. **
  5347. ** Note that when type conversions occur, pointers returned by prior
  5348. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  5349. ** sqlite3_column_text16() may be invalidated.
  5350. ** Type conversions and pointer invalidations might occur
  5351. ** in the following cases:
  5352. **
  5353. ** <ul>
  5354. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  5355. ** sqlite3_column_text16() is called. A zero-terminator might
  5356. ** need to be added to the string.</li>
  5357. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  5358. ** sqlite3_column_text16() is called. The content must be converted
  5359. ** to UTF-16.</li>
  5360. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  5361. ** sqlite3_column_text() is called. The content must be converted
  5362. ** to UTF-8.</li>
  5363. ** </ul>
  5364. **
  5365. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  5366. ** not invalidate a prior pointer, though of course the content of the buffer
  5367. ** that the prior pointer references will have been modified. Other kinds
  5368. ** of conversion are done in place when it is possible, but sometimes they
  5369. ** are not possible and in those cases prior pointers are invalidated.
  5370. **
  5371. ** The safest policy is to invoke these routines
  5372. ** in one of the following ways:
  5373. **
  5374. ** <ul>
  5375. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  5376. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  5377. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  5378. ** </ul>
  5379. **
  5380. ** In other words, you should call sqlite3_column_text(),
  5381. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  5382. ** into the desired format, then invoke sqlite3_column_bytes() or
  5383. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  5384. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  5385. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  5386. ** with calls to sqlite3_column_bytes().
  5387. **
  5388. ** ^The pointers returned are valid until a type conversion occurs as
  5389. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  5390. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  5391. ** and BLOBs is freed automatically. Do not pass the pointers returned
  5392. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  5393. ** [sqlite3_free()].
  5394. **
  5395. ** ^(If a memory allocation error occurs during the evaluation of any
  5396. ** of these routines, a default value is returned. The default value
  5397. ** is either the integer 0, the floating point number 0.0, or a NULL
  5398. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  5399. ** [SQLITE_NOMEM].)^
  5400. */
  5401. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  5402. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  5403. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  5404. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  5405. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  5406. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  5407. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  5408. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  5409. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  5410. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  5411. /*
  5412. ** CAPI3REF: Destroy A Prepared Statement Object
  5413. ** DESTRUCTOR: sqlite3_stmt
  5414. **
  5415. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  5416. ** ^If the most recent evaluation of the statement encountered no errors
  5417. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  5418. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  5419. ** sqlite3_finalize(S) returns the appropriate [error code] or
  5420. ** [extended error code].
  5421. **
  5422. ** ^The sqlite3_finalize(S) routine can be called at any point during
  5423. ** the life cycle of [prepared statement] S:
  5424. ** before statement S is ever evaluated, after
  5425. ** one or more calls to [sqlite3_reset()], or after any call
  5426. ** to [sqlite3_step()] regardless of whether or not the statement has
  5427. ** completed execution.
  5428. **
  5429. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  5430. **
  5431. ** The application must finalize every [prepared statement] in order to avoid
  5432. ** resource leaks. It is a grievous error for the application to try to use
  5433. ** a prepared statement after it has been finalized. Any use of a prepared
  5434. ** statement after it has been finalized can result in undefined and
  5435. ** undesirable behavior such as segfaults and heap corruption.
  5436. */
  5437. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  5438. /*
  5439. ** CAPI3REF: Reset A Prepared Statement Object
  5440. ** METHOD: sqlite3_stmt
  5441. **
  5442. ** The sqlite3_reset() function is called to reset a [prepared statement]
  5443. ** object back to its initial state, ready to be re-executed.
  5444. ** ^Any SQL statement variables that had values bound to them using
  5445. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  5446. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  5447. **
  5448. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  5449. ** back to the beginning of its program.
  5450. **
  5451. ** ^If the most recent call to [sqlite3_step(S)] for the
  5452. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  5453. ** or if [sqlite3_step(S)] has never before been called on S,
  5454. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  5455. **
  5456. ** ^If the most recent call to [sqlite3_step(S)] for the
  5457. ** [prepared statement] S indicated an error, then
  5458. ** [sqlite3_reset(S)] returns an appropriate [error code].
  5459. **
  5460. ** ^The [sqlite3_reset(S)] interface does not change the values
  5461. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  5462. */
  5463. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  5464. /*
  5465. ** CAPI3REF: Create Or Redefine SQL Functions
  5466. ** KEYWORDS: {function creation routines}
  5467. ** KEYWORDS: {application-defined SQL function}
  5468. ** KEYWORDS: {application-defined SQL functions}
  5469. ** METHOD: sqlite3
  5470. **
  5471. ** ^These functions (collectively known as "function creation routines")
  5472. ** are used to add SQL functions or aggregates or to redefine the behavior
  5473. ** of existing SQL functions or aggregates. The only differences between
  5474. ** these routines are the text encoding expected for
  5475. ** the second parameter (the name of the function being created)
  5476. ** and the presence or absence of a destructor callback for
  5477. ** the application data pointer.
  5478. **
  5479. ** ^The first parameter is the [database connection] to which the SQL
  5480. ** function is to be added. ^If an application uses more than one database
  5481. ** connection then application-defined SQL functions must be added
  5482. ** to each database connection separately.
  5483. **
  5484. ** ^The second parameter is the name of the SQL function to be created or
  5485. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  5486. ** representation, exclusive of the zero-terminator. ^Note that the name
  5487. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  5488. ** ^Any attempt to create a function with a longer name
  5489. ** will result in [SQLITE_MISUSE] being returned.
  5490. **
  5491. ** ^The third parameter (nArg)
  5492. ** is the number of arguments that the SQL function or
  5493. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  5494. ** aggregate may take any number of arguments between 0 and the limit
  5495. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  5496. ** parameter is less than -1 or greater than 127 then the behavior is
  5497. ** undefined.
  5498. **
  5499. ** ^The fourth parameter, eTextRep, specifies what
  5500. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  5501. ** its parameters. The application should set this parameter to
  5502. ** [SQLITE_UTF16LE] if the function implementation invokes
  5503. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  5504. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  5505. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  5506. ** otherwise. ^The same SQL function may be registered multiple times using
  5507. ** different preferred text encodings, with different implementations for
  5508. ** each encoding.
  5509. ** ^When multiple implementations of the same function are available, SQLite
  5510. ** will pick the one that involves the least amount of data conversion.
  5511. **
  5512. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  5513. ** to signal that the function will always return the same result given
  5514. ** the same inputs within a single SQL statement. Most SQL functions are
  5515. ** deterministic. The built-in [random()] SQL function is an example of a
  5516. ** function that is not deterministic. The SQLite query planner is able to
  5517. ** perform additional optimizations on deterministic functions, so use
  5518. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  5519. **
  5520. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  5521. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  5522. **
  5523. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  5524. ** pointers to C-language functions that implement the SQL function or
  5525. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  5526. ** callback only; NULL pointers must be passed as the xStep and xFinal
  5527. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  5528. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  5529. ** SQL function or aggregate, pass NULL pointers for all three function
  5530. ** callbacks.
  5531. **
  5532. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  5533. ** then it is destructor for the application data pointer.
  5534. ** The destructor is invoked when the function is deleted, either by being
  5535. ** overloaded or when the database connection closes.)^
  5536. ** ^The destructor is also invoked if the call to
  5537. ** sqlite3_create_function_v2() fails.
  5538. ** ^When the destructor callback of the tenth parameter is invoked, it
  5539. ** is passed a single argument which is a copy of the application data
  5540. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  5541. **
  5542. ** ^It is permitted to register multiple implementations of the same
  5543. ** functions with the same name but with either differing numbers of
  5544. ** arguments or differing preferred text encodings. ^SQLite will use
  5545. ** the implementation that most closely matches the way in which the
  5546. ** SQL function is used. ^A function implementation with a non-negative
  5547. ** nArg parameter is a better match than a function implementation with
  5548. ** a negative nArg. ^A function where the preferred text encoding
  5549. ** matches the database encoding is a better
  5550. ** match than a function where the encoding is different.
  5551. ** ^A function where the encoding difference is between UTF16le and UTF16be
  5552. ** is a closer match than a function where the encoding difference is
  5553. ** between UTF8 and UTF16.
  5554. **
  5555. ** ^Built-in functions may be overloaded by new application-defined functions.
  5556. **
  5557. ** ^An application-defined function is permitted to call other
  5558. ** SQLite interfaces. However, such calls must not
  5559. ** close the database connection nor finalize or reset the prepared
  5560. ** statement in which the function is running.
  5561. */
  5562. SQLITE_API int sqlite3_create_function(
  5563. sqlite3 *db,
  5564. const char *zFunctionName,
  5565. int nArg,
  5566. int eTextRep,
  5567. void *pApp,
  5568. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5569. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5570. void (*xFinal)(sqlite3_context*)
  5571. );
  5572. SQLITE_API int sqlite3_create_function16(
  5573. sqlite3 *db,
  5574. const void *zFunctionName,
  5575. int nArg,
  5576. int eTextRep,
  5577. void *pApp,
  5578. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5579. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5580. void (*xFinal)(sqlite3_context*)
  5581. );
  5582. SQLITE_API int sqlite3_create_function_v2(
  5583. sqlite3 *db,
  5584. const char *zFunctionName,
  5585. int nArg,
  5586. int eTextRep,
  5587. void *pApp,
  5588. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  5589. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  5590. void (*xFinal)(sqlite3_context*),
  5591. void(*xDestroy)(void*)
  5592. );
  5593. /*
  5594. ** CAPI3REF: Text Encodings
  5595. **
  5596. ** These constant define integer codes that represent the various
  5597. ** text encodings supported by SQLite.
  5598. */
  5599. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  5600. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  5601. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  5602. #define SQLITE_UTF16 4 /* Use native byte order */
  5603. #define SQLITE_ANY 5 /* Deprecated */
  5604. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  5605. /*
  5606. ** CAPI3REF: Function Flags
  5607. **
  5608. ** These constants may be ORed together with the
  5609. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  5610. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  5611. ** [sqlite3_create_function_v2()].
  5612. */
  5613. #define SQLITE_DETERMINISTIC 0x800
  5614. /*
  5615. ** CAPI3REF: Deprecated Functions
  5616. ** DEPRECATED
  5617. **
  5618. ** These functions are [deprecated]. In order to maintain
  5619. ** backwards compatibility with older code, these functions continue
  5620. ** to be supported. However, new applications should avoid
  5621. ** the use of these functions. To encourage programmers to avoid
  5622. ** these functions, we will not explain what they do.
  5623. */
  5624. #ifndef SQLITE_OMIT_DEPRECATED
  5625. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  5626. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  5627. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  5628. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  5629. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  5630. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  5631. void*,sqlite3_int64);
  5632. #endif
  5633. /*
  5634. ** CAPI3REF: Obtaining SQL Values
  5635. ** METHOD: sqlite3_value
  5636. **
  5637. ** <b>Summary:</b>
  5638. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5639. ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
  5640. ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
  5641. ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
  5642. ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
  5643. ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
  5644. ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
  5645. ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
  5646. ** the native byteorder
  5647. ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
  5648. ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
  5649. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5650. ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
  5651. ** or a UTF-8 TEXT in bytes
  5652. ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
  5653. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5654. ** TEXT in bytes
  5655. ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
  5656. ** datatype of the value
  5657. ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
  5658. ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
  5659. ** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
  5660. ** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
  5661. ** against a virtual table.
  5662. ** </table></blockquote>
  5663. **
  5664. ** <b>Details:</b>
  5665. **
  5666. ** These routines extract type, size, and content information from
  5667. ** [protected sqlite3_value] objects. Protected sqlite3_value objects
  5668. ** are used to pass parameter information into implementation of
  5669. ** [application-defined SQL functions] and [virtual tables].
  5670. **
  5671. ** These routines work only with [protected sqlite3_value] objects.
  5672. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  5673. ** is not threadsafe.
  5674. **
  5675. ** ^These routines work just like the corresponding [column access functions]
  5676. ** except that these routines take a single [protected sqlite3_value] object
  5677. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  5678. **
  5679. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  5680. ** in the native byte-order of the host machine. ^The
  5681. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  5682. ** extract UTF-16 strings as big-endian and little-endian respectively.
  5683. **
  5684. ** ^If [sqlite3_value] object V was initialized
  5685. ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
  5686. ** and if X and Y are strings that compare equal according to strcmp(X,Y),
  5687. ** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
  5688. ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
  5689. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  5690. **
  5691. ** ^(The sqlite3_value_type(V) interface returns the
  5692. ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
  5693. ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
  5694. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
  5695. ** Other interfaces might change the datatype for an sqlite3_value object.
  5696. ** For example, if the datatype is initially SQLITE_INTEGER and
  5697. ** sqlite3_value_text(V) is called to extract a text value for that
  5698. ** integer, then subsequent calls to sqlite3_value_type(V) might return
  5699. ** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
  5700. ** occurs is undefined and may change from one release of SQLite to the next.
  5701. **
  5702. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  5703. ** numeric affinity to the value. This means that an attempt is
  5704. ** made to convert the value to an integer or floating point. If
  5705. ** such a conversion is possible without loss of information (in other
  5706. ** words, if the value is a string that looks like a number)
  5707. ** then the conversion is performed. Otherwise no conversion occurs.
  5708. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  5709. **
  5710. ** ^Within the [xUpdate] method of a [virtual table], the
  5711. ** sqlite3_value_nochange(X) interface returns true if and only if
  5712. ** the column corresponding to X is unchanged by the UPDATE operation
  5713. ** that the xUpdate method call was invoked to implement and if
  5714. ** and the prior [xColumn] method call that was invoked to extracted
  5715. ** the value for that column returned without setting a result (probably
  5716. ** because it queried [sqlite3_vtab_nochange()] and found that the column
  5717. ** was unchanging). ^Within an [xUpdate] method, any value for which
  5718. ** sqlite3_value_nochange(X) is true will in all other respects appear
  5719. ** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
  5720. ** than within an [xUpdate] method call for an UPDATE statement, then
  5721. ** the return value is arbitrary and meaningless.
  5722. **
  5723. ** Please pay particular attention to the fact that the pointer returned
  5724. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  5725. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  5726. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  5727. ** or [sqlite3_value_text16()].
  5728. **
  5729. ** These routines must be called from the same thread as
  5730. ** the SQL function that supplied the [sqlite3_value*] parameters.
  5731. */
  5732. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  5733. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  5734. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  5735. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  5736. SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
  5737. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  5738. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  5739. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  5740. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  5741. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  5742. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  5743. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  5744. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  5745. SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
  5746. /*
  5747. ** CAPI3REF: Finding The Subtype Of SQL Values
  5748. ** METHOD: sqlite3_value
  5749. **
  5750. ** The sqlite3_value_subtype(V) function returns the subtype for
  5751. ** an [application-defined SQL function] argument V. The subtype
  5752. ** information can be used to pass a limited amount of context from
  5753. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  5754. ** routine to set the subtype for the return value of an SQL function.
  5755. */
  5756. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  5757. /*
  5758. ** CAPI3REF: Copy And Free SQL Values
  5759. ** METHOD: sqlite3_value
  5760. **
  5761. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  5762. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  5763. ** is a [protected sqlite3_value] object even if the input is not.
  5764. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  5765. ** memory allocation fails.
  5766. **
  5767. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  5768. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  5769. ** then sqlite3_value_free(V) is a harmless no-op.
  5770. */
  5771. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  5772. SQLITE_API void sqlite3_value_free(sqlite3_value*);
  5773. /*
  5774. ** CAPI3REF: Obtain Aggregate Function Context
  5775. ** METHOD: sqlite3_context
  5776. **
  5777. ** Implementations of aggregate SQL functions use this
  5778. ** routine to allocate memory for storing their state.
  5779. **
  5780. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  5781. ** for a particular aggregate function, SQLite
  5782. ** allocates N of memory, zeroes out that memory, and returns a pointer
  5783. ** to the new memory. ^On second and subsequent calls to
  5784. ** sqlite3_aggregate_context() for the same aggregate function instance,
  5785. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  5786. ** called once for each invocation of the xStep callback and then one
  5787. ** last time when the xFinal callback is invoked. ^(When no rows match
  5788. ** an aggregate query, the xStep() callback of the aggregate function
  5789. ** implementation is never called and xFinal() is called exactly once.
  5790. ** In those cases, sqlite3_aggregate_context() might be called for the
  5791. ** first time from within xFinal().)^
  5792. **
  5793. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  5794. ** when first called if N is less than or equal to zero or if a memory
  5795. ** allocate error occurs.
  5796. **
  5797. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  5798. ** determined by the N parameter on first successful call. Changing the
  5799. ** value of N in subsequent call to sqlite3_aggregate_context() within
  5800. ** the same aggregate function instance will not resize the memory
  5801. ** allocation.)^ Within the xFinal callback, it is customary to set
  5802. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  5803. ** pointless memory allocations occur.
  5804. **
  5805. ** ^SQLite automatically frees the memory allocated by
  5806. ** sqlite3_aggregate_context() when the aggregate query concludes.
  5807. **
  5808. ** The first parameter must be a copy of the
  5809. ** [sqlite3_context | SQL function context] that is the first parameter
  5810. ** to the xStep or xFinal callback routine that implements the aggregate
  5811. ** function.
  5812. **
  5813. ** This routine must be called from the same thread in which
  5814. ** the aggregate SQL function is running.
  5815. */
  5816. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  5817. /*
  5818. ** CAPI3REF: User Data For Functions
  5819. ** METHOD: sqlite3_context
  5820. **
  5821. ** ^The sqlite3_user_data() interface returns a copy of
  5822. ** the pointer that was the pUserData parameter (the 5th parameter)
  5823. ** of the [sqlite3_create_function()]
  5824. ** and [sqlite3_create_function16()] routines that originally
  5825. ** registered the application defined function.
  5826. **
  5827. ** This routine must be called from the same thread in which
  5828. ** the application-defined function is running.
  5829. */
  5830. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  5831. /*
  5832. ** CAPI3REF: Database Connection For Functions
  5833. ** METHOD: sqlite3_context
  5834. **
  5835. ** ^The sqlite3_context_db_handle() interface returns a copy of
  5836. ** the pointer to the [database connection] (the 1st parameter)
  5837. ** of the [sqlite3_create_function()]
  5838. ** and [sqlite3_create_function16()] routines that originally
  5839. ** registered the application defined function.
  5840. */
  5841. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  5842. /*
  5843. ** CAPI3REF: Function Auxiliary Data
  5844. ** METHOD: sqlite3_context
  5845. **
  5846. ** These functions may be used by (non-aggregate) SQL functions to
  5847. ** associate metadata with argument values. If the same value is passed to
  5848. ** multiple invocations of the same SQL function during query execution, under
  5849. ** some circumstances the associated metadata may be preserved. An example
  5850. ** of where this might be useful is in a regular-expression matching
  5851. ** function. The compiled version of the regular expression can be stored as
  5852. ** metadata associated with the pattern string.
  5853. ** Then as long as the pattern string remains the same,
  5854. ** the compiled regular expression can be reused on multiple
  5855. ** invocations of the same function.
  5856. **
  5857. ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  5858. ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  5859. ** value to the application-defined function. ^N is zero for the left-most
  5860. ** function argument. ^If there is no metadata
  5861. ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  5862. ** returns a NULL pointer.
  5863. **
  5864. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  5865. ** argument of the application-defined function. ^Subsequent
  5866. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  5867. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  5868. ** NULL if the metadata has been discarded.
  5869. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  5870. ** SQLite will invoke the destructor function X with parameter P exactly
  5871. ** once, when the metadata is discarded.
  5872. ** SQLite is free to discard the metadata at any time, including: <ul>
  5873. ** <li> ^(when the corresponding function parameter changes)^, or
  5874. ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  5875. ** SQL statement)^, or
  5876. ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  5877. ** parameter)^, or
  5878. ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
  5879. ** allocation error occurs.)^ </ul>
  5880. **
  5881. ** Note the last bullet in particular. The destructor X in
  5882. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  5883. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  5884. ** should be called near the end of the function implementation and the
  5885. ** function implementation should not make any use of P after
  5886. ** sqlite3_set_auxdata() has been called.
  5887. **
  5888. ** ^(In practice, metadata is preserved between function calls for
  5889. ** function parameters that are compile-time constants, including literal
  5890. ** values and [parameters] and expressions composed from the same.)^
  5891. **
  5892. ** The value of the N parameter to these interfaces should be non-negative.
  5893. ** Future enhancements may make use of negative N values to define new
  5894. ** kinds of function caching behavior.
  5895. **
  5896. ** These routines must be called from the same thread in which
  5897. ** the SQL function is running.
  5898. */
  5899. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  5900. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  5901. /*
  5902. ** CAPI3REF: Constants Defining Special Destructor Behavior
  5903. **
  5904. ** These are special values for the destructor that is passed in as the
  5905. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  5906. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  5907. ** and will never change. It does not need to be destroyed. ^The
  5908. ** SQLITE_TRANSIENT value means that the content will likely change in
  5909. ** the near future and that SQLite should make its own private copy of
  5910. ** the content before returning.
  5911. **
  5912. ** The typedef is necessary to work around problems in certain
  5913. ** C++ compilers.
  5914. */
  5915. typedef void (*sqlite3_destructor_type)(void*);
  5916. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  5917. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  5918. /*
  5919. ** CAPI3REF: Setting The Result Of An SQL Function
  5920. ** METHOD: sqlite3_context
  5921. **
  5922. ** These routines are used by the xFunc or xFinal callbacks that
  5923. ** implement SQL functions and aggregates. See
  5924. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  5925. ** for additional information.
  5926. **
  5927. ** These functions work very much like the [parameter binding] family of
  5928. ** functions used to bind values to host parameters in prepared statements.
  5929. ** Refer to the [SQL parameter] documentation for additional information.
  5930. **
  5931. ** ^The sqlite3_result_blob() interface sets the result from
  5932. ** an application-defined function to be the BLOB whose content is pointed
  5933. ** to by the second parameter and which is N bytes long where N is the
  5934. ** third parameter.
  5935. **
  5936. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  5937. ** interfaces set the result of the application-defined function to be
  5938. ** a BLOB containing all zero bytes and N bytes in size.
  5939. **
  5940. ** ^The sqlite3_result_double() interface sets the result from
  5941. ** an application-defined function to be a floating point value specified
  5942. ** by its 2nd argument.
  5943. **
  5944. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  5945. ** cause the implemented SQL function to throw an exception.
  5946. ** ^SQLite uses the string pointed to by the
  5947. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  5948. ** as the text of an error message. ^SQLite interprets the error
  5949. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  5950. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  5951. ** byte order. ^If the third parameter to sqlite3_result_error()
  5952. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  5953. ** message all text up through the first zero character.
  5954. ** ^If the third parameter to sqlite3_result_error() or
  5955. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  5956. ** bytes (not characters) from the 2nd parameter as the error message.
  5957. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  5958. ** routines make a private copy of the error message text before
  5959. ** they return. Hence, the calling function can deallocate or
  5960. ** modify the text after they return without harm.
  5961. ** ^The sqlite3_result_error_code() function changes the error code
  5962. ** returned by SQLite as a result of an error in a function. ^By default,
  5963. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  5964. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  5965. **
  5966. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  5967. ** error indicating that a string or BLOB is too long to represent.
  5968. **
  5969. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  5970. ** error indicating that a memory allocation failed.
  5971. **
  5972. ** ^The sqlite3_result_int() interface sets the return value
  5973. ** of the application-defined function to be the 32-bit signed integer
  5974. ** value given in the 2nd argument.
  5975. ** ^The sqlite3_result_int64() interface sets the return value
  5976. ** of the application-defined function to be the 64-bit signed integer
  5977. ** value given in the 2nd argument.
  5978. **
  5979. ** ^The sqlite3_result_null() interface sets the return value
  5980. ** of the application-defined function to be NULL.
  5981. **
  5982. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  5983. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  5984. ** set the return value of the application-defined function to be
  5985. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  5986. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  5987. ** ^The sqlite3_result_text64() interface sets the return value of an
  5988. ** application-defined function to be a text string in an encoding
  5989. ** specified by the fifth (and last) parameter, which must be one
  5990. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  5991. ** ^SQLite takes the text result from the application from
  5992. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  5993. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  5994. ** is negative, then SQLite takes result text from the 2nd parameter
  5995. ** through the first zero character.
  5996. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  5997. ** is non-negative, then as many bytes (not characters) of the text
  5998. ** pointed to by the 2nd parameter are taken as the application-defined
  5999. ** function result. If the 3rd parameter is non-negative, then it
  6000. ** must be the byte offset into the string where the NUL terminator would
  6001. ** appear if the string where NUL terminated. If any NUL characters occur
  6002. ** in the string at a byte offset that is less than the value of the 3rd
  6003. ** parameter, then the resulting string will contain embedded NULs and the
  6004. ** result of expressions operating on strings with embedded NULs is undefined.
  6005. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6006. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  6007. ** function as the destructor on the text or BLOB result when it has
  6008. ** finished using that result.
  6009. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  6010. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  6011. ** assumes that the text or BLOB result is in constant space and does not
  6012. ** copy the content of the parameter nor call a destructor on the content
  6013. ** when it has finished using that result.
  6014. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6015. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  6016. ** then SQLite makes a copy of the result into space obtained
  6017. ** from [sqlite3_malloc()] before it returns.
  6018. **
  6019. ** ^The sqlite3_result_value() interface sets the result of
  6020. ** the application-defined function to be a copy of the
  6021. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  6022. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  6023. ** so that the [sqlite3_value] specified in the parameter may change or
  6024. ** be deallocated after sqlite3_result_value() returns without harm.
  6025. ** ^A [protected sqlite3_value] object may always be used where an
  6026. ** [unprotected sqlite3_value] object is required, so either
  6027. ** kind of [sqlite3_value] object can be used with this interface.
  6028. **
  6029. ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
  6030. ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
  6031. ** also associates the host-language pointer P or type T with that
  6032. ** NULL value such that the pointer can be retrieved within an
  6033. ** [application-defined SQL function] using [sqlite3_value_pointer()].
  6034. ** ^If the D parameter is not NULL, then it is a pointer to a destructor
  6035. ** for the P parameter. ^SQLite invokes D with P as its only argument
  6036. ** when SQLite is finished with P. The T parameter should be a static
  6037. ** string and preferably a string literal. The sqlite3_result_pointer()
  6038. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6039. **
  6040. ** If these routines are called from within the different thread
  6041. ** than the one containing the application-defined function that received
  6042. ** the [sqlite3_context] pointer, the results are undefined.
  6043. */
  6044. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  6045. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  6046. sqlite3_uint64,void(*)(void*));
  6047. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  6048. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  6049. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  6050. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  6051. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  6052. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  6053. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  6054. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  6055. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  6056. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  6057. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  6058. void(*)(void*), unsigned char encoding);
  6059. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  6060. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  6061. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  6062. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  6063. SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
  6064. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  6065. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  6066. /*
  6067. ** CAPI3REF: Setting The Subtype Of An SQL Function
  6068. ** METHOD: sqlite3_context
  6069. **
  6070. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  6071. ** the result from the [application-defined SQL function] with
  6072. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  6073. ** of the subtype T are preserved in current versions of SQLite;
  6074. ** higher order bits are discarded.
  6075. ** The number of subtype bytes preserved by SQLite might increase
  6076. ** in future releases of SQLite.
  6077. */
  6078. SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  6079. /*
  6080. ** CAPI3REF: Define New Collating Sequences
  6081. ** METHOD: sqlite3
  6082. **
  6083. ** ^These functions add, remove, or modify a [collation] associated
  6084. ** with the [database connection] specified as the first argument.
  6085. **
  6086. ** ^The name of the collation is a UTF-8 string
  6087. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  6088. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  6089. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  6090. ** considered to be the same name.
  6091. **
  6092. ** ^(The third argument (eTextRep) must be one of the constants:
  6093. ** <ul>
  6094. ** <li> [SQLITE_UTF8],
  6095. ** <li> [SQLITE_UTF16LE],
  6096. ** <li> [SQLITE_UTF16BE],
  6097. ** <li> [SQLITE_UTF16], or
  6098. ** <li> [SQLITE_UTF16_ALIGNED].
  6099. ** </ul>)^
  6100. ** ^The eTextRep argument determines the encoding of strings passed
  6101. ** to the collating function callback, xCallback.
  6102. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  6103. ** force strings to be UTF16 with native byte order.
  6104. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  6105. ** on an even byte address.
  6106. **
  6107. ** ^The fourth argument, pArg, is an application data pointer that is passed
  6108. ** through as the first argument to the collating function callback.
  6109. **
  6110. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  6111. ** ^Multiple collating functions can be registered using the same name but
  6112. ** with different eTextRep parameters and SQLite will use whichever
  6113. ** function requires the least amount of data transformation.
  6114. ** ^If the xCallback argument is NULL then the collating function is
  6115. ** deleted. ^When all collating functions having the same name are deleted,
  6116. ** that collation is no longer usable.
  6117. **
  6118. ** ^The collating function callback is invoked with a copy of the pArg
  6119. ** application data pointer and with two strings in the encoding specified
  6120. ** by the eTextRep argument. The collating function must return an
  6121. ** integer that is negative, zero, or positive
  6122. ** if the first string is less than, equal to, or greater than the second,
  6123. ** respectively. A collating function must always return the same answer
  6124. ** given the same inputs. If two or more collating functions are registered
  6125. ** to the same collation name (using different eTextRep values) then all
  6126. ** must give an equivalent answer when invoked with equivalent strings.
  6127. ** The collating function must obey the following properties for all
  6128. ** strings A, B, and C:
  6129. **
  6130. ** <ol>
  6131. ** <li> If A==B then B==A.
  6132. ** <li> If A==B and B==C then A==C.
  6133. ** <li> If A&lt;B THEN B&gt;A.
  6134. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  6135. ** </ol>
  6136. **
  6137. ** If a collating function fails any of the above constraints and that
  6138. ** collating function is registered and used, then the behavior of SQLite
  6139. ** is undefined.
  6140. **
  6141. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  6142. ** with the addition that the xDestroy callback is invoked on pArg when
  6143. ** the collating function is deleted.
  6144. ** ^Collating functions are deleted when they are overridden by later
  6145. ** calls to the collation creation functions or when the
  6146. ** [database connection] is closed using [sqlite3_close()].
  6147. **
  6148. ** ^The xDestroy callback is <u>not</u> called if the
  6149. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  6150. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  6151. ** check the return code and dispose of the application data pointer
  6152. ** themselves rather than expecting SQLite to deal with it for them.
  6153. ** This is different from every other SQLite interface. The inconsistency
  6154. ** is unfortunate but cannot be changed without breaking backwards
  6155. ** compatibility.
  6156. **
  6157. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  6158. */
  6159. SQLITE_API int sqlite3_create_collation(
  6160. sqlite3*,
  6161. const char *zName,
  6162. int eTextRep,
  6163. void *pArg,
  6164. int(*xCompare)(void*,int,const void*,int,const void*)
  6165. );
  6166. SQLITE_API int sqlite3_create_collation_v2(
  6167. sqlite3*,
  6168. const char *zName,
  6169. int eTextRep,
  6170. void *pArg,
  6171. int(*xCompare)(void*,int,const void*,int,const void*),
  6172. void(*xDestroy)(void*)
  6173. );
  6174. SQLITE_API int sqlite3_create_collation16(
  6175. sqlite3*,
  6176. const void *zName,
  6177. int eTextRep,
  6178. void *pArg,
  6179. int(*xCompare)(void*,int,const void*,int,const void*)
  6180. );
  6181. /*
  6182. ** CAPI3REF: Collation Needed Callbacks
  6183. ** METHOD: sqlite3
  6184. **
  6185. ** ^To avoid having to register all collation sequences before a database
  6186. ** can be used, a single callback function may be registered with the
  6187. ** [database connection] to be invoked whenever an undefined collation
  6188. ** sequence is required.
  6189. **
  6190. ** ^If the function is registered using the sqlite3_collation_needed() API,
  6191. ** then it is passed the names of undefined collation sequences as strings
  6192. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  6193. ** the names are passed as UTF-16 in machine native byte order.
  6194. ** ^A call to either function replaces the existing collation-needed callback.
  6195. **
  6196. ** ^(When the callback is invoked, the first argument passed is a copy
  6197. ** of the second argument to sqlite3_collation_needed() or
  6198. ** sqlite3_collation_needed16(). The second argument is the database
  6199. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  6200. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  6201. ** sequence function required. The fourth parameter is the name of the
  6202. ** required collation sequence.)^
  6203. **
  6204. ** The callback function should register the desired collation using
  6205. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  6206. ** [sqlite3_create_collation_v2()].
  6207. */
  6208. SQLITE_API int sqlite3_collation_needed(
  6209. sqlite3*,
  6210. void*,
  6211. void(*)(void*,sqlite3*,int eTextRep,const char*)
  6212. );
  6213. SQLITE_API int sqlite3_collation_needed16(
  6214. sqlite3*,
  6215. void*,
  6216. void(*)(void*,sqlite3*,int eTextRep,const void*)
  6217. );
  6218. #ifdef SQLITE_HAS_CODEC
  6219. /*
  6220. ** Specify the key for an encrypted database. This routine should be
  6221. ** called right after sqlite3_open().
  6222. **
  6223. ** The code to implement this API is not available in the public release
  6224. ** of SQLite.
  6225. */
  6226. SQLITE_API int sqlite3_key(
  6227. sqlite3 *db, /* Database to be rekeyed */
  6228. const void *pKey, int nKey /* The key */
  6229. );
  6230. SQLITE_API int sqlite3_key_v2(
  6231. sqlite3 *db, /* Database to be rekeyed */
  6232. const char *zDbName, /* Name of the database */
  6233. const void *pKey, int nKey /* The key */
  6234. );
  6235. /*
  6236. ** Change the key on an open database. If the current database is not
  6237. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  6238. ** database is decrypted.
  6239. **
  6240. ** The code to implement this API is not available in the public release
  6241. ** of SQLite.
  6242. */
  6243. SQLITE_API int sqlite3_rekey(
  6244. sqlite3 *db, /* Database to be rekeyed */
  6245. const void *pKey, int nKey /* The new key */
  6246. );
  6247. SQLITE_API int sqlite3_rekey_v2(
  6248. sqlite3 *db, /* Database to be rekeyed */
  6249. const char *zDbName, /* Name of the database */
  6250. const void *pKey, int nKey /* The new key */
  6251. );
  6252. /*
  6253. ** Specify the activation key for a SEE database. Unless
  6254. ** activated, none of the SEE routines will work.
  6255. */
  6256. SQLITE_API void sqlite3_activate_see(
  6257. const char *zPassPhrase /* Activation phrase */
  6258. );
  6259. #endif
  6260. #ifdef SQLITE_ENABLE_CEROD
  6261. /*
  6262. ** Specify the activation key for a CEROD database. Unless
  6263. ** activated, none of the CEROD routines will work.
  6264. */
  6265. SQLITE_API void sqlite3_activate_cerod(
  6266. const char *zPassPhrase /* Activation phrase */
  6267. );
  6268. #endif
  6269. /*
  6270. ** CAPI3REF: Suspend Execution For A Short Time
  6271. **
  6272. ** The sqlite3_sleep() function causes the current thread to suspend execution
  6273. ** for at least a number of milliseconds specified in its parameter.
  6274. **
  6275. ** If the operating system does not support sleep requests with
  6276. ** millisecond time resolution, then the time will be rounded up to
  6277. ** the nearest second. The number of milliseconds of sleep actually
  6278. ** requested from the operating system is returned.
  6279. **
  6280. ** ^SQLite implements this interface by calling the xSleep()
  6281. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  6282. ** of the default VFS is not implemented correctly, or not implemented at
  6283. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  6284. ** in the previous paragraphs.
  6285. */
  6286. SQLITE_API int sqlite3_sleep(int);
  6287. /*
  6288. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  6289. **
  6290. ** ^(If this global variable is made to point to a string which is
  6291. ** the name of a folder (a.k.a. directory), then all temporary files
  6292. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  6293. ** will be placed in that directory.)^ ^If this variable
  6294. ** is a NULL pointer, then SQLite performs a search for an appropriate
  6295. ** temporary file directory.
  6296. **
  6297. ** Applications are strongly discouraged from using this global variable.
  6298. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  6299. ** But for all other platforms, it is highly recommended that applications
  6300. ** neither read nor write this variable. This global variable is a relic
  6301. ** that exists for backwards compatibility of legacy applications and should
  6302. ** be avoided in new projects.
  6303. **
  6304. ** It is not safe to read or modify this variable in more than one
  6305. ** thread at a time. It is not safe to read or modify this variable
  6306. ** if a [database connection] is being used at the same time in a separate
  6307. ** thread.
  6308. ** It is intended that this variable be set once
  6309. ** as part of process initialization and before any SQLite interface
  6310. ** routines have been called and that this variable remain unchanged
  6311. ** thereafter.
  6312. **
  6313. ** ^The [temp_store_directory pragma] may modify this variable and cause
  6314. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6315. ** the [temp_store_directory pragma] always assumes that any string
  6316. ** that this variable points to is held in memory obtained from
  6317. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6318. ** using [sqlite3_free].
  6319. ** Hence, if this variable is modified directly, either it should be
  6320. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6321. ** or else the use of the [temp_store_directory pragma] should be avoided.
  6322. ** Except when requested by the [temp_store_directory pragma], SQLite
  6323. ** does not free the memory that sqlite3_temp_directory points to. If
  6324. ** the application wants that memory to be freed, it must do
  6325. ** so itself, taking care to only do so after all [database connection]
  6326. ** objects have been destroyed.
  6327. **
  6328. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  6329. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  6330. ** features that require the use of temporary files may fail. Here is an
  6331. ** example of how to do this using C++ with the Windows Runtime:
  6332. **
  6333. ** <blockquote><pre>
  6334. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  6335. ** &nbsp; TemporaryFolder->Path->Data();
  6336. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  6337. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  6338. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  6339. ** &nbsp; NULL, NULL);
  6340. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  6341. ** </pre></blockquote>
  6342. */
  6343. SQLITE_API char *sqlite3_temp_directory;
  6344. /*
  6345. ** CAPI3REF: Name Of The Folder Holding Database Files
  6346. **
  6347. ** ^(If this global variable is made to point to a string which is
  6348. ** the name of a folder (a.k.a. directory), then all database files
  6349. ** specified with a relative pathname and created or accessed by
  6350. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  6351. ** to be relative to that directory.)^ ^If this variable is a NULL
  6352. ** pointer, then SQLite assumes that all database files specified
  6353. ** with a relative pathname are relative to the current directory
  6354. ** for the process. Only the windows VFS makes use of this global
  6355. ** variable; it is ignored by the unix VFS.
  6356. **
  6357. ** Changing the value of this variable while a database connection is
  6358. ** open can result in a corrupt database.
  6359. **
  6360. ** It is not safe to read or modify this variable in more than one
  6361. ** thread at a time. It is not safe to read or modify this variable
  6362. ** if a [database connection] is being used at the same time in a separate
  6363. ** thread.
  6364. ** It is intended that this variable be set once
  6365. ** as part of process initialization and before any SQLite interface
  6366. ** routines have been called and that this variable remain unchanged
  6367. ** thereafter.
  6368. **
  6369. ** ^The [data_store_directory pragma] may modify this variable and cause
  6370. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6371. ** the [data_store_directory pragma] always assumes that any string
  6372. ** that this variable points to is held in memory obtained from
  6373. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6374. ** using [sqlite3_free].
  6375. ** Hence, if this variable is modified directly, either it should be
  6376. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6377. ** or else the use of the [data_store_directory pragma] should be avoided.
  6378. */
  6379. SQLITE_API char *sqlite3_data_directory;
  6380. /*
  6381. ** CAPI3REF: Test For Auto-Commit Mode
  6382. ** KEYWORDS: {autocommit mode}
  6383. ** METHOD: sqlite3
  6384. **
  6385. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  6386. ** zero if the given database connection is or is not in autocommit mode,
  6387. ** respectively. ^Autocommit mode is on by default.
  6388. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  6389. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  6390. **
  6391. ** If certain kinds of errors occur on a statement within a multi-statement
  6392. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  6393. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  6394. ** transaction might be rolled back automatically. The only way to
  6395. ** find out whether SQLite automatically rolled back the transaction after
  6396. ** an error is to use this function.
  6397. **
  6398. ** If another thread changes the autocommit status of the database
  6399. ** connection while this routine is running, then the return value
  6400. ** is undefined.
  6401. */
  6402. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  6403. /*
  6404. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  6405. ** METHOD: sqlite3_stmt
  6406. **
  6407. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  6408. ** to which a [prepared statement] belongs. ^The [database connection]
  6409. ** returned by sqlite3_db_handle is the same [database connection]
  6410. ** that was the first argument
  6411. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  6412. ** create the statement in the first place.
  6413. */
  6414. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  6415. /*
  6416. ** CAPI3REF: Return The Filename For A Database Connection
  6417. ** METHOD: sqlite3
  6418. **
  6419. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  6420. ** associated with database N of connection D. ^The main database file
  6421. ** has the name "main". If there is no attached database N on the database
  6422. ** connection D, or if database N is a temporary or in-memory database, then
  6423. ** a NULL pointer is returned.
  6424. **
  6425. ** ^The filename returned by this function is the output of the
  6426. ** xFullPathname method of the [VFS]. ^In other words, the filename
  6427. ** will be an absolute pathname, even if the filename used
  6428. ** to open the database originally was a URI or relative pathname.
  6429. */
  6430. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  6431. /*
  6432. ** CAPI3REF: Determine if a database is read-only
  6433. ** METHOD: sqlite3
  6434. **
  6435. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  6436. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  6437. ** the name of a database on connection D.
  6438. */
  6439. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  6440. /*
  6441. ** CAPI3REF: Find the next prepared statement
  6442. ** METHOD: sqlite3
  6443. **
  6444. ** ^This interface returns a pointer to the next [prepared statement] after
  6445. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  6446. ** then this interface returns a pointer to the first prepared statement
  6447. ** associated with the database connection pDb. ^If no prepared statement
  6448. ** satisfies the conditions of this routine, it returns NULL.
  6449. **
  6450. ** The [database connection] pointer D in a call to
  6451. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  6452. ** connection and in particular must not be a NULL pointer.
  6453. */
  6454. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  6455. /*
  6456. ** CAPI3REF: Commit And Rollback Notification Callbacks
  6457. ** METHOD: sqlite3
  6458. **
  6459. ** ^The sqlite3_commit_hook() interface registers a callback
  6460. ** function to be invoked whenever a transaction is [COMMIT | committed].
  6461. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  6462. ** for the same database connection is overridden.
  6463. ** ^The sqlite3_rollback_hook() interface registers a callback
  6464. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  6465. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  6466. ** for the same database connection is overridden.
  6467. ** ^The pArg argument is passed through to the callback.
  6468. ** ^If the callback on a commit hook function returns non-zero,
  6469. ** then the commit is converted into a rollback.
  6470. **
  6471. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  6472. ** return the P argument from the previous call of the same function
  6473. ** on the same [database connection] D, or NULL for
  6474. ** the first call for each function on D.
  6475. **
  6476. ** The commit and rollback hook callbacks are not reentrant.
  6477. ** The callback implementation must not do anything that will modify
  6478. ** the database connection that invoked the callback. Any actions
  6479. ** to modify the database connection must be deferred until after the
  6480. ** completion of the [sqlite3_step()] call that triggered the commit
  6481. ** or rollback hook in the first place.
  6482. ** Note that running any other SQL statements, including SELECT statements,
  6483. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  6484. ** the database connections for the meaning of "modify" in this paragraph.
  6485. **
  6486. ** ^Registering a NULL function disables the callback.
  6487. **
  6488. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  6489. ** operation is allowed to continue normally. ^If the commit hook
  6490. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  6491. ** ^The rollback hook is invoked on a rollback that results from a commit
  6492. ** hook returning non-zero, just as it would be with any other rollback.
  6493. **
  6494. ** ^For the purposes of this API, a transaction is said to have been
  6495. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  6496. ** an error or constraint causes an implicit rollback to occur.
  6497. ** ^The rollback callback is not invoked if a transaction is
  6498. ** automatically rolled back because the database connection is closed.
  6499. **
  6500. ** See also the [sqlite3_update_hook()] interface.
  6501. */
  6502. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  6503. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  6504. /*
  6505. ** CAPI3REF: Data Change Notification Callbacks
  6506. ** METHOD: sqlite3
  6507. **
  6508. ** ^The sqlite3_update_hook() interface registers a callback function
  6509. ** with the [database connection] identified by the first argument
  6510. ** to be invoked whenever a row is updated, inserted or deleted in
  6511. ** a [rowid table].
  6512. ** ^Any callback set by a previous call to this function
  6513. ** for the same database connection is overridden.
  6514. **
  6515. ** ^The second argument is a pointer to the function to invoke when a
  6516. ** row is updated, inserted or deleted in a rowid table.
  6517. ** ^The first argument to the callback is a copy of the third argument
  6518. ** to sqlite3_update_hook().
  6519. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  6520. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  6521. ** to be invoked.
  6522. ** ^The third and fourth arguments to the callback contain pointers to the
  6523. ** database and table name containing the affected row.
  6524. ** ^The final callback parameter is the [rowid] of the row.
  6525. ** ^In the case of an update, this is the [rowid] after the update takes place.
  6526. **
  6527. ** ^(The update hook is not invoked when internal system tables are
  6528. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  6529. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  6530. **
  6531. ** ^In the current implementation, the update hook
  6532. ** is not invoked when conflicting rows are deleted because of an
  6533. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  6534. ** invoked when rows are deleted using the [truncate optimization].
  6535. ** The exceptions defined in this paragraph might change in a future
  6536. ** release of SQLite.
  6537. **
  6538. ** The update hook implementation must not do anything that will modify
  6539. ** the database connection that invoked the update hook. Any actions
  6540. ** to modify the database connection must be deferred until after the
  6541. ** completion of the [sqlite3_step()] call that triggered the update hook.
  6542. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  6543. ** database connections for the meaning of "modify" in this paragraph.
  6544. **
  6545. ** ^The sqlite3_update_hook(D,C,P) function
  6546. ** returns the P argument from the previous call
  6547. ** on the same [database connection] D, or NULL for
  6548. ** the first call on D.
  6549. **
  6550. ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  6551. ** and [sqlite3_preupdate_hook()] interfaces.
  6552. */
  6553. SQLITE_API void *sqlite3_update_hook(
  6554. sqlite3*,
  6555. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  6556. void*
  6557. );
  6558. /*
  6559. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  6560. **
  6561. ** ^(This routine enables or disables the sharing of the database cache
  6562. ** and schema data structures between [database connection | connections]
  6563. ** to the same database. Sharing is enabled if the argument is true
  6564. ** and disabled if the argument is false.)^
  6565. **
  6566. ** ^Cache sharing is enabled and disabled for an entire process.
  6567. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
  6568. ** In prior versions of SQLite,
  6569. ** sharing was enabled or disabled for each thread separately.
  6570. **
  6571. ** ^(The cache sharing mode set by this interface effects all subsequent
  6572. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  6573. ** Existing database connections continue use the sharing mode
  6574. ** that was in effect at the time they were opened.)^
  6575. **
  6576. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  6577. ** successfully. An [error code] is returned otherwise.)^
  6578. **
  6579. ** ^Shared cache is disabled by default. But this might change in
  6580. ** future releases of SQLite. Applications that care about shared
  6581. ** cache setting should set it explicitly.
  6582. **
  6583. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  6584. ** and will always return SQLITE_MISUSE. On those systems,
  6585. ** shared cache mode should be enabled per-database connection via
  6586. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  6587. **
  6588. ** This interface is threadsafe on processors where writing a
  6589. ** 32-bit integer is atomic.
  6590. **
  6591. ** See Also: [SQLite Shared-Cache Mode]
  6592. */
  6593. SQLITE_API int sqlite3_enable_shared_cache(int);
  6594. /*
  6595. ** CAPI3REF: Attempt To Free Heap Memory
  6596. **
  6597. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  6598. ** of heap memory by deallocating non-essential memory allocations
  6599. ** held by the database library. Memory used to cache database
  6600. ** pages to improve performance is an example of non-essential memory.
  6601. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  6602. ** which might be more or less than the amount requested.
  6603. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  6604. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6605. **
  6606. ** See also: [sqlite3_db_release_memory()]
  6607. */
  6608. SQLITE_API int sqlite3_release_memory(int);
  6609. /*
  6610. ** CAPI3REF: Free Memory Used By A Database Connection
  6611. ** METHOD: sqlite3
  6612. **
  6613. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  6614. ** memory as possible from database connection D. Unlike the
  6615. ** [sqlite3_release_memory()] interface, this interface is in effect even
  6616. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  6617. ** omitted.
  6618. **
  6619. ** See also: [sqlite3_release_memory()]
  6620. */
  6621. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  6622. /*
  6623. ** CAPI3REF: Impose A Limit On Heap Size
  6624. **
  6625. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  6626. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  6627. ** ^SQLite strives to keep heap memory utilization below the soft heap
  6628. ** limit by reducing the number of pages held in the page cache
  6629. ** as heap memory usages approaches the limit.
  6630. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  6631. ** below the limit, it will exceed the limit rather than generate
  6632. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  6633. ** is advisory only.
  6634. **
  6635. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  6636. ** the soft heap limit prior to the call, or negative in the case of an
  6637. ** error. ^If the argument N is negative
  6638. ** then no change is made to the soft heap limit. Hence, the current
  6639. ** size of the soft heap limit can be determined by invoking
  6640. ** sqlite3_soft_heap_limit64() with a negative argument.
  6641. **
  6642. ** ^If the argument N is zero then the soft heap limit is disabled.
  6643. **
  6644. ** ^(The soft heap limit is not enforced in the current implementation
  6645. ** if one or more of following conditions are true:
  6646. **
  6647. ** <ul>
  6648. ** <li> The soft heap limit is set to zero.
  6649. ** <li> Memory accounting is disabled using a combination of the
  6650. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  6651. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  6652. ** <li> An alternative page cache implementation is specified using
  6653. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  6654. ** <li> The page cache allocates from its own memory pool supplied
  6655. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  6656. ** from the heap.
  6657. ** </ul>)^
  6658. **
  6659. ** Beginning with SQLite [version 3.7.3] ([dateof:3.7.3]),
  6660. ** the soft heap limit is enforced
  6661. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  6662. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  6663. ** the soft heap limit is enforced on every memory allocation. Without
  6664. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  6665. ** when memory is allocated by the page cache. Testing suggests that because
  6666. ** the page cache is the predominate memory user in SQLite, most
  6667. ** applications will achieve adequate soft heap limit enforcement without
  6668. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  6669. **
  6670. ** The circumstances under which SQLite will enforce the soft heap limit may
  6671. ** changes in future releases of SQLite.
  6672. */
  6673. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  6674. /*
  6675. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  6676. ** DEPRECATED
  6677. **
  6678. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  6679. ** interface. This routine is provided for historical compatibility
  6680. ** only. All new applications should use the
  6681. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  6682. */
  6683. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  6684. /*
  6685. ** CAPI3REF: Extract Metadata About A Column Of A Table
  6686. ** METHOD: sqlite3
  6687. **
  6688. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  6689. ** information about column C of table T in database D
  6690. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  6691. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  6692. ** the final five arguments with appropriate values if the specified
  6693. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  6694. ** SQLITE_ERROR and if the specified column does not exist.
  6695. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  6696. ** NULL pointer, then this routine simply checks for the existence of the
  6697. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  6698. ** does not. If the table name parameter T in a call to
  6699. ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
  6700. ** undefined behavior.
  6701. **
  6702. ** ^The column is identified by the second, third and fourth parameters to
  6703. ** this function. ^(The second parameter is either the name of the database
  6704. ** (i.e. "main", "temp", or an attached database) containing the specified
  6705. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  6706. ** for the table using the same algorithm used by the database engine to
  6707. ** resolve unqualified table references.
  6708. **
  6709. ** ^The third and fourth parameters to this function are the table and column
  6710. ** name of the desired column, respectively.
  6711. **
  6712. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  6713. ** and subsequent parameters to this function. ^Any of these arguments may be
  6714. ** NULL, in which case the corresponding element of metadata is omitted.
  6715. **
  6716. ** ^(<blockquote>
  6717. ** <table border="1">
  6718. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  6719. **
  6720. ** <tr><td> 5th <td> const char* <td> Data type
  6721. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  6722. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  6723. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  6724. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  6725. ** </table>
  6726. ** </blockquote>)^
  6727. **
  6728. ** ^The memory pointed to by the character pointers returned for the
  6729. ** declaration type and collation sequence is valid until the next
  6730. ** call to any SQLite API function.
  6731. **
  6732. ** ^If the specified table is actually a view, an [error code] is returned.
  6733. **
  6734. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  6735. ** is not a [WITHOUT ROWID] table and an
  6736. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  6737. ** parameters are set for the explicitly declared column. ^(If there is no
  6738. ** [INTEGER PRIMARY KEY] column, then the outputs
  6739. ** for the [rowid] are set as follows:
  6740. **
  6741. ** <pre>
  6742. ** data type: "INTEGER"
  6743. ** collation sequence: "BINARY"
  6744. ** not null: 0
  6745. ** primary key: 1
  6746. ** auto increment: 0
  6747. ** </pre>)^
  6748. **
  6749. ** ^This function causes all database schemas to be read from disk and
  6750. ** parsed, if that has not already been done, and returns an error if
  6751. ** any errors are encountered while loading the schema.
  6752. */
  6753. SQLITE_API int sqlite3_table_column_metadata(
  6754. sqlite3 *db, /* Connection handle */
  6755. const char *zDbName, /* Database name or NULL */
  6756. const char *zTableName, /* Table name */
  6757. const char *zColumnName, /* Column name */
  6758. char const **pzDataType, /* OUTPUT: Declared data type */
  6759. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  6760. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  6761. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  6762. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  6763. );
  6764. /*
  6765. ** CAPI3REF: Load An Extension
  6766. ** METHOD: sqlite3
  6767. **
  6768. ** ^This interface loads an SQLite extension library from the named file.
  6769. **
  6770. ** ^The sqlite3_load_extension() interface attempts to load an
  6771. ** [SQLite extension] library contained in the file zFile. If
  6772. ** the file cannot be loaded directly, attempts are made to load
  6773. ** with various operating-system specific extensions added.
  6774. ** So for example, if "samplelib" cannot be loaded, then names like
  6775. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  6776. ** be tried also.
  6777. **
  6778. ** ^The entry point is zProc.
  6779. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  6780. ** entry point name on its own. It first tries "sqlite3_extension_init".
  6781. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  6782. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  6783. ** characters in the filename from the last "/" to the first following
  6784. ** "." and omitting any initial "lib".)^
  6785. ** ^The sqlite3_load_extension() interface returns
  6786. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  6787. ** ^If an error occurs and pzErrMsg is not 0, then the
  6788. ** [sqlite3_load_extension()] interface shall attempt to
  6789. ** fill *pzErrMsg with error message text stored in memory
  6790. ** obtained from [sqlite3_malloc()]. The calling function
  6791. ** should free this memory by calling [sqlite3_free()].
  6792. **
  6793. ** ^Extension loading must be enabled using
  6794. ** [sqlite3_enable_load_extension()] or
  6795. ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  6796. ** prior to calling this API,
  6797. ** otherwise an error will be returned.
  6798. **
  6799. ** <b>Security warning:</b> It is recommended that the
  6800. ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  6801. ** interface. The use of the [sqlite3_enable_load_extension()] interface
  6802. ** should be avoided. This will keep the SQL function [load_extension()]
  6803. ** disabled and prevent SQL injections from giving attackers
  6804. ** access to extension loading capabilities.
  6805. **
  6806. ** See also the [load_extension() SQL function].
  6807. */
  6808. SQLITE_API int sqlite3_load_extension(
  6809. sqlite3 *db, /* Load the extension into this database connection */
  6810. const char *zFile, /* Name of the shared library containing extension */
  6811. const char *zProc, /* Entry point. Derived from zFile if 0 */
  6812. char **pzErrMsg /* Put error message here if not 0 */
  6813. );
  6814. /*
  6815. ** CAPI3REF: Enable Or Disable Extension Loading
  6816. ** METHOD: sqlite3
  6817. **
  6818. ** ^So as not to open security holes in older applications that are
  6819. ** unprepared to deal with [extension loading], and as a means of disabling
  6820. ** [extension loading] while evaluating user-entered SQL, the following API
  6821. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  6822. **
  6823. ** ^Extension loading is off by default.
  6824. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  6825. ** to turn extension loading on and call it with onoff==0 to turn
  6826. ** it back off again.
  6827. **
  6828. ** ^This interface enables or disables both the C-API
  6829. ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  6830. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  6831. ** to enable or disable only the C-API.)^
  6832. **
  6833. ** <b>Security warning:</b> It is recommended that extension loading
  6834. ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  6835. ** rather than this interface, so the [load_extension()] SQL function
  6836. ** remains disabled. This will prevent SQL injections from giving attackers
  6837. ** access to extension loading capabilities.
  6838. */
  6839. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  6840. /*
  6841. ** CAPI3REF: Automatically Load Statically Linked Extensions
  6842. **
  6843. ** ^This interface causes the xEntryPoint() function to be invoked for
  6844. ** each new [database connection] that is created. The idea here is that
  6845. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  6846. ** that is to be automatically loaded into all new database connections.
  6847. **
  6848. ** ^(Even though the function prototype shows that xEntryPoint() takes
  6849. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  6850. ** arguments and expects an integer result as if the signature of the
  6851. ** entry point where as follows:
  6852. **
  6853. ** <blockquote><pre>
  6854. ** &nbsp; int xEntryPoint(
  6855. ** &nbsp; sqlite3 *db,
  6856. ** &nbsp; const char **pzErrMsg,
  6857. ** &nbsp; const struct sqlite3_api_routines *pThunk
  6858. ** &nbsp; );
  6859. ** </pre></blockquote>)^
  6860. **
  6861. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  6862. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  6863. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  6864. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  6865. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  6866. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  6867. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  6868. **
  6869. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  6870. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  6871. ** will be called more than once for each database connection that is opened.
  6872. **
  6873. ** See also: [sqlite3_reset_auto_extension()]
  6874. ** and [sqlite3_cancel_auto_extension()]
  6875. */
  6876. SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  6877. /*
  6878. ** CAPI3REF: Cancel Automatic Extension Loading
  6879. **
  6880. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  6881. ** initialization routine X that was registered using a prior call to
  6882. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  6883. ** routine returns 1 if initialization routine X was successfully
  6884. ** unregistered and it returns 0 if X was not on the list of initialization
  6885. ** routines.
  6886. */
  6887. SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  6888. /*
  6889. ** CAPI3REF: Reset Automatic Extension Loading
  6890. **
  6891. ** ^This interface disables all automatic extensions previously
  6892. ** registered using [sqlite3_auto_extension()].
  6893. */
  6894. SQLITE_API void sqlite3_reset_auto_extension(void);
  6895. /*
  6896. ** The interface to the virtual-table mechanism is currently considered
  6897. ** to be experimental. The interface might change in incompatible ways.
  6898. ** If this is a problem for you, do not use the interface at this time.
  6899. **
  6900. ** When the virtual-table mechanism stabilizes, we will declare the
  6901. ** interface fixed, support it indefinitely, and remove this comment.
  6902. */
  6903. /*
  6904. ** Structures used by the virtual table interface
  6905. */
  6906. typedef struct sqlite3_vtab sqlite3_vtab;
  6907. typedef struct sqlite3_index_info sqlite3_index_info;
  6908. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  6909. typedef struct sqlite3_module sqlite3_module;
  6910. /*
  6911. ** CAPI3REF: Virtual Table Object
  6912. ** KEYWORDS: sqlite3_module {virtual table module}
  6913. **
  6914. ** This structure, sometimes called a "virtual table module",
  6915. ** defines the implementation of a [virtual tables].
  6916. ** This structure consists mostly of methods for the module.
  6917. **
  6918. ** ^A virtual table module is created by filling in a persistent
  6919. ** instance of this structure and passing a pointer to that instance
  6920. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  6921. ** ^The registration remains valid until it is replaced by a different
  6922. ** module or until the [database connection] closes. The content
  6923. ** of this structure must not change while it is registered with
  6924. ** any database connection.
  6925. */
  6926. struct sqlite3_module {
  6927. int iVersion;
  6928. int (*xCreate)(sqlite3*, void *pAux,
  6929. int argc, const char *const*argv,
  6930. sqlite3_vtab **ppVTab, char**);
  6931. int (*xConnect)(sqlite3*, void *pAux,
  6932. int argc, const char *const*argv,
  6933. sqlite3_vtab **ppVTab, char**);
  6934. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  6935. int (*xDisconnect)(sqlite3_vtab *pVTab);
  6936. int (*xDestroy)(sqlite3_vtab *pVTab);
  6937. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  6938. int (*xClose)(sqlite3_vtab_cursor*);
  6939. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  6940. int argc, sqlite3_value **argv);
  6941. int (*xNext)(sqlite3_vtab_cursor*);
  6942. int (*xEof)(sqlite3_vtab_cursor*);
  6943. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  6944. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  6945. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  6946. int (*xBegin)(sqlite3_vtab *pVTab);
  6947. int (*xSync)(sqlite3_vtab *pVTab);
  6948. int (*xCommit)(sqlite3_vtab *pVTab);
  6949. int (*xRollback)(sqlite3_vtab *pVTab);
  6950. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  6951. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  6952. void **ppArg);
  6953. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  6954. /* The methods above are in version 1 of the sqlite_module object. Those
  6955. ** below are for version 2 and greater. */
  6956. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  6957. int (*xRelease)(sqlite3_vtab *pVTab, int);
  6958. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  6959. };
  6960. /*
  6961. ** CAPI3REF: Virtual Table Indexing Information
  6962. ** KEYWORDS: sqlite3_index_info
  6963. **
  6964. ** The sqlite3_index_info structure and its substructures is used as part
  6965. ** of the [virtual table] interface to
  6966. ** pass information into and receive the reply from the [xBestIndex]
  6967. ** method of a [virtual table module]. The fields under **Inputs** are the
  6968. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  6969. ** results into the **Outputs** fields.
  6970. **
  6971. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  6972. **
  6973. ** <blockquote>column OP expr</blockquote>
  6974. **
  6975. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  6976. ** stored in aConstraint[].op using one of the
  6977. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  6978. ** ^(The index of the column is stored in
  6979. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  6980. ** expr on the right-hand side can be evaluated (and thus the constraint
  6981. ** is usable) and false if it cannot.)^
  6982. **
  6983. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  6984. ** and makes other simplifications to the WHERE clause in an attempt to
  6985. ** get as many WHERE clause terms into the form shown above as possible.
  6986. ** ^The aConstraint[] array only reports WHERE clause terms that are
  6987. ** relevant to the particular virtual table being queried.
  6988. **
  6989. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  6990. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  6991. **
  6992. ** The colUsed field indicates which columns of the virtual table may be
  6993. ** required by the current scan. Virtual table columns are numbered from
  6994. ** zero in the order in which they appear within the CREATE TABLE statement
  6995. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  6996. ** the corresponding bit is set within the colUsed mask if the column may be
  6997. ** required by SQLite. If the table has at least 64 columns and any column
  6998. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  6999. ** set. In other words, column iCol may be required if the expression
  7000. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  7001. ** non-zero.
  7002. **
  7003. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  7004. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  7005. ** the right-hand side of the corresponding aConstraint[] is evaluated
  7006. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  7007. ** is true, then the constraint is assumed to be fully handled by the
  7008. ** virtual table and is not checked again by SQLite.)^
  7009. **
  7010. ** ^The idxNum and idxPtr values are recorded and passed into the
  7011. ** [xFilter] method.
  7012. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  7013. ** needToFreeIdxPtr is true.
  7014. **
  7015. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  7016. ** the correct order to satisfy the ORDER BY clause so that no separate
  7017. ** sorting step is required.
  7018. **
  7019. ** ^The estimatedCost value is an estimate of the cost of a particular
  7020. ** strategy. A cost of N indicates that the cost of the strategy is similar
  7021. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  7022. ** indicates that the expense of the operation is similar to that of a
  7023. ** binary search on a unique indexed field of an SQLite table with N rows.
  7024. **
  7025. ** ^The estimatedRows value is an estimate of the number of rows that
  7026. ** will be returned by the strategy.
  7027. **
  7028. ** The xBestIndex method may optionally populate the idxFlags field with a
  7029. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  7030. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  7031. ** assumes that the strategy may visit at most one row.
  7032. **
  7033. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  7034. ** SQLite also assumes that if a call to the xUpdate() method is made as
  7035. ** part of the same statement to delete or update a virtual table row and the
  7036. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  7037. ** any database changes. In other words, if the xUpdate() returns
  7038. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  7039. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  7040. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  7041. ** the xUpdate method are automatically rolled back by SQLite.
  7042. **
  7043. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  7044. ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
  7045. ** If a virtual table extension is
  7046. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  7047. ** to read or write the estimatedRows field are undefined (but are likely
  7048. ** to included crashing the application). The estimatedRows field should
  7049. ** therefore only be used if [sqlite3_libversion_number()] returns a
  7050. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  7051. ** was added for [version 3.9.0] ([dateof:3.9.0]).
  7052. ** It may therefore only be used if
  7053. ** sqlite3_libversion_number() returns a value greater than or equal to
  7054. ** 3009000.
  7055. */
  7056. struct sqlite3_index_info {
  7057. /* Inputs */
  7058. int nConstraint; /* Number of entries in aConstraint */
  7059. struct sqlite3_index_constraint {
  7060. int iColumn; /* Column constrained. -1 for ROWID */
  7061. unsigned char op; /* Constraint operator */
  7062. unsigned char usable; /* True if this constraint is usable */
  7063. int iTermOffset; /* Used internally - xBestIndex should ignore */
  7064. } *aConstraint; /* Table of WHERE clause constraints */
  7065. int nOrderBy; /* Number of terms in the ORDER BY clause */
  7066. struct sqlite3_index_orderby {
  7067. int iColumn; /* Column number */
  7068. unsigned char desc; /* True for DESC. False for ASC. */
  7069. } *aOrderBy; /* The ORDER BY clause */
  7070. /* Outputs */
  7071. struct sqlite3_index_constraint_usage {
  7072. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  7073. unsigned char omit; /* Do not code a test for this constraint */
  7074. } *aConstraintUsage;
  7075. int idxNum; /* Number used to identify the index */
  7076. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  7077. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  7078. int orderByConsumed; /* True if output is already ordered */
  7079. double estimatedCost; /* Estimated cost of using this index */
  7080. /* Fields below are only available in SQLite 3.8.2 and later */
  7081. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  7082. /* Fields below are only available in SQLite 3.9.0 and later */
  7083. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  7084. /* Fields below are only available in SQLite 3.10.0 and later */
  7085. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  7086. };
  7087. /*
  7088. ** CAPI3REF: Virtual Table Scan Flags
  7089. */
  7090. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  7091. /*
  7092. ** CAPI3REF: Virtual Table Constraint Operator Codes
  7093. **
  7094. ** These macros defined the allowed values for the
  7095. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  7096. ** an operator that is part of a constraint term in the wHERE clause of
  7097. ** a query that uses a [virtual table].
  7098. */
  7099. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  7100. #define SQLITE_INDEX_CONSTRAINT_GT 4
  7101. #define SQLITE_INDEX_CONSTRAINT_LE 8
  7102. #define SQLITE_INDEX_CONSTRAINT_LT 16
  7103. #define SQLITE_INDEX_CONSTRAINT_GE 32
  7104. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  7105. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  7106. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  7107. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  7108. #define SQLITE_INDEX_CONSTRAINT_NE 68
  7109. #define SQLITE_INDEX_CONSTRAINT_ISNOT 69
  7110. #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
  7111. #define SQLITE_INDEX_CONSTRAINT_ISNULL 71
  7112. #define SQLITE_INDEX_CONSTRAINT_IS 72
  7113. /*
  7114. ** CAPI3REF: Register A Virtual Table Implementation
  7115. ** METHOD: sqlite3
  7116. **
  7117. ** ^These routines are used to register a new [virtual table module] name.
  7118. ** ^Module names must be registered before
  7119. ** creating a new [virtual table] using the module and before using a
  7120. ** preexisting [virtual table] for the module.
  7121. **
  7122. ** ^The module name is registered on the [database connection] specified
  7123. ** by the first parameter. ^The name of the module is given by the
  7124. ** second parameter. ^The third parameter is a pointer to
  7125. ** the implementation of the [virtual table module]. ^The fourth
  7126. ** parameter is an arbitrary client data pointer that is passed through
  7127. ** into the [xCreate] and [xConnect] methods of the virtual table module
  7128. ** when a new virtual table is be being created or reinitialized.
  7129. **
  7130. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  7131. ** is a pointer to a destructor for the pClientData. ^SQLite will
  7132. ** invoke the destructor function (if it is not NULL) when SQLite
  7133. ** no longer needs the pClientData pointer. ^The destructor will also
  7134. ** be invoked if the call to sqlite3_create_module_v2() fails.
  7135. ** ^The sqlite3_create_module()
  7136. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  7137. ** destructor.
  7138. */
  7139. SQLITE_API int sqlite3_create_module(
  7140. sqlite3 *db, /* SQLite connection to register module with */
  7141. const char *zName, /* Name of the module */
  7142. const sqlite3_module *p, /* Methods for the module */
  7143. void *pClientData /* Client data for xCreate/xConnect */
  7144. );
  7145. SQLITE_API int sqlite3_create_module_v2(
  7146. sqlite3 *db, /* SQLite connection to register module with */
  7147. const char *zName, /* Name of the module */
  7148. const sqlite3_module *p, /* Methods for the module */
  7149. void *pClientData, /* Client data for xCreate/xConnect */
  7150. void(*xDestroy)(void*) /* Module destructor function */
  7151. );
  7152. /*
  7153. ** CAPI3REF: Virtual Table Instance Object
  7154. ** KEYWORDS: sqlite3_vtab
  7155. **
  7156. ** Every [virtual table module] implementation uses a subclass
  7157. ** of this object to describe a particular instance
  7158. ** of the [virtual table]. Each subclass will
  7159. ** be tailored to the specific needs of the module implementation.
  7160. ** The purpose of this superclass is to define certain fields that are
  7161. ** common to all module implementations.
  7162. **
  7163. ** ^Virtual tables methods can set an error message by assigning a
  7164. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  7165. ** take care that any prior string is freed by a call to [sqlite3_free()]
  7166. ** prior to assigning a new string to zErrMsg. ^After the error message
  7167. ** is delivered up to the client application, the string will be automatically
  7168. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  7169. */
  7170. struct sqlite3_vtab {
  7171. const sqlite3_module *pModule; /* The module for this virtual table */
  7172. int nRef; /* Number of open cursors */
  7173. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  7174. /* Virtual table implementations will typically add additional fields */
  7175. };
  7176. /*
  7177. ** CAPI3REF: Virtual Table Cursor Object
  7178. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  7179. **
  7180. ** Every [virtual table module] implementation uses a subclass of the
  7181. ** following structure to describe cursors that point into the
  7182. ** [virtual table] and are used
  7183. ** to loop through the virtual table. Cursors are created using the
  7184. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  7185. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  7186. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  7187. ** of the module. Each module implementation will define
  7188. ** the content of a cursor structure to suit its own needs.
  7189. **
  7190. ** This superclass exists in order to define fields of the cursor that
  7191. ** are common to all implementations.
  7192. */
  7193. struct sqlite3_vtab_cursor {
  7194. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  7195. /* Virtual table implementations will typically add additional fields */
  7196. };
  7197. /*
  7198. ** CAPI3REF: Declare The Schema Of A Virtual Table
  7199. **
  7200. ** ^The [xCreate] and [xConnect] methods of a
  7201. ** [virtual table module] call this interface
  7202. ** to declare the format (the names and datatypes of the columns) of
  7203. ** the virtual tables they implement.
  7204. */
  7205. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  7206. /*
  7207. ** CAPI3REF: Overload A Function For A Virtual Table
  7208. ** METHOD: sqlite3
  7209. **
  7210. ** ^(Virtual tables can provide alternative implementations of functions
  7211. ** using the [xFindFunction] method of the [virtual table module].
  7212. ** But global versions of those functions
  7213. ** must exist in order to be overloaded.)^
  7214. **
  7215. ** ^(This API makes sure a global version of a function with a particular
  7216. ** name and number of parameters exists. If no such function exists
  7217. ** before this API is called, a new function is created.)^ ^The implementation
  7218. ** of the new function always causes an exception to be thrown. So
  7219. ** the new function is not good for anything by itself. Its only
  7220. ** purpose is to be a placeholder function that can be overloaded
  7221. ** by a [virtual table].
  7222. */
  7223. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  7224. /*
  7225. ** The interface to the virtual-table mechanism defined above (back up
  7226. ** to a comment remarkably similar to this one) is currently considered
  7227. ** to be experimental. The interface might change in incompatible ways.
  7228. ** If this is a problem for you, do not use the interface at this time.
  7229. **
  7230. ** When the virtual-table mechanism stabilizes, we will declare the
  7231. ** interface fixed, support it indefinitely, and remove this comment.
  7232. */
  7233. /*
  7234. ** CAPI3REF: A Handle To An Open BLOB
  7235. ** KEYWORDS: {BLOB handle} {BLOB handles}
  7236. **
  7237. ** An instance of this object represents an open BLOB on which
  7238. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  7239. ** ^Objects of this type are created by [sqlite3_blob_open()]
  7240. ** and destroyed by [sqlite3_blob_close()].
  7241. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  7242. ** can be used to read or write small subsections of the BLOB.
  7243. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  7244. */
  7245. typedef struct sqlite3_blob sqlite3_blob;
  7246. /*
  7247. ** CAPI3REF: Open A BLOB For Incremental I/O
  7248. ** METHOD: sqlite3
  7249. ** CONSTRUCTOR: sqlite3_blob
  7250. **
  7251. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  7252. ** in row iRow, column zColumn, table zTable in database zDb;
  7253. ** in other words, the same BLOB that would be selected by:
  7254. **
  7255. ** <pre>
  7256. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  7257. ** </pre>)^
  7258. **
  7259. ** ^(Parameter zDb is not the filename that contains the database, but
  7260. ** rather the symbolic name of the database. For attached databases, this is
  7261. ** the name that appears after the AS keyword in the [ATTACH] statement.
  7262. ** For the main database file, the database name is "main". For TEMP
  7263. ** tables, the database name is "temp".)^
  7264. **
  7265. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  7266. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  7267. ** read-only access.
  7268. **
  7269. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  7270. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  7271. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  7272. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  7273. ** on *ppBlob after this function it returns.
  7274. **
  7275. ** This function fails with SQLITE_ERROR if any of the following are true:
  7276. ** <ul>
  7277. ** <li> ^(Database zDb does not exist)^,
  7278. ** <li> ^(Table zTable does not exist within database zDb)^,
  7279. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  7280. ** <li> ^(Column zColumn does not exist)^,
  7281. ** <li> ^(Row iRow is not present in the table)^,
  7282. ** <li> ^(The specified column of row iRow contains a value that is not
  7283. ** a TEXT or BLOB value)^,
  7284. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  7285. ** constraint and the blob is being opened for read/write access)^,
  7286. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  7287. ** column zColumn is part of a [child key] definition and the blob is
  7288. ** being opened for read/write access)^.
  7289. ** </ul>
  7290. **
  7291. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  7292. ** [database connection] error code and message accessible via
  7293. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7294. **
  7295. ** A BLOB referenced by sqlite3_blob_open() may be read using the
  7296. ** [sqlite3_blob_read()] interface and modified by using
  7297. ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
  7298. ** different row of the same table using the [sqlite3_blob_reopen()]
  7299. ** interface. However, the column, table, or database of a [BLOB handle]
  7300. ** cannot be changed after the [BLOB handle] is opened.
  7301. **
  7302. ** ^(If the row that a BLOB handle points to is modified by an
  7303. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  7304. ** then the BLOB handle is marked as "expired".
  7305. ** This is true if any column of the row is changed, even a column
  7306. ** other than the one the BLOB handle is open on.)^
  7307. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  7308. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  7309. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  7310. ** rolled back by the expiration of the BLOB. Such changes will eventually
  7311. ** commit if the transaction continues to completion.)^
  7312. **
  7313. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  7314. ** the opened blob. ^The size of a blob may not be changed by this
  7315. ** interface. Use the [UPDATE] SQL command to change the size of a
  7316. ** blob.
  7317. **
  7318. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  7319. ** and the built-in [zeroblob] SQL function may be used to create a
  7320. ** zero-filled blob to read or write using the incremental-blob interface.
  7321. **
  7322. ** To avoid a resource leak, every open [BLOB handle] should eventually
  7323. ** be released by a call to [sqlite3_blob_close()].
  7324. **
  7325. ** See also: [sqlite3_blob_close()],
  7326. ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  7327. ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  7328. */
  7329. SQLITE_API int sqlite3_blob_open(
  7330. sqlite3*,
  7331. const char *zDb,
  7332. const char *zTable,
  7333. const char *zColumn,
  7334. sqlite3_int64 iRow,
  7335. int flags,
  7336. sqlite3_blob **ppBlob
  7337. );
  7338. /*
  7339. ** CAPI3REF: Move a BLOB Handle to a New Row
  7340. ** METHOD: sqlite3_blob
  7341. **
  7342. ** ^This function is used to move an existing [BLOB handle] so that it points
  7343. ** to a different row of the same database table. ^The new row is identified
  7344. ** by the rowid value passed as the second argument. Only the row can be
  7345. ** changed. ^The database, table and column on which the blob handle is open
  7346. ** remain the same. Moving an existing [BLOB handle] to a new row is
  7347. ** faster than closing the existing handle and opening a new one.
  7348. **
  7349. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  7350. ** it must exist and there must be either a blob or text value stored in
  7351. ** the nominated column.)^ ^If the new row is not present in the table, or if
  7352. ** it does not contain a blob or text value, or if another error occurs, an
  7353. ** SQLite error code is returned and the blob handle is considered aborted.
  7354. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  7355. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  7356. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  7357. ** always returns zero.
  7358. **
  7359. ** ^This function sets the database handle error code and message.
  7360. */
  7361. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  7362. /*
  7363. ** CAPI3REF: Close A BLOB Handle
  7364. ** DESTRUCTOR: sqlite3_blob
  7365. **
  7366. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  7367. ** unconditionally. Even if this routine returns an error code, the
  7368. ** handle is still closed.)^
  7369. **
  7370. ** ^If the blob handle being closed was opened for read-write access, and if
  7371. ** the database is in auto-commit mode and there are no other open read-write
  7372. ** blob handles or active write statements, the current transaction is
  7373. ** committed. ^If an error occurs while committing the transaction, an error
  7374. ** code is returned and the transaction rolled back.
  7375. **
  7376. ** Calling this function with an argument that is not a NULL pointer or an
  7377. ** open blob handle results in undefined behaviour. ^Calling this routine
  7378. ** with a null pointer (such as would be returned by a failed call to
  7379. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  7380. ** is passed a valid open blob handle, the values returned by the
  7381. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  7382. */
  7383. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  7384. /*
  7385. ** CAPI3REF: Return The Size Of An Open BLOB
  7386. ** METHOD: sqlite3_blob
  7387. **
  7388. ** ^Returns the size in bytes of the BLOB accessible via the
  7389. ** successfully opened [BLOB handle] in its only argument. ^The
  7390. ** incremental blob I/O routines can only read or overwriting existing
  7391. ** blob content; they cannot change the size of a blob.
  7392. **
  7393. ** This routine only works on a [BLOB handle] which has been created
  7394. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7395. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7396. ** to this routine results in undefined and probably undesirable behavior.
  7397. */
  7398. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  7399. /*
  7400. ** CAPI3REF: Read Data From A BLOB Incrementally
  7401. ** METHOD: sqlite3_blob
  7402. **
  7403. ** ^(This function is used to read data from an open [BLOB handle] into a
  7404. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  7405. ** from the open BLOB, starting at offset iOffset.)^
  7406. **
  7407. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7408. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  7409. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  7410. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  7411. ** can be determined using the [sqlite3_blob_bytes()] interface.
  7412. **
  7413. ** ^An attempt to read from an expired [BLOB handle] fails with an
  7414. ** error code of [SQLITE_ABORT].
  7415. **
  7416. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  7417. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7418. **
  7419. ** This routine only works on a [BLOB handle] which has been created
  7420. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7421. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7422. ** to this routine results in undefined and probably undesirable behavior.
  7423. **
  7424. ** See also: [sqlite3_blob_write()].
  7425. */
  7426. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  7427. /*
  7428. ** CAPI3REF: Write Data Into A BLOB Incrementally
  7429. ** METHOD: sqlite3_blob
  7430. **
  7431. ** ^(This function is used to write data into an open [BLOB handle] from a
  7432. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  7433. ** into the open BLOB, starting at offset iOffset.)^
  7434. **
  7435. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  7436. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  7437. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  7438. ** [database connection] error code and message accessible via
  7439. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7440. **
  7441. ** ^If the [BLOB handle] passed as the first argument was not opened for
  7442. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  7443. ** this function returns [SQLITE_READONLY].
  7444. **
  7445. ** This function may only modify the contents of the BLOB; it is
  7446. ** not possible to increase the size of a BLOB using this API.
  7447. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  7448. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  7449. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  7450. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  7451. ** than zero [SQLITE_ERROR] is returned and no data is written.
  7452. **
  7453. ** ^An attempt to write to an expired [BLOB handle] fails with an
  7454. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  7455. ** before the [BLOB handle] expired are not rolled back by the
  7456. ** expiration of the handle, though of course those changes might
  7457. ** have been overwritten by the statement that expired the BLOB handle
  7458. ** or by other independent statements.
  7459. **
  7460. ** This routine only works on a [BLOB handle] which has been created
  7461. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  7462. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  7463. ** to this routine results in undefined and probably undesirable behavior.
  7464. **
  7465. ** See also: [sqlite3_blob_read()].
  7466. */
  7467. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  7468. /*
  7469. ** CAPI3REF: Virtual File System Objects
  7470. **
  7471. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  7472. ** that SQLite uses to interact
  7473. ** with the underlying operating system. Most SQLite builds come with a
  7474. ** single default VFS that is appropriate for the host computer.
  7475. ** New VFSes can be registered and existing VFSes can be unregistered.
  7476. ** The following interfaces are provided.
  7477. **
  7478. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  7479. ** ^Names are case sensitive.
  7480. ** ^Names are zero-terminated UTF-8 strings.
  7481. ** ^If there is no match, a NULL pointer is returned.
  7482. ** ^If zVfsName is NULL then the default VFS is returned.
  7483. **
  7484. ** ^New VFSes are registered with sqlite3_vfs_register().
  7485. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  7486. ** ^The same VFS can be registered multiple times without injury.
  7487. ** ^To make an existing VFS into the default VFS, register it again
  7488. ** with the makeDflt flag set. If two different VFSes with the
  7489. ** same name are registered, the behavior is undefined. If a
  7490. ** VFS is registered with a name that is NULL or an empty string,
  7491. ** then the behavior is undefined.
  7492. **
  7493. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  7494. ** ^(If the default VFS is unregistered, another VFS is chosen as
  7495. ** the default. The choice for the new VFS is arbitrary.)^
  7496. */
  7497. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  7498. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  7499. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  7500. /*
  7501. ** CAPI3REF: Mutexes
  7502. **
  7503. ** The SQLite core uses these routines for thread
  7504. ** synchronization. Though they are intended for internal
  7505. ** use by SQLite, code that links against SQLite is
  7506. ** permitted to use any of these routines.
  7507. **
  7508. ** The SQLite source code contains multiple implementations
  7509. ** of these mutex routines. An appropriate implementation
  7510. ** is selected automatically at compile-time. The following
  7511. ** implementations are available in the SQLite core:
  7512. **
  7513. ** <ul>
  7514. ** <li> SQLITE_MUTEX_PTHREADS
  7515. ** <li> SQLITE_MUTEX_W32
  7516. ** <li> SQLITE_MUTEX_NOOP
  7517. ** </ul>
  7518. **
  7519. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  7520. ** that does no real locking and is appropriate for use in
  7521. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  7522. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  7523. ** and Windows.
  7524. **
  7525. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  7526. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  7527. ** implementation is included with the library. In this case the
  7528. ** application must supply a custom mutex implementation using the
  7529. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  7530. ** before calling sqlite3_initialize() or any other public sqlite3_
  7531. ** function that calls sqlite3_initialize().
  7532. **
  7533. ** ^The sqlite3_mutex_alloc() routine allocates a new
  7534. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  7535. ** routine returns NULL if it is unable to allocate the requested
  7536. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  7537. ** integer constants:
  7538. **
  7539. ** <ul>
  7540. ** <li> SQLITE_MUTEX_FAST
  7541. ** <li> SQLITE_MUTEX_RECURSIVE
  7542. ** <li> SQLITE_MUTEX_STATIC_MASTER
  7543. ** <li> SQLITE_MUTEX_STATIC_MEM
  7544. ** <li> SQLITE_MUTEX_STATIC_OPEN
  7545. ** <li> SQLITE_MUTEX_STATIC_PRNG
  7546. ** <li> SQLITE_MUTEX_STATIC_LRU
  7547. ** <li> SQLITE_MUTEX_STATIC_PMEM
  7548. ** <li> SQLITE_MUTEX_STATIC_APP1
  7549. ** <li> SQLITE_MUTEX_STATIC_APP2
  7550. ** <li> SQLITE_MUTEX_STATIC_APP3
  7551. ** <li> SQLITE_MUTEX_STATIC_VFS1
  7552. ** <li> SQLITE_MUTEX_STATIC_VFS2
  7553. ** <li> SQLITE_MUTEX_STATIC_VFS3
  7554. ** </ul>
  7555. **
  7556. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  7557. ** cause sqlite3_mutex_alloc() to create
  7558. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  7559. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  7560. ** The mutex implementation does not need to make a distinction
  7561. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  7562. ** not want to. SQLite will only request a recursive mutex in
  7563. ** cases where it really needs one. If a faster non-recursive mutex
  7564. ** implementation is available on the host platform, the mutex subsystem
  7565. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  7566. **
  7567. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  7568. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  7569. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  7570. ** used by the current version of SQLite. Future versions of SQLite
  7571. ** may add additional static mutexes. Static mutexes are for internal
  7572. ** use by SQLite only. Applications that use SQLite mutexes should
  7573. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  7574. ** SQLITE_MUTEX_RECURSIVE.
  7575. **
  7576. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  7577. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  7578. ** returns a different mutex on every call. ^For the static
  7579. ** mutex types, the same mutex is returned on every call that has
  7580. ** the same type number.
  7581. **
  7582. ** ^The sqlite3_mutex_free() routine deallocates a previously
  7583. ** allocated dynamic mutex. Attempting to deallocate a static
  7584. ** mutex results in undefined behavior.
  7585. **
  7586. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  7587. ** to enter a mutex. ^If another thread is already within the mutex,
  7588. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  7589. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  7590. ** upon successful entry. ^(Mutexes created using
  7591. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  7592. ** In such cases, the
  7593. ** mutex must be exited an equal number of times before another thread
  7594. ** can enter.)^ If the same thread tries to enter any mutex other
  7595. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  7596. **
  7597. ** ^(Some systems (for example, Windows 95) do not support the operation
  7598. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  7599. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  7600. ** sqlite3_mutex_try() as an optimization so this is acceptable
  7601. ** behavior.)^
  7602. **
  7603. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  7604. ** previously entered by the same thread. The behavior
  7605. ** is undefined if the mutex is not currently entered by the
  7606. ** calling thread or is not currently allocated.
  7607. **
  7608. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  7609. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  7610. ** behave as no-ops.
  7611. **
  7612. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  7613. */
  7614. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  7615. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  7616. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  7617. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  7618. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  7619. /*
  7620. ** CAPI3REF: Mutex Methods Object
  7621. **
  7622. ** An instance of this structure defines the low-level routines
  7623. ** used to allocate and use mutexes.
  7624. **
  7625. ** Usually, the default mutex implementations provided by SQLite are
  7626. ** sufficient, however the application has the option of substituting a custom
  7627. ** implementation for specialized deployments or systems for which SQLite
  7628. ** does not provide a suitable implementation. In this case, the application
  7629. ** creates and populates an instance of this structure to pass
  7630. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  7631. ** Additionally, an instance of this structure can be used as an
  7632. ** output variable when querying the system for the current mutex
  7633. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  7634. **
  7635. ** ^The xMutexInit method defined by this structure is invoked as
  7636. ** part of system initialization by the sqlite3_initialize() function.
  7637. ** ^The xMutexInit routine is called by SQLite exactly once for each
  7638. ** effective call to [sqlite3_initialize()].
  7639. **
  7640. ** ^The xMutexEnd method defined by this structure is invoked as
  7641. ** part of system shutdown by the sqlite3_shutdown() function. The
  7642. ** implementation of this method is expected to release all outstanding
  7643. ** resources obtained by the mutex methods implementation, especially
  7644. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  7645. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  7646. **
  7647. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  7648. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  7649. ** xMutexNotheld) implement the following interfaces (respectively):
  7650. **
  7651. ** <ul>
  7652. ** <li> [sqlite3_mutex_alloc()] </li>
  7653. ** <li> [sqlite3_mutex_free()] </li>
  7654. ** <li> [sqlite3_mutex_enter()] </li>
  7655. ** <li> [sqlite3_mutex_try()] </li>
  7656. ** <li> [sqlite3_mutex_leave()] </li>
  7657. ** <li> [sqlite3_mutex_held()] </li>
  7658. ** <li> [sqlite3_mutex_notheld()] </li>
  7659. ** </ul>)^
  7660. **
  7661. ** The only difference is that the public sqlite3_XXX functions enumerated
  7662. ** above silently ignore any invocations that pass a NULL pointer instead
  7663. ** of a valid mutex handle. The implementations of the methods defined
  7664. ** by this structure are not required to handle this case, the results
  7665. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  7666. ** (i.e. it is acceptable to provide an implementation that segfaults if
  7667. ** it is passed a NULL pointer).
  7668. **
  7669. ** The xMutexInit() method must be threadsafe. It must be harmless to
  7670. ** invoke xMutexInit() multiple times within the same process and without
  7671. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  7672. ** xMutexInit() must be no-ops.
  7673. **
  7674. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  7675. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  7676. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  7677. ** memory allocation for a fast or recursive mutex.
  7678. **
  7679. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  7680. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  7681. ** If xMutexInit fails in any way, it is expected to clean up after itself
  7682. ** prior to returning.
  7683. */
  7684. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  7685. struct sqlite3_mutex_methods {
  7686. int (*xMutexInit)(void);
  7687. int (*xMutexEnd)(void);
  7688. sqlite3_mutex *(*xMutexAlloc)(int);
  7689. void (*xMutexFree)(sqlite3_mutex *);
  7690. void (*xMutexEnter)(sqlite3_mutex *);
  7691. int (*xMutexTry)(sqlite3_mutex *);
  7692. void (*xMutexLeave)(sqlite3_mutex *);
  7693. int (*xMutexHeld)(sqlite3_mutex *);
  7694. int (*xMutexNotheld)(sqlite3_mutex *);
  7695. };
  7696. /*
  7697. ** CAPI3REF: Mutex Verification Routines
  7698. **
  7699. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  7700. ** are intended for use inside assert() statements. The SQLite core
  7701. ** never uses these routines except inside an assert() and applications
  7702. ** are advised to follow the lead of the core. The SQLite core only
  7703. ** provides implementations for these routines when it is compiled
  7704. ** with the SQLITE_DEBUG flag. External mutex implementations
  7705. ** are only required to provide these routines if SQLITE_DEBUG is
  7706. ** defined and if NDEBUG is not defined.
  7707. **
  7708. ** These routines should return true if the mutex in their argument
  7709. ** is held or not held, respectively, by the calling thread.
  7710. **
  7711. ** The implementation is not required to provide versions of these
  7712. ** routines that actually work. If the implementation does not provide working
  7713. ** versions of these routines, it should at least provide stubs that always
  7714. ** return true so that one does not get spurious assertion failures.
  7715. **
  7716. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  7717. ** the routine should return 1. This seems counter-intuitive since
  7718. ** clearly the mutex cannot be held if it does not exist. But
  7719. ** the reason the mutex does not exist is because the build is not
  7720. ** using mutexes. And we do not want the assert() containing the
  7721. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  7722. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  7723. ** interface should also return 1 when given a NULL pointer.
  7724. */
  7725. #ifndef NDEBUG
  7726. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  7727. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  7728. #endif
  7729. /*
  7730. ** CAPI3REF: Mutex Types
  7731. **
  7732. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  7733. ** which is one of these integer constants.
  7734. **
  7735. ** The set of static mutexes may change from one SQLite release to the
  7736. ** next. Applications that override the built-in mutex logic must be
  7737. ** prepared to accommodate additional static mutexes.
  7738. */
  7739. #define SQLITE_MUTEX_FAST 0
  7740. #define SQLITE_MUTEX_RECURSIVE 1
  7741. #define SQLITE_MUTEX_STATIC_MASTER 2
  7742. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  7743. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  7744. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  7745. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
  7746. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  7747. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  7748. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  7749. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  7750. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  7751. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  7752. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  7753. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  7754. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  7755. /*
  7756. ** CAPI3REF: Retrieve the mutex for a database connection
  7757. ** METHOD: sqlite3
  7758. **
  7759. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  7760. ** serializes access to the [database connection] given in the argument
  7761. ** when the [threading mode] is Serialized.
  7762. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  7763. ** routine returns a NULL pointer.
  7764. */
  7765. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  7766. /*
  7767. ** CAPI3REF: Low-Level Control Of Database Files
  7768. ** METHOD: sqlite3
  7769. **
  7770. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  7771. ** xFileControl method for the [sqlite3_io_methods] object associated
  7772. ** with a particular database identified by the second argument. ^The
  7773. ** name of the database is "main" for the main database or "temp" for the
  7774. ** TEMP database, or the name that appears after the AS keyword for
  7775. ** databases that are added using the [ATTACH] SQL command.
  7776. ** ^A NULL pointer can be used in place of "main" to refer to the
  7777. ** main database file.
  7778. ** ^The third and fourth parameters to this routine
  7779. ** are passed directly through to the second and third parameters of
  7780. ** the xFileControl method. ^The return value of the xFileControl
  7781. ** method becomes the return value of this routine.
  7782. **
  7783. ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
  7784. ** a pointer to the underlying [sqlite3_file] object to be written into
  7785. ** the space pointed to by the 4th parameter. ^The [SQLITE_FCNTL_FILE_POINTER]
  7786. ** case is a short-circuit path which does not actually invoke the
  7787. ** underlying sqlite3_io_methods.xFileControl method.
  7788. **
  7789. ** ^If the second parameter (zDbName) does not match the name of any
  7790. ** open database file, then SQLITE_ERROR is returned. ^This error
  7791. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  7792. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  7793. ** also return SQLITE_ERROR. There is no way to distinguish between
  7794. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  7795. ** xFileControl method.
  7796. **
  7797. ** See also: [file control opcodes]
  7798. */
  7799. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  7800. /*
  7801. ** CAPI3REF: Testing Interface
  7802. **
  7803. ** ^The sqlite3_test_control() interface is used to read out internal
  7804. ** state of SQLite and to inject faults into SQLite for testing
  7805. ** purposes. ^The first parameter is an operation code that determines
  7806. ** the number, meaning, and operation of all subsequent parameters.
  7807. **
  7808. ** This interface is not for use by applications. It exists solely
  7809. ** for verifying the correct operation of the SQLite library. Depending
  7810. ** on how the SQLite library is compiled, this interface might not exist.
  7811. **
  7812. ** The details of the operation codes, their meanings, the parameters
  7813. ** they take, and what they do are all subject to change without notice.
  7814. ** Unlike most of the SQLite API, this function is not guaranteed to
  7815. ** operate consistently from one release to the next.
  7816. */
  7817. SQLITE_API int sqlite3_test_control(int op, ...);
  7818. /*
  7819. ** CAPI3REF: Testing Interface Operation Codes
  7820. **
  7821. ** These constants are the valid operation code parameters used
  7822. ** as the first argument to [sqlite3_test_control()].
  7823. **
  7824. ** These parameters and their meanings are subject to change
  7825. ** without notice. These values are for testing purposes only.
  7826. ** Applications should not use any of these parameters or the
  7827. ** [sqlite3_test_control()] interface.
  7828. */
  7829. #define SQLITE_TESTCTRL_FIRST 5
  7830. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  7831. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  7832. #define SQLITE_TESTCTRL_PRNG_RESET 7
  7833. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  7834. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  7835. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  7836. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  7837. #define SQLITE_TESTCTRL_ASSERT 12
  7838. #define SQLITE_TESTCTRL_ALWAYS 13
  7839. #define SQLITE_TESTCTRL_RESERVE 14
  7840. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  7841. #define SQLITE_TESTCTRL_ISKEYWORD 16
  7842. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
  7843. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  7844. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  7845. #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
  7846. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  7847. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  7848. #define SQLITE_TESTCTRL_BYTEORDER 22
  7849. #define SQLITE_TESTCTRL_ISINIT 23
  7850. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  7851. #define SQLITE_TESTCTRL_IMPOSTER 25
  7852. #define SQLITE_TESTCTRL_PARSER_COVERAGE 26
  7853. #define SQLITE_TESTCTRL_LAST 26 /* Largest TESTCTRL */
  7854. /*
  7855. ** CAPI3REF: SQLite Runtime Status
  7856. **
  7857. ** ^These interfaces are used to retrieve runtime status information
  7858. ** about the performance of SQLite, and optionally to reset various
  7859. ** highwater marks. ^The first argument is an integer code for
  7860. ** the specific parameter to measure. ^(Recognized integer codes
  7861. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  7862. ** ^The current value of the parameter is returned into *pCurrent.
  7863. ** ^The highest recorded value is returned in *pHighwater. ^If the
  7864. ** resetFlag is true, then the highest record value is reset after
  7865. ** *pHighwater is written. ^(Some parameters do not record the highest
  7866. ** value. For those parameters
  7867. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  7868. ** ^(Other parameters record only the highwater mark and not the current
  7869. ** value. For these latter parameters nothing is written into *pCurrent.)^
  7870. **
  7871. ** ^The sqlite3_status() and sqlite3_status64() routines return
  7872. ** SQLITE_OK on success and a non-zero [error code] on failure.
  7873. **
  7874. ** If either the current value or the highwater mark is too large to
  7875. ** be represented by a 32-bit integer, then the values returned by
  7876. ** sqlite3_status() are undefined.
  7877. **
  7878. ** See also: [sqlite3_db_status()]
  7879. */
  7880. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  7881. SQLITE_API int sqlite3_status64(
  7882. int op,
  7883. sqlite3_int64 *pCurrent,
  7884. sqlite3_int64 *pHighwater,
  7885. int resetFlag
  7886. );
  7887. /*
  7888. ** CAPI3REF: Status Parameters
  7889. ** KEYWORDS: {status parameters}
  7890. **
  7891. ** These integer constants designate various run-time status parameters
  7892. ** that can be returned by [sqlite3_status()].
  7893. **
  7894. ** <dl>
  7895. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  7896. ** <dd>This parameter is the current amount of memory checked out
  7897. ** using [sqlite3_malloc()], either directly or indirectly. The
  7898. ** figure includes calls made to [sqlite3_malloc()] by the application
  7899. ** and internal memory usage by the SQLite library. Auxiliary page-cache
  7900. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  7901. ** this parameter. The amount returned is the sum of the allocation
  7902. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  7903. **
  7904. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  7905. ** <dd>This parameter records the largest memory allocation request
  7906. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  7907. ** internal equivalents). Only the value returned in the
  7908. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  7909. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  7910. **
  7911. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  7912. ** <dd>This parameter records the number of separate memory allocations
  7913. ** currently checked out.</dd>)^
  7914. **
  7915. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  7916. ** <dd>This parameter returns the number of pages used out of the
  7917. ** [pagecache memory allocator] that was configured using
  7918. ** [SQLITE_CONFIG_PAGECACHE]. The
  7919. ** value returned is in pages, not in bytes.</dd>)^
  7920. **
  7921. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  7922. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  7923. ** <dd>This parameter returns the number of bytes of page cache
  7924. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  7925. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  7926. ** returned value includes allocations that overflowed because they
  7927. ** where too large (they were larger than the "sz" parameter to
  7928. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  7929. ** no space was left in the page cache.</dd>)^
  7930. **
  7931. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  7932. ** <dd>This parameter records the largest memory allocation request
  7933. ** handed to [pagecache memory allocator]. Only the value returned in the
  7934. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  7935. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  7936. **
  7937. ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  7938. ** <dd>No longer used.</dd>
  7939. **
  7940. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  7941. ** <dd>No longer used.</dd>
  7942. **
  7943. ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  7944. ** <dd>No longer used.</dd>
  7945. **
  7946. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  7947. ** <dd>The *pHighwater parameter records the deepest parser stack.
  7948. ** The *pCurrent value is undefined. The *pHighwater value is only
  7949. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  7950. ** </dl>
  7951. **
  7952. ** New status parameters may be added from time to time.
  7953. */
  7954. #define SQLITE_STATUS_MEMORY_USED 0
  7955. #define SQLITE_STATUS_PAGECACHE_USED 1
  7956. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  7957. #define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
  7958. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
  7959. #define SQLITE_STATUS_MALLOC_SIZE 5
  7960. #define SQLITE_STATUS_PARSER_STACK 6
  7961. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  7962. #define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
  7963. #define SQLITE_STATUS_MALLOC_COUNT 9
  7964. /*
  7965. ** CAPI3REF: Database Connection Status
  7966. ** METHOD: sqlite3
  7967. **
  7968. ** ^This interface is used to retrieve runtime status information
  7969. ** about a single [database connection]. ^The first argument is the
  7970. ** database connection object to be interrogated. ^The second argument
  7971. ** is an integer constant, taken from the set of
  7972. ** [SQLITE_DBSTATUS options], that
  7973. ** determines the parameter to interrogate. The set of
  7974. ** [SQLITE_DBSTATUS options] is likely
  7975. ** to grow in future releases of SQLite.
  7976. **
  7977. ** ^The current value of the requested parameter is written into *pCur
  7978. ** and the highest instantaneous value is written into *pHiwtr. ^If
  7979. ** the resetFlg is true, then the highest instantaneous value is
  7980. ** reset back down to the current value.
  7981. **
  7982. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  7983. ** non-zero [error code] on failure.
  7984. **
  7985. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  7986. */
  7987. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  7988. /*
  7989. ** CAPI3REF: Status Parameters for database connections
  7990. ** KEYWORDS: {SQLITE_DBSTATUS options}
  7991. **
  7992. ** These constants are the available integer "verbs" that can be passed as
  7993. ** the second argument to the [sqlite3_db_status()] interface.
  7994. **
  7995. ** New verbs may be added in future releases of SQLite. Existing verbs
  7996. ** might be discontinued. Applications should check the return code from
  7997. ** [sqlite3_db_status()] to make sure that the call worked.
  7998. ** The [sqlite3_db_status()] interface will return a non-zero error code
  7999. ** if a discontinued or unsupported verb is invoked.
  8000. **
  8001. ** <dl>
  8002. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  8003. ** <dd>This parameter returns the number of lookaside memory slots currently
  8004. ** checked out.</dd>)^
  8005. **
  8006. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  8007. ** <dd>This parameter returns the number malloc attempts that were
  8008. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  8009. ** the current value is always zero.)^
  8010. **
  8011. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  8012. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  8013. ** <dd>This parameter returns the number malloc attempts that might have
  8014. ** been satisfied using lookaside memory but failed due to the amount of
  8015. ** memory requested being larger than the lookaside slot size.
  8016. ** Only the high-water value is meaningful;
  8017. ** the current value is always zero.)^
  8018. **
  8019. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  8020. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  8021. ** <dd>This parameter returns the number malloc attempts that might have
  8022. ** been satisfied using lookaside memory but failed due to all lookaside
  8023. ** memory already being in use.
  8024. ** Only the high-water value is meaningful;
  8025. ** the current value is always zero.)^
  8026. **
  8027. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  8028. ** <dd>This parameter returns the approximate number of bytes of heap
  8029. ** memory used by all pager caches associated with the database connection.)^
  8030. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  8031. **
  8032. ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
  8033. ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  8034. ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  8035. ** pager cache is shared between two or more connections the bytes of heap
  8036. ** memory used by that pager cache is divided evenly between the attached
  8037. ** connections.)^ In other words, if none of the pager caches associated
  8038. ** with the database connection are shared, this request returns the same
  8039. ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  8040. ** shared, the value returned by this call will be smaller than that returned
  8041. ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  8042. ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  8043. **
  8044. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  8045. ** <dd>This parameter returns the approximate number of bytes of heap
  8046. ** memory used to store the schema for all databases associated
  8047. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  8048. ** ^The full amount of memory used by the schemas is reported, even if the
  8049. ** schema memory is shared with other database connections due to
  8050. ** [shared cache mode] being enabled.
  8051. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  8052. **
  8053. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  8054. ** <dd>This parameter returns the approximate number of bytes of heap
  8055. ** and lookaside memory used by all prepared statements associated with
  8056. ** the database connection.)^
  8057. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  8058. ** </dd>
  8059. **
  8060. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  8061. ** <dd>This parameter returns the number of pager cache hits that have
  8062. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  8063. ** is always 0.
  8064. ** </dd>
  8065. **
  8066. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  8067. ** <dd>This parameter returns the number of pager cache misses that have
  8068. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  8069. ** is always 0.
  8070. ** </dd>
  8071. **
  8072. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  8073. ** <dd>This parameter returns the number of dirty cache entries that have
  8074. ** been written to disk. Specifically, the number of pages written to the
  8075. ** wal file in wal mode databases, or the number of pages written to the
  8076. ** database file in rollback mode databases. Any pages written as part of
  8077. ** transaction rollback or database recovery operations are not included.
  8078. ** If an IO or other error occurs while writing a page to disk, the effect
  8079. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  8080. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  8081. ** </dd>
  8082. **
  8083. ** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
  8084. ** <dd>This parameter returns the number of dirty cache entries that have
  8085. ** been written to disk in the middle of a transaction due to the page
  8086. ** cache overflowing. Transactions are more efficient if they are written
  8087. ** to disk all at once. When pages spill mid-transaction, that introduces
  8088. ** additional overhead. This parameter can be used help identify
  8089. ** inefficiencies that can be resolve by increasing the cache size.
  8090. ** </dd>
  8091. **
  8092. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  8093. ** <dd>This parameter returns zero for the current value if and only if
  8094. ** all foreign key constraints (deferred or immediate) have been
  8095. ** resolved.)^ ^The highwater mark is always 0.
  8096. ** </dd>
  8097. ** </dl>
  8098. */
  8099. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  8100. #define SQLITE_DBSTATUS_CACHE_USED 1
  8101. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  8102. #define SQLITE_DBSTATUS_STMT_USED 3
  8103. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  8104. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  8105. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  8106. #define SQLITE_DBSTATUS_CACHE_HIT 7
  8107. #define SQLITE_DBSTATUS_CACHE_MISS 8
  8108. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  8109. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  8110. #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
  8111. #define SQLITE_DBSTATUS_CACHE_SPILL 12
  8112. #define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */
  8113. /*
  8114. ** CAPI3REF: Prepared Statement Status
  8115. ** METHOD: sqlite3_stmt
  8116. **
  8117. ** ^(Each prepared statement maintains various
  8118. ** [SQLITE_STMTSTATUS counters] that measure the number
  8119. ** of times it has performed specific operations.)^ These counters can
  8120. ** be used to monitor the performance characteristics of the prepared
  8121. ** statements. For example, if the number of table steps greatly exceeds
  8122. ** the number of table searches or result rows, that would tend to indicate
  8123. ** that the prepared statement is using a full table scan rather than
  8124. ** an index.
  8125. **
  8126. ** ^(This interface is used to retrieve and reset counter values from
  8127. ** a [prepared statement]. The first argument is the prepared statement
  8128. ** object to be interrogated. The second argument
  8129. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  8130. ** to be interrogated.)^
  8131. ** ^The current value of the requested counter is returned.
  8132. ** ^If the resetFlg is true, then the counter is reset to zero after this
  8133. ** interface call returns.
  8134. **
  8135. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  8136. */
  8137. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  8138. /*
  8139. ** CAPI3REF: Status Parameters for prepared statements
  8140. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  8141. **
  8142. ** These preprocessor macros define integer codes that name counter
  8143. ** values associated with the [sqlite3_stmt_status()] interface.
  8144. ** The meanings of the various counters are as follows:
  8145. **
  8146. ** <dl>
  8147. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  8148. ** <dd>^This is the number of times that SQLite has stepped forward in
  8149. ** a table as part of a full table scan. Large numbers for this counter
  8150. ** may indicate opportunities for performance improvement through
  8151. ** careful use of indices.</dd>
  8152. **
  8153. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  8154. ** <dd>^This is the number of sort operations that have occurred.
  8155. ** A non-zero value in this counter may indicate an opportunity to
  8156. ** improvement performance through careful use of indices.</dd>
  8157. **
  8158. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  8159. ** <dd>^This is the number of rows inserted into transient indices that
  8160. ** were created automatically in order to help joins run faster.
  8161. ** A non-zero value in this counter may indicate an opportunity to
  8162. ** improvement performance by adding permanent indices that do not
  8163. ** need to be reinitialized each time the statement is run.</dd>
  8164. **
  8165. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  8166. ** <dd>^This is the number of virtual machine operations executed
  8167. ** by the prepared statement if that number is less than or equal
  8168. ** to 2147483647. The number of virtual machine operations can be
  8169. ** used as a proxy for the total work done by the prepared statement.
  8170. ** If the number of virtual machine operations exceeds 2147483647
  8171. ** then the value returned by this statement status code is undefined.
  8172. **
  8173. ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
  8174. ** <dd>^This is the number of times that the prepare statement has been
  8175. ** automatically regenerated due to schema changes or change to
  8176. ** [bound parameters] that might affect the query plan.
  8177. **
  8178. ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
  8179. ** <dd>^This is the number of times that the prepared statement has
  8180. ** been run. A single "run" for the purposes of this counter is one
  8181. ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
  8182. ** The counter is incremented on the first [sqlite3_step()] call of each
  8183. ** cycle.
  8184. **
  8185. ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
  8186. ** <dd>^This is the approximate number of bytes of heap memory
  8187. ** used to store the prepared statement. ^This value is not actually
  8188. ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
  8189. ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
  8190. ** </dd>
  8191. ** </dl>
  8192. */
  8193. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  8194. #define SQLITE_STMTSTATUS_SORT 2
  8195. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  8196. #define SQLITE_STMTSTATUS_VM_STEP 4
  8197. #define SQLITE_STMTSTATUS_REPREPARE 5
  8198. #define SQLITE_STMTSTATUS_RUN 6
  8199. #define SQLITE_STMTSTATUS_MEMUSED 99
  8200. /*
  8201. ** CAPI3REF: Custom Page Cache Object
  8202. **
  8203. ** The sqlite3_pcache type is opaque. It is implemented by
  8204. ** the pluggable module. The SQLite core has no knowledge of
  8205. ** its size or internal structure and never deals with the
  8206. ** sqlite3_pcache object except by holding and passing pointers
  8207. ** to the object.
  8208. **
  8209. ** See [sqlite3_pcache_methods2] for additional information.
  8210. */
  8211. typedef struct sqlite3_pcache sqlite3_pcache;
  8212. /*
  8213. ** CAPI3REF: Custom Page Cache Object
  8214. **
  8215. ** The sqlite3_pcache_page object represents a single page in the
  8216. ** page cache. The page cache will allocate instances of this
  8217. ** object. Various methods of the page cache use pointers to instances
  8218. ** of this object as parameters or as their return value.
  8219. **
  8220. ** See [sqlite3_pcache_methods2] for additional information.
  8221. */
  8222. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  8223. struct sqlite3_pcache_page {
  8224. void *pBuf; /* The content of the page */
  8225. void *pExtra; /* Extra information associated with the page */
  8226. };
  8227. /*
  8228. ** CAPI3REF: Application Defined Page Cache.
  8229. ** KEYWORDS: {page cache}
  8230. **
  8231. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  8232. ** register an alternative page cache implementation by passing in an
  8233. ** instance of the sqlite3_pcache_methods2 structure.)^
  8234. ** In many applications, most of the heap memory allocated by
  8235. ** SQLite is used for the page cache.
  8236. ** By implementing a
  8237. ** custom page cache using this API, an application can better control
  8238. ** the amount of memory consumed by SQLite, the way in which
  8239. ** that memory is allocated and released, and the policies used to
  8240. ** determine exactly which parts of a database file are cached and for
  8241. ** how long.
  8242. **
  8243. ** The alternative page cache mechanism is an
  8244. ** extreme measure that is only needed by the most demanding applications.
  8245. ** The built-in page cache is recommended for most uses.
  8246. **
  8247. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  8248. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  8249. ** the application may discard the parameter after the call to
  8250. ** [sqlite3_config()] returns.)^
  8251. **
  8252. ** [[the xInit() page cache method]]
  8253. ** ^(The xInit() method is called once for each effective
  8254. ** call to [sqlite3_initialize()])^
  8255. ** (usually only once during the lifetime of the process). ^(The xInit()
  8256. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  8257. ** The intent of the xInit() method is to set up global data structures
  8258. ** required by the custom page cache implementation.
  8259. ** ^(If the xInit() method is NULL, then the
  8260. ** built-in default page cache is used instead of the application defined
  8261. ** page cache.)^
  8262. **
  8263. ** [[the xShutdown() page cache method]]
  8264. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  8265. ** It can be used to clean up
  8266. ** any outstanding resources before process shutdown, if required.
  8267. ** ^The xShutdown() method may be NULL.
  8268. **
  8269. ** ^SQLite automatically serializes calls to the xInit method,
  8270. ** so the xInit method need not be threadsafe. ^The
  8271. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  8272. ** not need to be threadsafe either. All other methods must be threadsafe
  8273. ** in multithreaded applications.
  8274. **
  8275. ** ^SQLite will never invoke xInit() more than once without an intervening
  8276. ** call to xShutdown().
  8277. **
  8278. ** [[the xCreate() page cache methods]]
  8279. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  8280. ** SQLite will typically create one cache instance for each open database file,
  8281. ** though this is not guaranteed. ^The
  8282. ** first parameter, szPage, is the size in bytes of the pages that must
  8283. ** be allocated by the cache. ^szPage will always a power of two. ^The
  8284. ** second parameter szExtra is a number of bytes of extra storage
  8285. ** associated with each page cache entry. ^The szExtra parameter will
  8286. ** a number less than 250. SQLite will use the
  8287. ** extra szExtra bytes on each page to store metadata about the underlying
  8288. ** database page on disk. The value passed into szExtra depends
  8289. ** on the SQLite version, the target platform, and how SQLite was compiled.
  8290. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  8291. ** created will be used to cache database pages of a file stored on disk, or
  8292. ** false if it is used for an in-memory database. The cache implementation
  8293. ** does not have to do anything special based with the value of bPurgeable;
  8294. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  8295. ** never invoke xUnpin() except to deliberately delete a page.
  8296. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  8297. ** false will always have the "discard" flag set to true.
  8298. ** ^Hence, a cache created with bPurgeable false will
  8299. ** never contain any unpinned pages.
  8300. **
  8301. ** [[the xCachesize() page cache method]]
  8302. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  8303. ** suggested maximum cache-size (number of pages stored by) the cache
  8304. ** instance passed as the first argument. This is the value configured using
  8305. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  8306. ** parameter, the implementation is not required to do anything with this
  8307. ** value; it is advisory only.
  8308. **
  8309. ** [[the xPagecount() page cache methods]]
  8310. ** The xPagecount() method must return the number of pages currently
  8311. ** stored in the cache, both pinned and unpinned.
  8312. **
  8313. ** [[the xFetch() page cache methods]]
  8314. ** The xFetch() method locates a page in the cache and returns a pointer to
  8315. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  8316. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  8317. ** pointer to a buffer of szPage bytes used to store the content of a
  8318. ** single database page. The pExtra element of sqlite3_pcache_page will be
  8319. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  8320. ** for each entry in the page cache.
  8321. **
  8322. ** The page to be fetched is determined by the key. ^The minimum key value
  8323. ** is 1. After it has been retrieved using xFetch, the page is considered
  8324. ** to be "pinned".
  8325. **
  8326. ** If the requested page is already in the page cache, then the page cache
  8327. ** implementation must return a pointer to the page buffer with its content
  8328. ** intact. If the requested page is not already in the cache, then the
  8329. ** cache implementation should use the value of the createFlag
  8330. ** parameter to help it determined what action to take:
  8331. **
  8332. ** <table border=1 width=85% align=center>
  8333. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  8334. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  8335. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  8336. ** Otherwise return NULL.
  8337. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  8338. ** NULL if allocating a new page is effectively impossible.
  8339. ** </table>
  8340. **
  8341. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  8342. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  8343. ** failed.)^ In between the to xFetch() calls, SQLite may
  8344. ** attempt to unpin one or more cache pages by spilling the content of
  8345. ** pinned pages to disk and synching the operating system disk cache.
  8346. **
  8347. ** [[the xUnpin() page cache method]]
  8348. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  8349. ** as its second argument. If the third parameter, discard, is non-zero,
  8350. ** then the page must be evicted from the cache.
  8351. ** ^If the discard parameter is
  8352. ** zero, then the page may be discarded or retained at the discretion of
  8353. ** page cache implementation. ^The page cache implementation
  8354. ** may choose to evict unpinned pages at any time.
  8355. **
  8356. ** The cache must not perform any reference counting. A single
  8357. ** call to xUnpin() unpins the page regardless of the number of prior calls
  8358. ** to xFetch().
  8359. **
  8360. ** [[the xRekey() page cache methods]]
  8361. ** The xRekey() method is used to change the key value associated with the
  8362. ** page passed as the second argument. If the cache
  8363. ** previously contains an entry associated with newKey, it must be
  8364. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  8365. ** to be pinned.
  8366. **
  8367. ** When SQLite calls the xTruncate() method, the cache must discard all
  8368. ** existing cache entries with page numbers (keys) greater than or equal
  8369. ** to the value of the iLimit parameter passed to xTruncate(). If any
  8370. ** of these pages are pinned, they are implicitly unpinned, meaning that
  8371. ** they can be safely discarded.
  8372. **
  8373. ** [[the xDestroy() page cache method]]
  8374. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  8375. ** All resources associated with the specified cache should be freed. ^After
  8376. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  8377. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  8378. ** functions.
  8379. **
  8380. ** [[the xShrink() page cache method]]
  8381. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  8382. ** free up as much of heap memory as possible. The page cache implementation
  8383. ** is not obligated to free any memory, but well-behaved implementations should
  8384. ** do their best.
  8385. */
  8386. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  8387. struct sqlite3_pcache_methods2 {
  8388. int iVersion;
  8389. void *pArg;
  8390. int (*xInit)(void*);
  8391. void (*xShutdown)(void*);
  8392. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  8393. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8394. int (*xPagecount)(sqlite3_pcache*);
  8395. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8396. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  8397. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  8398. unsigned oldKey, unsigned newKey);
  8399. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8400. void (*xDestroy)(sqlite3_pcache*);
  8401. void (*xShrink)(sqlite3_pcache*);
  8402. };
  8403. /*
  8404. ** This is the obsolete pcache_methods object that has now been replaced
  8405. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  8406. ** retained in the header file for backwards compatibility only.
  8407. */
  8408. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  8409. struct sqlite3_pcache_methods {
  8410. void *pArg;
  8411. int (*xInit)(void*);
  8412. void (*xShutdown)(void*);
  8413. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  8414. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  8415. int (*xPagecount)(sqlite3_pcache*);
  8416. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  8417. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  8418. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  8419. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  8420. void (*xDestroy)(sqlite3_pcache*);
  8421. };
  8422. /*
  8423. ** CAPI3REF: Online Backup Object
  8424. **
  8425. ** The sqlite3_backup object records state information about an ongoing
  8426. ** online backup operation. ^The sqlite3_backup object is created by
  8427. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  8428. ** [sqlite3_backup_finish()].
  8429. **
  8430. ** See Also: [Using the SQLite Online Backup API]
  8431. */
  8432. typedef struct sqlite3_backup sqlite3_backup;
  8433. /*
  8434. ** CAPI3REF: Online Backup API.
  8435. **
  8436. ** The backup API copies the content of one database into another.
  8437. ** It is useful either for creating backups of databases or
  8438. ** for copying in-memory databases to or from persistent files.
  8439. **
  8440. ** See Also: [Using the SQLite Online Backup API]
  8441. **
  8442. ** ^SQLite holds a write transaction open on the destination database file
  8443. ** for the duration of the backup operation.
  8444. ** ^The source database is read-locked only while it is being read;
  8445. ** it is not locked continuously for the entire backup operation.
  8446. ** ^Thus, the backup may be performed on a live source database without
  8447. ** preventing other database connections from
  8448. ** reading or writing to the source database while the backup is underway.
  8449. **
  8450. ** ^(To perform a backup operation:
  8451. ** <ol>
  8452. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  8453. ** backup,
  8454. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  8455. ** the data between the two databases, and finally
  8456. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  8457. ** associated with the backup operation.
  8458. ** </ol>)^
  8459. ** There should be exactly one call to sqlite3_backup_finish() for each
  8460. ** successful call to sqlite3_backup_init().
  8461. **
  8462. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  8463. **
  8464. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  8465. ** [database connection] associated with the destination database
  8466. ** and the database name, respectively.
  8467. ** ^The database name is "main" for the main database, "temp" for the
  8468. ** temporary database, or the name specified after the AS keyword in
  8469. ** an [ATTACH] statement for an attached database.
  8470. ** ^The S and M arguments passed to
  8471. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  8472. ** and database name of the source database, respectively.
  8473. ** ^The source and destination [database connections] (parameters S and D)
  8474. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  8475. ** an error.
  8476. **
  8477. ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
  8478. ** there is already a read or read-write transaction open on the
  8479. ** destination database.
  8480. **
  8481. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  8482. ** returned and an error code and error message are stored in the
  8483. ** destination [database connection] D.
  8484. ** ^The error code and message for the failed call to sqlite3_backup_init()
  8485. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  8486. ** [sqlite3_errmsg16()] functions.
  8487. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  8488. ** [sqlite3_backup] object.
  8489. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  8490. ** sqlite3_backup_finish() functions to perform the specified backup
  8491. ** operation.
  8492. **
  8493. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  8494. **
  8495. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  8496. ** the source and destination databases specified by [sqlite3_backup] object B.
  8497. ** ^If N is negative, all remaining source pages are copied.
  8498. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  8499. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  8500. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  8501. ** from source to destination, then it returns [SQLITE_DONE].
  8502. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  8503. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  8504. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  8505. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  8506. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  8507. **
  8508. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  8509. ** <ol>
  8510. ** <li> the destination database was opened read-only, or
  8511. ** <li> the destination database is using write-ahead-log journaling
  8512. ** and the destination and source page sizes differ, or
  8513. ** <li> the destination database is an in-memory database and the
  8514. ** destination and source page sizes differ.
  8515. ** </ol>)^
  8516. **
  8517. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  8518. ** the [sqlite3_busy_handler | busy-handler function]
  8519. ** is invoked (if one is specified). ^If the
  8520. ** busy-handler returns non-zero before the lock is available, then
  8521. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  8522. ** sqlite3_backup_step() can be retried later. ^If the source
  8523. ** [database connection]
  8524. ** is being used to write to the source database when sqlite3_backup_step()
  8525. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  8526. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  8527. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  8528. ** [SQLITE_READONLY] is returned, then
  8529. ** there is no point in retrying the call to sqlite3_backup_step(). These
  8530. ** errors are considered fatal.)^ The application must accept
  8531. ** that the backup operation has failed and pass the backup operation handle
  8532. ** to the sqlite3_backup_finish() to release associated resources.
  8533. **
  8534. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  8535. ** on the destination file. ^The exclusive lock is not released until either
  8536. ** sqlite3_backup_finish() is called or the backup operation is complete
  8537. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  8538. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  8539. ** lasts for the duration of the sqlite3_backup_step() call.
  8540. ** ^Because the source database is not locked between calls to
  8541. ** sqlite3_backup_step(), the source database may be modified mid-way
  8542. ** through the backup process. ^If the source database is modified by an
  8543. ** external process or via a database connection other than the one being
  8544. ** used by the backup operation, then the backup will be automatically
  8545. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  8546. ** database is modified by the using the same database connection as is used
  8547. ** by the backup operation, then the backup database is automatically
  8548. ** updated at the same time.
  8549. **
  8550. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  8551. **
  8552. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  8553. ** application wishes to abandon the backup operation, the application
  8554. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  8555. ** ^The sqlite3_backup_finish() interfaces releases all
  8556. ** resources associated with the [sqlite3_backup] object.
  8557. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  8558. ** active write-transaction on the destination database is rolled back.
  8559. ** The [sqlite3_backup] object is invalid
  8560. ** and may not be used following a call to sqlite3_backup_finish().
  8561. **
  8562. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  8563. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  8564. ** sqlite3_backup_step() completed.
  8565. ** ^If an out-of-memory condition or IO error occurred during any prior
  8566. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  8567. ** sqlite3_backup_finish() returns the corresponding [error code].
  8568. **
  8569. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  8570. ** is not a permanent error and does not affect the return value of
  8571. ** sqlite3_backup_finish().
  8572. **
  8573. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  8574. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  8575. **
  8576. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  8577. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  8578. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  8579. ** in the source database at the conclusion of the most recent
  8580. ** sqlite3_backup_step().
  8581. ** ^(The values returned by these functions are only updated by
  8582. ** sqlite3_backup_step(). If the source database is modified in a way that
  8583. ** changes the size of the source database or the number of pages remaining,
  8584. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  8585. ** and sqlite3_backup_remaining() until after the next
  8586. ** sqlite3_backup_step().)^
  8587. **
  8588. ** <b>Concurrent Usage of Database Handles</b>
  8589. **
  8590. ** ^The source [database connection] may be used by the application for other
  8591. ** purposes while a backup operation is underway or being initialized.
  8592. ** ^If SQLite is compiled and configured to support threadsafe database
  8593. ** connections, then the source database connection may be used concurrently
  8594. ** from within other threads.
  8595. **
  8596. ** However, the application must guarantee that the destination
  8597. ** [database connection] is not passed to any other API (by any thread) after
  8598. ** sqlite3_backup_init() is called and before the corresponding call to
  8599. ** sqlite3_backup_finish(). SQLite does not currently check to see
  8600. ** if the application incorrectly accesses the destination [database connection]
  8601. ** and so no error code is reported, but the operations may malfunction
  8602. ** nevertheless. Use of the destination database connection while a
  8603. ** backup is in progress might also also cause a mutex deadlock.
  8604. **
  8605. ** If running in [shared cache mode], the application must
  8606. ** guarantee that the shared cache used by the destination database
  8607. ** is not accessed while the backup is running. In practice this means
  8608. ** that the application must guarantee that the disk file being
  8609. ** backed up to is not accessed by any connection within the process,
  8610. ** not just the specific connection that was passed to sqlite3_backup_init().
  8611. **
  8612. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  8613. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  8614. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  8615. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  8616. ** same time as another thread is invoking sqlite3_backup_step() it is
  8617. ** possible that they return invalid values.
  8618. */
  8619. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  8620. sqlite3 *pDest, /* Destination database handle */
  8621. const char *zDestName, /* Destination database name */
  8622. sqlite3 *pSource, /* Source database handle */
  8623. const char *zSourceName /* Source database name */
  8624. );
  8625. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  8626. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  8627. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  8628. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  8629. /*
  8630. ** CAPI3REF: Unlock Notification
  8631. ** METHOD: sqlite3
  8632. **
  8633. ** ^When running in shared-cache mode, a database operation may fail with
  8634. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  8635. ** individual tables within the shared-cache cannot be obtained. See
  8636. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  8637. ** ^This API may be used to register a callback that SQLite will invoke
  8638. ** when the connection currently holding the required lock relinquishes it.
  8639. ** ^This API is only available if the library was compiled with the
  8640. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  8641. **
  8642. ** See Also: [Using the SQLite Unlock Notification Feature].
  8643. **
  8644. ** ^Shared-cache locks are released when a database connection concludes
  8645. ** its current transaction, either by committing it or rolling it back.
  8646. **
  8647. ** ^When a connection (known as the blocked connection) fails to obtain a
  8648. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  8649. ** identity of the database connection (the blocking connection) that
  8650. ** has locked the required resource is stored internally. ^After an
  8651. ** application receives an SQLITE_LOCKED error, it may call the
  8652. ** sqlite3_unlock_notify() method with the blocked connection handle as
  8653. ** the first argument to register for a callback that will be invoked
  8654. ** when the blocking connections current transaction is concluded. ^The
  8655. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  8656. ** call that concludes the blocking connections transaction.
  8657. **
  8658. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  8659. ** there is a chance that the blocking connection will have already
  8660. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  8661. ** If this happens, then the specified callback is invoked immediately,
  8662. ** from within the call to sqlite3_unlock_notify().)^
  8663. **
  8664. ** ^If the blocked connection is attempting to obtain a write-lock on a
  8665. ** shared-cache table, and more than one other connection currently holds
  8666. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  8667. ** the other connections to use as the blocking connection.
  8668. **
  8669. ** ^(There may be at most one unlock-notify callback registered by a
  8670. ** blocked connection. If sqlite3_unlock_notify() is called when the
  8671. ** blocked connection already has a registered unlock-notify callback,
  8672. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  8673. ** called with a NULL pointer as its second argument, then any existing
  8674. ** unlock-notify callback is canceled. ^The blocked connections
  8675. ** unlock-notify callback may also be canceled by closing the blocked
  8676. ** connection using [sqlite3_close()].
  8677. **
  8678. ** The unlock-notify callback is not reentrant. If an application invokes
  8679. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  8680. ** crash or deadlock may be the result.
  8681. **
  8682. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  8683. ** returns SQLITE_OK.
  8684. **
  8685. ** <b>Callback Invocation Details</b>
  8686. **
  8687. ** When an unlock-notify callback is registered, the application provides a
  8688. ** single void* pointer that is passed to the callback when it is invoked.
  8689. ** However, the signature of the callback function allows SQLite to pass
  8690. ** it an array of void* context pointers. The first argument passed to
  8691. ** an unlock-notify callback is a pointer to an array of void* pointers,
  8692. ** and the second is the number of entries in the array.
  8693. **
  8694. ** When a blocking connections transaction is concluded, there may be
  8695. ** more than one blocked connection that has registered for an unlock-notify
  8696. ** callback. ^If two or more such blocked connections have specified the
  8697. ** same callback function, then instead of invoking the callback function
  8698. ** multiple times, it is invoked once with the set of void* context pointers
  8699. ** specified by the blocked connections bundled together into an array.
  8700. ** This gives the application an opportunity to prioritize any actions
  8701. ** related to the set of unblocked database connections.
  8702. **
  8703. ** <b>Deadlock Detection</b>
  8704. **
  8705. ** Assuming that after registering for an unlock-notify callback a
  8706. ** database waits for the callback to be issued before taking any further
  8707. ** action (a reasonable assumption), then using this API may cause the
  8708. ** application to deadlock. For example, if connection X is waiting for
  8709. ** connection Y's transaction to be concluded, and similarly connection
  8710. ** Y is waiting on connection X's transaction, then neither connection
  8711. ** will proceed and the system may remain deadlocked indefinitely.
  8712. **
  8713. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  8714. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  8715. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  8716. ** unlock-notify callback is registered. The system is said to be in
  8717. ** a deadlocked state if connection A has registered for an unlock-notify
  8718. ** callback on the conclusion of connection B's transaction, and connection
  8719. ** B has itself registered for an unlock-notify callback when connection
  8720. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  8721. ** the system is also considered to be deadlocked if connection B has
  8722. ** registered for an unlock-notify callback on the conclusion of connection
  8723. ** C's transaction, where connection C is waiting on connection A. ^Any
  8724. ** number of levels of indirection are allowed.
  8725. **
  8726. ** <b>The "DROP TABLE" Exception</b>
  8727. **
  8728. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  8729. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  8730. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  8731. ** SQLite checks if there are any currently executing SELECT statements
  8732. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  8733. ** returned. In this case there is no "blocking connection", so invoking
  8734. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  8735. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  8736. ** or "DROP INDEX" query, an infinite loop might be the result.
  8737. **
  8738. ** One way around this problem is to check the extended error code returned
  8739. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  8740. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  8741. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  8742. ** SQLITE_LOCKED.)^
  8743. */
  8744. SQLITE_API int sqlite3_unlock_notify(
  8745. sqlite3 *pBlocked, /* Waiting connection */
  8746. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  8747. void *pNotifyArg /* Argument to pass to xNotify */
  8748. );
  8749. /*
  8750. ** CAPI3REF: String Comparison
  8751. **
  8752. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  8753. ** and extensions to compare the contents of two buffers containing UTF-8
  8754. ** strings in a case-independent fashion, using the same definition of "case
  8755. ** independence" that SQLite uses internally when comparing identifiers.
  8756. */
  8757. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  8758. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  8759. /*
  8760. ** CAPI3REF: String Globbing
  8761. *
  8762. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  8763. ** string X matches the [GLOB] pattern P.
  8764. ** ^The definition of [GLOB] pattern matching used in
  8765. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  8766. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  8767. ** is case sensitive.
  8768. **
  8769. ** Note that this routine returns zero on a match and non-zero if the strings
  8770. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  8771. **
  8772. ** See also: [sqlite3_strlike()].
  8773. */
  8774. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  8775. /*
  8776. ** CAPI3REF: String LIKE Matching
  8777. *
  8778. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  8779. ** string X matches the [LIKE] pattern P with escape character E.
  8780. ** ^The definition of [LIKE] pattern matching used in
  8781. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  8782. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  8783. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  8784. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  8785. ** insensitive - equivalent upper and lower case ASCII characters match
  8786. ** one another.
  8787. **
  8788. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  8789. ** only ASCII characters are case folded.
  8790. **
  8791. ** Note that this routine returns zero on a match and non-zero if the strings
  8792. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  8793. **
  8794. ** See also: [sqlite3_strglob()].
  8795. */
  8796. SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  8797. /*
  8798. ** CAPI3REF: Error Logging Interface
  8799. **
  8800. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  8801. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  8802. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  8803. ** used with [sqlite3_snprintf()] to generate the final output string.
  8804. **
  8805. ** The sqlite3_log() interface is intended for use by extensions such as
  8806. ** virtual tables, collating functions, and SQL functions. While there is
  8807. ** nothing to prevent an application from calling sqlite3_log(), doing so
  8808. ** is considered bad form.
  8809. **
  8810. ** The zFormat string must not be NULL.
  8811. **
  8812. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  8813. ** will not use dynamically allocated memory. The log message is stored in
  8814. ** a fixed-length buffer on the stack. If the log message is longer than
  8815. ** a few hundred characters, it will be truncated to the length of the
  8816. ** buffer.
  8817. */
  8818. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  8819. /*
  8820. ** CAPI3REF: Write-Ahead Log Commit Hook
  8821. ** METHOD: sqlite3
  8822. **
  8823. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  8824. ** is invoked each time data is committed to a database in wal mode.
  8825. **
  8826. ** ^(The callback is invoked by SQLite after the commit has taken place and
  8827. ** the associated write-lock on the database released)^, so the implementation
  8828. ** may read, write or [checkpoint] the database as required.
  8829. **
  8830. ** ^The first parameter passed to the callback function when it is invoked
  8831. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  8832. ** registering the callback. ^The second is a copy of the database handle.
  8833. ** ^The third parameter is the name of the database that was written to -
  8834. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  8835. ** is the number of pages currently in the write-ahead log file,
  8836. ** including those that were just committed.
  8837. **
  8838. ** The callback function should normally return [SQLITE_OK]. ^If an error
  8839. ** code is returned, that error will propagate back up through the
  8840. ** SQLite code base to cause the statement that provoked the callback
  8841. ** to report an error, though the commit will have still occurred. If the
  8842. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  8843. ** that does not correspond to any valid SQLite error code, the results
  8844. ** are undefined.
  8845. **
  8846. ** A single database handle may have at most a single write-ahead log callback
  8847. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  8848. ** previously registered write-ahead log callback. ^Note that the
  8849. ** [sqlite3_wal_autocheckpoint()] interface and the
  8850. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  8851. ** overwrite any prior [sqlite3_wal_hook()] settings.
  8852. */
  8853. SQLITE_API void *sqlite3_wal_hook(
  8854. sqlite3*,
  8855. int(*)(void *,sqlite3*,const char*,int),
  8856. void*
  8857. );
  8858. /*
  8859. ** CAPI3REF: Configure an auto-checkpoint
  8860. ** METHOD: sqlite3
  8861. **
  8862. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  8863. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  8864. ** to automatically [checkpoint]
  8865. ** after committing a transaction if there are N or
  8866. ** more frames in the [write-ahead log] file. ^Passing zero or
  8867. ** a negative value as the nFrame parameter disables automatic
  8868. ** checkpoints entirely.
  8869. **
  8870. ** ^The callback registered by this function replaces any existing callback
  8871. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  8872. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  8873. ** configured by this function.
  8874. **
  8875. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  8876. ** from SQL.
  8877. **
  8878. ** ^Checkpoints initiated by this mechanism are
  8879. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  8880. **
  8881. ** ^Every new [database connection] defaults to having the auto-checkpoint
  8882. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  8883. ** pages. The use of this interface
  8884. ** is only necessary if the default setting is found to be suboptimal
  8885. ** for a particular application.
  8886. */
  8887. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  8888. /*
  8889. ** CAPI3REF: Checkpoint a database
  8890. ** METHOD: sqlite3
  8891. **
  8892. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  8893. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  8894. **
  8895. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  8896. ** [write-ahead log] for database X on [database connection] D to be
  8897. ** transferred into the database file and for the write-ahead log to
  8898. ** be reset. See the [checkpointing] documentation for addition
  8899. ** information.
  8900. **
  8901. ** This interface used to be the only way to cause a checkpoint to
  8902. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  8903. ** interface was added. This interface is retained for backwards
  8904. ** compatibility and as a convenience for applications that need to manually
  8905. ** start a callback but which do not need the full power (and corresponding
  8906. ** complication) of [sqlite3_wal_checkpoint_v2()].
  8907. */
  8908. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  8909. /*
  8910. ** CAPI3REF: Checkpoint a database
  8911. ** METHOD: sqlite3
  8912. **
  8913. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  8914. ** operation on database X of [database connection] D in mode M. Status
  8915. ** information is written back into integers pointed to by L and C.)^
  8916. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  8917. **
  8918. ** <dl>
  8919. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  8920. ** ^Checkpoint as many frames as possible without waiting for any database
  8921. ** readers or writers to finish, then sync the database file if all frames
  8922. ** in the log were checkpointed. ^The [busy-handler callback]
  8923. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  8924. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  8925. ** if there are concurrent readers or writers.
  8926. **
  8927. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  8928. ** ^This mode blocks (it invokes the
  8929. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  8930. ** database writer and all readers are reading from the most recent database
  8931. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  8932. ** database file. ^This mode blocks new database writers while it is pending,
  8933. ** but new database readers are allowed to continue unimpeded.
  8934. **
  8935. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  8936. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  8937. ** that after checkpointing the log file it blocks (calls the
  8938. ** [busy-handler callback])
  8939. ** until all readers are reading from the database file only. ^This ensures
  8940. ** that the next writer will restart the log file from the beginning.
  8941. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  8942. ** database writer attempts while it is pending, but does not impede readers.
  8943. **
  8944. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  8945. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  8946. ** addition that it also truncates the log file to zero bytes just prior
  8947. ** to a successful return.
  8948. ** </dl>
  8949. **
  8950. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  8951. ** the log file or to -1 if the checkpoint could not run because
  8952. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  8953. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  8954. ** log file (including any that were already checkpointed before the function
  8955. ** was called) or to -1 if the checkpoint could not run due to an error or
  8956. ** because the database is not in WAL mode. ^Note that upon successful
  8957. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  8958. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  8959. **
  8960. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  8961. ** any other process is running a checkpoint operation at the same time, the
  8962. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  8963. ** busy-handler configured, it will not be invoked in this case.
  8964. **
  8965. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  8966. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  8967. ** obtained immediately, and a busy-handler is configured, it is invoked and
  8968. ** the writer lock retried until either the busy-handler returns 0 or the lock
  8969. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  8970. ** database readers as described above. ^If the busy-handler returns 0 before
  8971. ** the writer lock is obtained or while waiting for database readers, the
  8972. ** checkpoint operation proceeds from that point in the same way as
  8973. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  8974. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  8975. **
  8976. ** ^If parameter zDb is NULL or points to a zero length string, then the
  8977. ** specified operation is attempted on all WAL databases [attached] to
  8978. ** [database connection] db. In this case the
  8979. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  8980. ** an SQLITE_BUSY error is encountered when processing one or more of the
  8981. ** attached WAL databases, the operation is still attempted on any remaining
  8982. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  8983. ** error occurs while processing an attached database, processing is abandoned
  8984. ** and the error code is returned to the caller immediately. ^If no error
  8985. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  8986. ** databases, SQLITE_OK is returned.
  8987. **
  8988. ** ^If database zDb is the name of an attached database that is not in WAL
  8989. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  8990. ** zDb is not NULL (or a zero length string) and is not the name of any
  8991. ** attached database, SQLITE_ERROR is returned to the caller.
  8992. **
  8993. ** ^Unless it returns SQLITE_MISUSE,
  8994. ** the sqlite3_wal_checkpoint_v2() interface
  8995. ** sets the error information that is queried by
  8996. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  8997. **
  8998. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  8999. ** from SQL.
  9000. */
  9001. SQLITE_API int sqlite3_wal_checkpoint_v2(
  9002. sqlite3 *db, /* Database handle */
  9003. const char *zDb, /* Name of attached database (or NULL) */
  9004. int eMode, /* SQLITE_CHECKPOINT_* value */
  9005. int *pnLog, /* OUT: Size of WAL log in frames */
  9006. int *pnCkpt /* OUT: Total number of frames checkpointed */
  9007. );
  9008. /*
  9009. ** CAPI3REF: Checkpoint Mode Values
  9010. ** KEYWORDS: {checkpoint mode}
  9011. **
  9012. ** These constants define all valid values for the "checkpoint mode" passed
  9013. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  9014. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  9015. ** meaning of each of these checkpoint modes.
  9016. */
  9017. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  9018. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  9019. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  9020. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  9021. /*
  9022. ** CAPI3REF: Virtual Table Interface Configuration
  9023. **
  9024. ** This function may be called by either the [xConnect] or [xCreate] method
  9025. ** of a [virtual table] implementation to configure
  9026. ** various facets of the virtual table interface.
  9027. **
  9028. ** If this interface is invoked outside the context of an xConnect or
  9029. ** xCreate virtual table method then the behavior is undefined.
  9030. **
  9031. ** At present, there is only one option that may be configured using
  9032. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  9033. ** may be added in the future.
  9034. */
  9035. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  9036. /*
  9037. ** CAPI3REF: Virtual Table Configuration Options
  9038. **
  9039. ** These macros define the various options to the
  9040. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  9041. ** can use to customize and optimize their behavior.
  9042. **
  9043. ** <dl>
  9044. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  9045. ** <dd>Calls of the form
  9046. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  9047. ** where X is an integer. If X is zero, then the [virtual table] whose
  9048. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  9049. ** support constraints. In this configuration (which is the default) if
  9050. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  9051. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  9052. ** specified as part of the users SQL statement, regardless of the actual
  9053. ** ON CONFLICT mode specified.
  9054. **
  9055. ** If X is non-zero, then the virtual table implementation guarantees
  9056. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  9057. ** any modifications to internal or persistent data structures have been made.
  9058. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  9059. ** is able to roll back a statement or database transaction, and abandon
  9060. ** or continue processing the current SQL statement as appropriate.
  9061. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  9062. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  9063. ** had been ABORT.
  9064. **
  9065. ** Virtual table implementations that are required to handle OR REPLACE
  9066. ** must do so within the [xUpdate] method. If a call to the
  9067. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  9068. ** CONFLICT policy is REPLACE, the virtual table implementation should
  9069. ** silently replace the appropriate rows within the xUpdate callback and
  9070. ** return SQLITE_OK. Or, if this is not possible, it may return
  9071. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  9072. ** constraint handling.
  9073. ** </dl>
  9074. */
  9075. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  9076. /*
  9077. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  9078. **
  9079. ** This function may only be called from within a call to the [xUpdate] method
  9080. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  9081. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  9082. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  9083. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  9084. ** [virtual table].
  9085. */
  9086. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  9087. /*
  9088. ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
  9089. **
  9090. ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
  9091. ** method of a [virtual table], then it returns true if and only if the
  9092. ** column is being fetched as part of an UPDATE operation during which the
  9093. ** column value will not change. Applications might use this to substitute
  9094. ** a lighter-weight value to return that the corresponding [xUpdate] method
  9095. ** understands as a "no-change" value.
  9096. **
  9097. ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
  9098. ** the column is not changed by the UPDATE statement, they the xColumn
  9099. ** method can optionally return without setting a result, without calling
  9100. ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
  9101. ** In that case, [sqlite3_value_nochange(X)] will return true for the
  9102. ** same column in the [xUpdate] method.
  9103. */
  9104. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
  9105. /*
  9106. ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
  9107. **
  9108. ** This function may only be called from within a call to the [xBestIndex]
  9109. ** method of a [virtual table].
  9110. **
  9111. ** The first argument must be the sqlite3_index_info object that is the
  9112. ** first parameter to the xBestIndex() method. The second argument must be
  9113. ** an index into the aConstraint[] array belonging to the sqlite3_index_info
  9114. ** structure passed to xBestIndex. This function returns a pointer to a buffer
  9115. ** containing the name of the collation sequence for the corresponding
  9116. ** constraint.
  9117. */
  9118. SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
  9119. /*
  9120. ** CAPI3REF: Conflict resolution modes
  9121. ** KEYWORDS: {conflict resolution mode}
  9122. **
  9123. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  9124. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  9125. ** is for the SQL statement being evaluated.
  9126. **
  9127. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  9128. ** return value from the [sqlite3_set_authorizer()] callback and that
  9129. ** [SQLITE_ABORT] is also a [result code].
  9130. */
  9131. #define SQLITE_ROLLBACK 1
  9132. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  9133. #define SQLITE_FAIL 3
  9134. /* #define SQLITE_ABORT 4 // Also an error code */
  9135. #define SQLITE_REPLACE 5
  9136. /*
  9137. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  9138. ** KEYWORDS: {scanstatus options}
  9139. **
  9140. ** The following constants can be used for the T parameter to the
  9141. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  9142. ** different metric for sqlite3_stmt_scanstatus() to return.
  9143. **
  9144. ** When the value returned to V is a string, space to hold that string is
  9145. ** managed by the prepared statement S and will be automatically freed when
  9146. ** S is finalized.
  9147. **
  9148. ** <dl>
  9149. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  9150. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  9151. ** set to the total number of times that the X-th loop has run.</dd>
  9152. **
  9153. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  9154. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  9155. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  9156. **
  9157. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  9158. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  9159. ** query planner's estimate for the average number of rows output from each
  9160. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  9161. ** then this value will approximate the quotient NVISIT/NLOOP and the
  9162. ** product of this value for all prior loops with the same SELECTID will
  9163. ** be the NLOOP value for the current loop.
  9164. **
  9165. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  9166. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9167. ** to a zero-terminated UTF-8 string containing the name of the index or table
  9168. ** used for the X-th loop.
  9169. **
  9170. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  9171. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  9172. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  9173. ** description for the X-th loop.
  9174. **
  9175. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  9176. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  9177. ** "select-id" for the X-th loop. The select-id identifies which query or
  9178. ** subquery the loop is part of. The main query has a select-id of zero.
  9179. ** The select-id is the same value as is output in the first column
  9180. ** of an [EXPLAIN QUERY PLAN] query.
  9181. ** </dl>
  9182. */
  9183. #define SQLITE_SCANSTAT_NLOOP 0
  9184. #define SQLITE_SCANSTAT_NVISIT 1
  9185. #define SQLITE_SCANSTAT_EST 2
  9186. #define SQLITE_SCANSTAT_NAME 3
  9187. #define SQLITE_SCANSTAT_EXPLAIN 4
  9188. #define SQLITE_SCANSTAT_SELECTID 5
  9189. /*
  9190. ** CAPI3REF: Prepared Statement Scan Status
  9191. ** METHOD: sqlite3_stmt
  9192. **
  9193. ** This interface returns information about the predicted and measured
  9194. ** performance for pStmt. Advanced applications can use this
  9195. ** interface to compare the predicted and the measured performance and
  9196. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  9197. **
  9198. ** Since this interface is expected to be rarely used, it is only
  9199. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  9200. ** compile-time option.
  9201. **
  9202. ** The "iScanStatusOp" parameter determines which status information to return.
  9203. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  9204. ** of this interface is undefined.
  9205. ** ^The requested measurement is written into a variable pointed to by
  9206. ** the "pOut" parameter.
  9207. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  9208. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  9209. ** zero or greater than or equal to the total number of loops used to implement
  9210. ** the statement - a non-zero value is returned and the variable that pOut
  9211. ** points to is unchanged.
  9212. **
  9213. ** ^Statistics might not be available for all loops in all statements. ^In cases
  9214. ** where there exist loops with no available statistics, this function behaves
  9215. ** as if the loop did not exist - it returns non-zero and leave the variable
  9216. ** that pOut points to unchanged.
  9217. **
  9218. ** See also: [sqlite3_stmt_scanstatus_reset()]
  9219. */
  9220. SQLITE_API int sqlite3_stmt_scanstatus(
  9221. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  9222. int idx, /* Index of loop to report on */
  9223. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  9224. void *pOut /* Result written here */
  9225. );
  9226. /*
  9227. ** CAPI3REF: Zero Scan-Status Counters
  9228. ** METHOD: sqlite3_stmt
  9229. **
  9230. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  9231. **
  9232. ** This API is only available if the library is built with pre-processor
  9233. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  9234. */
  9235. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  9236. /*
  9237. ** CAPI3REF: Flush caches to disk mid-transaction
  9238. **
  9239. ** ^If a write-transaction is open on [database connection] D when the
  9240. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  9241. ** pages in the pager-cache that are not currently in use are written out
  9242. ** to disk. A dirty page may be in use if a database cursor created by an
  9243. ** active SQL statement is reading from it, or if it is page 1 of a database
  9244. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  9245. ** interface flushes caches for all schemas - "main", "temp", and
  9246. ** any [attached] databases.
  9247. **
  9248. ** ^If this function needs to obtain extra database locks before dirty pages
  9249. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  9250. ** immediately and there is a busy-handler callback configured, it is invoked
  9251. ** in the usual manner. ^If the required lock still cannot be obtained, then
  9252. ** the database is skipped and an attempt made to flush any dirty pages
  9253. ** belonging to the next (if any) database. ^If any databases are skipped
  9254. ** because locks cannot be obtained, but no other error occurs, this
  9255. ** function returns SQLITE_BUSY.
  9256. **
  9257. ** ^If any other error occurs while flushing dirty pages to disk (for
  9258. ** example an IO error or out-of-memory condition), then processing is
  9259. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  9260. **
  9261. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  9262. **
  9263. ** ^This function does not set the database handle error code or message
  9264. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  9265. */
  9266. SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  9267. /*
  9268. ** CAPI3REF: The pre-update hook.
  9269. **
  9270. ** ^These interfaces are only available if SQLite is compiled using the
  9271. ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  9272. **
  9273. ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  9274. ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
  9275. ** on a database table.
  9276. ** ^At most one preupdate hook may be registered at a time on a single
  9277. ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
  9278. ** the previous setting.
  9279. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
  9280. ** with a NULL pointer as the second parameter.
  9281. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
  9282. ** the first parameter to callbacks.
  9283. **
  9284. ** ^The preupdate hook only fires for changes to real database tables; the
  9285. ** preupdate hook is not invoked for changes to [virtual tables] or to
  9286. ** system tables like sqlite_master or sqlite_stat1.
  9287. **
  9288. ** ^The second parameter to the preupdate callback is a pointer to
  9289. ** the [database connection] that registered the preupdate hook.
  9290. ** ^The third parameter to the preupdate callback is one of the constants
  9291. ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
  9292. ** kind of update operation that is about to occur.
  9293. ** ^(The fourth parameter to the preupdate callback is the name of the
  9294. ** database within the database connection that is being modified. This
  9295. ** will be "main" for the main database or "temp" for TEMP tables or
  9296. ** the name given after the AS keyword in the [ATTACH] statement for attached
  9297. ** databases.)^
  9298. ** ^The fifth parameter to the preupdate callback is the name of the
  9299. ** table that is being modified.
  9300. **
  9301. ** For an UPDATE or DELETE operation on a [rowid table], the sixth
  9302. ** parameter passed to the preupdate callback is the initial [rowid] of the
  9303. ** row being modified or deleted. For an INSERT operation on a rowid table,
  9304. ** or any operation on a WITHOUT ROWID table, the value of the sixth
  9305. ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
  9306. ** seventh parameter is the final rowid value of the row being inserted
  9307. ** or updated. The value of the seventh parameter passed to the callback
  9308. ** function is not defined for operations on WITHOUT ROWID tables, or for
  9309. ** INSERT operations on rowid tables.
  9310. **
  9311. ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
  9312. ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
  9313. ** provide additional information about a preupdate event. These routines
  9314. ** may only be called from within a preupdate callback. Invoking any of
  9315. ** these routines from outside of a preupdate callback or with a
  9316. ** [database connection] pointer that is different from the one supplied
  9317. ** to the preupdate callback results in undefined and probably undesirable
  9318. ** behavior.
  9319. **
  9320. ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
  9321. ** in the row that is being inserted, updated, or deleted.
  9322. **
  9323. ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
  9324. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9325. ** the table row before it is updated. The N parameter must be between 0
  9326. ** and one less than the number of columns or the behavior will be
  9327. ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
  9328. ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
  9329. ** behavior is undefined. The [sqlite3_value] that P points to
  9330. ** will be destroyed when the preupdate callback returns.
  9331. **
  9332. ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
  9333. ** a [protected sqlite3_value] that contains the value of the Nth column of
  9334. ** the table row after it is updated. The N parameter must be between 0
  9335. ** and one less than the number of columns or the behavior will be
  9336. ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
  9337. ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
  9338. ** behavior is undefined. The [sqlite3_value] that P points to
  9339. ** will be destroyed when the preupdate callback returns.
  9340. **
  9341. ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
  9342. ** callback was invoked as a result of a direct insert, update, or delete
  9343. ** operation; or 1 for inserts, updates, or deletes invoked by top-level
  9344. ** triggers; or 2 for changes resulting from triggers called by top-level
  9345. ** triggers; and so forth.
  9346. **
  9347. ** See also: [sqlite3_update_hook()]
  9348. */
  9349. #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  9350. SQLITE_API void *sqlite3_preupdate_hook(
  9351. sqlite3 *db,
  9352. void(*xPreUpdate)(
  9353. void *pCtx, /* Copy of third arg to preupdate_hook() */
  9354. sqlite3 *db, /* Database handle */
  9355. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  9356. char const *zDb, /* Database name */
  9357. char const *zName, /* Table name */
  9358. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  9359. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  9360. ),
  9361. void*
  9362. );
  9363. SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
  9364. SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
  9365. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
  9366. SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
  9367. #endif
  9368. /*
  9369. ** CAPI3REF: Low-level system error code
  9370. **
  9371. ** ^Attempt to return the underlying operating system error code or error
  9372. ** number that caused the most recent I/O error or failure to open a file.
  9373. ** The return value is OS-dependent. For example, on unix systems, after
  9374. ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  9375. ** called to get back the underlying "errno" that caused the problem, such
  9376. ** as ENOSPC, EAUTH, EISDIR, and so forth.
  9377. */
  9378. SQLITE_API int sqlite3_system_errno(sqlite3*);
  9379. /*
  9380. ** CAPI3REF: Database Snapshot
  9381. ** KEYWORDS: {snapshot} {sqlite3_snapshot}
  9382. ** EXPERIMENTAL
  9383. **
  9384. ** An instance of the snapshot object records the state of a [WAL mode]
  9385. ** database for some specific point in history.
  9386. **
  9387. ** In [WAL mode], multiple [database connections] that are open on the
  9388. ** same database file can each be reading a different historical version
  9389. ** of the database file. When a [database connection] begins a read
  9390. ** transaction, that connection sees an unchanging copy of the database
  9391. ** as it existed for the point in time when the transaction first started.
  9392. ** Subsequent changes to the database from other connections are not seen
  9393. ** by the reader until a new read transaction is started.
  9394. **
  9395. ** The sqlite3_snapshot object records state information about an historical
  9396. ** version of the database file so that it is possible to later open a new read
  9397. ** transaction that sees that historical version of the database rather than
  9398. ** the most recent version.
  9399. **
  9400. ** The constructor for this object is [sqlite3_snapshot_get()]. The
  9401. ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
  9402. ** to an historical snapshot (if possible). The destructor for
  9403. ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
  9404. */
  9405. typedef struct sqlite3_snapshot {
  9406. unsigned char hidden[48];
  9407. } sqlite3_snapshot;
  9408. /*
  9409. ** CAPI3REF: Record A Database Snapshot
  9410. ** EXPERIMENTAL
  9411. **
  9412. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  9413. ** new [sqlite3_snapshot] object that records the current state of
  9414. ** schema S in database connection D. ^On success, the
  9415. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  9416. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  9417. ** If there is not already a read-transaction open on schema S when
  9418. ** this function is called, one is opened automatically.
  9419. **
  9420. ** The following must be true for this function to succeed. If any of
  9421. ** the following statements are false when sqlite3_snapshot_get() is
  9422. ** called, SQLITE_ERROR is returned. The final value of *P is undefined
  9423. ** in this case.
  9424. **
  9425. ** <ul>
  9426. ** <li> The database handle must be in [autocommit mode].
  9427. **
  9428. ** <li> Schema S of [database connection] D must be a [WAL mode] database.
  9429. **
  9430. ** <li> There must not be a write transaction open on schema S of database
  9431. ** connection D.
  9432. **
  9433. ** <li> One or more transactions must have been written to the current wal
  9434. ** file since it was created on disk (by any connection). This means
  9435. ** that a snapshot cannot be taken on a wal mode database with no wal
  9436. ** file immediately after it is first opened. At least one transaction
  9437. ** must be written to it first.
  9438. ** </ul>
  9439. **
  9440. ** This function may also return SQLITE_NOMEM. If it is called with the
  9441. ** database handle in autocommit mode but fails for some other reason,
  9442. ** whether or not a read transaction is opened on schema S is undefined.
  9443. **
  9444. ** The [sqlite3_snapshot] object returned from a successful call to
  9445. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  9446. ** to avoid a memory leak.
  9447. **
  9448. ** The [sqlite3_snapshot_get()] interface is only available when the
  9449. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9450. */
  9451. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
  9452. sqlite3 *db,
  9453. const char *zSchema,
  9454. sqlite3_snapshot **ppSnapshot
  9455. );
  9456. /*
  9457. ** CAPI3REF: Start a read transaction on an historical snapshot
  9458. ** EXPERIMENTAL
  9459. **
  9460. ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
  9461. ** read transaction for schema S of
  9462. ** [database connection] D such that the read transaction
  9463. ** refers to historical [snapshot] P, rather than the most
  9464. ** recent change to the database.
  9465. ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
  9466. ** or an appropriate [error code] if it fails.
  9467. **
  9468. ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
  9469. ** the first operation following the [BEGIN] that takes the schema S
  9470. ** out of [autocommit mode].
  9471. ** ^In other words, schema S must not currently be in
  9472. ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
  9473. ** database connection D must be out of [autocommit mode].
  9474. ** ^A [snapshot] will fail to open if it has been overwritten by a
  9475. ** [checkpoint].
  9476. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
  9477. ** database connection D does not know that the database file for
  9478. ** schema S is in [WAL mode]. A database connection might not know
  9479. ** that the database file is in [WAL mode] if there has been no prior
  9480. ** I/O on that database connection, or if the database entered [WAL mode]
  9481. ** after the most recent I/O on the database connection.)^
  9482. ** (Hint: Run "[PRAGMA application_id]" against a newly opened
  9483. ** database connection in order to make it ready to use snapshots.)
  9484. **
  9485. ** The [sqlite3_snapshot_open()] interface is only available when the
  9486. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9487. */
  9488. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
  9489. sqlite3 *db,
  9490. const char *zSchema,
  9491. sqlite3_snapshot *pSnapshot
  9492. );
  9493. /*
  9494. ** CAPI3REF: Destroy a snapshot
  9495. ** EXPERIMENTAL
  9496. **
  9497. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  9498. ** The application must eventually free every [sqlite3_snapshot] object
  9499. ** using this routine to avoid a memory leak.
  9500. **
  9501. ** The [sqlite3_snapshot_free()] interface is only available when the
  9502. ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
  9503. */
  9504. SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
  9505. /*
  9506. ** CAPI3REF: Compare the ages of two snapshot handles.
  9507. ** EXPERIMENTAL
  9508. **
  9509. ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
  9510. ** of two valid snapshot handles.
  9511. **
  9512. ** If the two snapshot handles are not associated with the same database
  9513. ** file, the result of the comparison is undefined.
  9514. **
  9515. ** Additionally, the result of the comparison is only valid if both of the
  9516. ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
  9517. ** last time the wal file was deleted. The wal file is deleted when the
  9518. ** database is changed back to rollback mode or when the number of database
  9519. ** clients drops to zero. If either snapshot handle was obtained before the
  9520. ** wal file was last deleted, the value returned by this function
  9521. ** is undefined.
  9522. **
  9523. ** Otherwise, this API returns a negative value if P1 refers to an older
  9524. ** snapshot than P2, zero if the two handles refer to the same database
  9525. ** snapshot, and a positive value if P1 is a newer snapshot than P2.
  9526. */
  9527. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
  9528. sqlite3_snapshot *p1,
  9529. sqlite3_snapshot *p2
  9530. );
  9531. /*
  9532. ** CAPI3REF: Recover snapshots from a wal file
  9533. ** EXPERIMENTAL
  9534. **
  9535. ** If all connections disconnect from a database file but do not perform
  9536. ** a checkpoint, the existing wal file is opened along with the database
  9537. ** file the next time the database is opened. At this point it is only
  9538. ** possible to successfully call sqlite3_snapshot_open() to open the most
  9539. ** recent snapshot of the database (the one at the head of the wal file),
  9540. ** even though the wal file may contain other valid snapshots for which
  9541. ** clients have sqlite3_snapshot handles.
  9542. **
  9543. ** This function attempts to scan the wal file associated with database zDb
  9544. ** of database handle db and make all valid snapshots available to
  9545. ** sqlite3_snapshot_open(). It is an error if there is already a read
  9546. ** transaction open on the database, or if the database is not a wal mode
  9547. ** database.
  9548. **
  9549. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  9550. */
  9551. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
  9552. /*
  9553. ** CAPI3REF: Serialize a database
  9554. **
  9555. ** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
  9556. ** that is a serialization of the S database on [database connection] D.
  9557. ** If P is not a NULL pointer, then the size of the database in bytes
  9558. ** is written into *P.
  9559. **
  9560. ** For an ordinary on-disk database file, the serialization is just a
  9561. ** copy of the disk file. For an in-memory database or a "TEMP" database,
  9562. ** the serialization is the same sequence of bytes which would be written
  9563. ** to disk if that database where backed up to disk.
  9564. **
  9565. ** The usual case is that sqlite3_serialize() copies the serialization of
  9566. ** the database into memory obtained from [sqlite3_malloc64()] and returns
  9567. ** a pointer to that memory. The caller is responsible for freeing the
  9568. ** returned value to avoid a memory leak. However, if the F argument
  9569. ** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
  9570. ** are made, and the sqlite3_serialize() function will return a pointer
  9571. ** to the contiguous memory representation of the database that SQLite
  9572. ** is currently using for that database, or NULL if the no such contiguous
  9573. ** memory representation of the database exists. A contiguous memory
  9574. ** representation of the database will usually only exist if there has
  9575. ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
  9576. ** values of D and S.
  9577. ** The size of the database is written into *P even if the
  9578. ** SQLITE_SERIALIZE_NOCOPY bit is set but no contigious copy
  9579. ** of the database exists.
  9580. **
  9581. ** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
  9582. ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
  9583. ** allocation error occurs.
  9584. **
  9585. ** This interface is only available if SQLite is compiled with the
  9586. ** [SQLITE_ENABLE_DESERIALIZE] option.
  9587. */
  9588. SQLITE_API unsigned char *sqlite3_serialize(
  9589. sqlite3 *db, /* The database connection */
  9590. const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
  9591. sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
  9592. unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
  9593. );
  9594. /*
  9595. ** CAPI3REF: Flags for sqlite3_serialize
  9596. **
  9597. ** Zero or more of the following constants can be OR-ed together for
  9598. ** the F argument to [sqlite3_serialize(D,S,P,F)].
  9599. **
  9600. ** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
  9601. ** a pointer to contiguous in-memory database that it is currently using,
  9602. ** without making a copy of the database. If SQLite is not currently using
  9603. ** a contiguous in-memory database, then this option causes
  9604. ** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
  9605. ** using a contiguous in-memory database if it has been initialized by a
  9606. ** prior call to [sqlite3_deserialize()].
  9607. */
  9608. #define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */
  9609. /*
  9610. ** CAPI3REF: Deserialize a database
  9611. **
  9612. ** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
  9613. ** [database connection] D to disconnect from database S and then
  9614. ** reopen S as an in-memory database based on the serialization contained
  9615. ** in P. The serialized database P is N bytes in size. M is the size of
  9616. ** the buffer P, which might be larger than N. If M is larger than N, and
  9617. ** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
  9618. ** permitted to add content to the in-memory database as long as the total
  9619. ** size does not exceed M bytes.
  9620. **
  9621. ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
  9622. ** invoke sqlite3_free() on the serialization buffer when the database
  9623. ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
  9624. ** SQLite will try to increase the buffer size using sqlite3_realloc64()
  9625. ** if writes on the database cause it to grow larger than M bytes.
  9626. **
  9627. ** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
  9628. ** database is currently in a read transaction or is involved in a backup
  9629. ** operation.
  9630. **
  9631. ** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
  9632. ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
  9633. ** [sqlite3_free()] is invoked on argument P prior to returning.
  9634. **
  9635. ** This interface is only available if SQLite is compiled with the
  9636. ** [SQLITE_ENABLE_DESERIALIZE] option.
  9637. */
  9638. SQLITE_API int sqlite3_deserialize(
  9639. sqlite3 *db, /* The database connection */
  9640. const char *zSchema, /* Which DB to reopen with the deserialization */
  9641. unsigned char *pData, /* The serialized database content */
  9642. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  9643. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  9644. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  9645. );
  9646. /*
  9647. ** CAPI3REF: Flags for sqlite3_deserialize()
  9648. **
  9649. ** The following are allowed values for 6th argument (the F argument) to
  9650. ** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
  9651. **
  9652. ** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
  9653. ** in the P argument is held in memory obtained from [sqlite3_malloc64()]
  9654. ** and that SQLite should take ownership of this memory and automatically
  9655. ** free it when it has finished using it. Without this flag, the caller
  9656. ** is resposible for freeing any dynamically allocated memory.
  9657. **
  9658. ** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
  9659. ** grow the size of the database using calls to [sqlite3_realloc64()]. This
  9660. ** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
  9661. ** Without this flag, the deserialized database cannot increase in size beyond
  9662. ** the number of bytes specified by the M parameter.
  9663. **
  9664. ** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
  9665. ** should be treated as read-only.
  9666. */
  9667. #define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
  9668. #define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */
  9669. #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
  9670. /*
  9671. ** Undo the hack that converts floating point types to integer for
  9672. ** builds on processors without floating point support.
  9673. */
  9674. #ifdef SQLITE_OMIT_FLOATING_POINT
  9675. # undef double
  9676. #endif
  9677. #if 0
  9678. } /* End of the 'extern "C"' block */
  9679. #endif
  9680. #endif /* SQLITE3_H */
  9681. /******** Begin file sqlite3rtree.h *********/
  9682. /*
  9683. ** 2010 August 30
  9684. **
  9685. ** The author disclaims copyright to this source code. In place of
  9686. ** a legal notice, here is a blessing:
  9687. **
  9688. ** May you do good and not evil.
  9689. ** May you find forgiveness for yourself and forgive others.
  9690. ** May you share freely, never taking more than you give.
  9691. **
  9692. *************************************************************************
  9693. */
  9694. #ifndef _SQLITE3RTREE_H_
  9695. #define _SQLITE3RTREE_H_
  9696. #if 0
  9697. extern "C" {
  9698. #endif
  9699. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  9700. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  9701. /* The double-precision datatype used by RTree depends on the
  9702. ** SQLITE_RTREE_INT_ONLY compile-time option.
  9703. */
  9704. #ifdef SQLITE_RTREE_INT_ONLY
  9705. typedef sqlite3_int64 sqlite3_rtree_dbl;
  9706. #else
  9707. typedef double sqlite3_rtree_dbl;
  9708. #endif
  9709. /*
  9710. ** Register a geometry callback named zGeom that can be used as part of an
  9711. ** R-Tree geometry query as follows:
  9712. **
  9713. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  9714. */
  9715. SQLITE_API int sqlite3_rtree_geometry_callback(
  9716. sqlite3 *db,
  9717. const char *zGeom,
  9718. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  9719. void *pContext
  9720. );
  9721. /*
  9722. ** A pointer to a structure of the following type is passed as the first
  9723. ** argument to callbacks registered using rtree_geometry_callback().
  9724. */
  9725. struct sqlite3_rtree_geometry {
  9726. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  9727. int nParam; /* Size of array aParam[] */
  9728. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  9729. void *pUser; /* Callback implementation user data */
  9730. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  9731. };
  9732. /*
  9733. ** Register a 2nd-generation geometry callback named zScore that can be
  9734. ** used as part of an R-Tree geometry query as follows:
  9735. **
  9736. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  9737. */
  9738. SQLITE_API int sqlite3_rtree_query_callback(
  9739. sqlite3 *db,
  9740. const char *zQueryFunc,
  9741. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  9742. void *pContext,
  9743. void (*xDestructor)(void*)
  9744. );
  9745. /*
  9746. ** A pointer to a structure of the following type is passed as the
  9747. ** argument to scored geometry callback registered using
  9748. ** sqlite3_rtree_query_callback().
  9749. **
  9750. ** Note that the first 5 fields of this structure are identical to
  9751. ** sqlite3_rtree_geometry. This structure is a subclass of
  9752. ** sqlite3_rtree_geometry.
  9753. */
  9754. struct sqlite3_rtree_query_info {
  9755. void *pContext; /* pContext from when function registered */
  9756. int nParam; /* Number of function parameters */
  9757. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  9758. void *pUser; /* callback can use this, if desired */
  9759. void (*xDelUser)(void*); /* function to free pUser */
  9760. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  9761. unsigned int *anQueue; /* Number of pending entries in the queue */
  9762. int nCoord; /* Number of coordinates */
  9763. int iLevel; /* Level of current node or entry */
  9764. int mxLevel; /* The largest iLevel value in the tree */
  9765. sqlite3_int64 iRowid; /* Rowid for current entry */
  9766. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  9767. int eParentWithin; /* Visibility of parent node */
  9768. int eWithin; /* OUT: Visiblity */
  9769. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  9770. /* The following fields are only available in 3.8.11 and later */
  9771. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  9772. };
  9773. /*
  9774. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  9775. */
  9776. #define NOT_WITHIN 0 /* Object completely outside of query region */
  9777. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  9778. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  9779. #if 0
  9780. } /* end of the 'extern "C"' block */
  9781. #endif
  9782. #endif /* ifndef _SQLITE3RTREE_H_ */
  9783. /******** End of sqlite3rtree.h *********/
  9784. /******** Begin file sqlite3session.h *********/
  9785. #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
  9786. #define __SQLITESESSION_H_ 1
  9787. /*
  9788. ** Make sure we can call this stuff from C++.
  9789. */
  9790. #if 0
  9791. extern "C" {
  9792. #endif
  9793. /*
  9794. ** CAPI3REF: Session Object Handle
  9795. **
  9796. ** An instance of this object is a [session] that can be used to
  9797. ** record changes to a database.
  9798. */
  9799. typedef struct sqlite3_session sqlite3_session;
  9800. /*
  9801. ** CAPI3REF: Changeset Iterator Handle
  9802. **
  9803. ** An instance of this object acts as a cursor for iterating
  9804. ** over the elements of a [changeset] or [patchset].
  9805. */
  9806. typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
  9807. /*
  9808. ** CAPI3REF: Create A New Session Object
  9809. ** CONSTRUCTOR: sqlite3_session
  9810. **
  9811. ** Create a new session object attached to database handle db. If successful,
  9812. ** a pointer to the new object is written to *ppSession and SQLITE_OK is
  9813. ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
  9814. ** error code (e.g. SQLITE_NOMEM) is returned.
  9815. **
  9816. ** It is possible to create multiple session objects attached to a single
  9817. ** database handle.
  9818. **
  9819. ** Session objects created using this function should be deleted using the
  9820. ** [sqlite3session_delete()] function before the database handle that they
  9821. ** are attached to is itself closed. If the database handle is closed before
  9822. ** the session object is deleted, then the results of calling any session
  9823. ** module function, including [sqlite3session_delete()] on the session object
  9824. ** are undefined.
  9825. **
  9826. ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
  9827. ** is not possible for an application to register a pre-update hook on a
  9828. ** database handle that has one or more session objects attached. Nor is
  9829. ** it possible to create a session object attached to a database handle for
  9830. ** which a pre-update hook is already defined. The results of attempting
  9831. ** either of these things are undefined.
  9832. **
  9833. ** The session object will be used to create changesets for tables in
  9834. ** database zDb, where zDb is either "main", or "temp", or the name of an
  9835. ** attached database. It is not an error if database zDb is not attached
  9836. ** to the database when the session object is created.
  9837. */
  9838. SQLITE_API int sqlite3session_create(
  9839. sqlite3 *db, /* Database handle */
  9840. const char *zDb, /* Name of db (e.g. "main") */
  9841. sqlite3_session **ppSession /* OUT: New session object */
  9842. );
  9843. /*
  9844. ** CAPI3REF: Delete A Session Object
  9845. ** DESTRUCTOR: sqlite3_session
  9846. **
  9847. ** Delete a session object previously allocated using
  9848. ** [sqlite3session_create()]. Once a session object has been deleted, the
  9849. ** results of attempting to use pSession with any other session module
  9850. ** function are undefined.
  9851. **
  9852. ** Session objects must be deleted before the database handle to which they
  9853. ** are attached is closed. Refer to the documentation for
  9854. ** [sqlite3session_create()] for details.
  9855. */
  9856. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
  9857. /*
  9858. ** CAPI3REF: Enable Or Disable A Session Object
  9859. ** METHOD: sqlite3_session
  9860. **
  9861. ** Enable or disable the recording of changes by a session object. When
  9862. ** enabled, a session object records changes made to the database. When
  9863. ** disabled - it does not. A newly created session object is enabled.
  9864. ** Refer to the documentation for [sqlite3session_changeset()] for further
  9865. ** details regarding how enabling and disabling a session object affects
  9866. ** the eventual changesets.
  9867. **
  9868. ** Passing zero to this function disables the session. Passing a value
  9869. ** greater than zero enables it. Passing a value less than zero is a
  9870. ** no-op, and may be used to query the current state of the session.
  9871. **
  9872. ** The return value indicates the final state of the session object: 0 if
  9873. ** the session is disabled, or 1 if it is enabled.
  9874. */
  9875. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
  9876. /*
  9877. ** CAPI3REF: Set Or Clear the Indirect Change Flag
  9878. ** METHOD: sqlite3_session
  9879. **
  9880. ** Each change recorded by a session object is marked as either direct or
  9881. ** indirect. A change is marked as indirect if either:
  9882. **
  9883. ** <ul>
  9884. ** <li> The session object "indirect" flag is set when the change is
  9885. ** made, or
  9886. ** <li> The change is made by an SQL trigger or foreign key action
  9887. ** instead of directly as a result of a users SQL statement.
  9888. ** </ul>
  9889. **
  9890. ** If a single row is affected by more than one operation within a session,
  9891. ** then the change is considered indirect if all operations meet the criteria
  9892. ** for an indirect change above, or direct otherwise.
  9893. **
  9894. ** This function is used to set, clear or query the session object indirect
  9895. ** flag. If the second argument passed to this function is zero, then the
  9896. ** indirect flag is cleared. If it is greater than zero, the indirect flag
  9897. ** is set. Passing a value less than zero does not modify the current value
  9898. ** of the indirect flag, and may be used to query the current state of the
  9899. ** indirect flag for the specified session object.
  9900. **
  9901. ** The return value indicates the final state of the indirect flag: 0 if
  9902. ** it is clear, or 1 if it is set.
  9903. */
  9904. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
  9905. /*
  9906. ** CAPI3REF: Attach A Table To A Session Object
  9907. ** METHOD: sqlite3_session
  9908. **
  9909. ** If argument zTab is not NULL, then it is the name of a table to attach
  9910. ** to the session object passed as the first argument. All subsequent changes
  9911. ** made to the table while the session object is enabled will be recorded. See
  9912. ** documentation for [sqlite3session_changeset()] for further details.
  9913. **
  9914. ** Or, if argument zTab is NULL, then changes are recorded for all tables
  9915. ** in the database. If additional tables are added to the database (by
  9916. ** executing "CREATE TABLE" statements) after this call is made, changes for
  9917. ** the new tables are also recorded.
  9918. **
  9919. ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
  9920. ** defined as part of their CREATE TABLE statement. It does not matter if the
  9921. ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
  9922. ** KEY may consist of a single column, or may be a composite key.
  9923. **
  9924. ** It is not an error if the named table does not exist in the database. Nor
  9925. ** is it an error if the named table does not have a PRIMARY KEY. However,
  9926. ** no changes will be recorded in either of these scenarios.
  9927. **
  9928. ** Changes are not recorded for individual rows that have NULL values stored
  9929. ** in one or more of their PRIMARY KEY columns.
  9930. **
  9931. ** SQLITE_OK is returned if the call completes without error. Or, if an error
  9932. ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  9933. **
  9934. ** <h3>Special sqlite_stat1 Handling</h3>
  9935. **
  9936. ** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
  9937. ** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
  9938. ** <pre>
  9939. ** &nbsp; CREATE TABLE sqlite_stat1(tbl,idx,stat)
  9940. ** </pre>
  9941. **
  9942. ** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
  9943. ** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
  9944. ** are recorded for rows for which (idx IS NULL) is true. However, for such
  9945. ** rows a zero-length blob (SQL value X'') is stored in the changeset or
  9946. ** patchset instead of a NULL value. This allows such changesets to be
  9947. ** manipulated by legacy implementations of sqlite3changeset_invert(),
  9948. ** concat() and similar.
  9949. **
  9950. ** The sqlite3changeset_apply() function automatically converts the
  9951. ** zero-length blob back to a NULL value when updating the sqlite_stat1
  9952. ** table. However, if the application calls sqlite3changeset_new(),
  9953. ** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
  9954. ** iterator directly (including on a changeset iterator passed to a
  9955. ** conflict-handler callback) then the X'' value is returned. The application
  9956. ** must translate X'' to NULL itself if required.
  9957. **
  9958. ** Legacy (older than 3.22.0) versions of the sessions module cannot capture
  9959. ** changes made to the sqlite_stat1 table. Legacy versions of the
  9960. ** sqlite3changeset_apply() function silently ignore any modifications to the
  9961. ** sqlite_stat1 table that are part of a changeset or patchset.
  9962. */
  9963. SQLITE_API int sqlite3session_attach(
  9964. sqlite3_session *pSession, /* Session object */
  9965. const char *zTab /* Table name */
  9966. );
  9967. /*
  9968. ** CAPI3REF: Set a table filter on a Session Object.
  9969. ** METHOD: sqlite3_session
  9970. **
  9971. ** The second argument (xFilter) is the "filter callback". For changes to rows
  9972. ** in tables that are not attached to the Session object, the filter is called
  9973. ** to determine whether changes to the table's rows should be tracked or not.
  9974. ** If xFilter returns 0, changes is not tracked. Note that once a table is
  9975. ** attached, xFilter will not be called again.
  9976. */
  9977. SQLITE_API void sqlite3session_table_filter(
  9978. sqlite3_session *pSession, /* Session object */
  9979. int(*xFilter)(
  9980. void *pCtx, /* Copy of third arg to _filter_table() */
  9981. const char *zTab /* Table name */
  9982. ),
  9983. void *pCtx /* First argument passed to xFilter */
  9984. );
  9985. /*
  9986. ** CAPI3REF: Generate A Changeset From A Session Object
  9987. ** METHOD: sqlite3_session
  9988. **
  9989. ** Obtain a changeset containing changes to the tables attached to the
  9990. ** session object passed as the first argument. If successful,
  9991. ** set *ppChangeset to point to a buffer containing the changeset
  9992. ** and *pnChangeset to the size of the changeset in bytes before returning
  9993. ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
  9994. ** zero and return an SQLite error code.
  9995. **
  9996. ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
  9997. ** each representing a change to a single row of an attached table. An INSERT
  9998. ** change contains the values of each field of a new database row. A DELETE
  9999. ** contains the original values of each field of a deleted database row. An
  10000. ** UPDATE change contains the original values of each field of an updated
  10001. ** database row along with the updated values for each updated non-primary-key
  10002. ** column. It is not possible for an UPDATE change to represent a change that
  10003. ** modifies the values of primary key columns. If such a change is made, it
  10004. ** is represented in a changeset as a DELETE followed by an INSERT.
  10005. **
  10006. ** Changes are not recorded for rows that have NULL values stored in one or
  10007. ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
  10008. ** no corresponding change is present in the changesets returned by this
  10009. ** function. If an existing row with one or more NULL values stored in
  10010. ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
  10011. ** only an INSERT is appears in the changeset. Similarly, if an existing row
  10012. ** with non-NULL PRIMARY KEY values is updated so that one or more of its
  10013. ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
  10014. ** DELETE change only.
  10015. **
  10016. ** The contents of a changeset may be traversed using an iterator created
  10017. ** using the [sqlite3changeset_start()] API. A changeset may be applied to
  10018. ** a database with a compatible schema using the [sqlite3changeset_apply()]
  10019. ** API.
  10020. **
  10021. ** Within a changeset generated by this function, all changes related to a
  10022. ** single table are grouped together. In other words, when iterating through
  10023. ** a changeset or when applying a changeset to a database, all changes related
  10024. ** to a single table are processed before moving on to the next table. Tables
  10025. ** are sorted in the same order in which they were attached (or auto-attached)
  10026. ** to the sqlite3_session object. The order in which the changes related to
  10027. ** a single table are stored is undefined.
  10028. **
  10029. ** Following a successful call to this function, it is the responsibility of
  10030. ** the caller to eventually free the buffer that *ppChangeset points to using
  10031. ** [sqlite3_free()].
  10032. **
  10033. ** <h3>Changeset Generation</h3>
  10034. **
  10035. ** Once a table has been attached to a session object, the session object
  10036. ** records the primary key values of all new rows inserted into the table.
  10037. ** It also records the original primary key and other column values of any
  10038. ** deleted or updated rows. For each unique primary key value, data is only
  10039. ** recorded once - the first time a row with said primary key is inserted,
  10040. ** updated or deleted in the lifetime of the session.
  10041. **
  10042. ** There is one exception to the previous paragraph: when a row is inserted,
  10043. ** updated or deleted, if one or more of its primary key columns contain a
  10044. ** NULL value, no record of the change is made.
  10045. **
  10046. ** The session object therefore accumulates two types of records - those
  10047. ** that consist of primary key values only (created when the user inserts
  10048. ** a new record) and those that consist of the primary key values and the
  10049. ** original values of other table columns (created when the users deletes
  10050. ** or updates a record).
  10051. **
  10052. ** When this function is called, the requested changeset is created using
  10053. ** both the accumulated records and the current contents of the database
  10054. ** file. Specifically:
  10055. **
  10056. ** <ul>
  10057. ** <li> For each record generated by an insert, the database is queried
  10058. ** for a row with a matching primary key. If one is found, an INSERT
  10059. ** change is added to the changeset. If no such row is found, no change
  10060. ** is added to the changeset.
  10061. **
  10062. ** <li> For each record generated by an update or delete, the database is
  10063. ** queried for a row with a matching primary key. If such a row is
  10064. ** found and one or more of the non-primary key fields have been
  10065. ** modified from their original values, an UPDATE change is added to
  10066. ** the changeset. Or, if no such row is found in the table, a DELETE
  10067. ** change is added to the changeset. If there is a row with a matching
  10068. ** primary key in the database, but all fields contain their original
  10069. ** values, no change is added to the changeset.
  10070. ** </ul>
  10071. **
  10072. ** This means, amongst other things, that if a row is inserted and then later
  10073. ** deleted while a session object is active, neither the insert nor the delete
  10074. ** will be present in the changeset. Or if a row is deleted and then later a
  10075. ** row with the same primary key values inserted while a session object is
  10076. ** active, the resulting changeset will contain an UPDATE change instead of
  10077. ** a DELETE and an INSERT.
  10078. **
  10079. ** When a session object is disabled (see the [sqlite3session_enable()] API),
  10080. ** it does not accumulate records when rows are inserted, updated or deleted.
  10081. ** This may appear to have some counter-intuitive effects if a single row
  10082. ** is written to more than once during a session. For example, if a row
  10083. ** is inserted while a session object is enabled, then later deleted while
  10084. ** the same session object is disabled, no INSERT record will appear in the
  10085. ** changeset, even though the delete took place while the session was disabled.
  10086. ** Or, if one field of a row is updated while a session is disabled, and
  10087. ** another field of the same row is updated while the session is enabled, the
  10088. ** resulting changeset will contain an UPDATE change that updates both fields.
  10089. */
  10090. SQLITE_API int sqlite3session_changeset(
  10091. sqlite3_session *pSession, /* Session object */
  10092. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  10093. void **ppChangeset /* OUT: Buffer containing changeset */
  10094. );
  10095. /*
  10096. ** CAPI3REF: Load The Difference Between Tables Into A Session
  10097. ** METHOD: sqlite3_session
  10098. **
  10099. ** If it is not already attached to the session object passed as the first
  10100. ** argument, this function attaches table zTbl in the same manner as the
  10101. ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
  10102. ** does not have a primary key, this function is a no-op (but does not return
  10103. ** an error).
  10104. **
  10105. ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
  10106. ** attached to the same database handle as the session object that contains
  10107. ** a table compatible with the table attached to the session by this function.
  10108. ** A table is considered compatible if it:
  10109. **
  10110. ** <ul>
  10111. ** <li> Has the same name,
  10112. ** <li> Has the same set of columns declared in the same order, and
  10113. ** <li> Has the same PRIMARY KEY definition.
  10114. ** </ul>
  10115. **
  10116. ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
  10117. ** are compatible but do not have any PRIMARY KEY columns, it is not an error
  10118. ** but no changes are added to the session object. As with other session
  10119. ** APIs, tables without PRIMARY KEYs are simply ignored.
  10120. **
  10121. ** This function adds a set of changes to the session object that could be
  10122. ** used to update the table in database zFrom (call this the "from-table")
  10123. ** so that its content is the same as the table attached to the session
  10124. ** object (call this the "to-table"). Specifically:
  10125. **
  10126. ** <ul>
  10127. ** <li> For each row (primary key) that exists in the to-table but not in
  10128. ** the from-table, an INSERT record is added to the session object.
  10129. **
  10130. ** <li> For each row (primary key) that exists in the to-table but not in
  10131. ** the from-table, a DELETE record is added to the session object.
  10132. **
  10133. ** <li> For each row (primary key) that exists in both tables, but features
  10134. ** different non-PK values in each, an UPDATE record is added to the
  10135. ** session.
  10136. ** </ul>
  10137. **
  10138. ** To clarify, if this function is called and then a changeset constructed
  10139. ** using [sqlite3session_changeset()], then after applying that changeset to
  10140. ** database zFrom the contents of the two compatible tables would be
  10141. ** identical.
  10142. **
  10143. ** It an error if database zFrom does not exist or does not contain the
  10144. ** required compatible table.
  10145. **
  10146. ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
  10147. ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
  10148. ** may be set to point to a buffer containing an English language error
  10149. ** message. It is the responsibility of the caller to free this buffer using
  10150. ** sqlite3_free().
  10151. */
  10152. SQLITE_API int sqlite3session_diff(
  10153. sqlite3_session *pSession,
  10154. const char *zFromDb,
  10155. const char *zTbl,
  10156. char **pzErrMsg
  10157. );
  10158. /*
  10159. ** CAPI3REF: Generate A Patchset From A Session Object
  10160. ** METHOD: sqlite3_session
  10161. **
  10162. ** The differences between a patchset and a changeset are that:
  10163. **
  10164. ** <ul>
  10165. ** <li> DELETE records consist of the primary key fields only. The
  10166. ** original values of other fields are omitted.
  10167. ** <li> The original values of any modified fields are omitted from
  10168. ** UPDATE records.
  10169. ** </ul>
  10170. **
  10171. ** A patchset blob may be used with up to date versions of all
  10172. ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
  10173. ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
  10174. ** attempting to use a patchset blob with old versions of the
  10175. ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
  10176. **
  10177. ** Because the non-primary key "old.*" fields are omitted, no
  10178. ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
  10179. ** is passed to the sqlite3changeset_apply() API. Other conflict types work
  10180. ** in the same way as for changesets.
  10181. **
  10182. ** Changes within a patchset are ordered in the same way as for changesets
  10183. ** generated by the sqlite3session_changeset() function (i.e. all changes for
  10184. ** a single table are grouped together, tables appear in the order in which
  10185. ** they were attached to the session object).
  10186. */
  10187. SQLITE_API int sqlite3session_patchset(
  10188. sqlite3_session *pSession, /* Session object */
  10189. int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
  10190. void **ppPatchset /* OUT: Buffer containing patchset */
  10191. );
  10192. /*
  10193. ** CAPI3REF: Test if a changeset has recorded any changes.
  10194. **
  10195. ** Return non-zero if no changes to attached tables have been recorded by
  10196. ** the session object passed as the first argument. Otherwise, if one or
  10197. ** more changes have been recorded, return zero.
  10198. **
  10199. ** Even if this function returns zero, it is possible that calling
  10200. ** [sqlite3session_changeset()] on the session handle may still return a
  10201. ** changeset that contains no changes. This can happen when a row in
  10202. ** an attached table is modified and then later on the original values
  10203. ** are restored. However, if this function returns non-zero, then it is
  10204. ** guaranteed that a call to sqlite3session_changeset() will return a
  10205. ** changeset containing zero changes.
  10206. */
  10207. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
  10208. /*
  10209. ** CAPI3REF: Create An Iterator To Traverse A Changeset
  10210. ** CONSTRUCTOR: sqlite3_changeset_iter
  10211. **
  10212. ** Create an iterator used to iterate through the contents of a changeset.
  10213. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
  10214. ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
  10215. ** SQLite error code is returned.
  10216. **
  10217. ** The following functions can be used to advance and query a changeset
  10218. ** iterator created by this function:
  10219. **
  10220. ** <ul>
  10221. ** <li> [sqlite3changeset_next()]
  10222. ** <li> [sqlite3changeset_op()]
  10223. ** <li> [sqlite3changeset_new()]
  10224. ** <li> [sqlite3changeset_old()]
  10225. ** </ul>
  10226. **
  10227. ** It is the responsibility of the caller to eventually destroy the iterator
  10228. ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
  10229. ** changeset (pChangeset) must remain valid until after the iterator is
  10230. ** destroyed.
  10231. **
  10232. ** Assuming the changeset blob was created by one of the
  10233. ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
  10234. ** [sqlite3changeset_invert()] functions, all changes within the changeset
  10235. ** that apply to a single table are grouped together. This means that when
  10236. ** an application iterates through a changeset using an iterator created by
  10237. ** this function, all changes that relate to a single table are visited
  10238. ** consecutively. There is no chance that the iterator will visit a change
  10239. ** the applies to table X, then one for table Y, and then later on visit
  10240. ** another change for table X.
  10241. */
  10242. SQLITE_API int sqlite3changeset_start(
  10243. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  10244. int nChangeset, /* Size of changeset blob in bytes */
  10245. void *pChangeset /* Pointer to blob containing changeset */
  10246. );
  10247. /*
  10248. ** CAPI3REF: Advance A Changeset Iterator
  10249. ** METHOD: sqlite3_changeset_iter
  10250. **
  10251. ** This function may only be used with iterators created by function
  10252. ** [sqlite3changeset_start()]. If it is called on an iterator passed to
  10253. ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
  10254. ** is returned and the call has no effect.
  10255. **
  10256. ** Immediately after an iterator is created by sqlite3changeset_start(), it
  10257. ** does not point to any change in the changeset. Assuming the changeset
  10258. ** is not empty, the first call to this function advances the iterator to
  10259. ** point to the first change in the changeset. Each subsequent call advances
  10260. ** the iterator to point to the next change in the changeset (if any). If
  10261. ** no error occurs and the iterator points to a valid change after a call
  10262. ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
  10263. ** Otherwise, if all changes in the changeset have already been visited,
  10264. ** SQLITE_DONE is returned.
  10265. **
  10266. ** If an error occurs, an SQLite error code is returned. Possible error
  10267. ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
  10268. ** SQLITE_NOMEM.
  10269. */
  10270. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
  10271. /*
  10272. ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
  10273. ** METHOD: sqlite3_changeset_iter
  10274. **
  10275. ** The pIter argument passed to this function may either be an iterator
  10276. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10277. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10278. ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
  10279. ** is not the case, this function returns [SQLITE_MISUSE].
  10280. **
  10281. ** If argument pzTab is not NULL, then *pzTab is set to point to a
  10282. ** nul-terminated utf-8 encoded string containing the name of the table
  10283. ** affected by the current change. The buffer remains valid until either
  10284. ** sqlite3changeset_next() is called on the iterator or until the
  10285. ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
  10286. ** set to the number of columns in the table affected by the change. If
  10287. ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
  10288. ** is an indirect change, or false (0) otherwise. See the documentation for
  10289. ** [sqlite3session_indirect()] for a description of direct and indirect
  10290. ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
  10291. ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
  10292. ** type of change that the iterator currently points to.
  10293. **
  10294. ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
  10295. ** SQLite error code is returned. The values of the output variables may not
  10296. ** be trusted in this case.
  10297. */
  10298. SQLITE_API int sqlite3changeset_op(
  10299. sqlite3_changeset_iter *pIter, /* Iterator object */
  10300. const char **pzTab, /* OUT: Pointer to table name */
  10301. int *pnCol, /* OUT: Number of columns in table */
  10302. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  10303. int *pbIndirect /* OUT: True for an 'indirect' change */
  10304. );
  10305. /*
  10306. ** CAPI3REF: Obtain The Primary Key Definition Of A Table
  10307. ** METHOD: sqlite3_changeset_iter
  10308. **
  10309. ** For each modified table, a changeset includes the following:
  10310. **
  10311. ** <ul>
  10312. ** <li> The number of columns in the table, and
  10313. ** <li> Which of those columns make up the tables PRIMARY KEY.
  10314. ** </ul>
  10315. **
  10316. ** This function is used to find which columns comprise the PRIMARY KEY of
  10317. ** the table modified by the change that iterator pIter currently points to.
  10318. ** If successful, *pabPK is set to point to an array of nCol entries, where
  10319. ** nCol is the number of columns in the table. Elements of *pabPK are set to
  10320. ** 0x01 if the corresponding column is part of the tables primary key, or
  10321. ** 0x00 if it is not.
  10322. **
  10323. ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
  10324. ** in the table.
  10325. **
  10326. ** If this function is called when the iterator does not point to a valid
  10327. ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
  10328. ** SQLITE_OK is returned and the output variables populated as described
  10329. ** above.
  10330. */
  10331. SQLITE_API int sqlite3changeset_pk(
  10332. sqlite3_changeset_iter *pIter, /* Iterator object */
  10333. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  10334. int *pnCol /* OUT: Number of entries in output array */
  10335. );
  10336. /*
  10337. ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
  10338. ** METHOD: sqlite3_changeset_iter
  10339. **
  10340. ** The pIter argument passed to this function may either be an iterator
  10341. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10342. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10343. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10344. ** Furthermore, it may only be called if the type of change that the iterator
  10345. ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
  10346. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10347. **
  10348. ** Argument iVal must be greater than or equal to 0, and less than the number
  10349. ** of columns in the table affected by the current change. Otherwise,
  10350. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10351. **
  10352. ** If successful, this function sets *ppValue to point to a protected
  10353. ** sqlite3_value object containing the iVal'th value from the vector of
  10354. ** original row values stored as part of the UPDATE or DELETE change and
  10355. ** returns SQLITE_OK. The name of the function comes from the fact that this
  10356. ** is similar to the "old.*" columns available to update or delete triggers.
  10357. **
  10358. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10359. ** is returned and *ppValue is set to NULL.
  10360. */
  10361. SQLITE_API int sqlite3changeset_old(
  10362. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10363. int iVal, /* Column number */
  10364. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  10365. );
  10366. /*
  10367. ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
  10368. ** METHOD: sqlite3_changeset_iter
  10369. **
  10370. ** The pIter argument passed to this function may either be an iterator
  10371. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  10372. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  10373. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  10374. ** Furthermore, it may only be called if the type of change that the iterator
  10375. ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
  10376. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  10377. **
  10378. ** Argument iVal must be greater than or equal to 0, and less than the number
  10379. ** of columns in the table affected by the current change. Otherwise,
  10380. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10381. **
  10382. ** If successful, this function sets *ppValue to point to a protected
  10383. ** sqlite3_value object containing the iVal'th value from the vector of
  10384. ** new row values stored as part of the UPDATE or INSERT change and
  10385. ** returns SQLITE_OK. If the change is an UPDATE and does not include
  10386. ** a new value for the requested column, *ppValue is set to NULL and
  10387. ** SQLITE_OK returned. The name of the function comes from the fact that
  10388. ** this is similar to the "new.*" columns available to update or delete
  10389. ** triggers.
  10390. **
  10391. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10392. ** is returned and *ppValue is set to NULL.
  10393. */
  10394. SQLITE_API int sqlite3changeset_new(
  10395. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10396. int iVal, /* Column number */
  10397. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  10398. );
  10399. /*
  10400. ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
  10401. ** METHOD: sqlite3_changeset_iter
  10402. **
  10403. ** This function should only be used with iterator objects passed to a
  10404. ** conflict-handler callback by [sqlite3changeset_apply()] with either
  10405. ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
  10406. ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
  10407. ** is set to NULL.
  10408. **
  10409. ** Argument iVal must be greater than or equal to 0, and less than the number
  10410. ** of columns in the table affected by the current change. Otherwise,
  10411. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  10412. **
  10413. ** If successful, this function sets *ppValue to point to a protected
  10414. ** sqlite3_value object containing the iVal'th value from the
  10415. ** "conflicting row" associated with the current conflict-handler callback
  10416. ** and returns SQLITE_OK.
  10417. **
  10418. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  10419. ** is returned and *ppValue is set to NULL.
  10420. */
  10421. SQLITE_API int sqlite3changeset_conflict(
  10422. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10423. int iVal, /* Column number */
  10424. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  10425. );
  10426. /*
  10427. ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
  10428. ** METHOD: sqlite3_changeset_iter
  10429. **
  10430. ** This function may only be called with an iterator passed to an
  10431. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  10432. ** it sets the output variable to the total number of known foreign key
  10433. ** violations in the destination database and returns SQLITE_OK.
  10434. **
  10435. ** In all other cases this function returns SQLITE_MISUSE.
  10436. */
  10437. SQLITE_API int sqlite3changeset_fk_conflicts(
  10438. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  10439. int *pnOut /* OUT: Number of FK violations */
  10440. );
  10441. /*
  10442. ** CAPI3REF: Finalize A Changeset Iterator
  10443. ** METHOD: sqlite3_changeset_iter
  10444. **
  10445. ** This function is used to finalize an iterator allocated with
  10446. ** [sqlite3changeset_start()].
  10447. **
  10448. ** This function should only be called on iterators created using the
  10449. ** [sqlite3changeset_start()] function. If an application calls this
  10450. ** function with an iterator passed to a conflict-handler by
  10451. ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
  10452. ** call has no effect.
  10453. **
  10454. ** If an error was encountered within a call to an sqlite3changeset_xxx()
  10455. ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
  10456. ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
  10457. ** to that error is returned by this function. Otherwise, SQLITE_OK is
  10458. ** returned. This is to allow the following pattern (pseudo-code):
  10459. **
  10460. ** <pre>
  10461. ** sqlite3changeset_start();
  10462. ** while( SQLITE_ROW==sqlite3changeset_next() ){
  10463. ** // Do something with change.
  10464. ** }
  10465. ** rc = sqlite3changeset_finalize();
  10466. ** if( rc!=SQLITE_OK ){
  10467. ** // An error has occurred
  10468. ** }
  10469. ** </pre>
  10470. */
  10471. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
  10472. /*
  10473. ** CAPI3REF: Invert A Changeset
  10474. **
  10475. ** This function is used to "invert" a changeset object. Applying an inverted
  10476. ** changeset to a database reverses the effects of applying the uninverted
  10477. ** changeset. Specifically:
  10478. **
  10479. ** <ul>
  10480. ** <li> Each DELETE change is changed to an INSERT, and
  10481. ** <li> Each INSERT change is changed to a DELETE, and
  10482. ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
  10483. ** </ul>
  10484. **
  10485. ** This function does not change the order in which changes appear within
  10486. ** the changeset. It merely reverses the sense of each individual change.
  10487. **
  10488. ** If successful, a pointer to a buffer containing the inverted changeset
  10489. ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
  10490. ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
  10491. ** zeroed and an SQLite error code returned.
  10492. **
  10493. ** It is the responsibility of the caller to eventually call sqlite3_free()
  10494. ** on the *ppOut pointer to free the buffer allocation following a successful
  10495. ** call to this function.
  10496. **
  10497. ** WARNING/TODO: This function currently assumes that the input is a valid
  10498. ** changeset. If it is not, the results are undefined.
  10499. */
  10500. SQLITE_API int sqlite3changeset_invert(
  10501. int nIn, const void *pIn, /* Input changeset */
  10502. int *pnOut, void **ppOut /* OUT: Inverse of input */
  10503. );
  10504. /*
  10505. ** CAPI3REF: Concatenate Two Changeset Objects
  10506. **
  10507. ** This function is used to concatenate two changesets, A and B, into a
  10508. ** single changeset. The result is a changeset equivalent to applying
  10509. ** changeset A followed by changeset B.
  10510. **
  10511. ** This function combines the two input changesets using an
  10512. ** sqlite3_changegroup object. Calling it produces similar results as the
  10513. ** following code fragment:
  10514. **
  10515. ** <pre>
  10516. ** sqlite3_changegroup *pGrp;
  10517. ** rc = sqlite3_changegroup_new(&pGrp);
  10518. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
  10519. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
  10520. ** if( rc==SQLITE_OK ){
  10521. ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  10522. ** }else{
  10523. ** *ppOut = 0;
  10524. ** *pnOut = 0;
  10525. ** }
  10526. ** </pre>
  10527. **
  10528. ** Refer to the sqlite3_changegroup documentation below for details.
  10529. */
  10530. SQLITE_API int sqlite3changeset_concat(
  10531. int nA, /* Number of bytes in buffer pA */
  10532. void *pA, /* Pointer to buffer containing changeset A */
  10533. int nB, /* Number of bytes in buffer pB */
  10534. void *pB, /* Pointer to buffer containing changeset B */
  10535. int *pnOut, /* OUT: Number of bytes in output changeset */
  10536. void **ppOut /* OUT: Buffer containing output changeset */
  10537. );
  10538. /*
  10539. ** CAPI3REF: Changegroup Handle
  10540. **
  10541. ** A changegroup is an object used to combine two or more
  10542. ** [changesets] or [patchsets]
  10543. */
  10544. typedef struct sqlite3_changegroup sqlite3_changegroup;
  10545. /*
  10546. ** CAPI3REF: Create A New Changegroup Object
  10547. ** CONSTRUCTOR: sqlite3_changegroup
  10548. **
  10549. ** An sqlite3_changegroup object is used to combine two or more changesets
  10550. ** (or patchsets) into a single changeset (or patchset). A single changegroup
  10551. ** object may combine changesets or patchsets, but not both. The output is
  10552. ** always in the same format as the input.
  10553. **
  10554. ** If successful, this function returns SQLITE_OK and populates (*pp) with
  10555. ** a pointer to a new sqlite3_changegroup object before returning. The caller
  10556. ** should eventually free the returned object using a call to
  10557. ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
  10558. ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
  10559. **
  10560. ** The usual usage pattern for an sqlite3_changegroup object is as follows:
  10561. **
  10562. ** <ul>
  10563. ** <li> It is created using a call to sqlite3changegroup_new().
  10564. **
  10565. ** <li> Zero or more changesets (or patchsets) are added to the object
  10566. ** by calling sqlite3changegroup_add().
  10567. **
  10568. ** <li> The result of combining all input changesets together is obtained
  10569. ** by the application via a call to sqlite3changegroup_output().
  10570. **
  10571. ** <li> The object is deleted using a call to sqlite3changegroup_delete().
  10572. ** </ul>
  10573. **
  10574. ** Any number of calls to add() and output() may be made between the calls to
  10575. ** new() and delete(), and in any order.
  10576. **
  10577. ** As well as the regular sqlite3changegroup_add() and
  10578. ** sqlite3changegroup_output() functions, also available are the streaming
  10579. ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
  10580. */
  10581. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
  10582. /*
  10583. ** CAPI3REF: Add A Changeset To A Changegroup
  10584. ** METHOD: sqlite3_changegroup
  10585. **
  10586. ** Add all changes within the changeset (or patchset) in buffer pData (size
  10587. ** nData bytes) to the changegroup.
  10588. **
  10589. ** If the buffer contains a patchset, then all prior calls to this function
  10590. ** on the same changegroup object must also have specified patchsets. Or, if
  10591. ** the buffer contains a changeset, so must have the earlier calls to this
  10592. ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
  10593. ** to the changegroup.
  10594. **
  10595. ** Rows within the changeset and changegroup are identified by the values in
  10596. ** their PRIMARY KEY columns. A change in the changeset is considered to
  10597. ** apply to the same row as a change already present in the changegroup if
  10598. ** the two rows have the same primary key.
  10599. **
  10600. ** Changes to rows that do not already appear in the changegroup are
  10601. ** simply copied into it. Or, if both the new changeset and the changegroup
  10602. ** contain changes that apply to a single row, the final contents of the
  10603. ** changegroup depends on the type of each change, as follows:
  10604. **
  10605. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  10606. ** <tr><th style="white-space:pre">Existing Change </th>
  10607. ** <th style="white-space:pre">New Change </th>
  10608. ** <th>Output Change
  10609. ** <tr><td>INSERT <td>INSERT <td>
  10610. ** The new change is ignored. This case does not occur if the new
  10611. ** changeset was recorded immediately after the changesets already
  10612. ** added to the changegroup.
  10613. ** <tr><td>INSERT <td>UPDATE <td>
  10614. ** The INSERT change remains in the changegroup. The values in the
  10615. ** INSERT change are modified as if the row was inserted by the
  10616. ** existing change and then updated according to the new change.
  10617. ** <tr><td>INSERT <td>DELETE <td>
  10618. ** The existing INSERT is removed from the changegroup. The DELETE is
  10619. ** not added.
  10620. ** <tr><td>UPDATE <td>INSERT <td>
  10621. ** The new change is ignored. This case does not occur if the new
  10622. ** changeset was recorded immediately after the changesets already
  10623. ** added to the changegroup.
  10624. ** <tr><td>UPDATE <td>UPDATE <td>
  10625. ** The existing UPDATE remains within the changegroup. It is amended
  10626. ** so that the accompanying values are as if the row was updated once
  10627. ** by the existing change and then again by the new change.
  10628. ** <tr><td>UPDATE <td>DELETE <td>
  10629. ** The existing UPDATE is replaced by the new DELETE within the
  10630. ** changegroup.
  10631. ** <tr><td>DELETE <td>INSERT <td>
  10632. ** If one or more of the column values in the row inserted by the
  10633. ** new change differ from those in the row deleted by the existing
  10634. ** change, the existing DELETE is replaced by an UPDATE within the
  10635. ** changegroup. Otherwise, if the inserted row is exactly the same
  10636. ** as the deleted row, the existing DELETE is simply discarded.
  10637. ** <tr><td>DELETE <td>UPDATE <td>
  10638. ** The new change is ignored. This case does not occur if the new
  10639. ** changeset was recorded immediately after the changesets already
  10640. ** added to the changegroup.
  10641. ** <tr><td>DELETE <td>DELETE <td>
  10642. ** The new change is ignored. This case does not occur if the new
  10643. ** changeset was recorded immediately after the changesets already
  10644. ** added to the changegroup.
  10645. ** </table>
  10646. **
  10647. ** If the new changeset contains changes to a table that is already present
  10648. ** in the changegroup, then the number of columns and the position of the
  10649. ** primary key columns for the table must be consistent. If this is not the
  10650. ** case, this function fails with SQLITE_SCHEMA. If the input changeset
  10651. ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
  10652. ** returned. Or, if an out-of-memory condition occurs during processing, this
  10653. ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
  10654. ** final contents of the changegroup is undefined.
  10655. **
  10656. ** If no error occurs, SQLITE_OK is returned.
  10657. */
  10658. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
  10659. /*
  10660. ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
  10661. ** METHOD: sqlite3_changegroup
  10662. **
  10663. ** Obtain a buffer containing a changeset (or patchset) representing the
  10664. ** current contents of the changegroup. If the inputs to the changegroup
  10665. ** were themselves changesets, the output is a changeset. Or, if the
  10666. ** inputs were patchsets, the output is also a patchset.
  10667. **
  10668. ** As with the output of the sqlite3session_changeset() and
  10669. ** sqlite3session_patchset() functions, all changes related to a single
  10670. ** table are grouped together in the output of this function. Tables appear
  10671. ** in the same order as for the very first changeset added to the changegroup.
  10672. ** If the second or subsequent changesets added to the changegroup contain
  10673. ** changes for tables that do not appear in the first changeset, they are
  10674. ** appended onto the end of the output changeset, again in the order in
  10675. ** which they are first encountered.
  10676. **
  10677. ** If an error occurs, an SQLite error code is returned and the output
  10678. ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
  10679. ** is returned and the output variables are set to the size of and a
  10680. ** pointer to the output buffer, respectively. In this case it is the
  10681. ** responsibility of the caller to eventually free the buffer using a
  10682. ** call to sqlite3_free().
  10683. */
  10684. SQLITE_API int sqlite3changegroup_output(
  10685. sqlite3_changegroup*,
  10686. int *pnData, /* OUT: Size of output buffer in bytes */
  10687. void **ppData /* OUT: Pointer to output buffer */
  10688. );
  10689. /*
  10690. ** CAPI3REF: Delete A Changegroup Object
  10691. ** DESTRUCTOR: sqlite3_changegroup
  10692. */
  10693. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
  10694. /*
  10695. ** CAPI3REF: Apply A Changeset To A Database
  10696. **
  10697. ** Apply a changeset or patchset to a database. These functions attempt to
  10698. ** update the "main" database attached to handle db with the changes found in
  10699. ** the changeset passed via the second and third arguments.
  10700. **
  10701. ** The fourth argument (xFilter) passed to these functions is the "filter
  10702. ** callback". If it is not NULL, then for each table affected by at least one
  10703. ** change in the changeset, the filter callback is invoked with
  10704. ** the table name as the second argument, and a copy of the context pointer
  10705. ** passed as the sixth argument as the first. If the "filter callback"
  10706. ** returns zero, then no attempt is made to apply any changes to the table.
  10707. ** Otherwise, if the return value is non-zero or the xFilter argument to
  10708. ** is NULL, all changes related to the table are attempted.
  10709. **
  10710. ** For each table that is not excluded by the filter callback, this function
  10711. ** tests that the target database contains a compatible table. A table is
  10712. ** considered compatible if all of the following are true:
  10713. **
  10714. ** <ul>
  10715. ** <li> The table has the same name as the name recorded in the
  10716. ** changeset, and
  10717. ** <li> The table has at least as many columns as recorded in the
  10718. ** changeset, and
  10719. ** <li> The table has primary key columns in the same position as
  10720. ** recorded in the changeset.
  10721. ** </ul>
  10722. **
  10723. ** If there is no compatible table, it is not an error, but none of the
  10724. ** changes associated with the table are applied. A warning message is issued
  10725. ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
  10726. ** one such warning is issued for each table in the changeset.
  10727. **
  10728. ** For each change for which there is a compatible table, an attempt is made
  10729. ** to modify the table contents according to the UPDATE, INSERT or DELETE
  10730. ** change. If a change cannot be applied cleanly, the conflict handler
  10731. ** function passed as the fifth argument to sqlite3changeset_apply() may be
  10732. ** invoked. A description of exactly when the conflict handler is invoked for
  10733. ** each type of change is below.
  10734. **
  10735. ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
  10736. ** of passing anything other than a valid function pointer as the xConflict
  10737. ** argument are undefined.
  10738. **
  10739. ** Each time the conflict handler function is invoked, it must return one
  10740. ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
  10741. ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
  10742. ** if the second argument passed to the conflict handler is either
  10743. ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
  10744. ** returns an illegal value, any changes already made are rolled back and
  10745. ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
  10746. ** actions are taken by sqlite3changeset_apply() depending on the value
  10747. ** returned by each invocation of the conflict-handler function. Refer to
  10748. ** the documentation for the three
  10749. ** [SQLITE_CHANGESET_OMIT|available return values] for details.
  10750. **
  10751. ** <dl>
  10752. ** <dt>DELETE Changes<dd>
  10753. ** For each DELETE change, the function checks if the target database
  10754. ** contains a row with the same primary key value (or values) as the
  10755. ** original row values stored in the changeset. If it does, and the values
  10756. ** stored in all non-primary key columns also match the values stored in
  10757. ** the changeset the row is deleted from the target database.
  10758. **
  10759. ** If a row with matching primary key values is found, but one or more of
  10760. ** the non-primary key fields contains a value different from the original
  10761. ** row value stored in the changeset, the conflict-handler function is
  10762. ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
  10763. ** database table has more columns than are recorded in the changeset,
  10764. ** only the values of those non-primary key fields are compared against
  10765. ** the current database contents - any trailing database table columns
  10766. ** are ignored.
  10767. **
  10768. ** If no row with matching primary key values is found in the database,
  10769. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  10770. ** passed as the second argument.
  10771. **
  10772. ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
  10773. ** (which can only happen if a foreign key constraint is violated), the
  10774. ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
  10775. ** passed as the second argument. This includes the case where the DELETE
  10776. ** operation is attempted because an earlier call to the conflict handler
  10777. ** function returned [SQLITE_CHANGESET_REPLACE].
  10778. **
  10779. ** <dt>INSERT Changes<dd>
  10780. ** For each INSERT change, an attempt is made to insert the new row into
  10781. ** the database. If the changeset row contains fewer fields than the
  10782. ** database table, the trailing fields are populated with their default
  10783. ** values.
  10784. **
  10785. ** If the attempt to insert the row fails because the database already
  10786. ** contains a row with the same primary key values, the conflict handler
  10787. ** function is invoked with the second argument set to
  10788. ** [SQLITE_CHANGESET_CONFLICT].
  10789. **
  10790. ** If the attempt to insert the row fails because of some other constraint
  10791. ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
  10792. ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
  10793. ** This includes the case where the INSERT operation is re-attempted because
  10794. ** an earlier call to the conflict handler function returned
  10795. ** [SQLITE_CHANGESET_REPLACE].
  10796. **
  10797. ** <dt>UPDATE Changes<dd>
  10798. ** For each UPDATE change, the function checks if the target database
  10799. ** contains a row with the same primary key value (or values) as the
  10800. ** original row values stored in the changeset. If it does, and the values
  10801. ** stored in all modified non-primary key columns also match the values
  10802. ** stored in the changeset the row is updated within the target database.
  10803. **
  10804. ** If a row with matching primary key values is found, but one or more of
  10805. ** the modified non-primary key fields contains a value different from an
  10806. ** original row value stored in the changeset, the conflict-handler function
  10807. ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
  10808. ** UPDATE changes only contain values for non-primary key fields that are
  10809. ** to be modified, only those fields need to match the original values to
  10810. ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
  10811. **
  10812. ** If no row with matching primary key values is found in the database,
  10813. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  10814. ** passed as the second argument.
  10815. **
  10816. ** If the UPDATE operation is attempted, but SQLite returns
  10817. ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
  10818. ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
  10819. ** This includes the case where the UPDATE operation is attempted after
  10820. ** an earlier call to the conflict handler function returned
  10821. ** [SQLITE_CHANGESET_REPLACE].
  10822. ** </dl>
  10823. **
  10824. ** It is safe to execute SQL statements, including those that write to the
  10825. ** table that the callback related to, from within the xConflict callback.
  10826. ** This can be used to further customize the applications conflict
  10827. ** resolution strategy.
  10828. **
  10829. ** All changes made by these functions are enclosed in a savepoint transaction.
  10830. ** If any other error (aside from a constraint failure when attempting to
  10831. ** write to the target database) occurs, then the savepoint transaction is
  10832. ** rolled back, restoring the target database to its original state, and an
  10833. ** SQLite error code returned.
  10834. **
  10835. ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
  10836. ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
  10837. ** may set (*ppRebase) to point to a "rebase" that may be used with the
  10838. ** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
  10839. ** is set to the size of the buffer in bytes. It is the responsibility of the
  10840. ** caller to eventually free any such buffer using sqlite3_free(). The buffer
  10841. ** is only allocated and populated if one or more conflicts were encountered
  10842. ** while applying the patchset. See comments surrounding the sqlite3_rebaser
  10843. ** APIs for further details.
  10844. **
  10845. ** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
  10846. ** may be modified by passing a combination of
  10847. ** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
  10848. **
  10849. ** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
  10850. ** and therefore subject to change.
  10851. */
  10852. SQLITE_API int sqlite3changeset_apply(
  10853. sqlite3 *db, /* Apply change to "main" db of this handle */
  10854. int nChangeset, /* Size of changeset in bytes */
  10855. void *pChangeset, /* Changeset blob */
  10856. int(*xFilter)(
  10857. void *pCtx, /* Copy of sixth arg to _apply() */
  10858. const char *zTab /* Table name */
  10859. ),
  10860. int(*xConflict)(
  10861. void *pCtx, /* Copy of sixth arg to _apply() */
  10862. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  10863. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  10864. ),
  10865. void *pCtx /* First argument passed to xConflict */
  10866. );
  10867. SQLITE_API int sqlite3changeset_apply_v2(
  10868. sqlite3 *db, /* Apply change to "main" db of this handle */
  10869. int nChangeset, /* Size of changeset in bytes */
  10870. void *pChangeset, /* Changeset blob */
  10871. int(*xFilter)(
  10872. void *pCtx, /* Copy of sixth arg to _apply() */
  10873. const char *zTab /* Table name */
  10874. ),
  10875. int(*xConflict)(
  10876. void *pCtx, /* Copy of sixth arg to _apply() */
  10877. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  10878. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  10879. ),
  10880. void *pCtx, /* First argument passed to xConflict */
  10881. void **ppRebase, int *pnRebase, /* OUT: Rebase data */
  10882. int flags /* Combination of SESSION_APPLY_* flags */
  10883. );
  10884. /*
  10885. ** CAPI3REF: Flags for sqlite3changeset_apply_v2
  10886. **
  10887. ** The following flags may passed via the 9th parameter to
  10888. ** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
  10889. **
  10890. ** <dl>
  10891. ** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
  10892. ** Usually, the sessions module encloses all operations performed by
  10893. ** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
  10894. ** SAVEPOINT is committed if the changeset or patchset is successfully
  10895. ** applied, or rolled back if an error occurs. Specifying this flag
  10896. ** causes the sessions module to omit this savepoint. In this case, if the
  10897. ** caller has an open transaction or savepoint when apply_v2() is called,
  10898. ** it may revert the partially applied changeset by rolling it back.
  10899. */
  10900. #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001
  10901. /*
  10902. ** CAPI3REF: Constants Passed To The Conflict Handler
  10903. **
  10904. ** Values that may be passed as the second argument to a conflict-handler.
  10905. **
  10906. ** <dl>
  10907. ** <dt>SQLITE_CHANGESET_DATA<dd>
  10908. ** The conflict handler is invoked with CHANGESET_DATA as the second argument
  10909. ** when processing a DELETE or UPDATE change if a row with the required
  10910. ** PRIMARY KEY fields is present in the database, but one or more other
  10911. ** (non primary-key) fields modified by the update do not contain the
  10912. ** expected "before" values.
  10913. **
  10914. ** The conflicting row, in this case, is the database row with the matching
  10915. ** primary key.
  10916. **
  10917. ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
  10918. ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
  10919. ** argument when processing a DELETE or UPDATE change if a row with the
  10920. ** required PRIMARY KEY fields is not present in the database.
  10921. **
  10922. ** There is no conflicting row in this case. The results of invoking the
  10923. ** sqlite3changeset_conflict() API are undefined.
  10924. **
  10925. ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
  10926. ** CHANGESET_CONFLICT is passed as the second argument to the conflict
  10927. ** handler while processing an INSERT change if the operation would result
  10928. ** in duplicate primary key values.
  10929. **
  10930. ** The conflicting row in this case is the database row with the matching
  10931. ** primary key.
  10932. **
  10933. ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
  10934. ** If foreign key handling is enabled, and applying a changeset leaves the
  10935. ** database in a state containing foreign key violations, the conflict
  10936. ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
  10937. ** exactly once before the changeset is committed. If the conflict handler
  10938. ** returns CHANGESET_OMIT, the changes, including those that caused the
  10939. ** foreign key constraint violation, are committed. Or, if it returns
  10940. ** CHANGESET_ABORT, the changeset is rolled back.
  10941. **
  10942. ** No current or conflicting row information is provided. The only function
  10943. ** it is possible to call on the supplied sqlite3_changeset_iter handle
  10944. ** is sqlite3changeset_fk_conflicts().
  10945. **
  10946. ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
  10947. ** If any other constraint violation occurs while applying a change (i.e.
  10948. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
  10949. ** invoked with CHANGESET_CONSTRAINT as the second argument.
  10950. **
  10951. ** There is no conflicting row in this case. The results of invoking the
  10952. ** sqlite3changeset_conflict() API are undefined.
  10953. **
  10954. ** </dl>
  10955. */
  10956. #define SQLITE_CHANGESET_DATA 1
  10957. #define SQLITE_CHANGESET_NOTFOUND 2
  10958. #define SQLITE_CHANGESET_CONFLICT 3
  10959. #define SQLITE_CHANGESET_CONSTRAINT 4
  10960. #define SQLITE_CHANGESET_FOREIGN_KEY 5
  10961. /*
  10962. ** CAPI3REF: Constants Returned By The Conflict Handler
  10963. **
  10964. ** A conflict handler callback must return one of the following three values.
  10965. **
  10966. ** <dl>
  10967. ** <dt>SQLITE_CHANGESET_OMIT<dd>
  10968. ** If a conflict handler returns this value no special action is taken. The
  10969. ** change that caused the conflict is not applied. The session module
  10970. ** continues to the next change in the changeset.
  10971. **
  10972. ** <dt>SQLITE_CHANGESET_REPLACE<dd>
  10973. ** This value may only be returned if the second argument to the conflict
  10974. ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
  10975. ** is not the case, any changes applied so far are rolled back and the
  10976. ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
  10977. **
  10978. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
  10979. ** handler, then the conflicting row is either updated or deleted, depending
  10980. ** on the type of change.
  10981. **
  10982. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
  10983. ** handler, then the conflicting row is removed from the database and a
  10984. ** second attempt to apply the change is made. If this second attempt fails,
  10985. ** the original row is restored to the database before continuing.
  10986. **
  10987. ** <dt>SQLITE_CHANGESET_ABORT<dd>
  10988. ** If this value is returned, any changes applied so far are rolled back
  10989. ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
  10990. ** </dl>
  10991. */
  10992. #define SQLITE_CHANGESET_OMIT 0
  10993. #define SQLITE_CHANGESET_REPLACE 1
  10994. #define SQLITE_CHANGESET_ABORT 2
  10995. /*
  10996. ** CAPI3REF: Rebasing changesets
  10997. ** EXPERIMENTAL
  10998. **
  10999. ** Suppose there is a site hosting a database in state S0. And that
  11000. ** modifications are made that move that database to state S1 and a
  11001. ** changeset recorded (the "local" changeset). Then, a changeset based
  11002. ** on S0 is received from another site (the "remote" changeset) and
  11003. ** applied to the database. The database is then in state
  11004. ** (S1+"remote"), where the exact state depends on any conflict
  11005. ** resolution decisions (OMIT or REPLACE) made while applying "remote".
  11006. ** Rebasing a changeset is to update it to take those conflict
  11007. ** resolution decisions into account, so that the same conflicts
  11008. ** do not have to be resolved elsewhere in the network.
  11009. **
  11010. ** For example, if both the local and remote changesets contain an
  11011. ** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
  11012. **
  11013. ** local: INSERT INTO t1 VALUES(1, 'v1');
  11014. ** remote: INSERT INTO t1 VALUES(1, 'v2');
  11015. **
  11016. ** and the conflict resolution is REPLACE, then the INSERT change is
  11017. ** removed from the local changeset (it was overridden). Or, if the
  11018. ** conflict resolution was "OMIT", then the local changeset is modified
  11019. ** to instead contain:
  11020. **
  11021. ** UPDATE t1 SET b = 'v2' WHERE a=1;
  11022. **
  11023. ** Changes within the local changeset are rebased as follows:
  11024. **
  11025. ** <dl>
  11026. ** <dt>Local INSERT<dd>
  11027. ** This may only conflict with a remote INSERT. If the conflict
  11028. ** resolution was OMIT, then add an UPDATE change to the rebased
  11029. ** changeset. Or, if the conflict resolution was REPLACE, add
  11030. ** nothing to the rebased changeset.
  11031. **
  11032. ** <dt>Local DELETE<dd>
  11033. ** This may conflict with a remote UPDATE or DELETE. In both cases the
  11034. ** only possible resolution is OMIT. If the remote operation was a
  11035. ** DELETE, then add no change to the rebased changeset. If the remote
  11036. ** operation was an UPDATE, then the old.* fields of change are updated
  11037. ** to reflect the new.* values in the UPDATE.
  11038. **
  11039. ** <dt>Local UPDATE<dd>
  11040. ** This may conflict with a remote UPDATE or DELETE. If it conflicts
  11041. ** with a DELETE, and the conflict resolution was OMIT, then the update
  11042. ** is changed into an INSERT. Any undefined values in the new.* record
  11043. ** from the update change are filled in using the old.* values from
  11044. ** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
  11045. ** the UPDATE change is simply omitted from the rebased changeset.
  11046. **
  11047. ** If conflict is with a remote UPDATE and the resolution is OMIT, then
  11048. ** the old.* values are rebased using the new.* values in the remote
  11049. ** change. Or, if the resolution is REPLACE, then the change is copied
  11050. ** into the rebased changeset with updates to columns also updated by
  11051. ** the conflicting remote UPDATE removed. If this means no columns would
  11052. ** be updated, the change is omitted.
  11053. ** </dl>
  11054. **
  11055. ** A local change may be rebased against multiple remote changes
  11056. ** simultaneously. If a single key is modified by multiple remote
  11057. ** changesets, they are combined as follows before the local changeset
  11058. ** is rebased:
  11059. **
  11060. ** <ul>
  11061. ** <li> If there has been one or more REPLACE resolutions on a
  11062. ** key, it is rebased according to a REPLACE.
  11063. **
  11064. ** <li> If there have been no REPLACE resolutions on a key, then
  11065. ** the local changeset is rebased according to the most recent
  11066. ** of the OMIT resolutions.
  11067. ** </ul>
  11068. **
  11069. ** Note that conflict resolutions from multiple remote changesets are
  11070. ** combined on a per-field basis, not per-row. This means that in the
  11071. ** case of multiple remote UPDATE operations, some fields of a single
  11072. ** local change may be rebased for REPLACE while others are rebased for
  11073. ** OMIT.
  11074. **
  11075. ** In order to rebase a local changeset, the remote changeset must first
  11076. ** be applied to the local database using sqlite3changeset_apply_v2() and
  11077. ** the buffer of rebase information captured. Then:
  11078. **
  11079. ** <ol>
  11080. ** <li> An sqlite3_rebaser object is created by calling
  11081. ** sqlite3rebaser_create().
  11082. ** <li> The new object is configured with the rebase buffer obtained from
  11083. ** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
  11084. ** If the local changeset is to be rebased against multiple remote
  11085. ** changesets, then sqlite3rebaser_configure() should be called
  11086. ** multiple times, in the same order that the multiple
  11087. ** sqlite3changeset_apply_v2() calls were made.
  11088. ** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
  11089. ** <li> The sqlite3_rebaser object is deleted by calling
  11090. ** sqlite3rebaser_delete().
  11091. ** </ol>
  11092. */
  11093. typedef struct sqlite3_rebaser sqlite3_rebaser;
  11094. /*
  11095. ** CAPI3REF: Create a changeset rebaser object.
  11096. ** EXPERIMENTAL
  11097. **
  11098. ** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
  11099. ** point to the new object and return SQLITE_OK. Otherwise, if an error
  11100. ** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
  11101. ** to NULL.
  11102. */
  11103. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
  11104. /*
  11105. ** CAPI3REF: Configure a changeset rebaser object.
  11106. ** EXPERIMENTAL
  11107. **
  11108. ** Configure the changeset rebaser object to rebase changesets according
  11109. ** to the conflict resolutions described by buffer pRebase (size nRebase
  11110. ** bytes), which must have been obtained from a previous call to
  11111. ** sqlite3changeset_apply_v2().
  11112. */
  11113. SQLITE_API int sqlite3rebaser_configure(
  11114. sqlite3_rebaser*,
  11115. int nRebase, const void *pRebase
  11116. );
  11117. /*
  11118. ** CAPI3REF: Rebase a changeset
  11119. ** EXPERIMENTAL
  11120. **
  11121. ** Argument pIn must point to a buffer containing a changeset nIn bytes
  11122. ** in size. This function allocates and populates a buffer with a copy
  11123. ** of the changeset rebased rebased according to the configuration of the
  11124. ** rebaser object passed as the first argument. If successful, (*ppOut)
  11125. ** is set to point to the new buffer containing the rebased changset and
  11126. ** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
  11127. ** responsibility of the caller to eventually free the new buffer using
  11128. ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
  11129. ** are set to zero and an SQLite error code returned.
  11130. */
  11131. SQLITE_API int sqlite3rebaser_rebase(
  11132. sqlite3_rebaser*,
  11133. int nIn, const void *pIn,
  11134. int *pnOut, void **ppOut
  11135. );
  11136. /*
  11137. ** CAPI3REF: Delete a changeset rebaser object.
  11138. ** EXPERIMENTAL
  11139. **
  11140. ** Delete the changeset rebaser object and all associated resources. There
  11141. ** should be one call to this function for each successful invocation
  11142. ** of sqlite3rebaser_create().
  11143. */
  11144. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
  11145. /*
  11146. ** CAPI3REF: Streaming Versions of API functions.
  11147. **
  11148. ** The six streaming API xxx_strm() functions serve similar purposes to the
  11149. ** corresponding non-streaming API functions:
  11150. **
  11151. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  11152. ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
  11153. ** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
  11154. ** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
  11155. ** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
  11156. ** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
  11157. ** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
  11158. ** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
  11159. ** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
  11160. ** </table>
  11161. **
  11162. ** Non-streaming functions that accept changesets (or patchsets) as input
  11163. ** require that the entire changeset be stored in a single buffer in memory.
  11164. ** Similarly, those that return a changeset or patchset do so by returning
  11165. ** a pointer to a single large buffer allocated using sqlite3_malloc().
  11166. ** Normally this is convenient. However, if an application running in a
  11167. ** low-memory environment is required to handle very large changesets, the
  11168. ** large contiguous memory allocations required can become onerous.
  11169. **
  11170. ** In order to avoid this problem, instead of a single large buffer, input
  11171. ** is passed to a streaming API functions by way of a callback function that
  11172. ** the sessions module invokes to incrementally request input data as it is
  11173. ** required. In all cases, a pair of API function parameters such as
  11174. **
  11175. ** <pre>
  11176. ** &nbsp; int nChangeset,
  11177. ** &nbsp; void *pChangeset,
  11178. ** </pre>
  11179. **
  11180. ** Is replaced by:
  11181. **
  11182. ** <pre>
  11183. ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
  11184. ** &nbsp; void *pIn,
  11185. ** </pre>
  11186. **
  11187. ** Each time the xInput callback is invoked by the sessions module, the first
  11188. ** argument passed is a copy of the supplied pIn context pointer. The second
  11189. ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
  11190. ** error occurs the xInput method should copy up to (*pnData) bytes of data
  11191. ** into the buffer and set (*pnData) to the actual number of bytes copied
  11192. ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
  11193. ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
  11194. ** error code should be returned. In all cases, if an xInput callback returns
  11195. ** an error, all processing is abandoned and the streaming API function
  11196. ** returns a copy of the error code to the caller.
  11197. **
  11198. ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
  11199. ** invoked by the sessions module at any point during the lifetime of the
  11200. ** iterator. If such an xInput callback returns an error, the iterator enters
  11201. ** an error state, whereby all subsequent calls to iterator functions
  11202. ** immediately fail with the same error code as returned by xInput.
  11203. **
  11204. ** Similarly, streaming API functions that return changesets (or patchsets)
  11205. ** return them in chunks by way of a callback function instead of via a
  11206. ** pointer to a single large buffer. In this case, a pair of parameters such
  11207. ** as:
  11208. **
  11209. ** <pre>
  11210. ** &nbsp; int *pnChangeset,
  11211. ** &nbsp; void **ppChangeset,
  11212. ** </pre>
  11213. **
  11214. ** Is replaced by:
  11215. **
  11216. ** <pre>
  11217. ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
  11218. ** &nbsp; void *pOut
  11219. ** </pre>
  11220. **
  11221. ** The xOutput callback is invoked zero or more times to return data to
  11222. ** the application. The first parameter passed to each call is a copy of the
  11223. ** pOut pointer supplied by the application. The second parameter, pData,
  11224. ** points to a buffer nData bytes in size containing the chunk of output
  11225. ** data being returned. If the xOutput callback successfully processes the
  11226. ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
  11227. ** it should return some other SQLite error code. In this case processing
  11228. ** is immediately abandoned and the streaming API function returns a copy
  11229. ** of the xOutput error code to the application.
  11230. **
  11231. ** The sessions module never invokes an xOutput callback with the third
  11232. ** parameter set to a value less than or equal to zero. Other than this,
  11233. ** no guarantees are made as to the size of the chunks of data returned.
  11234. */
  11235. SQLITE_API int sqlite3changeset_apply_strm(
  11236. sqlite3 *db, /* Apply change to "main" db of this handle */
  11237. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  11238. void *pIn, /* First arg for xInput */
  11239. int(*xFilter)(
  11240. void *pCtx, /* Copy of sixth arg to _apply() */
  11241. const char *zTab /* Table name */
  11242. ),
  11243. int(*xConflict)(
  11244. void *pCtx, /* Copy of sixth arg to _apply() */
  11245. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11246. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11247. ),
  11248. void *pCtx /* First argument passed to xConflict */
  11249. );
  11250. SQLITE_API int sqlite3changeset_apply_v2_strm(
  11251. sqlite3 *db, /* Apply change to "main" db of this handle */
  11252. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  11253. void *pIn, /* First arg for xInput */
  11254. int(*xFilter)(
  11255. void *pCtx, /* Copy of sixth arg to _apply() */
  11256. const char *zTab /* Table name */
  11257. ),
  11258. int(*xConflict)(
  11259. void *pCtx, /* Copy of sixth arg to _apply() */
  11260. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11261. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11262. ),
  11263. void *pCtx, /* First argument passed to xConflict */
  11264. void **ppRebase, int *pnRebase,
  11265. int flags
  11266. );
  11267. SQLITE_API int sqlite3changeset_concat_strm(
  11268. int (*xInputA)(void *pIn, void *pData, int *pnData),
  11269. void *pInA,
  11270. int (*xInputB)(void *pIn, void *pData, int *pnData),
  11271. void *pInB,
  11272. int (*xOutput)(void *pOut, const void *pData, int nData),
  11273. void *pOut
  11274. );
  11275. SQLITE_API int sqlite3changeset_invert_strm(
  11276. int (*xInput)(void *pIn, void *pData, int *pnData),
  11277. void *pIn,
  11278. int (*xOutput)(void *pOut, const void *pData, int nData),
  11279. void *pOut
  11280. );
  11281. SQLITE_API int sqlite3changeset_start_strm(
  11282. sqlite3_changeset_iter **pp,
  11283. int (*xInput)(void *pIn, void *pData, int *pnData),
  11284. void *pIn
  11285. );
  11286. SQLITE_API int sqlite3session_changeset_strm(
  11287. sqlite3_session *pSession,
  11288. int (*xOutput)(void *pOut, const void *pData, int nData),
  11289. void *pOut
  11290. );
  11291. SQLITE_API int sqlite3session_patchset_strm(
  11292. sqlite3_session *pSession,
  11293. int (*xOutput)(void *pOut, const void *pData, int nData),
  11294. void *pOut
  11295. );
  11296. SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
  11297. int (*xInput)(void *pIn, void *pData, int *pnData),
  11298. void *pIn
  11299. );
  11300. SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
  11301. int (*xOutput)(void *pOut, const void *pData, int nData),
  11302. void *pOut
  11303. );
  11304. SQLITE_API int sqlite3rebaser_rebase_strm(
  11305. sqlite3_rebaser *pRebaser,
  11306. int (*xInput)(void *pIn, void *pData, int *pnData),
  11307. void *pIn,
  11308. int (*xOutput)(void *pOut, const void *pData, int nData),
  11309. void *pOut
  11310. );
  11311. /*
  11312. ** Make sure we can call this stuff from C++.
  11313. */
  11314. #if 0
  11315. }
  11316. #endif
  11317. #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
  11318. /******** End of sqlite3session.h *********/
  11319. /******** Begin file fts5.h *********/
  11320. /*
  11321. ** 2014 May 31
  11322. **
  11323. ** The author disclaims copyright to this source code. In place of
  11324. ** a legal notice, here is a blessing:
  11325. **
  11326. ** May you do good and not evil.
  11327. ** May you find forgiveness for yourself and forgive others.
  11328. ** May you share freely, never taking more than you give.
  11329. **
  11330. ******************************************************************************
  11331. **
  11332. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  11333. ** FTS5 may be extended with:
  11334. **
  11335. ** * custom tokenizers, and
  11336. ** * custom auxiliary functions.
  11337. */
  11338. #ifndef _FTS5_H
  11339. #define _FTS5_H
  11340. #if 0
  11341. extern "C" {
  11342. #endif
  11343. /*************************************************************************
  11344. ** CUSTOM AUXILIARY FUNCTIONS
  11345. **
  11346. ** Virtual table implementations may overload SQL functions by implementing
  11347. ** the sqlite3_module.xFindFunction() method.
  11348. */
  11349. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  11350. typedef struct Fts5Context Fts5Context;
  11351. typedef struct Fts5PhraseIter Fts5PhraseIter;
  11352. typedef void (*fts5_extension_function)(
  11353. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  11354. Fts5Context *pFts, /* First arg to pass to pApi functions */
  11355. sqlite3_context *pCtx, /* Context for returning result/error */
  11356. int nVal, /* Number of values in apVal[] array */
  11357. sqlite3_value **apVal /* Array of trailing arguments */
  11358. );
  11359. struct Fts5PhraseIter {
  11360. const unsigned char *a;
  11361. const unsigned char *b;
  11362. };
  11363. /*
  11364. ** EXTENSION API FUNCTIONS
  11365. **
  11366. ** xUserData(pFts):
  11367. ** Return a copy of the context pointer the extension function was
  11368. ** registered with.
  11369. **
  11370. ** xColumnTotalSize(pFts, iCol, pnToken):
  11371. ** If parameter iCol is less than zero, set output variable *pnToken
  11372. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  11373. ** non-negative but less than the number of columns in the table, return
  11374. ** the total number of tokens in column iCol, considering all rows in
  11375. ** the FTS5 table.
  11376. **
  11377. ** If parameter iCol is greater than or equal to the number of columns
  11378. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  11379. ** an OOM condition or IO error), an appropriate SQLite error code is
  11380. ** returned.
  11381. **
  11382. ** xColumnCount(pFts):
  11383. ** Return the number of columns in the table.
  11384. **
  11385. ** xColumnSize(pFts, iCol, pnToken):
  11386. ** If parameter iCol is less than zero, set output variable *pnToken
  11387. ** to the total number of tokens in the current row. Or, if iCol is
  11388. ** non-negative but less than the number of columns in the table, set
  11389. ** *pnToken to the number of tokens in column iCol of the current row.
  11390. **
  11391. ** If parameter iCol is greater than or equal to the number of columns
  11392. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  11393. ** an OOM condition or IO error), an appropriate SQLite error code is
  11394. ** returned.
  11395. **
  11396. ** This function may be quite inefficient if used with an FTS5 table
  11397. ** created with the "columnsize=0" option.
  11398. **
  11399. ** xColumnText:
  11400. ** This function attempts to retrieve the text of column iCol of the
  11401. ** current document. If successful, (*pz) is set to point to a buffer
  11402. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  11403. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  11404. ** if an error occurs, an SQLite error code is returned and the final values
  11405. ** of (*pz) and (*pn) are undefined.
  11406. **
  11407. ** xPhraseCount:
  11408. ** Returns the number of phrases in the current query expression.
  11409. **
  11410. ** xPhraseSize:
  11411. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  11412. ** are numbered starting from zero.
  11413. **
  11414. ** xInstCount:
  11415. ** Set *pnInst to the total number of occurrences of all phrases within
  11416. ** the query within the current row. Return SQLITE_OK if successful, or
  11417. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  11418. **
  11419. ** This API can be quite slow if used with an FTS5 table created with the
  11420. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  11421. ** with either "detail=none" or "detail=column" and "content=" option
  11422. ** (i.e. if it is a contentless table), then this API always returns 0.
  11423. **
  11424. ** xInst:
  11425. ** Query for the details of phrase match iIdx within the current row.
  11426. ** Phrase matches are numbered starting from zero, so the iIdx argument
  11427. ** should be greater than or equal to zero and smaller than the value
  11428. ** output by xInstCount().
  11429. **
  11430. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  11431. ** to the column in which it occurs and *piOff the token offset of the
  11432. ** first token of the phrase. The exception is if the table was created
  11433. ** with the offsets=0 option specified. In this case *piOff is always
  11434. ** set to -1.
  11435. **
  11436. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  11437. ** if an error occurs.
  11438. **
  11439. ** This API can be quite slow if used with an FTS5 table created with the
  11440. ** "detail=none" or "detail=column" option.
  11441. **
  11442. ** xRowid:
  11443. ** Returns the rowid of the current row.
  11444. **
  11445. ** xTokenize:
  11446. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  11447. **
  11448. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  11449. ** This API function is used to query the FTS table for phrase iPhrase
  11450. ** of the current query. Specifically, a query equivalent to:
  11451. **
  11452. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  11453. **
  11454. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  11455. ** current query is executed. Any column filter that applies to
  11456. ** phrase iPhrase of the current query is included in $p. For each
  11457. ** row visited, the callback function passed as the fourth argument
  11458. ** is invoked. The context and API objects passed to the callback
  11459. ** function may be used to access the properties of each matched row.
  11460. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  11461. ** the third argument to pUserData.
  11462. **
  11463. ** If the callback function returns any value other than SQLITE_OK, the
  11464. ** query is abandoned and the xQueryPhrase function returns immediately.
  11465. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  11466. ** Otherwise, the error code is propagated upwards.
  11467. **
  11468. ** If the query runs to completion without incident, SQLITE_OK is returned.
  11469. ** Or, if some error occurs before the query completes or is aborted by
  11470. ** the callback, an SQLite error code is returned.
  11471. **
  11472. **
  11473. ** xSetAuxdata(pFts5, pAux, xDelete)
  11474. **
  11475. ** Save the pointer passed as the second argument as the extension functions
  11476. ** "auxiliary data". The pointer may then be retrieved by the current or any
  11477. ** future invocation of the same fts5 extension function made as part of
  11478. ** of the same MATCH query using the xGetAuxdata() API.
  11479. **
  11480. ** Each extension function is allocated a single auxiliary data slot for
  11481. ** each FTS query (MATCH expression). If the extension function is invoked
  11482. ** more than once for a single FTS query, then all invocations share a
  11483. ** single auxiliary data context.
  11484. **
  11485. ** If there is already an auxiliary data pointer when this function is
  11486. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  11487. ** was specified along with the original pointer, it is invoked at this
  11488. ** point.
  11489. **
  11490. ** The xDelete callback, if one is specified, is also invoked on the
  11491. ** auxiliary data pointer after the FTS5 query has finished.
  11492. **
  11493. ** If an error (e.g. an OOM condition) occurs within this function, an
  11494. ** the auxiliary data is set to NULL and an error code returned. If the
  11495. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  11496. ** pointer before returning.
  11497. **
  11498. **
  11499. ** xGetAuxdata(pFts5, bClear)
  11500. **
  11501. ** Returns the current auxiliary data pointer for the fts5 extension
  11502. ** function. See the xSetAuxdata() method for details.
  11503. **
  11504. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  11505. ** (set to NULL) before this function returns. In this case the xDelete,
  11506. ** if any, is not invoked.
  11507. **
  11508. **
  11509. ** xRowCount(pFts5, pnRow)
  11510. **
  11511. ** This function is used to retrieve the total number of rows in the table.
  11512. ** In other words, the same value that would be returned by:
  11513. **
  11514. ** SELECT count(*) FROM ftstable;
  11515. **
  11516. ** xPhraseFirst()
  11517. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  11518. ** method, to iterate through all instances of a single query phrase within
  11519. ** the current row. This is the same information as is accessible via the
  11520. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  11521. ** to use, this API may be faster under some circumstances. To iterate
  11522. ** through instances of phrase iPhrase, use the following code:
  11523. **
  11524. ** Fts5PhraseIter iter;
  11525. ** int iCol, iOff;
  11526. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  11527. ** iCol>=0;
  11528. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  11529. ** ){
  11530. ** // An instance of phrase iPhrase at offset iOff of column iCol
  11531. ** }
  11532. **
  11533. ** The Fts5PhraseIter structure is defined above. Applications should not
  11534. ** modify this structure directly - it should only be used as shown above
  11535. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  11536. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  11537. **
  11538. ** This API can be quite slow if used with an FTS5 table created with the
  11539. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  11540. ** with either "detail=none" or "detail=column" and "content=" option
  11541. ** (i.e. if it is a contentless table), then this API always iterates
  11542. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  11543. **
  11544. ** xPhraseNext()
  11545. ** See xPhraseFirst above.
  11546. **
  11547. ** xPhraseFirstColumn()
  11548. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  11549. ** and xPhraseNext() APIs described above. The difference is that instead
  11550. ** of iterating through all instances of a phrase in the current row, these
  11551. ** APIs are used to iterate through the set of columns in the current row
  11552. ** that contain one or more instances of a specified phrase. For example:
  11553. **
  11554. ** Fts5PhraseIter iter;
  11555. ** int iCol;
  11556. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  11557. ** iCol>=0;
  11558. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  11559. ** ){
  11560. ** // Column iCol contains at least one instance of phrase iPhrase
  11561. ** }
  11562. **
  11563. ** This API can be quite slow if used with an FTS5 table created with the
  11564. ** "detail=none" option. If the FTS5 table is created with either
  11565. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  11566. ** then this API always iterates through an empty set (all calls to
  11567. ** xPhraseFirstColumn() set iCol to -1).
  11568. **
  11569. ** The information accessed using this API and its companion
  11570. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  11571. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  11572. ** significantly more efficient than those alternatives when used with
  11573. ** "detail=column" tables.
  11574. **
  11575. ** xPhraseNextColumn()
  11576. ** See xPhraseFirstColumn above.
  11577. */
  11578. struct Fts5ExtensionApi {
  11579. int iVersion; /* Currently always set to 3 */
  11580. void *(*xUserData)(Fts5Context*);
  11581. int (*xColumnCount)(Fts5Context*);
  11582. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  11583. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  11584. int (*xTokenize)(Fts5Context*,
  11585. const char *pText, int nText, /* Text to tokenize */
  11586. void *pCtx, /* Context passed to xToken() */
  11587. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  11588. );
  11589. int (*xPhraseCount)(Fts5Context*);
  11590. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  11591. int (*xInstCount)(Fts5Context*, int *pnInst);
  11592. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  11593. sqlite3_int64 (*xRowid)(Fts5Context*);
  11594. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  11595. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  11596. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  11597. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  11598. );
  11599. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  11600. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  11601. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  11602. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  11603. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  11604. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  11605. };
  11606. /*
  11607. ** CUSTOM AUXILIARY FUNCTIONS
  11608. *************************************************************************/
  11609. /*************************************************************************
  11610. ** CUSTOM TOKENIZERS
  11611. **
  11612. ** Applications may also register custom tokenizer types. A tokenizer
  11613. ** is registered by providing fts5 with a populated instance of the
  11614. ** following structure. All structure methods must be defined, setting
  11615. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  11616. ** behaviour. The structure methods are expected to function as follows:
  11617. **
  11618. ** xCreate:
  11619. ** This function is used to allocate and initialize a tokenizer instance.
  11620. ** A tokenizer instance is required to actually tokenize text.
  11621. **
  11622. ** The first argument passed to this function is a copy of the (void*)
  11623. ** pointer provided by the application when the fts5_tokenizer object
  11624. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  11625. ** The second and third arguments are an array of nul-terminated strings
  11626. ** containing the tokenizer arguments, if any, specified following the
  11627. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  11628. ** to create the FTS5 table.
  11629. **
  11630. ** The final argument is an output variable. If successful, (*ppOut)
  11631. ** should be set to point to the new tokenizer handle and SQLITE_OK
  11632. ** returned. If an error occurs, some value other than SQLITE_OK should
  11633. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  11634. ** is undefined.
  11635. **
  11636. ** xDelete:
  11637. ** This function is invoked to delete a tokenizer handle previously
  11638. ** allocated using xCreate(). Fts5 guarantees that this function will
  11639. ** be invoked exactly once for each successful call to xCreate().
  11640. **
  11641. ** xTokenize:
  11642. ** This function is expected to tokenize the nText byte string indicated
  11643. ** by argument pText. pText may or may not be nul-terminated. The first
  11644. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  11645. ** returned by an earlier call to xCreate().
  11646. **
  11647. ** The second argument indicates the reason that FTS5 is requesting
  11648. ** tokenization of the supplied text. This is always one of the following
  11649. ** four values:
  11650. **
  11651. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  11652. ** or removed from the FTS table. The tokenizer is being invoked to
  11653. ** determine the set of tokens to add to (or delete from) the
  11654. ** FTS index.
  11655. **
  11656. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  11657. ** against the FTS index. The tokenizer is being called to tokenize
  11658. ** a bareword or quoted string specified as part of the query.
  11659. **
  11660. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  11661. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  11662. ** followed by a "*" character, indicating that the last token
  11663. ** returned by the tokenizer will be treated as a token prefix.
  11664. **
  11665. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  11666. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  11667. ** function. Or an fts5_api.xColumnSize() request made by the same
  11668. ** on a columnsize=0 database.
  11669. ** </ul>
  11670. **
  11671. ** For each token in the input string, the supplied callback xToken() must
  11672. ** be invoked. The first argument to it should be a copy of the pointer
  11673. ** passed as the second argument to xTokenize(). The third and fourth
  11674. ** arguments are a pointer to a buffer containing the token text, and the
  11675. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  11676. ** of the first byte of and first byte immediately following the text from
  11677. ** which the token is derived within the input.
  11678. **
  11679. ** The second argument passed to the xToken() callback ("tflags") should
  11680. ** normally be set to 0. The exception is if the tokenizer supports
  11681. ** synonyms. In this case see the discussion below for details.
  11682. **
  11683. ** FTS5 assumes the xToken() callback is invoked for each token in the
  11684. ** order that they occur within the input text.
  11685. **
  11686. ** If an xToken() callback returns any value other than SQLITE_OK, then
  11687. ** the tokenization should be abandoned and the xTokenize() method should
  11688. ** immediately return a copy of the xToken() return value. Or, if the
  11689. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  11690. ** if an error occurs with the xTokenize() implementation itself, it
  11691. ** may abandon the tokenization and return any error code other than
  11692. ** SQLITE_OK or SQLITE_DONE.
  11693. **
  11694. ** SYNONYM SUPPORT
  11695. **
  11696. ** Custom tokenizers may also support synonyms. Consider a case in which a
  11697. ** user wishes to query for a phrase such as "first place". Using the
  11698. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  11699. ** of "first place" within the document set, but not alternative forms
  11700. ** such as "1st place". In some applications, it would be better to match
  11701. ** all instances of "first place" or "1st place" regardless of which form
  11702. ** the user specified in the MATCH query text.
  11703. **
  11704. ** There are several ways to approach this in FTS5:
  11705. **
  11706. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  11707. ** In the above example, this means that the tokenizer returns the
  11708. ** same token for inputs "first" and "1st". Say that token is in
  11709. ** fact "first", so that when the user inserts the document "I won
  11710. ** 1st place" entries are added to the index for tokens "i", "won",
  11711. ** "first" and "place". If the user then queries for '1st + place',
  11712. ** the tokenizer substitutes "first" for "1st" and the query works
  11713. ** as expected.
  11714. **
  11715. ** <li> By adding multiple synonyms for a single term to the FTS index.
  11716. ** In this case, when tokenizing query text, the tokenizer may
  11717. ** provide multiple synonyms for a single term within the document.
  11718. ** FTS5 then queries the index for each synonym individually. For
  11719. ** example, faced with the query:
  11720. **
  11721. ** <codeblock>
  11722. ** ... MATCH 'first place'</codeblock>
  11723. **
  11724. ** the tokenizer offers both "1st" and "first" as synonyms for the
  11725. ** first token in the MATCH query and FTS5 effectively runs a query
  11726. ** similar to:
  11727. **
  11728. ** <codeblock>
  11729. ** ... MATCH '(first OR 1st) place'</codeblock>
  11730. **
  11731. ** except that, for the purposes of auxiliary functions, the query
  11732. ** still appears to contain just two phrases - "(first OR 1st)"
  11733. ** being treated as a single phrase.
  11734. **
  11735. ** <li> By adding multiple synonyms for a single term to the FTS index.
  11736. ** Using this method, when tokenizing document text, the tokenizer
  11737. ** provides multiple synonyms for each token. So that when a
  11738. ** document such as "I won first place" is tokenized, entries are
  11739. ** added to the FTS index for "i", "won", "first", "1st" and
  11740. ** "place".
  11741. **
  11742. ** This way, even if the tokenizer does not provide synonyms
  11743. ** when tokenizing query text (it should not - to do would be
  11744. ** inefficient), it doesn't matter if the user queries for
  11745. ** 'first + place' or '1st + place', as there are entires in the
  11746. ** FTS index corresponding to both forms of the first token.
  11747. ** </ol>
  11748. **
  11749. ** Whether it is parsing document or query text, any call to xToken that
  11750. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  11751. ** is considered to supply a synonym for the previous token. For example,
  11752. ** when parsing the document "I won first place", a tokenizer that supports
  11753. ** synonyms would call xToken() 5 times, as follows:
  11754. **
  11755. ** <codeblock>
  11756. ** xToken(pCtx, 0, "i", 1, 0, 1);
  11757. ** xToken(pCtx, 0, "won", 3, 2, 5);
  11758. ** xToken(pCtx, 0, "first", 5, 6, 11);
  11759. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  11760. ** xToken(pCtx, 0, "place", 5, 12, 17);
  11761. **</codeblock>
  11762. **
  11763. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  11764. ** xToken() is called. Multiple synonyms may be specified for a single token
  11765. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  11766. ** There is no limit to the number of synonyms that may be provided for a
  11767. ** single token.
  11768. **
  11769. ** In many cases, method (1) above is the best approach. It does not add
  11770. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  11771. ** so it is efficient in terms of disk space and query speed. However, it
  11772. ** does not support prefix queries very well. If, as suggested above, the
  11773. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  11774. **
  11775. ** <codeblock>
  11776. ** ... MATCH '1s*'</codeblock>
  11777. **
  11778. ** will not match documents that contain the token "1st" (as the tokenizer
  11779. ** will probably not map "1s" to any prefix of "first").
  11780. **
  11781. ** For full prefix support, method (3) may be preferred. In this case,
  11782. ** because the index contains entries for both "first" and "1st", prefix
  11783. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  11784. ** extra entries are added to the FTS index, this method uses more space
  11785. ** within the database.
  11786. **
  11787. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  11788. ** a query such as '1s*' will match documents that contain the literal
  11789. ** token "1st", but not "first" (assuming the tokenizer is not able to
  11790. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  11791. ** will match against "1st" and "first". This method does not require
  11792. ** extra disk space, as no extra entries are added to the FTS index.
  11793. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  11794. ** as separate queries of the FTS index are required for each synonym.
  11795. **
  11796. ** When using methods (2) or (3), it is important that the tokenizer only
  11797. ** provide synonyms when tokenizing document text (method (2)) or query
  11798. ** text (method (3)), not both. Doing so will not cause any errors, but is
  11799. ** inefficient.
  11800. */
  11801. typedef struct Fts5Tokenizer Fts5Tokenizer;
  11802. typedef struct fts5_tokenizer fts5_tokenizer;
  11803. struct fts5_tokenizer {
  11804. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  11805. void (*xDelete)(Fts5Tokenizer*);
  11806. int (*xTokenize)(Fts5Tokenizer*,
  11807. void *pCtx,
  11808. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  11809. const char *pText, int nText,
  11810. int (*xToken)(
  11811. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  11812. int tflags, /* Mask of FTS5_TOKEN_* flags */
  11813. const char *pToken, /* Pointer to buffer containing token */
  11814. int nToken, /* Size of token in bytes */
  11815. int iStart, /* Byte offset of token within input text */
  11816. int iEnd /* Byte offset of end of token within input text */
  11817. )
  11818. );
  11819. };
  11820. /* Flags that may be passed as the third argument to xTokenize() */
  11821. #define FTS5_TOKENIZE_QUERY 0x0001
  11822. #define FTS5_TOKENIZE_PREFIX 0x0002
  11823. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  11824. #define FTS5_TOKENIZE_AUX 0x0008
  11825. /* Flags that may be passed by the tokenizer implementation back to FTS5
  11826. ** as the third argument to the supplied xToken callback. */
  11827. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  11828. /*
  11829. ** END OF CUSTOM TOKENIZERS
  11830. *************************************************************************/
  11831. /*************************************************************************
  11832. ** FTS5 EXTENSION REGISTRATION API
  11833. */
  11834. typedef struct fts5_api fts5_api;
  11835. struct fts5_api {
  11836. int iVersion; /* Currently always set to 2 */
  11837. /* Create a new tokenizer */
  11838. int (*xCreateTokenizer)(
  11839. fts5_api *pApi,
  11840. const char *zName,
  11841. void *pContext,
  11842. fts5_tokenizer *pTokenizer,
  11843. void (*xDestroy)(void*)
  11844. );
  11845. /* Find an existing tokenizer */
  11846. int (*xFindTokenizer)(
  11847. fts5_api *pApi,
  11848. const char *zName,
  11849. void **ppContext,
  11850. fts5_tokenizer *pTokenizer
  11851. );
  11852. /* Create a new auxiliary function */
  11853. int (*xCreateFunction)(
  11854. fts5_api *pApi,
  11855. const char *zName,
  11856. void *pContext,
  11857. fts5_extension_function xFunction,
  11858. void (*xDestroy)(void*)
  11859. );
  11860. };
  11861. /*
  11862. ** END OF REGISTRATION API
  11863. *************************************************************************/
  11864. #if 0
  11865. } /* end of the 'extern "C"' block */
  11866. #endif
  11867. #endif /* _FTS5_H */
  11868. /******** End of fts5.h *********/
  11869. /************** End of sqlite3.h *********************************************/
  11870. /************** Continuing where we left off in sqliteInt.h ******************/
  11871. /*
  11872. ** Include the configuration header output by 'configure' if we're using the
  11873. ** autoconf-based build
  11874. */
  11875. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  11876. /* #include "config.h" */
  11877. #define SQLITECONFIG_H 1
  11878. #endif
  11879. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  11880. /************** Begin file sqliteLimit.h *************************************/
  11881. /*
  11882. ** 2007 May 7
  11883. **
  11884. ** The author disclaims copyright to this source code. In place of
  11885. ** a legal notice, here is a blessing:
  11886. **
  11887. ** May you do good and not evil.
  11888. ** May you find forgiveness for yourself and forgive others.
  11889. ** May you share freely, never taking more than you give.
  11890. **
  11891. *************************************************************************
  11892. **
  11893. ** This file defines various limits of what SQLite can process.
  11894. */
  11895. /*
  11896. ** The maximum length of a TEXT or BLOB in bytes. This also
  11897. ** limits the size of a row in a table or index.
  11898. **
  11899. ** The hard limit is the ability of a 32-bit signed integer
  11900. ** to count the size: 2^31-1 or 2147483647.
  11901. */
  11902. #ifndef SQLITE_MAX_LENGTH
  11903. # define SQLITE_MAX_LENGTH 1000000000
  11904. #endif
  11905. /*
  11906. ** This is the maximum number of
  11907. **
  11908. ** * Columns in a table
  11909. ** * Columns in an index
  11910. ** * Columns in a view
  11911. ** * Terms in the SET clause of an UPDATE statement
  11912. ** * Terms in the result set of a SELECT statement
  11913. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  11914. ** * Terms in the VALUES clause of an INSERT statement
  11915. **
  11916. ** The hard upper limit here is 32676. Most database people will
  11917. ** tell you that in a well-normalized database, you usually should
  11918. ** not have more than a dozen or so columns in any table. And if
  11919. ** that is the case, there is no point in having more than a few
  11920. ** dozen values in any of the other situations described above.
  11921. */
  11922. #ifndef SQLITE_MAX_COLUMN
  11923. # define SQLITE_MAX_COLUMN 2000
  11924. #endif
  11925. /*
  11926. ** The maximum length of a single SQL statement in bytes.
  11927. **
  11928. ** It used to be the case that setting this value to zero would
  11929. ** turn the limit off. That is no longer true. It is not possible
  11930. ** to turn this limit off.
  11931. */
  11932. #ifndef SQLITE_MAX_SQL_LENGTH
  11933. # define SQLITE_MAX_SQL_LENGTH 1000000000
  11934. #endif
  11935. /*
  11936. ** The maximum depth of an expression tree. This is limited to
  11937. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  11938. ** want to place more severe limits on the complexity of an
  11939. ** expression.
  11940. **
  11941. ** A value of 0 used to mean that the limit was not enforced.
  11942. ** But that is no longer true. The limit is now strictly enforced
  11943. ** at all times.
  11944. */
  11945. #ifndef SQLITE_MAX_EXPR_DEPTH
  11946. # define SQLITE_MAX_EXPR_DEPTH 1000
  11947. #endif
  11948. /*
  11949. ** The maximum number of terms in a compound SELECT statement.
  11950. ** The code generator for compound SELECT statements does one
  11951. ** level of recursion for each term. A stack overflow can result
  11952. ** if the number of terms is too large. In practice, most SQL
  11953. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  11954. ** any limit on the number of terms in a compount SELECT.
  11955. */
  11956. #ifndef SQLITE_MAX_COMPOUND_SELECT
  11957. # define SQLITE_MAX_COMPOUND_SELECT 500
  11958. #endif
  11959. /*
  11960. ** The maximum number of opcodes in a VDBE program.
  11961. ** Not currently enforced.
  11962. */
  11963. #ifndef SQLITE_MAX_VDBE_OP
  11964. # define SQLITE_MAX_VDBE_OP 250000000
  11965. #endif
  11966. /*
  11967. ** The maximum number of arguments to an SQL function.
  11968. */
  11969. #ifndef SQLITE_MAX_FUNCTION_ARG
  11970. # define SQLITE_MAX_FUNCTION_ARG 127
  11971. #endif
  11972. /*
  11973. ** The suggested maximum number of in-memory pages to use for
  11974. ** the main database table and for temporary tables.
  11975. **
  11976. ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
  11977. ** which means the cache size is limited to 2048000 bytes of memory.
  11978. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  11979. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  11980. */
  11981. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  11982. # define SQLITE_DEFAULT_CACHE_SIZE -2000
  11983. #endif
  11984. /*
  11985. ** The default number of frames to accumulate in the log file before
  11986. ** checkpointing the database in WAL mode.
  11987. */
  11988. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  11989. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  11990. #endif
  11991. /*
  11992. ** The maximum number of attached databases. This must be between 0
  11993. ** and 125. The upper bound of 125 is because the attached databases are
  11994. ** counted using a signed 8-bit integer which has a maximum value of 127
  11995. ** and we have to allow 2 extra counts for the "main" and "temp" databases.
  11996. */
  11997. #ifndef SQLITE_MAX_ATTACHED
  11998. # define SQLITE_MAX_ATTACHED 10
  11999. #endif
  12000. /*
  12001. ** The maximum value of a ?nnn wildcard that the parser will accept.
  12002. */
  12003. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  12004. # define SQLITE_MAX_VARIABLE_NUMBER 999
  12005. #endif
  12006. /* Maximum page size. The upper bound on this value is 65536. This a limit
  12007. ** imposed by the use of 16-bit offsets within each page.
  12008. **
  12009. ** Earlier versions of SQLite allowed the user to change this value at
  12010. ** compile time. This is no longer permitted, on the grounds that it creates
  12011. ** a library that is technically incompatible with an SQLite library
  12012. ** compiled with a different limit. If a process operating on a database
  12013. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  12014. ** compiled with the default page-size limit will not be able to rollback
  12015. ** the aborted transaction. This could lead to database corruption.
  12016. */
  12017. #ifdef SQLITE_MAX_PAGE_SIZE
  12018. # undef SQLITE_MAX_PAGE_SIZE
  12019. #endif
  12020. #define SQLITE_MAX_PAGE_SIZE 65536
  12021. /*
  12022. ** The default size of a database page.
  12023. */
  12024. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  12025. # define SQLITE_DEFAULT_PAGE_SIZE 4096
  12026. #endif
  12027. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  12028. # undef SQLITE_DEFAULT_PAGE_SIZE
  12029. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  12030. #endif
  12031. /*
  12032. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  12033. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  12034. ** device characteristics (sector-size and atomic write() support),
  12035. ** SQLite may choose a larger value. This constant is the maximum value
  12036. ** SQLite will choose on its own.
  12037. */
  12038. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  12039. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  12040. #endif
  12041. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  12042. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  12043. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  12044. #endif
  12045. /*
  12046. ** Maximum number of pages in one database file.
  12047. **
  12048. ** This is really just the default value for the max_page_count pragma.
  12049. ** This value can be lowered (or raised) at run-time using that the
  12050. ** max_page_count macro.
  12051. */
  12052. #ifndef SQLITE_MAX_PAGE_COUNT
  12053. # define SQLITE_MAX_PAGE_COUNT 1073741823
  12054. #endif
  12055. /*
  12056. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  12057. ** operator.
  12058. */
  12059. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  12060. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  12061. #endif
  12062. /*
  12063. ** Maximum depth of recursion for triggers.
  12064. **
  12065. ** A value of 1 means that a trigger program will not be able to itself
  12066. ** fire any triggers. A value of 0 means that no trigger programs at all
  12067. ** may be executed.
  12068. */
  12069. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  12070. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  12071. #endif
  12072. /************** End of sqliteLimit.h *****************************************/
  12073. /************** Continuing where we left off in sqliteInt.h ******************/
  12074. /* Disable nuisance warnings on Borland compilers */
  12075. #if defined(__BORLANDC__)
  12076. #pragma warn -rch /* unreachable code */
  12077. #pragma warn -ccc /* Condition is always true or false */
  12078. #pragma warn -aus /* Assigned value is never used */
  12079. #pragma warn -csu /* Comparing signed and unsigned */
  12080. #pragma warn -spa /* Suspicious pointer arithmetic */
  12081. #endif
  12082. /*
  12083. ** Include standard header files as necessary
  12084. */
  12085. #ifdef HAVE_STDINT_H
  12086. #include <stdint.h>
  12087. #endif
  12088. #ifdef HAVE_INTTYPES_H
  12089. #include <inttypes.h>
  12090. #endif
  12091. /*
  12092. ** The following macros are used to cast pointers to integers and
  12093. ** integers to pointers. The way you do this varies from one compiler
  12094. ** to the next, so we have developed the following set of #if statements
  12095. ** to generate appropriate macros for a wide range of compilers.
  12096. **
  12097. ** The correct "ANSI" way to do this is to use the intptr_t type.
  12098. ** Unfortunately, that typedef is not available on all compilers, or
  12099. ** if it is available, it requires an #include of specific headers
  12100. ** that vary from one machine to the next.
  12101. **
  12102. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  12103. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  12104. ** So we have to define the macros in different ways depending on the
  12105. ** compiler.
  12106. */
  12107. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  12108. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  12109. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  12110. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  12111. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  12112. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  12113. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  12114. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  12115. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  12116. #else /* Generates a warning - but it always works */
  12117. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  12118. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  12119. #endif
  12120. /*
  12121. ** A macro to hint to the compiler that a function should not be
  12122. ** inlined.
  12123. */
  12124. #if defined(__GNUC__)
  12125. # define SQLITE_NOINLINE __attribute__((noinline))
  12126. #elif defined(_MSC_VER) && _MSC_VER>=1310
  12127. # define SQLITE_NOINLINE __declspec(noinline)
  12128. #else
  12129. # define SQLITE_NOINLINE
  12130. #endif
  12131. /*
  12132. ** Make sure that the compiler intrinsics we desire are enabled when
  12133. ** compiling with an appropriate version of MSVC unless prevented by
  12134. ** the SQLITE_DISABLE_INTRINSIC define.
  12135. */
  12136. #if !defined(SQLITE_DISABLE_INTRINSIC)
  12137. # if defined(_MSC_VER) && _MSC_VER>=1400
  12138. # if !defined(_WIN32_WCE)
  12139. # include <intrin.h>
  12140. # pragma intrinsic(_byteswap_ushort)
  12141. # pragma intrinsic(_byteswap_ulong)
  12142. # pragma intrinsic(_byteswap_uint64)
  12143. # pragma intrinsic(_ReadWriteBarrier)
  12144. # else
  12145. # include <cmnintrin.h>
  12146. # endif
  12147. # endif
  12148. #endif
  12149. /*
  12150. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  12151. ** 0 means mutexes are permanently disable and the library is never
  12152. ** threadsafe. 1 means the library is serialized which is the highest
  12153. ** level of threadsafety. 2 means the library is multithreaded - multiple
  12154. ** threads can use SQLite as long as no two threads try to use the same
  12155. ** database connection at the same time.
  12156. **
  12157. ** Older versions of SQLite used an optional THREADSAFE macro.
  12158. ** We support that for legacy.
  12159. **
  12160. ** To ensure that the correct value of "THREADSAFE" is reported when querying
  12161. ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
  12162. ** logic is partially replicated in ctime.c. If it is updated here, it should
  12163. ** also be updated there.
  12164. */
  12165. #if !defined(SQLITE_THREADSAFE)
  12166. # if defined(THREADSAFE)
  12167. # define SQLITE_THREADSAFE THREADSAFE
  12168. # else
  12169. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  12170. # endif
  12171. #endif
  12172. /*
  12173. ** Powersafe overwrite is on by default. But can be turned off using
  12174. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  12175. */
  12176. #ifndef SQLITE_POWERSAFE_OVERWRITE
  12177. # define SQLITE_POWERSAFE_OVERWRITE 1
  12178. #endif
  12179. /*
  12180. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  12181. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  12182. ** which case memory allocation statistics are disabled by default.
  12183. */
  12184. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  12185. # define SQLITE_DEFAULT_MEMSTATUS 1
  12186. #endif
  12187. /*
  12188. ** Exactly one of the following macros must be defined in order to
  12189. ** specify which memory allocation subsystem to use.
  12190. **
  12191. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  12192. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  12193. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  12194. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  12195. **
  12196. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  12197. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  12198. ** will cause HeapValidate to be called. If heap validation should fail, an
  12199. ** assertion will be triggered.
  12200. **
  12201. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  12202. ** the default.
  12203. */
  12204. #if defined(SQLITE_SYSTEM_MALLOC) \
  12205. + defined(SQLITE_WIN32_MALLOC) \
  12206. + defined(SQLITE_ZERO_MALLOC) \
  12207. + defined(SQLITE_MEMDEBUG)>1
  12208. # error "Two or more of the following compile-time configuration options\
  12209. are defined but at most one is allowed:\
  12210. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  12211. SQLITE_ZERO_MALLOC"
  12212. #endif
  12213. #if defined(SQLITE_SYSTEM_MALLOC) \
  12214. + defined(SQLITE_WIN32_MALLOC) \
  12215. + defined(SQLITE_ZERO_MALLOC) \
  12216. + defined(SQLITE_MEMDEBUG)==0
  12217. # define SQLITE_SYSTEM_MALLOC 1
  12218. #endif
  12219. /*
  12220. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  12221. ** sizes of memory allocations below this value where possible.
  12222. */
  12223. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  12224. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  12225. #endif
  12226. /*
  12227. ** We need to define _XOPEN_SOURCE as follows in order to enable
  12228. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  12229. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  12230. ** it.
  12231. */
  12232. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  12233. # define _XOPEN_SOURCE 600
  12234. #endif
  12235. /*
  12236. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  12237. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  12238. ** make it true by defining or undefining NDEBUG.
  12239. **
  12240. ** Setting NDEBUG makes the code smaller and faster by disabling the
  12241. ** assert() statements in the code. So we want the default action
  12242. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  12243. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  12244. ** feature.
  12245. */
  12246. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  12247. # define NDEBUG 1
  12248. #endif
  12249. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  12250. # undef NDEBUG
  12251. #endif
  12252. /*
  12253. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  12254. */
  12255. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  12256. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  12257. #endif
  12258. /*
  12259. ** The testcase() macro is used to aid in coverage testing. When
  12260. ** doing coverage testing, the condition inside the argument to
  12261. ** testcase() must be evaluated both true and false in order to
  12262. ** get full branch coverage. The testcase() macro is inserted
  12263. ** to help ensure adequate test coverage in places where simple
  12264. ** condition/decision coverage is inadequate. For example, testcase()
  12265. ** can be used to make sure boundary values are tested. For
  12266. ** bitmask tests, testcase() can be used to make sure each bit
  12267. ** is significant and used at least once. On switch statements
  12268. ** where multiple cases go to the same block of code, testcase()
  12269. ** can insure that all cases are evaluated.
  12270. **
  12271. */
  12272. #ifdef SQLITE_COVERAGE_TEST
  12273. SQLITE_PRIVATE void sqlite3Coverage(int);
  12274. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  12275. #else
  12276. # define testcase(X)
  12277. #endif
  12278. /*
  12279. ** The TESTONLY macro is used to enclose variable declarations or
  12280. ** other bits of code that are needed to support the arguments
  12281. ** within testcase() and assert() macros.
  12282. */
  12283. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  12284. # define TESTONLY(X) X
  12285. #else
  12286. # define TESTONLY(X)
  12287. #endif
  12288. /*
  12289. ** Sometimes we need a small amount of code such as a variable initialization
  12290. ** to setup for a later assert() statement. We do not want this code to
  12291. ** appear when assert() is disabled. The following macro is therefore
  12292. ** used to contain that setup code. The "VVA" acronym stands for
  12293. ** "Verification, Validation, and Accreditation". In other words, the
  12294. ** code within VVA_ONLY() will only run during verification processes.
  12295. */
  12296. #ifndef NDEBUG
  12297. # define VVA_ONLY(X) X
  12298. #else
  12299. # define VVA_ONLY(X)
  12300. #endif
  12301. /*
  12302. ** The ALWAYS and NEVER macros surround boolean expressions which
  12303. ** are intended to always be true or false, respectively. Such
  12304. ** expressions could be omitted from the code completely. But they
  12305. ** are included in a few cases in order to enhance the resilience
  12306. ** of SQLite to unexpected behavior - to make the code "self-healing"
  12307. ** or "ductile" rather than being "brittle" and crashing at the first
  12308. ** hint of unplanned behavior.
  12309. **
  12310. ** In other words, ALWAYS and NEVER are added for defensive code.
  12311. **
  12312. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  12313. ** be true and false so that the unreachable code they specify will
  12314. ** not be counted as untested code.
  12315. */
  12316. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  12317. # define ALWAYS(X) (1)
  12318. # define NEVER(X) (0)
  12319. #elif !defined(NDEBUG)
  12320. # define ALWAYS(X) ((X)?1:(assert(0),0))
  12321. # define NEVER(X) ((X)?(assert(0),1):0)
  12322. #else
  12323. # define ALWAYS(X) (X)
  12324. # define NEVER(X) (X)
  12325. #endif
  12326. /*
  12327. ** Some conditionals are optimizations only. In other words, if the
  12328. ** conditionals are replaced with a constant 1 (true) or 0 (false) then
  12329. ** the correct answer is still obtained, though perhaps not as quickly.
  12330. **
  12331. ** The following macros mark these optimizations conditionals.
  12332. */
  12333. #if defined(SQLITE_MUTATION_TEST)
  12334. # define OK_IF_ALWAYS_TRUE(X) (1)
  12335. # define OK_IF_ALWAYS_FALSE(X) (0)
  12336. #else
  12337. # define OK_IF_ALWAYS_TRUE(X) (X)
  12338. # define OK_IF_ALWAYS_FALSE(X) (X)
  12339. #endif
  12340. /*
  12341. ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
  12342. ** defined. We need to defend against those failures when testing with
  12343. ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
  12344. ** during a normal build. The following macro can be used to disable tests
  12345. ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
  12346. */
  12347. #if defined(SQLITE_TEST_REALLOC_STRESS)
  12348. # define ONLY_IF_REALLOC_STRESS(X) (X)
  12349. #elif !defined(NDEBUG)
  12350. # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
  12351. #else
  12352. # define ONLY_IF_REALLOC_STRESS(X) (0)
  12353. #endif
  12354. /*
  12355. ** Declarations used for tracing the operating system interfaces.
  12356. */
  12357. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  12358. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  12359. extern int sqlite3OSTrace;
  12360. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  12361. # define SQLITE_HAVE_OS_TRACE
  12362. #else
  12363. # define OSTRACE(X)
  12364. # undef SQLITE_HAVE_OS_TRACE
  12365. #endif
  12366. /*
  12367. ** Is the sqlite3ErrName() function needed in the build? Currently,
  12368. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  12369. ** OSTRACE is enabled), and by several "test*.c" files (which are
  12370. ** compiled using SQLITE_TEST).
  12371. */
  12372. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  12373. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  12374. # define SQLITE_NEED_ERR_NAME
  12375. #else
  12376. # undef SQLITE_NEED_ERR_NAME
  12377. #endif
  12378. /*
  12379. ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
  12380. */
  12381. #ifdef SQLITE_OMIT_EXPLAIN
  12382. # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
  12383. #endif
  12384. /*
  12385. ** Return true (non-zero) if the input is an integer that is too large
  12386. ** to fit in 32-bits. This macro is used inside of various testcase()
  12387. ** macros to verify that we have tested SQLite for large-file support.
  12388. */
  12389. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  12390. /*
  12391. ** The macro unlikely() is a hint that surrounds a boolean
  12392. ** expression that is usually false. Macro likely() surrounds
  12393. ** a boolean expression that is usually true. These hints could,
  12394. ** in theory, be used by the compiler to generate better code, but
  12395. ** currently they are just comments for human readers.
  12396. */
  12397. #define likely(X) (X)
  12398. #define unlikely(X) (X)
  12399. /************** Include hash.h in the middle of sqliteInt.h ******************/
  12400. /************** Begin file hash.h ********************************************/
  12401. /*
  12402. ** 2001 September 22
  12403. **
  12404. ** The author disclaims copyright to this source code. In place of
  12405. ** a legal notice, here is a blessing:
  12406. **
  12407. ** May you do good and not evil.
  12408. ** May you find forgiveness for yourself and forgive others.
  12409. ** May you share freely, never taking more than you give.
  12410. **
  12411. *************************************************************************
  12412. ** This is the header file for the generic hash-table implementation
  12413. ** used in SQLite.
  12414. */
  12415. #ifndef SQLITE_HASH_H
  12416. #define SQLITE_HASH_H
  12417. /* Forward declarations of structures. */
  12418. typedef struct Hash Hash;
  12419. typedef struct HashElem HashElem;
  12420. /* A complete hash table is an instance of the following structure.
  12421. ** The internals of this structure are intended to be opaque -- client
  12422. ** code should not attempt to access or modify the fields of this structure
  12423. ** directly. Change this structure only by using the routines below.
  12424. ** However, some of the "procedures" and "functions" for modifying and
  12425. ** accessing this structure are really macros, so we can't really make
  12426. ** this structure opaque.
  12427. **
  12428. ** All elements of the hash table are on a single doubly-linked list.
  12429. ** Hash.first points to the head of this list.
  12430. **
  12431. ** There are Hash.htsize buckets. Each bucket points to a spot in
  12432. ** the global doubly-linked list. The contents of the bucket are the
  12433. ** element pointed to plus the next _ht.count-1 elements in the list.
  12434. **
  12435. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  12436. ** by a linear search of the global list. For small tables, the
  12437. ** Hash.ht table is never allocated because if there are few elements
  12438. ** in the table, it is faster to do a linear search than to manage
  12439. ** the hash table.
  12440. */
  12441. struct Hash {
  12442. unsigned int htsize; /* Number of buckets in the hash table */
  12443. unsigned int count; /* Number of entries in this table */
  12444. HashElem *first; /* The first element of the array */
  12445. struct _ht { /* the hash table */
  12446. int count; /* Number of entries with this hash */
  12447. HashElem *chain; /* Pointer to first entry with this hash */
  12448. } *ht;
  12449. };
  12450. /* Each element in the hash table is an instance of the following
  12451. ** structure. All elements are stored on a single doubly-linked list.
  12452. **
  12453. ** Again, this structure is intended to be opaque, but it can't really
  12454. ** be opaque because it is used by macros.
  12455. */
  12456. struct HashElem {
  12457. HashElem *next, *prev; /* Next and previous elements in the table */
  12458. void *data; /* Data associated with this element */
  12459. const char *pKey; /* Key associated with this element */
  12460. };
  12461. /*
  12462. ** Access routines. To delete, insert a NULL pointer.
  12463. */
  12464. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  12465. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  12466. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  12467. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  12468. /*
  12469. ** Macros for looping over all elements of a hash table. The idiom is
  12470. ** like this:
  12471. **
  12472. ** Hash h;
  12473. ** HashElem *p;
  12474. ** ...
  12475. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  12476. ** SomeStructure *pData = sqliteHashData(p);
  12477. ** // do something with pData
  12478. ** }
  12479. */
  12480. #define sqliteHashFirst(H) ((H)->first)
  12481. #define sqliteHashNext(E) ((E)->next)
  12482. #define sqliteHashData(E) ((E)->data)
  12483. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  12484. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  12485. /*
  12486. ** Number of entries in a hash table
  12487. */
  12488. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  12489. #endif /* SQLITE_HASH_H */
  12490. /************** End of hash.h ************************************************/
  12491. /************** Continuing where we left off in sqliteInt.h ******************/
  12492. /************** Include parse.h in the middle of sqliteInt.h *****************/
  12493. /************** Begin file parse.h *******************************************/
  12494. #define TK_SEMI 1
  12495. #define TK_EXPLAIN 2
  12496. #define TK_QUERY 3
  12497. #define TK_PLAN 4
  12498. #define TK_BEGIN 5
  12499. #define TK_TRANSACTION 6
  12500. #define TK_DEFERRED 7
  12501. #define TK_IMMEDIATE 8
  12502. #define TK_EXCLUSIVE 9
  12503. #define TK_COMMIT 10
  12504. #define TK_END 11
  12505. #define TK_ROLLBACK 12
  12506. #define TK_SAVEPOINT 13
  12507. #define TK_RELEASE 14
  12508. #define TK_TO 15
  12509. #define TK_TABLE 16
  12510. #define TK_CREATE 17
  12511. #define TK_IF 18
  12512. #define TK_NOT 19
  12513. #define TK_EXISTS 20
  12514. #define TK_TEMP 21
  12515. #define TK_LP 22
  12516. #define TK_RP 23
  12517. #define TK_AS 24
  12518. #define TK_WITHOUT 25
  12519. #define TK_COMMA 26
  12520. #define TK_ABORT 27
  12521. #define TK_ACTION 28
  12522. #define TK_AFTER 29
  12523. #define TK_ANALYZE 30
  12524. #define TK_ASC 31
  12525. #define TK_ATTACH 32
  12526. #define TK_BEFORE 33
  12527. #define TK_BY 34
  12528. #define TK_CASCADE 35
  12529. #define TK_CAST 36
  12530. #define TK_CONFLICT 37
  12531. #define TK_DATABASE 38
  12532. #define TK_DESC 39
  12533. #define TK_DETACH 40
  12534. #define TK_EACH 41
  12535. #define TK_FAIL 42
  12536. #define TK_OR 43
  12537. #define TK_AND 44
  12538. #define TK_IS 45
  12539. #define TK_MATCH 46
  12540. #define TK_LIKE_KW 47
  12541. #define TK_BETWEEN 48
  12542. #define TK_IN 49
  12543. #define TK_ISNULL 50
  12544. #define TK_NOTNULL 51
  12545. #define TK_NE 52
  12546. #define TK_EQ 53
  12547. #define TK_GT 54
  12548. #define TK_LE 55
  12549. #define TK_LT 56
  12550. #define TK_GE 57
  12551. #define TK_ESCAPE 58
  12552. #define TK_ID 59
  12553. #define TK_COLUMNKW 60
  12554. #define TK_FOR 61
  12555. #define TK_IGNORE 62
  12556. #define TK_INITIALLY 63
  12557. #define TK_INSTEAD 64
  12558. #define TK_NO 65
  12559. #define TK_KEY 66
  12560. #define TK_OF 67
  12561. #define TK_OFFSET 68
  12562. #define TK_PRAGMA 69
  12563. #define TK_RAISE 70
  12564. #define TK_RECURSIVE 71
  12565. #define TK_REPLACE 72
  12566. #define TK_RESTRICT 73
  12567. #define TK_ROW 74
  12568. #define TK_TRIGGER 75
  12569. #define TK_VACUUM 76
  12570. #define TK_VIEW 77
  12571. #define TK_VIRTUAL 78
  12572. #define TK_WITH 79
  12573. #define TK_REINDEX 80
  12574. #define TK_RENAME 81
  12575. #define TK_CTIME_KW 82
  12576. #define TK_ANY 83
  12577. #define TK_BITAND 84
  12578. #define TK_BITOR 85
  12579. #define TK_LSHIFT 86
  12580. #define TK_RSHIFT 87
  12581. #define TK_PLUS 88
  12582. #define TK_MINUS 89
  12583. #define TK_STAR 90
  12584. #define TK_SLASH 91
  12585. #define TK_REM 92
  12586. #define TK_CONCAT 93
  12587. #define TK_COLLATE 94
  12588. #define TK_BITNOT 95
  12589. #define TK_INDEXED 96
  12590. #define TK_STRING 97
  12591. #define TK_JOIN_KW 98
  12592. #define TK_CONSTRAINT 99
  12593. #define TK_DEFAULT 100
  12594. #define TK_NULL 101
  12595. #define TK_PRIMARY 102
  12596. #define TK_UNIQUE 103
  12597. #define TK_CHECK 104
  12598. #define TK_REFERENCES 105
  12599. #define TK_AUTOINCR 106
  12600. #define TK_ON 107
  12601. #define TK_INSERT 108
  12602. #define TK_DELETE 109
  12603. #define TK_UPDATE 110
  12604. #define TK_SET 111
  12605. #define TK_DEFERRABLE 112
  12606. #define TK_FOREIGN 113
  12607. #define TK_DROP 114
  12608. #define TK_UNION 115
  12609. #define TK_ALL 116
  12610. #define TK_EXCEPT 117
  12611. #define TK_INTERSECT 118
  12612. #define TK_SELECT 119
  12613. #define TK_VALUES 120
  12614. #define TK_DISTINCT 121
  12615. #define TK_DOT 122
  12616. #define TK_FROM 123
  12617. #define TK_JOIN 124
  12618. #define TK_USING 125
  12619. #define TK_ORDER 126
  12620. #define TK_GROUP 127
  12621. #define TK_HAVING 128
  12622. #define TK_LIMIT 129
  12623. #define TK_WHERE 130
  12624. #define TK_INTO 131
  12625. #define TK_FLOAT 132
  12626. #define TK_BLOB 133
  12627. #define TK_INTEGER 134
  12628. #define TK_VARIABLE 135
  12629. #define TK_CASE 136
  12630. #define TK_WHEN 137
  12631. #define TK_THEN 138
  12632. #define TK_ELSE 139
  12633. #define TK_INDEX 140
  12634. #define TK_ALTER 141
  12635. #define TK_ADD 142
  12636. #define TK_TRUEFALSE 143
  12637. #define TK_ISNOT 144
  12638. #define TK_FUNCTION 145
  12639. #define TK_COLUMN 146
  12640. #define TK_AGG_FUNCTION 147
  12641. #define TK_AGG_COLUMN 148
  12642. #define TK_UMINUS 149
  12643. #define TK_UPLUS 150
  12644. #define TK_TRUTH 151
  12645. #define TK_REGISTER 152
  12646. #define TK_VECTOR 153
  12647. #define TK_SELECT_COLUMN 154
  12648. #define TK_IF_NULL_ROW 155
  12649. #define TK_ASTERISK 156
  12650. #define TK_SPAN 157
  12651. #define TK_END_OF_FILE 158
  12652. #define TK_UNCLOSED_STRING 159
  12653. #define TK_SPACE 160
  12654. #define TK_ILLEGAL 161
  12655. /* The token codes above must all fit in 8 bits */
  12656. #define TKFLG_MASK 0xff
  12657. /* Flags that can be added to a token code when it is not
  12658. ** being stored in a u8: */
  12659. #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
  12660. /************** End of parse.h ***********************************************/
  12661. /************** Continuing where we left off in sqliteInt.h ******************/
  12662. #include <stdio.h>
  12663. #include <stdlib.h>
  12664. #include <string.h>
  12665. #include <assert.h>
  12666. #include <stddef.h>
  12667. /*
  12668. ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
  12669. ** This allows better measurements of where memcpy() is used when running
  12670. ** cachegrind. But this macro version of memcpy() is very slow so it
  12671. ** should not be used in production. This is a performance measurement
  12672. ** hack only.
  12673. */
  12674. #ifdef SQLITE_INLINE_MEMCPY
  12675. # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
  12676. int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
  12677. #endif
  12678. /*
  12679. ** If compiling for a processor that lacks floating point support,
  12680. ** substitute integer for floating-point
  12681. */
  12682. #ifdef SQLITE_OMIT_FLOATING_POINT
  12683. # define double sqlite_int64
  12684. # define float sqlite_int64
  12685. # define LONGDOUBLE_TYPE sqlite_int64
  12686. # ifndef SQLITE_BIG_DBL
  12687. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  12688. # endif
  12689. # define SQLITE_OMIT_DATETIME_FUNCS 1
  12690. # define SQLITE_OMIT_TRACE 1
  12691. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  12692. # undef SQLITE_HAVE_ISNAN
  12693. #endif
  12694. #ifndef SQLITE_BIG_DBL
  12695. # define SQLITE_BIG_DBL (1e99)
  12696. #endif
  12697. /*
  12698. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  12699. ** afterward. Having this macro allows us to cause the C compiler
  12700. ** to omit code used by TEMP tables without messy #ifndef statements.
  12701. */
  12702. #ifdef SQLITE_OMIT_TEMPDB
  12703. #define OMIT_TEMPDB 1
  12704. #else
  12705. #define OMIT_TEMPDB 0
  12706. #endif
  12707. /*
  12708. ** The "file format" number is an integer that is incremented whenever
  12709. ** the VDBE-level file format changes. The following macros define the
  12710. ** the default file format for new databases and the maximum file format
  12711. ** that the library can read.
  12712. */
  12713. #define SQLITE_MAX_FILE_FORMAT 4
  12714. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  12715. # define SQLITE_DEFAULT_FILE_FORMAT 4
  12716. #endif
  12717. /*
  12718. ** Determine whether triggers are recursive by default. This can be
  12719. ** changed at run-time using a pragma.
  12720. */
  12721. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  12722. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  12723. #endif
  12724. /*
  12725. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  12726. ** on the command-line
  12727. */
  12728. #ifndef SQLITE_TEMP_STORE
  12729. # define SQLITE_TEMP_STORE 1
  12730. #endif
  12731. /*
  12732. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  12733. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  12734. ** to zero.
  12735. */
  12736. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  12737. # undef SQLITE_MAX_WORKER_THREADS
  12738. # define SQLITE_MAX_WORKER_THREADS 0
  12739. #endif
  12740. #ifndef SQLITE_MAX_WORKER_THREADS
  12741. # define SQLITE_MAX_WORKER_THREADS 8
  12742. #endif
  12743. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  12744. # define SQLITE_DEFAULT_WORKER_THREADS 0
  12745. #endif
  12746. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  12747. # undef SQLITE_MAX_WORKER_THREADS
  12748. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  12749. #endif
  12750. /*
  12751. ** The default initial allocation for the pagecache when using separate
  12752. ** pagecaches for each database connection. A positive number is the
  12753. ** number of pages. A negative number N translations means that a buffer
  12754. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  12755. **
  12756. ** The default value of "20" was choosen to minimize the run-time of the
  12757. ** speedtest1 test program with options: --shrink-memory --reprepare
  12758. */
  12759. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  12760. # define SQLITE_DEFAULT_PCACHE_INITSZ 20
  12761. #endif
  12762. /*
  12763. ** The compile-time options SQLITE_MMAP_READWRITE and
  12764. ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
  12765. ** You must choose one or the other (or neither) but not both.
  12766. */
  12767. #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  12768. #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  12769. #endif
  12770. /*
  12771. ** GCC does not define the offsetof() macro so we'll have to do it
  12772. ** ourselves.
  12773. */
  12774. #ifndef offsetof
  12775. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  12776. #endif
  12777. /*
  12778. ** Macros to compute minimum and maximum of two numbers.
  12779. */
  12780. #ifndef MIN
  12781. # define MIN(A,B) ((A)<(B)?(A):(B))
  12782. #endif
  12783. #ifndef MAX
  12784. # define MAX(A,B) ((A)>(B)?(A):(B))
  12785. #endif
  12786. /*
  12787. ** Swap two objects of type TYPE.
  12788. */
  12789. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  12790. /*
  12791. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  12792. ** not, there are still machines out there that use EBCDIC.)
  12793. */
  12794. #if 'A' == '\301'
  12795. # define SQLITE_EBCDIC 1
  12796. #else
  12797. # define SQLITE_ASCII 1
  12798. #endif
  12799. /*
  12800. ** Integers of known sizes. These typedefs might change for architectures
  12801. ** where the sizes very. Preprocessor macros are available so that the
  12802. ** types can be conveniently redefined at compile-type. Like this:
  12803. **
  12804. ** cc '-DUINTPTR_TYPE=long long int' ...
  12805. */
  12806. #ifndef UINT32_TYPE
  12807. # ifdef HAVE_UINT32_T
  12808. # define UINT32_TYPE uint32_t
  12809. # else
  12810. # define UINT32_TYPE unsigned int
  12811. # endif
  12812. #endif
  12813. #ifndef UINT16_TYPE
  12814. # ifdef HAVE_UINT16_T
  12815. # define UINT16_TYPE uint16_t
  12816. # else
  12817. # define UINT16_TYPE unsigned short int
  12818. # endif
  12819. #endif
  12820. #ifndef INT16_TYPE
  12821. # ifdef HAVE_INT16_T
  12822. # define INT16_TYPE int16_t
  12823. # else
  12824. # define INT16_TYPE short int
  12825. # endif
  12826. #endif
  12827. #ifndef UINT8_TYPE
  12828. # ifdef HAVE_UINT8_T
  12829. # define UINT8_TYPE uint8_t
  12830. # else
  12831. # define UINT8_TYPE unsigned char
  12832. # endif
  12833. #endif
  12834. #ifndef INT8_TYPE
  12835. # ifdef HAVE_INT8_T
  12836. # define INT8_TYPE int8_t
  12837. # else
  12838. # define INT8_TYPE signed char
  12839. # endif
  12840. #endif
  12841. #ifndef LONGDOUBLE_TYPE
  12842. # define LONGDOUBLE_TYPE long double
  12843. #endif
  12844. typedef sqlite_int64 i64; /* 8-byte signed integer */
  12845. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  12846. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  12847. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  12848. typedef INT16_TYPE i16; /* 2-byte signed integer */
  12849. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  12850. typedef INT8_TYPE i8; /* 1-byte signed integer */
  12851. /*
  12852. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  12853. ** that can be stored in a u32 without loss of data. The value
  12854. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  12855. ** have to specify the value in the less intuitive manner shown:
  12856. */
  12857. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  12858. /*
  12859. ** The datatype used to store estimates of the number of rows in a
  12860. ** table or index. This is an unsigned integer type. For 99.9% of
  12861. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  12862. ** can be used at compile-time if desired.
  12863. */
  12864. #ifdef SQLITE_64BIT_STATS
  12865. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  12866. #else
  12867. typedef u32 tRowcnt; /* 32-bit is the default */
  12868. #endif
  12869. /*
  12870. ** Estimated quantities used for query planning are stored as 16-bit
  12871. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  12872. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  12873. ** But the allowed values are "grainy". Not every value is representable.
  12874. ** For example, quantities 16 and 17 are both represented by a LogEst
  12875. ** of 40. However, since LogEst quantities are suppose to be estimates,
  12876. ** not exact values, this imprecision is not a problem.
  12877. **
  12878. ** "LogEst" is short for "Logarithmic Estimate".
  12879. **
  12880. ** Examples:
  12881. ** 1 -> 0 20 -> 43 10000 -> 132
  12882. ** 2 -> 10 25 -> 46 25000 -> 146
  12883. ** 3 -> 16 100 -> 66 1000000 -> 199
  12884. ** 4 -> 20 1000 -> 99 1048576 -> 200
  12885. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  12886. **
  12887. ** The LogEst can be negative to indicate fractional values.
  12888. ** Examples:
  12889. **
  12890. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  12891. */
  12892. typedef INT16_TYPE LogEst;
  12893. /*
  12894. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  12895. */
  12896. #ifndef SQLITE_PTRSIZE
  12897. # if defined(__SIZEOF_POINTER__)
  12898. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  12899. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  12900. defined(_M_ARM) || defined(__arm__) || defined(__x86)
  12901. # define SQLITE_PTRSIZE 4
  12902. # else
  12903. # define SQLITE_PTRSIZE 8
  12904. # endif
  12905. #endif
  12906. /* The uptr type is an unsigned integer large enough to hold a pointer
  12907. */
  12908. #if defined(HAVE_STDINT_H)
  12909. typedef uintptr_t uptr;
  12910. #elif SQLITE_PTRSIZE==4
  12911. typedef u32 uptr;
  12912. #else
  12913. typedef u64 uptr;
  12914. #endif
  12915. /*
  12916. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  12917. ** something between S (inclusive) and E (exclusive).
  12918. **
  12919. ** In other words, S is a buffer and E is a pointer to the first byte after
  12920. ** the end of buffer S. This macro returns true if P points to something
  12921. ** contained within the buffer S.
  12922. */
  12923. #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
  12924. /*
  12925. ** Macros to determine whether the machine is big or little endian,
  12926. ** and whether or not that determination is run-time or compile-time.
  12927. **
  12928. ** For best performance, an attempt is made to guess at the byte-order
  12929. ** using C-preprocessor macros. If that is unsuccessful, or if
  12930. ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
  12931. ** at run-time.
  12932. */
  12933. #ifndef SQLITE_BYTEORDER
  12934. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  12935. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  12936. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  12937. defined(__arm__)
  12938. # define SQLITE_BYTEORDER 1234
  12939. # elif defined(sparc) || defined(__ppc__)
  12940. # define SQLITE_BYTEORDER 4321
  12941. # else
  12942. # define SQLITE_BYTEORDER 0
  12943. # endif
  12944. #endif
  12945. #if SQLITE_BYTEORDER==4321
  12946. # define SQLITE_BIGENDIAN 1
  12947. # define SQLITE_LITTLEENDIAN 0
  12948. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  12949. #elif SQLITE_BYTEORDER==1234
  12950. # define SQLITE_BIGENDIAN 0
  12951. # define SQLITE_LITTLEENDIAN 1
  12952. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  12953. #else
  12954. # ifdef SQLITE_AMALGAMATION
  12955. const int sqlite3one = 1;
  12956. # else
  12957. extern const int sqlite3one;
  12958. # endif
  12959. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  12960. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  12961. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  12962. #endif
  12963. /*
  12964. ** Constants for the largest and smallest possible 64-bit signed integers.
  12965. ** These macros are designed to work correctly on both 32-bit and 64-bit
  12966. ** compilers.
  12967. */
  12968. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  12969. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  12970. /*
  12971. ** Round up a number to the next larger multiple of 8. This is used
  12972. ** to force 8-byte alignment on 64-bit architectures.
  12973. */
  12974. #define ROUND8(x) (((x)+7)&~7)
  12975. /*
  12976. ** Round down to the nearest multiple of 8
  12977. */
  12978. #define ROUNDDOWN8(x) ((x)&~7)
  12979. /*
  12980. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  12981. ** macro is used only within assert() to verify that the code gets
  12982. ** all alignment restrictions correct.
  12983. **
  12984. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  12985. ** underlying malloc() implementation might return us 4-byte aligned
  12986. ** pointers. In that case, only verify 4-byte alignment.
  12987. */
  12988. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  12989. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  12990. #else
  12991. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  12992. #endif
  12993. /*
  12994. ** Disable MMAP on platforms where it is known to not work
  12995. */
  12996. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  12997. # undef SQLITE_MAX_MMAP_SIZE
  12998. # define SQLITE_MAX_MMAP_SIZE 0
  12999. #endif
  13000. /*
  13001. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  13002. */
  13003. #ifdef __APPLE__
  13004. # include <TargetConditionals.h>
  13005. #endif
  13006. #ifndef SQLITE_MAX_MMAP_SIZE
  13007. # if defined(__linux__) \
  13008. || defined(_WIN32) \
  13009. || (defined(__APPLE__) && defined(__MACH__)) \
  13010. || defined(__sun) \
  13011. || defined(__FreeBSD__) \
  13012. || defined(__DragonFly__)
  13013. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  13014. # else
  13015. # define SQLITE_MAX_MMAP_SIZE 0
  13016. # endif
  13017. #endif
  13018. /*
  13019. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  13020. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  13021. ** not exceed the maximum mmap size.
  13022. */
  13023. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  13024. # define SQLITE_DEFAULT_MMAP_SIZE 0
  13025. #endif
  13026. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  13027. # undef SQLITE_DEFAULT_MMAP_SIZE
  13028. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  13029. #endif
  13030. /*
  13031. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  13032. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  13033. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  13034. */
  13035. #ifdef SQLITE_ENABLE_STAT4
  13036. # undef SQLITE_ENABLE_STAT3
  13037. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  13038. #elif SQLITE_ENABLE_STAT3
  13039. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  13040. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  13041. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  13042. #endif
  13043. /*
  13044. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  13045. ** the Select query generator tracing logic is turned on.
  13046. */
  13047. #if defined(SQLITE_ENABLE_SELECTTRACE)
  13048. # define SELECTTRACE_ENABLED 1
  13049. #else
  13050. # define SELECTTRACE_ENABLED 0
  13051. #endif
  13052. /*
  13053. ** An instance of the following structure is used to store the busy-handler
  13054. ** callback for a given sqlite handle.
  13055. **
  13056. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  13057. ** callback for the database handle. Each pager opened via the sqlite
  13058. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  13059. ** callback is currently invoked only from within pager.c.
  13060. */
  13061. typedef struct BusyHandler BusyHandler;
  13062. struct BusyHandler {
  13063. int (*xBusyHandler)(void *,int); /* The busy callback */
  13064. void *pBusyArg; /* First arg to busy callback */
  13065. int nBusy; /* Incremented with each busy call */
  13066. u8 bExtraFileArg; /* Include sqlite3_file as callback arg */
  13067. };
  13068. /*
  13069. ** Name of the master database table. The master database table
  13070. ** is a special table that holds the names and attributes of all
  13071. ** user tables and indices.
  13072. */
  13073. #define MASTER_NAME "sqlite_master"
  13074. #define TEMP_MASTER_NAME "sqlite_temp_master"
  13075. /*
  13076. ** The root-page of the master database table.
  13077. */
  13078. #define MASTER_ROOT 1
  13079. /*
  13080. ** The name of the schema table.
  13081. */
  13082. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  13083. /*
  13084. ** A convenience macro that returns the number of elements in
  13085. ** an array.
  13086. */
  13087. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  13088. /*
  13089. ** Determine if the argument is a power of two
  13090. */
  13091. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  13092. /*
  13093. ** The following value as a destructor means to use sqlite3DbFree().
  13094. ** The sqlite3DbFree() routine requires two parameters instead of the
  13095. ** one parameter that destructors normally want. So we have to introduce
  13096. ** this magic value that the code knows to handle differently. Any
  13097. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  13098. ** and SQLITE_TRANSIENT.
  13099. */
  13100. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  13101. /*
  13102. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  13103. ** not support Writable Static Data (WSD) such as global and static variables.
  13104. ** All variables must either be on the stack or dynamically allocated from
  13105. ** the heap. When WSD is unsupported, the variable declarations scattered
  13106. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  13107. ** macro is used for this purpose. And instead of referencing the variable
  13108. ** directly, we use its constant as a key to lookup the run-time allocated
  13109. ** buffer that holds real variable. The constant is also the initializer
  13110. ** for the run-time allocated buffer.
  13111. **
  13112. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  13113. ** macros become no-ops and have zero performance impact.
  13114. */
  13115. #ifdef SQLITE_OMIT_WSD
  13116. #define SQLITE_WSD const
  13117. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  13118. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  13119. SQLITE_API int sqlite3_wsd_init(int N, int J);
  13120. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  13121. #else
  13122. #define SQLITE_WSD
  13123. #define GLOBAL(t,v) v
  13124. #define sqlite3GlobalConfig sqlite3Config
  13125. #endif
  13126. /*
  13127. ** The following macros are used to suppress compiler warnings and to
  13128. ** make it clear to human readers when a function parameter is deliberately
  13129. ** left unused within the body of a function. This usually happens when
  13130. ** a function is called via a function pointer. For example the
  13131. ** implementation of an SQL aggregate step callback may not use the
  13132. ** parameter indicating the number of arguments passed to the aggregate,
  13133. ** if it knows that this is enforced elsewhere.
  13134. **
  13135. ** When a function parameter is not used at all within the body of a function,
  13136. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  13137. ** However, these macros may also be used to suppress warnings related to
  13138. ** parameters that may or may not be used depending on compilation options.
  13139. ** For example those parameters only used in assert() statements. In these
  13140. ** cases the parameters are named as per the usual conventions.
  13141. */
  13142. #define UNUSED_PARAMETER(x) (void)(x)
  13143. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  13144. /*
  13145. ** Forward references to structures
  13146. */
  13147. typedef struct AggInfo AggInfo;
  13148. typedef struct AuthContext AuthContext;
  13149. typedef struct AutoincInfo AutoincInfo;
  13150. typedef struct Bitvec Bitvec;
  13151. typedef struct CollSeq CollSeq;
  13152. typedef struct Column Column;
  13153. typedef struct Db Db;
  13154. typedef struct Schema Schema;
  13155. typedef struct Expr Expr;
  13156. typedef struct ExprList ExprList;
  13157. typedef struct FKey FKey;
  13158. typedef struct FuncDestructor FuncDestructor;
  13159. typedef struct FuncDef FuncDef;
  13160. typedef struct FuncDefHash FuncDefHash;
  13161. typedef struct IdList IdList;
  13162. typedef struct Index Index;
  13163. typedef struct IndexSample IndexSample;
  13164. typedef struct KeyClass KeyClass;
  13165. typedef struct KeyInfo KeyInfo;
  13166. typedef struct Lookaside Lookaside;
  13167. typedef struct LookasideSlot LookasideSlot;
  13168. typedef struct Module Module;
  13169. typedef struct NameContext NameContext;
  13170. typedef struct Parse Parse;
  13171. typedef struct PreUpdate PreUpdate;
  13172. typedef struct PrintfArguments PrintfArguments;
  13173. typedef struct RowSet RowSet;
  13174. typedef struct Savepoint Savepoint;
  13175. typedef struct Select Select;
  13176. typedef struct SQLiteThread SQLiteThread;
  13177. typedef struct SelectDest SelectDest;
  13178. typedef struct SrcList SrcList;
  13179. typedef struct StrAccum StrAccum;
  13180. typedef struct Table Table;
  13181. typedef struct TableLock TableLock;
  13182. typedef struct Token Token;
  13183. typedef struct TreeView TreeView;
  13184. typedef struct Trigger Trigger;
  13185. typedef struct TriggerPrg TriggerPrg;
  13186. typedef struct TriggerStep TriggerStep;
  13187. typedef struct UnpackedRecord UnpackedRecord;
  13188. typedef struct VTable VTable;
  13189. typedef struct VtabCtx VtabCtx;
  13190. typedef struct Walker Walker;
  13191. typedef struct WhereInfo WhereInfo;
  13192. typedef struct With With;
  13193. /* A VList object records a mapping between parameters/variables/wildcards
  13194. ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
  13195. ** variable number associated with that parameter. See the format description
  13196. ** on the sqlite3VListAdd() routine for more information. A VList is really
  13197. ** just an array of integers.
  13198. */
  13199. typedef int VList;
  13200. /*
  13201. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  13202. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  13203. ** pointer types (i.e. FuncDef) defined above.
  13204. */
  13205. /************** Include btree.h in the middle of sqliteInt.h *****************/
  13206. /************** Begin file btree.h *******************************************/
  13207. /*
  13208. ** 2001 September 15
  13209. **
  13210. ** The author disclaims copyright to this source code. In place of
  13211. ** a legal notice, here is a blessing:
  13212. **
  13213. ** May you do good and not evil.
  13214. ** May you find forgiveness for yourself and forgive others.
  13215. ** May you share freely, never taking more than you give.
  13216. **
  13217. *************************************************************************
  13218. ** This header file defines the interface that the sqlite B-Tree file
  13219. ** subsystem. See comments in the source code for a detailed description
  13220. ** of what each interface routine does.
  13221. */
  13222. #ifndef SQLITE_BTREE_H
  13223. #define SQLITE_BTREE_H
  13224. /* TODO: This definition is just included so other modules compile. It
  13225. ** needs to be revisited.
  13226. */
  13227. #define SQLITE_N_BTREE_META 16
  13228. /*
  13229. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  13230. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  13231. */
  13232. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  13233. #define SQLITE_DEFAULT_AUTOVACUUM 0
  13234. #endif
  13235. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  13236. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  13237. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  13238. /*
  13239. ** Forward declarations of structure
  13240. */
  13241. typedef struct Btree Btree;
  13242. typedef struct BtCursor BtCursor;
  13243. typedef struct BtShared BtShared;
  13244. typedef struct BtreePayload BtreePayload;
  13245. SQLITE_PRIVATE int sqlite3BtreeOpen(
  13246. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  13247. const char *zFilename, /* Name of database file to open */
  13248. sqlite3 *db, /* Associated database connection */
  13249. Btree **ppBtree, /* Return open Btree* here */
  13250. int flags, /* Flags */
  13251. int vfsFlags /* Flags passed through to VFS open */
  13252. );
  13253. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  13254. ** following values.
  13255. **
  13256. ** NOTE: These values must match the corresponding PAGER_ values in
  13257. ** pager.h.
  13258. */
  13259. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  13260. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  13261. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  13262. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  13263. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  13264. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  13265. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  13266. #if SQLITE_MAX_MMAP_SIZE>0
  13267. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  13268. #endif
  13269. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  13270. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  13271. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  13272. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  13273. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  13274. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  13275. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  13276. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  13277. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  13278. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  13279. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  13280. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  13281. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  13282. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  13283. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  13284. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  13285. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  13286. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  13287. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  13288. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  13289. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  13290. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  13291. #ifndef SQLITE_OMIT_SHARED_CACHE
  13292. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  13293. #endif
  13294. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  13295. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  13296. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  13297. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  13298. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  13299. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  13300. ** of the flags shown below.
  13301. **
  13302. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  13303. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  13304. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  13305. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  13306. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  13307. ** indices.)
  13308. */
  13309. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  13310. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  13311. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  13312. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  13313. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  13314. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  13315. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  13316. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  13317. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  13318. /*
  13319. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  13320. ** should be one of the following values. The integer values are assigned
  13321. ** to constants so that the offset of the corresponding field in an
  13322. ** SQLite database header may be found using the following formula:
  13323. **
  13324. ** offset = 36 + (idx * 4)
  13325. **
  13326. ** For example, the free-page-count field is located at byte offset 36 of
  13327. ** the database file header. The incr-vacuum-flag field is located at
  13328. ** byte offset 64 (== 36+4*7).
  13329. **
  13330. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  13331. ** It is a read-only number computed by the pager. But we merge it with
  13332. ** the header value access routines since its access pattern is the same.
  13333. ** Call it a "virtual meta value".
  13334. */
  13335. #define BTREE_FREE_PAGE_COUNT 0
  13336. #define BTREE_SCHEMA_VERSION 1
  13337. #define BTREE_FILE_FORMAT 2
  13338. #define BTREE_DEFAULT_CACHE_SIZE 3
  13339. #define BTREE_LARGEST_ROOT_PAGE 4
  13340. #define BTREE_TEXT_ENCODING 5
  13341. #define BTREE_USER_VERSION 6
  13342. #define BTREE_INCR_VACUUM 7
  13343. #define BTREE_APPLICATION_ID 8
  13344. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  13345. /*
  13346. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  13347. ** interface.
  13348. **
  13349. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  13350. **
  13351. ** The first argument is an Expr* (which is guaranteed to be constant for
  13352. ** the lifetime of the cursor) that defines constraints on which rows
  13353. ** might be fetched with this cursor. The Expr* tree may contain
  13354. ** TK_REGISTER nodes that refer to values stored in the array of registers
  13355. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  13356. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  13357. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  13358. ** column of the b-tree of the cursor. The Expr tree will not contain
  13359. ** any function calls nor subqueries nor references to b-trees other than
  13360. ** the cursor being hinted.
  13361. **
  13362. ** The design of the _RANGE hint is aid b-tree implementations that try
  13363. ** to prefetch content from remote machines - to provide those
  13364. ** implementations with limits on what needs to be prefetched and thereby
  13365. ** reduce network bandwidth.
  13366. **
  13367. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  13368. ** standard SQLite. The other hints are provided for extentions that use
  13369. ** the SQLite parser and code generator but substitute their own storage
  13370. ** engine.
  13371. */
  13372. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  13373. /*
  13374. ** Values that may be OR'd together to form the argument to the
  13375. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  13376. **
  13377. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  13378. ** to be filled with content that is already in sorted order.
  13379. **
  13380. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  13381. ** OP_SeekLE opcodes for a range search, but where the range of entries
  13382. ** selected will all have the same key. In other words, the cursor will
  13383. ** be used only for equality key searches.
  13384. **
  13385. */
  13386. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  13387. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  13388. /*
  13389. ** Flags passed as the third argument to sqlite3BtreeCursor().
  13390. **
  13391. ** For read-only cursors the wrFlag argument is always zero. For read-write
  13392. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
  13393. ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
  13394. ** only be used by SQLite for the following:
  13395. **
  13396. ** * to seek to and then delete specific entries, and/or
  13397. **
  13398. ** * to read values that will be used to create keys that other
  13399. ** BTREE_FORDELETE cursors will seek to and delete.
  13400. **
  13401. ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
  13402. ** by this, the native b-tree engine of SQLite, but it is available to
  13403. ** alternative storage engines that might be substituted in place of this
  13404. ** b-tree system. For alternative storage engines in which a delete of
  13405. ** the main table row automatically deletes corresponding index rows,
  13406. ** the FORDELETE flag hint allows those alternative storage engines to
  13407. ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
  13408. ** and DELETE operations as no-ops, and any READ operation against a
  13409. ** FORDELETE cursor may return a null row: 0x01 0x00.
  13410. */
  13411. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  13412. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  13413. SQLITE_PRIVATE int sqlite3BtreeCursor(
  13414. Btree*, /* BTree containing table to open */
  13415. int iTable, /* Index of root page */
  13416. int wrFlag, /* 1 for writing. 0 for read-only */
  13417. struct KeyInfo*, /* First argument to compare function */
  13418. BtCursor *pCursor /* Space to write cursor structure */
  13419. );
  13420. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
  13421. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  13422. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  13423. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  13424. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  13425. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  13426. #endif
  13427. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  13428. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  13429. BtCursor*,
  13430. UnpackedRecord *pUnKey,
  13431. i64 intKey,
  13432. int bias,
  13433. int *pRes
  13434. );
  13435. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  13436. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  13437. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
  13438. /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
  13439. #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
  13440. #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
  13441. #define BTREE_APPEND 0x08 /* Insert is likely an append */
  13442. /* An instance of the BtreePayload object describes the content of a single
  13443. ** entry in either an index or table btree.
  13444. **
  13445. ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
  13446. ** an arbitrary key and no data. These btrees have pKey,nKey set to their
  13447. ** key and pData,nData,nZero set to zero.
  13448. **
  13449. ** Table btrees (used for rowid tables) contain an integer rowid used as
  13450. ** the key and passed in the nKey field. The pKey field is zero.
  13451. ** pData,nData hold the content of the new entry. nZero extra zero bytes
  13452. ** are appended to the end of the content when constructing the entry.
  13453. **
  13454. ** This object is used to pass information into sqlite3BtreeInsert(). The
  13455. ** same information used to be passed as five separate parameters. But placing
  13456. ** the information into this object helps to keep the interface more
  13457. ** organized and understandable, and it also helps the resulting code to
  13458. ** run a little faster by using fewer registers for parameter passing.
  13459. */
  13460. struct BtreePayload {
  13461. const void *pKey; /* Key content for indexes. NULL for tables */
  13462. sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
  13463. const void *pData; /* Data for tables. NULL for indexes */
  13464. sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
  13465. u16 nMem; /* Number of aMem[] value. Might be zero */
  13466. int nData; /* Size of pData. 0 if none. */
  13467. int nZero; /* Extra zero data appended after pData,nData */
  13468. };
  13469. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
  13470. int flags, int seekResult);
  13471. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  13472. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  13473. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
  13474. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  13475. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
  13476. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
  13477. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  13478. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
  13479. #endif
  13480. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
  13481. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
  13482. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
  13483. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  13484. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  13485. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
  13486. #ifndef SQLITE_OMIT_INCRBLOB
  13487. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
  13488. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  13489. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  13490. #endif
  13491. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  13492. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  13493. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  13494. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  13495. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  13496. #ifndef NDEBUG
  13497. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  13498. #endif
  13499. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
  13500. #ifndef SQLITE_OMIT_BTREECOUNT
  13501. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  13502. #endif
  13503. #ifdef SQLITE_TEST
  13504. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  13505. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  13506. #endif
  13507. #ifndef SQLITE_OMIT_WAL
  13508. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  13509. #endif
  13510. /*
  13511. ** If we are not using shared cache, then there is no need to
  13512. ** use mutexes to access the BtShared structures. So make the
  13513. ** Enter and Leave procedures no-ops.
  13514. */
  13515. #ifndef SQLITE_OMIT_SHARED_CACHE
  13516. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  13517. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  13518. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  13519. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  13520. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
  13521. #else
  13522. # define sqlite3BtreeEnter(X)
  13523. # define sqlite3BtreeEnterAll(X)
  13524. # define sqlite3BtreeSharable(X) 0
  13525. # define sqlite3BtreeEnterCursor(X)
  13526. # define sqlite3BtreeConnectionCount(X) 1
  13527. #endif
  13528. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  13529. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  13530. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  13531. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  13532. #ifndef NDEBUG
  13533. /* These routines are used inside assert() statements only. */
  13534. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  13535. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  13536. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  13537. #endif
  13538. #else
  13539. # define sqlite3BtreeLeave(X)
  13540. # define sqlite3BtreeLeaveCursor(X)
  13541. # define sqlite3BtreeLeaveAll(X)
  13542. # define sqlite3BtreeHoldsMutex(X) 1
  13543. # define sqlite3BtreeHoldsAllMutexes(X) 1
  13544. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  13545. #endif
  13546. #endif /* SQLITE_BTREE_H */
  13547. /************** End of btree.h ***********************************************/
  13548. /************** Continuing where we left off in sqliteInt.h ******************/
  13549. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  13550. /************** Begin file vdbe.h ********************************************/
  13551. /*
  13552. ** 2001 September 15
  13553. **
  13554. ** The author disclaims copyright to this source code. In place of
  13555. ** a legal notice, here is a blessing:
  13556. **
  13557. ** May you do good and not evil.
  13558. ** May you find forgiveness for yourself and forgive others.
  13559. ** May you share freely, never taking more than you give.
  13560. **
  13561. *************************************************************************
  13562. ** Header file for the Virtual DataBase Engine (VDBE)
  13563. **
  13564. ** This header defines the interface to the virtual database engine
  13565. ** or VDBE. The VDBE implements an abstract machine that runs a
  13566. ** simple program to access and modify the underlying database.
  13567. */
  13568. #ifndef SQLITE_VDBE_H
  13569. #define SQLITE_VDBE_H
  13570. /* #include <stdio.h> */
  13571. /*
  13572. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  13573. ** in the source file sqliteVdbe.c are allowed to see the insides
  13574. ** of this structure.
  13575. */
  13576. typedef struct Vdbe Vdbe;
  13577. /*
  13578. ** The names of the following types declared in vdbeInt.h are required
  13579. ** for the VdbeOp definition.
  13580. */
  13581. typedef struct sqlite3_value Mem;
  13582. typedef struct SubProgram SubProgram;
  13583. /*
  13584. ** A single instruction of the virtual machine has an opcode
  13585. ** and as many as three operands. The instruction is recorded
  13586. ** as an instance of the following structure:
  13587. */
  13588. struct VdbeOp {
  13589. u8 opcode; /* What operation to perform */
  13590. signed char p4type; /* One of the P4_xxx constants for p4 */
  13591. u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
  13592. int p1; /* First operand */
  13593. int p2; /* Second parameter (often the jump destination) */
  13594. int p3; /* The third parameter */
  13595. union p4union { /* fourth parameter */
  13596. int i; /* Integer value if p4type==P4_INT32 */
  13597. void *p; /* Generic pointer */
  13598. char *z; /* Pointer to data for string (char array) types */
  13599. i64 *pI64; /* Used when p4type is P4_INT64 */
  13600. double *pReal; /* Used when p4type is P4_REAL */
  13601. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  13602. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  13603. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  13604. Mem *pMem; /* Used when p4type is P4_MEM */
  13605. VTable *pVtab; /* Used when p4type is P4_VTAB */
  13606. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  13607. int *ai; /* Used when p4type is P4_INTARRAY */
  13608. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  13609. Table *pTab; /* Used when p4type is P4_TABLE */
  13610. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  13611. Expr *pExpr; /* Used when p4type is P4_EXPR */
  13612. #endif
  13613. int (*xAdvance)(BtCursor *, int);
  13614. } p4;
  13615. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  13616. char *zComment; /* Comment to improve readability */
  13617. #endif
  13618. #ifdef VDBE_PROFILE
  13619. u32 cnt; /* Number of times this instruction was executed */
  13620. u64 cycles; /* Total time spent executing this instruction */
  13621. #endif
  13622. #ifdef SQLITE_VDBE_COVERAGE
  13623. int iSrcLine; /* Source-code line that generated this opcode */
  13624. #endif
  13625. };
  13626. typedef struct VdbeOp VdbeOp;
  13627. /*
  13628. ** A sub-routine used to implement a trigger program.
  13629. */
  13630. struct SubProgram {
  13631. VdbeOp *aOp; /* Array of opcodes for sub-program */
  13632. int nOp; /* Elements in aOp[] */
  13633. int nMem; /* Number of memory cells required */
  13634. int nCsr; /* Number of cursors required */
  13635. u8 *aOnce; /* Array of OP_Once flags */
  13636. void *token; /* id that may be used to recursive triggers */
  13637. SubProgram *pNext; /* Next sub-program already visited */
  13638. };
  13639. /*
  13640. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  13641. ** it takes up less space.
  13642. */
  13643. struct VdbeOpList {
  13644. u8 opcode; /* What operation to perform */
  13645. signed char p1; /* First operand */
  13646. signed char p2; /* Second parameter (often the jump destination) */
  13647. signed char p3; /* Third parameter */
  13648. };
  13649. typedef struct VdbeOpList VdbeOpList;
  13650. /*
  13651. ** Allowed values of VdbeOp.p4type
  13652. */
  13653. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  13654. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  13655. #define P4_STATIC (-1) /* Pointer to a static string */
  13656. #define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
  13657. #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
  13658. #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
  13659. #define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  13660. #define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
  13661. /* Above do not own any resources. Must free those below */
  13662. #define P4_FREE_IF_LE (-7)
  13663. #define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
  13664. #define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
  13665. #define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
  13666. #define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
  13667. #define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
  13668. #define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
  13669. #define P4_REAL (-13) /* P4 is a 64-bit floating point value */
  13670. #define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
  13671. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  13672. #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
  13673. #define P4_DYNBLOB (-17) /* Pointer to memory from sqliteMalloc() */
  13674. /* Error message codes for OP_Halt */
  13675. #define P5_ConstraintNotNull 1
  13676. #define P5_ConstraintUnique 2
  13677. #define P5_ConstraintCheck 3
  13678. #define P5_ConstraintFK 4
  13679. /*
  13680. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  13681. ** number of columns of data returned by the statement.
  13682. */
  13683. #define COLNAME_NAME 0
  13684. #define COLNAME_DECLTYPE 1
  13685. #define COLNAME_DATABASE 2
  13686. #define COLNAME_TABLE 3
  13687. #define COLNAME_COLUMN 4
  13688. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  13689. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  13690. #else
  13691. # ifdef SQLITE_OMIT_DECLTYPE
  13692. # define COLNAME_N 1 /* Store only the name */
  13693. # else
  13694. # define COLNAME_N 2 /* Store the name and decltype */
  13695. # endif
  13696. #endif
  13697. /*
  13698. ** The following macro converts a relative address in the p2 field
  13699. ** of a VdbeOp structure into a negative number so that
  13700. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  13701. ** the macro again restores the address.
  13702. */
  13703. #define ADDR(X) (-1-(X))
  13704. /*
  13705. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  13706. ** header file that defines a number for each opcode used by the VDBE.
  13707. */
  13708. /************** Include opcodes.h in the middle of vdbe.h ********************/
  13709. /************** Begin file opcodes.h *****************************************/
  13710. /* Automatically generated. Do not edit */
  13711. /* See the tool/mkopcodeh.tcl script for details */
  13712. #define OP_Savepoint 0
  13713. #define OP_AutoCommit 1
  13714. #define OP_Transaction 2
  13715. #define OP_SorterNext 3 /* jump */
  13716. #define OP_PrevIfOpen 4 /* jump */
  13717. #define OP_NextIfOpen 5 /* jump */
  13718. #define OP_Prev 6 /* jump */
  13719. #define OP_Next 7 /* jump */
  13720. #define OP_Checkpoint 8
  13721. #define OP_JournalMode 9
  13722. #define OP_Vacuum 10
  13723. #define OP_VFilter 11 /* jump, synopsis: iplan=r[P3] zplan='P4' */
  13724. #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
  13725. #define OP_Goto 13 /* jump */
  13726. #define OP_Gosub 14 /* jump */
  13727. #define OP_InitCoroutine 15 /* jump */
  13728. #define OP_Yield 16 /* jump */
  13729. #define OP_MustBeInt 17 /* jump */
  13730. #define OP_Jump 18 /* jump */
  13731. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  13732. #define OP_Once 20 /* jump */
  13733. #define OP_If 21 /* jump */
  13734. #define OP_IfNot 22 /* jump */
  13735. #define OP_IfNullRow 23 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
  13736. #define OP_SeekLT 24 /* jump, synopsis: key=r[P3@P4] */
  13737. #define OP_SeekLE 25 /* jump, synopsis: key=r[P3@P4] */
  13738. #define OP_SeekGE 26 /* jump, synopsis: key=r[P3@P4] */
  13739. #define OP_SeekGT 27 /* jump, synopsis: key=r[P3@P4] */
  13740. #define OP_NoConflict 28 /* jump, synopsis: key=r[P3@P4] */
  13741. #define OP_NotFound 29 /* jump, synopsis: key=r[P3@P4] */
  13742. #define OP_Found 30 /* jump, synopsis: key=r[P3@P4] */
  13743. #define OP_SeekRowid 31 /* jump, synopsis: intkey=r[P3] */
  13744. #define OP_NotExists 32 /* jump, synopsis: intkey=r[P3] */
  13745. #define OP_Last 33 /* jump */
  13746. #define OP_IfSmaller 34 /* jump */
  13747. #define OP_SorterSort 35 /* jump */
  13748. #define OP_Sort 36 /* jump */
  13749. #define OP_Rewind 37 /* jump */
  13750. #define OP_IdxLE 38 /* jump, synopsis: key=r[P3@P4] */
  13751. #define OP_IdxGT 39 /* jump, synopsis: key=r[P3@P4] */
  13752. #define OP_IdxLT 40 /* jump, synopsis: key=r[P3@P4] */
  13753. #define OP_IdxGE 41 /* jump, synopsis: key=r[P3@P4] */
  13754. #define OP_RowSetRead 42 /* jump, synopsis: r[P3]=rowset(P1) */
  13755. #define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  13756. #define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  13757. #define OP_RowSetTest 45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
  13758. #define OP_Program 46 /* jump */
  13759. #define OP_FkIfZero 47 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
  13760. #define OP_IfPos 48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  13761. #define OP_IfNotZero 49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
  13762. #define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  13763. #define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  13764. #define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
  13765. #define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
  13766. #define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
  13767. #define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
  13768. #define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
  13769. #define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
  13770. #define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */
  13771. #define OP_DecrJumpZero 59 /* jump, synopsis: if (--r[P1])==0 goto P2 */
  13772. #define OP_IncrVacuum 60 /* jump */
  13773. #define OP_VNext 61 /* jump */
  13774. #define OP_Init 62 /* jump, synopsis: Start at P2 */
  13775. #define OP_Return 63
  13776. #define OP_EndCoroutine 64
  13777. #define OP_HaltIfNull 65 /* synopsis: if r[P3]=null halt */
  13778. #define OP_Halt 66
  13779. #define OP_Integer 67 /* synopsis: r[P2]=P1 */
  13780. #define OP_Int64 68 /* synopsis: r[P2]=P4 */
  13781. #define OP_String 69 /* synopsis: r[P2]='P4' (len=P1) */
  13782. #define OP_Null 70 /* synopsis: r[P2..P3]=NULL */
  13783. #define OP_SoftNull 71 /* synopsis: r[P1]=NULL */
  13784. #define OP_Blob 72 /* synopsis: r[P2]=P4 (len=P1) */
  13785. #define OP_Variable 73 /* synopsis: r[P2]=parameter(P1,P4) */
  13786. #define OP_Move 74 /* synopsis: r[P2@P3]=r[P1@P3] */
  13787. #define OP_Copy 75 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  13788. #define OP_SCopy 76 /* synopsis: r[P2]=r[P1] */
  13789. #define OP_IntCopy 77 /* synopsis: r[P2]=r[P1] */
  13790. #define OP_ResultRow 78 /* synopsis: output=r[P1@P2] */
  13791. #define OP_CollSeq 79
  13792. #define OP_AddImm 80 /* synopsis: r[P1]=r[P1]+P2 */
  13793. #define OP_RealAffinity 81
  13794. #define OP_Cast 82 /* synopsis: affinity(r[P1]) */
  13795. #define OP_Permutation 83
  13796. #define OP_BitAnd 84 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  13797. #define OP_BitOr 85 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  13798. #define OP_ShiftLeft 86 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  13799. #define OP_ShiftRight 87 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  13800. #define OP_Add 88 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  13801. #define OP_Subtract 89 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  13802. #define OP_Multiply 90 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  13803. #define OP_Divide 91 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  13804. #define OP_Remainder 92 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  13805. #define OP_Concat 93 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  13806. #define OP_Compare 94 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  13807. #define OP_BitNot 95 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  13808. #define OP_IsTrue 96 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
  13809. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  13810. #define OP_Offset 98 /* synopsis: r[P3] = sqlite_offset(P1) */
  13811. #define OP_Column 99 /* synopsis: r[P3]=PX */
  13812. #define OP_Affinity 100 /* synopsis: affinity(r[P1@P2]) */
  13813. #define OP_MakeRecord 101 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  13814. #define OP_Count 102 /* synopsis: r[P2]=count() */
  13815. #define OP_ReadCookie 103
  13816. #define OP_SetCookie 104
  13817. #define OP_ReopenIdx 105 /* synopsis: root=P2 iDb=P3 */
  13818. #define OP_OpenRead 106 /* synopsis: root=P2 iDb=P3 */
  13819. #define OP_OpenWrite 107 /* synopsis: root=P2 iDb=P3 */
  13820. #define OP_OpenDup 108
  13821. #define OP_OpenAutoindex 109 /* synopsis: nColumn=P2 */
  13822. #define OP_OpenEphemeral 110 /* synopsis: nColumn=P2 */
  13823. #define OP_SorterOpen 111
  13824. #define OP_SequenceTest 112 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  13825. #define OP_OpenPseudo 113 /* synopsis: P3 columns in r[P2] */
  13826. #define OP_Close 114
  13827. #define OP_ColumnsUsed 115
  13828. #define OP_Sequence 116 /* synopsis: r[P2]=cursor[P1].ctr++ */
  13829. #define OP_NewRowid 117 /* synopsis: r[P2]=rowid */
  13830. #define OP_Insert 118 /* synopsis: intkey=r[P3] data=r[P2] */
  13831. #define OP_InsertInt 119 /* synopsis: intkey=P3 data=r[P2] */
  13832. #define OP_Delete 120
  13833. #define OP_ResetCount 121
  13834. #define OP_SorterCompare 122 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  13835. #define OP_SorterData 123 /* synopsis: r[P2]=data */
  13836. #define OP_RowData 124 /* synopsis: r[P2]=data */
  13837. #define OP_Rowid 125 /* synopsis: r[P2]=rowid */
  13838. #define OP_NullRow 126
  13839. #define OP_SeekEnd 127
  13840. #define OP_SorterInsert 128 /* synopsis: key=r[P2] */
  13841. #define OP_IdxInsert 129 /* synopsis: key=r[P2] */
  13842. #define OP_IdxDelete 130 /* synopsis: key=r[P2@P3] */
  13843. #define OP_DeferredSeek 131 /* synopsis: Move P3 to P1.rowid if needed */
  13844. #define OP_Real 132 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  13845. #define OP_IdxRowid 133 /* synopsis: r[P2]=rowid */
  13846. #define OP_Destroy 134
  13847. #define OP_Clear 135
  13848. #define OP_ResetSorter 136
  13849. #define OP_CreateBtree 137 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
  13850. #define OP_SqlExec 138
  13851. #define OP_ParseSchema 139
  13852. #define OP_LoadAnalysis 140
  13853. #define OP_DropTable 141
  13854. #define OP_DropIndex 142
  13855. #define OP_DropTrigger 143
  13856. #define OP_IntegrityCk 144
  13857. #define OP_RowSetAdd 145 /* synopsis: rowset(P1)=r[P2] */
  13858. #define OP_Param 146
  13859. #define OP_FkCounter 147 /* synopsis: fkctr[P1]+=P2 */
  13860. #define OP_MemMax 148 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  13861. #define OP_OffsetLimit 149 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
  13862. #define OP_AggStep0 150 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  13863. #define OP_AggStep 151 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  13864. #define OP_AggFinal 152 /* synopsis: accum=r[P1] N=P2 */
  13865. #define OP_Expire 153
  13866. #define OP_TableLock 154 /* synopsis: iDb=P1 root=P2 write=P3 */
  13867. #define OP_VBegin 155
  13868. #define OP_VCreate 156
  13869. #define OP_VDestroy 157
  13870. #define OP_VOpen 158
  13871. #define OP_VColumn 159 /* synopsis: r[P3]=vcolumn(P2) */
  13872. #define OP_VRename 160
  13873. #define OP_Pagecount 161
  13874. #define OP_MaxPgcnt 162
  13875. #define OP_PureFunc0 163
  13876. #define OP_Function0 164 /* synopsis: r[P3]=func(r[P2@P5]) */
  13877. #define OP_PureFunc 165
  13878. #define OP_Function 166 /* synopsis: r[P3]=func(r[P2@P5]) */
  13879. #define OP_Trace 167
  13880. #define OP_CursorHint 168
  13881. #define OP_Noop 169
  13882. #define OP_Explain 170
  13883. /* Properties such as "out2" or "jump" that are specified in
  13884. ** comments following the "case" for each opcode in the vdbe.c
  13885. ** are encoded into bitvectors as follows:
  13886. */
  13887. #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
  13888. #define OPFLG_IN1 0x02 /* in1: P1 is an input */
  13889. #define OPFLG_IN2 0x04 /* in2: P2 is an input */
  13890. #define OPFLG_IN3 0x08 /* in3: P3 is an input */
  13891. #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
  13892. #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
  13893. #define OPFLG_INITIALIZER {\
  13894. /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
  13895. /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
  13896. /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x01,\
  13897. /* 24 */ 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,\
  13898. /* 32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
  13899. /* 40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\
  13900. /* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
  13901. /* 56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x02,\
  13902. /* 64 */ 0x02, 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00,\
  13903. /* 72 */ 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
  13904. /* 80 */ 0x02, 0x02, 0x02, 0x00, 0x26, 0x26, 0x26, 0x26,\
  13905. /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00, 0x12,\
  13906. /* 96 */ 0x12, 0x10, 0x20, 0x00, 0x00, 0x00, 0x10, 0x10,\
  13907. /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  13908. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
  13909. /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,\
  13910. /* 128 */ 0x04, 0x04, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00,\
  13911. /* 136 */ 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  13912. /* 144 */ 0x00, 0x06, 0x10, 0x00, 0x04, 0x1a, 0x00, 0x00,\
  13913. /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  13914. /* 160 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
  13915. /* 168 */ 0x00, 0x00, 0x00,}
  13916. /* The sqlite3P2Values() routine is able to run faster if it knows
  13917. ** the value of the largest JUMP opcode. The smaller the maximum
  13918. ** JUMP opcode the better, so the mkopcodeh.tcl script that
  13919. ** generated this include file strives to group all JUMP opcodes
  13920. ** together near the beginning of the list.
  13921. */
  13922. #define SQLITE_MX_JUMP_OPCODE 62 /* Maximum JUMP opcode */
  13923. /************** End of opcodes.h *********************************************/
  13924. /************** Continuing where we left off in vdbe.h ***********************/
  13925. /*
  13926. ** Additional non-public SQLITE_PREPARE_* flags
  13927. */
  13928. #define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
  13929. #define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
  13930. /*
  13931. ** Prototypes for the VDBE interface. See comments on the implementation
  13932. ** for a description of what each of these routines does.
  13933. */
  13934. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  13935. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  13936. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  13937. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  13938. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  13939. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  13940. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  13941. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  13942. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  13943. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  13944. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  13945. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
  13946. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  13947. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
  13948. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
  13949. #else
  13950. # define sqlite3VdbeVerifyNoMallocRequired(A,B)
  13951. # define sqlite3VdbeVerifyNoResultRow(A)
  13952. #endif
  13953. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  13954. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  13955. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, u32 addr, u8);
  13956. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  13957. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  13958. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  13959. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
  13960. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  13961. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  13962. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  13963. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  13964. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
  13965. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  13966. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  13967. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  13968. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  13969. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  13970. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
  13971. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  13972. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  13973. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  13974. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  13975. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  13976. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  13977. #ifdef SQLITE_DEBUG
  13978. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  13979. #endif
  13980. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  13981. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  13982. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  13983. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  13984. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  13985. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  13986. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  13987. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
  13988. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
  13989. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  13990. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  13991. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  13992. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  13993. #ifndef SQLITE_OMIT_TRACE
  13994. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  13995. #endif
  13996. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  13997. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  13998. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  13999. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  14000. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
  14001. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  14002. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  14003. #ifndef SQLITE_OMIT_TRIGGER
  14004. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  14005. #endif
  14006. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
  14007. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  14008. ** each VDBE opcode.
  14009. **
  14010. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  14011. ** comments in VDBE programs that show key decision points in the code
  14012. ** generator.
  14013. */
  14014. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  14015. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  14016. # define VdbeComment(X) sqlite3VdbeComment X
  14017. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  14018. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  14019. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  14020. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  14021. # else
  14022. # define VdbeModuleComment(X)
  14023. # endif
  14024. #else
  14025. # define VdbeComment(X)
  14026. # define VdbeNoopComment(X)
  14027. # define VdbeModuleComment(X)
  14028. #endif
  14029. /*
  14030. ** The VdbeCoverage macros are used to set a coverage testing point
  14031. ** for VDBE branch instructions. The coverage testing points are line
  14032. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  14033. ** only works with an amalagmation build. That's ok since a VDBE branch
  14034. ** coverage build designed for testing the test suite only. No application
  14035. ** should ever ship with VDBE branch coverage measuring turned on.
  14036. **
  14037. ** VdbeCoverage(v) // Mark the previously coded instruction
  14038. ** // as a branch
  14039. **
  14040. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  14041. **
  14042. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  14043. **
  14044. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  14045. **
  14046. ** Every VDBE branch operation must be tagged with one of the macros above.
  14047. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  14048. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  14049. ** routine in vdbe.c, alerting the developer to the missed tag.
  14050. */
  14051. #ifdef SQLITE_VDBE_COVERAGE
  14052. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  14053. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  14054. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  14055. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  14056. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  14057. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  14058. #else
  14059. # define VdbeCoverage(v)
  14060. # define VdbeCoverageIf(v,x)
  14061. # define VdbeCoverageAlwaysTaken(v)
  14062. # define VdbeCoverageNeverTaken(v)
  14063. # define VDBE_OFFSET_LINENO(x) 0
  14064. #endif
  14065. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  14066. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  14067. #else
  14068. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  14069. #endif
  14070. #endif /* SQLITE_VDBE_H */
  14071. /************** End of vdbe.h ************************************************/
  14072. /************** Continuing where we left off in sqliteInt.h ******************/
  14073. /************** Include pager.h in the middle of sqliteInt.h *****************/
  14074. /************** Begin file pager.h *******************************************/
  14075. /*
  14076. ** 2001 September 15
  14077. **
  14078. ** The author disclaims copyright to this source code. In place of
  14079. ** a legal notice, here is a blessing:
  14080. **
  14081. ** May you do good and not evil.
  14082. ** May you find forgiveness for yourself and forgive others.
  14083. ** May you share freely, never taking more than you give.
  14084. **
  14085. *************************************************************************
  14086. ** This header file defines the interface that the sqlite page cache
  14087. ** subsystem. The page cache subsystem reads and writes a file a page
  14088. ** at a time and provides a journal for rollback.
  14089. */
  14090. #ifndef SQLITE_PAGER_H
  14091. #define SQLITE_PAGER_H
  14092. /*
  14093. ** Default maximum size for persistent journal files. A negative
  14094. ** value means no limit. This value may be overridden using the
  14095. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  14096. */
  14097. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  14098. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  14099. #endif
  14100. /*
  14101. ** The type used to represent a page number. The first page in a file
  14102. ** is called page 1. 0 is used to represent "not a page".
  14103. */
  14104. typedef u32 Pgno;
  14105. /*
  14106. ** Each open file is managed by a separate instance of the "Pager" structure.
  14107. */
  14108. typedef struct Pager Pager;
  14109. /*
  14110. ** Handle type for pages.
  14111. */
  14112. typedef struct PgHdr DbPage;
  14113. /*
  14114. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  14115. ** reserved for working around a windows/posix incompatibility). It is
  14116. ** used in the journal to signify that the remainder of the journal file
  14117. ** is devoted to storing a master journal name - there are no more pages to
  14118. ** roll back. See comments for function writeMasterJournal() in pager.c
  14119. ** for details.
  14120. */
  14121. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  14122. /*
  14123. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  14124. **
  14125. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  14126. */
  14127. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  14128. #define PAGER_MEMORY 0x0002 /* In-memory database */
  14129. /*
  14130. ** Valid values for the second argument to sqlite3PagerLockingMode().
  14131. */
  14132. #define PAGER_LOCKINGMODE_QUERY -1
  14133. #define PAGER_LOCKINGMODE_NORMAL 0
  14134. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  14135. /*
  14136. ** Numeric constants that encode the journalmode.
  14137. **
  14138. ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
  14139. ** are exposed in the API via the "PRAGMA journal_mode" command and
  14140. ** therefore cannot be changed without a compatibility break.
  14141. */
  14142. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  14143. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  14144. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  14145. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  14146. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  14147. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  14148. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  14149. /*
  14150. ** Flags that make up the mask passed to sqlite3PagerGet().
  14151. */
  14152. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  14153. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  14154. /*
  14155. ** Flags for sqlite3PagerSetFlags()
  14156. **
  14157. ** Value constraints (enforced via assert()):
  14158. ** PAGER_FULLFSYNC == SQLITE_FullFSync
  14159. ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
  14160. ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
  14161. */
  14162. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  14163. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  14164. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  14165. #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
  14166. #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
  14167. #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
  14168. #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
  14169. #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
  14170. #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
  14171. /*
  14172. ** The remainder of this file contains the declarations of the functions
  14173. ** that make up the Pager sub-system API. See source code comments for
  14174. ** a detailed description of each routine.
  14175. */
  14176. /* Open and close a Pager connection. */
  14177. SQLITE_PRIVATE int sqlite3PagerOpen(
  14178. sqlite3_vfs*,
  14179. Pager **ppPager,
  14180. const char*,
  14181. int,
  14182. int,
  14183. int,
  14184. void(*)(DbPage*)
  14185. );
  14186. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
  14187. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  14188. /* Functions used to configure a Pager object. */
  14189. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
  14190. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  14191. #ifdef SQLITE_HAS_CODEC
  14192. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
  14193. #endif
  14194. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  14195. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  14196. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  14197. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  14198. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  14199. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  14200. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  14201. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  14202. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  14203. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  14204. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  14205. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  14206. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  14207. /* Functions used to obtain and release page references. */
  14208. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  14209. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  14210. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  14211. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  14212. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  14213. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
  14214. /* Operations on page references. */
  14215. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  14216. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  14217. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  14218. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  14219. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  14220. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  14221. /* Functions used to manage pager transactions and savepoints. */
  14222. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  14223. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  14224. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  14225. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  14226. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  14227. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  14228. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  14229. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  14230. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  14231. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  14232. #ifndef SQLITE_OMIT_WAL
  14233. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
  14234. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  14235. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  14236. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  14237. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
  14238. # ifdef SQLITE_DIRECT_OVERFLOW_READ
  14239. SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno);
  14240. # endif
  14241. # ifdef SQLITE_ENABLE_SNAPSHOT
  14242. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
  14243. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
  14244. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
  14245. # endif
  14246. #else
  14247. # define sqlite3PagerUseWal(x,y) 0
  14248. #endif
  14249. #ifdef SQLITE_ENABLE_ZIPVFS
  14250. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  14251. #endif
  14252. /* Functions used to query pager state and configuration. */
  14253. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  14254. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  14255. #ifdef SQLITE_DEBUG
  14256. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  14257. #endif
  14258. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  14259. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  14260. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  14261. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  14262. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  14263. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  14264. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  14265. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  14266. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  14267. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
  14268. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  14269. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  14270. SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager);
  14271. #else
  14272. # define sqlite3PagerResetLockTimeout(X)
  14273. #endif
  14274. /* Functions used to truncate the database file. */
  14275. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  14276. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  14277. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  14278. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  14279. #endif
  14280. /* Functions to support testing and debugging. */
  14281. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  14282. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  14283. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  14284. #endif
  14285. #ifdef SQLITE_TEST
  14286. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  14287. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  14288. void disable_simulated_io_errors(void);
  14289. void enable_simulated_io_errors(void);
  14290. #else
  14291. # define disable_simulated_io_errors()
  14292. # define enable_simulated_io_errors()
  14293. #endif
  14294. #endif /* SQLITE_PAGER_H */
  14295. /************** End of pager.h ***********************************************/
  14296. /************** Continuing where we left off in sqliteInt.h ******************/
  14297. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  14298. /************** Begin file pcache.h ******************************************/
  14299. /*
  14300. ** 2008 August 05
  14301. **
  14302. ** The author disclaims copyright to this source code. In place of
  14303. ** a legal notice, here is a blessing:
  14304. **
  14305. ** May you do good and not evil.
  14306. ** May you find forgiveness for yourself and forgive others.
  14307. ** May you share freely, never taking more than you give.
  14308. **
  14309. *************************************************************************
  14310. ** This header file defines the interface that the sqlite page cache
  14311. ** subsystem.
  14312. */
  14313. #ifndef _PCACHE_H_
  14314. typedef struct PgHdr PgHdr;
  14315. typedef struct PCache PCache;
  14316. /*
  14317. ** Every page in the cache is controlled by an instance of the following
  14318. ** structure.
  14319. */
  14320. struct PgHdr {
  14321. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  14322. void *pData; /* Page data */
  14323. void *pExtra; /* Extra content */
  14324. PCache *pCache; /* PRIVATE: Cache that owns this page */
  14325. PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
  14326. Pager *pPager; /* The pager this page is part of */
  14327. Pgno pgno; /* Page number for this page */
  14328. #ifdef SQLITE_CHECK_PAGES
  14329. u32 pageHash; /* Hash of page content */
  14330. #endif
  14331. u16 flags; /* PGHDR flags defined below */
  14332. /**********************************************************************
  14333. ** Elements above, except pCache, are public. All that follow are
  14334. ** private to pcache.c and should not be accessed by other modules.
  14335. ** pCache is grouped with the public elements for efficiency.
  14336. */
  14337. i16 nRef; /* Number of users of this page */
  14338. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  14339. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  14340. /* NB: pDirtyNext and pDirtyPrev are undefined if the
  14341. ** PgHdr object is not dirty */
  14342. };
  14343. /* Bit values for PgHdr.flags */
  14344. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  14345. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  14346. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  14347. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  14348. ** writing this page to the database */
  14349. #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
  14350. #define PGHDR_MMAP 0x020 /* This is an mmap page object */
  14351. #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
  14352. /* Initialize and shutdown the page cache subsystem */
  14353. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  14354. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  14355. /* Page cache buffer management:
  14356. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  14357. */
  14358. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  14359. /* Create a new pager cache.
  14360. ** Under memory stress, invoke xStress to try to make pages clean.
  14361. ** Only clean and unpinned pages can be reclaimed.
  14362. */
  14363. SQLITE_PRIVATE int sqlite3PcacheOpen(
  14364. int szPage, /* Size of every page */
  14365. int szExtra, /* Extra space associated with each page */
  14366. int bPurgeable, /* True if pages are on backing store */
  14367. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  14368. void *pStress, /* Argument to xStress */
  14369. PCache *pToInit /* Preallocated space for the PCache */
  14370. );
  14371. /* Modify the page-size after the cache has been created. */
  14372. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  14373. /* Return the size in bytes of a PCache object. Used to preallocate
  14374. ** storage space.
  14375. */
  14376. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  14377. /* One release per successful fetch. Page is pinned until released.
  14378. ** Reference counted.
  14379. */
  14380. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  14381. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  14382. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  14383. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  14384. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  14385. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  14386. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  14387. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  14388. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
  14389. /* Change a page number. Used by incr-vacuum. */
  14390. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  14391. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  14392. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  14393. /* Get a list of all dirty pages in the cache, sorted by page number */
  14394. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  14395. /* Reset and close the cache object */
  14396. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  14397. /* Clear flags from pages of the page cache */
  14398. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  14399. /* Discard the contents of the cache */
  14400. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  14401. /* Return the total number of outstanding page references */
  14402. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  14403. /* Increment the reference count of an existing page */
  14404. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  14405. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  14406. /* Return the total number of pages stored in the cache */
  14407. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  14408. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  14409. /* Iterate through all dirty pages currently stored in the cache. This
  14410. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  14411. ** library is built.
  14412. */
  14413. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  14414. #endif
  14415. #if defined(SQLITE_DEBUG)
  14416. /* Check invariants on a PgHdr object */
  14417. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
  14418. #endif
  14419. /* Set and get the suggested cache-size for the specified pager-cache.
  14420. **
  14421. ** If no global maximum is configured, then the system attempts to limit
  14422. ** the total number of pages cached by purgeable pager-caches to the sum
  14423. ** of the suggested cache-sizes.
  14424. */
  14425. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  14426. #ifdef SQLITE_TEST
  14427. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  14428. #endif
  14429. /* Set or get the suggested spill-size for the specified pager-cache.
  14430. **
  14431. ** The spill-size is the minimum number of pages in cache before the cache
  14432. ** will attempt to spill dirty pages by calling xStress.
  14433. */
  14434. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  14435. /* Free up as much memory as possible from the page cache */
  14436. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  14437. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  14438. /* Try to return memory used by the pcache module to the main memory heap */
  14439. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  14440. #endif
  14441. #ifdef SQLITE_TEST
  14442. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  14443. #endif
  14444. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  14445. /* Return the header size */
  14446. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  14447. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  14448. /* Number of dirty pages as a percentage of the configured cache size */
  14449. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
  14450. #endif /* _PCACHE_H_ */
  14451. /************** End of pcache.h **********************************************/
  14452. /************** Continuing where we left off in sqliteInt.h ******************/
  14453. /************** Include os.h in the middle of sqliteInt.h ********************/
  14454. /************** Begin file os.h **********************************************/
  14455. /*
  14456. ** 2001 September 16
  14457. **
  14458. ** The author disclaims copyright to this source code. In place of
  14459. ** a legal notice, here is a blessing:
  14460. **
  14461. ** May you do good and not evil.
  14462. ** May you find forgiveness for yourself and forgive others.
  14463. ** May you share freely, never taking more than you give.
  14464. **
  14465. ******************************************************************************
  14466. **
  14467. ** This header file (together with is companion C source-code file
  14468. ** "os.c") attempt to abstract the underlying operating system so that
  14469. ** the SQLite library will work on both POSIX and windows systems.
  14470. **
  14471. ** This header file is #include-ed by sqliteInt.h and thus ends up
  14472. ** being included by every source file.
  14473. */
  14474. #ifndef _SQLITE_OS_H_
  14475. #define _SQLITE_OS_H_
  14476. /*
  14477. ** Attempt to automatically detect the operating system and setup the
  14478. ** necessary pre-processor macros for it.
  14479. */
  14480. /************** Include os_setup.h in the middle of os.h *********************/
  14481. /************** Begin file os_setup.h ****************************************/
  14482. /*
  14483. ** 2013 November 25
  14484. **
  14485. ** The author disclaims copyright to this source code. In place of
  14486. ** a legal notice, here is a blessing:
  14487. **
  14488. ** May you do good and not evil.
  14489. ** May you find forgiveness for yourself and forgive others.
  14490. ** May you share freely, never taking more than you give.
  14491. **
  14492. ******************************************************************************
  14493. **
  14494. ** This file contains pre-processor directives related to operating system
  14495. ** detection and/or setup.
  14496. */
  14497. #ifndef SQLITE_OS_SETUP_H
  14498. #define SQLITE_OS_SETUP_H
  14499. /*
  14500. ** Figure out if we are dealing with Unix, Windows, or some other operating
  14501. ** system.
  14502. **
  14503. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  14504. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  14505. ** the three will be 1. The other two will be 0.
  14506. */
  14507. #if defined(SQLITE_OS_OTHER)
  14508. # if SQLITE_OS_OTHER==1
  14509. # undef SQLITE_OS_UNIX
  14510. # define SQLITE_OS_UNIX 0
  14511. # undef SQLITE_OS_WIN
  14512. # define SQLITE_OS_WIN 0
  14513. # else
  14514. # undef SQLITE_OS_OTHER
  14515. # endif
  14516. #endif
  14517. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  14518. # define SQLITE_OS_OTHER 0
  14519. # ifndef SQLITE_OS_WIN
  14520. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  14521. defined(__MINGW32__) || defined(__BORLANDC__)
  14522. # define SQLITE_OS_WIN 1
  14523. # define SQLITE_OS_UNIX 0
  14524. # else
  14525. # define SQLITE_OS_WIN 0
  14526. # define SQLITE_OS_UNIX 1
  14527. # endif
  14528. # else
  14529. # define SQLITE_OS_UNIX 0
  14530. # endif
  14531. #else
  14532. # ifndef SQLITE_OS_WIN
  14533. # define SQLITE_OS_WIN 0
  14534. # endif
  14535. #endif
  14536. #endif /* SQLITE_OS_SETUP_H */
  14537. /************** End of os_setup.h ********************************************/
  14538. /************** Continuing where we left off in os.h *************************/
  14539. /* If the SET_FULLSYNC macro is not defined above, then make it
  14540. ** a no-op
  14541. */
  14542. #ifndef SET_FULLSYNC
  14543. # define SET_FULLSYNC(x,y)
  14544. #endif
  14545. /*
  14546. ** The default size of a disk sector
  14547. */
  14548. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  14549. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  14550. #endif
  14551. /*
  14552. ** Temporary files are named starting with this prefix followed by 16 random
  14553. ** alphanumeric characters, and no file extension. They are stored in the
  14554. ** OS's standard temporary file directory, and are deleted prior to exit.
  14555. ** If sqlite is being embedded in another program, you may wish to change the
  14556. ** prefix to reflect your program's name, so that if your program exits
  14557. ** prematurely, old temporary files can be easily identified. This can be done
  14558. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  14559. **
  14560. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  14561. ** Mcafee started using SQLite in their anti-virus product and it
  14562. ** started putting files with the "sqlite" name in the c:/temp folder.
  14563. ** This annoyed many windows users. Those users would then do a
  14564. ** Google search for "sqlite", find the telephone numbers of the
  14565. ** developers and call to wake them up at night and complain.
  14566. ** For this reason, the default name prefix is changed to be "sqlite"
  14567. ** spelled backwards. So the temp files are still identified, but
  14568. ** anybody smart enough to figure out the code is also likely smart
  14569. ** enough to know that calling the developer will not help get rid
  14570. ** of the file.
  14571. */
  14572. #ifndef SQLITE_TEMP_FILE_PREFIX
  14573. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  14574. #endif
  14575. /*
  14576. ** The following values may be passed as the second argument to
  14577. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  14578. **
  14579. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  14580. ** RESERVED: A single process may hold a RESERVED lock on a file at
  14581. ** any time. Other processes may hold and obtain new SHARED locks.
  14582. ** PENDING: A single process may hold a PENDING lock on a file at
  14583. ** any one time. Existing SHARED locks may persist, but no new
  14584. ** SHARED locks may be obtained by other processes.
  14585. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  14586. **
  14587. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  14588. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  14589. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  14590. ** sqlite3OsLock().
  14591. */
  14592. #define NO_LOCK 0
  14593. #define SHARED_LOCK 1
  14594. #define RESERVED_LOCK 2
  14595. #define PENDING_LOCK 3
  14596. #define EXCLUSIVE_LOCK 4
  14597. /*
  14598. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  14599. **
  14600. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  14601. ** those functions are not available. So we use only LockFile() and
  14602. ** UnlockFile().
  14603. **
  14604. ** LockFile() prevents not just writing but also reading by other processes.
  14605. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  14606. ** byte out of a specific range of bytes. The lock byte is obtained at
  14607. ** random so two separate readers can probably access the file at the
  14608. ** same time, unless they are unlucky and choose the same lock byte.
  14609. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  14610. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  14611. ** a single byte of the file that is designated as the reserved lock byte.
  14612. ** A PENDING_LOCK is obtained by locking a designated byte different from
  14613. ** the RESERVED_LOCK byte.
  14614. **
  14615. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  14616. ** which means we can use reader/writer locks. When reader/writer locks
  14617. ** are used, the lock is placed on the same range of bytes that is used
  14618. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  14619. ** will support two or more Win95 readers or two or more WinNT readers.
  14620. ** But a single Win95 reader will lock out all WinNT readers and a single
  14621. ** WinNT reader will lock out all other Win95 readers.
  14622. **
  14623. ** The following #defines specify the range of bytes used for locking.
  14624. ** SHARED_SIZE is the number of bytes available in the pool from which
  14625. ** a random byte is selected for a shared lock. The pool of bytes for
  14626. ** shared locks begins at SHARED_FIRST.
  14627. **
  14628. ** The same locking strategy and
  14629. ** byte ranges are used for Unix. This leaves open the possibility of having
  14630. ** clients on win95, winNT, and unix all talking to the same shared file
  14631. ** and all locking correctly. To do so would require that samba (or whatever
  14632. ** tool is being used for file sharing) implements locks correctly between
  14633. ** windows and unix. I'm guessing that isn't likely to happen, but by
  14634. ** using the same locking range we are at least open to the possibility.
  14635. **
  14636. ** Locking in windows is manditory. For this reason, we cannot store
  14637. ** actual data in the bytes used for locking. The pager never allocates
  14638. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  14639. ** that all locks will fit on a single page even at the minimum page size.
  14640. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  14641. ** is set high so that we don't have to allocate an unused page except
  14642. ** for very large databases. But one should test the page skipping logic
  14643. ** by setting PENDING_BYTE low and running the entire regression suite.
  14644. **
  14645. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  14646. ** file format. Depending on how it is changed, you might not notice
  14647. ** the incompatibility right away, even running a full regression test.
  14648. ** The default location of PENDING_BYTE is the first byte past the
  14649. ** 1GB boundary.
  14650. **
  14651. */
  14652. #ifdef SQLITE_OMIT_WSD
  14653. # define PENDING_BYTE (0x40000000)
  14654. #else
  14655. # define PENDING_BYTE sqlite3PendingByte
  14656. #endif
  14657. #define RESERVED_BYTE (PENDING_BYTE+1)
  14658. #define SHARED_FIRST (PENDING_BYTE+2)
  14659. #define SHARED_SIZE 510
  14660. /*
  14661. ** Wrapper around OS specific sqlite3_os_init() function.
  14662. */
  14663. SQLITE_PRIVATE int sqlite3OsInit(void);
  14664. /*
  14665. ** Functions for accessing sqlite3_file methods
  14666. */
  14667. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
  14668. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  14669. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  14670. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  14671. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  14672. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  14673. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  14674. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  14675. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  14676. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  14677. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  14678. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  14679. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  14680. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  14681. #ifndef SQLITE_OMIT_WAL
  14682. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  14683. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  14684. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  14685. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  14686. #endif /* SQLITE_OMIT_WAL */
  14687. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  14688. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  14689. /*
  14690. ** Functions for accessing sqlite3_vfs methods
  14691. */
  14692. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  14693. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  14694. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  14695. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  14696. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14697. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  14698. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  14699. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  14700. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  14701. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  14702. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  14703. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  14704. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
  14705. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  14706. /*
  14707. ** Convenience functions for opening and closing files using
  14708. ** sqlite3_malloc() to obtain space for the file-handle structure.
  14709. */
  14710. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  14711. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
  14712. #endif /* _SQLITE_OS_H_ */
  14713. /************** End of os.h **************************************************/
  14714. /************** Continuing where we left off in sqliteInt.h ******************/
  14715. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  14716. /************** Begin file mutex.h *******************************************/
  14717. /*
  14718. ** 2007 August 28
  14719. **
  14720. ** The author disclaims copyright to this source code. In place of
  14721. ** a legal notice, here is a blessing:
  14722. **
  14723. ** May you do good and not evil.
  14724. ** May you find forgiveness for yourself and forgive others.
  14725. ** May you share freely, never taking more than you give.
  14726. **
  14727. *************************************************************************
  14728. **
  14729. ** This file contains the common header for all mutex implementations.
  14730. ** The sqliteInt.h header #includes this file so that it is available
  14731. ** to all source files. We break it out in an effort to keep the code
  14732. ** better organized.
  14733. **
  14734. ** NOTE: source files should *not* #include this header file directly.
  14735. ** Source files should #include the sqliteInt.h file and let that file
  14736. ** include this one indirectly.
  14737. */
  14738. /*
  14739. ** Figure out what version of the code to use. The choices are
  14740. **
  14741. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  14742. ** mutexes implementation cannot be overridden
  14743. ** at start-time.
  14744. **
  14745. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  14746. ** mutual exclusion is provided. But this
  14747. ** implementation can be overridden at
  14748. ** start-time.
  14749. **
  14750. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  14751. **
  14752. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  14753. */
  14754. #if !SQLITE_THREADSAFE
  14755. # define SQLITE_MUTEX_OMIT
  14756. #endif
  14757. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  14758. # if SQLITE_OS_UNIX
  14759. # define SQLITE_MUTEX_PTHREADS
  14760. # elif SQLITE_OS_WIN
  14761. # define SQLITE_MUTEX_W32
  14762. # else
  14763. # define SQLITE_MUTEX_NOOP
  14764. # endif
  14765. #endif
  14766. #ifdef SQLITE_MUTEX_OMIT
  14767. /*
  14768. ** If this is a no-op implementation, implement everything as macros.
  14769. */
  14770. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  14771. #define sqlite3_mutex_free(X)
  14772. #define sqlite3_mutex_enter(X)
  14773. #define sqlite3_mutex_try(X) SQLITE_OK
  14774. #define sqlite3_mutex_leave(X)
  14775. #define sqlite3_mutex_held(X) ((void)(X),1)
  14776. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  14777. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  14778. #define sqlite3MutexInit() SQLITE_OK
  14779. #define sqlite3MutexEnd()
  14780. #define MUTEX_LOGIC(X)
  14781. #else
  14782. #define MUTEX_LOGIC(X) X
  14783. #endif /* defined(SQLITE_MUTEX_OMIT) */
  14784. /************** End of mutex.h ***********************************************/
  14785. /************** Continuing where we left off in sqliteInt.h ******************/
  14786. /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
  14787. ** synchronous setting to EXTRA. It is no longer supported.
  14788. */
  14789. #ifdef SQLITE_EXTRA_DURABLE
  14790. # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
  14791. # define SQLITE_DEFAULT_SYNCHRONOUS 3
  14792. #endif
  14793. /*
  14794. ** Default synchronous levels.
  14795. **
  14796. ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
  14797. ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
  14798. **
  14799. ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
  14800. ** OFF 1 0
  14801. ** NORMAL 2 1
  14802. ** FULL 3 2
  14803. ** EXTRA 4 3
  14804. **
  14805. ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
  14806. ** In other words, the zero-based numbers are used for all external interfaces
  14807. ** and the one-based values are used internally.
  14808. */
  14809. #ifndef SQLITE_DEFAULT_SYNCHRONOUS
  14810. # define SQLITE_DEFAULT_SYNCHRONOUS 2
  14811. #endif
  14812. #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  14813. # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
  14814. #endif
  14815. /*
  14816. ** Each database file to be accessed by the system is an instance
  14817. ** of the following structure. There are normally two of these structures
  14818. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  14819. ** aDb[1] is the database file used to hold temporary tables. Additional
  14820. ** databases may be attached.
  14821. */
  14822. struct Db {
  14823. char *zDbSName; /* Name of this database. (schema name, not filename) */
  14824. Btree *pBt; /* The B*Tree structure for this database file */
  14825. u8 safety_level; /* How aggressive at syncing data to disk */
  14826. u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
  14827. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  14828. };
  14829. /*
  14830. ** An instance of the following structure stores a database schema.
  14831. **
  14832. ** Most Schema objects are associated with a Btree. The exception is
  14833. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  14834. ** In shared cache mode, a single Schema object can be shared by multiple
  14835. ** Btrees that refer to the same underlying BtShared object.
  14836. **
  14837. ** Schema objects are automatically deallocated when the last Btree that
  14838. ** references them is destroyed. The TEMP Schema is manually freed by
  14839. ** sqlite3_close().
  14840. *
  14841. ** A thread must be holding a mutex on the corresponding Btree in order
  14842. ** to access Schema content. This implies that the thread must also be
  14843. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  14844. ** For a TEMP Schema, only the connection mutex is required.
  14845. */
  14846. struct Schema {
  14847. int schema_cookie; /* Database schema version number for this file */
  14848. int iGeneration; /* Generation counter. Incremented with each change */
  14849. Hash tblHash; /* All tables indexed by name */
  14850. Hash idxHash; /* All (named) indices indexed by name */
  14851. Hash trigHash; /* All triggers indexed by name */
  14852. Hash fkeyHash; /* All foreign keys by referenced table name */
  14853. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  14854. u8 file_format; /* Schema format version for this file */
  14855. u8 enc; /* Text encoding used by this database */
  14856. u16 schemaFlags; /* Flags associated with this schema */
  14857. int cache_size; /* Number of pages to use in the cache */
  14858. };
  14859. /*
  14860. ** These macros can be used to test, set, or clear bits in the
  14861. ** Db.pSchema->flags field.
  14862. */
  14863. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  14864. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  14865. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  14866. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  14867. /*
  14868. ** Allowed values for the DB.pSchema->flags field.
  14869. **
  14870. ** The DB_SchemaLoaded flag is set after the database schema has been
  14871. ** read into internal hash tables.
  14872. **
  14873. ** DB_UnresetViews means that one or more views have column names that
  14874. ** have been filled out. If the schema changes, these column names might
  14875. ** changes and so the view will need to be reset.
  14876. */
  14877. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  14878. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  14879. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  14880. #define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
  14881. /*
  14882. ** The number of different kinds of things that can be limited
  14883. ** using the sqlite3_limit() interface.
  14884. */
  14885. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  14886. /*
  14887. ** Lookaside malloc is a set of fixed-size buffers that can be used
  14888. ** to satisfy small transient memory allocation requests for objects
  14889. ** associated with a particular database connection. The use of
  14890. ** lookaside malloc provides a significant performance enhancement
  14891. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  14892. ** SQL statements.
  14893. **
  14894. ** The Lookaside structure holds configuration information about the
  14895. ** lookaside malloc subsystem. Each available memory allocation in
  14896. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  14897. ** objects.
  14898. **
  14899. ** Lookaside allocations are only allowed for objects that are associated
  14900. ** with a particular database connection. Hence, schema information cannot
  14901. ** be stored in lookaside because in shared cache mode the schema information
  14902. ** is shared by multiple database connections. Therefore, while parsing
  14903. ** schema information, the Lookaside.bEnabled flag is cleared so that
  14904. ** lookaside allocations are not used to construct the schema objects.
  14905. */
  14906. struct Lookaside {
  14907. u32 bDisable; /* Only operate the lookaside when zero */
  14908. u16 sz; /* Size of each buffer in bytes */
  14909. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  14910. u32 nSlot; /* Number of lookaside slots allocated */
  14911. u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  14912. LookasideSlot *pInit; /* List of buffers not previously used */
  14913. LookasideSlot *pFree; /* List of available buffers */
  14914. void *pStart; /* First byte of available memory space */
  14915. void *pEnd; /* First byte past end of available space */
  14916. };
  14917. struct LookasideSlot {
  14918. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  14919. };
  14920. /*
  14921. ** A hash table for built-in function definitions. (Application-defined
  14922. ** functions use a regular table table from hash.h.)
  14923. **
  14924. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  14925. ** Collisions are on the FuncDef.u.pHash chain.
  14926. */
  14927. #define SQLITE_FUNC_HASH_SZ 23
  14928. struct FuncDefHash {
  14929. FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
  14930. };
  14931. #ifdef SQLITE_USER_AUTHENTICATION
  14932. /*
  14933. ** Information held in the "sqlite3" database connection object and used
  14934. ** to manage user authentication.
  14935. */
  14936. typedef struct sqlite3_userauth sqlite3_userauth;
  14937. struct sqlite3_userauth {
  14938. u8 authLevel; /* Current authentication level */
  14939. int nAuthPW; /* Size of the zAuthPW in bytes */
  14940. char *zAuthPW; /* Password used to authenticate */
  14941. char *zAuthUser; /* User name used to authenticate */
  14942. };
  14943. /* Allowed values for sqlite3_userauth.authLevel */
  14944. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  14945. #define UAUTH_Fail 1 /* User authentication failed */
  14946. #define UAUTH_User 2 /* Authenticated as a normal user */
  14947. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  14948. /* Functions used only by user authorization logic */
  14949. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  14950. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  14951. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  14952. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  14953. #endif /* SQLITE_USER_AUTHENTICATION */
  14954. /*
  14955. ** typedef for the authorization callback function.
  14956. */
  14957. #ifdef SQLITE_USER_AUTHENTICATION
  14958. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  14959. const char*, const char*);
  14960. #else
  14961. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  14962. const char*);
  14963. #endif
  14964. #ifndef SQLITE_OMIT_DEPRECATED
  14965. /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
  14966. ** in the style of sqlite3_trace()
  14967. */
  14968. #define SQLITE_TRACE_LEGACY 0x80
  14969. #else
  14970. #define SQLITE_TRACE_LEGACY 0
  14971. #endif /* SQLITE_OMIT_DEPRECATED */
  14972. /*
  14973. ** Each database connection is an instance of the following structure.
  14974. */
  14975. struct sqlite3 {
  14976. sqlite3_vfs *pVfs; /* OS Interface */
  14977. struct Vdbe *pVdbe; /* List of active virtual machines */
  14978. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  14979. sqlite3_mutex *mutex; /* Connection mutex */
  14980. Db *aDb; /* All backends */
  14981. int nDb; /* Number of backends currently in use */
  14982. u32 mDbFlags; /* flags recording internal state */
  14983. u32 flags; /* flags settable by pragmas. See below */
  14984. i64 lastRowid; /* ROWID of most recent insert (see above) */
  14985. i64 szMmap; /* Default mmap_size setting */
  14986. u32 nSchemaLock; /* Do not reset the schema when non-zero */
  14987. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  14988. int errCode; /* Most recent error code (SQLITE_*) */
  14989. int errMask; /* & result codes with this before returning */
  14990. int iSysErrno; /* Errno value from last system error */
  14991. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  14992. u8 enc; /* Text encoding */
  14993. u8 autoCommit; /* The auto-commit flag. */
  14994. u8 temp_store; /* 1: file 2: memory 0: default */
  14995. u8 mallocFailed; /* True if we have seen a malloc failure */
  14996. u8 bBenignMalloc; /* Do not require OOMs if true */
  14997. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  14998. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  14999. u8 suppressErr; /* Do not issue error messages if true */
  15000. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  15001. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  15002. u8 mTrace; /* zero or more SQLITE_TRACE flags */
  15003. u8 skipBtreeMutex; /* True if no shared-cache backends */
  15004. u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
  15005. int nextPagesize; /* Pagesize after VACUUM if >0 */
  15006. u32 magic; /* Magic number for detect library misuse */
  15007. int nChange; /* Value returned by sqlite3_changes() */
  15008. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  15009. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  15010. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  15011. struct sqlite3InitInfo { /* Information used during initialization */
  15012. int newTnum; /* Rootpage of table being initialized */
  15013. u8 iDb; /* Which db file is being initialized */
  15014. u8 busy; /* TRUE if currently initializing */
  15015. unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
  15016. unsigned imposterTable : 1; /* Building an imposter table */
  15017. unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
  15018. } init;
  15019. int nVdbeActive; /* Number of VDBEs currently running */
  15020. int nVdbeRead; /* Number of active VDBEs that read or write */
  15021. int nVdbeWrite; /* Number of active VDBEs that read and write */
  15022. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  15023. int nVDestroy; /* Number of active OP_VDestroy operations */
  15024. int nExtension; /* Number of loaded extensions */
  15025. void **aExtension; /* Array of shared library handles */
  15026. int (*xTrace)(u32,void*,void*,void*); /* Trace function */
  15027. void *pTraceArg; /* Argument to the trace function */
  15028. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  15029. void *pProfileArg; /* Argument to profile function */
  15030. void *pCommitArg; /* Argument to xCommitCallback() */
  15031. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  15032. void *pRollbackArg; /* Argument to xRollbackCallback() */
  15033. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  15034. void *pUpdateArg;
  15035. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  15036. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  15037. void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
  15038. void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
  15039. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
  15040. );
  15041. PreUpdate *pPreUpdate; /* Context for active pre-update callback */
  15042. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  15043. #ifndef SQLITE_OMIT_WAL
  15044. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  15045. void *pWalArg;
  15046. #endif
  15047. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  15048. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  15049. void *pCollNeededArg;
  15050. sqlite3_value *pErr; /* Most recent error message */
  15051. union {
  15052. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  15053. double notUsed1; /* Spacer */
  15054. } u1;
  15055. Lookaside lookaside; /* Lookaside malloc configuration */
  15056. #ifndef SQLITE_OMIT_AUTHORIZATION
  15057. sqlite3_xauth xAuth; /* Access authorization function */
  15058. void *pAuthArg; /* 1st argument to the access auth function */
  15059. #endif
  15060. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  15061. int (*xProgress)(void *); /* The progress callback */
  15062. void *pProgressArg; /* Argument to the progress callback */
  15063. unsigned nProgressOps; /* Number of opcodes for progress callback */
  15064. #endif
  15065. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15066. int nVTrans; /* Allocated size of aVTrans */
  15067. Hash aModule; /* populated by sqlite3_create_module() */
  15068. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  15069. VTable **aVTrans; /* Virtual tables with open transactions */
  15070. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  15071. #endif
  15072. Hash aFunc; /* Hash table of connection functions */
  15073. Hash aCollSeq; /* All collating sequences */
  15074. BusyHandler busyHandler; /* Busy callback */
  15075. Db aDbStatic[2]; /* Static space for the 2 default backends */
  15076. Savepoint *pSavepoint; /* List of active savepoints */
  15077. int busyTimeout; /* Busy handler timeout, in msec */
  15078. int nSavepoint; /* Number of non-transaction savepoints */
  15079. int nStatement; /* Number of nested statement-transactions */
  15080. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  15081. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  15082. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  15083. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  15084. /* The following variables are all protected by the STATIC_MASTER
  15085. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  15086. **
  15087. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  15088. ** unlock so that it can proceed.
  15089. **
  15090. ** When X.pBlockingConnection==Y, that means that something that X tried
  15091. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  15092. ** held by Y.
  15093. */
  15094. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  15095. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  15096. void *pUnlockArg; /* Argument to xUnlockNotify */
  15097. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  15098. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  15099. #endif
  15100. #ifdef SQLITE_USER_AUTHENTICATION
  15101. sqlite3_userauth auth; /* User authentication information */
  15102. #endif
  15103. };
  15104. /*
  15105. ** A macro to discover the encoding of a database.
  15106. */
  15107. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  15108. #define ENC(db) ((db)->enc)
  15109. /*
  15110. ** Possible values for the sqlite3.flags.
  15111. **
  15112. ** Value constraints (enforced via assert()):
  15113. ** SQLITE_FullFSync == PAGER_FULLFSYNC
  15114. ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
  15115. ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
  15116. */
  15117. #define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */
  15118. #define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
  15119. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  15120. #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
  15121. #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
  15122. #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
  15123. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  15124. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  15125. /* DELETE, or UPDATE and return */
  15126. /* the count using a callback. */
  15127. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  15128. /* result set is empty */
  15129. #define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
  15130. #define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
  15131. #define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
  15132. #define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
  15133. #define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
  15134. #define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
  15135. #define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
  15136. #define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
  15137. #define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
  15138. #define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
  15139. #define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
  15140. #define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
  15141. #define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
  15142. #define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
  15143. #define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/
  15144. #define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
  15145. /* Flags used only if debugging */
  15146. #ifdef SQLITE_DEBUG
  15147. #define SQLITE_SqlTrace 0x08000000 /* Debug print SQL as it executes */
  15148. #define SQLITE_VdbeListing 0x10000000 /* Debug listings of VDBE programs */
  15149. #define SQLITE_VdbeTrace 0x20000000 /* True to trace VDBE execution */
  15150. #define SQLITE_VdbeAddopTrace 0x40000000 /* Trace sqlite3VdbeAddOp() calls */
  15151. #define SQLITE_VdbeEQP 0x80000000 /* Debug EXPLAIN QUERY PLAN */
  15152. #endif
  15153. /*
  15154. ** Allowed values for sqlite3.mDbFlags
  15155. */
  15156. #define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
  15157. #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
  15158. #define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
  15159. /*
  15160. ** Bits of the sqlite3.dbOptFlags field that are used by the
  15161. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  15162. ** selectively disable various optimizations.
  15163. */
  15164. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  15165. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  15166. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  15167. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  15168. #define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */
  15169. #define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */
  15170. #define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */
  15171. #define SQLITE_Transitive 0x0080 /* Transitive constraints */
  15172. #define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */
  15173. #define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */
  15174. #define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */
  15175. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  15176. /* TH3 expects the Stat34 ^^^^^^ value to be 0x0800. Don't change it */
  15177. #define SQLITE_PushDown 0x1000 /* The push-down optimization */
  15178. #define SQLITE_SimplifyJoin 0x2000 /* Convert LEFT JOIN to JOIN */
  15179. #define SQLITE_AllOpts 0xffff /* All optimizations */
  15180. /*
  15181. ** Macros for testing whether or not optimizations are enabled or disabled.
  15182. */
  15183. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  15184. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  15185. /*
  15186. ** Return true if it OK to factor constant expressions into the initialization
  15187. ** code. The argument is a Parse object for the code generator.
  15188. */
  15189. #define ConstFactorOk(P) ((P)->okConstFactor)
  15190. /*
  15191. ** Possible values for the sqlite.magic field.
  15192. ** The numbers are obtained at random and have no special meaning, other
  15193. ** than being distinct from one another.
  15194. */
  15195. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  15196. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  15197. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  15198. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  15199. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  15200. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  15201. /*
  15202. ** Each SQL function is defined by an instance of the following
  15203. ** structure. For global built-in functions (ex: substr(), max(), count())
  15204. ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
  15205. ** For per-connection application-defined functions, a pointer to this
  15206. ** structure is held in the db->aHash hash table.
  15207. **
  15208. ** The u.pHash field is used by the global built-ins. The u.pDestructor
  15209. ** field is used by per-connection app-def functions.
  15210. */
  15211. struct FuncDef {
  15212. i8 nArg; /* Number of arguments. -1 means unlimited */
  15213. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  15214. void *pUserData; /* User data parameter */
  15215. FuncDef *pNext; /* Next function with same name */
  15216. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
  15217. void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
  15218. const char *zName; /* SQL name of the function. */
  15219. union {
  15220. FuncDef *pHash; /* Next with a different name but the same hash */
  15221. FuncDestructor *pDestructor; /* Reference counted destructor function */
  15222. } u;
  15223. };
  15224. /*
  15225. ** This structure encapsulates a user-function destructor callback (as
  15226. ** configured using create_function_v2()) and a reference counter. When
  15227. ** create_function_v2() is called to create a function with a destructor,
  15228. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  15229. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  15230. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  15231. ** member of each of the new FuncDef objects is set to point to the allocated
  15232. ** FuncDestructor.
  15233. **
  15234. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  15235. ** count on this object is decremented. When it reaches 0, the destructor
  15236. ** is invoked and the FuncDestructor structure freed.
  15237. */
  15238. struct FuncDestructor {
  15239. int nRef;
  15240. void (*xDestroy)(void *);
  15241. void *pUserData;
  15242. };
  15243. /*
  15244. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  15245. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  15246. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  15247. ** are assert() statements in the code to verify this.
  15248. **
  15249. ** Value constraints (enforced via assert()):
  15250. ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
  15251. ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
  15252. ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
  15253. ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
  15254. ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
  15255. */
  15256. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  15257. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  15258. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  15259. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  15260. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  15261. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  15262. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  15263. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  15264. #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
  15265. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  15266. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  15267. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  15268. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  15269. ** single query - might change over time */
  15270. #define SQLITE_FUNC_AFFINITY 0x4000 /* Built-in affinity() function */
  15271. #define SQLITE_FUNC_OFFSET 0x8000 /* Built-in sqlite_offset() function */
  15272. /*
  15273. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  15274. ** used to create the initializers for the FuncDef structures.
  15275. **
  15276. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  15277. ** Used to create a scalar function definition of a function zName
  15278. ** implemented by C function xFunc that accepts nArg arguments. The
  15279. ** value passed as iArg is cast to a (void*) and made available
  15280. ** as the user-data (sqlite3_user_data()) for the function. If
  15281. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  15282. **
  15283. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  15284. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  15285. **
  15286. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  15287. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  15288. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  15289. ** and functions like sqlite_version() that can change, but not during
  15290. ** a single query. The iArg is ignored. The user-data is always set
  15291. ** to a NULL pointer. The bNC parameter is not used.
  15292. **
  15293. ** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
  15294. ** Used for "pure" date/time functions, this macro is like DFUNCTION
  15295. ** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
  15296. ** ignored and the user-data for these functions is set to an
  15297. ** arbitrary non-NULL pointer. The bNC parameter is not used.
  15298. **
  15299. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  15300. ** Used to create an aggregate function definition implemented by
  15301. ** the C functions xStep and xFinal. The first four parameters
  15302. ** are interpreted in the same way as the first 4 parameters to
  15303. ** FUNCTION().
  15304. **
  15305. ** LIKEFUNC(zName, nArg, pArg, flags)
  15306. ** Used to create a scalar function definition of a function zName
  15307. ** that accepts nArg arguments and is implemented by a call to C
  15308. ** function likeFunc. Argument pArg is cast to a (void *) and made
  15309. ** available as the function user-data (sqlite3_user_data()). The
  15310. ** FuncDef.flags variable is set to the value passed as the flags
  15311. ** parameter.
  15312. */
  15313. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  15314. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  15315. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  15316. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  15317. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  15318. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  15319. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  15320. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
  15321. 0, 0, xFunc, 0, #zName, {0} }
  15322. #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
  15323. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  15324. (void*)&sqlite3Config, 0, xFunc, 0, #zName, {0} }
  15325. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  15326. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  15327. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
  15328. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  15329. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  15330. pArg, 0, xFunc, 0, #zName, }
  15331. #define LIKEFUNC(zName, nArg, arg, flags) \
  15332. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  15333. (void *)arg, 0, likeFunc, 0, #zName, {0} }
  15334. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  15335. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  15336. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  15337. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  15338. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  15339. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
  15340. /*
  15341. ** All current savepoints are stored in a linked list starting at
  15342. ** sqlite3.pSavepoint. The first element in the list is the most recently
  15343. ** opened savepoint. Savepoints are added to the list by the vdbe
  15344. ** OP_Savepoint instruction.
  15345. */
  15346. struct Savepoint {
  15347. char *zName; /* Savepoint name (nul-terminated) */
  15348. i64 nDeferredCons; /* Number of deferred fk violations */
  15349. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  15350. Savepoint *pNext; /* Parent savepoint (if any) */
  15351. };
  15352. /*
  15353. ** The following are used as the second parameter to sqlite3Savepoint(),
  15354. ** and as the P1 argument to the OP_Savepoint instruction.
  15355. */
  15356. #define SAVEPOINT_BEGIN 0
  15357. #define SAVEPOINT_RELEASE 1
  15358. #define SAVEPOINT_ROLLBACK 2
  15359. /*
  15360. ** Each SQLite module (virtual table definition) is defined by an
  15361. ** instance of the following structure, stored in the sqlite3.aModule
  15362. ** hash table.
  15363. */
  15364. struct Module {
  15365. const sqlite3_module *pModule; /* Callback pointers */
  15366. const char *zName; /* Name passed to create_module() */
  15367. void *pAux; /* pAux passed to create_module() */
  15368. void (*xDestroy)(void *); /* Module destructor function */
  15369. Table *pEpoTab; /* Eponymous table for this module */
  15370. };
  15371. /*
  15372. ** information about each column of an SQL table is held in an instance
  15373. ** of this structure.
  15374. */
  15375. struct Column {
  15376. char *zName; /* Name of this column, \000, then the type */
  15377. Expr *pDflt; /* Default value of this column */
  15378. char *zColl; /* Collating sequence. If NULL, use the default */
  15379. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  15380. char affinity; /* One of the SQLITE_AFF_... values */
  15381. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  15382. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  15383. };
  15384. /* Allowed values for Column.colFlags:
  15385. */
  15386. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  15387. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  15388. #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
  15389. #define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */
  15390. /*
  15391. ** A "Collating Sequence" is defined by an instance of the following
  15392. ** structure. Conceptually, a collating sequence consists of a name and
  15393. ** a comparison routine that defines the order of that sequence.
  15394. **
  15395. ** If CollSeq.xCmp is NULL, it means that the
  15396. ** collating sequence is undefined. Indices built on an undefined
  15397. ** collating sequence may not be read or written.
  15398. */
  15399. struct CollSeq {
  15400. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  15401. u8 enc; /* Text encoding handled by xCmp() */
  15402. void *pUser; /* First argument to xCmp() */
  15403. int (*xCmp)(void*,int, const void*, int, const void*);
  15404. void (*xDel)(void*); /* Destructor for pUser */
  15405. };
  15406. /*
  15407. ** A sort order can be either ASC or DESC.
  15408. */
  15409. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  15410. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  15411. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  15412. /*
  15413. ** Column affinity types.
  15414. **
  15415. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  15416. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  15417. ** the speed a little by numbering the values consecutively.
  15418. **
  15419. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  15420. ** when multiple affinity types are concatenated into a string and
  15421. ** used as the P4 operand, they will be more readable.
  15422. **
  15423. ** Note also that the numeric types are grouped together so that testing
  15424. ** for a numeric type is a single comparison. And the BLOB type is first.
  15425. */
  15426. #define SQLITE_AFF_BLOB 'A'
  15427. #define SQLITE_AFF_TEXT 'B'
  15428. #define SQLITE_AFF_NUMERIC 'C'
  15429. #define SQLITE_AFF_INTEGER 'D'
  15430. #define SQLITE_AFF_REAL 'E'
  15431. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  15432. /*
  15433. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  15434. ** affinity value.
  15435. */
  15436. #define SQLITE_AFF_MASK 0x47
  15437. /*
  15438. ** Additional bit values that can be ORed with an affinity without
  15439. ** changing the affinity.
  15440. **
  15441. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  15442. ** It causes an assert() to fire if either operand to a comparison
  15443. ** operator is NULL. It is added to certain comparison operators to
  15444. ** prove that the operands are always NOT NULL.
  15445. */
  15446. #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
  15447. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  15448. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  15449. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  15450. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  15451. /*
  15452. ** An object of this type is created for each virtual table present in
  15453. ** the database schema.
  15454. **
  15455. ** If the database schema is shared, then there is one instance of this
  15456. ** structure for each database connection (sqlite3*) that uses the shared
  15457. ** schema. This is because each database connection requires its own unique
  15458. ** instance of the sqlite3_vtab* handle used to access the virtual table
  15459. ** implementation. sqlite3_vtab* handles can not be shared between
  15460. ** database connections, even when the rest of the in-memory database
  15461. ** schema is shared, as the implementation often stores the database
  15462. ** connection handle passed to it via the xConnect() or xCreate() method
  15463. ** during initialization internally. This database connection handle may
  15464. ** then be used by the virtual table implementation to access real tables
  15465. ** within the database. So that they appear as part of the callers
  15466. ** transaction, these accesses need to be made via the same database
  15467. ** connection as that used to execute SQL operations on the virtual table.
  15468. **
  15469. ** All VTable objects that correspond to a single table in a shared
  15470. ** database schema are initially stored in a linked-list pointed to by
  15471. ** the Table.pVTable member variable of the corresponding Table object.
  15472. ** When an sqlite3_prepare() operation is required to access the virtual
  15473. ** table, it searches the list for the VTable that corresponds to the
  15474. ** database connection doing the preparing so as to use the correct
  15475. ** sqlite3_vtab* handle in the compiled query.
  15476. **
  15477. ** When an in-memory Table object is deleted (for example when the
  15478. ** schema is being reloaded for some reason), the VTable objects are not
  15479. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  15480. ** immediately. Instead, they are moved from the Table.pVTable list to
  15481. ** another linked list headed by the sqlite3.pDisconnect member of the
  15482. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  15483. ** next time a statement is prepared using said sqlite3*. This is done
  15484. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  15485. ** Refer to comments above function sqlite3VtabUnlockList() for an
  15486. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  15487. ** list without holding the corresponding sqlite3.mutex mutex.
  15488. **
  15489. ** The memory for objects of this type is always allocated by
  15490. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  15491. ** the first argument.
  15492. */
  15493. struct VTable {
  15494. sqlite3 *db; /* Database connection associated with this table */
  15495. Module *pMod; /* Pointer to module implementation */
  15496. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  15497. int nRef; /* Number of pointers to this structure */
  15498. u8 bConstraint; /* True if constraints are supported */
  15499. int iSavepoint; /* Depth of the SAVEPOINT stack */
  15500. VTable *pNext; /* Next in linked list (see above) */
  15501. };
  15502. /*
  15503. ** The schema for each SQL table and view is represented in memory
  15504. ** by an instance of the following structure.
  15505. */
  15506. struct Table {
  15507. char *zName; /* Name of the table or view */
  15508. Column *aCol; /* Information about each column */
  15509. Index *pIndex; /* List of SQL indexes on this table. */
  15510. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  15511. FKey *pFKey; /* Linked list of all foreign keys in this table */
  15512. char *zColAff; /* String defining the affinity of each column */
  15513. ExprList *pCheck; /* All CHECK constraints */
  15514. /* ... also used as column name list in a VIEW */
  15515. int tnum; /* Root BTree page for this table */
  15516. u32 nTabRef; /* Number of pointers to this Table */
  15517. u32 tabFlags; /* Mask of TF_* values */
  15518. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  15519. i16 nCol; /* Number of columns in this table */
  15520. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  15521. LogEst szTabRow; /* Estimated size of each table row in bytes */
  15522. #ifdef SQLITE_ENABLE_COSTMULT
  15523. LogEst costMult; /* Cost multiplier for using this table */
  15524. #endif
  15525. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  15526. #ifndef SQLITE_OMIT_ALTERTABLE
  15527. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  15528. #endif
  15529. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15530. int nModuleArg; /* Number of arguments to the module */
  15531. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  15532. VTable *pVTable; /* List of VTable objects. */
  15533. #endif
  15534. Trigger *pTrigger; /* List of triggers stored in pSchema */
  15535. Schema *pSchema; /* Schema that contains this table */
  15536. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  15537. };
  15538. /*
  15539. ** Allowed values for Table.tabFlags.
  15540. **
  15541. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  15542. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  15543. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  15544. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  15545. ** special handling during INSERT processing.
  15546. */
  15547. #define TF_Readonly 0x0001 /* Read-only system table */
  15548. #define TF_Ephemeral 0x0002 /* An ephemeral table */
  15549. #define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
  15550. #define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
  15551. #define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
  15552. #define TF_WithoutRowid 0x0020 /* No rowid. PRIMARY KEY is the key */
  15553. #define TF_NoVisibleRowid 0x0040 /* No user-visible "rowid" column */
  15554. #define TF_OOOHidden 0x0080 /* Out-of-Order hidden columns */
  15555. #define TF_StatsUsed 0x0100 /* Query planner decisions affected by
  15556. ** Index.aiRowLogEst[] values */
  15557. #define TF_HasNotNull 0x0200 /* Contains NOT NULL constraints */
  15558. /*
  15559. ** Test to see whether or not a table is a virtual table. This is
  15560. ** done as a macro so that it will be optimized out when virtual
  15561. ** table support is omitted from the build.
  15562. */
  15563. #ifndef SQLITE_OMIT_VIRTUALTABLE
  15564. # define IsVirtual(X) ((X)->nModuleArg)
  15565. #else
  15566. # define IsVirtual(X) 0
  15567. #endif
  15568. /*
  15569. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  15570. ** only works for non-virtual tables (ordinary tables and views) and is
  15571. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  15572. ** IsHiddenColumn() macro is general purpose.
  15573. */
  15574. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  15575. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  15576. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  15577. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  15578. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  15579. # define IsOrdinaryHiddenColumn(X) 0
  15580. #else
  15581. # define IsHiddenColumn(X) 0
  15582. # define IsOrdinaryHiddenColumn(X) 0
  15583. #endif
  15584. /* Does the table have a rowid */
  15585. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  15586. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  15587. /*
  15588. ** Each foreign key constraint is an instance of the following structure.
  15589. **
  15590. ** A foreign key is associated with two tables. The "from" table is
  15591. ** the table that contains the REFERENCES clause that creates the foreign
  15592. ** key. The "to" table is the table that is named in the REFERENCES clause.
  15593. ** Consider this example:
  15594. **
  15595. ** CREATE TABLE ex1(
  15596. ** a INTEGER PRIMARY KEY,
  15597. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  15598. ** );
  15599. **
  15600. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  15601. ** Equivalent names:
  15602. **
  15603. ** from-table == child-table
  15604. ** to-table == parent-table
  15605. **
  15606. ** Each REFERENCES clause generates an instance of the following structure
  15607. ** which is attached to the from-table. The to-table need not exist when
  15608. ** the from-table is created. The existence of the to-table is not checked.
  15609. **
  15610. ** The list of all parents for child Table X is held at X.pFKey.
  15611. **
  15612. ** A list of all children for a table named Z (which might not even exist)
  15613. ** is held in Schema.fkeyHash with a hash key of Z.
  15614. */
  15615. struct FKey {
  15616. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  15617. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  15618. char *zTo; /* Name of table that the key points to (aka: Parent) */
  15619. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  15620. FKey *pPrevTo; /* Previous with the same zTo */
  15621. int nCol; /* Number of columns in this key */
  15622. /* EV: R-30323-21917 */
  15623. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  15624. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  15625. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  15626. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  15627. int iFrom; /* Index of column in pFrom */
  15628. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  15629. } aCol[1]; /* One entry for each of nCol columns */
  15630. };
  15631. /*
  15632. ** SQLite supports many different ways to resolve a constraint
  15633. ** error. ROLLBACK processing means that a constraint violation
  15634. ** causes the operation in process to fail and for the current transaction
  15635. ** to be rolled back. ABORT processing means the operation in process
  15636. ** fails and any prior changes from that one operation are backed out,
  15637. ** but the transaction is not rolled back. FAIL processing means that
  15638. ** the operation in progress stops and returns an error code. But prior
  15639. ** changes due to the same operation are not backed out and no rollback
  15640. ** occurs. IGNORE means that the particular row that caused the constraint
  15641. ** error is not inserted or updated. Processing continues and no error
  15642. ** is returned. REPLACE means that preexisting database rows that caused
  15643. ** a UNIQUE constraint violation are removed so that the new insert or
  15644. ** update can proceed. Processing continues and no error is reported.
  15645. **
  15646. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  15647. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  15648. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  15649. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  15650. ** referenced table row is propagated into the row that holds the
  15651. ** foreign key.
  15652. **
  15653. ** The following symbolic values are used to record which type
  15654. ** of action to take.
  15655. */
  15656. #define OE_None 0 /* There is no constraint to check */
  15657. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  15658. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  15659. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  15660. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  15661. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  15662. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  15663. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  15664. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  15665. #define OE_Cascade 9 /* Cascade the changes */
  15666. #define OE_Default 10 /* Do whatever the default action is */
  15667. /*
  15668. ** An instance of the following structure is passed as the first
  15669. ** argument to sqlite3VdbeKeyCompare and is used to control the
  15670. ** comparison of the two index keys.
  15671. **
  15672. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  15673. ** are nField slots for the columns of an index then one extra slot
  15674. ** for the rowid at the end.
  15675. */
  15676. struct KeyInfo {
  15677. u32 nRef; /* Number of references to this KeyInfo object */
  15678. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  15679. u16 nKeyField; /* Number of key columns in the index */
  15680. u16 nAllField; /* Total columns, including key plus others */
  15681. sqlite3 *db; /* The database connection */
  15682. u8 *aSortOrder; /* Sort order for each column. */
  15683. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  15684. };
  15685. /*
  15686. ** This object holds a record which has been parsed out into individual
  15687. ** fields, for the purposes of doing a comparison.
  15688. **
  15689. ** A record is an object that contains one or more fields of data.
  15690. ** Records are used to store the content of a table row and to store
  15691. ** the key of an index. A blob encoding of a record is created by
  15692. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  15693. ** OP_Column opcode.
  15694. **
  15695. ** An instance of this object serves as a "key" for doing a search on
  15696. ** an index b+tree. The goal of the search is to find the entry that
  15697. ** is closed to the key described by this object. This object might hold
  15698. ** just a prefix of the key. The number of fields is given by
  15699. ** pKeyInfo->nField.
  15700. **
  15701. ** The r1 and r2 fields are the values to return if this key is less than
  15702. ** or greater than a key in the btree, respectively. These are normally
  15703. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  15704. ** is in DESC order.
  15705. **
  15706. ** The key comparison functions actually return default_rc when they find
  15707. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  15708. ** multiple entries in the b-tree with the same key (when only looking
  15709. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  15710. ** cause the search to find the last match, or +1 to cause the search to
  15711. ** find the first match.
  15712. **
  15713. ** The key comparison functions will set eqSeen to true if they ever
  15714. ** get and equal results when comparing this structure to a b-tree record.
  15715. ** When default_rc!=0, the search might end up on the record immediately
  15716. ** before the first match or immediately after the last match. The
  15717. ** eqSeen field will indicate whether or not an exact match exists in the
  15718. ** b-tree.
  15719. */
  15720. struct UnpackedRecord {
  15721. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  15722. Mem *aMem; /* Values */
  15723. u16 nField; /* Number of entries in apMem[] */
  15724. i8 default_rc; /* Comparison result if keys are equal */
  15725. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  15726. i8 r1; /* Value to return if (lhs < rhs) */
  15727. i8 r2; /* Value to return if (lhs > rhs) */
  15728. u8 eqSeen; /* True if an equality comparison has been seen */
  15729. };
  15730. /*
  15731. ** Each SQL index is represented in memory by an
  15732. ** instance of the following structure.
  15733. **
  15734. ** The columns of the table that are to be indexed are described
  15735. ** by the aiColumn[] field of this structure. For example, suppose
  15736. ** we have the following table and index:
  15737. **
  15738. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  15739. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  15740. **
  15741. ** In the Table structure describing Ex1, nCol==3 because there are
  15742. ** three columns in the table. In the Index structure describing
  15743. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  15744. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  15745. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  15746. ** The second column to be indexed (c1) has an index of 0 in
  15747. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  15748. **
  15749. ** The Index.onError field determines whether or not the indexed columns
  15750. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  15751. ** it means this is not a unique index. Otherwise it is a unique index
  15752. ** and the value of Index.onError indicate the which conflict resolution
  15753. ** algorithm to employ whenever an attempt is made to insert a non-unique
  15754. ** element.
  15755. **
  15756. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  15757. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  15758. ** table as part of parsing an existing database schema), transient instances
  15759. ** of this structure may be created. In this case the Index.tnum variable is
  15760. ** used to store the address of a VDBE instruction, not a database page
  15761. ** number (it cannot - the database page is not allocated until the VDBE
  15762. ** program is executed). See convertToWithoutRowidTable() for details.
  15763. */
  15764. struct Index {
  15765. char *zName; /* Name of this index */
  15766. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  15767. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  15768. Table *pTable; /* The SQL table being indexed */
  15769. char *zColAff; /* String defining the affinity of each column */
  15770. Index *pNext; /* The next index associated with the same table */
  15771. Schema *pSchema; /* Schema containing this index */
  15772. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  15773. const char **azColl; /* Array of collation sequence names for index */
  15774. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  15775. ExprList *aColExpr; /* Column expressions */
  15776. int tnum; /* DB Page containing root of this index */
  15777. LogEst szIdxRow; /* Estimated average row size in bytes */
  15778. u16 nKeyCol; /* Number of columns forming the key */
  15779. u16 nColumn; /* Number of columns stored in the index */
  15780. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  15781. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  15782. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  15783. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  15784. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  15785. unsigned isCovering:1; /* True if this is a covering index */
  15786. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  15787. unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
  15788. unsigned bNoQuery:1; /* Do not use this index to optimize queries */
  15789. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  15790. int nSample; /* Number of elements in aSample[] */
  15791. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  15792. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  15793. IndexSample *aSample; /* Samples of the left-most key */
  15794. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  15795. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  15796. #endif
  15797. };
  15798. /*
  15799. ** Allowed values for Index.idxType
  15800. */
  15801. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  15802. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  15803. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  15804. /* Return true if index X is a PRIMARY KEY index */
  15805. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  15806. /* Return true if index X is a UNIQUE index */
  15807. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  15808. /* The Index.aiColumn[] values are normally positive integer. But
  15809. ** there are some negative values that have special meaning:
  15810. */
  15811. #define XN_ROWID (-1) /* Indexed column is the rowid */
  15812. #define XN_EXPR (-2) /* Indexed column is an expression */
  15813. /*
  15814. ** Each sample stored in the sqlite_stat3 table is represented in memory
  15815. ** using a structure of this type. See documentation at the top of the
  15816. ** analyze.c source file for additional information.
  15817. */
  15818. struct IndexSample {
  15819. void *p; /* Pointer to sampled record */
  15820. int n; /* Size of record in bytes */
  15821. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  15822. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  15823. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  15824. };
  15825. /*
  15826. ** Each token coming out of the lexer is an instance of
  15827. ** this structure. Tokens are also used as part of an expression.
  15828. **
  15829. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  15830. ** may contain random values. Do not make any assumptions about Token.dyn
  15831. ** and Token.n when Token.z==0.
  15832. */
  15833. struct Token {
  15834. const char *z; /* Text of the token. Not NULL-terminated! */
  15835. unsigned int n; /* Number of characters in this token */
  15836. };
  15837. /*
  15838. ** An instance of this structure contains information needed to generate
  15839. ** code for a SELECT that contains aggregate functions.
  15840. **
  15841. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  15842. ** pointer to this structure. The Expr.iColumn field is the index in
  15843. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  15844. ** code for that node.
  15845. **
  15846. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  15847. ** original Select structure that describes the SELECT statement. These
  15848. ** fields do not need to be freed when deallocating the AggInfo structure.
  15849. */
  15850. struct AggInfo {
  15851. u8 directMode; /* Direct rendering mode means take data directly
  15852. ** from source tables rather than from accumulators */
  15853. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  15854. ** than the source table */
  15855. int sortingIdx; /* Cursor number of the sorting index */
  15856. int sortingIdxPTab; /* Cursor number of pseudo-table */
  15857. int nSortingColumn; /* Number of columns in the sorting index */
  15858. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  15859. ExprList *pGroupBy; /* The group by clause */
  15860. struct AggInfo_col { /* For each column used in source tables */
  15861. Table *pTab; /* Source table */
  15862. int iTable; /* Cursor number of the source table */
  15863. int iColumn; /* Column number within the source table */
  15864. int iSorterColumn; /* Column number in the sorting index */
  15865. int iMem; /* Memory location that acts as accumulator */
  15866. Expr *pExpr; /* The original expression */
  15867. } *aCol;
  15868. int nColumn; /* Number of used entries in aCol[] */
  15869. int nAccumulator; /* Number of columns that show through to the output.
  15870. ** Additional columns are used only as parameters to
  15871. ** aggregate functions */
  15872. struct AggInfo_func { /* For each aggregate function */
  15873. Expr *pExpr; /* Expression encoding the function */
  15874. FuncDef *pFunc; /* The aggregate function implementation */
  15875. int iMem; /* Memory location that acts as accumulator */
  15876. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  15877. } *aFunc;
  15878. int nFunc; /* Number of entries in aFunc[] */
  15879. };
  15880. /*
  15881. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  15882. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  15883. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  15884. ** it uses less memory in the Expr object, which is a big memory user
  15885. ** in systems with lots of prepared statements. And few applications
  15886. ** need more than about 10 or 20 variables. But some extreme users want
  15887. ** to have prepared statements with over 32767 variables, and for them
  15888. ** the option is available (at compile-time).
  15889. */
  15890. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  15891. typedef i16 ynVar;
  15892. #else
  15893. typedef int ynVar;
  15894. #endif
  15895. /*
  15896. ** Each node of an expression in the parse tree is an instance
  15897. ** of this structure.
  15898. **
  15899. ** Expr.op is the opcode. The integer parser token codes are reused
  15900. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  15901. ** code representing the ">=" operator. This same integer code is reused
  15902. ** to represent the greater-than-or-equal-to operator in the expression
  15903. ** tree.
  15904. **
  15905. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  15906. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  15907. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  15908. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  15909. ** then Expr.token contains the name of the function.
  15910. **
  15911. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  15912. ** binary operator. Either or both may be NULL.
  15913. **
  15914. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  15915. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  15916. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  15917. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  15918. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  15919. ** valid.
  15920. **
  15921. ** An expression of the form ID or ID.ID refers to a column in a table.
  15922. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  15923. ** the integer cursor number of a VDBE cursor pointing to that table and
  15924. ** Expr.iColumn is the column number for the specific column. If the
  15925. ** expression is used as a result in an aggregate SELECT, then the
  15926. ** value is also stored in the Expr.iAgg column in the aggregate so that
  15927. ** it can be accessed after all aggregates are computed.
  15928. **
  15929. ** If the expression is an unbound variable marker (a question mark
  15930. ** character '?' in the original SQL) then the Expr.iTable holds the index
  15931. ** number for that variable.
  15932. **
  15933. ** If the expression is a subquery then Expr.iColumn holds an integer
  15934. ** register number containing the result of the subquery. If the
  15935. ** subquery gives a constant result, then iTable is -1. If the subquery
  15936. ** gives a different answer at different times during statement processing
  15937. ** then iTable is the address of a subroutine that computes the subquery.
  15938. **
  15939. ** If the Expr is of type OP_Column, and the table it is selecting from
  15940. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  15941. ** corresponding table definition.
  15942. **
  15943. ** ALLOCATION NOTES:
  15944. **
  15945. ** Expr objects can use a lot of memory space in database schema. To
  15946. ** help reduce memory requirements, sometimes an Expr object will be
  15947. ** truncated. And to reduce the number of memory allocations, sometimes
  15948. ** two or more Expr objects will be stored in a single memory allocation,
  15949. ** together with Expr.zToken strings.
  15950. **
  15951. ** If the EP_Reduced and EP_TokenOnly flags are set when
  15952. ** an Expr object is truncated. When EP_Reduced is set, then all
  15953. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  15954. ** are contained within the same memory allocation. Note, however, that
  15955. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  15956. ** allocated, regardless of whether or not EP_Reduced is set.
  15957. */
  15958. struct Expr {
  15959. u8 op; /* Operation performed by this node */
  15960. char affinity; /* The affinity of the column or 0 if not a column */
  15961. u32 flags; /* Various flags. EP_* See below */
  15962. union {
  15963. char *zToken; /* Token value. Zero terminated and dequoted */
  15964. int iValue; /* Non-negative integer value if EP_IntValue */
  15965. } u;
  15966. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  15967. ** space is allocated for the fields below this point. An attempt to
  15968. ** access them will result in a segfault or malfunction.
  15969. *********************************************************************/
  15970. Expr *pLeft; /* Left subnode */
  15971. Expr *pRight; /* Right subnode */
  15972. union {
  15973. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  15974. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  15975. } x;
  15976. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  15977. ** space is allocated for the fields below this point. An attempt to
  15978. ** access them will result in a segfault or malfunction.
  15979. *********************************************************************/
  15980. #if SQLITE_MAX_EXPR_DEPTH>0
  15981. int nHeight; /* Height of the tree headed by this node */
  15982. #endif
  15983. int iTable; /* TK_COLUMN: cursor number of table holding column
  15984. ** TK_REGISTER: register number
  15985. ** TK_TRIGGER: 1 -> new, 0 -> old
  15986. ** EP_Unlikely: 134217728 times likelihood
  15987. ** TK_SELECT: 1st register of result vector */
  15988. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  15989. ** TK_VARIABLE: variable number (always >= 1).
  15990. ** TK_SELECT_COLUMN: column of the result vector */
  15991. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  15992. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  15993. u8 op2; /* TK_REGISTER: original value of Expr.op
  15994. ** TK_COLUMN: the value of p5 for OP_Column
  15995. ** TK_AGG_FUNCTION: nesting depth */
  15996. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  15997. Table *pTab; /* Table for TK_COLUMN expressions. Can be NULL
  15998. ** for a column of an index on an expression */
  15999. };
  16000. /*
  16001. ** The following are the meanings of bits in the Expr.flags field.
  16002. */
  16003. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  16004. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  16005. #define EP_HasFunc 0x000004 /* Contains one or more functions of any kind */
  16006. /* 0x000008 // available for use */
  16007. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  16008. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  16009. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  16010. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  16011. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  16012. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  16013. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  16014. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  16015. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  16016. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  16017. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  16018. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  16019. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  16020. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  16021. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  16022. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  16023. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  16024. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  16025. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  16026. #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
  16027. /*
  16028. ** The EP_Propagate mask is a set of properties that automatically propagate
  16029. ** upwards into parent nodes.
  16030. */
  16031. #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
  16032. /*
  16033. ** These macros can be used to test, set, or clear bits in the
  16034. ** Expr.flags field.
  16035. */
  16036. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  16037. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  16038. #define ExprSetProperty(E,P) (E)->flags|=(P)
  16039. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  16040. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  16041. ** and Accreditation only. It works like ExprSetProperty() during VVA
  16042. ** processes but is a no-op for delivery.
  16043. */
  16044. #ifdef SQLITE_DEBUG
  16045. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  16046. #else
  16047. # define ExprSetVVAProperty(E,P)
  16048. #endif
  16049. /*
  16050. ** Macros to determine the number of bytes required by a normal Expr
  16051. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  16052. ** and an Expr struct with the EP_TokenOnly flag set.
  16053. */
  16054. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  16055. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  16056. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  16057. /*
  16058. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  16059. ** above sqlite3ExprDup() for details.
  16060. */
  16061. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  16062. /*
  16063. ** A list of expressions. Each expression may optionally have a
  16064. ** name. An expr/name combination can be used in several ways, such
  16065. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  16066. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  16067. ** also be used as the argument to a function, in which case the a.zName
  16068. ** field is not used.
  16069. **
  16070. ** By default the Expr.zSpan field holds a human-readable description of
  16071. ** the expression that is used in the generation of error messages and
  16072. ** column labels. In this case, Expr.zSpan is typically the text of a
  16073. ** column expression as it exists in a SELECT statement. However, if
  16074. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  16075. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  16076. ** form is used for name resolution with nested FROM clauses.
  16077. */
  16078. struct ExprList {
  16079. int nExpr; /* Number of expressions on the list */
  16080. struct ExprList_item { /* For each expression in the list */
  16081. Expr *pExpr; /* The parse tree for this expression */
  16082. char *zName; /* Token associated with this expression */
  16083. char *zSpan; /* Original text of the expression */
  16084. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  16085. unsigned done :1; /* A flag to indicate when processing is finished */
  16086. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  16087. unsigned reusable :1; /* Constant expression is reusable */
  16088. union {
  16089. struct {
  16090. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  16091. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  16092. } x;
  16093. int iConstExprReg; /* Register in which Expr value is cached */
  16094. } u;
  16095. } a[1]; /* One slot for each expression in the list */
  16096. };
  16097. /*
  16098. ** An instance of this structure can hold a simple list of identifiers,
  16099. ** such as the list "a,b,c" in the following statements:
  16100. **
  16101. ** INSERT INTO t(a,b,c) VALUES ...;
  16102. ** CREATE INDEX idx ON t(a,b,c);
  16103. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  16104. **
  16105. ** The IdList.a.idx field is used when the IdList represents the list of
  16106. ** column names after a table name in an INSERT statement. In the statement
  16107. **
  16108. ** INSERT INTO t(a,b,c) ...
  16109. **
  16110. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  16111. */
  16112. struct IdList {
  16113. struct IdList_item {
  16114. char *zName; /* Name of the identifier */
  16115. int idx; /* Index in some Table.aCol[] of a column named zName */
  16116. } *a;
  16117. int nId; /* Number of identifiers on the list */
  16118. };
  16119. /*
  16120. ** The bitmask datatype defined below is used for various optimizations.
  16121. **
  16122. ** Changing this from a 64-bit to a 32-bit type limits the number of
  16123. ** tables in a join to 32 instead of 64. But it also reduces the size
  16124. ** of the library by 738 bytes on ix86.
  16125. */
  16126. #ifdef SQLITE_BITMASK_TYPE
  16127. typedef SQLITE_BITMASK_TYPE Bitmask;
  16128. #else
  16129. typedef u64 Bitmask;
  16130. #endif
  16131. /*
  16132. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  16133. */
  16134. #define BMS ((int)(sizeof(Bitmask)*8))
  16135. /*
  16136. ** A bit in a Bitmask
  16137. */
  16138. #define MASKBIT(n) (((Bitmask)1)<<(n))
  16139. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  16140. #define ALLBITS ((Bitmask)-1)
  16141. /*
  16142. ** The following structure describes the FROM clause of a SELECT statement.
  16143. ** Each table or subquery in the FROM clause is a separate element of
  16144. ** the SrcList.a[] array.
  16145. **
  16146. ** With the addition of multiple database support, the following structure
  16147. ** can also be used to describe a particular table such as the table that
  16148. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  16149. ** such a table must be a simple name: ID. But in SQLite, the table can
  16150. ** now be identified by a database name, a dot, then the table name: ID.ID.
  16151. **
  16152. ** The jointype starts out showing the join type between the current table
  16153. ** and the next table on the list. The parser builds the list this way.
  16154. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  16155. ** jointype expresses the join between the table and the previous table.
  16156. **
  16157. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  16158. ** contains more than 63 columns and the 64-th or later column is used.
  16159. */
  16160. struct SrcList {
  16161. int nSrc; /* Number of tables or subqueries in the FROM clause */
  16162. u32 nAlloc; /* Number of entries allocated in a[] below */
  16163. struct SrcList_item {
  16164. Schema *pSchema; /* Schema to which this item is fixed */
  16165. char *zDatabase; /* Name of database holding this table */
  16166. char *zName; /* Name of the table */
  16167. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  16168. Table *pTab; /* An SQL table corresponding to zName */
  16169. Select *pSelect; /* A SELECT statement used in place of a table name */
  16170. int addrFillSub; /* Address of subroutine to manifest a subquery */
  16171. int regReturn; /* Register holding return address of addrFillSub */
  16172. int regResult; /* Registers holding results of a co-routine */
  16173. struct {
  16174. u8 jointype; /* Type of join between this table and the previous */
  16175. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  16176. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  16177. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  16178. unsigned isCorrelated :1; /* True if sub-query is correlated */
  16179. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  16180. unsigned isRecursive :1; /* True for recursive reference in WITH */
  16181. } fg;
  16182. #ifndef SQLITE_OMIT_EXPLAIN
  16183. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  16184. #endif
  16185. int iCursor; /* The VDBE cursor number used to access this table */
  16186. Expr *pOn; /* The ON clause of a join */
  16187. IdList *pUsing; /* The USING clause of a join */
  16188. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  16189. union {
  16190. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  16191. ExprList *pFuncArg; /* Arguments to table-valued-function */
  16192. } u1;
  16193. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  16194. } a[1]; /* One entry for each identifier on the list */
  16195. };
  16196. /*
  16197. ** Permitted values of the SrcList.a.jointype field
  16198. */
  16199. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  16200. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  16201. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  16202. #define JT_LEFT 0x0008 /* Left outer join */
  16203. #define JT_RIGHT 0x0010 /* Right outer join */
  16204. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  16205. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  16206. /*
  16207. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  16208. ** and the WhereInfo.wctrlFlags member.
  16209. **
  16210. ** Value constraints (enforced via assert()):
  16211. ** WHERE_USE_LIMIT == SF_FixedLimit
  16212. */
  16213. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  16214. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  16215. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  16216. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  16217. #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
  16218. #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
  16219. #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
  16220. ** the OR optimization */
  16221. #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
  16222. #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
  16223. #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
  16224. #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
  16225. #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
  16226. #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
  16227. #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
  16228. /* 0x2000 not currently used */
  16229. #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
  16230. /* 0x8000 not currently used */
  16231. /* Allowed return values from sqlite3WhereIsDistinct()
  16232. */
  16233. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  16234. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  16235. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  16236. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  16237. /*
  16238. ** A NameContext defines a context in which to resolve table and column
  16239. ** names. The context consists of a list of tables (the pSrcList) field and
  16240. ** a list of named expression (pEList). The named expression list may
  16241. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  16242. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  16243. ** pEList corresponds to the result set of a SELECT and is NULL for
  16244. ** other statements.
  16245. **
  16246. ** NameContexts can be nested. When resolving names, the inner-most
  16247. ** context is searched first. If no match is found, the next outer
  16248. ** context is checked. If there is still no match, the next context
  16249. ** is checked. This process continues until either a match is found
  16250. ** or all contexts are check. When a match is found, the nRef member of
  16251. ** the context containing the match is incremented.
  16252. **
  16253. ** Each subquery gets a new NameContext. The pNext field points to the
  16254. ** NameContext in the parent query. Thus the process of scanning the
  16255. ** NameContext list corresponds to searching through successively outer
  16256. ** subqueries looking for a match.
  16257. */
  16258. struct NameContext {
  16259. Parse *pParse; /* The parser */
  16260. SrcList *pSrcList; /* One or more tables used to resolve names */
  16261. ExprList *pEList; /* Optional list of result-set columns */
  16262. AggInfo *pAggInfo; /* Information about aggregates at this level */
  16263. NameContext *pNext; /* Next outer name context. NULL for outermost */
  16264. int nRef; /* Number of names resolved by this context */
  16265. int nErr; /* Number of errors encountered while resolving names */
  16266. u16 ncFlags; /* Zero or more NC_* flags defined below */
  16267. };
  16268. /*
  16269. ** Allowed values for the NameContext, ncFlags field.
  16270. **
  16271. ** Value constraints (all checked via assert()):
  16272. ** NC_HasAgg == SF_HasAgg
  16273. ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
  16274. **
  16275. */
  16276. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  16277. #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
  16278. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  16279. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  16280. #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
  16281. #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
  16282. #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
  16283. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  16284. #define NC_Complex 0x2000 /* True if a function or subquery seen */
  16285. /*
  16286. ** An instance of the following structure contains all information
  16287. ** needed to generate code for a single SELECT statement.
  16288. **
  16289. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  16290. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  16291. ** limit and nOffset to the value of the offset (or 0 if there is not
  16292. ** offset). But later on, nLimit and nOffset become the memory locations
  16293. ** in the VDBE that record the limit and offset counters.
  16294. **
  16295. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  16296. ** These addresses must be stored so that we can go back and fill in
  16297. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  16298. ** the number of columns in P2 can be computed at the same time
  16299. ** as the OP_OpenEphm instruction is coded because not
  16300. ** enough information about the compound query is known at that point.
  16301. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  16302. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  16303. ** sequences for the ORDER BY clause.
  16304. */
  16305. struct Select {
  16306. ExprList *pEList; /* The fields of the result */
  16307. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  16308. LogEst nSelectRow; /* Estimated number of result rows */
  16309. u32 selFlags; /* Various SF_* values */
  16310. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  16311. #if SELECTTRACE_ENABLED
  16312. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  16313. #endif
  16314. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  16315. SrcList *pSrc; /* The FROM clause */
  16316. Expr *pWhere; /* The WHERE clause */
  16317. ExprList *pGroupBy; /* The GROUP BY clause */
  16318. Expr *pHaving; /* The HAVING clause */
  16319. ExprList *pOrderBy; /* The ORDER BY clause */
  16320. Select *pPrior; /* Prior select in a compound select statement */
  16321. Select *pNext; /* Next select to the left in a compound */
  16322. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  16323. With *pWith; /* WITH clause attached to this select. Or NULL. */
  16324. };
  16325. /*
  16326. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  16327. ** "Select Flag".
  16328. **
  16329. ** Value constraints (all checked via assert())
  16330. ** SF_HasAgg == NC_HasAgg
  16331. ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
  16332. ** SF_FixedLimit == WHERE_USE_LIMIT
  16333. */
  16334. #define SF_Distinct 0x00001 /* Output should be DISTINCT */
  16335. #define SF_All 0x00002 /* Includes the ALL keyword */
  16336. #define SF_Resolved 0x00004 /* Identifiers have been resolved */
  16337. #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
  16338. #define SF_HasAgg 0x00010 /* Contains aggregate functions */
  16339. #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
  16340. #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
  16341. #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
  16342. #define SF_Compound 0x00100 /* Part of a compound query */
  16343. #define SF_Values 0x00200 /* Synthesized from VALUES clause */
  16344. #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
  16345. #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
  16346. #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
  16347. #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
  16348. #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
  16349. #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
  16350. #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
  16351. #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
  16352. #define SF_ComplexResult 0x40000 /* Result set contains subquery or function */
  16353. /*
  16354. ** The results of a SELECT can be distributed in several ways, as defined
  16355. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  16356. ** Type".
  16357. **
  16358. ** SRT_Union Store results as a key in a temporary index
  16359. ** identified by pDest->iSDParm.
  16360. **
  16361. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  16362. **
  16363. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  16364. ** set is not empty.
  16365. **
  16366. ** SRT_Discard Throw the results away. This is used by SELECT
  16367. ** statements within triggers whose only purpose is
  16368. ** the side-effects of functions.
  16369. **
  16370. ** All of the above are free to ignore their ORDER BY clause. Those that
  16371. ** follow must honor the ORDER BY clause.
  16372. **
  16373. ** SRT_Output Generate a row of output (using the OP_ResultRow
  16374. ** opcode) for each row in the result set.
  16375. **
  16376. ** SRT_Mem Only valid if the result is a single column.
  16377. ** Store the first column of the first result row
  16378. ** in register pDest->iSDParm then abandon the rest
  16379. ** of the query. This destination implies "LIMIT 1".
  16380. **
  16381. ** SRT_Set The result must be a single column. Store each
  16382. ** row of result as the key in table pDest->iSDParm.
  16383. ** Apply the affinity pDest->affSdst before storing
  16384. ** results. Used to implement "IN (SELECT ...)".
  16385. **
  16386. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  16387. ** the result there. The cursor is left open after
  16388. ** returning. This is like SRT_Table except that
  16389. ** this destination uses OP_OpenEphemeral to create
  16390. ** the table first.
  16391. **
  16392. ** SRT_Coroutine Generate a co-routine that returns a new row of
  16393. ** results each time it is invoked. The entry point
  16394. ** of the co-routine is stored in register pDest->iSDParm
  16395. ** and the result row is stored in pDest->nDest registers
  16396. ** starting with pDest->iSdst.
  16397. **
  16398. ** SRT_Table Store results in temporary table pDest->iSDParm.
  16399. ** SRT_Fifo This is like SRT_EphemTab except that the table
  16400. ** is assumed to already be open. SRT_Fifo has
  16401. ** the additional property of being able to ignore
  16402. ** the ORDER BY clause.
  16403. **
  16404. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  16405. ** But also use temporary table pDest->iSDParm+1 as
  16406. ** a record of all prior results and ignore any duplicate
  16407. ** rows. Name means: "Distinct Fifo".
  16408. **
  16409. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  16410. ** an index). Append a sequence number so that all entries
  16411. ** are distinct.
  16412. **
  16413. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  16414. ** the same record has never been stored before. The
  16415. ** index at pDest->iSDParm+1 hold all prior stores.
  16416. */
  16417. #define SRT_Union 1 /* Store result as keys in an index */
  16418. #define SRT_Except 2 /* Remove result from a UNION index */
  16419. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  16420. #define SRT_Discard 4 /* Do not save the results anywhere */
  16421. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  16422. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  16423. #define SRT_Queue 7 /* Store result in an queue */
  16424. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  16425. /* The ORDER BY clause is ignored for all of the above */
  16426. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  16427. #define SRT_Output 9 /* Output each row of result */
  16428. #define SRT_Mem 10 /* Store result in a memory cell */
  16429. #define SRT_Set 11 /* Store results as keys in an index */
  16430. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  16431. #define SRT_Coroutine 13 /* Generate a single row of result */
  16432. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  16433. /*
  16434. ** An instance of this object describes where to put of the results of
  16435. ** a SELECT statement.
  16436. */
  16437. struct SelectDest {
  16438. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  16439. int iSDParm; /* A parameter used by the eDest disposal method */
  16440. int iSdst; /* Base register where results are written */
  16441. int nSdst; /* Number of registers allocated */
  16442. char *zAffSdst; /* Affinity used when eDest==SRT_Set */
  16443. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  16444. };
  16445. /*
  16446. ** During code generation of statements that do inserts into AUTOINCREMENT
  16447. ** tables, the following information is attached to the Table.u.autoInc.p
  16448. ** pointer of each autoincrement table to record some side information that
  16449. ** the code generator needs. We have to keep per-table autoincrement
  16450. ** information in case inserts are done within triggers. Triggers do not
  16451. ** normally coordinate their activities, but we do need to coordinate the
  16452. ** loading and saving of autoincrement information.
  16453. */
  16454. struct AutoincInfo {
  16455. AutoincInfo *pNext; /* Next info block in a list of them all */
  16456. Table *pTab; /* Table this info block refers to */
  16457. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  16458. int regCtr; /* Memory register holding the rowid counter */
  16459. };
  16460. /*
  16461. ** Size of the column cache
  16462. */
  16463. #ifndef SQLITE_N_COLCACHE
  16464. # define SQLITE_N_COLCACHE 10
  16465. #endif
  16466. /*
  16467. ** At least one instance of the following structure is created for each
  16468. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  16469. ** statement. All such objects are stored in the linked list headed at
  16470. ** Parse.pTriggerPrg and deleted once statement compilation has been
  16471. ** completed.
  16472. **
  16473. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  16474. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  16475. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  16476. ** The Parse.pTriggerPrg list never contains two entries with the same
  16477. ** values for both pTrigger and orconf.
  16478. **
  16479. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  16480. ** accessed (or set to 0 for triggers fired as a result of INSERT
  16481. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  16482. ** a mask of new.* columns used by the program.
  16483. */
  16484. struct TriggerPrg {
  16485. Trigger *pTrigger; /* Trigger this program was coded from */
  16486. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  16487. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  16488. int orconf; /* Default ON CONFLICT policy */
  16489. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  16490. };
  16491. /*
  16492. ** The yDbMask datatype for the bitmask of all attached databases.
  16493. */
  16494. #if SQLITE_MAX_ATTACHED>30
  16495. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  16496. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  16497. # define DbMaskZero(M) memset((M),0,sizeof(M))
  16498. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  16499. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  16500. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  16501. #else
  16502. typedef unsigned int yDbMask;
  16503. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  16504. # define DbMaskZero(M) (M)=0
  16505. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  16506. # define DbMaskAllZero(M) (M)==0
  16507. # define DbMaskNonZero(M) (M)!=0
  16508. #endif
  16509. /*
  16510. ** An SQL parser context. A copy of this structure is passed through
  16511. ** the parser and down into all the parser action routine in order to
  16512. ** carry around information that is global to the entire parse.
  16513. **
  16514. ** The structure is divided into two parts. When the parser and code
  16515. ** generate call themselves recursively, the first part of the structure
  16516. ** is constant but the second part is reset at the beginning and end of
  16517. ** each recursion.
  16518. **
  16519. ** The nTableLock and aTableLock variables are only used if the shared-cache
  16520. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  16521. ** used to store the set of table-locks required by the statement being
  16522. ** compiled. Function sqlite3TableLock() is used to add entries to the
  16523. ** list.
  16524. */
  16525. struct Parse {
  16526. sqlite3 *db; /* The main database structure */
  16527. char *zErrMsg; /* An error message */
  16528. Vdbe *pVdbe; /* An engine for executing database bytecode */
  16529. int rc; /* Return code from execution */
  16530. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  16531. u8 checkSchema; /* Causes schema cookie check after an error */
  16532. u8 nested; /* Number of nested calls to the parser/code generator */
  16533. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  16534. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  16535. u8 mayAbort; /* True if statement may throw an ABORT exception */
  16536. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  16537. u8 okConstFactor; /* OK to factor out constants */
  16538. u8 disableLookaside; /* Number of times lookaside has been disabled */
  16539. u8 nColCache; /* Number of entries in aColCache[] */
  16540. int nRangeReg; /* Size of the temporary register block */
  16541. int iRangeReg; /* First register in temporary register block */
  16542. int nErr; /* Number of errors seen */
  16543. int nTab; /* Number of previously allocated VDBE cursors */
  16544. int nMem; /* Number of memory cells used so far */
  16545. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  16546. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  16547. int iSelfTab; /* Table associated with an index on expr, or negative
  16548. ** of the base register during check-constraint eval */
  16549. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  16550. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  16551. int nLabel; /* Number of labels used */
  16552. int *aLabel; /* Space to hold the labels */
  16553. ExprList *pConstExpr;/* Constant expressions */
  16554. Token constraintName;/* Name of the constraint currently being parsed */
  16555. yDbMask writeMask; /* Start a write transaction on these databases */
  16556. yDbMask cookieMask; /* Bitmask of schema verified databases */
  16557. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  16558. int regRoot; /* Register holding root page number for new objects */
  16559. int nMaxArg; /* Max args passed to user function by sub-program */
  16560. #if SELECTTRACE_ENABLED
  16561. int nSelect; /* Number of SELECT statements seen */
  16562. #endif
  16563. #ifndef SQLITE_OMIT_SHARED_CACHE
  16564. int nTableLock; /* Number of locks in aTableLock */
  16565. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  16566. #endif
  16567. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  16568. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  16569. Table *pTriggerTab; /* Table triggers are being coded for */
  16570. int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */
  16571. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  16572. u32 oldmask; /* Mask of old.* columns referenced */
  16573. u32 newmask; /* Mask of new.* columns referenced */
  16574. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  16575. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  16576. u8 disableTriggers; /* True to disable triggers */
  16577. /**************************************************************************
  16578. ** Fields above must be initialized to zero. The fields that follow,
  16579. ** down to the beginning of the recursive section, do not need to be
  16580. ** initialized as they will be set before being used. The boundary is
  16581. ** determined by offsetof(Parse,aColCache).
  16582. **************************************************************************/
  16583. struct yColCache {
  16584. int iTable; /* Table cursor number */
  16585. i16 iColumn; /* Table column number */
  16586. u8 tempReg; /* iReg is a temp register that needs to be freed */
  16587. int iLevel; /* Nesting level */
  16588. int iReg; /* Reg with value of this column. 0 means none. */
  16589. int lru; /* Least recently used entry has the smallest value */
  16590. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  16591. int aTempReg[8]; /* Holding area for temporary registers */
  16592. Token sNameToken; /* Token with unqualified schema object name */
  16593. /************************************************************************
  16594. ** Above is constant between recursions. Below is reset before and after
  16595. ** each recursion. The boundary between these two regions is determined
  16596. ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
  16597. ** first field in the recursive region.
  16598. ************************************************************************/
  16599. Token sLastToken; /* The last token parsed */
  16600. ynVar nVar; /* Number of '?' variables seen in the SQL so far */
  16601. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  16602. u8 explain; /* True if the EXPLAIN flag is found on the query */
  16603. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16604. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  16605. int nVtabLock; /* Number of virtual tables to lock */
  16606. #endif
  16607. int nHeight; /* Expression tree height of current sub-select */
  16608. #ifndef SQLITE_OMIT_EXPLAIN
  16609. int iSelectId; /* ID of current select for EXPLAIN output */
  16610. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  16611. #endif
  16612. VList *pVList; /* Mapping between variable names and numbers */
  16613. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  16614. const char *zTail; /* All SQL text past the last semicolon parsed */
  16615. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  16616. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  16617. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  16618. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16619. Token sArg; /* Complete text of a module argument */
  16620. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  16621. #endif
  16622. Table *pZombieTab; /* List of Table objects to delete after code gen */
  16623. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  16624. With *pWith; /* Current WITH clause, or NULL */
  16625. With *pWithToFree; /* Free this WITH object at the end of the parse */
  16626. };
  16627. /*
  16628. ** Sizes and pointers of various parts of the Parse object.
  16629. */
  16630. #define PARSE_HDR_SZ offsetof(Parse,aColCache) /* Recursive part w/o aColCache*/
  16631. #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
  16632. #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
  16633. #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
  16634. /*
  16635. ** Return true if currently inside an sqlite3_declare_vtab() call.
  16636. */
  16637. #ifdef SQLITE_OMIT_VIRTUALTABLE
  16638. #define IN_DECLARE_VTAB 0
  16639. #else
  16640. #define IN_DECLARE_VTAB (pParse->declareVtab)
  16641. #endif
  16642. /*
  16643. ** An instance of the following structure can be declared on a stack and used
  16644. ** to save the Parse.zAuthContext value so that it can be restored later.
  16645. */
  16646. struct AuthContext {
  16647. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  16648. Parse *pParse; /* The Parse structure */
  16649. };
  16650. /*
  16651. ** Bitfield flags for P5 value in various opcodes.
  16652. **
  16653. ** Value constraints (enforced via assert()):
  16654. ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
  16655. ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
  16656. ** OPFLAG_BULKCSR == BTREE_BULKLOAD
  16657. ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
  16658. ** OPFLAG_FORDELETE == BTREE_FORDELETE
  16659. ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
  16660. ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
  16661. */
  16662. #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
  16663. /* Also used in P2 (not P5) of OP_Delete */
  16664. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  16665. #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
  16666. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  16667. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  16668. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  16669. #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
  16670. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  16671. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  16672. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  16673. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  16674. #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
  16675. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  16676. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  16677. #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
  16678. #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
  16679. #define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */
  16680. /*
  16681. * Each trigger present in the database schema is stored as an instance of
  16682. * struct Trigger.
  16683. *
  16684. * Pointers to instances of struct Trigger are stored in two ways.
  16685. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  16686. * database). This allows Trigger structures to be retrieved by name.
  16687. * 2. All triggers associated with a single table form a linked list, using the
  16688. * pNext member of struct Trigger. A pointer to the first element of the
  16689. * linked list is stored as the "pTrigger" member of the associated
  16690. * struct Table.
  16691. *
  16692. * The "step_list" member points to the first element of a linked list
  16693. * containing the SQL statements specified as the trigger program.
  16694. */
  16695. struct Trigger {
  16696. char *zName; /* The name of the trigger */
  16697. char *table; /* The table or view to which the trigger applies */
  16698. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  16699. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  16700. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  16701. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  16702. the <column-list> is stored here */
  16703. Schema *pSchema; /* Schema containing the trigger */
  16704. Schema *pTabSchema; /* Schema containing the table */
  16705. TriggerStep *step_list; /* Link list of trigger program steps */
  16706. Trigger *pNext; /* Next trigger associated with the table */
  16707. };
  16708. /*
  16709. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  16710. ** determine which.
  16711. **
  16712. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  16713. ** In that cases, the constants below can be ORed together.
  16714. */
  16715. #define TRIGGER_BEFORE 1
  16716. #define TRIGGER_AFTER 2
  16717. /*
  16718. * An instance of struct TriggerStep is used to store a single SQL statement
  16719. * that is a part of a trigger-program.
  16720. *
  16721. * Instances of struct TriggerStep are stored in a singly linked list (linked
  16722. * using the "pNext" member) referenced by the "step_list" member of the
  16723. * associated struct Trigger instance. The first element of the linked list is
  16724. * the first step of the trigger-program.
  16725. *
  16726. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  16727. * "SELECT" statement. The meanings of the other members is determined by the
  16728. * value of "op" as follows:
  16729. *
  16730. * (op == TK_INSERT)
  16731. * orconf -> stores the ON CONFLICT algorithm
  16732. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  16733. * this stores a pointer to the SELECT statement. Otherwise NULL.
  16734. * zTarget -> Dequoted name of the table to insert into.
  16735. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  16736. * this stores values to be inserted. Otherwise NULL.
  16737. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  16738. * statement, then this stores the column-names to be
  16739. * inserted into.
  16740. *
  16741. * (op == TK_DELETE)
  16742. * zTarget -> Dequoted name of the table to delete from.
  16743. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  16744. * Otherwise NULL.
  16745. *
  16746. * (op == TK_UPDATE)
  16747. * zTarget -> Dequoted name of the table to update.
  16748. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  16749. * Otherwise NULL.
  16750. * pExprList -> A list of the columns to update and the expressions to update
  16751. * them to. See sqlite3Update() documentation of "pChanges"
  16752. * argument.
  16753. *
  16754. */
  16755. struct TriggerStep {
  16756. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  16757. u8 orconf; /* OE_Rollback etc. */
  16758. Trigger *pTrig; /* The trigger that this step is a part of */
  16759. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  16760. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  16761. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  16762. ExprList *pExprList; /* SET clause for UPDATE. */
  16763. IdList *pIdList; /* Column names for INSERT */
  16764. char *zSpan; /* Original SQL text of this command */
  16765. TriggerStep *pNext; /* Next in the link-list */
  16766. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  16767. };
  16768. /*
  16769. ** The following structure contains information used by the sqliteFix...
  16770. ** routines as they walk the parse tree to make database references
  16771. ** explicit.
  16772. */
  16773. typedef struct DbFixer DbFixer;
  16774. struct DbFixer {
  16775. Parse *pParse; /* The parsing context. Error messages written here */
  16776. Schema *pSchema; /* Fix items to this schema */
  16777. int bVarOnly; /* Check for variable references only */
  16778. const char *zDb; /* Make sure all objects are contained in this database */
  16779. const char *zType; /* Type of the container - used for error messages */
  16780. const Token *pName; /* Name of the container - used for error messages */
  16781. };
  16782. /*
  16783. ** An objected used to accumulate the text of a string where we
  16784. ** do not necessarily know how big the string will be in the end.
  16785. */
  16786. struct StrAccum {
  16787. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  16788. char *zText; /* The string collected so far */
  16789. u32 nAlloc; /* Amount of space allocated in zText */
  16790. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  16791. u32 nChar; /* Length of the string so far */
  16792. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  16793. u8 printfFlags; /* SQLITE_PRINTF flags below */
  16794. };
  16795. #define STRACCUM_NOMEM 1
  16796. #define STRACCUM_TOOBIG 2
  16797. #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
  16798. #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
  16799. #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
  16800. #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
  16801. /*
  16802. ** A pointer to this structure is used to communicate information
  16803. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  16804. */
  16805. typedef struct {
  16806. sqlite3 *db; /* The database being initialized */
  16807. char **pzErrMsg; /* Error message stored here */
  16808. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  16809. int rc; /* Result code stored here */
  16810. } InitData;
  16811. /*
  16812. ** Structure containing global configuration data for the SQLite library.
  16813. **
  16814. ** This structure also contains some state information.
  16815. */
  16816. struct Sqlite3Config {
  16817. int bMemstat; /* True to enable memory status */
  16818. int bCoreMutex; /* True to enable core mutexing */
  16819. int bFullMutex; /* True to enable full mutexing */
  16820. int bOpenUri; /* True to interpret filenames as URIs */
  16821. int bUseCis; /* Use covering indices for full-scans */
  16822. int bSmallMalloc; /* Avoid large memory allocations if true */
  16823. int mxStrlen; /* Maximum string length */
  16824. int neverCorrupt; /* Database is always well-formed */
  16825. int szLookaside; /* Default lookaside buffer size */
  16826. int nLookaside; /* Default lookaside buffer count */
  16827. int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
  16828. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  16829. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  16830. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  16831. void *pHeap; /* Heap storage space */
  16832. int nHeap; /* Size of pHeap[] */
  16833. int mnReq, mxReq; /* Min and max heap requests sizes */
  16834. sqlite3_int64 szMmap; /* mmap() space per open file */
  16835. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  16836. void *pPage; /* Page cache memory */
  16837. int szPage; /* Size of each page in pPage[] */
  16838. int nPage; /* Number of pages in pPage[] */
  16839. int mxParserStack; /* maximum depth of the parser stack */
  16840. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  16841. u32 szPma; /* Maximum Sorter PMA size */
  16842. /* The above might be initialized to non-zero. The following need to always
  16843. ** initially be zero, however. */
  16844. int isInit; /* True after initialization has finished */
  16845. int inProgress; /* True while initialization in progress */
  16846. int isMutexInit; /* True after mutexes are initialized */
  16847. int isMallocInit; /* True after malloc is initialized */
  16848. int isPCacheInit; /* True after malloc is initialized */
  16849. int nRefInitMutex; /* Number of users of pInitMutex */
  16850. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  16851. void (*xLog)(void*,int,const char*); /* Function for logging */
  16852. void *pLogArg; /* First argument to xLog() */
  16853. #ifdef SQLITE_ENABLE_SQLLOG
  16854. void(*xSqllog)(void*,sqlite3*,const char*, int);
  16855. void *pSqllogArg;
  16856. #endif
  16857. #ifdef SQLITE_VDBE_COVERAGE
  16858. /* The following callback (if not NULL) is invoked on every VDBE branch
  16859. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  16860. */
  16861. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  16862. void *pVdbeBranchArg; /* 1st argument */
  16863. #endif
  16864. #ifndef SQLITE_UNTESTABLE
  16865. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  16866. #endif
  16867. int bLocaltimeFault; /* True to fail localtime() calls */
  16868. int iOnceResetThreshold; /* When to reset OP_Once counters */
  16869. };
  16870. /*
  16871. ** This macro is used inside of assert() statements to indicate that
  16872. ** the assert is only valid on a well-formed database. Instead of:
  16873. **
  16874. ** assert( X );
  16875. **
  16876. ** One writes:
  16877. **
  16878. ** assert( X || CORRUPT_DB );
  16879. **
  16880. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  16881. ** that the database is definitely corrupt, only that it might be corrupt.
  16882. ** For most test cases, CORRUPT_DB is set to false using a special
  16883. ** sqlite3_test_control(). This enables assert() statements to prove
  16884. ** things that are always true for well-formed databases.
  16885. */
  16886. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  16887. /*
  16888. ** Context pointer passed down through the tree-walk.
  16889. */
  16890. struct Walker {
  16891. Parse *pParse; /* Parser context. */
  16892. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  16893. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  16894. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  16895. int walkerDepth; /* Number of subqueries */
  16896. u8 eCode; /* A small processing code */
  16897. union { /* Extra data for callback */
  16898. NameContext *pNC; /* Naming context */
  16899. int n; /* A counter */
  16900. int iCur; /* A cursor number */
  16901. SrcList *pSrcList; /* FROM clause */
  16902. struct SrcCount *pSrcCount; /* Counting column references */
  16903. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  16904. int *aiCol; /* array of column indexes */
  16905. struct IdxCover *pIdxCover; /* Check for index coverage */
  16906. struct IdxExprTrans *pIdxTrans; /* Convert idxed expr to column */
  16907. ExprList *pGroupBy; /* GROUP BY clause */
  16908. Select *pSelect; /* HAVING to WHERE clause ctx */
  16909. } u;
  16910. };
  16911. /* Forward declarations */
  16912. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  16913. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  16914. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  16915. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  16916. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  16917. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  16918. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
  16919. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
  16920. #ifdef SQLITE_DEBUG
  16921. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
  16922. #endif
  16923. /*
  16924. ** Return code from the parse-tree walking primitives and their
  16925. ** callbacks.
  16926. */
  16927. #define WRC_Continue 0 /* Continue down into children */
  16928. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  16929. #define WRC_Abort 2 /* Abandon the tree walk */
  16930. /*
  16931. ** An instance of this structure represents a set of one or more CTEs
  16932. ** (common table expressions) created by a single WITH clause.
  16933. */
  16934. struct With {
  16935. int nCte; /* Number of CTEs in the WITH clause */
  16936. With *pOuter; /* Containing WITH clause, or NULL */
  16937. struct Cte { /* For each CTE in the WITH clause.... */
  16938. char *zName; /* Name of this CTE */
  16939. ExprList *pCols; /* List of explicit column names, or NULL */
  16940. Select *pSelect; /* The definition of this CTE */
  16941. const char *zCteErr; /* Error message for circular references */
  16942. } a[1];
  16943. };
  16944. #ifdef SQLITE_DEBUG
  16945. /*
  16946. ** An instance of the TreeView object is used for printing the content of
  16947. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  16948. */
  16949. struct TreeView {
  16950. int iLevel; /* Which level of the tree we are on */
  16951. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  16952. };
  16953. #endif /* SQLITE_DEBUG */
  16954. /*
  16955. ** Assuming zIn points to the first byte of a UTF-8 character,
  16956. ** advance zIn to point to the first byte of the next UTF-8 character.
  16957. */
  16958. #define SQLITE_SKIP_UTF8(zIn) { \
  16959. if( (*(zIn++))>=0xc0 ){ \
  16960. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  16961. } \
  16962. }
  16963. /*
  16964. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  16965. ** the same name but without the _BKPT suffix. These macros invoke
  16966. ** routines that report the line-number on which the error originated
  16967. ** using sqlite3_log(). The routines also provide a convenient place
  16968. ** to set a debugger breakpoint.
  16969. */
  16970. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
  16971. SQLITE_PRIVATE int sqlite3CorruptError(int);
  16972. SQLITE_PRIVATE int sqlite3MisuseError(int);
  16973. SQLITE_PRIVATE int sqlite3CantopenError(int);
  16974. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  16975. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  16976. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  16977. #ifdef SQLITE_DEBUG
  16978. SQLITE_PRIVATE int sqlite3NomemError(int);
  16979. SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
  16980. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
  16981. # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
  16982. # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
  16983. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
  16984. #else
  16985. # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
  16986. # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
  16987. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
  16988. #endif
  16989. /*
  16990. ** FTS3 and FTS4 both require virtual table support
  16991. */
  16992. #if defined(SQLITE_OMIT_VIRTUALTABLE)
  16993. # undef SQLITE_ENABLE_FTS3
  16994. # undef SQLITE_ENABLE_FTS4
  16995. #endif
  16996. /*
  16997. ** FTS4 is really an extension for FTS3. It is enabled using the
  16998. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  16999. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  17000. */
  17001. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  17002. # define SQLITE_ENABLE_FTS3 1
  17003. #endif
  17004. /*
  17005. ** The ctype.h header is needed for non-ASCII systems. It is also
  17006. ** needed by FTS3 when FTS3 is included in the amalgamation.
  17007. */
  17008. #if !defined(SQLITE_ASCII) || \
  17009. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  17010. # include <ctype.h>
  17011. #endif
  17012. /*
  17013. ** The following macros mimic the standard library functions toupper(),
  17014. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  17015. ** sqlite versions only work for ASCII characters, regardless of locale.
  17016. */
  17017. #ifdef SQLITE_ASCII
  17018. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  17019. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  17020. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  17021. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  17022. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  17023. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  17024. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  17025. # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
  17026. #else
  17027. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  17028. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  17029. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  17030. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  17031. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  17032. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  17033. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  17034. # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
  17035. #endif
  17036. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  17037. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  17038. #endif
  17039. /*
  17040. ** Internal function prototypes
  17041. */
  17042. SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
  17043. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  17044. SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
  17045. #define sqlite3StrNICmp sqlite3_strnicmp
  17046. SQLITE_PRIVATE int sqlite3MallocInit(void);
  17047. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  17048. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  17049. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  17050. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  17051. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  17052. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
  17053. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  17054. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  17055. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
  17056. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  17057. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  17058. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  17059. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  17060. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
  17061. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  17062. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  17063. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  17064. SQLITE_PRIVATE void sqlite3PageFree(void*);
  17065. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  17066. #ifndef SQLITE_UNTESTABLE
  17067. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  17068. #endif
  17069. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  17070. /*
  17071. ** On systems with ample stack space and that support alloca(), make
  17072. ** use of alloca() to obtain space for large automatic objects. By default,
  17073. ** obtain space from malloc().
  17074. **
  17075. ** The alloca() routine never returns NULL. This will cause code paths
  17076. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  17077. */
  17078. #ifdef SQLITE_USE_ALLOCA
  17079. # define sqlite3StackAllocRaw(D,N) alloca(N)
  17080. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  17081. # define sqlite3StackFree(D,P)
  17082. #else
  17083. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  17084. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  17085. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  17086. #endif
  17087. /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
  17088. ** are, disable MEMSYS3
  17089. */
  17090. #ifdef SQLITE_ENABLE_MEMSYS5
  17091. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  17092. #undef SQLITE_ENABLE_MEMSYS3
  17093. #endif
  17094. #ifdef SQLITE_ENABLE_MEMSYS3
  17095. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  17096. #endif
  17097. #ifndef SQLITE_MUTEX_OMIT
  17098. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  17099. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  17100. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  17101. SQLITE_PRIVATE int sqlite3MutexInit(void);
  17102. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  17103. #endif
  17104. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  17105. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  17106. #else
  17107. # define sqlite3MemoryBarrier()
  17108. #endif
  17109. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  17110. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  17111. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  17112. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  17113. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
  17114. /* Access to mutexes used by sqlite3_status() */
  17115. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  17116. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  17117. #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
  17118. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
  17119. #else
  17120. # define sqlite3MutexWarnOnContention(x)
  17121. #endif
  17122. #ifndef SQLITE_OMIT_FLOATING_POINT
  17123. SQLITE_PRIVATE int sqlite3IsNaN(double);
  17124. #else
  17125. # define sqlite3IsNaN(X) 0
  17126. #endif
  17127. /*
  17128. ** An instance of the following structure holds information about SQL
  17129. ** functions arguments that are the parameters to the printf() function.
  17130. */
  17131. struct PrintfArguments {
  17132. int nArg; /* Total number of arguments */
  17133. int nUsed; /* Number of arguments used so far */
  17134. sqlite3_value **apArg; /* The argument values */
  17135. };
  17136. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
  17137. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  17138. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  17139. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  17140. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  17141. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  17142. #endif
  17143. #if defined(SQLITE_TEST)
  17144. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  17145. #endif
  17146. #if defined(SQLITE_DEBUG)
  17147. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  17148. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
  17149. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  17150. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  17151. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  17152. #endif
  17153. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  17154. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  17155. SQLITE_PRIVATE void sqlite3Dequote(char*);
  17156. SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
  17157. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  17158. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  17159. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  17160. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  17161. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  17162. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  17163. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  17164. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  17165. #ifdef SQLITE_DEBUG
  17166. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
  17167. #endif
  17168. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  17169. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  17170. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  17171. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
  17172. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
  17173. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  17174. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  17175. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
  17176. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  17177. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  17178. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
  17179. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int);
  17180. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  17181. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
  17182. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  17183. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  17184. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  17185. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  17186. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  17187. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17188. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
  17189. #endif
  17190. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  17191. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  17192. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  17193. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  17194. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  17195. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  17196. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*);
  17197. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  17198. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  17199. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  17200. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  17201. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  17202. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  17203. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  17204. #else
  17205. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  17206. #endif
  17207. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
  17208. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  17209. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  17210. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  17211. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
  17212. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  17213. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  17214. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  17215. sqlite3_vfs**,char**,char **);
  17216. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  17217. #ifdef SQLITE_UNTESTABLE
  17218. # define sqlite3FaultSim(X) SQLITE_OK
  17219. #else
  17220. SQLITE_PRIVATE int sqlite3FaultSim(int);
  17221. #endif
  17222. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  17223. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  17224. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  17225. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  17226. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  17227. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  17228. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  17229. #ifndef SQLITE_UNTESTABLE
  17230. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  17231. #endif
  17232. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  17233. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  17234. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  17235. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  17236. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  17237. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  17238. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  17239. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  17240. #else
  17241. # define sqlite3ViewGetColumnNames(A,B) 0
  17242. #endif
  17243. #if SQLITE_MAX_ATTACHED>30
  17244. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  17245. #endif
  17246. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  17247. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  17248. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  17249. #ifndef SQLITE_OMIT_AUTOINCREMENT
  17250. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  17251. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  17252. #else
  17253. # define sqlite3AutoincrementBegin(X)
  17254. # define sqlite3AutoincrementEnd(X)
  17255. #endif
  17256. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  17257. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  17258. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  17259. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  17260. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  17261. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  17262. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  17263. Token*, Select*, Expr*, IdList*);
  17264. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  17265. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  17266. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  17267. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  17268. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  17269. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  17270. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  17271. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  17272. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  17273. Expr*, int, int, u8);
  17274. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  17275. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  17276. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  17277. Expr*,ExprList*,u32,Expr*);
  17278. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  17279. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  17280. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  17281. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  17282. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  17283. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
  17284. #endif
  17285. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
  17286. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*);
  17287. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  17288. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  17289. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
  17290. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  17291. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  17292. SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo*);
  17293. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  17294. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  17295. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  17296. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  17297. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  17298. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  17299. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  17300. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  17301. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  17302. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse*, Table*, int, int, int);
  17303. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  17304. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  17305. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  17306. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  17307. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  17308. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  17309. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  17310. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  17311. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  17312. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  17313. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  17314. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(Parse*, Expr*, int);
  17315. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  17316. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  17317. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  17318. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  17319. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  17320. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  17321. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  17322. #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
  17323. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  17324. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  17325. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  17326. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  17327. #define LOCATE_VIEW 0x01
  17328. #define LOCATE_NOERR 0x02
  17329. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
  17330. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
  17331. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  17332. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  17333. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  17334. SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*);
  17335. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int);
  17336. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  17337. SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
  17338. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
  17339. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  17340. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
  17341. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
  17342. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  17343. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  17344. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
  17345. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  17346. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  17347. #ifndef SQLITE_UNTESTABLE
  17348. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  17349. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  17350. #endif
  17351. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  17352. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  17353. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  17354. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  17355. SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
  17356. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  17357. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  17358. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  17359. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
  17360. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
  17361. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  17362. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  17363. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  17364. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
  17365. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  17366. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  17367. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  17368. #endif
  17369. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  17370. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  17371. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  17372. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  17373. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  17374. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  17375. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  17376. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  17377. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  17378. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  17379. u8,u8,int,int*,int*);
  17380. #ifdef SQLITE_ENABLE_NULL_TRIM
  17381. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
  17382. #else
  17383. # define sqlite3SetMakeRecordP5(A,B)
  17384. #endif
  17385. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  17386. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  17387. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  17388. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  17389. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  17390. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  17391. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  17392. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  17393. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  17394. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  17395. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  17396. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  17397. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  17398. #if SELECTTRACE_ENABLED
  17399. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  17400. #else
  17401. # define sqlite3SelectSetName(A,B)
  17402. #endif
  17403. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
  17404. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
  17405. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
  17406. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  17407. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
  17408. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  17409. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  17410. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  17411. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  17412. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
  17413. #endif
  17414. #ifndef SQLITE_OMIT_TRIGGER
  17415. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  17416. Expr*,int, int);
  17417. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  17418. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  17419. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  17420. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  17421. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  17422. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  17423. int, int, int);
  17424. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  17425. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  17426. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  17427. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
  17428. const char*,const char*);
  17429. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  17430. Select*,u8,const char*,const char*);
  17431. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8,
  17432. const char*,const char*);
  17433. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*,
  17434. const char*,const char*);
  17435. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  17436. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  17437. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  17438. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  17439. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  17440. #else
  17441. # define sqlite3TriggersExist(B,C,D,E,F) 0
  17442. # define sqlite3DeleteTrigger(A,B)
  17443. # define sqlite3DropTriggerPtr(A,B)
  17444. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  17445. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  17446. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  17447. # define sqlite3TriggerList(X, Y) 0
  17448. # define sqlite3ParseToplevel(p) p
  17449. # define sqlite3IsToplevel(p) 1
  17450. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  17451. #endif
  17452. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  17453. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  17454. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  17455. #ifndef SQLITE_OMIT_AUTHORIZATION
  17456. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  17457. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  17458. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  17459. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  17460. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  17461. #else
  17462. # define sqlite3AuthRead(a,b,c,d)
  17463. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  17464. # define sqlite3AuthContextPush(a,b,c)
  17465. # define sqlite3AuthContextPop(a) ((void)(a))
  17466. #endif
  17467. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  17468. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  17469. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  17470. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  17471. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  17472. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  17473. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  17474. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  17475. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  17476. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  17477. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  17478. #ifndef SQLITE_OMIT_UTF16
  17479. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  17480. #endif
  17481. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  17482. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  17483. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  17484. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  17485. #ifndef SQLITE_OMIT_VIRTUALTABLE
  17486. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  17487. #endif
  17488. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  17489. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  17490. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  17491. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  17492. #endif
  17493. SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
  17494. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
  17495. SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
  17496. /*
  17497. ** Routines to read and write variable-length integers. These used to
  17498. ** be defined locally, but now we use the varint routines in the util.c
  17499. ** file.
  17500. */
  17501. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  17502. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  17503. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  17504. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  17505. /*
  17506. ** The common case is for a varint to be a single byte. They following
  17507. ** macros handle the common case without a procedure call, but then call
  17508. ** the procedure for larger varints.
  17509. */
  17510. #define getVarint32(A,B) \
  17511. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  17512. #define putVarint32(A,B) \
  17513. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  17514. sqlite3PutVarint((A),(B)))
  17515. #define getVarint sqlite3GetVarint
  17516. #define putVarint sqlite3PutVarint
  17517. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  17518. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  17519. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  17520. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  17521. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
  17522. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  17523. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  17524. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  17525. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  17526. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  17527. SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
  17528. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  17529. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  17530. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  17531. #if defined(SQLITE_NEED_ERR_NAME)
  17532. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  17533. #endif
  17534. #ifdef SQLITE_ENABLE_DESERIALIZE
  17535. SQLITE_PRIVATE int sqlite3MemdbInit(void);
  17536. #endif
  17537. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  17538. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  17539. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  17540. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  17541. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  17542. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr);
  17543. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,Expr*,Expr*);
  17544. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  17545. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  17546. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  17547. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  17548. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  17549. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  17550. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  17551. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  17552. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  17553. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  17554. #ifdef SQLITE_ENABLE_8_3_NAMES
  17555. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  17556. #else
  17557. # define sqlite3FileSuffix3(X,Y)
  17558. #endif
  17559. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  17560. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  17561. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  17562. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  17563. void(*)(void*));
  17564. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  17565. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  17566. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  17567. #ifndef SQLITE_OMIT_UTF16
  17568. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  17569. #endif
  17570. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  17571. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  17572. #ifndef SQLITE_AMALGAMATION
  17573. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  17574. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  17575. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  17576. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  17577. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  17578. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  17579. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  17580. #ifndef SQLITE_OMIT_WSD
  17581. SQLITE_PRIVATE int sqlite3PendingByte;
  17582. #endif
  17583. #endif
  17584. #ifdef VDBE_PROFILE
  17585. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
  17586. #endif
  17587. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  17588. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  17589. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  17590. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  17591. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  17592. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  17593. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  17594. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr *, int, int);
  17595. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  17596. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  17597. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  17598. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  17599. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  17600. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  17601. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  17602. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  17603. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  17604. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  17605. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  17606. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  17607. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  17608. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  17609. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*, sqlite3_file*);
  17610. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  17611. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  17612. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  17613. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  17614. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  17615. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  17616. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  17617. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  17618. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  17619. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  17620. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  17621. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  17622. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  17623. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  17624. #ifdef SQLITE_DEBUG
  17625. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  17626. #endif
  17627. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  17628. void (*)(sqlite3_context*,int,sqlite3_value **),
  17629. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  17630. FuncDestructor *pDestructor
  17631. );
  17632. SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
  17633. SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
  17634. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  17635. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  17636. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  17637. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  17638. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  17639. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
  17640. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  17641. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  17642. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  17643. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  17644. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  17645. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  17646. #ifndef SQLITE_OMIT_SUBQUERY
  17647. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
  17648. #else
  17649. # define sqlite3ExprCheckIN(x,y) SQLITE_OK
  17650. #endif
  17651. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  17652. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  17653. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  17654. Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
  17655. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  17656. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  17657. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  17658. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
  17659. #endif
  17660. /*
  17661. ** The interface to the LEMON-generated parser
  17662. */
  17663. #ifndef SQLITE_AMALGAMATION
  17664. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  17665. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  17666. #endif
  17667. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  17668. #ifdef YYTRACKMAXSTACKDEPTH
  17669. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  17670. #endif
  17671. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  17672. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  17673. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  17674. #else
  17675. # define sqlite3CloseExtensions(X)
  17676. #endif
  17677. #ifndef SQLITE_OMIT_SHARED_CACHE
  17678. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  17679. #else
  17680. #define sqlite3TableLock(v,w,x,y,z)
  17681. #endif
  17682. #ifdef SQLITE_TEST
  17683. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  17684. #endif
  17685. #ifdef SQLITE_OMIT_VIRTUALTABLE
  17686. # define sqlite3VtabClear(Y)
  17687. # define sqlite3VtabSync(X,Y) SQLITE_OK
  17688. # define sqlite3VtabRollback(X)
  17689. # define sqlite3VtabCommit(X)
  17690. # define sqlite3VtabInSync(db) 0
  17691. # define sqlite3VtabLock(X)
  17692. # define sqlite3VtabUnlock(X)
  17693. # define sqlite3VtabUnlockList(X)
  17694. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  17695. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  17696. #else
  17697. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  17698. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  17699. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  17700. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  17701. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  17702. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  17703. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  17704. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  17705. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  17706. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  17707. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  17708. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  17709. sqlite3*,
  17710. const char*,
  17711. const sqlite3_module*,
  17712. void*,
  17713. void(*)(void*)
  17714. );
  17715. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  17716. #endif
  17717. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  17718. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  17719. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  17720. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  17721. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  17722. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  17723. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  17724. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  17725. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  17726. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  17727. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  17728. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  17729. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  17730. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  17731. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  17732. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  17733. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  17734. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  17735. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  17736. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  17737. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  17738. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  17739. #ifndef SQLITE_OMIT_WAL
  17740. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  17741. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  17742. #endif
  17743. #ifndef SQLITE_OMIT_CTE
  17744. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  17745. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  17746. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  17747. #else
  17748. #define sqlite3WithPush(x,y,z)
  17749. #define sqlite3WithDelete(x,y)
  17750. #endif
  17751. /* Declarations for functions in fkey.c. All of these are replaced by
  17752. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  17753. ** key functionality is available. If OMIT_TRIGGER is defined but
  17754. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  17755. ** this case foreign keys are parsed, but no other functionality is
  17756. ** provided (enforcement of FK constraints requires the triggers sub-system).
  17757. */
  17758. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  17759. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  17760. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  17761. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  17762. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  17763. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  17764. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  17765. #else
  17766. #define sqlite3FkActions(a,b,c,d,e,f)
  17767. #define sqlite3FkCheck(a,b,c,d,e,f)
  17768. #define sqlite3FkDropTable(a,b,c)
  17769. #define sqlite3FkOldmask(a,b) 0
  17770. #define sqlite3FkRequired(a,b,c,d) 0
  17771. #define sqlite3FkReferences(a) 0
  17772. #endif
  17773. #ifndef SQLITE_OMIT_FOREIGN_KEY
  17774. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  17775. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  17776. #else
  17777. #define sqlite3FkDelete(a,b)
  17778. #define sqlite3FkLocateIndex(a,b,c,d,e)
  17779. #endif
  17780. /*
  17781. ** Available fault injectors. Should be numbered beginning with 0.
  17782. */
  17783. #define SQLITE_FAULTINJECTOR_MALLOC 0
  17784. #define SQLITE_FAULTINJECTOR_COUNT 1
  17785. /*
  17786. ** The interface to the code in fault.c used for identifying "benign"
  17787. ** malloc failures. This is only present if SQLITE_UNTESTABLE
  17788. ** is not defined.
  17789. */
  17790. #ifndef SQLITE_UNTESTABLE
  17791. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  17792. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  17793. #else
  17794. #define sqlite3BeginBenignMalloc()
  17795. #define sqlite3EndBenignMalloc()
  17796. #endif
  17797. /*
  17798. ** Allowed return values from sqlite3FindInIndex()
  17799. */
  17800. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  17801. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  17802. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  17803. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  17804. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  17805. /*
  17806. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  17807. */
  17808. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  17809. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  17810. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  17811. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*);
  17812. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  17813. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  17814. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  17815. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  17816. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  17817. #endif
  17818. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
  17819. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  17820. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  17821. #if SQLITE_MAX_EXPR_DEPTH>0
  17822. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  17823. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  17824. #else
  17825. #define sqlite3SelectExprHeight(x) 0
  17826. #define sqlite3ExprCheckHeight(x,y)
  17827. #endif
  17828. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  17829. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  17830. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  17831. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  17832. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  17833. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  17834. #else
  17835. #define sqlite3ConnectionBlocked(x,y)
  17836. #define sqlite3ConnectionUnlocked(x)
  17837. #define sqlite3ConnectionClosed(x)
  17838. #endif
  17839. #ifdef SQLITE_DEBUG
  17840. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  17841. #endif
  17842. #if defined(YYCOVERAGE)
  17843. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE*);
  17844. #endif
  17845. /*
  17846. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  17847. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  17848. ** print I/O tracing messages.
  17849. */
  17850. #ifdef SQLITE_ENABLE_IOTRACE
  17851. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  17852. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  17853. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  17854. #else
  17855. # define IOTRACE(A)
  17856. # define sqlite3VdbeIOTraceSql(X)
  17857. #endif
  17858. /*
  17859. ** These routines are available for the mem2.c debugging memory allocator
  17860. ** only. They are used to verify that different "types" of memory
  17861. ** allocations are properly tracked by the system.
  17862. **
  17863. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  17864. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  17865. ** a single bit set.
  17866. **
  17867. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  17868. ** argument match the type set by the previous sqlite3MemdebugSetType().
  17869. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  17870. **
  17871. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  17872. ** argument match the type set by the previous sqlite3MemdebugSetType().
  17873. **
  17874. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  17875. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  17876. ** it might have been allocated by lookaside, except the allocation was
  17877. ** too large or lookaside was already full. It is important to verify
  17878. ** that allocations that might have been satisfied by lookaside are not
  17879. ** passed back to non-lookaside free() routines. Asserts such as the
  17880. ** example above are placed on the non-lookaside free() routines to verify
  17881. ** this constraint.
  17882. **
  17883. ** All of this is no-op for a production build. It only comes into
  17884. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  17885. */
  17886. #ifdef SQLITE_MEMDEBUG
  17887. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  17888. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  17889. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  17890. #else
  17891. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  17892. # define sqlite3MemdebugHasType(X,Y) 1
  17893. # define sqlite3MemdebugNoType(X,Y) 1
  17894. #endif
  17895. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  17896. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  17897. #define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
  17898. /*
  17899. ** Threading interface
  17900. */
  17901. #if SQLITE_MAX_WORKER_THREADS>0
  17902. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  17903. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  17904. #endif
  17905. #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
  17906. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
  17907. #endif
  17908. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  17909. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  17910. #endif
  17911. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
  17912. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
  17913. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
  17914. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
  17915. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
  17916. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  17917. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
  17918. #endif
  17919. #endif /* SQLITEINT_H */
  17920. /************** End of sqliteInt.h *******************************************/
  17921. /************** Begin file global.c ******************************************/
  17922. /*
  17923. ** 2008 June 13
  17924. **
  17925. ** The author disclaims copyright to this source code. In place of
  17926. ** a legal notice, here is a blessing:
  17927. **
  17928. ** May you do good and not evil.
  17929. ** May you find forgiveness for yourself and forgive others.
  17930. ** May you share freely, never taking more than you give.
  17931. **
  17932. *************************************************************************
  17933. **
  17934. ** This file contains definitions of global variables and constants.
  17935. */
  17936. /* #include "sqliteInt.h" */
  17937. /* An array to map all upper-case characters into their corresponding
  17938. ** lower-case character.
  17939. **
  17940. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  17941. ** handle case conversions for the UTF character set since the tables
  17942. ** involved are nearly as big or bigger than SQLite itself.
  17943. */
  17944. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  17945. #ifdef SQLITE_ASCII
  17946. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  17947. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  17948. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  17949. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  17950. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  17951. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  17952. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  17953. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  17954. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  17955. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  17956. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  17957. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  17958. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  17959. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  17960. 252,253,254,255
  17961. #endif
  17962. #ifdef SQLITE_EBCDIC
  17963. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  17964. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  17965. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  17966. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  17967. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  17968. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  17969. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  17970. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  17971. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  17972. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  17973. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  17974. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  17975. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  17976. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  17977. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  17978. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  17979. #endif
  17980. };
  17981. /*
  17982. ** The following 256 byte lookup table is used to support SQLites built-in
  17983. ** equivalents to the following standard library functions:
  17984. **
  17985. ** isspace() 0x01
  17986. ** isalpha() 0x02
  17987. ** isdigit() 0x04
  17988. ** isalnum() 0x06
  17989. ** isxdigit() 0x08
  17990. ** toupper() 0x20
  17991. ** SQLite identifier character 0x40
  17992. ** Quote character 0x80
  17993. **
  17994. ** Bit 0x20 is set if the mapped character requires translation to upper
  17995. ** case. i.e. if the character is a lower-case ASCII character.
  17996. ** If x is a lower-case ASCII character, then its upper-case equivalent
  17997. ** is (x - 0x20). Therefore toupper() can be implemented as:
  17998. **
  17999. ** (x & ~(map[x]&0x20))
  18000. **
  18001. ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
  18002. ** array. tolower() is used more often than toupper() by SQLite.
  18003. **
  18004. ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
  18005. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  18006. ** non-ASCII UTF character. Hence the test for whether or not a character is
  18007. ** part of an identifier is 0x46.
  18008. */
  18009. #ifdef SQLITE_ASCII
  18010. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  18011. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  18012. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  18013. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  18014. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  18015. 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
  18016. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  18017. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  18018. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  18019. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  18020. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  18021. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  18022. 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  18023. 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  18024. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  18025. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  18026. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  18027. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  18028. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  18029. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  18030. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  18031. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  18032. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  18033. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  18034. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  18035. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  18036. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  18037. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  18038. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  18039. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  18040. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  18041. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  18042. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  18043. };
  18044. #endif
  18045. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  18046. ** compatibility for legacy applications, the URI filename capability is
  18047. ** disabled by default.
  18048. **
  18049. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  18050. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  18051. **
  18052. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  18053. ** disabled. The default value may be changed by compiling with the
  18054. ** SQLITE_USE_URI symbol defined.
  18055. **
  18056. ** URI filenames are enabled by default if SQLITE_HAS_CODEC is
  18057. ** enabled.
  18058. */
  18059. #ifndef SQLITE_USE_URI
  18060. # ifdef SQLITE_HAS_CODEC
  18061. # define SQLITE_USE_URI 1
  18062. # else
  18063. # define SQLITE_USE_URI 0
  18064. # endif
  18065. #endif
  18066. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  18067. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  18068. ** that compile-time option is omitted.
  18069. */
  18070. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  18071. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  18072. #endif
  18073. /* The minimum PMA size is set to this value multiplied by the database
  18074. ** page size in bytes.
  18075. */
  18076. #ifndef SQLITE_SORTER_PMASZ
  18077. # define SQLITE_SORTER_PMASZ 250
  18078. #endif
  18079. /* Statement journals spill to disk when their size exceeds the following
  18080. ** threshold (in bytes). 0 means that statement journals are created and
  18081. ** written to disk immediately (the default behavior for SQLite versions
  18082. ** before 3.12.0). -1 means always keep the entire statement journal in
  18083. ** memory. (The statement journal is also always held entirely in memory
  18084. ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
  18085. ** setting.)
  18086. */
  18087. #ifndef SQLITE_STMTJRNL_SPILL
  18088. # define SQLITE_STMTJRNL_SPILL (64*1024)
  18089. #endif
  18090. /*
  18091. ** The default lookaside-configuration, the format "SZ,N". SZ is the
  18092. ** number of bytes in each lookaside slot (should be a multiple of 8)
  18093. ** and N is the number of slots. The lookaside-configuration can be
  18094. ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
  18095. ** or at run-time for an individual database connection using
  18096. ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
  18097. */
  18098. #ifndef SQLITE_DEFAULT_LOOKASIDE
  18099. # define SQLITE_DEFAULT_LOOKASIDE 1200,100
  18100. #endif
  18101. /*
  18102. ** The following singleton contains the global configuration for
  18103. ** the SQLite library.
  18104. */
  18105. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  18106. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  18107. 1, /* bCoreMutex */
  18108. SQLITE_THREADSAFE==1, /* bFullMutex */
  18109. SQLITE_USE_URI, /* bOpenUri */
  18110. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  18111. 0, /* bSmallMalloc */
  18112. 0x7ffffffe, /* mxStrlen */
  18113. 0, /* neverCorrupt */
  18114. SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
  18115. SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
  18116. {0,0,0,0,0,0,0,0}, /* m */
  18117. {0,0,0,0,0,0,0,0,0}, /* mutex */
  18118. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  18119. (void*)0, /* pHeap */
  18120. 0, /* nHeap */
  18121. 0, 0, /* mnHeap, mxHeap */
  18122. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  18123. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  18124. (void*)0, /* pPage */
  18125. 0, /* szPage */
  18126. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  18127. 0, /* mxParserStack */
  18128. 0, /* sharedCacheEnabled */
  18129. SQLITE_SORTER_PMASZ, /* szPma */
  18130. /* All the rest should always be initialized to zero */
  18131. 0, /* isInit */
  18132. 0, /* inProgress */
  18133. 0, /* isMutexInit */
  18134. 0, /* isMallocInit */
  18135. 0, /* isPCacheInit */
  18136. 0, /* nRefInitMutex */
  18137. 0, /* pInitMutex */
  18138. 0, /* xLog */
  18139. 0, /* pLogArg */
  18140. #ifdef SQLITE_ENABLE_SQLLOG
  18141. 0, /* xSqllog */
  18142. 0, /* pSqllogArg */
  18143. #endif
  18144. #ifdef SQLITE_VDBE_COVERAGE
  18145. 0, /* xVdbeBranch */
  18146. 0, /* pVbeBranchArg */
  18147. #endif
  18148. #ifndef SQLITE_UNTESTABLE
  18149. 0, /* xTestCallback */
  18150. #endif
  18151. 0, /* bLocaltimeFault */
  18152. 0x7ffffffe /* iOnceResetThreshold */
  18153. };
  18154. /*
  18155. ** Hash table for global functions - functions common to all
  18156. ** database connections. After initialization, this table is
  18157. ** read-only.
  18158. */
  18159. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  18160. /*
  18161. ** Constant tokens for values 0 and 1.
  18162. */
  18163. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  18164. { "0", 1 },
  18165. { "1", 1 }
  18166. };
  18167. #ifdef VDBE_PROFILE
  18168. /*
  18169. ** The following performance counter can be used in place of
  18170. ** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
  18171. */
  18172. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
  18173. #endif
  18174. /*
  18175. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  18176. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  18177. ** the database page that contains the pending byte. It never attempts
  18178. ** to read or write that page. The pending byte page is set aside
  18179. ** for use by the VFS layers as space for managing file locks.
  18180. **
  18181. ** During testing, it is often desirable to move the pending byte to
  18182. ** a different position in the file. This allows code that has to
  18183. ** deal with the pending byte to run on files that are much smaller
  18184. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  18185. ** move the pending byte.
  18186. **
  18187. ** IMPORTANT: Changing the pending byte to any value other than
  18188. ** 0x40000000 results in an incompatible database file format!
  18189. ** Changing the pending byte during operation will result in undefined
  18190. ** and incorrect behavior.
  18191. */
  18192. #ifndef SQLITE_OMIT_WSD
  18193. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  18194. #endif
  18195. /* #include "opcodes.h" */
  18196. /*
  18197. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  18198. ** created by mkopcodeh.awk during compilation. Data is obtained
  18199. ** from the comments following the "case OP_xxxx:" statements in
  18200. ** the vdbe.c file.
  18201. */
  18202. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  18203. /*
  18204. ** Name of the default collating sequence
  18205. */
  18206. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  18207. /************** End of global.c **********************************************/
  18208. /************** Begin file status.c ******************************************/
  18209. /*
  18210. ** 2008 June 18
  18211. **
  18212. ** The author disclaims copyright to this source code. In place of
  18213. ** a legal notice, here is a blessing:
  18214. **
  18215. ** May you do good and not evil.
  18216. ** May you find forgiveness for yourself and forgive others.
  18217. ** May you share freely, never taking more than you give.
  18218. **
  18219. *************************************************************************
  18220. **
  18221. ** This module implements the sqlite3_status() interface and related
  18222. ** functionality.
  18223. */
  18224. /* #include "sqliteInt.h" */
  18225. /************** Include vdbeInt.h in the middle of status.c ******************/
  18226. /************** Begin file vdbeInt.h *****************************************/
  18227. /*
  18228. ** 2003 September 6
  18229. **
  18230. ** The author disclaims copyright to this source code. In place of
  18231. ** a legal notice, here is a blessing:
  18232. **
  18233. ** May you do good and not evil.
  18234. ** May you find forgiveness for yourself and forgive others.
  18235. ** May you share freely, never taking more than you give.
  18236. **
  18237. *************************************************************************
  18238. ** This is the header file for information that is private to the
  18239. ** VDBE. This information used to all be at the top of the single
  18240. ** source code file "vdbe.c". When that file became too big (over
  18241. ** 6000 lines long) it was split up into several smaller files and
  18242. ** this header information was factored out.
  18243. */
  18244. #ifndef SQLITE_VDBEINT_H
  18245. #define SQLITE_VDBEINT_H
  18246. /*
  18247. ** The maximum number of times that a statement will try to reparse
  18248. ** itself before giving up and returning SQLITE_SCHEMA.
  18249. */
  18250. #ifndef SQLITE_MAX_SCHEMA_RETRY
  18251. # define SQLITE_MAX_SCHEMA_RETRY 50
  18252. #endif
  18253. /*
  18254. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  18255. ** "explain" P4 display logic is enabled.
  18256. */
  18257. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  18258. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  18259. # define VDBE_DISPLAY_P4 1
  18260. #else
  18261. # define VDBE_DISPLAY_P4 0
  18262. #endif
  18263. /*
  18264. ** SQL is translated into a sequence of instructions to be
  18265. ** executed by a virtual machine. Each instruction is an instance
  18266. ** of the following structure.
  18267. */
  18268. typedef struct VdbeOp Op;
  18269. /*
  18270. ** Boolean values
  18271. */
  18272. typedef unsigned Bool;
  18273. /* Opaque type used by code in vdbesort.c */
  18274. typedef struct VdbeSorter VdbeSorter;
  18275. /* Elements of the linked list at Vdbe.pAuxData */
  18276. typedef struct AuxData AuxData;
  18277. /* Types of VDBE cursors */
  18278. #define CURTYPE_BTREE 0
  18279. #define CURTYPE_SORTER 1
  18280. #define CURTYPE_VTAB 2
  18281. #define CURTYPE_PSEUDO 3
  18282. /*
  18283. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  18284. **
  18285. ** * A b-tree cursor
  18286. ** - In the main database or in an ephemeral database
  18287. ** - On either an index or a table
  18288. ** * A sorter
  18289. ** * A virtual table
  18290. ** * A one-row "pseudotable" stored in a single register
  18291. */
  18292. typedef struct VdbeCursor VdbeCursor;
  18293. struct VdbeCursor {
  18294. u8 eCurType; /* One of the CURTYPE_* values above */
  18295. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  18296. u8 nullRow; /* True if pointing to a row with no data */
  18297. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  18298. u8 isTable; /* True for rowid tables. False for indexes */
  18299. #ifdef SQLITE_DEBUG
  18300. u8 seekOp; /* Most recent seek operation on this cursor */
  18301. u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
  18302. #endif
  18303. Bool isEphemeral:1; /* True for an ephemeral table */
  18304. Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
  18305. Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
  18306. Btree *pBtx; /* Separate file holding temporary table */
  18307. i64 seqCount; /* Sequence counter */
  18308. int *aAltMap; /* Mapping from table to index column numbers */
  18309. /* Cached OP_Column parse information is only valid if cacheStatus matches
  18310. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  18311. ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
  18312. ** the cache is out of date. */
  18313. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  18314. int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
  18315. ** if there have been no prior seeks on the cursor. */
  18316. /* seekResult does not distinguish between "no seeks have ever occurred
  18317. ** on this cursor" and "the most recent seek was an exact match".
  18318. ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
  18319. /* When a new VdbeCursor is allocated, only the fields above are zeroed.
  18320. ** The fields that follow are uninitialized, and must be individually
  18321. ** initialized prior to first use. */
  18322. VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
  18323. union {
  18324. BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
  18325. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  18326. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  18327. } uc;
  18328. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  18329. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  18330. Pgno pgnoRoot; /* Root page of the open btree cursor */
  18331. i16 nField; /* Number of fields in the header */
  18332. u16 nHdrParsed; /* Number of header fields parsed so far */
  18333. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  18334. u32 *aOffset; /* Pointer to aType[nField] */
  18335. const u8 *aRow; /* Data for the current row, if all on one page */
  18336. u32 payloadSize; /* Total number of bytes in the record */
  18337. u32 szRow; /* Byte available in aRow */
  18338. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  18339. u64 maskUsed; /* Mask of columns used by this cursor */
  18340. #endif
  18341. /* 2*nField extra array elements allocated for aType[], beyond the one
  18342. ** static element declared in the structure. nField total array slots for
  18343. ** aType[] and nField+1 array slots for aOffset[] */
  18344. u32 aType[1]; /* Type values record decode. MUST BE LAST */
  18345. };
  18346. /*
  18347. ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
  18348. */
  18349. #define CACHE_STALE 0
  18350. /*
  18351. ** When a sub-program is executed (OP_Program), a structure of this type
  18352. ** is allocated to store the current value of the program counter, as
  18353. ** well as the current memory cell array and various other frame specific
  18354. ** values stored in the Vdbe struct. When the sub-program is finished,
  18355. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  18356. ** restoring the state of the VM to as it was before the sub-program
  18357. ** began executing.
  18358. **
  18359. ** The memory for a VdbeFrame object is allocated and managed by a memory
  18360. ** cell in the parent (calling) frame. When the memory cell is deleted or
  18361. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  18362. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  18363. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  18364. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  18365. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  18366. ** child frame are released.
  18367. **
  18368. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  18369. ** set to NULL if the currently executing frame is the main program.
  18370. */
  18371. typedef struct VdbeFrame VdbeFrame;
  18372. struct VdbeFrame {
  18373. Vdbe *v; /* VM this frame belongs to */
  18374. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  18375. Op *aOp; /* Program instructions for parent frame */
  18376. i64 *anExec; /* Event counters from parent frame */
  18377. Mem *aMem; /* Array of memory cells for parent frame */
  18378. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  18379. u8 *aOnce; /* Bitmask used by OP_Once */
  18380. void *token; /* Copy of SubProgram.token */
  18381. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  18382. AuxData *pAuxData; /* Linked list of auxdata allocations */
  18383. int nCursor; /* Number of entries in apCsr */
  18384. int pc; /* Program Counter in parent (calling) frame */
  18385. int nOp; /* Size of aOp array */
  18386. int nMem; /* Number of entries in aMem */
  18387. int nChildMem; /* Number of memory cells for child frame */
  18388. int nChildCsr; /* Number of cursors for child frame */
  18389. int nChange; /* Statement changes (Vdbe.nChange) */
  18390. int nDbChange; /* Value of db->nChange */
  18391. };
  18392. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  18393. /*
  18394. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  18395. ** structures. Each Mem struct may cache multiple representations (string,
  18396. ** integer etc.) of the same value.
  18397. */
  18398. struct sqlite3_value {
  18399. union MemValue {
  18400. double r; /* Real value used when MEM_Real is set in flags */
  18401. i64 i; /* Integer value used when MEM_Int is set in flags */
  18402. int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
  18403. const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
  18404. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  18405. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  18406. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  18407. } u;
  18408. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  18409. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  18410. u8 eSubtype; /* Subtype for this value */
  18411. int n; /* Number of characters in string value, excluding '\0' */
  18412. char *z; /* String or BLOB value */
  18413. /* ShallowCopy only needs to copy the information above */
  18414. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  18415. int szMalloc; /* Size of the zMalloc allocation */
  18416. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  18417. sqlite3 *db; /* The associated database connection */
  18418. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  18419. #ifdef SQLITE_DEBUG
  18420. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  18421. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  18422. #endif
  18423. };
  18424. /*
  18425. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  18426. ** follows.
  18427. */
  18428. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  18429. /* One or more of the following flags are set to indicate the validOK
  18430. ** representations of the value stored in the Mem struct.
  18431. **
  18432. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  18433. ** For a pointer type created using sqlite3_bind_pointer() or
  18434. ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
  18435. **
  18436. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  18437. ** Usually this is encoded in the same unicode encoding as the main
  18438. ** database (see below for exceptions). If the MEM_Term flag is also
  18439. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  18440. ** flags may coexist with the MEM_Str flag.
  18441. */
  18442. #define MEM_Null 0x0001 /* Value is NULL (or a pointer) */
  18443. #define MEM_Str 0x0002 /* Value is a string */
  18444. #define MEM_Int 0x0004 /* Value is an integer */
  18445. #define MEM_Real 0x0008 /* Value is a real number */
  18446. #define MEM_Blob 0x0010 /* Value is a BLOB */
  18447. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  18448. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  18449. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  18450. #define MEM_Undefined 0x0080 /* Value is undefined */
  18451. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  18452. #define MEM_TypeMask 0xc1ff /* Mask of type bits */
  18453. /* Whenever Mem contains a valid string or blob representation, one of
  18454. ** the following flags must be set to determine the memory management
  18455. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  18456. ** string is \000 or \u0000 terminated
  18457. */
  18458. #define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
  18459. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  18460. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  18461. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  18462. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  18463. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  18464. #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
  18465. #ifdef SQLITE_OMIT_INCRBLOB
  18466. #undef MEM_Zero
  18467. #define MEM_Zero 0x0000
  18468. #endif
  18469. /* Return TRUE if Mem X contains dynamically allocated content - anything
  18470. ** that needs to be deallocated to avoid a leak.
  18471. */
  18472. #define VdbeMemDynamic(X) \
  18473. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  18474. /*
  18475. ** Clear any existing type flags from a Mem and replace them with f
  18476. */
  18477. #define MemSetTypeFlag(p, f) \
  18478. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  18479. /*
  18480. ** Return true if a memory cell is not marked as invalid. This macro
  18481. ** is for use inside assert() statements only.
  18482. */
  18483. #ifdef SQLITE_DEBUG
  18484. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  18485. #endif
  18486. /*
  18487. ** Each auxiliary data pointer stored by a user defined function
  18488. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  18489. ** of this structure. All such structures associated with a single VM
  18490. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  18491. ** when the VM is halted (if not before).
  18492. */
  18493. struct AuxData {
  18494. int iAuxOp; /* Instruction number of OP_Function opcode */
  18495. int iAuxArg; /* Index of function argument. */
  18496. void *pAux; /* Aux data pointer */
  18497. void (*xDeleteAux)(void*); /* Destructor for the aux data */
  18498. AuxData *pNextAux; /* Next element in list */
  18499. };
  18500. /*
  18501. ** The "context" argument for an installable function. A pointer to an
  18502. ** instance of this structure is the first argument to the routines used
  18503. ** implement the SQL functions.
  18504. **
  18505. ** There is a typedef for this structure in sqlite.h. So all routines,
  18506. ** even the public interface to SQLite, can use a pointer to this structure.
  18507. ** But this file is the only place where the internal details of this
  18508. ** structure are known.
  18509. **
  18510. ** This structure is defined inside of vdbeInt.h because it uses substructures
  18511. ** (Mem) which are only defined there.
  18512. */
  18513. struct sqlite3_context {
  18514. Mem *pOut; /* The return value is stored here */
  18515. FuncDef *pFunc; /* Pointer to function information */
  18516. Mem *pMem; /* Memory cell used to store aggregate context */
  18517. Vdbe *pVdbe; /* The VM that owns this context */
  18518. int iOp; /* Instruction number of OP_Function */
  18519. int isError; /* Error code returned by the function. */
  18520. u8 skipFlag; /* Skip accumulator loading if true */
  18521. u8 argc; /* Number of arguments */
  18522. sqlite3_value *argv[1]; /* Argument set */
  18523. };
  18524. /* A bitfield type for use inside of structures. Always follow with :N where
  18525. ** N is the number of bits.
  18526. */
  18527. typedef unsigned bft; /* Bit Field Type */
  18528. typedef struct ScanStatus ScanStatus;
  18529. struct ScanStatus {
  18530. int addrExplain; /* OP_Explain for loop */
  18531. int addrLoop; /* Address of "loops" counter */
  18532. int addrVisit; /* Address of "rows visited" counter */
  18533. int iSelectID; /* The "Select-ID" for this loop */
  18534. LogEst nEst; /* Estimated output rows per loop */
  18535. char *zName; /* Name of table or index */
  18536. };
  18537. /*
  18538. ** An instance of the virtual machine. This structure contains the complete
  18539. ** state of the virtual machine.
  18540. **
  18541. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  18542. ** is really a pointer to an instance of this structure.
  18543. */
  18544. struct Vdbe {
  18545. sqlite3 *db; /* The database connection that owns this statement */
  18546. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  18547. Parse *pParse; /* Parsing context used to create this Vdbe */
  18548. ynVar nVar; /* Number of entries in aVar[] */
  18549. u32 magic; /* Magic number for sanity checking */
  18550. int nMem; /* Number of memory locations currently allocated */
  18551. int nCursor; /* Number of slots in apCsr[] */
  18552. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  18553. int pc; /* The program counter */
  18554. int rc; /* Value to return */
  18555. int nChange; /* Number of db changes made since last reset */
  18556. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  18557. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  18558. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  18559. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  18560. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  18561. /* When allocating a new Vdbe object, all of the fields below should be
  18562. ** initialized to zero or NULL */
  18563. Op *aOp; /* Space to hold the virtual machine's program */
  18564. Mem *aMem; /* The memory locations */
  18565. Mem **apArg; /* Arguments to currently executing user function */
  18566. Mem *aColName; /* Column names to return */
  18567. Mem *pResultSet; /* Pointer to an array of results */
  18568. char *zErrMsg; /* Error message written here */
  18569. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  18570. Mem *aVar; /* Values for the OP_Variable opcode. */
  18571. VList *pVList; /* Name of variables */
  18572. #ifndef SQLITE_OMIT_TRACE
  18573. i64 startTime; /* Time when query started - used for profiling */
  18574. #endif
  18575. int nOp; /* Number of instructions in the program */
  18576. #ifdef SQLITE_DEBUG
  18577. int rcApp; /* errcode set by sqlite3_result_error_code() */
  18578. #endif
  18579. u16 nResColumn; /* Number of columns in one row of the result set */
  18580. u8 errorAction; /* Recovery action to do in case of an error */
  18581. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  18582. u8 prepFlags; /* SQLITE_PREPARE_* flags */
  18583. bft expired:1; /* True if the VM needs to be recompiled */
  18584. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  18585. bft explain:2; /* True if EXPLAIN present on SQL command */
  18586. bft changeCntOn:1; /* True to update the change-counter */
  18587. bft runOnlyOnce:1; /* Automatically expire on reset */
  18588. bft usesStmtJournal:1; /* True if uses a statement journal */
  18589. bft readOnly:1; /* True for statements that do not write */
  18590. bft bIsReader:1; /* True for statements that read */
  18591. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  18592. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  18593. u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
  18594. char *zSql; /* Text of the SQL statement that generated this */
  18595. void *pFree; /* Free this when deleting the vdbe */
  18596. VdbeFrame *pFrame; /* Parent frame */
  18597. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  18598. int nFrame; /* Number of frames in pFrame list */
  18599. u32 expmask; /* Binding to these vars invalidates VM */
  18600. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  18601. AuxData *pAuxData; /* Linked list of auxdata allocations */
  18602. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  18603. i64 *anExec; /* Number of times each op has been executed */
  18604. int nScan; /* Entries in aScan[] */
  18605. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  18606. #endif
  18607. };
  18608. /*
  18609. ** The following are allowed values for Vdbe.magic
  18610. */
  18611. #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
  18612. #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
  18613. #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
  18614. #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
  18615. #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
  18616. /*
  18617. ** Structure used to store the context required by the
  18618. ** sqlite3_preupdate_*() API functions.
  18619. */
  18620. struct PreUpdate {
  18621. Vdbe *v;
  18622. VdbeCursor *pCsr; /* Cursor to read old values from */
  18623. int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
  18624. u8 *aRecord; /* old.* database record */
  18625. KeyInfo keyinfo;
  18626. UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
  18627. UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
  18628. int iNewReg; /* Register for new.* values */
  18629. i64 iKey1; /* First key value passed to hook */
  18630. i64 iKey2; /* Second key value passed to hook */
  18631. Mem *aNew; /* Array of new.* values */
  18632. Table *pTab; /* Schema object being upated */
  18633. Index *pPk; /* PK index if pTab is WITHOUT ROWID */
  18634. };
  18635. /*
  18636. ** Function prototypes
  18637. */
  18638. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  18639. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  18640. void sqliteVdbePopStack(Vdbe*,int);
  18641. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
  18642. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  18643. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  18644. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  18645. #endif
  18646. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  18647. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  18648. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
  18649. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  18650. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  18651. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
  18652. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  18653. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  18654. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  18655. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  18656. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  18657. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  18658. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  18659. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  18660. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  18661. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  18662. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  18663. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  18664. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  18665. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  18666. #ifdef SQLITE_OMIT_FLOATING_POINT
  18667. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  18668. #else
  18669. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  18670. #endif
  18671. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
  18672. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  18673. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  18674. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  18675. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  18676. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  18677. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  18678. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  18679. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  18680. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  18681. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
  18682. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  18683. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  18684. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  18685. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  18686. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
  18687. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  18688. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  18689. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  18690. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  18691. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  18692. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  18693. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  18694. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  18695. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  18696. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
  18697. #endif
  18698. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  18699. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  18700. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  18701. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  18702. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  18703. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
  18704. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  18705. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  18706. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  18707. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  18708. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  18709. #else
  18710. # define sqlite3VdbeEnter(X)
  18711. #endif
  18712. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  18713. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  18714. #else
  18715. # define sqlite3VdbeLeave(X)
  18716. #endif
  18717. #ifdef SQLITE_DEBUG
  18718. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  18719. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  18720. #endif
  18721. #ifndef SQLITE_OMIT_FOREIGN_KEY
  18722. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  18723. #else
  18724. # define sqlite3VdbeCheckFk(p,i) 0
  18725. #endif
  18726. #ifdef SQLITE_DEBUG
  18727. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  18728. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  18729. #endif
  18730. #ifndef SQLITE_OMIT_UTF16
  18731. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  18732. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  18733. #endif
  18734. #ifndef SQLITE_OMIT_INCRBLOB
  18735. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  18736. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  18737. #else
  18738. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  18739. #define ExpandBlob(P) SQLITE_OK
  18740. #endif
  18741. #endif /* !defined(SQLITE_VDBEINT_H) */
  18742. /************** End of vdbeInt.h *********************************************/
  18743. /************** Continuing where we left off in status.c *********************/
  18744. /*
  18745. ** Variables in which to record status information.
  18746. */
  18747. #if SQLITE_PTRSIZE>4
  18748. typedef sqlite3_int64 sqlite3StatValueType;
  18749. #else
  18750. typedef u32 sqlite3StatValueType;
  18751. #endif
  18752. typedef struct sqlite3StatType sqlite3StatType;
  18753. static SQLITE_WSD struct sqlite3StatType {
  18754. sqlite3StatValueType nowValue[10]; /* Current value */
  18755. sqlite3StatValueType mxValue[10]; /* Maximum value */
  18756. } sqlite3Stat = { {0,}, {0,} };
  18757. /*
  18758. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  18759. ** mutex, or by the pcache1 mutex. The following array determines which.
  18760. */
  18761. static const char statMutex[] = {
  18762. 0, /* SQLITE_STATUS_MEMORY_USED */
  18763. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  18764. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  18765. 0, /* SQLITE_STATUS_SCRATCH_USED */
  18766. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  18767. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  18768. 0, /* SQLITE_STATUS_PARSER_STACK */
  18769. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  18770. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  18771. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  18772. };
  18773. /* The "wsdStat" macro will resolve to the status information
  18774. ** state vector. If writable static data is unsupported on the target,
  18775. ** we have to locate the state vector at run-time. In the more common
  18776. ** case where writable static data is supported, wsdStat can refer directly
  18777. ** to the "sqlite3Stat" state vector declared above.
  18778. */
  18779. #ifdef SQLITE_OMIT_WSD
  18780. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  18781. # define wsdStat x[0]
  18782. #else
  18783. # define wsdStatInit
  18784. # define wsdStat sqlite3Stat
  18785. #endif
  18786. /*
  18787. ** Return the current value of a status parameter. The caller must
  18788. ** be holding the appropriate mutex.
  18789. */
  18790. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  18791. wsdStatInit;
  18792. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  18793. assert( op>=0 && op<ArraySize(statMutex) );
  18794. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  18795. : sqlite3MallocMutex()) );
  18796. return wsdStat.nowValue[op];
  18797. }
  18798. /*
  18799. ** Add N to the value of a status record. The caller must hold the
  18800. ** appropriate mutex. (Locking is checked by assert()).
  18801. **
  18802. ** The StatusUp() routine can accept positive or negative values for N.
  18803. ** The value of N is added to the current status value and the high-water
  18804. ** mark is adjusted if necessary.
  18805. **
  18806. ** The StatusDown() routine lowers the current value by N. The highwater
  18807. ** mark is unchanged. N must be non-negative for StatusDown().
  18808. */
  18809. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  18810. wsdStatInit;
  18811. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  18812. assert( op>=0 && op<ArraySize(statMutex) );
  18813. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  18814. : sqlite3MallocMutex()) );
  18815. wsdStat.nowValue[op] += N;
  18816. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  18817. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  18818. }
  18819. }
  18820. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  18821. wsdStatInit;
  18822. assert( N>=0 );
  18823. assert( op>=0 && op<ArraySize(statMutex) );
  18824. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  18825. : sqlite3MallocMutex()) );
  18826. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  18827. wsdStat.nowValue[op] -= N;
  18828. }
  18829. /*
  18830. ** Adjust the highwater mark if necessary.
  18831. ** The caller must hold the appropriate mutex.
  18832. */
  18833. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  18834. sqlite3StatValueType newValue;
  18835. wsdStatInit;
  18836. assert( X>=0 );
  18837. newValue = (sqlite3StatValueType)X;
  18838. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  18839. assert( op>=0 && op<ArraySize(statMutex) );
  18840. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  18841. : sqlite3MallocMutex()) );
  18842. assert( op==SQLITE_STATUS_MALLOC_SIZE
  18843. || op==SQLITE_STATUS_PAGECACHE_SIZE
  18844. || op==SQLITE_STATUS_PARSER_STACK );
  18845. if( newValue>wsdStat.mxValue[op] ){
  18846. wsdStat.mxValue[op] = newValue;
  18847. }
  18848. }
  18849. /*
  18850. ** Query status information.
  18851. */
  18852. SQLITE_API int sqlite3_status64(
  18853. int op,
  18854. sqlite3_int64 *pCurrent,
  18855. sqlite3_int64 *pHighwater,
  18856. int resetFlag
  18857. ){
  18858. sqlite3_mutex *pMutex;
  18859. wsdStatInit;
  18860. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  18861. return SQLITE_MISUSE_BKPT;
  18862. }
  18863. #ifdef SQLITE_ENABLE_API_ARMOR
  18864. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  18865. #endif
  18866. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  18867. sqlite3_mutex_enter(pMutex);
  18868. *pCurrent = wsdStat.nowValue[op];
  18869. *pHighwater = wsdStat.mxValue[op];
  18870. if( resetFlag ){
  18871. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  18872. }
  18873. sqlite3_mutex_leave(pMutex);
  18874. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  18875. return SQLITE_OK;
  18876. }
  18877. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  18878. sqlite3_int64 iCur = 0, iHwtr = 0;
  18879. int rc;
  18880. #ifdef SQLITE_ENABLE_API_ARMOR
  18881. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  18882. #endif
  18883. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  18884. if( rc==0 ){
  18885. *pCurrent = (int)iCur;
  18886. *pHighwater = (int)iHwtr;
  18887. }
  18888. return rc;
  18889. }
  18890. /*
  18891. ** Return the number of LookasideSlot elements on the linked list
  18892. */
  18893. static u32 countLookasideSlots(LookasideSlot *p){
  18894. u32 cnt = 0;
  18895. while( p ){
  18896. p = p->pNext;
  18897. cnt++;
  18898. }
  18899. return cnt;
  18900. }
  18901. /*
  18902. ** Count the number of slots of lookaside memory that are outstanding
  18903. */
  18904. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
  18905. u32 nInit = countLookasideSlots(db->lookaside.pInit);
  18906. u32 nFree = countLookasideSlots(db->lookaside.pFree);
  18907. if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
  18908. return db->lookaside.nSlot - (nInit+nFree);
  18909. }
  18910. /*
  18911. ** Query status information for a single database connection
  18912. */
  18913. SQLITE_API int sqlite3_db_status(
  18914. sqlite3 *db, /* The database connection whose status is desired */
  18915. int op, /* Status verb */
  18916. int *pCurrent, /* Write current value here */
  18917. int *pHighwater, /* Write high-water mark here */
  18918. int resetFlag /* Reset high-water mark if true */
  18919. ){
  18920. int rc = SQLITE_OK; /* Return code */
  18921. #ifdef SQLITE_ENABLE_API_ARMOR
  18922. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  18923. return SQLITE_MISUSE_BKPT;
  18924. }
  18925. #endif
  18926. sqlite3_mutex_enter(db->mutex);
  18927. switch( op ){
  18928. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  18929. *pCurrent = sqlite3LookasideUsed(db, pHighwater);
  18930. if( resetFlag ){
  18931. LookasideSlot *p = db->lookaside.pFree;
  18932. if( p ){
  18933. while( p->pNext ) p = p->pNext;
  18934. p->pNext = db->lookaside.pInit;
  18935. db->lookaside.pInit = db->lookaside.pFree;
  18936. db->lookaside.pFree = 0;
  18937. }
  18938. }
  18939. break;
  18940. }
  18941. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  18942. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  18943. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  18944. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  18945. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  18946. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  18947. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  18948. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  18949. *pCurrent = 0;
  18950. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  18951. if( resetFlag ){
  18952. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  18953. }
  18954. break;
  18955. }
  18956. /*
  18957. ** Return an approximation for the amount of memory currently used
  18958. ** by all pagers associated with the given database connection. The
  18959. ** highwater mark is meaningless and is returned as zero.
  18960. */
  18961. case SQLITE_DBSTATUS_CACHE_USED_SHARED:
  18962. case SQLITE_DBSTATUS_CACHE_USED: {
  18963. int totalUsed = 0;
  18964. int i;
  18965. sqlite3BtreeEnterAll(db);
  18966. for(i=0; i<db->nDb; i++){
  18967. Btree *pBt = db->aDb[i].pBt;
  18968. if( pBt ){
  18969. Pager *pPager = sqlite3BtreePager(pBt);
  18970. int nByte = sqlite3PagerMemUsed(pPager);
  18971. if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
  18972. nByte = nByte / sqlite3BtreeConnectionCount(pBt);
  18973. }
  18974. totalUsed += nByte;
  18975. }
  18976. }
  18977. sqlite3BtreeLeaveAll(db);
  18978. *pCurrent = totalUsed;
  18979. *pHighwater = 0;
  18980. break;
  18981. }
  18982. /*
  18983. ** *pCurrent gets an accurate estimate of the amount of memory used
  18984. ** to store the schema for all databases (main, temp, and any ATTACHed
  18985. ** databases. *pHighwater is set to zero.
  18986. */
  18987. case SQLITE_DBSTATUS_SCHEMA_USED: {
  18988. int i; /* Used to iterate through schemas */
  18989. int nByte = 0; /* Used to accumulate return value */
  18990. sqlite3BtreeEnterAll(db);
  18991. db->pnBytesFreed = &nByte;
  18992. for(i=0; i<db->nDb; i++){
  18993. Schema *pSchema = db->aDb[i].pSchema;
  18994. if( ALWAYS(pSchema!=0) ){
  18995. HashElem *p;
  18996. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  18997. pSchema->tblHash.count
  18998. + pSchema->trigHash.count
  18999. + pSchema->idxHash.count
  19000. + pSchema->fkeyHash.count
  19001. );
  19002. nByte += sqlite3_msize(pSchema->tblHash.ht);
  19003. nByte += sqlite3_msize(pSchema->trigHash.ht);
  19004. nByte += sqlite3_msize(pSchema->idxHash.ht);
  19005. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  19006. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  19007. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  19008. }
  19009. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  19010. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  19011. }
  19012. }
  19013. }
  19014. db->pnBytesFreed = 0;
  19015. sqlite3BtreeLeaveAll(db);
  19016. *pHighwater = 0;
  19017. *pCurrent = nByte;
  19018. break;
  19019. }
  19020. /*
  19021. ** *pCurrent gets an accurate estimate of the amount of memory used
  19022. ** to store all prepared statements.
  19023. ** *pHighwater is set to zero.
  19024. */
  19025. case SQLITE_DBSTATUS_STMT_USED: {
  19026. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  19027. int nByte = 0; /* Used to accumulate return value */
  19028. db->pnBytesFreed = &nByte;
  19029. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  19030. sqlite3VdbeClearObject(db, pVdbe);
  19031. sqlite3DbFree(db, pVdbe);
  19032. }
  19033. db->pnBytesFreed = 0;
  19034. *pHighwater = 0; /* IMP: R-64479-57858 */
  19035. *pCurrent = nByte;
  19036. break;
  19037. }
  19038. /*
  19039. ** Set *pCurrent to the total cache hits or misses encountered by all
  19040. ** pagers the database handle is connected to. *pHighwater is always set
  19041. ** to zero.
  19042. */
  19043. case SQLITE_DBSTATUS_CACHE_SPILL:
  19044. op = SQLITE_DBSTATUS_CACHE_WRITE+1;
  19045. /* Fall through into the next case */
  19046. case SQLITE_DBSTATUS_CACHE_HIT:
  19047. case SQLITE_DBSTATUS_CACHE_MISS:
  19048. case SQLITE_DBSTATUS_CACHE_WRITE:{
  19049. int i;
  19050. int nRet = 0;
  19051. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  19052. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  19053. for(i=0; i<db->nDb; i++){
  19054. if( db->aDb[i].pBt ){
  19055. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  19056. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  19057. }
  19058. }
  19059. *pHighwater = 0; /* IMP: R-42420-56072 */
  19060. /* IMP: R-54100-20147 */
  19061. /* IMP: R-29431-39229 */
  19062. *pCurrent = nRet;
  19063. break;
  19064. }
  19065. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  19066. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  19067. ** have been satisfied. The *pHighwater is always set to zero.
  19068. */
  19069. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  19070. *pHighwater = 0; /* IMP: R-11967-56545 */
  19071. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  19072. break;
  19073. }
  19074. default: {
  19075. rc = SQLITE_ERROR;
  19076. }
  19077. }
  19078. sqlite3_mutex_leave(db->mutex);
  19079. return rc;
  19080. }
  19081. /************** End of status.c **********************************************/
  19082. /************** Begin file date.c ********************************************/
  19083. /*
  19084. ** 2003 October 31
  19085. **
  19086. ** The author disclaims copyright to this source code. In place of
  19087. ** a legal notice, here is a blessing:
  19088. **
  19089. ** May you do good and not evil.
  19090. ** May you find forgiveness for yourself and forgive others.
  19091. ** May you share freely, never taking more than you give.
  19092. **
  19093. *************************************************************************
  19094. ** This file contains the C functions that implement date and time
  19095. ** functions for SQLite.
  19096. **
  19097. ** There is only one exported symbol in this file - the function
  19098. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  19099. ** All other code has file scope.
  19100. **
  19101. ** SQLite processes all times and dates as julian day numbers. The
  19102. ** dates and times are stored as the number of days since noon
  19103. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  19104. ** calendar system.
  19105. **
  19106. ** 1970-01-01 00:00:00 is JD 2440587.5
  19107. ** 2000-01-01 00:00:00 is JD 2451544.5
  19108. **
  19109. ** This implementation requires years to be expressed as a 4-digit number
  19110. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  19111. ** be represented, even though julian day numbers allow a much wider
  19112. ** range of dates.
  19113. **
  19114. ** The Gregorian calendar system is used for all dates and times,
  19115. ** even those that predate the Gregorian calendar. Historians usually
  19116. ** use the julian calendar for dates prior to 1582-10-15 and for some
  19117. ** dates afterwards, depending on locale. Beware of this difference.
  19118. **
  19119. ** The conversion algorithms are implemented based on descriptions
  19120. ** in the following text:
  19121. **
  19122. ** Jean Meeus
  19123. ** Astronomical Algorithms, 2nd Edition, 1998
  19124. ** ISBN 0-943396-61-1
  19125. ** Willmann-Bell, Inc
  19126. ** Richmond, Virginia (USA)
  19127. */
  19128. /* #include "sqliteInt.h" */
  19129. /* #include <stdlib.h> */
  19130. /* #include <assert.h> */
  19131. #include <time.h>
  19132. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  19133. /*
  19134. ** The MSVC CRT on Windows CE may not have a localtime() function.
  19135. ** So declare a substitute. The substitute function itself is
  19136. ** defined in "os_win.c".
  19137. */
  19138. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  19139. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  19140. struct tm *__cdecl localtime(const time_t *);
  19141. #endif
  19142. /*
  19143. ** A structure for holding a single date and time.
  19144. */
  19145. typedef struct DateTime DateTime;
  19146. struct DateTime {
  19147. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  19148. int Y, M, D; /* Year, month, and day */
  19149. int h, m; /* Hour and minutes */
  19150. int tz; /* Timezone offset in minutes */
  19151. double s; /* Seconds */
  19152. char validJD; /* True (1) if iJD is valid */
  19153. char rawS; /* Raw numeric value stored in s */
  19154. char validYMD; /* True (1) if Y,M,D are valid */
  19155. char validHMS; /* True (1) if h,m,s are valid */
  19156. char validTZ; /* True (1) if tz is valid */
  19157. char tzSet; /* Timezone was set explicitly */
  19158. char isError; /* An overflow has occurred */
  19159. };
  19160. /*
  19161. ** Convert zDate into one or more integers according to the conversion
  19162. ** specifier zFormat.
  19163. **
  19164. ** zFormat[] contains 4 characters for each integer converted, except for
  19165. ** the last integer which is specified by three characters. The meaning
  19166. ** of a four-character format specifiers ABCD is:
  19167. **
  19168. ** A: number of digits to convert. Always "2" or "4".
  19169. ** B: minimum value. Always "0" or "1".
  19170. ** C: maximum value, decoded as:
  19171. ** a: 12
  19172. ** b: 14
  19173. ** c: 24
  19174. ** d: 31
  19175. ** e: 59
  19176. ** f: 9999
  19177. ** D: the separator character, or \000 to indicate this is the
  19178. ** last number to convert.
  19179. **
  19180. ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
  19181. ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
  19182. ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
  19183. ** the 2-digit day which is the last integer in the set.
  19184. **
  19185. ** The function returns the number of successful conversions.
  19186. */
  19187. static int getDigits(const char *zDate, const char *zFormat, ...){
  19188. /* The aMx[] array translates the 3rd character of each format
  19189. ** spec into a max size: a b c d e f */
  19190. static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
  19191. va_list ap;
  19192. int cnt = 0;
  19193. char nextC;
  19194. va_start(ap, zFormat);
  19195. do{
  19196. char N = zFormat[0] - '0';
  19197. char min = zFormat[1] - '0';
  19198. int val = 0;
  19199. u16 max;
  19200. assert( zFormat[2]>='a' && zFormat[2]<='f' );
  19201. max = aMx[zFormat[2] - 'a'];
  19202. nextC = zFormat[3];
  19203. val = 0;
  19204. while( N-- ){
  19205. if( !sqlite3Isdigit(*zDate) ){
  19206. goto end_getDigits;
  19207. }
  19208. val = val*10 + *zDate - '0';
  19209. zDate++;
  19210. }
  19211. if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
  19212. goto end_getDigits;
  19213. }
  19214. *va_arg(ap,int*) = val;
  19215. zDate++;
  19216. cnt++;
  19217. zFormat += 4;
  19218. }while( nextC );
  19219. end_getDigits:
  19220. va_end(ap);
  19221. return cnt;
  19222. }
  19223. /*
  19224. ** Parse a timezone extension on the end of a date-time.
  19225. ** The extension is of the form:
  19226. **
  19227. ** (+/-)HH:MM
  19228. **
  19229. ** Or the "zulu" notation:
  19230. **
  19231. ** Z
  19232. **
  19233. ** If the parse is successful, write the number of minutes
  19234. ** of change in p->tz and return 0. If a parser error occurs,
  19235. ** return non-zero.
  19236. **
  19237. ** A missing specifier is not considered an error.
  19238. */
  19239. static int parseTimezone(const char *zDate, DateTime *p){
  19240. int sgn = 0;
  19241. int nHr, nMn;
  19242. int c;
  19243. while( sqlite3Isspace(*zDate) ){ zDate++; }
  19244. p->tz = 0;
  19245. c = *zDate;
  19246. if( c=='-' ){
  19247. sgn = -1;
  19248. }else if( c=='+' ){
  19249. sgn = +1;
  19250. }else if( c=='Z' || c=='z' ){
  19251. zDate++;
  19252. goto zulu_time;
  19253. }else{
  19254. return c!=0;
  19255. }
  19256. zDate++;
  19257. if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
  19258. return 1;
  19259. }
  19260. zDate += 5;
  19261. p->tz = sgn*(nMn + nHr*60);
  19262. zulu_time:
  19263. while( sqlite3Isspace(*zDate) ){ zDate++; }
  19264. p->tzSet = 1;
  19265. return *zDate!=0;
  19266. }
  19267. /*
  19268. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  19269. ** The HH, MM, and SS must each be exactly 2 digits. The
  19270. ** fractional seconds FFFF can be one or more digits.
  19271. **
  19272. ** Return 1 if there is a parsing error and 0 on success.
  19273. */
  19274. static int parseHhMmSs(const char *zDate, DateTime *p){
  19275. int h, m, s;
  19276. double ms = 0.0;
  19277. if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
  19278. return 1;
  19279. }
  19280. zDate += 5;
  19281. if( *zDate==':' ){
  19282. zDate++;
  19283. if( getDigits(zDate, "20e", &s)!=1 ){
  19284. return 1;
  19285. }
  19286. zDate += 2;
  19287. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  19288. double rScale = 1.0;
  19289. zDate++;
  19290. while( sqlite3Isdigit(*zDate) ){
  19291. ms = ms*10.0 + *zDate - '0';
  19292. rScale *= 10.0;
  19293. zDate++;
  19294. }
  19295. ms /= rScale;
  19296. }
  19297. }else{
  19298. s = 0;
  19299. }
  19300. p->validJD = 0;
  19301. p->rawS = 0;
  19302. p->validHMS = 1;
  19303. p->h = h;
  19304. p->m = m;
  19305. p->s = s + ms;
  19306. if( parseTimezone(zDate, p) ) return 1;
  19307. p->validTZ = (p->tz!=0)?1:0;
  19308. return 0;
  19309. }
  19310. /*
  19311. ** Put the DateTime object into its error state.
  19312. */
  19313. static void datetimeError(DateTime *p){
  19314. memset(p, 0, sizeof(*p));
  19315. p->isError = 1;
  19316. }
  19317. /*
  19318. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  19319. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  19320. **
  19321. ** Reference: Meeus page 61
  19322. */
  19323. static void computeJD(DateTime *p){
  19324. int Y, M, D, A, B, X1, X2;
  19325. if( p->validJD ) return;
  19326. if( p->validYMD ){
  19327. Y = p->Y;
  19328. M = p->M;
  19329. D = p->D;
  19330. }else{
  19331. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  19332. M = 1;
  19333. D = 1;
  19334. }
  19335. if( Y<-4713 || Y>9999 || p->rawS ){
  19336. datetimeError(p);
  19337. return;
  19338. }
  19339. if( M<=2 ){
  19340. Y--;
  19341. M += 12;
  19342. }
  19343. A = Y/100;
  19344. B = 2 - A + (A/4);
  19345. X1 = 36525*(Y+4716)/100;
  19346. X2 = 306001*(M+1)/10000;
  19347. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  19348. p->validJD = 1;
  19349. if( p->validHMS ){
  19350. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  19351. if( p->validTZ ){
  19352. p->iJD -= p->tz*60000;
  19353. p->validYMD = 0;
  19354. p->validHMS = 0;
  19355. p->validTZ = 0;
  19356. }
  19357. }
  19358. }
  19359. /*
  19360. ** Parse dates of the form
  19361. **
  19362. ** YYYY-MM-DD HH:MM:SS.FFF
  19363. ** YYYY-MM-DD HH:MM:SS
  19364. ** YYYY-MM-DD HH:MM
  19365. ** YYYY-MM-DD
  19366. **
  19367. ** Write the result into the DateTime structure and return 0
  19368. ** on success and 1 if the input string is not a well-formed
  19369. ** date.
  19370. */
  19371. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  19372. int Y, M, D, neg;
  19373. if( zDate[0]=='-' ){
  19374. zDate++;
  19375. neg = 1;
  19376. }else{
  19377. neg = 0;
  19378. }
  19379. if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
  19380. return 1;
  19381. }
  19382. zDate += 10;
  19383. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  19384. if( parseHhMmSs(zDate, p)==0 ){
  19385. /* We got the time */
  19386. }else if( *zDate==0 ){
  19387. p->validHMS = 0;
  19388. }else{
  19389. return 1;
  19390. }
  19391. p->validJD = 0;
  19392. p->validYMD = 1;
  19393. p->Y = neg ? -Y : Y;
  19394. p->M = M;
  19395. p->D = D;
  19396. if( p->validTZ ){
  19397. computeJD(p);
  19398. }
  19399. return 0;
  19400. }
  19401. /*
  19402. ** Set the time to the current time reported by the VFS.
  19403. **
  19404. ** Return the number of errors.
  19405. */
  19406. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  19407. p->iJD = sqlite3StmtCurrentTime(context);
  19408. if( p->iJD>0 ){
  19409. p->validJD = 1;
  19410. return 0;
  19411. }else{
  19412. return 1;
  19413. }
  19414. }
  19415. /*
  19416. ** Input "r" is a numeric quantity which might be a julian day number,
  19417. ** or the number of seconds since 1970. If the value if r is within
  19418. ** range of a julian day number, install it as such and set validJD.
  19419. ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
  19420. */
  19421. static void setRawDateNumber(DateTime *p, double r){
  19422. p->s = r;
  19423. p->rawS = 1;
  19424. if( r>=0.0 && r<5373484.5 ){
  19425. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  19426. p->validJD = 1;
  19427. }
  19428. }
  19429. /*
  19430. ** Attempt to parse the given string into a julian day number. Return
  19431. ** the number of errors.
  19432. **
  19433. ** The following are acceptable forms for the input string:
  19434. **
  19435. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  19436. ** DDDD.DD
  19437. ** now
  19438. **
  19439. ** In the first form, the +/-HH:MM is always optional. The fractional
  19440. ** seconds extension (the ".FFF") is optional. The seconds portion
  19441. ** (":SS.FFF") is option. The year and date can be omitted as long
  19442. ** as there is a time string. The time string can be omitted as long
  19443. ** as there is a year and date.
  19444. */
  19445. static int parseDateOrTime(
  19446. sqlite3_context *context,
  19447. const char *zDate,
  19448. DateTime *p
  19449. ){
  19450. double r;
  19451. if( parseYyyyMmDd(zDate,p)==0 ){
  19452. return 0;
  19453. }else if( parseHhMmSs(zDate, p)==0 ){
  19454. return 0;
  19455. }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
  19456. return setDateTimeToCurrent(context, p);
  19457. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  19458. setRawDateNumber(p, r);
  19459. return 0;
  19460. }
  19461. return 1;
  19462. }
  19463. /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
  19464. ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
  19465. ** for DateTime.iJD.
  19466. **
  19467. ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
  19468. ** such a large integer literal, so we have to encode it.
  19469. */
  19470. #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
  19471. /*
  19472. ** Return TRUE if the given julian day number is within range.
  19473. **
  19474. ** The input is the JulianDay times 86400000.
  19475. */
  19476. static int validJulianDay(sqlite3_int64 iJD){
  19477. return iJD>=0 && iJD<=INT_464269060799999;
  19478. }
  19479. /*
  19480. ** Compute the Year, Month, and Day from the julian day number.
  19481. */
  19482. static void computeYMD(DateTime *p){
  19483. int Z, A, B, C, D, E, X1;
  19484. if( p->validYMD ) return;
  19485. if( !p->validJD ){
  19486. p->Y = 2000;
  19487. p->M = 1;
  19488. p->D = 1;
  19489. }else if( !validJulianDay(p->iJD) ){
  19490. datetimeError(p);
  19491. return;
  19492. }else{
  19493. Z = (int)((p->iJD + 43200000)/86400000);
  19494. A = (int)((Z - 1867216.25)/36524.25);
  19495. A = Z + 1 + A - (A/4);
  19496. B = A + 1524;
  19497. C = (int)((B - 122.1)/365.25);
  19498. D = (36525*(C&32767))/100;
  19499. E = (int)((B-D)/30.6001);
  19500. X1 = (int)(30.6001*E);
  19501. p->D = B - D - X1;
  19502. p->M = E<14 ? E-1 : E-13;
  19503. p->Y = p->M>2 ? C - 4716 : C - 4715;
  19504. }
  19505. p->validYMD = 1;
  19506. }
  19507. /*
  19508. ** Compute the Hour, Minute, and Seconds from the julian day number.
  19509. */
  19510. static void computeHMS(DateTime *p){
  19511. int s;
  19512. if( p->validHMS ) return;
  19513. computeJD(p);
  19514. s = (int)((p->iJD + 43200000) % 86400000);
  19515. p->s = s/1000.0;
  19516. s = (int)p->s;
  19517. p->s -= s;
  19518. p->h = s/3600;
  19519. s -= p->h*3600;
  19520. p->m = s/60;
  19521. p->s += s - p->m*60;
  19522. p->rawS = 0;
  19523. p->validHMS = 1;
  19524. }
  19525. /*
  19526. ** Compute both YMD and HMS
  19527. */
  19528. static void computeYMD_HMS(DateTime *p){
  19529. computeYMD(p);
  19530. computeHMS(p);
  19531. }
  19532. /*
  19533. ** Clear the YMD and HMS and the TZ
  19534. */
  19535. static void clearYMD_HMS_TZ(DateTime *p){
  19536. p->validYMD = 0;
  19537. p->validHMS = 0;
  19538. p->validTZ = 0;
  19539. }
  19540. #ifndef SQLITE_OMIT_LOCALTIME
  19541. /*
  19542. ** On recent Windows platforms, the localtime_s() function is available
  19543. ** as part of the "Secure CRT". It is essentially equivalent to
  19544. ** localtime_r() available under most POSIX platforms, except that the
  19545. ** order of the parameters is reversed.
  19546. **
  19547. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  19548. **
  19549. ** If the user has not indicated to use localtime_r() or localtime_s()
  19550. ** already, check for an MSVC build environment that provides
  19551. ** localtime_s().
  19552. */
  19553. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  19554. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  19555. #undef HAVE_LOCALTIME_S
  19556. #define HAVE_LOCALTIME_S 1
  19557. #endif
  19558. /*
  19559. ** The following routine implements the rough equivalent of localtime_r()
  19560. ** using whatever operating-system specific localtime facility that
  19561. ** is available. This routine returns 0 on success and
  19562. ** non-zero on any kind of error.
  19563. **
  19564. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  19565. ** routine will always fail.
  19566. **
  19567. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  19568. ** library function localtime_r() is used to assist in the calculation of
  19569. ** local time.
  19570. */
  19571. static int osLocaltime(time_t *t, struct tm *pTm){
  19572. int rc;
  19573. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  19574. struct tm *pX;
  19575. #if SQLITE_THREADSAFE>0
  19576. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  19577. #endif
  19578. sqlite3_mutex_enter(mutex);
  19579. pX = localtime(t);
  19580. #ifndef SQLITE_UNTESTABLE
  19581. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  19582. #endif
  19583. if( pX ) *pTm = *pX;
  19584. sqlite3_mutex_leave(mutex);
  19585. rc = pX==0;
  19586. #else
  19587. #ifndef SQLITE_UNTESTABLE
  19588. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  19589. #endif
  19590. #if HAVE_LOCALTIME_R
  19591. rc = localtime_r(t, pTm)==0;
  19592. #else
  19593. rc = localtime_s(pTm, t);
  19594. #endif /* HAVE_LOCALTIME_R */
  19595. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  19596. return rc;
  19597. }
  19598. #endif /* SQLITE_OMIT_LOCALTIME */
  19599. #ifndef SQLITE_OMIT_LOCALTIME
  19600. /*
  19601. ** Compute the difference (in milliseconds) between localtime and UTC
  19602. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  19603. ** return this value and set *pRc to SQLITE_OK.
  19604. **
  19605. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  19606. ** is undefined in this case.
  19607. */
  19608. static sqlite3_int64 localtimeOffset(
  19609. DateTime *p, /* Date at which to calculate offset */
  19610. sqlite3_context *pCtx, /* Write error here if one occurs */
  19611. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  19612. ){
  19613. DateTime x, y;
  19614. time_t t;
  19615. struct tm sLocal;
  19616. /* Initialize the contents of sLocal to avoid a compiler warning. */
  19617. memset(&sLocal, 0, sizeof(sLocal));
  19618. x = *p;
  19619. computeYMD_HMS(&x);
  19620. if( x.Y<1971 || x.Y>=2038 ){
  19621. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  19622. ** works for years between 1970 and 2037. For dates outside this range,
  19623. ** SQLite attempts to map the year into an equivalent year within this
  19624. ** range, do the calculation, then map the year back.
  19625. */
  19626. x.Y = 2000;
  19627. x.M = 1;
  19628. x.D = 1;
  19629. x.h = 0;
  19630. x.m = 0;
  19631. x.s = 0.0;
  19632. } else {
  19633. int s = (int)(x.s + 0.5);
  19634. x.s = s;
  19635. }
  19636. x.tz = 0;
  19637. x.validJD = 0;
  19638. computeJD(&x);
  19639. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  19640. if( osLocaltime(&t, &sLocal) ){
  19641. sqlite3_result_error(pCtx, "local time unavailable", -1);
  19642. *pRc = SQLITE_ERROR;
  19643. return 0;
  19644. }
  19645. y.Y = sLocal.tm_year + 1900;
  19646. y.M = sLocal.tm_mon + 1;
  19647. y.D = sLocal.tm_mday;
  19648. y.h = sLocal.tm_hour;
  19649. y.m = sLocal.tm_min;
  19650. y.s = sLocal.tm_sec;
  19651. y.validYMD = 1;
  19652. y.validHMS = 1;
  19653. y.validJD = 0;
  19654. y.rawS = 0;
  19655. y.validTZ = 0;
  19656. y.isError = 0;
  19657. computeJD(&y);
  19658. *pRc = SQLITE_OK;
  19659. return y.iJD - x.iJD;
  19660. }
  19661. #endif /* SQLITE_OMIT_LOCALTIME */
  19662. /*
  19663. ** The following table defines various date transformations of the form
  19664. **
  19665. ** 'NNN days'
  19666. **
  19667. ** Where NNN is an arbitrary floating-point number and "days" can be one
  19668. ** of several units of time.
  19669. */
  19670. static const struct {
  19671. u8 eType; /* Transformation type code */
  19672. u8 nName; /* Length of th name */
  19673. char *zName; /* Name of the transformation */
  19674. double rLimit; /* Maximum NNN value for this transform */
  19675. double rXform; /* Constant used for this transform */
  19676. } aXformType[] = {
  19677. { 0, 6, "second", 464269060800.0, 86400000.0/(24.0*60.0*60.0) },
  19678. { 0, 6, "minute", 7737817680.0, 86400000.0/(24.0*60.0) },
  19679. { 0, 4, "hour", 128963628.0, 86400000.0/24.0 },
  19680. { 0, 3, "day", 5373485.0, 86400000.0 },
  19681. { 1, 5, "month", 176546.0, 30.0*86400000.0 },
  19682. { 2, 4, "year", 14713.0, 365.0*86400000.0 },
  19683. };
  19684. /*
  19685. ** Process a modifier to a date-time stamp. The modifiers are
  19686. ** as follows:
  19687. **
  19688. ** NNN days
  19689. ** NNN hours
  19690. ** NNN minutes
  19691. ** NNN.NNNN seconds
  19692. ** NNN months
  19693. ** NNN years
  19694. ** start of month
  19695. ** start of year
  19696. ** start of week
  19697. ** start of day
  19698. ** weekday N
  19699. ** unixepoch
  19700. ** localtime
  19701. ** utc
  19702. **
  19703. ** Return 0 on success and 1 if there is any kind of error. If the error
  19704. ** is in a system call (i.e. localtime()), then an error message is written
  19705. ** to context pCtx. If the error is an unrecognized modifier, no error is
  19706. ** written to pCtx.
  19707. */
  19708. static int parseModifier(
  19709. sqlite3_context *pCtx, /* Function context */
  19710. const char *z, /* The text of the modifier */
  19711. int n, /* Length of zMod in bytes */
  19712. DateTime *p /* The date/time value to be modified */
  19713. ){
  19714. int rc = 1;
  19715. double r;
  19716. switch(sqlite3UpperToLower[(u8)z[0]] ){
  19717. #ifndef SQLITE_OMIT_LOCALTIME
  19718. case 'l': {
  19719. /* localtime
  19720. **
  19721. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  19722. ** show local time.
  19723. */
  19724. if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
  19725. computeJD(p);
  19726. p->iJD += localtimeOffset(p, pCtx, &rc);
  19727. clearYMD_HMS_TZ(p);
  19728. }
  19729. break;
  19730. }
  19731. #endif
  19732. case 'u': {
  19733. /*
  19734. ** unixepoch
  19735. **
  19736. ** Treat the current value of p->s as the number of
  19737. ** seconds since 1970. Convert to a real julian day number.
  19738. */
  19739. if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
  19740. r = p->s*1000.0 + 210866760000000.0;
  19741. if( r>=0.0 && r<464269060800000.0 ){
  19742. clearYMD_HMS_TZ(p);
  19743. p->iJD = (sqlite3_int64)r;
  19744. p->validJD = 1;
  19745. p->rawS = 0;
  19746. rc = 0;
  19747. }
  19748. }
  19749. #ifndef SQLITE_OMIT_LOCALTIME
  19750. else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
  19751. if( p->tzSet==0 ){
  19752. sqlite3_int64 c1;
  19753. computeJD(p);
  19754. c1 = localtimeOffset(p, pCtx, &rc);
  19755. if( rc==SQLITE_OK ){
  19756. p->iJD -= c1;
  19757. clearYMD_HMS_TZ(p);
  19758. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  19759. }
  19760. p->tzSet = 1;
  19761. }else{
  19762. rc = SQLITE_OK;
  19763. }
  19764. }
  19765. #endif
  19766. break;
  19767. }
  19768. case 'w': {
  19769. /*
  19770. ** weekday N
  19771. **
  19772. ** Move the date to the same time on the next occurrence of
  19773. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  19774. ** date is already on the appropriate weekday, this is a no-op.
  19775. */
  19776. if( sqlite3_strnicmp(z, "weekday ", 8)==0
  19777. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  19778. && (n=(int)r)==r && n>=0 && r<7 ){
  19779. sqlite3_int64 Z;
  19780. computeYMD_HMS(p);
  19781. p->validTZ = 0;
  19782. p->validJD = 0;
  19783. computeJD(p);
  19784. Z = ((p->iJD + 129600000)/86400000) % 7;
  19785. if( Z>n ) Z -= 7;
  19786. p->iJD += (n - Z)*86400000;
  19787. clearYMD_HMS_TZ(p);
  19788. rc = 0;
  19789. }
  19790. break;
  19791. }
  19792. case 's': {
  19793. /*
  19794. ** start of TTTTT
  19795. **
  19796. ** Move the date backwards to the beginning of the current day,
  19797. ** or month or year.
  19798. */
  19799. if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
  19800. if( !p->validJD && !p->validYMD && !p->validHMS ) break;
  19801. z += 9;
  19802. computeYMD(p);
  19803. p->validHMS = 1;
  19804. p->h = p->m = 0;
  19805. p->s = 0.0;
  19806. p->rawS = 0;
  19807. p->validTZ = 0;
  19808. p->validJD = 0;
  19809. if( sqlite3_stricmp(z,"month")==0 ){
  19810. p->D = 1;
  19811. rc = 0;
  19812. }else if( sqlite3_stricmp(z,"year")==0 ){
  19813. p->M = 1;
  19814. p->D = 1;
  19815. rc = 0;
  19816. }else if( sqlite3_stricmp(z,"day")==0 ){
  19817. rc = 0;
  19818. }
  19819. break;
  19820. }
  19821. case '+':
  19822. case '-':
  19823. case '0':
  19824. case '1':
  19825. case '2':
  19826. case '3':
  19827. case '4':
  19828. case '5':
  19829. case '6':
  19830. case '7':
  19831. case '8':
  19832. case '9': {
  19833. double rRounder;
  19834. int i;
  19835. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  19836. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  19837. rc = 1;
  19838. break;
  19839. }
  19840. if( z[n]==':' ){
  19841. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  19842. ** specified number of hours, minutes, seconds, and fractional seconds
  19843. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  19844. ** omitted.
  19845. */
  19846. const char *z2 = z;
  19847. DateTime tx;
  19848. sqlite3_int64 day;
  19849. if( !sqlite3Isdigit(*z2) ) z2++;
  19850. memset(&tx, 0, sizeof(tx));
  19851. if( parseHhMmSs(z2, &tx) ) break;
  19852. computeJD(&tx);
  19853. tx.iJD -= 43200000;
  19854. day = tx.iJD/86400000;
  19855. tx.iJD -= day*86400000;
  19856. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  19857. computeJD(p);
  19858. clearYMD_HMS_TZ(p);
  19859. p->iJD += tx.iJD;
  19860. rc = 0;
  19861. break;
  19862. }
  19863. /* If control reaches this point, it means the transformation is
  19864. ** one of the forms like "+NNN days". */
  19865. z += n;
  19866. while( sqlite3Isspace(*z) ) z++;
  19867. n = sqlite3Strlen30(z);
  19868. if( n>10 || n<3 ) break;
  19869. if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
  19870. computeJD(p);
  19871. rc = 1;
  19872. rRounder = r<0 ? -0.5 : +0.5;
  19873. for(i=0; i<ArraySize(aXformType); i++){
  19874. if( aXformType[i].nName==n
  19875. && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
  19876. && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
  19877. ){
  19878. switch( aXformType[i].eType ){
  19879. case 1: { /* Special processing to add months */
  19880. int x;
  19881. computeYMD_HMS(p);
  19882. p->M += (int)r;
  19883. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  19884. p->Y += x;
  19885. p->M -= x*12;
  19886. p->validJD = 0;
  19887. r -= (int)r;
  19888. break;
  19889. }
  19890. case 2: { /* Special processing to add years */
  19891. int y = (int)r;
  19892. computeYMD_HMS(p);
  19893. p->Y += y;
  19894. p->validJD = 0;
  19895. r -= (int)r;
  19896. break;
  19897. }
  19898. }
  19899. computeJD(p);
  19900. p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
  19901. rc = 0;
  19902. break;
  19903. }
  19904. }
  19905. clearYMD_HMS_TZ(p);
  19906. break;
  19907. }
  19908. default: {
  19909. break;
  19910. }
  19911. }
  19912. return rc;
  19913. }
  19914. /*
  19915. ** Process time function arguments. argv[0] is a date-time stamp.
  19916. ** argv[1] and following are modifiers. Parse them all and write
  19917. ** the resulting time into the DateTime structure p. Return 0
  19918. ** on success and 1 if there are any errors.
  19919. **
  19920. ** If there are zero parameters (if even argv[0] is undefined)
  19921. ** then assume a default value of "now" for argv[0].
  19922. */
  19923. static int isDate(
  19924. sqlite3_context *context,
  19925. int argc,
  19926. sqlite3_value **argv,
  19927. DateTime *p
  19928. ){
  19929. int i, n;
  19930. const unsigned char *z;
  19931. int eType;
  19932. memset(p, 0, sizeof(*p));
  19933. if( argc==0 ){
  19934. return setDateTimeToCurrent(context, p);
  19935. }
  19936. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  19937. || eType==SQLITE_INTEGER ){
  19938. setRawDateNumber(p, sqlite3_value_double(argv[0]));
  19939. }else{
  19940. z = sqlite3_value_text(argv[0]);
  19941. if( !z || parseDateOrTime(context, (char*)z, p) ){
  19942. return 1;
  19943. }
  19944. }
  19945. for(i=1; i<argc; i++){
  19946. z = sqlite3_value_text(argv[i]);
  19947. n = sqlite3_value_bytes(argv[i]);
  19948. if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
  19949. }
  19950. computeJD(p);
  19951. if( p->isError || !validJulianDay(p->iJD) ) return 1;
  19952. return 0;
  19953. }
  19954. /*
  19955. ** The following routines implement the various date and time functions
  19956. ** of SQLite.
  19957. */
  19958. /*
  19959. ** julianday( TIMESTRING, MOD, MOD, ...)
  19960. **
  19961. ** Return the julian day number of the date specified in the arguments
  19962. */
  19963. static void juliandayFunc(
  19964. sqlite3_context *context,
  19965. int argc,
  19966. sqlite3_value **argv
  19967. ){
  19968. DateTime x;
  19969. if( isDate(context, argc, argv, &x)==0 ){
  19970. computeJD(&x);
  19971. sqlite3_result_double(context, x.iJD/86400000.0);
  19972. }
  19973. }
  19974. /*
  19975. ** datetime( TIMESTRING, MOD, MOD, ...)
  19976. **
  19977. ** Return YYYY-MM-DD HH:MM:SS
  19978. */
  19979. static void datetimeFunc(
  19980. sqlite3_context *context,
  19981. int argc,
  19982. sqlite3_value **argv
  19983. ){
  19984. DateTime x;
  19985. if( isDate(context, argc, argv, &x)==0 ){
  19986. char zBuf[100];
  19987. computeYMD_HMS(&x);
  19988. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  19989. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  19990. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  19991. }
  19992. }
  19993. /*
  19994. ** time( TIMESTRING, MOD, MOD, ...)
  19995. **
  19996. ** Return HH:MM:SS
  19997. */
  19998. static void timeFunc(
  19999. sqlite3_context *context,
  20000. int argc,
  20001. sqlite3_value **argv
  20002. ){
  20003. DateTime x;
  20004. if( isDate(context, argc, argv, &x)==0 ){
  20005. char zBuf[100];
  20006. computeHMS(&x);
  20007. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  20008. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20009. }
  20010. }
  20011. /*
  20012. ** date( TIMESTRING, MOD, MOD, ...)
  20013. **
  20014. ** Return YYYY-MM-DD
  20015. */
  20016. static void dateFunc(
  20017. sqlite3_context *context,
  20018. int argc,
  20019. sqlite3_value **argv
  20020. ){
  20021. DateTime x;
  20022. if( isDate(context, argc, argv, &x)==0 ){
  20023. char zBuf[100];
  20024. computeYMD(&x);
  20025. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  20026. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20027. }
  20028. }
  20029. /*
  20030. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  20031. **
  20032. ** Return a string described by FORMAT. Conversions as follows:
  20033. **
  20034. ** %d day of month
  20035. ** %f ** fractional seconds SS.SSS
  20036. ** %H hour 00-24
  20037. ** %j day of year 000-366
  20038. ** %J ** julian day number
  20039. ** %m month 01-12
  20040. ** %M minute 00-59
  20041. ** %s seconds since 1970-01-01
  20042. ** %S seconds 00-59
  20043. ** %w day of week 0-6 sunday==0
  20044. ** %W week of year 00-53
  20045. ** %Y year 0000-9999
  20046. ** %% %
  20047. */
  20048. static void strftimeFunc(
  20049. sqlite3_context *context,
  20050. int argc,
  20051. sqlite3_value **argv
  20052. ){
  20053. DateTime x;
  20054. u64 n;
  20055. size_t i,j;
  20056. char *z;
  20057. sqlite3 *db;
  20058. const char *zFmt;
  20059. char zBuf[100];
  20060. if( argc==0 ) return;
  20061. zFmt = (const char*)sqlite3_value_text(argv[0]);
  20062. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  20063. db = sqlite3_context_db_handle(context);
  20064. for(i=0, n=1; zFmt[i]; i++, n++){
  20065. if( zFmt[i]=='%' ){
  20066. switch( zFmt[i+1] ){
  20067. case 'd':
  20068. case 'H':
  20069. case 'm':
  20070. case 'M':
  20071. case 'S':
  20072. case 'W':
  20073. n++;
  20074. /* fall thru */
  20075. case 'w':
  20076. case '%':
  20077. break;
  20078. case 'f':
  20079. n += 8;
  20080. break;
  20081. case 'j':
  20082. n += 3;
  20083. break;
  20084. case 'Y':
  20085. n += 8;
  20086. break;
  20087. case 's':
  20088. case 'J':
  20089. n += 50;
  20090. break;
  20091. default:
  20092. return; /* ERROR. return a NULL */
  20093. }
  20094. i++;
  20095. }
  20096. }
  20097. testcase( n==sizeof(zBuf)-1 );
  20098. testcase( n==sizeof(zBuf) );
  20099. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  20100. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  20101. if( n<sizeof(zBuf) ){
  20102. z = zBuf;
  20103. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  20104. sqlite3_result_error_toobig(context);
  20105. return;
  20106. }else{
  20107. z = sqlite3DbMallocRawNN(db, (int)n);
  20108. if( z==0 ){
  20109. sqlite3_result_error_nomem(context);
  20110. return;
  20111. }
  20112. }
  20113. computeJD(&x);
  20114. computeYMD_HMS(&x);
  20115. for(i=j=0; zFmt[i]; i++){
  20116. if( zFmt[i]!='%' ){
  20117. z[j++] = zFmt[i];
  20118. }else{
  20119. i++;
  20120. switch( zFmt[i] ){
  20121. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  20122. case 'f': {
  20123. double s = x.s;
  20124. if( s>59.999 ) s = 59.999;
  20125. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  20126. j += sqlite3Strlen30(&z[j]);
  20127. break;
  20128. }
  20129. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  20130. case 'W': /* Fall thru */
  20131. case 'j': {
  20132. int nDay; /* Number of days since 1st day of year */
  20133. DateTime y = x;
  20134. y.validJD = 0;
  20135. y.M = 1;
  20136. y.D = 1;
  20137. computeJD(&y);
  20138. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  20139. if( zFmt[i]=='W' ){
  20140. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  20141. wd = (int)(((x.iJD+43200000)/86400000)%7);
  20142. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  20143. j += 2;
  20144. }else{
  20145. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  20146. j += 3;
  20147. }
  20148. break;
  20149. }
  20150. case 'J': {
  20151. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  20152. j+=sqlite3Strlen30(&z[j]);
  20153. break;
  20154. }
  20155. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  20156. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  20157. case 's': {
  20158. sqlite3_snprintf(30,&z[j],"%lld",
  20159. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  20160. j += sqlite3Strlen30(&z[j]);
  20161. break;
  20162. }
  20163. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  20164. case 'w': {
  20165. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  20166. break;
  20167. }
  20168. case 'Y': {
  20169. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  20170. break;
  20171. }
  20172. default: z[j++] = '%'; break;
  20173. }
  20174. }
  20175. }
  20176. z[j] = 0;
  20177. sqlite3_result_text(context, z, -1,
  20178. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  20179. }
  20180. /*
  20181. ** current_time()
  20182. **
  20183. ** This function returns the same value as time('now').
  20184. */
  20185. static void ctimeFunc(
  20186. sqlite3_context *context,
  20187. int NotUsed,
  20188. sqlite3_value **NotUsed2
  20189. ){
  20190. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  20191. timeFunc(context, 0, 0);
  20192. }
  20193. /*
  20194. ** current_date()
  20195. **
  20196. ** This function returns the same value as date('now').
  20197. */
  20198. static void cdateFunc(
  20199. sqlite3_context *context,
  20200. int NotUsed,
  20201. sqlite3_value **NotUsed2
  20202. ){
  20203. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  20204. dateFunc(context, 0, 0);
  20205. }
  20206. /*
  20207. ** current_timestamp()
  20208. **
  20209. ** This function returns the same value as datetime('now').
  20210. */
  20211. static void ctimestampFunc(
  20212. sqlite3_context *context,
  20213. int NotUsed,
  20214. sqlite3_value **NotUsed2
  20215. ){
  20216. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  20217. datetimeFunc(context, 0, 0);
  20218. }
  20219. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  20220. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  20221. /*
  20222. ** If the library is compiled to omit the full-scale date and time
  20223. ** handling (to get a smaller binary), the following minimal version
  20224. ** of the functions current_time(), current_date() and current_timestamp()
  20225. ** are included instead. This is to support column declarations that
  20226. ** include "DEFAULT CURRENT_TIME" etc.
  20227. **
  20228. ** This function uses the C-library functions time(), gmtime()
  20229. ** and strftime(). The format string to pass to strftime() is supplied
  20230. ** as the user-data for the function.
  20231. */
  20232. static void currentTimeFunc(
  20233. sqlite3_context *context,
  20234. int argc,
  20235. sqlite3_value **argv
  20236. ){
  20237. time_t t;
  20238. char *zFormat = (char *)sqlite3_user_data(context);
  20239. sqlite3_int64 iT;
  20240. struct tm *pTm;
  20241. struct tm sNow;
  20242. char zBuf[20];
  20243. UNUSED_PARAMETER(argc);
  20244. UNUSED_PARAMETER(argv);
  20245. iT = sqlite3StmtCurrentTime(context);
  20246. if( iT<=0 ) return;
  20247. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  20248. #if HAVE_GMTIME_R
  20249. pTm = gmtime_r(&t, &sNow);
  20250. #else
  20251. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  20252. pTm = gmtime(&t);
  20253. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  20254. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  20255. #endif
  20256. if( pTm ){
  20257. strftime(zBuf, 20, zFormat, &sNow);
  20258. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  20259. }
  20260. }
  20261. #endif
  20262. /*
  20263. ** This function registered all of the above C functions as SQL
  20264. ** functions. This should be the only routine in this file with
  20265. ** external linkage.
  20266. */
  20267. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  20268. static FuncDef aDateTimeFuncs[] = {
  20269. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  20270. PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
  20271. PURE_DATE(date, -1, 0, 0, dateFunc ),
  20272. PURE_DATE(time, -1, 0, 0, timeFunc ),
  20273. PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
  20274. PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
  20275. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  20276. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  20277. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  20278. #else
  20279. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  20280. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  20281. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  20282. #endif
  20283. };
  20284. sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
  20285. }
  20286. /************** End of date.c ************************************************/
  20287. /************** Begin file os.c **********************************************/
  20288. /*
  20289. ** 2005 November 29
  20290. **
  20291. ** The author disclaims copyright to this source code. In place of
  20292. ** a legal notice, here is a blessing:
  20293. **
  20294. ** May you do good and not evil.
  20295. ** May you find forgiveness for yourself and forgive others.
  20296. ** May you share freely, never taking more than you give.
  20297. **
  20298. ******************************************************************************
  20299. **
  20300. ** This file contains OS interface code that is common to all
  20301. ** architectures.
  20302. */
  20303. /* #include "sqliteInt.h" */
  20304. /*
  20305. ** If we compile with the SQLITE_TEST macro set, then the following block
  20306. ** of code will give us the ability to simulate a disk I/O error. This
  20307. ** is used for testing the I/O recovery logic.
  20308. */
  20309. #if defined(SQLITE_TEST)
  20310. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  20311. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  20312. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  20313. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  20314. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  20315. SQLITE_API int sqlite3_diskfull_pending = 0;
  20316. SQLITE_API int sqlite3_diskfull = 0;
  20317. #endif /* defined(SQLITE_TEST) */
  20318. /*
  20319. ** When testing, also keep a count of the number of open files.
  20320. */
  20321. #if defined(SQLITE_TEST)
  20322. SQLITE_API int sqlite3_open_file_count = 0;
  20323. #endif /* defined(SQLITE_TEST) */
  20324. /*
  20325. ** The default SQLite sqlite3_vfs implementations do not allocate
  20326. ** memory (actually, os_unix.c allocates a small amount of memory
  20327. ** from within OsOpen()), but some third-party implementations may.
  20328. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  20329. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  20330. **
  20331. ** The following functions are instrumented for malloc() failure
  20332. ** testing:
  20333. **
  20334. ** sqlite3OsRead()
  20335. ** sqlite3OsWrite()
  20336. ** sqlite3OsSync()
  20337. ** sqlite3OsFileSize()
  20338. ** sqlite3OsLock()
  20339. ** sqlite3OsCheckReservedLock()
  20340. ** sqlite3OsFileControl()
  20341. ** sqlite3OsShmMap()
  20342. ** sqlite3OsOpen()
  20343. ** sqlite3OsDelete()
  20344. ** sqlite3OsAccess()
  20345. ** sqlite3OsFullPathname()
  20346. **
  20347. */
  20348. #if defined(SQLITE_TEST)
  20349. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  20350. #define DO_OS_MALLOC_TEST(x) \
  20351. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
  20352. void *pTstAlloc = sqlite3Malloc(10); \
  20353. if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
  20354. sqlite3_free(pTstAlloc); \
  20355. }
  20356. #else
  20357. #define DO_OS_MALLOC_TEST(x)
  20358. #endif
  20359. /*
  20360. ** The following routines are convenience wrappers around methods
  20361. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  20362. ** of this would be completely automatic if SQLite were coded using
  20363. ** C++ instead of plain old C.
  20364. */
  20365. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
  20366. if( pId->pMethods ){
  20367. pId->pMethods->xClose(pId);
  20368. pId->pMethods = 0;
  20369. }
  20370. }
  20371. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  20372. DO_OS_MALLOC_TEST(id);
  20373. return id->pMethods->xRead(id, pBuf, amt, offset);
  20374. }
  20375. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  20376. DO_OS_MALLOC_TEST(id);
  20377. return id->pMethods->xWrite(id, pBuf, amt, offset);
  20378. }
  20379. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  20380. return id->pMethods->xTruncate(id, size);
  20381. }
  20382. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  20383. DO_OS_MALLOC_TEST(id);
  20384. return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
  20385. }
  20386. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  20387. DO_OS_MALLOC_TEST(id);
  20388. return id->pMethods->xFileSize(id, pSize);
  20389. }
  20390. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  20391. DO_OS_MALLOC_TEST(id);
  20392. return id->pMethods->xLock(id, lockType);
  20393. }
  20394. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  20395. return id->pMethods->xUnlock(id, lockType);
  20396. }
  20397. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  20398. DO_OS_MALLOC_TEST(id);
  20399. return id->pMethods->xCheckReservedLock(id, pResOut);
  20400. }
  20401. /*
  20402. ** Use sqlite3OsFileControl() when we are doing something that might fail
  20403. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  20404. ** when simply tossing information over the wall to the VFS and we do not
  20405. ** really care if the VFS receives and understands the information since it
  20406. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  20407. ** routine has no return value since the return value would be meaningless.
  20408. */
  20409. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  20410. if( id->pMethods==0 ) return SQLITE_NOTFOUND;
  20411. #ifdef SQLITE_TEST
  20412. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
  20413. && op!=SQLITE_FCNTL_LOCK_TIMEOUT
  20414. ){
  20415. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  20416. ** is using a regular VFS, it is called after the corresponding
  20417. ** transaction has been committed. Injecting a fault at this point
  20418. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  20419. ** but the transaction is committed anyway.
  20420. **
  20421. ** The core must call OsFileControl() though, not OsFileControlHint(),
  20422. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  20423. ** means the commit really has failed and an error should be returned
  20424. ** to the user. */
  20425. DO_OS_MALLOC_TEST(id);
  20426. }
  20427. #endif
  20428. return id->pMethods->xFileControl(id, op, pArg);
  20429. }
  20430. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  20431. if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
  20432. }
  20433. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  20434. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  20435. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  20436. }
  20437. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  20438. return id->pMethods->xDeviceCharacteristics(id);
  20439. }
  20440. #ifndef SQLITE_OMIT_WAL
  20441. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  20442. return id->pMethods->xShmLock(id, offset, n, flags);
  20443. }
  20444. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  20445. id->pMethods->xShmBarrier(id);
  20446. }
  20447. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  20448. return id->pMethods->xShmUnmap(id, deleteFlag);
  20449. }
  20450. SQLITE_PRIVATE int sqlite3OsShmMap(
  20451. sqlite3_file *id, /* Database file handle */
  20452. int iPage,
  20453. int pgsz,
  20454. int bExtend, /* True to extend file if necessary */
  20455. void volatile **pp /* OUT: Pointer to mapping */
  20456. ){
  20457. DO_OS_MALLOC_TEST(id);
  20458. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  20459. }
  20460. #endif /* SQLITE_OMIT_WAL */
  20461. #if SQLITE_MAX_MMAP_SIZE>0
  20462. /* The real implementation of xFetch and xUnfetch */
  20463. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  20464. DO_OS_MALLOC_TEST(id);
  20465. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  20466. }
  20467. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  20468. return id->pMethods->xUnfetch(id, iOff, p);
  20469. }
  20470. #else
  20471. /* No-op stubs to use when memory-mapped I/O is disabled */
  20472. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  20473. *pp = 0;
  20474. return SQLITE_OK;
  20475. }
  20476. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  20477. return SQLITE_OK;
  20478. }
  20479. #endif
  20480. /*
  20481. ** The next group of routines are convenience wrappers around the
  20482. ** VFS methods.
  20483. */
  20484. SQLITE_PRIVATE int sqlite3OsOpen(
  20485. sqlite3_vfs *pVfs,
  20486. const char *zPath,
  20487. sqlite3_file *pFile,
  20488. int flags,
  20489. int *pFlagsOut
  20490. ){
  20491. int rc;
  20492. DO_OS_MALLOC_TEST(0);
  20493. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  20494. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  20495. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  20496. ** reaching the VFS. */
  20497. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  20498. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  20499. return rc;
  20500. }
  20501. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  20502. DO_OS_MALLOC_TEST(0);
  20503. assert( dirSync==0 || dirSync==1 );
  20504. return pVfs->xDelete(pVfs, zPath, dirSync);
  20505. }
  20506. SQLITE_PRIVATE int sqlite3OsAccess(
  20507. sqlite3_vfs *pVfs,
  20508. const char *zPath,
  20509. int flags,
  20510. int *pResOut
  20511. ){
  20512. DO_OS_MALLOC_TEST(0);
  20513. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  20514. }
  20515. SQLITE_PRIVATE int sqlite3OsFullPathname(
  20516. sqlite3_vfs *pVfs,
  20517. const char *zPath,
  20518. int nPathOut,
  20519. char *zPathOut
  20520. ){
  20521. DO_OS_MALLOC_TEST(0);
  20522. zPathOut[0] = 0;
  20523. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  20524. }
  20525. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  20526. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  20527. return pVfs->xDlOpen(pVfs, zPath);
  20528. }
  20529. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  20530. pVfs->xDlError(pVfs, nByte, zBufOut);
  20531. }
  20532. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  20533. return pVfs->xDlSym(pVfs, pHdle, zSym);
  20534. }
  20535. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  20536. pVfs->xDlClose(pVfs, pHandle);
  20537. }
  20538. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  20539. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  20540. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  20541. }
  20542. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  20543. return pVfs->xSleep(pVfs, nMicro);
  20544. }
  20545. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
  20546. return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
  20547. }
  20548. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  20549. int rc;
  20550. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  20551. ** method to get the current date and time if that method is available
  20552. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  20553. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  20554. ** unavailable.
  20555. */
  20556. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  20557. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  20558. }else{
  20559. double r;
  20560. rc = pVfs->xCurrentTime(pVfs, &r);
  20561. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  20562. }
  20563. return rc;
  20564. }
  20565. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  20566. sqlite3_vfs *pVfs,
  20567. const char *zFile,
  20568. sqlite3_file **ppFile,
  20569. int flags,
  20570. int *pOutFlags
  20571. ){
  20572. int rc;
  20573. sqlite3_file *pFile;
  20574. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  20575. if( pFile ){
  20576. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  20577. if( rc!=SQLITE_OK ){
  20578. sqlite3_free(pFile);
  20579. }else{
  20580. *ppFile = pFile;
  20581. }
  20582. }else{
  20583. rc = SQLITE_NOMEM_BKPT;
  20584. }
  20585. return rc;
  20586. }
  20587. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
  20588. assert( pFile );
  20589. sqlite3OsClose(pFile);
  20590. sqlite3_free(pFile);
  20591. }
  20592. /*
  20593. ** This function is a wrapper around the OS specific implementation of
  20594. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  20595. ** ability to simulate a malloc failure, so that the handling of an
  20596. ** error in sqlite3_os_init() by the upper layers can be tested.
  20597. */
  20598. SQLITE_PRIVATE int sqlite3OsInit(void){
  20599. void *p = sqlite3_malloc(10);
  20600. if( p==0 ) return SQLITE_NOMEM_BKPT;
  20601. sqlite3_free(p);
  20602. return sqlite3_os_init();
  20603. }
  20604. /*
  20605. ** The list of all registered VFS implementations.
  20606. */
  20607. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  20608. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  20609. /*
  20610. ** Locate a VFS by name. If no name is given, simply return the
  20611. ** first VFS on the list.
  20612. */
  20613. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  20614. sqlite3_vfs *pVfs = 0;
  20615. #if SQLITE_THREADSAFE
  20616. sqlite3_mutex *mutex;
  20617. #endif
  20618. #ifndef SQLITE_OMIT_AUTOINIT
  20619. int rc = sqlite3_initialize();
  20620. if( rc ) return 0;
  20621. #endif
  20622. #if SQLITE_THREADSAFE
  20623. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  20624. #endif
  20625. sqlite3_mutex_enter(mutex);
  20626. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  20627. if( zVfs==0 ) break;
  20628. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  20629. }
  20630. sqlite3_mutex_leave(mutex);
  20631. return pVfs;
  20632. }
  20633. /*
  20634. ** Unlink a VFS from the linked list
  20635. */
  20636. static void vfsUnlink(sqlite3_vfs *pVfs){
  20637. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  20638. if( pVfs==0 ){
  20639. /* No-op */
  20640. }else if( vfsList==pVfs ){
  20641. vfsList = pVfs->pNext;
  20642. }else if( vfsList ){
  20643. sqlite3_vfs *p = vfsList;
  20644. while( p->pNext && p->pNext!=pVfs ){
  20645. p = p->pNext;
  20646. }
  20647. if( p->pNext==pVfs ){
  20648. p->pNext = pVfs->pNext;
  20649. }
  20650. }
  20651. }
  20652. /*
  20653. ** Register a VFS with the system. It is harmless to register the same
  20654. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  20655. ** true.
  20656. */
  20657. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  20658. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  20659. #ifndef SQLITE_OMIT_AUTOINIT
  20660. int rc = sqlite3_initialize();
  20661. if( rc ) return rc;
  20662. #endif
  20663. #ifdef SQLITE_ENABLE_API_ARMOR
  20664. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  20665. #endif
  20666. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  20667. sqlite3_mutex_enter(mutex);
  20668. vfsUnlink(pVfs);
  20669. if( makeDflt || vfsList==0 ){
  20670. pVfs->pNext = vfsList;
  20671. vfsList = pVfs;
  20672. }else{
  20673. pVfs->pNext = vfsList->pNext;
  20674. vfsList->pNext = pVfs;
  20675. }
  20676. assert(vfsList);
  20677. sqlite3_mutex_leave(mutex);
  20678. return SQLITE_OK;
  20679. }
  20680. /*
  20681. ** Unregister a VFS so that it is no longer accessible.
  20682. */
  20683. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  20684. #if SQLITE_THREADSAFE
  20685. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  20686. #endif
  20687. sqlite3_mutex_enter(mutex);
  20688. vfsUnlink(pVfs);
  20689. sqlite3_mutex_leave(mutex);
  20690. return SQLITE_OK;
  20691. }
  20692. /************** End of os.c **************************************************/
  20693. /************** Begin file fault.c *******************************************/
  20694. /*
  20695. ** 2008 Jan 22
  20696. **
  20697. ** The author disclaims copyright to this source code. In place of
  20698. ** a legal notice, here is a blessing:
  20699. **
  20700. ** May you do good and not evil.
  20701. ** May you find forgiveness for yourself and forgive others.
  20702. ** May you share freely, never taking more than you give.
  20703. **
  20704. *************************************************************************
  20705. **
  20706. ** This file contains code to support the concept of "benign"
  20707. ** malloc failures (when the xMalloc() or xRealloc() method of the
  20708. ** sqlite3_mem_methods structure fails to allocate a block of memory
  20709. ** and returns 0).
  20710. **
  20711. ** Most malloc failures are non-benign. After they occur, SQLite
  20712. ** abandons the current operation and returns an error code (usually
  20713. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  20714. ** fatal. For example, if a malloc fails while resizing a hash table, this
  20715. ** is completely recoverable simply by not carrying out the resize. The
  20716. ** hash table will continue to function normally. So a malloc failure
  20717. ** during a hash table resize is a benign fault.
  20718. */
  20719. /* #include "sqliteInt.h" */
  20720. #ifndef SQLITE_UNTESTABLE
  20721. /*
  20722. ** Global variables.
  20723. */
  20724. typedef struct BenignMallocHooks BenignMallocHooks;
  20725. static SQLITE_WSD struct BenignMallocHooks {
  20726. void (*xBenignBegin)(void);
  20727. void (*xBenignEnd)(void);
  20728. } sqlite3Hooks = { 0, 0 };
  20729. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  20730. ** structure. If writable static data is unsupported on the target,
  20731. ** we have to locate the state vector at run-time. In the more common
  20732. ** case where writable static data is supported, wsdHooks can refer directly
  20733. ** to the "sqlite3Hooks" state vector declared above.
  20734. */
  20735. #ifdef SQLITE_OMIT_WSD
  20736. # define wsdHooksInit \
  20737. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  20738. # define wsdHooks x[0]
  20739. #else
  20740. # define wsdHooksInit
  20741. # define wsdHooks sqlite3Hooks
  20742. #endif
  20743. /*
  20744. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  20745. ** sqlite3EndBenignMalloc() are called, respectively.
  20746. */
  20747. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  20748. void (*xBenignBegin)(void),
  20749. void (*xBenignEnd)(void)
  20750. ){
  20751. wsdHooksInit;
  20752. wsdHooks.xBenignBegin = xBenignBegin;
  20753. wsdHooks.xBenignEnd = xBenignEnd;
  20754. }
  20755. /*
  20756. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  20757. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  20758. ** indicates that subsequent malloc failures are non-benign.
  20759. */
  20760. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  20761. wsdHooksInit;
  20762. if( wsdHooks.xBenignBegin ){
  20763. wsdHooks.xBenignBegin();
  20764. }
  20765. }
  20766. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  20767. wsdHooksInit;
  20768. if( wsdHooks.xBenignEnd ){
  20769. wsdHooks.xBenignEnd();
  20770. }
  20771. }
  20772. #endif /* #ifndef SQLITE_UNTESTABLE */
  20773. /************** End of fault.c ***********************************************/
  20774. /************** Begin file mem0.c ********************************************/
  20775. /*
  20776. ** 2008 October 28
  20777. **
  20778. ** The author disclaims copyright to this source code. In place of
  20779. ** a legal notice, here is a blessing:
  20780. **
  20781. ** May you do good and not evil.
  20782. ** May you find forgiveness for yourself and forgive others.
  20783. ** May you share freely, never taking more than you give.
  20784. **
  20785. *************************************************************************
  20786. **
  20787. ** This file contains a no-op memory allocation drivers for use when
  20788. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  20789. ** here always fail. SQLite will not operate with these drivers. These
  20790. ** are merely placeholders. Real drivers must be substituted using
  20791. ** sqlite3_config() before SQLite will operate.
  20792. */
  20793. /* #include "sqliteInt.h" */
  20794. /*
  20795. ** This version of the memory allocator is the default. It is
  20796. ** used when no other memory allocator is specified using compile-time
  20797. ** macros.
  20798. */
  20799. #ifdef SQLITE_ZERO_MALLOC
  20800. /*
  20801. ** No-op versions of all memory allocation routines
  20802. */
  20803. static void *sqlite3MemMalloc(int nByte){ return 0; }
  20804. static void sqlite3MemFree(void *pPrior){ return; }
  20805. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  20806. static int sqlite3MemSize(void *pPrior){ return 0; }
  20807. static int sqlite3MemRoundup(int n){ return n; }
  20808. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  20809. static void sqlite3MemShutdown(void *NotUsed){ return; }
  20810. /*
  20811. ** This routine is the only routine in this file with external linkage.
  20812. **
  20813. ** Populate the low-level memory allocation function pointers in
  20814. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  20815. */
  20816. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  20817. static const sqlite3_mem_methods defaultMethods = {
  20818. sqlite3MemMalloc,
  20819. sqlite3MemFree,
  20820. sqlite3MemRealloc,
  20821. sqlite3MemSize,
  20822. sqlite3MemRoundup,
  20823. sqlite3MemInit,
  20824. sqlite3MemShutdown,
  20825. 0
  20826. };
  20827. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  20828. }
  20829. #endif /* SQLITE_ZERO_MALLOC */
  20830. /************** End of mem0.c ************************************************/
  20831. /************** Begin file mem1.c ********************************************/
  20832. /*
  20833. ** 2007 August 14
  20834. **
  20835. ** The author disclaims copyright to this source code. In place of
  20836. ** a legal notice, here is a blessing:
  20837. **
  20838. ** May you do good and not evil.
  20839. ** May you find forgiveness for yourself and forgive others.
  20840. ** May you share freely, never taking more than you give.
  20841. **
  20842. *************************************************************************
  20843. **
  20844. ** This file contains low-level memory allocation drivers for when
  20845. ** SQLite will use the standard C-library malloc/realloc/free interface
  20846. ** to obtain the memory it needs.
  20847. **
  20848. ** This file contains implementations of the low-level memory allocation
  20849. ** routines specified in the sqlite3_mem_methods object. The content of
  20850. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  20851. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  20852. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  20853. ** default configuration is to use memory allocation routines in this
  20854. ** file.
  20855. **
  20856. ** C-preprocessor macro summary:
  20857. **
  20858. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  20859. ** the malloc_usable_size() interface exists
  20860. ** on the target platform. Or, this symbol
  20861. ** can be set manually, if desired.
  20862. ** If an equivalent interface exists by
  20863. ** a different name, using a separate -D
  20864. ** option to rename it.
  20865. **
  20866. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  20867. ** memory allocator. Set this symbol to enable
  20868. ** building on older macs.
  20869. **
  20870. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  20871. ** _msize() on windows systems. This might
  20872. ** be necessary when compiling for Delphi,
  20873. ** for example.
  20874. */
  20875. /* #include "sqliteInt.h" */
  20876. /*
  20877. ** This version of the memory allocator is the default. It is
  20878. ** used when no other memory allocator is specified using compile-time
  20879. ** macros.
  20880. */
  20881. #ifdef SQLITE_SYSTEM_MALLOC
  20882. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  20883. /*
  20884. ** Use the zone allocator available on apple products unless the
  20885. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  20886. */
  20887. #include <sys/sysctl.h>
  20888. #include <malloc/malloc.h>
  20889. #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
  20890. #include <libkern/OSAtomic.h>
  20891. #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
  20892. static malloc_zone_t* _sqliteZone_;
  20893. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  20894. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  20895. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  20896. #define SQLITE_MALLOCSIZE(x) \
  20897. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  20898. #else /* if not __APPLE__ */
  20899. /*
  20900. ** Use standard C library malloc and free on non-Apple systems.
  20901. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  20902. */
  20903. #define SQLITE_MALLOC(x) malloc(x)
  20904. #define SQLITE_FREE(x) free(x)
  20905. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  20906. /*
  20907. ** The malloc.h header file is needed for malloc_usable_size() function
  20908. ** on some systems (e.g. Linux).
  20909. */
  20910. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  20911. # define SQLITE_USE_MALLOC_H 1
  20912. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  20913. /*
  20914. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  20915. ** use of _msize() is automatic, but can be disabled by compiling with
  20916. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  20917. ** the malloc.h header file.
  20918. */
  20919. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  20920. # define SQLITE_USE_MALLOC_H
  20921. # define SQLITE_USE_MSIZE
  20922. #endif
  20923. /*
  20924. ** Include the malloc.h header file, if necessary. Also set define macro
  20925. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  20926. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  20927. ** The memory size function can always be overridden manually by defining
  20928. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  20929. */
  20930. #if defined(SQLITE_USE_MALLOC_H)
  20931. # include <malloc.h>
  20932. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  20933. # if !defined(SQLITE_MALLOCSIZE)
  20934. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  20935. # endif
  20936. # elif defined(SQLITE_USE_MSIZE)
  20937. # if !defined(SQLITE_MALLOCSIZE)
  20938. # define SQLITE_MALLOCSIZE _msize
  20939. # endif
  20940. # endif
  20941. #endif /* defined(SQLITE_USE_MALLOC_H) */
  20942. #endif /* __APPLE__ or not __APPLE__ */
  20943. /*
  20944. ** Like malloc(), but remember the size of the allocation
  20945. ** so that we can find it later using sqlite3MemSize().
  20946. **
  20947. ** For this low-level routine, we are guaranteed that nByte>0 because
  20948. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  20949. ** routines.
  20950. */
  20951. static void *sqlite3MemMalloc(int nByte){
  20952. #ifdef SQLITE_MALLOCSIZE
  20953. void *p;
  20954. testcase( ROUND8(nByte)==nByte );
  20955. p = SQLITE_MALLOC( nByte );
  20956. if( p==0 ){
  20957. testcase( sqlite3GlobalConfig.xLog!=0 );
  20958. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  20959. }
  20960. return p;
  20961. #else
  20962. sqlite3_int64 *p;
  20963. assert( nByte>0 );
  20964. testcase( ROUND8(nByte)!=nByte );
  20965. p = SQLITE_MALLOC( nByte+8 );
  20966. if( p ){
  20967. p[0] = nByte;
  20968. p++;
  20969. }else{
  20970. testcase( sqlite3GlobalConfig.xLog!=0 );
  20971. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  20972. }
  20973. return (void *)p;
  20974. #endif
  20975. }
  20976. /*
  20977. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  20978. ** or sqlite3MemRealloc().
  20979. **
  20980. ** For this low-level routine, we already know that pPrior!=0 since
  20981. ** cases where pPrior==0 will have been intecepted and dealt with
  20982. ** by higher-level routines.
  20983. */
  20984. static void sqlite3MemFree(void *pPrior){
  20985. #ifdef SQLITE_MALLOCSIZE
  20986. SQLITE_FREE(pPrior);
  20987. #else
  20988. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  20989. assert( pPrior!=0 );
  20990. p--;
  20991. SQLITE_FREE(p);
  20992. #endif
  20993. }
  20994. /*
  20995. ** Report the allocated size of a prior return from xMalloc()
  20996. ** or xRealloc().
  20997. */
  20998. static int sqlite3MemSize(void *pPrior){
  20999. #ifdef SQLITE_MALLOCSIZE
  21000. assert( pPrior!=0 );
  21001. return (int)SQLITE_MALLOCSIZE(pPrior);
  21002. #else
  21003. sqlite3_int64 *p;
  21004. assert( pPrior!=0 );
  21005. p = (sqlite3_int64*)pPrior;
  21006. p--;
  21007. return (int)p[0];
  21008. #endif
  21009. }
  21010. /*
  21011. ** Like realloc(). Resize an allocation previously obtained from
  21012. ** sqlite3MemMalloc().
  21013. **
  21014. ** For this low-level interface, we know that pPrior!=0. Cases where
  21015. ** pPrior==0 while have been intercepted by higher-level routine and
  21016. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  21017. ** cases where nByte<=0 will have been intercepted by higher-level
  21018. ** routines and redirected to xFree.
  21019. */
  21020. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  21021. #ifdef SQLITE_MALLOCSIZE
  21022. void *p = SQLITE_REALLOC(pPrior, nByte);
  21023. if( p==0 ){
  21024. testcase( sqlite3GlobalConfig.xLog!=0 );
  21025. sqlite3_log(SQLITE_NOMEM,
  21026. "failed memory resize %u to %u bytes",
  21027. SQLITE_MALLOCSIZE(pPrior), nByte);
  21028. }
  21029. return p;
  21030. #else
  21031. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  21032. assert( pPrior!=0 && nByte>0 );
  21033. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  21034. p--;
  21035. p = SQLITE_REALLOC(p, nByte+8 );
  21036. if( p ){
  21037. p[0] = nByte;
  21038. p++;
  21039. }else{
  21040. testcase( sqlite3GlobalConfig.xLog!=0 );
  21041. sqlite3_log(SQLITE_NOMEM,
  21042. "failed memory resize %u to %u bytes",
  21043. sqlite3MemSize(pPrior), nByte);
  21044. }
  21045. return (void*)p;
  21046. #endif
  21047. }
  21048. /*
  21049. ** Round up a request size to the next valid allocation size.
  21050. */
  21051. static int sqlite3MemRoundup(int n){
  21052. return ROUND8(n);
  21053. }
  21054. /*
  21055. ** Initialize this module.
  21056. */
  21057. static int sqlite3MemInit(void *NotUsed){
  21058. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  21059. int cpuCount;
  21060. size_t len;
  21061. if( _sqliteZone_ ){
  21062. return SQLITE_OK;
  21063. }
  21064. len = sizeof(cpuCount);
  21065. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  21066. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  21067. if( cpuCount>1 ){
  21068. /* defer MT decisions to system malloc */
  21069. _sqliteZone_ = malloc_default_zone();
  21070. }else{
  21071. /* only 1 core, use our own zone to contention over global locks,
  21072. ** e.g. we have our own dedicated locks */
  21073. _sqliteZone_ = malloc_create_zone(4096, 0);
  21074. malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
  21075. }
  21076. #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
  21077. UNUSED_PARAMETER(NotUsed);
  21078. return SQLITE_OK;
  21079. }
  21080. /*
  21081. ** Deinitialize this module.
  21082. */
  21083. static void sqlite3MemShutdown(void *NotUsed){
  21084. UNUSED_PARAMETER(NotUsed);
  21085. return;
  21086. }
  21087. /*
  21088. ** This routine is the only routine in this file with external linkage.
  21089. **
  21090. ** Populate the low-level memory allocation function pointers in
  21091. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  21092. */
  21093. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  21094. static const sqlite3_mem_methods defaultMethods = {
  21095. sqlite3MemMalloc,
  21096. sqlite3MemFree,
  21097. sqlite3MemRealloc,
  21098. sqlite3MemSize,
  21099. sqlite3MemRoundup,
  21100. sqlite3MemInit,
  21101. sqlite3MemShutdown,
  21102. 0
  21103. };
  21104. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  21105. }
  21106. #endif /* SQLITE_SYSTEM_MALLOC */
  21107. /************** End of mem1.c ************************************************/
  21108. /************** Begin file mem2.c ********************************************/
  21109. /*
  21110. ** 2007 August 15
  21111. **
  21112. ** The author disclaims copyright to this source code. In place of
  21113. ** a legal notice, here is a blessing:
  21114. **
  21115. ** May you do good and not evil.
  21116. ** May you find forgiveness for yourself and forgive others.
  21117. ** May you share freely, never taking more than you give.
  21118. **
  21119. *************************************************************************
  21120. **
  21121. ** This file contains low-level memory allocation drivers for when
  21122. ** SQLite will use the standard C-library malloc/realloc/free interface
  21123. ** to obtain the memory it needs while adding lots of additional debugging
  21124. ** information to each allocation in order to help detect and fix memory
  21125. ** leaks and memory usage errors.
  21126. **
  21127. ** This file contains implementations of the low-level memory allocation
  21128. ** routines specified in the sqlite3_mem_methods object.
  21129. */
  21130. /* #include "sqliteInt.h" */
  21131. /*
  21132. ** This version of the memory allocator is used only if the
  21133. ** SQLITE_MEMDEBUG macro is defined
  21134. */
  21135. #ifdef SQLITE_MEMDEBUG
  21136. /*
  21137. ** The backtrace functionality is only available with GLIBC
  21138. */
  21139. #ifdef __GLIBC__
  21140. extern int backtrace(void**,int);
  21141. extern void backtrace_symbols_fd(void*const*,int,int);
  21142. #else
  21143. # define backtrace(A,B) 1
  21144. # define backtrace_symbols_fd(A,B,C)
  21145. #endif
  21146. /* #include <stdio.h> */
  21147. /*
  21148. ** Each memory allocation looks like this:
  21149. **
  21150. ** ------------------------------------------------------------------------
  21151. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  21152. ** ------------------------------------------------------------------------
  21153. **
  21154. ** The application code sees only a pointer to the allocation. We have
  21155. ** to back up from the allocation pointer to find the MemBlockHdr. The
  21156. ** MemBlockHdr tells us the size of the allocation and the number of
  21157. ** backtrace pointers. There is also a guard word at the end of the
  21158. ** MemBlockHdr.
  21159. */
  21160. struct MemBlockHdr {
  21161. i64 iSize; /* Size of this allocation */
  21162. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  21163. char nBacktrace; /* Number of backtraces on this alloc */
  21164. char nBacktraceSlots; /* Available backtrace slots */
  21165. u8 nTitle; /* Bytes of title; includes '\0' */
  21166. u8 eType; /* Allocation type code */
  21167. int iForeGuard; /* Guard word for sanity */
  21168. };
  21169. /*
  21170. ** Guard words
  21171. */
  21172. #define FOREGUARD 0x80F5E153
  21173. #define REARGUARD 0xE4676B53
  21174. /*
  21175. ** Number of malloc size increments to track.
  21176. */
  21177. #define NCSIZE 1000
  21178. /*
  21179. ** All of the static variables used by this module are collected
  21180. ** into a single structure named "mem". This is to keep the
  21181. ** static variables organized and to reduce namespace pollution
  21182. ** when this module is combined with other in the amalgamation.
  21183. */
  21184. static struct {
  21185. /*
  21186. ** Mutex to control access to the memory allocation subsystem.
  21187. */
  21188. sqlite3_mutex *mutex;
  21189. /*
  21190. ** Head and tail of a linked list of all outstanding allocations
  21191. */
  21192. struct MemBlockHdr *pFirst;
  21193. struct MemBlockHdr *pLast;
  21194. /*
  21195. ** The number of levels of backtrace to save in new allocations.
  21196. */
  21197. int nBacktrace;
  21198. void (*xBacktrace)(int, int, void **);
  21199. /*
  21200. ** Title text to insert in front of each block
  21201. */
  21202. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  21203. char zTitle[100]; /* The title text */
  21204. /*
  21205. ** sqlite3MallocDisallow() increments the following counter.
  21206. ** sqlite3MallocAllow() decrements it.
  21207. */
  21208. int disallow; /* Do not allow memory allocation */
  21209. /*
  21210. ** Gather statistics on the sizes of memory allocations.
  21211. ** nAlloc[i] is the number of allocation attempts of i*8
  21212. ** bytes. i==NCSIZE is the number of allocation attempts for
  21213. ** sizes more than NCSIZE*8 bytes.
  21214. */
  21215. int nAlloc[NCSIZE]; /* Total number of allocations */
  21216. int nCurrent[NCSIZE]; /* Current number of allocations */
  21217. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  21218. } mem;
  21219. /*
  21220. ** Adjust memory usage statistics
  21221. */
  21222. static void adjustStats(int iSize, int increment){
  21223. int i = ROUND8(iSize)/8;
  21224. if( i>NCSIZE-1 ){
  21225. i = NCSIZE - 1;
  21226. }
  21227. if( increment>0 ){
  21228. mem.nAlloc[i]++;
  21229. mem.nCurrent[i]++;
  21230. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  21231. mem.mxCurrent[i] = mem.nCurrent[i];
  21232. }
  21233. }else{
  21234. mem.nCurrent[i]--;
  21235. assert( mem.nCurrent[i]>=0 );
  21236. }
  21237. }
  21238. /*
  21239. ** Given an allocation, find the MemBlockHdr for that allocation.
  21240. **
  21241. ** This routine checks the guards at either end of the allocation and
  21242. ** if they are incorrect it asserts.
  21243. */
  21244. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  21245. struct MemBlockHdr *p;
  21246. int *pInt;
  21247. u8 *pU8;
  21248. int nReserve;
  21249. p = (struct MemBlockHdr*)pAllocation;
  21250. p--;
  21251. assert( p->iForeGuard==(int)FOREGUARD );
  21252. nReserve = ROUND8(p->iSize);
  21253. pInt = (int*)pAllocation;
  21254. pU8 = (u8*)pAllocation;
  21255. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  21256. /* This checks any of the "extra" bytes allocated due
  21257. ** to rounding up to an 8 byte boundary to ensure
  21258. ** they haven't been overwritten.
  21259. */
  21260. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  21261. return p;
  21262. }
  21263. /*
  21264. ** Return the number of bytes currently allocated at address p.
  21265. */
  21266. static int sqlite3MemSize(void *p){
  21267. struct MemBlockHdr *pHdr;
  21268. if( !p ){
  21269. return 0;
  21270. }
  21271. pHdr = sqlite3MemsysGetHeader(p);
  21272. return (int)pHdr->iSize;
  21273. }
  21274. /*
  21275. ** Initialize the memory allocation subsystem.
  21276. */
  21277. static int sqlite3MemInit(void *NotUsed){
  21278. UNUSED_PARAMETER(NotUsed);
  21279. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  21280. if( !sqlite3GlobalConfig.bMemstat ){
  21281. /* If memory status is enabled, then the malloc.c wrapper will already
  21282. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  21283. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  21284. }
  21285. return SQLITE_OK;
  21286. }
  21287. /*
  21288. ** Deinitialize the memory allocation subsystem.
  21289. */
  21290. static void sqlite3MemShutdown(void *NotUsed){
  21291. UNUSED_PARAMETER(NotUsed);
  21292. mem.mutex = 0;
  21293. }
  21294. /*
  21295. ** Round up a request size to the next valid allocation size.
  21296. */
  21297. static int sqlite3MemRoundup(int n){
  21298. return ROUND8(n);
  21299. }
  21300. /*
  21301. ** Fill a buffer with pseudo-random bytes. This is used to preset
  21302. ** the content of a new memory allocation to unpredictable values and
  21303. ** to clear the content of a freed allocation to unpredictable values.
  21304. */
  21305. static void randomFill(char *pBuf, int nByte){
  21306. unsigned int x, y, r;
  21307. x = SQLITE_PTR_TO_INT(pBuf);
  21308. y = nByte | 1;
  21309. while( nByte >= 4 ){
  21310. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  21311. y = y*1103515245 + 12345;
  21312. r = x ^ y;
  21313. *(int*)pBuf = r;
  21314. pBuf += 4;
  21315. nByte -= 4;
  21316. }
  21317. while( nByte-- > 0 ){
  21318. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  21319. y = y*1103515245 + 12345;
  21320. r = x ^ y;
  21321. *(pBuf++) = r & 0xff;
  21322. }
  21323. }
  21324. /*
  21325. ** Allocate nByte bytes of memory.
  21326. */
  21327. static void *sqlite3MemMalloc(int nByte){
  21328. struct MemBlockHdr *pHdr;
  21329. void **pBt;
  21330. char *z;
  21331. int *pInt;
  21332. void *p = 0;
  21333. int totalSize;
  21334. int nReserve;
  21335. sqlite3_mutex_enter(mem.mutex);
  21336. assert( mem.disallow==0 );
  21337. nReserve = ROUND8(nByte);
  21338. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  21339. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  21340. p = malloc(totalSize);
  21341. if( p ){
  21342. z = p;
  21343. pBt = (void**)&z[mem.nTitle];
  21344. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  21345. pHdr->pNext = 0;
  21346. pHdr->pPrev = mem.pLast;
  21347. if( mem.pLast ){
  21348. mem.pLast->pNext = pHdr;
  21349. }else{
  21350. mem.pFirst = pHdr;
  21351. }
  21352. mem.pLast = pHdr;
  21353. pHdr->iForeGuard = FOREGUARD;
  21354. pHdr->eType = MEMTYPE_HEAP;
  21355. pHdr->nBacktraceSlots = mem.nBacktrace;
  21356. pHdr->nTitle = mem.nTitle;
  21357. if( mem.nBacktrace ){
  21358. void *aAddr[40];
  21359. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  21360. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  21361. assert(pBt[0]);
  21362. if( mem.xBacktrace ){
  21363. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  21364. }
  21365. }else{
  21366. pHdr->nBacktrace = 0;
  21367. }
  21368. if( mem.nTitle ){
  21369. memcpy(z, mem.zTitle, mem.nTitle);
  21370. }
  21371. pHdr->iSize = nByte;
  21372. adjustStats(nByte, +1);
  21373. pInt = (int*)&pHdr[1];
  21374. pInt[nReserve/sizeof(int)] = REARGUARD;
  21375. randomFill((char*)pInt, nByte);
  21376. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  21377. p = (void*)pInt;
  21378. }
  21379. sqlite3_mutex_leave(mem.mutex);
  21380. return p;
  21381. }
  21382. /*
  21383. ** Free memory.
  21384. */
  21385. static void sqlite3MemFree(void *pPrior){
  21386. struct MemBlockHdr *pHdr;
  21387. void **pBt;
  21388. char *z;
  21389. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  21390. || mem.mutex!=0 );
  21391. pHdr = sqlite3MemsysGetHeader(pPrior);
  21392. pBt = (void**)pHdr;
  21393. pBt -= pHdr->nBacktraceSlots;
  21394. sqlite3_mutex_enter(mem.mutex);
  21395. if( pHdr->pPrev ){
  21396. assert( pHdr->pPrev->pNext==pHdr );
  21397. pHdr->pPrev->pNext = pHdr->pNext;
  21398. }else{
  21399. assert( mem.pFirst==pHdr );
  21400. mem.pFirst = pHdr->pNext;
  21401. }
  21402. if( pHdr->pNext ){
  21403. assert( pHdr->pNext->pPrev==pHdr );
  21404. pHdr->pNext->pPrev = pHdr->pPrev;
  21405. }else{
  21406. assert( mem.pLast==pHdr );
  21407. mem.pLast = pHdr->pPrev;
  21408. }
  21409. z = (char*)pBt;
  21410. z -= pHdr->nTitle;
  21411. adjustStats((int)pHdr->iSize, -1);
  21412. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  21413. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  21414. free(z);
  21415. sqlite3_mutex_leave(mem.mutex);
  21416. }
  21417. /*
  21418. ** Change the size of an existing memory allocation.
  21419. **
  21420. ** For this debugging implementation, we *always* make a copy of the
  21421. ** allocation into a new place in memory. In this way, if the
  21422. ** higher level code is using pointer to the old allocation, it is
  21423. ** much more likely to break and we are much more liking to find
  21424. ** the error.
  21425. */
  21426. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  21427. struct MemBlockHdr *pOldHdr;
  21428. void *pNew;
  21429. assert( mem.disallow==0 );
  21430. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  21431. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  21432. pNew = sqlite3MemMalloc(nByte);
  21433. if( pNew ){
  21434. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  21435. if( nByte>pOldHdr->iSize ){
  21436. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  21437. }
  21438. sqlite3MemFree(pPrior);
  21439. }
  21440. return pNew;
  21441. }
  21442. /*
  21443. ** Populate the low-level memory allocation function pointers in
  21444. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  21445. */
  21446. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  21447. static const sqlite3_mem_methods defaultMethods = {
  21448. sqlite3MemMalloc,
  21449. sqlite3MemFree,
  21450. sqlite3MemRealloc,
  21451. sqlite3MemSize,
  21452. sqlite3MemRoundup,
  21453. sqlite3MemInit,
  21454. sqlite3MemShutdown,
  21455. 0
  21456. };
  21457. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  21458. }
  21459. /*
  21460. ** Set the "type" of an allocation.
  21461. */
  21462. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  21463. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  21464. struct MemBlockHdr *pHdr;
  21465. pHdr = sqlite3MemsysGetHeader(p);
  21466. assert( pHdr->iForeGuard==FOREGUARD );
  21467. pHdr->eType = eType;
  21468. }
  21469. }
  21470. /*
  21471. ** Return TRUE if the mask of type in eType matches the type of the
  21472. ** allocation p. Also return true if p==NULL.
  21473. **
  21474. ** This routine is designed for use within an assert() statement, to
  21475. ** verify the type of an allocation. For example:
  21476. **
  21477. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  21478. */
  21479. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  21480. int rc = 1;
  21481. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  21482. struct MemBlockHdr *pHdr;
  21483. pHdr = sqlite3MemsysGetHeader(p);
  21484. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  21485. if( (pHdr->eType&eType)==0 ){
  21486. rc = 0;
  21487. }
  21488. }
  21489. return rc;
  21490. }
  21491. /*
  21492. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  21493. ** allocation p. Also return true if p==NULL.
  21494. **
  21495. ** This routine is designed for use within an assert() statement, to
  21496. ** verify the type of an allocation. For example:
  21497. **
  21498. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  21499. */
  21500. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  21501. int rc = 1;
  21502. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  21503. struct MemBlockHdr *pHdr;
  21504. pHdr = sqlite3MemsysGetHeader(p);
  21505. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  21506. if( (pHdr->eType&eType)!=0 ){
  21507. rc = 0;
  21508. }
  21509. }
  21510. return rc;
  21511. }
  21512. /*
  21513. ** Set the number of backtrace levels kept for each allocation.
  21514. ** A value of zero turns off backtracing. The number is always rounded
  21515. ** up to a multiple of 2.
  21516. */
  21517. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  21518. if( depth<0 ){ depth = 0; }
  21519. if( depth>20 ){ depth = 20; }
  21520. depth = (depth+1)&0xfe;
  21521. mem.nBacktrace = depth;
  21522. }
  21523. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  21524. mem.xBacktrace = xBacktrace;
  21525. }
  21526. /*
  21527. ** Set the title string for subsequent allocations.
  21528. */
  21529. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  21530. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  21531. sqlite3_mutex_enter(mem.mutex);
  21532. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  21533. memcpy(mem.zTitle, zTitle, n);
  21534. mem.zTitle[n] = 0;
  21535. mem.nTitle = ROUND8(n);
  21536. sqlite3_mutex_leave(mem.mutex);
  21537. }
  21538. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  21539. struct MemBlockHdr *pHdr;
  21540. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  21541. void **pBt = (void**)pHdr;
  21542. pBt -= pHdr->nBacktraceSlots;
  21543. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  21544. }
  21545. }
  21546. /*
  21547. ** Open the file indicated and write a log of all unfreed memory
  21548. ** allocations into that log.
  21549. */
  21550. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  21551. FILE *out;
  21552. struct MemBlockHdr *pHdr;
  21553. void **pBt;
  21554. int i;
  21555. out = fopen(zFilename, "w");
  21556. if( out==0 ){
  21557. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  21558. zFilename);
  21559. return;
  21560. }
  21561. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  21562. char *z = (char*)pHdr;
  21563. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  21564. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  21565. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  21566. if( pHdr->nBacktrace ){
  21567. fflush(out);
  21568. pBt = (void**)pHdr;
  21569. pBt -= pHdr->nBacktraceSlots;
  21570. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  21571. fprintf(out, "\n");
  21572. }
  21573. }
  21574. fprintf(out, "COUNTS:\n");
  21575. for(i=0; i<NCSIZE-1; i++){
  21576. if( mem.nAlloc[i] ){
  21577. fprintf(out, " %5d: %10d %10d %10d\n",
  21578. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  21579. }
  21580. }
  21581. if( mem.nAlloc[NCSIZE-1] ){
  21582. fprintf(out, " %5d: %10d %10d %10d\n",
  21583. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  21584. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  21585. }
  21586. fclose(out);
  21587. }
  21588. /*
  21589. ** Return the number of times sqlite3MemMalloc() has been called.
  21590. */
  21591. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  21592. int i;
  21593. int nTotal = 0;
  21594. for(i=0; i<NCSIZE; i++){
  21595. nTotal += mem.nAlloc[i];
  21596. }
  21597. return nTotal;
  21598. }
  21599. #endif /* SQLITE_MEMDEBUG */
  21600. /************** End of mem2.c ************************************************/
  21601. /************** Begin file mem3.c ********************************************/
  21602. /*
  21603. ** 2007 October 14
  21604. **
  21605. ** The author disclaims copyright to this source code. In place of
  21606. ** a legal notice, here is a blessing:
  21607. **
  21608. ** May you do good and not evil.
  21609. ** May you find forgiveness for yourself and forgive others.
  21610. ** May you share freely, never taking more than you give.
  21611. **
  21612. *************************************************************************
  21613. ** This file contains the C functions that implement a memory
  21614. ** allocation subsystem for use by SQLite.
  21615. **
  21616. ** This version of the memory allocation subsystem omits all
  21617. ** use of malloc(). The SQLite user supplies a block of memory
  21618. ** before calling sqlite3_initialize() from which allocations
  21619. ** are made and returned by the xMalloc() and xRealloc()
  21620. ** implementations. Once sqlite3_initialize() has been called,
  21621. ** the amount of memory available to SQLite is fixed and cannot
  21622. ** be changed.
  21623. **
  21624. ** This version of the memory allocation subsystem is included
  21625. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  21626. */
  21627. /* #include "sqliteInt.h" */
  21628. /*
  21629. ** This version of the memory allocator is only built into the library
  21630. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  21631. ** mean that the library will use a memory-pool by default, just that
  21632. ** it is available. The mempool allocator is activated by calling
  21633. ** sqlite3_config().
  21634. */
  21635. #ifdef SQLITE_ENABLE_MEMSYS3
  21636. /*
  21637. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  21638. */
  21639. #define MX_SMALL 10
  21640. /*
  21641. ** Number of freelist hash slots
  21642. */
  21643. #define N_HASH 61
  21644. /*
  21645. ** A memory allocation (also called a "chunk") consists of two or
  21646. ** more blocks where each block is 8 bytes. The first 8 bytes are
  21647. ** a header that is not returned to the user.
  21648. **
  21649. ** A chunk is two or more blocks that is either checked out or
  21650. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  21651. ** size of the allocation in blocks if the allocation is free.
  21652. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  21653. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  21654. ** is true if the previous chunk is checked out and false if the
  21655. ** previous chunk is free. The u.hdr.prevSize field is the size of
  21656. ** the previous chunk in blocks if the previous chunk is on the
  21657. ** freelist. If the previous chunk is checked out, then
  21658. ** u.hdr.prevSize can be part of the data for that chunk and should
  21659. ** not be read or written.
  21660. **
  21661. ** We often identify a chunk by its index in mem3.aPool[]. When
  21662. ** this is done, the chunk index refers to the second block of
  21663. ** the chunk. In this way, the first chunk has an index of 1.
  21664. ** A chunk index of 0 means "no such chunk" and is the equivalent
  21665. ** of a NULL pointer.
  21666. **
  21667. ** The second block of free chunks is of the form u.list. The
  21668. ** two fields form a double-linked list of chunks of related sizes.
  21669. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  21670. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  21671. **
  21672. ** The second block of a chunk is user data if the chunk is checked
  21673. ** out. If a chunk is checked out, the user data may extend into
  21674. ** the u.hdr.prevSize value of the following chunk.
  21675. */
  21676. typedef struct Mem3Block Mem3Block;
  21677. struct Mem3Block {
  21678. union {
  21679. struct {
  21680. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  21681. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  21682. } hdr;
  21683. struct {
  21684. u32 next; /* Index in mem3.aPool[] of next free chunk */
  21685. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  21686. } list;
  21687. } u;
  21688. };
  21689. /*
  21690. ** All of the static variables used by this module are collected
  21691. ** into a single structure named "mem3". This is to keep the
  21692. ** static variables organized and to reduce namespace pollution
  21693. ** when this module is combined with other in the amalgamation.
  21694. */
  21695. static SQLITE_WSD struct Mem3Global {
  21696. /*
  21697. ** Memory available for allocation. nPool is the size of the array
  21698. ** (in Mem3Blocks) pointed to by aPool less 2.
  21699. */
  21700. u32 nPool;
  21701. Mem3Block *aPool;
  21702. /*
  21703. ** True if we are evaluating an out-of-memory callback.
  21704. */
  21705. int alarmBusy;
  21706. /*
  21707. ** Mutex to control access to the memory allocation subsystem.
  21708. */
  21709. sqlite3_mutex *mutex;
  21710. /*
  21711. ** The minimum amount of free space that we have seen.
  21712. */
  21713. u32 mnMaster;
  21714. /*
  21715. ** iMaster is the index of the master chunk. Most new allocations
  21716. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  21717. ** of the current master. iMaster is 0 if there is not master chunk.
  21718. ** The master chunk is not in either the aiHash[] or aiSmall[].
  21719. */
  21720. u32 iMaster;
  21721. u32 szMaster;
  21722. /*
  21723. ** Array of lists of free blocks according to the block size
  21724. ** for smaller chunks, or a hash on the block size for larger
  21725. ** chunks.
  21726. */
  21727. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  21728. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  21729. } mem3 = { 97535575 };
  21730. #define mem3 GLOBAL(struct Mem3Global, mem3)
  21731. /*
  21732. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  21733. ** on. *pRoot is the list that i is a member of.
  21734. */
  21735. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  21736. u32 next = mem3.aPool[i].u.list.next;
  21737. u32 prev = mem3.aPool[i].u.list.prev;
  21738. assert( sqlite3_mutex_held(mem3.mutex) );
  21739. if( prev==0 ){
  21740. *pRoot = next;
  21741. }else{
  21742. mem3.aPool[prev].u.list.next = next;
  21743. }
  21744. if( next ){
  21745. mem3.aPool[next].u.list.prev = prev;
  21746. }
  21747. mem3.aPool[i].u.list.next = 0;
  21748. mem3.aPool[i].u.list.prev = 0;
  21749. }
  21750. /*
  21751. ** Unlink the chunk at index i from
  21752. ** whatever list is currently a member of.
  21753. */
  21754. static void memsys3Unlink(u32 i){
  21755. u32 size, hash;
  21756. assert( sqlite3_mutex_held(mem3.mutex) );
  21757. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  21758. assert( i>=1 );
  21759. size = mem3.aPool[i-1].u.hdr.size4x/4;
  21760. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  21761. assert( size>=2 );
  21762. if( size <= MX_SMALL ){
  21763. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  21764. }else{
  21765. hash = size % N_HASH;
  21766. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  21767. }
  21768. }
  21769. /*
  21770. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  21771. ** at *pRoot.
  21772. */
  21773. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  21774. assert( sqlite3_mutex_held(mem3.mutex) );
  21775. mem3.aPool[i].u.list.next = *pRoot;
  21776. mem3.aPool[i].u.list.prev = 0;
  21777. if( *pRoot ){
  21778. mem3.aPool[*pRoot].u.list.prev = i;
  21779. }
  21780. *pRoot = i;
  21781. }
  21782. /*
  21783. ** Link the chunk at index i into either the appropriate
  21784. ** small chunk list, or into the large chunk hash table.
  21785. */
  21786. static void memsys3Link(u32 i){
  21787. u32 size, hash;
  21788. assert( sqlite3_mutex_held(mem3.mutex) );
  21789. assert( i>=1 );
  21790. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  21791. size = mem3.aPool[i-1].u.hdr.size4x/4;
  21792. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  21793. assert( size>=2 );
  21794. if( size <= MX_SMALL ){
  21795. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  21796. }else{
  21797. hash = size % N_HASH;
  21798. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  21799. }
  21800. }
  21801. /*
  21802. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  21803. ** will already be held (obtained by code in malloc.c) if
  21804. ** sqlite3GlobalConfig.bMemStat is true.
  21805. */
  21806. static void memsys3Enter(void){
  21807. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  21808. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  21809. }
  21810. sqlite3_mutex_enter(mem3.mutex);
  21811. }
  21812. static void memsys3Leave(void){
  21813. sqlite3_mutex_leave(mem3.mutex);
  21814. }
  21815. /*
  21816. ** Called when we are unable to satisfy an allocation of nBytes.
  21817. */
  21818. static void memsys3OutOfMemory(int nByte){
  21819. if( !mem3.alarmBusy ){
  21820. mem3.alarmBusy = 1;
  21821. assert( sqlite3_mutex_held(mem3.mutex) );
  21822. sqlite3_mutex_leave(mem3.mutex);
  21823. sqlite3_release_memory(nByte);
  21824. sqlite3_mutex_enter(mem3.mutex);
  21825. mem3.alarmBusy = 0;
  21826. }
  21827. }
  21828. /*
  21829. ** Chunk i is a free chunk that has been unlinked. Adjust its
  21830. ** size parameters for check-out and return a pointer to the
  21831. ** user portion of the chunk.
  21832. */
  21833. static void *memsys3Checkout(u32 i, u32 nBlock){
  21834. u32 x;
  21835. assert( sqlite3_mutex_held(mem3.mutex) );
  21836. assert( i>=1 );
  21837. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  21838. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  21839. x = mem3.aPool[i-1].u.hdr.size4x;
  21840. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  21841. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  21842. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  21843. return &mem3.aPool[i];
  21844. }
  21845. /*
  21846. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  21847. ** Return a pointer to the new allocation. Or, if the master chunk
  21848. ** is not large enough, return 0.
  21849. */
  21850. static void *memsys3FromMaster(u32 nBlock){
  21851. assert( sqlite3_mutex_held(mem3.mutex) );
  21852. assert( mem3.szMaster>=nBlock );
  21853. if( nBlock>=mem3.szMaster-1 ){
  21854. /* Use the entire master */
  21855. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  21856. mem3.iMaster = 0;
  21857. mem3.szMaster = 0;
  21858. mem3.mnMaster = 0;
  21859. return p;
  21860. }else{
  21861. /* Split the master block. Return the tail. */
  21862. u32 newi, x;
  21863. newi = mem3.iMaster + mem3.szMaster - nBlock;
  21864. assert( newi > mem3.iMaster+1 );
  21865. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  21866. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  21867. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  21868. mem3.szMaster -= nBlock;
  21869. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  21870. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  21871. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  21872. if( mem3.szMaster < mem3.mnMaster ){
  21873. mem3.mnMaster = mem3.szMaster;
  21874. }
  21875. return (void*)&mem3.aPool[newi];
  21876. }
  21877. }
  21878. /*
  21879. ** *pRoot is the head of a list of free chunks of the same size
  21880. ** or same size hash. In other words, *pRoot is an entry in either
  21881. ** mem3.aiSmall[] or mem3.aiHash[].
  21882. **
  21883. ** This routine examines all entries on the given list and tries
  21884. ** to coalesce each entries with adjacent free chunks.
  21885. **
  21886. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  21887. ** the current mem3.iMaster with the new larger chunk. In order for
  21888. ** this mem3.iMaster replacement to work, the master chunk must be
  21889. ** linked into the hash tables. That is not the normal state of
  21890. ** affairs, of course. The calling routine must link the master
  21891. ** chunk before invoking this routine, then must unlink the (possibly
  21892. ** changed) master chunk once this routine has finished.
  21893. */
  21894. static void memsys3Merge(u32 *pRoot){
  21895. u32 iNext, prev, size, i, x;
  21896. assert( sqlite3_mutex_held(mem3.mutex) );
  21897. for(i=*pRoot; i>0; i=iNext){
  21898. iNext = mem3.aPool[i].u.list.next;
  21899. size = mem3.aPool[i-1].u.hdr.size4x;
  21900. assert( (size&1)==0 );
  21901. if( (size&2)==0 ){
  21902. memsys3UnlinkFromList(i, pRoot);
  21903. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  21904. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  21905. if( prev==iNext ){
  21906. iNext = mem3.aPool[prev].u.list.next;
  21907. }
  21908. memsys3Unlink(prev);
  21909. size = i + size/4 - prev;
  21910. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  21911. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  21912. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  21913. memsys3Link(prev);
  21914. i = prev;
  21915. }else{
  21916. size /= 4;
  21917. }
  21918. if( size>mem3.szMaster ){
  21919. mem3.iMaster = i;
  21920. mem3.szMaster = size;
  21921. }
  21922. }
  21923. }
  21924. /*
  21925. ** Return a block of memory of at least nBytes in size.
  21926. ** Return NULL if unable.
  21927. **
  21928. ** This function assumes that the necessary mutexes, if any, are
  21929. ** already held by the caller. Hence "Unsafe".
  21930. */
  21931. static void *memsys3MallocUnsafe(int nByte){
  21932. u32 i;
  21933. u32 nBlock;
  21934. u32 toFree;
  21935. assert( sqlite3_mutex_held(mem3.mutex) );
  21936. assert( sizeof(Mem3Block)==8 );
  21937. if( nByte<=12 ){
  21938. nBlock = 2;
  21939. }else{
  21940. nBlock = (nByte + 11)/8;
  21941. }
  21942. assert( nBlock>=2 );
  21943. /* STEP 1:
  21944. ** Look for an entry of the correct size in either the small
  21945. ** chunk table or in the large chunk hash table. This is
  21946. ** successful most of the time (about 9 times out of 10).
  21947. */
  21948. if( nBlock <= MX_SMALL ){
  21949. i = mem3.aiSmall[nBlock-2];
  21950. if( i>0 ){
  21951. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  21952. return memsys3Checkout(i, nBlock);
  21953. }
  21954. }else{
  21955. int hash = nBlock % N_HASH;
  21956. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  21957. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  21958. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  21959. return memsys3Checkout(i, nBlock);
  21960. }
  21961. }
  21962. }
  21963. /* STEP 2:
  21964. ** Try to satisfy the allocation by carving a piece off of the end
  21965. ** of the master chunk. This step usually works if step 1 fails.
  21966. */
  21967. if( mem3.szMaster>=nBlock ){
  21968. return memsys3FromMaster(nBlock);
  21969. }
  21970. /* STEP 3:
  21971. ** Loop through the entire memory pool. Coalesce adjacent free
  21972. ** chunks. Recompute the master chunk as the largest free chunk.
  21973. ** Then try again to satisfy the allocation by carving a piece off
  21974. ** of the end of the master chunk. This step happens very
  21975. ** rarely (we hope!)
  21976. */
  21977. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  21978. memsys3OutOfMemory(toFree);
  21979. if( mem3.iMaster ){
  21980. memsys3Link(mem3.iMaster);
  21981. mem3.iMaster = 0;
  21982. mem3.szMaster = 0;
  21983. }
  21984. for(i=0; i<N_HASH; i++){
  21985. memsys3Merge(&mem3.aiHash[i]);
  21986. }
  21987. for(i=0; i<MX_SMALL-1; i++){
  21988. memsys3Merge(&mem3.aiSmall[i]);
  21989. }
  21990. if( mem3.szMaster ){
  21991. memsys3Unlink(mem3.iMaster);
  21992. if( mem3.szMaster>=nBlock ){
  21993. return memsys3FromMaster(nBlock);
  21994. }
  21995. }
  21996. }
  21997. /* If none of the above worked, then we fail. */
  21998. return 0;
  21999. }
  22000. /*
  22001. ** Free an outstanding memory allocation.
  22002. **
  22003. ** This function assumes that the necessary mutexes, if any, are
  22004. ** already held by the caller. Hence "Unsafe".
  22005. */
  22006. static void memsys3FreeUnsafe(void *pOld){
  22007. Mem3Block *p = (Mem3Block*)pOld;
  22008. int i;
  22009. u32 size, x;
  22010. assert( sqlite3_mutex_held(mem3.mutex) );
  22011. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  22012. i = p - mem3.aPool;
  22013. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  22014. size = mem3.aPool[i-1].u.hdr.size4x/4;
  22015. assert( i+size<=mem3.nPool+1 );
  22016. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  22017. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  22018. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  22019. memsys3Link(i);
  22020. /* Try to expand the master using the newly freed chunk */
  22021. if( mem3.iMaster ){
  22022. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  22023. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  22024. mem3.iMaster -= size;
  22025. mem3.szMaster += size;
  22026. memsys3Unlink(mem3.iMaster);
  22027. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22028. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22029. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  22030. }
  22031. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  22032. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  22033. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  22034. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  22035. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  22036. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  22037. }
  22038. }
  22039. }
  22040. /*
  22041. ** Return the size of an outstanding allocation, in bytes. The
  22042. ** size returned omits the 8-byte header overhead. This only
  22043. ** works for chunks that are currently checked out.
  22044. */
  22045. static int memsys3Size(void *p){
  22046. Mem3Block *pBlock;
  22047. assert( p!=0 );
  22048. pBlock = (Mem3Block*)p;
  22049. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  22050. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  22051. }
  22052. /*
  22053. ** Round up a request size to the next valid allocation size.
  22054. */
  22055. static int memsys3Roundup(int n){
  22056. if( n<=12 ){
  22057. return 12;
  22058. }else{
  22059. return ((n+11)&~7) - 4;
  22060. }
  22061. }
  22062. /*
  22063. ** Allocate nBytes of memory.
  22064. */
  22065. static void *memsys3Malloc(int nBytes){
  22066. sqlite3_int64 *p;
  22067. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  22068. memsys3Enter();
  22069. p = memsys3MallocUnsafe(nBytes);
  22070. memsys3Leave();
  22071. return (void*)p;
  22072. }
  22073. /*
  22074. ** Free memory.
  22075. */
  22076. static void memsys3Free(void *pPrior){
  22077. assert( pPrior );
  22078. memsys3Enter();
  22079. memsys3FreeUnsafe(pPrior);
  22080. memsys3Leave();
  22081. }
  22082. /*
  22083. ** Change the size of an existing memory allocation
  22084. */
  22085. static void *memsys3Realloc(void *pPrior, int nBytes){
  22086. int nOld;
  22087. void *p;
  22088. if( pPrior==0 ){
  22089. return sqlite3_malloc(nBytes);
  22090. }
  22091. if( nBytes<=0 ){
  22092. sqlite3_free(pPrior);
  22093. return 0;
  22094. }
  22095. nOld = memsys3Size(pPrior);
  22096. if( nBytes<=nOld && nBytes>=nOld-128 ){
  22097. return pPrior;
  22098. }
  22099. memsys3Enter();
  22100. p = memsys3MallocUnsafe(nBytes);
  22101. if( p ){
  22102. if( nOld<nBytes ){
  22103. memcpy(p, pPrior, nOld);
  22104. }else{
  22105. memcpy(p, pPrior, nBytes);
  22106. }
  22107. memsys3FreeUnsafe(pPrior);
  22108. }
  22109. memsys3Leave();
  22110. return p;
  22111. }
  22112. /*
  22113. ** Initialize this module.
  22114. */
  22115. static int memsys3Init(void *NotUsed){
  22116. UNUSED_PARAMETER(NotUsed);
  22117. if( !sqlite3GlobalConfig.pHeap ){
  22118. return SQLITE_ERROR;
  22119. }
  22120. /* Store a pointer to the memory block in global structure mem3. */
  22121. assert( sizeof(Mem3Block)==8 );
  22122. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  22123. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  22124. /* Initialize the master block. */
  22125. mem3.szMaster = mem3.nPool;
  22126. mem3.mnMaster = mem3.szMaster;
  22127. mem3.iMaster = 1;
  22128. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  22129. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  22130. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  22131. return SQLITE_OK;
  22132. }
  22133. /*
  22134. ** Deinitialize this module.
  22135. */
  22136. static void memsys3Shutdown(void *NotUsed){
  22137. UNUSED_PARAMETER(NotUsed);
  22138. mem3.mutex = 0;
  22139. return;
  22140. }
  22141. /*
  22142. ** Open the file indicated and write a log of all unfreed memory
  22143. ** allocations into that log.
  22144. */
  22145. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  22146. #ifdef SQLITE_DEBUG
  22147. FILE *out;
  22148. u32 i, j;
  22149. u32 size;
  22150. if( zFilename==0 || zFilename[0]==0 ){
  22151. out = stdout;
  22152. }else{
  22153. out = fopen(zFilename, "w");
  22154. if( out==0 ){
  22155. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  22156. zFilename);
  22157. return;
  22158. }
  22159. }
  22160. memsys3Enter();
  22161. fprintf(out, "CHUNKS:\n");
  22162. for(i=1; i<=mem3.nPool; i+=size/4){
  22163. size = mem3.aPool[i-1].u.hdr.size4x;
  22164. if( size/4<=1 ){
  22165. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  22166. assert( 0 );
  22167. break;
  22168. }
  22169. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  22170. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  22171. assert( 0 );
  22172. break;
  22173. }
  22174. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  22175. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  22176. assert( 0 );
  22177. break;
  22178. }
  22179. if( size&1 ){
  22180. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  22181. }else{
  22182. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  22183. i==mem3.iMaster ? " **master**" : "");
  22184. }
  22185. }
  22186. for(i=0; i<MX_SMALL-1; i++){
  22187. if( mem3.aiSmall[i]==0 ) continue;
  22188. fprintf(out, "small(%2d):", i);
  22189. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  22190. fprintf(out, " %p(%d)", &mem3.aPool[j],
  22191. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  22192. }
  22193. fprintf(out, "\n");
  22194. }
  22195. for(i=0; i<N_HASH; i++){
  22196. if( mem3.aiHash[i]==0 ) continue;
  22197. fprintf(out, "hash(%2d):", i);
  22198. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  22199. fprintf(out, " %p(%d)", &mem3.aPool[j],
  22200. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  22201. }
  22202. fprintf(out, "\n");
  22203. }
  22204. fprintf(out, "master=%d\n", mem3.iMaster);
  22205. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  22206. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  22207. sqlite3_mutex_leave(mem3.mutex);
  22208. if( out==stdout ){
  22209. fflush(stdout);
  22210. }else{
  22211. fclose(out);
  22212. }
  22213. #else
  22214. UNUSED_PARAMETER(zFilename);
  22215. #endif
  22216. }
  22217. /*
  22218. ** This routine is the only routine in this file with external
  22219. ** linkage.
  22220. **
  22221. ** Populate the low-level memory allocation function pointers in
  22222. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  22223. ** arguments specify the block of memory to manage.
  22224. **
  22225. ** This routine is only called by sqlite3_config(), and therefore
  22226. ** is not required to be threadsafe (it is not).
  22227. */
  22228. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  22229. static const sqlite3_mem_methods mempoolMethods = {
  22230. memsys3Malloc,
  22231. memsys3Free,
  22232. memsys3Realloc,
  22233. memsys3Size,
  22234. memsys3Roundup,
  22235. memsys3Init,
  22236. memsys3Shutdown,
  22237. 0
  22238. };
  22239. return &mempoolMethods;
  22240. }
  22241. #endif /* SQLITE_ENABLE_MEMSYS3 */
  22242. /************** End of mem3.c ************************************************/
  22243. /************** Begin file mem5.c ********************************************/
  22244. /*
  22245. ** 2007 October 14
  22246. **
  22247. ** The author disclaims copyright to this source code. In place of
  22248. ** a legal notice, here is a blessing:
  22249. **
  22250. ** May you do good and not evil.
  22251. ** May you find forgiveness for yourself and forgive others.
  22252. ** May you share freely, never taking more than you give.
  22253. **
  22254. *************************************************************************
  22255. ** This file contains the C functions that implement a memory
  22256. ** allocation subsystem for use by SQLite.
  22257. **
  22258. ** This version of the memory allocation subsystem omits all
  22259. ** use of malloc(). The application gives SQLite a block of memory
  22260. ** before calling sqlite3_initialize() from which allocations
  22261. ** are made and returned by the xMalloc() and xRealloc()
  22262. ** implementations. Once sqlite3_initialize() has been called,
  22263. ** the amount of memory available to SQLite is fixed and cannot
  22264. ** be changed.
  22265. **
  22266. ** This version of the memory allocation subsystem is included
  22267. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  22268. **
  22269. ** This memory allocator uses the following algorithm:
  22270. **
  22271. ** 1. All memory allocation sizes are rounded up to a power of 2.
  22272. **
  22273. ** 2. If two adjacent free blocks are the halves of a larger block,
  22274. ** then the two blocks are coalesced into the single larger block.
  22275. **
  22276. ** 3. New memory is allocated from the first available free block.
  22277. **
  22278. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  22279. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  22280. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  22281. **
  22282. ** Let n be the size of the largest allocation divided by the minimum
  22283. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  22284. ** be the maximum amount of memory ever outstanding at one time. Let
  22285. ** N be the total amount of memory available for allocation. Robson
  22286. ** proved that this memory allocator will never breakdown due to
  22287. ** fragmentation as long as the following constraint holds:
  22288. **
  22289. ** N >= M*(1 + log2(n)/2) - n + 1
  22290. **
  22291. ** The sqlite3_status() logic tracks the maximum values of n and M so
  22292. ** that an application can, at any time, verify this constraint.
  22293. */
  22294. /* #include "sqliteInt.h" */
  22295. /*
  22296. ** This version of the memory allocator is used only when
  22297. ** SQLITE_ENABLE_MEMSYS5 is defined.
  22298. */
  22299. #ifdef SQLITE_ENABLE_MEMSYS5
  22300. /*
  22301. ** A minimum allocation is an instance of the following structure.
  22302. ** Larger allocations are an array of these structures where the
  22303. ** size of the array is a power of 2.
  22304. **
  22305. ** The size of this object must be a power of two. That fact is
  22306. ** verified in memsys5Init().
  22307. */
  22308. typedef struct Mem5Link Mem5Link;
  22309. struct Mem5Link {
  22310. int next; /* Index of next free chunk */
  22311. int prev; /* Index of previous free chunk */
  22312. };
  22313. /*
  22314. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  22315. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  22316. ** it is not actually possible to reach this limit.
  22317. */
  22318. #define LOGMAX 30
  22319. /*
  22320. ** Masks used for mem5.aCtrl[] elements.
  22321. */
  22322. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  22323. #define CTRL_FREE 0x20 /* True if not checked out */
  22324. /*
  22325. ** All of the static variables used by this module are collected
  22326. ** into a single structure named "mem5". This is to keep the
  22327. ** static variables organized and to reduce namespace pollution
  22328. ** when this module is combined with other in the amalgamation.
  22329. */
  22330. static SQLITE_WSD struct Mem5Global {
  22331. /*
  22332. ** Memory available for allocation
  22333. */
  22334. int szAtom; /* Smallest possible allocation in bytes */
  22335. int nBlock; /* Number of szAtom sized blocks in zPool */
  22336. u8 *zPool; /* Memory available to be allocated */
  22337. /*
  22338. ** Mutex to control access to the memory allocation subsystem.
  22339. */
  22340. sqlite3_mutex *mutex;
  22341. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22342. /*
  22343. ** Performance statistics
  22344. */
  22345. u64 nAlloc; /* Total number of calls to malloc */
  22346. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  22347. u64 totalExcess; /* Total internal fragmentation */
  22348. u32 currentOut; /* Current checkout, including internal fragmentation */
  22349. u32 currentCount; /* Current number of distinct checkouts */
  22350. u32 maxOut; /* Maximum instantaneous currentOut */
  22351. u32 maxCount; /* Maximum instantaneous currentCount */
  22352. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  22353. #endif
  22354. /*
  22355. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  22356. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  22357. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  22358. */
  22359. int aiFreelist[LOGMAX+1];
  22360. /*
  22361. ** Space for tracking which blocks are checked out and the size
  22362. ** of each block. One byte per block.
  22363. */
  22364. u8 *aCtrl;
  22365. } mem5;
  22366. /*
  22367. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  22368. */
  22369. #define mem5 GLOBAL(struct Mem5Global, mem5)
  22370. /*
  22371. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  22372. ** structures, return a pointer to the idx-th such link.
  22373. */
  22374. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  22375. /*
  22376. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  22377. ** on. It should be found on mem5.aiFreelist[iLogsize].
  22378. */
  22379. static void memsys5Unlink(int i, int iLogsize){
  22380. int next, prev;
  22381. assert( i>=0 && i<mem5.nBlock );
  22382. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  22383. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  22384. next = MEM5LINK(i)->next;
  22385. prev = MEM5LINK(i)->prev;
  22386. if( prev<0 ){
  22387. mem5.aiFreelist[iLogsize] = next;
  22388. }else{
  22389. MEM5LINK(prev)->next = next;
  22390. }
  22391. if( next>=0 ){
  22392. MEM5LINK(next)->prev = prev;
  22393. }
  22394. }
  22395. /*
  22396. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  22397. ** free list.
  22398. */
  22399. static void memsys5Link(int i, int iLogsize){
  22400. int x;
  22401. assert( sqlite3_mutex_held(mem5.mutex) );
  22402. assert( i>=0 && i<mem5.nBlock );
  22403. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  22404. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  22405. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  22406. MEM5LINK(i)->prev = -1;
  22407. if( x>=0 ){
  22408. assert( x<mem5.nBlock );
  22409. MEM5LINK(x)->prev = i;
  22410. }
  22411. mem5.aiFreelist[iLogsize] = i;
  22412. }
  22413. /*
  22414. ** Obtain or release the mutex needed to access global data structures.
  22415. */
  22416. static void memsys5Enter(void){
  22417. sqlite3_mutex_enter(mem5.mutex);
  22418. }
  22419. static void memsys5Leave(void){
  22420. sqlite3_mutex_leave(mem5.mutex);
  22421. }
  22422. /*
  22423. ** Return the size of an outstanding allocation, in bytes.
  22424. ** This only works for chunks that are currently checked out.
  22425. */
  22426. static int memsys5Size(void *p){
  22427. int iSize, i;
  22428. assert( p!=0 );
  22429. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  22430. assert( i>=0 && i<mem5.nBlock );
  22431. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  22432. return iSize;
  22433. }
  22434. /*
  22435. ** Return a block of memory of at least nBytes in size.
  22436. ** Return NULL if unable. Return NULL if nBytes==0.
  22437. **
  22438. ** The caller guarantees that nByte is positive.
  22439. **
  22440. ** The caller has obtained a mutex prior to invoking this
  22441. ** routine so there is never any chance that two or more
  22442. ** threads can be in this routine at the same time.
  22443. */
  22444. static void *memsys5MallocUnsafe(int nByte){
  22445. int i; /* Index of a mem5.aPool[] slot */
  22446. int iBin; /* Index into mem5.aiFreelist[] */
  22447. int iFullSz; /* Size of allocation rounded up to power of 2 */
  22448. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  22449. /* nByte must be a positive */
  22450. assert( nByte>0 );
  22451. /* No more than 1GiB per allocation */
  22452. if( nByte > 0x40000000 ) return 0;
  22453. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22454. /* Keep track of the maximum allocation request. Even unfulfilled
  22455. ** requests are counted */
  22456. if( (u32)nByte>mem5.maxRequest ){
  22457. mem5.maxRequest = nByte;
  22458. }
  22459. #endif
  22460. /* Round nByte up to the next valid power of two */
  22461. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  22462. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  22463. ** block. If not, then split a block of the next larger power of
  22464. ** two in order to create a new free block of size iLogsize.
  22465. */
  22466. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  22467. if( iBin>LOGMAX ){
  22468. testcase( sqlite3GlobalConfig.xLog!=0 );
  22469. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  22470. return 0;
  22471. }
  22472. i = mem5.aiFreelist[iBin];
  22473. memsys5Unlink(i, iBin);
  22474. while( iBin>iLogsize ){
  22475. int newSize;
  22476. iBin--;
  22477. newSize = 1 << iBin;
  22478. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  22479. memsys5Link(i+newSize, iBin);
  22480. }
  22481. mem5.aCtrl[i] = iLogsize;
  22482. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22483. /* Update allocator performance statistics. */
  22484. mem5.nAlloc++;
  22485. mem5.totalAlloc += iFullSz;
  22486. mem5.totalExcess += iFullSz - nByte;
  22487. mem5.currentCount++;
  22488. mem5.currentOut += iFullSz;
  22489. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  22490. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  22491. #endif
  22492. #ifdef SQLITE_DEBUG
  22493. /* Make sure the allocated memory does not assume that it is set to zero
  22494. ** or retains a value from a previous allocation */
  22495. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  22496. #endif
  22497. /* Return a pointer to the allocated memory. */
  22498. return (void*)&mem5.zPool[i*mem5.szAtom];
  22499. }
  22500. /*
  22501. ** Free an outstanding memory allocation.
  22502. */
  22503. static void memsys5FreeUnsafe(void *pOld){
  22504. u32 size, iLogsize;
  22505. int iBlock;
  22506. /* Set iBlock to the index of the block pointed to by pOld in
  22507. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  22508. */
  22509. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  22510. /* Check that the pointer pOld points to a valid, non-free block. */
  22511. assert( iBlock>=0 && iBlock<mem5.nBlock );
  22512. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  22513. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  22514. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  22515. size = 1<<iLogsize;
  22516. assert( iBlock+size-1<(u32)mem5.nBlock );
  22517. mem5.aCtrl[iBlock] |= CTRL_FREE;
  22518. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  22519. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  22520. assert( mem5.currentCount>0 );
  22521. assert( mem5.currentOut>=(size*mem5.szAtom) );
  22522. mem5.currentCount--;
  22523. mem5.currentOut -= size*mem5.szAtom;
  22524. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  22525. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  22526. #endif
  22527. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  22528. while( ALWAYS(iLogsize<LOGMAX) ){
  22529. int iBuddy;
  22530. if( (iBlock>>iLogsize) & 1 ){
  22531. iBuddy = iBlock - size;
  22532. assert( iBuddy>=0 );
  22533. }else{
  22534. iBuddy = iBlock + size;
  22535. if( iBuddy>=mem5.nBlock ) break;
  22536. }
  22537. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  22538. memsys5Unlink(iBuddy, iLogsize);
  22539. iLogsize++;
  22540. if( iBuddy<iBlock ){
  22541. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  22542. mem5.aCtrl[iBlock] = 0;
  22543. iBlock = iBuddy;
  22544. }else{
  22545. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  22546. mem5.aCtrl[iBuddy] = 0;
  22547. }
  22548. size *= 2;
  22549. }
  22550. #ifdef SQLITE_DEBUG
  22551. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  22552. ** not used after being freed */
  22553. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  22554. #endif
  22555. memsys5Link(iBlock, iLogsize);
  22556. }
  22557. /*
  22558. ** Allocate nBytes of memory.
  22559. */
  22560. static void *memsys5Malloc(int nBytes){
  22561. sqlite3_int64 *p = 0;
  22562. if( nBytes>0 ){
  22563. memsys5Enter();
  22564. p = memsys5MallocUnsafe(nBytes);
  22565. memsys5Leave();
  22566. }
  22567. return (void*)p;
  22568. }
  22569. /*
  22570. ** Free memory.
  22571. **
  22572. ** The outer layer memory allocator prevents this routine from
  22573. ** being called with pPrior==0.
  22574. */
  22575. static void memsys5Free(void *pPrior){
  22576. assert( pPrior!=0 );
  22577. memsys5Enter();
  22578. memsys5FreeUnsafe(pPrior);
  22579. memsys5Leave();
  22580. }
  22581. /*
  22582. ** Change the size of an existing memory allocation.
  22583. **
  22584. ** The outer layer memory allocator prevents this routine from
  22585. ** being called with pPrior==0.
  22586. **
  22587. ** nBytes is always a value obtained from a prior call to
  22588. ** memsys5Round(). Hence nBytes is always a non-negative power
  22589. ** of two. If nBytes==0 that means that an oversize allocation
  22590. ** (an allocation larger than 0x40000000) was requested and this
  22591. ** routine should return 0 without freeing pPrior.
  22592. */
  22593. static void *memsys5Realloc(void *pPrior, int nBytes){
  22594. int nOld;
  22595. void *p;
  22596. assert( pPrior!=0 );
  22597. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  22598. assert( nBytes>=0 );
  22599. if( nBytes==0 ){
  22600. return 0;
  22601. }
  22602. nOld = memsys5Size(pPrior);
  22603. if( nBytes<=nOld ){
  22604. return pPrior;
  22605. }
  22606. p = memsys5Malloc(nBytes);
  22607. if( p ){
  22608. memcpy(p, pPrior, nOld);
  22609. memsys5Free(pPrior);
  22610. }
  22611. return p;
  22612. }
  22613. /*
  22614. ** Round up a request size to the next valid allocation size. If
  22615. ** the allocation is too large to be handled by this allocation system,
  22616. ** return 0.
  22617. **
  22618. ** All allocations must be a power of two and must be expressed by a
  22619. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  22620. ** or 1073741824 bytes.
  22621. */
  22622. static int memsys5Roundup(int n){
  22623. int iFullSz;
  22624. if( n > 0x40000000 ) return 0;
  22625. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  22626. return iFullSz;
  22627. }
  22628. /*
  22629. ** Return the ceiling of the logarithm base 2 of iValue.
  22630. **
  22631. ** Examples: memsys5Log(1) -> 0
  22632. ** memsys5Log(2) -> 1
  22633. ** memsys5Log(4) -> 2
  22634. ** memsys5Log(5) -> 3
  22635. ** memsys5Log(8) -> 3
  22636. ** memsys5Log(9) -> 4
  22637. */
  22638. static int memsys5Log(int iValue){
  22639. int iLog;
  22640. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  22641. return iLog;
  22642. }
  22643. /*
  22644. ** Initialize the memory allocator.
  22645. **
  22646. ** This routine is not threadsafe. The caller must be holding a mutex
  22647. ** to prevent multiple threads from entering at the same time.
  22648. */
  22649. static int memsys5Init(void *NotUsed){
  22650. int ii; /* Loop counter */
  22651. int nByte; /* Number of bytes of memory available to this allocator */
  22652. u8 *zByte; /* Memory usable by this allocator */
  22653. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  22654. int iOffset; /* An offset into mem5.aCtrl[] */
  22655. UNUSED_PARAMETER(NotUsed);
  22656. /* For the purposes of this routine, disable the mutex */
  22657. mem5.mutex = 0;
  22658. /* The size of a Mem5Link object must be a power of two. Verify that
  22659. ** this is case.
  22660. */
  22661. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  22662. nByte = sqlite3GlobalConfig.nHeap;
  22663. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  22664. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  22665. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  22666. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  22667. mem5.szAtom = (1<<nMinLog);
  22668. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  22669. mem5.szAtom = mem5.szAtom << 1;
  22670. }
  22671. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  22672. mem5.zPool = zByte;
  22673. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  22674. for(ii=0; ii<=LOGMAX; ii++){
  22675. mem5.aiFreelist[ii] = -1;
  22676. }
  22677. iOffset = 0;
  22678. for(ii=LOGMAX; ii>=0; ii--){
  22679. int nAlloc = (1<<ii);
  22680. if( (iOffset+nAlloc)<=mem5.nBlock ){
  22681. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  22682. memsys5Link(iOffset, ii);
  22683. iOffset += nAlloc;
  22684. }
  22685. assert((iOffset+nAlloc)>mem5.nBlock);
  22686. }
  22687. /* If a mutex is required for normal operation, allocate one */
  22688. if( sqlite3GlobalConfig.bMemstat==0 ){
  22689. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  22690. }
  22691. return SQLITE_OK;
  22692. }
  22693. /*
  22694. ** Deinitialize this module.
  22695. */
  22696. static void memsys5Shutdown(void *NotUsed){
  22697. UNUSED_PARAMETER(NotUsed);
  22698. mem5.mutex = 0;
  22699. return;
  22700. }
  22701. #ifdef SQLITE_TEST
  22702. /*
  22703. ** Open the file indicated and write a log of all unfreed memory
  22704. ** allocations into that log.
  22705. */
  22706. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  22707. FILE *out;
  22708. int i, j, n;
  22709. int nMinLog;
  22710. if( zFilename==0 || zFilename[0]==0 ){
  22711. out = stdout;
  22712. }else{
  22713. out = fopen(zFilename, "w");
  22714. if( out==0 ){
  22715. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  22716. zFilename);
  22717. return;
  22718. }
  22719. }
  22720. memsys5Enter();
  22721. nMinLog = memsys5Log(mem5.szAtom);
  22722. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  22723. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  22724. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  22725. }
  22726. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  22727. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  22728. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  22729. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  22730. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  22731. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  22732. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  22733. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  22734. memsys5Leave();
  22735. if( out==stdout ){
  22736. fflush(stdout);
  22737. }else{
  22738. fclose(out);
  22739. }
  22740. }
  22741. #endif
  22742. /*
  22743. ** This routine is the only routine in this file with external
  22744. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  22745. ** struct populated with the memsys5 methods.
  22746. */
  22747. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  22748. static const sqlite3_mem_methods memsys5Methods = {
  22749. memsys5Malloc,
  22750. memsys5Free,
  22751. memsys5Realloc,
  22752. memsys5Size,
  22753. memsys5Roundup,
  22754. memsys5Init,
  22755. memsys5Shutdown,
  22756. 0
  22757. };
  22758. return &memsys5Methods;
  22759. }
  22760. #endif /* SQLITE_ENABLE_MEMSYS5 */
  22761. /************** End of mem5.c ************************************************/
  22762. /************** Begin file mutex.c *******************************************/
  22763. /*
  22764. ** 2007 August 14
  22765. **
  22766. ** The author disclaims copyright to this source code. In place of
  22767. ** a legal notice, here is a blessing:
  22768. **
  22769. ** May you do good and not evil.
  22770. ** May you find forgiveness for yourself and forgive others.
  22771. ** May you share freely, never taking more than you give.
  22772. **
  22773. *************************************************************************
  22774. ** This file contains the C functions that implement mutexes.
  22775. **
  22776. ** This file contains code that is common across all mutex implementations.
  22777. */
  22778. /* #include "sqliteInt.h" */
  22779. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  22780. /*
  22781. ** For debugging purposes, record when the mutex subsystem is initialized
  22782. ** and uninitialized so that we can assert() if there is an attempt to
  22783. ** allocate a mutex while the system is uninitialized.
  22784. */
  22785. static SQLITE_WSD int mutexIsInit = 0;
  22786. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  22787. #ifndef SQLITE_MUTEX_OMIT
  22788. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  22789. /*
  22790. ** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
  22791. ** the implementation of a wrapper around the system default mutex
  22792. ** implementation (sqlite3DefaultMutex()).
  22793. **
  22794. ** Most calls are passed directly through to the underlying default
  22795. ** mutex implementation. Except, if a mutex is configured by calling
  22796. ** sqlite3MutexWarnOnContention() on it, then if contention is ever
  22797. ** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
  22798. **
  22799. ** This type of mutex is used as the database handle mutex when testing
  22800. ** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
  22801. */
  22802. /*
  22803. ** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
  22804. ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
  22805. ** allocated by the system mutex implementation. Variable iType is usually set
  22806. ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
  22807. ** or one of the static mutex identifiers. Or, if this is a recursive mutex
  22808. ** that has been configured using sqlite3MutexWarnOnContention(), it is
  22809. ** set to SQLITE_MUTEX_WARNONCONTENTION.
  22810. */
  22811. typedef struct CheckMutex CheckMutex;
  22812. struct CheckMutex {
  22813. int iType;
  22814. sqlite3_mutex *mutex;
  22815. };
  22816. #define SQLITE_MUTEX_WARNONCONTENTION (-1)
  22817. /*
  22818. ** Pointer to real mutex methods object used by the CheckMutex
  22819. ** implementation. Set by checkMutexInit().
  22820. */
  22821. static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
  22822. #ifdef SQLITE_DEBUG
  22823. static int checkMutexHeld(sqlite3_mutex *p){
  22824. return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
  22825. }
  22826. static int checkMutexNotheld(sqlite3_mutex *p){
  22827. return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
  22828. }
  22829. #endif
  22830. /*
  22831. ** Initialize and deinitialize the mutex subsystem.
  22832. */
  22833. static int checkMutexInit(void){
  22834. pGlobalMutexMethods = sqlite3DefaultMutex();
  22835. return SQLITE_OK;
  22836. }
  22837. static int checkMutexEnd(void){
  22838. pGlobalMutexMethods = 0;
  22839. return SQLITE_OK;
  22840. }
  22841. /*
  22842. ** Allocate a mutex.
  22843. */
  22844. static sqlite3_mutex *checkMutexAlloc(int iType){
  22845. static CheckMutex staticMutexes[] = {
  22846. {2, 0}, {3, 0}, {4, 0}, {5, 0},
  22847. {6, 0}, {7, 0}, {8, 0}, {9, 0},
  22848. {10, 0}, {11, 0}, {12, 0}, {13, 0}
  22849. };
  22850. CheckMutex *p = 0;
  22851. assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
  22852. if( iType<2 ){
  22853. p = sqlite3MallocZero(sizeof(CheckMutex));
  22854. if( p==0 ) return 0;
  22855. p->iType = iType;
  22856. }else{
  22857. #ifdef SQLITE_ENABLE_API_ARMOR
  22858. if( iType-2>=ArraySize(staticMutexes) ){
  22859. (void)SQLITE_MISUSE_BKPT;
  22860. return 0;
  22861. }
  22862. #endif
  22863. p = &staticMutexes[iType-2];
  22864. }
  22865. if( p->mutex==0 ){
  22866. p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
  22867. if( p->mutex==0 ){
  22868. if( iType<2 ){
  22869. sqlite3_free(p);
  22870. }
  22871. p = 0;
  22872. }
  22873. }
  22874. return (sqlite3_mutex*)p;
  22875. }
  22876. /*
  22877. ** Free a mutex.
  22878. */
  22879. static void checkMutexFree(sqlite3_mutex *p){
  22880. assert( SQLITE_MUTEX_RECURSIVE<2 );
  22881. assert( SQLITE_MUTEX_FAST<2 );
  22882. assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
  22883. #if SQLITE_ENABLE_API_ARMOR
  22884. if( ((CheckMutex*)p)->iType<2 )
  22885. #endif
  22886. {
  22887. CheckMutex *pCheck = (CheckMutex*)p;
  22888. pGlobalMutexMethods->xMutexFree(pCheck->mutex);
  22889. sqlite3_free(pCheck);
  22890. }
  22891. #ifdef SQLITE_ENABLE_API_ARMOR
  22892. else{
  22893. (void)SQLITE_MISUSE_BKPT;
  22894. }
  22895. #endif
  22896. }
  22897. /*
  22898. ** Enter the mutex.
  22899. */
  22900. static void checkMutexEnter(sqlite3_mutex *p){
  22901. CheckMutex *pCheck = (CheckMutex*)p;
  22902. if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
  22903. if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
  22904. return;
  22905. }
  22906. sqlite3_log(SQLITE_MISUSE,
  22907. "illegal multi-threaded access to database connection"
  22908. );
  22909. }
  22910. pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
  22911. }
  22912. /*
  22913. ** Enter the mutex (do not block).
  22914. */
  22915. static int checkMutexTry(sqlite3_mutex *p){
  22916. CheckMutex *pCheck = (CheckMutex*)p;
  22917. return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
  22918. }
  22919. /*
  22920. ** Leave the mutex.
  22921. */
  22922. static void checkMutexLeave(sqlite3_mutex *p){
  22923. CheckMutex *pCheck = (CheckMutex*)p;
  22924. pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
  22925. }
  22926. sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
  22927. static const sqlite3_mutex_methods sMutex = {
  22928. checkMutexInit,
  22929. checkMutexEnd,
  22930. checkMutexAlloc,
  22931. checkMutexFree,
  22932. checkMutexEnter,
  22933. checkMutexTry,
  22934. checkMutexLeave,
  22935. #ifdef SQLITE_DEBUG
  22936. checkMutexHeld,
  22937. checkMutexNotheld
  22938. #else
  22939. 0,
  22940. 0
  22941. #endif
  22942. };
  22943. return &sMutex;
  22944. }
  22945. /*
  22946. ** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
  22947. ** one on which there should be no contention.
  22948. */
  22949. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
  22950. if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
  22951. CheckMutex *pCheck = (CheckMutex*)p;
  22952. assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
  22953. pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
  22954. }
  22955. }
  22956. #endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
  22957. /*
  22958. ** Initialize the mutex system.
  22959. */
  22960. SQLITE_PRIVATE int sqlite3MutexInit(void){
  22961. int rc = SQLITE_OK;
  22962. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  22963. /* If the xMutexAlloc method has not been set, then the user did not
  22964. ** install a mutex implementation via sqlite3_config() prior to
  22965. ** sqlite3_initialize() being called. This block copies pointers to
  22966. ** the default implementation into the sqlite3GlobalConfig structure.
  22967. */
  22968. sqlite3_mutex_methods const *pFrom;
  22969. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  22970. if( sqlite3GlobalConfig.bCoreMutex ){
  22971. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  22972. pFrom = multiThreadedCheckMutex();
  22973. #else
  22974. pFrom = sqlite3DefaultMutex();
  22975. #endif
  22976. }else{
  22977. pFrom = sqlite3NoopMutex();
  22978. }
  22979. pTo->xMutexInit = pFrom->xMutexInit;
  22980. pTo->xMutexEnd = pFrom->xMutexEnd;
  22981. pTo->xMutexFree = pFrom->xMutexFree;
  22982. pTo->xMutexEnter = pFrom->xMutexEnter;
  22983. pTo->xMutexTry = pFrom->xMutexTry;
  22984. pTo->xMutexLeave = pFrom->xMutexLeave;
  22985. pTo->xMutexHeld = pFrom->xMutexHeld;
  22986. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  22987. sqlite3MemoryBarrier();
  22988. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  22989. }
  22990. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  22991. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  22992. #ifdef SQLITE_DEBUG
  22993. GLOBAL(int, mutexIsInit) = 1;
  22994. #endif
  22995. return rc;
  22996. }
  22997. /*
  22998. ** Shutdown the mutex system. This call frees resources allocated by
  22999. ** sqlite3MutexInit().
  23000. */
  23001. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  23002. int rc = SQLITE_OK;
  23003. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  23004. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  23005. }
  23006. #ifdef SQLITE_DEBUG
  23007. GLOBAL(int, mutexIsInit) = 0;
  23008. #endif
  23009. return rc;
  23010. }
  23011. /*
  23012. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  23013. */
  23014. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  23015. #ifndef SQLITE_OMIT_AUTOINIT
  23016. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  23017. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  23018. #endif
  23019. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  23020. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  23021. }
  23022. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  23023. if( !sqlite3GlobalConfig.bCoreMutex ){
  23024. return 0;
  23025. }
  23026. assert( GLOBAL(int, mutexIsInit) );
  23027. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  23028. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  23029. }
  23030. /*
  23031. ** Free a dynamic mutex.
  23032. */
  23033. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  23034. if( p ){
  23035. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  23036. sqlite3GlobalConfig.mutex.xMutexFree(p);
  23037. }
  23038. }
  23039. /*
  23040. ** Obtain the mutex p. If some other thread already has the mutex, block
  23041. ** until it can be obtained.
  23042. */
  23043. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  23044. if( p ){
  23045. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  23046. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  23047. }
  23048. }
  23049. /*
  23050. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  23051. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  23052. */
  23053. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  23054. int rc = SQLITE_OK;
  23055. if( p ){
  23056. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  23057. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  23058. }
  23059. return rc;
  23060. }
  23061. /*
  23062. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  23063. ** entered by the same thread. The behavior is undefined if the mutex
  23064. ** is not currently entered. If a NULL pointer is passed as an argument
  23065. ** this function is a no-op.
  23066. */
  23067. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  23068. if( p ){
  23069. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  23070. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  23071. }
  23072. }
  23073. #ifndef NDEBUG
  23074. /*
  23075. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  23076. ** intended for use inside assert() statements.
  23077. */
  23078. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  23079. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  23080. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  23081. }
  23082. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  23083. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  23084. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  23085. }
  23086. #endif
  23087. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  23088. /************** End of mutex.c ***********************************************/
  23089. /************** Begin file mutex_noop.c **************************************/
  23090. /*
  23091. ** 2008 October 07
  23092. **
  23093. ** The author disclaims copyright to this source code. In place of
  23094. ** a legal notice, here is a blessing:
  23095. **
  23096. ** May you do good and not evil.
  23097. ** May you find forgiveness for yourself and forgive others.
  23098. ** May you share freely, never taking more than you give.
  23099. **
  23100. *************************************************************************
  23101. ** This file contains the C functions that implement mutexes.
  23102. **
  23103. ** This implementation in this file does not provide any mutual
  23104. ** exclusion and is thus suitable for use only in applications
  23105. ** that use SQLite in a single thread. The routines defined
  23106. ** here are place-holders. Applications can substitute working
  23107. ** mutex routines at start-time using the
  23108. **
  23109. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  23110. **
  23111. ** interface.
  23112. **
  23113. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  23114. ** that does error checking on mutexes to make sure they are being
  23115. ** called correctly.
  23116. */
  23117. /* #include "sqliteInt.h" */
  23118. #ifndef SQLITE_MUTEX_OMIT
  23119. #ifndef SQLITE_DEBUG
  23120. /*
  23121. ** Stub routines for all mutex methods.
  23122. **
  23123. ** This routines provide no mutual exclusion or error checking.
  23124. */
  23125. static int noopMutexInit(void){ return SQLITE_OK; }
  23126. static int noopMutexEnd(void){ return SQLITE_OK; }
  23127. static sqlite3_mutex *noopMutexAlloc(int id){
  23128. UNUSED_PARAMETER(id);
  23129. return (sqlite3_mutex*)8;
  23130. }
  23131. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  23132. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  23133. static int noopMutexTry(sqlite3_mutex *p){
  23134. UNUSED_PARAMETER(p);
  23135. return SQLITE_OK;
  23136. }
  23137. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  23138. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  23139. static const sqlite3_mutex_methods sMutex = {
  23140. noopMutexInit,
  23141. noopMutexEnd,
  23142. noopMutexAlloc,
  23143. noopMutexFree,
  23144. noopMutexEnter,
  23145. noopMutexTry,
  23146. noopMutexLeave,
  23147. 0,
  23148. 0,
  23149. };
  23150. return &sMutex;
  23151. }
  23152. #endif /* !SQLITE_DEBUG */
  23153. #ifdef SQLITE_DEBUG
  23154. /*
  23155. ** In this implementation, error checking is provided for testing
  23156. ** and debugging purposes. The mutexes still do not provide any
  23157. ** mutual exclusion.
  23158. */
  23159. /*
  23160. ** The mutex object
  23161. */
  23162. typedef struct sqlite3_debug_mutex {
  23163. int id; /* The mutex type */
  23164. int cnt; /* Number of entries without a matching leave */
  23165. } sqlite3_debug_mutex;
  23166. /*
  23167. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  23168. ** intended for use inside assert() statements.
  23169. */
  23170. static int debugMutexHeld(sqlite3_mutex *pX){
  23171. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23172. return p==0 || p->cnt>0;
  23173. }
  23174. static int debugMutexNotheld(sqlite3_mutex *pX){
  23175. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23176. return p==0 || p->cnt==0;
  23177. }
  23178. /*
  23179. ** Initialize and deinitialize the mutex subsystem.
  23180. */
  23181. static int debugMutexInit(void){ return SQLITE_OK; }
  23182. static int debugMutexEnd(void){ return SQLITE_OK; }
  23183. /*
  23184. ** The sqlite3_mutex_alloc() routine allocates a new
  23185. ** mutex and returns a pointer to it. If it returns NULL
  23186. ** that means that a mutex could not be allocated.
  23187. */
  23188. static sqlite3_mutex *debugMutexAlloc(int id){
  23189. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  23190. sqlite3_debug_mutex *pNew = 0;
  23191. switch( id ){
  23192. case SQLITE_MUTEX_FAST:
  23193. case SQLITE_MUTEX_RECURSIVE: {
  23194. pNew = sqlite3Malloc(sizeof(*pNew));
  23195. if( pNew ){
  23196. pNew->id = id;
  23197. pNew->cnt = 0;
  23198. }
  23199. break;
  23200. }
  23201. default: {
  23202. #ifdef SQLITE_ENABLE_API_ARMOR
  23203. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  23204. (void)SQLITE_MISUSE_BKPT;
  23205. return 0;
  23206. }
  23207. #endif
  23208. pNew = &aStatic[id-2];
  23209. pNew->id = id;
  23210. break;
  23211. }
  23212. }
  23213. return (sqlite3_mutex*)pNew;
  23214. }
  23215. /*
  23216. ** This routine deallocates a previously allocated mutex.
  23217. */
  23218. static void debugMutexFree(sqlite3_mutex *pX){
  23219. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23220. assert( p->cnt==0 );
  23221. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  23222. sqlite3_free(p);
  23223. }else{
  23224. #ifdef SQLITE_ENABLE_API_ARMOR
  23225. (void)SQLITE_MISUSE_BKPT;
  23226. #endif
  23227. }
  23228. }
  23229. /*
  23230. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  23231. ** to enter a mutex. If another thread is already within the mutex,
  23232. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  23233. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  23234. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  23235. ** be entered multiple times by the same thread. In such cases the,
  23236. ** mutex must be exited an equal number of times before another thread
  23237. ** can enter. If the same thread tries to enter any other kind of mutex
  23238. ** more than once, the behavior is undefined.
  23239. */
  23240. static void debugMutexEnter(sqlite3_mutex *pX){
  23241. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23242. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  23243. p->cnt++;
  23244. }
  23245. static int debugMutexTry(sqlite3_mutex *pX){
  23246. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23247. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  23248. p->cnt++;
  23249. return SQLITE_OK;
  23250. }
  23251. /*
  23252. ** The sqlite3_mutex_leave() routine exits a mutex that was
  23253. ** previously entered by the same thread. The behavior
  23254. ** is undefined if the mutex is not currently entered or
  23255. ** is not currently allocated. SQLite will never do either.
  23256. */
  23257. static void debugMutexLeave(sqlite3_mutex *pX){
  23258. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  23259. assert( debugMutexHeld(pX) );
  23260. p->cnt--;
  23261. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  23262. }
  23263. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  23264. static const sqlite3_mutex_methods sMutex = {
  23265. debugMutexInit,
  23266. debugMutexEnd,
  23267. debugMutexAlloc,
  23268. debugMutexFree,
  23269. debugMutexEnter,
  23270. debugMutexTry,
  23271. debugMutexLeave,
  23272. debugMutexHeld,
  23273. debugMutexNotheld
  23274. };
  23275. return &sMutex;
  23276. }
  23277. #endif /* SQLITE_DEBUG */
  23278. /*
  23279. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  23280. ** is used regardless of the run-time threadsafety setting.
  23281. */
  23282. #ifdef SQLITE_MUTEX_NOOP
  23283. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  23284. return sqlite3NoopMutex();
  23285. }
  23286. #endif /* defined(SQLITE_MUTEX_NOOP) */
  23287. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  23288. /************** End of mutex_noop.c ******************************************/
  23289. /************** Begin file mutex_unix.c **************************************/
  23290. /*
  23291. ** 2007 August 28
  23292. **
  23293. ** The author disclaims copyright to this source code. In place of
  23294. ** a legal notice, here is a blessing:
  23295. **
  23296. ** May you do good and not evil.
  23297. ** May you find forgiveness for yourself and forgive others.
  23298. ** May you share freely, never taking more than you give.
  23299. **
  23300. *************************************************************************
  23301. ** This file contains the C functions that implement mutexes for pthreads
  23302. */
  23303. /* #include "sqliteInt.h" */
  23304. /*
  23305. ** The code in this file is only used if we are compiling threadsafe
  23306. ** under unix with pthreads.
  23307. **
  23308. ** Note that this implementation requires a version of pthreads that
  23309. ** supports recursive mutexes.
  23310. */
  23311. #ifdef SQLITE_MUTEX_PTHREADS
  23312. #include <pthread.h>
  23313. /*
  23314. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  23315. ** are necessary under two condidtions: (1) Debug builds and (2) using
  23316. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  23317. */
  23318. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  23319. # define SQLITE_MUTEX_NREF 1
  23320. #else
  23321. # define SQLITE_MUTEX_NREF 0
  23322. #endif
  23323. /*
  23324. ** Each recursive mutex is an instance of the following structure.
  23325. */
  23326. struct sqlite3_mutex {
  23327. pthread_mutex_t mutex; /* Mutex controlling the lock */
  23328. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  23329. int id; /* Mutex type */
  23330. #endif
  23331. #if SQLITE_MUTEX_NREF
  23332. volatile int nRef; /* Number of entrances */
  23333. volatile pthread_t owner; /* Thread that is within this mutex */
  23334. int trace; /* True to trace changes */
  23335. #endif
  23336. };
  23337. #if SQLITE_MUTEX_NREF
  23338. # define SQLITE3_MUTEX_INITIALIZER(id) \
  23339. {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
  23340. #elif defined(SQLITE_ENABLE_API_ARMOR)
  23341. # define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
  23342. #else
  23343. #define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
  23344. #endif
  23345. /*
  23346. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  23347. ** intended for use only inside assert() statements. On some platforms,
  23348. ** there might be race conditions that can cause these routines to
  23349. ** deliver incorrect results. In particular, if pthread_equal() is
  23350. ** not an atomic operation, then these routines might delivery
  23351. ** incorrect results. On most platforms, pthread_equal() is a
  23352. ** comparison of two integers and is therefore atomic. But we are
  23353. ** told that HPUX is not such a platform. If so, then these routines
  23354. ** will not always work correctly on HPUX.
  23355. **
  23356. ** On those platforms where pthread_equal() is not atomic, SQLite
  23357. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  23358. ** make sure no assert() statements are evaluated and hence these
  23359. ** routines are never called.
  23360. */
  23361. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  23362. static int pthreadMutexHeld(sqlite3_mutex *p){
  23363. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  23364. }
  23365. static int pthreadMutexNotheld(sqlite3_mutex *p){
  23366. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  23367. }
  23368. #endif
  23369. /*
  23370. ** Try to provide a memory barrier operation, needed for initialization
  23371. ** and also for the implementation of xShmBarrier in the VFS in cases
  23372. ** where SQLite is compiled without mutexes.
  23373. */
  23374. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  23375. #if defined(SQLITE_MEMORY_BARRIER)
  23376. SQLITE_MEMORY_BARRIER;
  23377. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  23378. __sync_synchronize();
  23379. #endif
  23380. }
  23381. /*
  23382. ** Initialize and deinitialize the mutex subsystem.
  23383. */
  23384. static int pthreadMutexInit(void){ return SQLITE_OK; }
  23385. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  23386. /*
  23387. ** The sqlite3_mutex_alloc() routine allocates a new
  23388. ** mutex and returns a pointer to it. If it returns NULL
  23389. ** that means that a mutex could not be allocated. SQLite
  23390. ** will unwind its stack and return an error. The argument
  23391. ** to sqlite3_mutex_alloc() is one of these integer constants:
  23392. **
  23393. ** <ul>
  23394. ** <li> SQLITE_MUTEX_FAST
  23395. ** <li> SQLITE_MUTEX_RECURSIVE
  23396. ** <li> SQLITE_MUTEX_STATIC_MASTER
  23397. ** <li> SQLITE_MUTEX_STATIC_MEM
  23398. ** <li> SQLITE_MUTEX_STATIC_OPEN
  23399. ** <li> SQLITE_MUTEX_STATIC_PRNG
  23400. ** <li> SQLITE_MUTEX_STATIC_LRU
  23401. ** <li> SQLITE_MUTEX_STATIC_PMEM
  23402. ** <li> SQLITE_MUTEX_STATIC_APP1
  23403. ** <li> SQLITE_MUTEX_STATIC_APP2
  23404. ** <li> SQLITE_MUTEX_STATIC_APP3
  23405. ** <li> SQLITE_MUTEX_STATIC_VFS1
  23406. ** <li> SQLITE_MUTEX_STATIC_VFS2
  23407. ** <li> SQLITE_MUTEX_STATIC_VFS3
  23408. ** </ul>
  23409. **
  23410. ** The first two constants cause sqlite3_mutex_alloc() to create
  23411. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  23412. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  23413. ** The mutex implementation does not need to make a distinction
  23414. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  23415. ** not want to. But SQLite will only request a recursive mutex in
  23416. ** cases where it really needs one. If a faster non-recursive mutex
  23417. ** implementation is available on the host platform, the mutex subsystem
  23418. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  23419. **
  23420. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  23421. ** a pointer to a static preexisting mutex. Six static mutexes are
  23422. ** used by the current version of SQLite. Future versions of SQLite
  23423. ** may add additional static mutexes. Static mutexes are for internal
  23424. ** use by SQLite only. Applications that use SQLite mutexes should
  23425. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  23426. ** SQLITE_MUTEX_RECURSIVE.
  23427. **
  23428. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  23429. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  23430. ** returns a different mutex on every call. But for the static
  23431. ** mutex types, the same mutex is returned on every call that has
  23432. ** the same type number.
  23433. */
  23434. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  23435. static sqlite3_mutex staticMutexes[] = {
  23436. SQLITE3_MUTEX_INITIALIZER(2),
  23437. SQLITE3_MUTEX_INITIALIZER(3),
  23438. SQLITE3_MUTEX_INITIALIZER(4),
  23439. SQLITE3_MUTEX_INITIALIZER(5),
  23440. SQLITE3_MUTEX_INITIALIZER(6),
  23441. SQLITE3_MUTEX_INITIALIZER(7),
  23442. SQLITE3_MUTEX_INITIALIZER(8),
  23443. SQLITE3_MUTEX_INITIALIZER(9),
  23444. SQLITE3_MUTEX_INITIALIZER(10),
  23445. SQLITE3_MUTEX_INITIALIZER(11),
  23446. SQLITE3_MUTEX_INITIALIZER(12),
  23447. SQLITE3_MUTEX_INITIALIZER(13)
  23448. };
  23449. sqlite3_mutex *p;
  23450. switch( iType ){
  23451. case SQLITE_MUTEX_RECURSIVE: {
  23452. p = sqlite3MallocZero( sizeof(*p) );
  23453. if( p ){
  23454. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  23455. /* If recursive mutexes are not available, we will have to
  23456. ** build our own. See below. */
  23457. pthread_mutex_init(&p->mutex, 0);
  23458. #else
  23459. /* Use a recursive mutex if it is available */
  23460. pthread_mutexattr_t recursiveAttr;
  23461. pthread_mutexattr_init(&recursiveAttr);
  23462. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  23463. pthread_mutex_init(&p->mutex, &recursiveAttr);
  23464. pthread_mutexattr_destroy(&recursiveAttr);
  23465. #endif
  23466. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  23467. p->id = SQLITE_MUTEX_RECURSIVE;
  23468. #endif
  23469. }
  23470. break;
  23471. }
  23472. case SQLITE_MUTEX_FAST: {
  23473. p = sqlite3MallocZero( sizeof(*p) );
  23474. if( p ){
  23475. pthread_mutex_init(&p->mutex, 0);
  23476. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  23477. p->id = SQLITE_MUTEX_FAST;
  23478. #endif
  23479. }
  23480. break;
  23481. }
  23482. default: {
  23483. #ifdef SQLITE_ENABLE_API_ARMOR
  23484. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  23485. (void)SQLITE_MISUSE_BKPT;
  23486. return 0;
  23487. }
  23488. #endif
  23489. p = &staticMutexes[iType-2];
  23490. break;
  23491. }
  23492. }
  23493. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  23494. assert( p==0 || p->id==iType );
  23495. #endif
  23496. return p;
  23497. }
  23498. /*
  23499. ** This routine deallocates a previously
  23500. ** allocated mutex. SQLite is careful to deallocate every
  23501. ** mutex that it allocates.
  23502. */
  23503. static void pthreadMutexFree(sqlite3_mutex *p){
  23504. assert( p->nRef==0 );
  23505. #if SQLITE_ENABLE_API_ARMOR
  23506. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  23507. #endif
  23508. {
  23509. pthread_mutex_destroy(&p->mutex);
  23510. sqlite3_free(p);
  23511. }
  23512. #ifdef SQLITE_ENABLE_API_ARMOR
  23513. else{
  23514. (void)SQLITE_MISUSE_BKPT;
  23515. }
  23516. #endif
  23517. }
  23518. /*
  23519. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  23520. ** to enter a mutex. If another thread is already within the mutex,
  23521. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  23522. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  23523. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  23524. ** be entered multiple times by the same thread. In such cases the,
  23525. ** mutex must be exited an equal number of times before another thread
  23526. ** can enter. If the same thread tries to enter any other kind of mutex
  23527. ** more than once, the behavior is undefined.
  23528. */
  23529. static void pthreadMutexEnter(sqlite3_mutex *p){
  23530. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  23531. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  23532. /* If recursive mutexes are not available, then we have to grow
  23533. ** our own. This implementation assumes that pthread_equal()
  23534. ** is atomic - that it cannot be deceived into thinking self
  23535. ** and p->owner are equal if p->owner changes between two values
  23536. ** that are not equal to self while the comparison is taking place.
  23537. ** This implementation also assumes a coherent cache - that
  23538. ** separate processes cannot read different values from the same
  23539. ** address at the same time. If either of these two conditions
  23540. ** are not met, then the mutexes will fail and problems will result.
  23541. */
  23542. {
  23543. pthread_t self = pthread_self();
  23544. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  23545. p->nRef++;
  23546. }else{
  23547. pthread_mutex_lock(&p->mutex);
  23548. assert( p->nRef==0 );
  23549. p->owner = self;
  23550. p->nRef = 1;
  23551. }
  23552. }
  23553. #else
  23554. /* Use the built-in recursive mutexes if they are available.
  23555. */
  23556. pthread_mutex_lock(&p->mutex);
  23557. #if SQLITE_MUTEX_NREF
  23558. assert( p->nRef>0 || p->owner==0 );
  23559. p->owner = pthread_self();
  23560. p->nRef++;
  23561. #endif
  23562. #endif
  23563. #ifdef SQLITE_DEBUG
  23564. if( p->trace ){
  23565. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  23566. }
  23567. #endif
  23568. }
  23569. static int pthreadMutexTry(sqlite3_mutex *p){
  23570. int rc;
  23571. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  23572. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  23573. /* If recursive mutexes are not available, then we have to grow
  23574. ** our own. This implementation assumes that pthread_equal()
  23575. ** is atomic - that it cannot be deceived into thinking self
  23576. ** and p->owner are equal if p->owner changes between two values
  23577. ** that are not equal to self while the comparison is taking place.
  23578. ** This implementation also assumes a coherent cache - that
  23579. ** separate processes cannot read different values from the same
  23580. ** address at the same time. If either of these two conditions
  23581. ** are not met, then the mutexes will fail and problems will result.
  23582. */
  23583. {
  23584. pthread_t self = pthread_self();
  23585. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  23586. p->nRef++;
  23587. rc = SQLITE_OK;
  23588. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  23589. assert( p->nRef==0 );
  23590. p->owner = self;
  23591. p->nRef = 1;
  23592. rc = SQLITE_OK;
  23593. }else{
  23594. rc = SQLITE_BUSY;
  23595. }
  23596. }
  23597. #else
  23598. /* Use the built-in recursive mutexes if they are available.
  23599. */
  23600. if( pthread_mutex_trylock(&p->mutex)==0 ){
  23601. #if SQLITE_MUTEX_NREF
  23602. p->owner = pthread_self();
  23603. p->nRef++;
  23604. #endif
  23605. rc = SQLITE_OK;
  23606. }else{
  23607. rc = SQLITE_BUSY;
  23608. }
  23609. #endif
  23610. #ifdef SQLITE_DEBUG
  23611. if( rc==SQLITE_OK && p->trace ){
  23612. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  23613. }
  23614. #endif
  23615. return rc;
  23616. }
  23617. /*
  23618. ** The sqlite3_mutex_leave() routine exits a mutex that was
  23619. ** previously entered by the same thread. The behavior
  23620. ** is undefined if the mutex is not currently entered or
  23621. ** is not currently allocated. SQLite will never do either.
  23622. */
  23623. static void pthreadMutexLeave(sqlite3_mutex *p){
  23624. assert( pthreadMutexHeld(p) );
  23625. #if SQLITE_MUTEX_NREF
  23626. p->nRef--;
  23627. if( p->nRef==0 ) p->owner = 0;
  23628. #endif
  23629. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  23630. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  23631. if( p->nRef==0 ){
  23632. pthread_mutex_unlock(&p->mutex);
  23633. }
  23634. #else
  23635. pthread_mutex_unlock(&p->mutex);
  23636. #endif
  23637. #ifdef SQLITE_DEBUG
  23638. if( p->trace ){
  23639. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  23640. }
  23641. #endif
  23642. }
  23643. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  23644. static const sqlite3_mutex_methods sMutex = {
  23645. pthreadMutexInit,
  23646. pthreadMutexEnd,
  23647. pthreadMutexAlloc,
  23648. pthreadMutexFree,
  23649. pthreadMutexEnter,
  23650. pthreadMutexTry,
  23651. pthreadMutexLeave,
  23652. #ifdef SQLITE_DEBUG
  23653. pthreadMutexHeld,
  23654. pthreadMutexNotheld
  23655. #else
  23656. 0,
  23657. 0
  23658. #endif
  23659. };
  23660. return &sMutex;
  23661. }
  23662. #endif /* SQLITE_MUTEX_PTHREADS */
  23663. /************** End of mutex_unix.c ******************************************/
  23664. /************** Begin file mutex_w32.c ***************************************/
  23665. /*
  23666. ** 2007 August 14
  23667. **
  23668. ** The author disclaims copyright to this source code. In place of
  23669. ** a legal notice, here is a blessing:
  23670. **
  23671. ** May you do good and not evil.
  23672. ** May you find forgiveness for yourself and forgive others.
  23673. ** May you share freely, never taking more than you give.
  23674. **
  23675. *************************************************************************
  23676. ** This file contains the C functions that implement mutexes for Win32.
  23677. */
  23678. /* #include "sqliteInt.h" */
  23679. #if SQLITE_OS_WIN
  23680. /*
  23681. ** Include code that is common to all os_*.c files
  23682. */
  23683. /************** Include os_common.h in the middle of mutex_w32.c *************/
  23684. /************** Begin file os_common.h ***************************************/
  23685. /*
  23686. ** 2004 May 22
  23687. **
  23688. ** The author disclaims copyright to this source code. In place of
  23689. ** a legal notice, here is a blessing:
  23690. **
  23691. ** May you do good and not evil.
  23692. ** May you find forgiveness for yourself and forgive others.
  23693. ** May you share freely, never taking more than you give.
  23694. **
  23695. ******************************************************************************
  23696. **
  23697. ** This file contains macros and a little bit of code that is common to
  23698. ** all of the platform-specific files (os_*.c) and is #included into those
  23699. ** files.
  23700. **
  23701. ** This file should be #included by the os_*.c files only. It is not a
  23702. ** general purpose header file.
  23703. */
  23704. #ifndef _OS_COMMON_H_
  23705. #define _OS_COMMON_H_
  23706. /*
  23707. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  23708. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  23709. ** switch. The following code should catch this problem at compile-time.
  23710. */
  23711. #ifdef MEMORY_DEBUG
  23712. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  23713. #endif
  23714. /*
  23715. ** Macros for performance tracing. Normally turned off. Only works
  23716. ** on i486 hardware.
  23717. */
  23718. #ifdef SQLITE_PERFORMANCE_TRACE
  23719. /*
  23720. ** hwtime.h contains inline assembler code for implementing
  23721. ** high-performance timing routines.
  23722. */
  23723. /************** Include hwtime.h in the middle of os_common.h ****************/
  23724. /************** Begin file hwtime.h ******************************************/
  23725. /*
  23726. ** 2008 May 27
  23727. **
  23728. ** The author disclaims copyright to this source code. In place of
  23729. ** a legal notice, here is a blessing:
  23730. **
  23731. ** May you do good and not evil.
  23732. ** May you find forgiveness for yourself and forgive others.
  23733. ** May you share freely, never taking more than you give.
  23734. **
  23735. ******************************************************************************
  23736. **
  23737. ** This file contains inline asm code for retrieving "high-performance"
  23738. ** counters for x86 class CPUs.
  23739. */
  23740. #ifndef SQLITE_HWTIME_H
  23741. #define SQLITE_HWTIME_H
  23742. /*
  23743. ** The following routine only works on pentium-class (or newer) processors.
  23744. ** It uses the RDTSC opcode to read the cycle count value out of the
  23745. ** processor and returns that value. This can be used for high-res
  23746. ** profiling.
  23747. */
  23748. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  23749. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  23750. #if defined(__GNUC__)
  23751. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23752. unsigned int lo, hi;
  23753. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  23754. return (sqlite_uint64)hi << 32 | lo;
  23755. }
  23756. #elif defined(_MSC_VER)
  23757. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  23758. __asm {
  23759. rdtsc
  23760. ret ; return value at EDX:EAX
  23761. }
  23762. }
  23763. #endif
  23764. #elif (defined(__GNUC__) && defined(__x86_64__))
  23765. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23766. unsigned long val;
  23767. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  23768. return val;
  23769. }
  23770. #elif (defined(__GNUC__) && defined(__ppc__))
  23771. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23772. unsigned long long retval;
  23773. unsigned long junk;
  23774. __asm__ __volatile__ ("\n\
  23775. 1: mftbu %1\n\
  23776. mftb %L0\n\
  23777. mftbu %0\n\
  23778. cmpw %0,%1\n\
  23779. bne 1b"
  23780. : "=r" (retval), "=r" (junk));
  23781. return retval;
  23782. }
  23783. #else
  23784. #error Need implementation of sqlite3Hwtime() for your platform.
  23785. /*
  23786. ** To compile without implementing sqlite3Hwtime() for your platform,
  23787. ** you can remove the above #error and use the following
  23788. ** stub function. You will lose timing support for many
  23789. ** of the debugging and testing utilities, but it should at
  23790. ** least compile and run.
  23791. */
  23792. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  23793. #endif
  23794. #endif /* !defined(SQLITE_HWTIME_H) */
  23795. /************** End of hwtime.h **********************************************/
  23796. /************** Continuing where we left off in os_common.h ******************/
  23797. static sqlite_uint64 g_start;
  23798. static sqlite_uint64 g_elapsed;
  23799. #define TIMER_START g_start=sqlite3Hwtime()
  23800. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  23801. #define TIMER_ELAPSED g_elapsed
  23802. #else
  23803. #define TIMER_START
  23804. #define TIMER_END
  23805. #define TIMER_ELAPSED ((sqlite_uint64)0)
  23806. #endif
  23807. /*
  23808. ** If we compile with the SQLITE_TEST macro set, then the following block
  23809. ** of code will give us the ability to simulate a disk I/O error. This
  23810. ** is used for testing the I/O recovery logic.
  23811. */
  23812. #if defined(SQLITE_TEST)
  23813. SQLITE_API extern int sqlite3_io_error_hit;
  23814. SQLITE_API extern int sqlite3_io_error_hardhit;
  23815. SQLITE_API extern int sqlite3_io_error_pending;
  23816. SQLITE_API extern int sqlite3_io_error_persist;
  23817. SQLITE_API extern int sqlite3_io_error_benign;
  23818. SQLITE_API extern int sqlite3_diskfull_pending;
  23819. SQLITE_API extern int sqlite3_diskfull;
  23820. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  23821. #define SimulateIOError(CODE) \
  23822. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  23823. || sqlite3_io_error_pending-- == 1 ) \
  23824. { local_ioerr(); CODE; }
  23825. static void local_ioerr(){
  23826. IOTRACE(("IOERR\n"));
  23827. sqlite3_io_error_hit++;
  23828. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  23829. }
  23830. #define SimulateDiskfullError(CODE) \
  23831. if( sqlite3_diskfull_pending ){ \
  23832. if( sqlite3_diskfull_pending == 1 ){ \
  23833. local_ioerr(); \
  23834. sqlite3_diskfull = 1; \
  23835. sqlite3_io_error_hit = 1; \
  23836. CODE; \
  23837. }else{ \
  23838. sqlite3_diskfull_pending--; \
  23839. } \
  23840. }
  23841. #else
  23842. #define SimulateIOErrorBenign(X)
  23843. #define SimulateIOError(A)
  23844. #define SimulateDiskfullError(A)
  23845. #endif /* defined(SQLITE_TEST) */
  23846. /*
  23847. ** When testing, keep a count of the number of open files.
  23848. */
  23849. #if defined(SQLITE_TEST)
  23850. SQLITE_API extern int sqlite3_open_file_count;
  23851. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  23852. #else
  23853. #define OpenCounter(X)
  23854. #endif /* defined(SQLITE_TEST) */
  23855. #endif /* !defined(_OS_COMMON_H_) */
  23856. /************** End of os_common.h *******************************************/
  23857. /************** Continuing where we left off in mutex_w32.c ******************/
  23858. /*
  23859. ** Include the header file for the Windows VFS.
  23860. */
  23861. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  23862. /************** Begin file os_win.h ******************************************/
  23863. /*
  23864. ** 2013 November 25
  23865. **
  23866. ** The author disclaims copyright to this source code. In place of
  23867. ** a legal notice, here is a blessing:
  23868. **
  23869. ** May you do good and not evil.
  23870. ** May you find forgiveness for yourself and forgive others.
  23871. ** May you share freely, never taking more than you give.
  23872. **
  23873. ******************************************************************************
  23874. **
  23875. ** This file contains code that is specific to Windows.
  23876. */
  23877. #ifndef SQLITE_OS_WIN_H
  23878. #define SQLITE_OS_WIN_H
  23879. /*
  23880. ** Include the primary Windows SDK header file.
  23881. */
  23882. #include "windows.h"
  23883. #ifdef __CYGWIN__
  23884. # include <sys/cygwin.h>
  23885. # include <errno.h> /* amalgamator: dontcache */
  23886. #endif
  23887. /*
  23888. ** Determine if we are dealing with Windows NT.
  23889. **
  23890. ** We ought to be able to determine if we are compiling for Windows 9x or
  23891. ** Windows NT using the _WIN32_WINNT macro as follows:
  23892. **
  23893. ** #if defined(_WIN32_WINNT)
  23894. ** # define SQLITE_OS_WINNT 1
  23895. ** #else
  23896. ** # define SQLITE_OS_WINNT 0
  23897. ** #endif
  23898. **
  23899. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  23900. ** it ought to, so the above test does not work. We'll just assume that
  23901. ** everything is Windows NT unless the programmer explicitly says otherwise
  23902. ** by setting SQLITE_OS_WINNT to 0.
  23903. */
  23904. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  23905. # define SQLITE_OS_WINNT 1
  23906. #endif
  23907. /*
  23908. ** Determine if we are dealing with Windows CE - which has a much reduced
  23909. ** API.
  23910. */
  23911. #if defined(_WIN32_WCE)
  23912. # define SQLITE_OS_WINCE 1
  23913. #else
  23914. # define SQLITE_OS_WINCE 0
  23915. #endif
  23916. /*
  23917. ** Determine if we are dealing with WinRT, which provides only a subset of
  23918. ** the full Win32 API.
  23919. */
  23920. #if !defined(SQLITE_OS_WINRT)
  23921. # define SQLITE_OS_WINRT 0
  23922. #endif
  23923. /*
  23924. ** For WinCE, some API function parameters do not appear to be declared as
  23925. ** volatile.
  23926. */
  23927. #if SQLITE_OS_WINCE
  23928. # define SQLITE_WIN32_VOLATILE
  23929. #else
  23930. # define SQLITE_WIN32_VOLATILE volatile
  23931. #endif
  23932. /*
  23933. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  23934. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  23935. */
  23936. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  23937. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  23938. # define SQLITE_OS_WIN_THREADS 1
  23939. #else
  23940. # define SQLITE_OS_WIN_THREADS 0
  23941. #endif
  23942. #endif /* SQLITE_OS_WIN_H */
  23943. /************** End of os_win.h **********************************************/
  23944. /************** Continuing where we left off in mutex_w32.c ******************/
  23945. #endif
  23946. /*
  23947. ** The code in this file is only used if we are compiling multithreaded
  23948. ** on a Win32 system.
  23949. */
  23950. #ifdef SQLITE_MUTEX_W32
  23951. /*
  23952. ** Each recursive mutex is an instance of the following structure.
  23953. */
  23954. struct sqlite3_mutex {
  23955. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  23956. int id; /* Mutex type */
  23957. #ifdef SQLITE_DEBUG
  23958. volatile int nRef; /* Number of enterances */
  23959. volatile DWORD owner; /* Thread holding this mutex */
  23960. volatile LONG trace; /* True to trace changes */
  23961. #endif
  23962. };
  23963. /*
  23964. ** These are the initializer values used when declaring a "static" mutex
  23965. ** on Win32. It should be noted that all mutexes require initialization
  23966. ** on the Win32 platform.
  23967. */
  23968. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  23969. #ifdef SQLITE_DEBUG
  23970. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
  23971. 0L, (DWORD)0, 0 }
  23972. #else
  23973. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
  23974. #endif
  23975. #ifdef SQLITE_DEBUG
  23976. /*
  23977. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  23978. ** intended for use only inside assert() statements.
  23979. */
  23980. static int winMutexHeld(sqlite3_mutex *p){
  23981. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  23982. }
  23983. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  23984. return p->nRef==0 || p->owner!=tid;
  23985. }
  23986. static int winMutexNotheld(sqlite3_mutex *p){
  23987. DWORD tid = GetCurrentThreadId();
  23988. return winMutexNotheld2(p, tid);
  23989. }
  23990. #endif
  23991. /*
  23992. ** Try to provide a memory barrier operation, needed for initialization
  23993. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  23994. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  23995. */
  23996. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  23997. #if defined(SQLITE_MEMORY_BARRIER)
  23998. SQLITE_MEMORY_BARRIER;
  23999. #elif defined(__GNUC__)
  24000. __sync_synchronize();
  24001. #elif MSVC_VERSION>=1300
  24002. _ReadWriteBarrier();
  24003. #elif defined(MemoryBarrier)
  24004. MemoryBarrier();
  24005. #endif
  24006. }
  24007. /*
  24008. ** Initialize and deinitialize the mutex subsystem.
  24009. */
  24010. static sqlite3_mutex winMutex_staticMutexes[] = {
  24011. SQLITE3_MUTEX_INITIALIZER(2),
  24012. SQLITE3_MUTEX_INITIALIZER(3),
  24013. SQLITE3_MUTEX_INITIALIZER(4),
  24014. SQLITE3_MUTEX_INITIALIZER(5),
  24015. SQLITE3_MUTEX_INITIALIZER(6),
  24016. SQLITE3_MUTEX_INITIALIZER(7),
  24017. SQLITE3_MUTEX_INITIALIZER(8),
  24018. SQLITE3_MUTEX_INITIALIZER(9),
  24019. SQLITE3_MUTEX_INITIALIZER(10),
  24020. SQLITE3_MUTEX_INITIALIZER(11),
  24021. SQLITE3_MUTEX_INITIALIZER(12),
  24022. SQLITE3_MUTEX_INITIALIZER(13)
  24023. };
  24024. static int winMutex_isInit = 0;
  24025. static int winMutex_isNt = -1; /* <0 means "need to query" */
  24026. /* As the winMutexInit() and winMutexEnd() functions are called as part
  24027. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  24028. ** "interlocked" magic used here is probably not strictly necessary.
  24029. */
  24030. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  24031. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  24032. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  24033. static int winMutexInit(void){
  24034. /* The first to increment to 1 does actual initialization */
  24035. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  24036. int i;
  24037. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  24038. #if SQLITE_OS_WINRT
  24039. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  24040. #else
  24041. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  24042. #endif
  24043. }
  24044. winMutex_isInit = 1;
  24045. }else{
  24046. /* Another thread is (in the process of) initializing the static
  24047. ** mutexes */
  24048. while( !winMutex_isInit ){
  24049. sqlite3_win32_sleep(1);
  24050. }
  24051. }
  24052. return SQLITE_OK;
  24053. }
  24054. static int winMutexEnd(void){
  24055. /* The first to decrement to 0 does actual shutdown
  24056. ** (which should be the last to shutdown.) */
  24057. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  24058. if( winMutex_isInit==1 ){
  24059. int i;
  24060. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  24061. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  24062. }
  24063. winMutex_isInit = 0;
  24064. }
  24065. }
  24066. return SQLITE_OK;
  24067. }
  24068. /*
  24069. ** The sqlite3_mutex_alloc() routine allocates a new
  24070. ** mutex and returns a pointer to it. If it returns NULL
  24071. ** that means that a mutex could not be allocated. SQLite
  24072. ** will unwind its stack and return an error. The argument
  24073. ** to sqlite3_mutex_alloc() is one of these integer constants:
  24074. **
  24075. ** <ul>
  24076. ** <li> SQLITE_MUTEX_FAST
  24077. ** <li> SQLITE_MUTEX_RECURSIVE
  24078. ** <li> SQLITE_MUTEX_STATIC_MASTER
  24079. ** <li> SQLITE_MUTEX_STATIC_MEM
  24080. ** <li> SQLITE_MUTEX_STATIC_OPEN
  24081. ** <li> SQLITE_MUTEX_STATIC_PRNG
  24082. ** <li> SQLITE_MUTEX_STATIC_LRU
  24083. ** <li> SQLITE_MUTEX_STATIC_PMEM
  24084. ** <li> SQLITE_MUTEX_STATIC_APP1
  24085. ** <li> SQLITE_MUTEX_STATIC_APP2
  24086. ** <li> SQLITE_MUTEX_STATIC_APP3
  24087. ** <li> SQLITE_MUTEX_STATIC_VFS1
  24088. ** <li> SQLITE_MUTEX_STATIC_VFS2
  24089. ** <li> SQLITE_MUTEX_STATIC_VFS3
  24090. ** </ul>
  24091. **
  24092. ** The first two constants cause sqlite3_mutex_alloc() to create
  24093. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  24094. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  24095. ** The mutex implementation does not need to make a distinction
  24096. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  24097. ** not want to. But SQLite will only request a recursive mutex in
  24098. ** cases where it really needs one. If a faster non-recursive mutex
  24099. ** implementation is available on the host platform, the mutex subsystem
  24100. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  24101. **
  24102. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  24103. ** a pointer to a static preexisting mutex. Six static mutexes are
  24104. ** used by the current version of SQLite. Future versions of SQLite
  24105. ** may add additional static mutexes. Static mutexes are for internal
  24106. ** use by SQLite only. Applications that use SQLite mutexes should
  24107. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  24108. ** SQLITE_MUTEX_RECURSIVE.
  24109. **
  24110. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  24111. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  24112. ** returns a different mutex on every call. But for the static
  24113. ** mutex types, the same mutex is returned on every call that has
  24114. ** the same type number.
  24115. */
  24116. static sqlite3_mutex *winMutexAlloc(int iType){
  24117. sqlite3_mutex *p;
  24118. switch( iType ){
  24119. case SQLITE_MUTEX_FAST:
  24120. case SQLITE_MUTEX_RECURSIVE: {
  24121. p = sqlite3MallocZero( sizeof(*p) );
  24122. if( p ){
  24123. p->id = iType;
  24124. #ifdef SQLITE_DEBUG
  24125. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  24126. p->trace = 1;
  24127. #endif
  24128. #endif
  24129. #if SQLITE_OS_WINRT
  24130. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  24131. #else
  24132. InitializeCriticalSection(&p->mutex);
  24133. #endif
  24134. }
  24135. break;
  24136. }
  24137. default: {
  24138. #ifdef SQLITE_ENABLE_API_ARMOR
  24139. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  24140. (void)SQLITE_MISUSE_BKPT;
  24141. return 0;
  24142. }
  24143. #endif
  24144. p = &winMutex_staticMutexes[iType-2];
  24145. #ifdef SQLITE_DEBUG
  24146. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  24147. InterlockedCompareExchange(&p->trace, 1, 0);
  24148. #endif
  24149. #endif
  24150. break;
  24151. }
  24152. }
  24153. assert( p==0 || p->id==iType );
  24154. return p;
  24155. }
  24156. /*
  24157. ** This routine deallocates a previously
  24158. ** allocated mutex. SQLite is careful to deallocate every
  24159. ** mutex that it allocates.
  24160. */
  24161. static void winMutexFree(sqlite3_mutex *p){
  24162. assert( p );
  24163. assert( p->nRef==0 && p->owner==0 );
  24164. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  24165. DeleteCriticalSection(&p->mutex);
  24166. sqlite3_free(p);
  24167. }else{
  24168. #ifdef SQLITE_ENABLE_API_ARMOR
  24169. (void)SQLITE_MISUSE_BKPT;
  24170. #endif
  24171. }
  24172. }
  24173. /*
  24174. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  24175. ** to enter a mutex. If another thread is already within the mutex,
  24176. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  24177. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  24178. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  24179. ** be entered multiple times by the same thread. In such cases the,
  24180. ** mutex must be exited an equal number of times before another thread
  24181. ** can enter. If the same thread tries to enter any other kind of mutex
  24182. ** more than once, the behavior is undefined.
  24183. */
  24184. static void winMutexEnter(sqlite3_mutex *p){
  24185. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  24186. DWORD tid = GetCurrentThreadId();
  24187. #endif
  24188. #ifdef SQLITE_DEBUG
  24189. assert( p );
  24190. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  24191. #else
  24192. assert( p );
  24193. #endif
  24194. assert( winMutex_isInit==1 );
  24195. EnterCriticalSection(&p->mutex);
  24196. #ifdef SQLITE_DEBUG
  24197. assert( p->nRef>0 || p->owner==0 );
  24198. p->owner = tid;
  24199. p->nRef++;
  24200. if( p->trace ){
  24201. OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  24202. tid, p->id, p, p->trace, p->nRef));
  24203. }
  24204. #endif
  24205. }
  24206. static int winMutexTry(sqlite3_mutex *p){
  24207. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  24208. DWORD tid = GetCurrentThreadId();
  24209. #endif
  24210. int rc = SQLITE_BUSY;
  24211. assert( p );
  24212. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  24213. /*
  24214. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  24215. ** is used it is merely an optimization. So it is OK for it to always
  24216. ** fail.
  24217. **
  24218. ** The TryEnterCriticalSection() interface is only available on WinNT.
  24219. ** And some windows compilers complain if you try to use it without
  24220. ** first doing some #defines that prevent SQLite from building on Win98.
  24221. ** For that reason, we will omit this optimization for now. See
  24222. ** ticket #2685.
  24223. */
  24224. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  24225. assert( winMutex_isInit==1 );
  24226. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  24227. if( winMutex_isNt<0 ){
  24228. winMutex_isNt = sqlite3_win32_is_nt();
  24229. }
  24230. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  24231. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  24232. #ifdef SQLITE_DEBUG
  24233. p->owner = tid;
  24234. p->nRef++;
  24235. #endif
  24236. rc = SQLITE_OK;
  24237. }
  24238. #else
  24239. UNUSED_PARAMETER(p);
  24240. #endif
  24241. #ifdef SQLITE_DEBUG
  24242. if( p->trace ){
  24243. OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  24244. tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  24245. }
  24246. #endif
  24247. return rc;
  24248. }
  24249. /*
  24250. ** The sqlite3_mutex_leave() routine exits a mutex that was
  24251. ** previously entered by the same thread. The behavior
  24252. ** is undefined if the mutex is not currently entered or
  24253. ** is not currently allocated. SQLite will never do either.
  24254. */
  24255. static void winMutexLeave(sqlite3_mutex *p){
  24256. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  24257. DWORD tid = GetCurrentThreadId();
  24258. #endif
  24259. assert( p );
  24260. #ifdef SQLITE_DEBUG
  24261. assert( p->nRef>0 );
  24262. assert( p->owner==tid );
  24263. p->nRef--;
  24264. if( p->nRef==0 ) p->owner = 0;
  24265. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  24266. #endif
  24267. assert( winMutex_isInit==1 );
  24268. LeaveCriticalSection(&p->mutex);
  24269. #ifdef SQLITE_DEBUG
  24270. if( p->trace ){
  24271. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  24272. tid, p->id, p, p->trace, p->nRef));
  24273. }
  24274. #endif
  24275. }
  24276. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  24277. static const sqlite3_mutex_methods sMutex = {
  24278. winMutexInit,
  24279. winMutexEnd,
  24280. winMutexAlloc,
  24281. winMutexFree,
  24282. winMutexEnter,
  24283. winMutexTry,
  24284. winMutexLeave,
  24285. #ifdef SQLITE_DEBUG
  24286. winMutexHeld,
  24287. winMutexNotheld
  24288. #else
  24289. 0,
  24290. 0
  24291. #endif
  24292. };
  24293. return &sMutex;
  24294. }
  24295. #endif /* SQLITE_MUTEX_W32 */
  24296. /************** End of mutex_w32.c *******************************************/
  24297. /************** Begin file malloc.c ******************************************/
  24298. /*
  24299. ** 2001 September 15
  24300. **
  24301. ** The author disclaims copyright to this source code. In place of
  24302. ** a legal notice, here is a blessing:
  24303. **
  24304. ** May you do good and not evil.
  24305. ** May you find forgiveness for yourself and forgive others.
  24306. ** May you share freely, never taking more than you give.
  24307. **
  24308. *************************************************************************
  24309. **
  24310. ** Memory allocation functions used throughout sqlite.
  24311. */
  24312. /* #include "sqliteInt.h" */
  24313. /* #include <stdarg.h> */
  24314. /*
  24315. ** Attempt to release up to n bytes of non-essential memory currently
  24316. ** held by SQLite. An example of non-essential memory is memory used to
  24317. ** cache database pages that are not currently in use.
  24318. */
  24319. SQLITE_API int sqlite3_release_memory(int n){
  24320. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  24321. return sqlite3PcacheReleaseMemory(n);
  24322. #else
  24323. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  24324. ** is a no-op returning zero if SQLite is not compiled with
  24325. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  24326. UNUSED_PARAMETER(n);
  24327. return 0;
  24328. #endif
  24329. }
  24330. /*
  24331. ** State information local to the memory allocation subsystem.
  24332. */
  24333. static SQLITE_WSD struct Mem0Global {
  24334. sqlite3_mutex *mutex; /* Mutex to serialize access */
  24335. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  24336. /*
  24337. ** True if heap is nearly "full" where "full" is defined by the
  24338. ** sqlite3_soft_heap_limit() setting.
  24339. */
  24340. int nearlyFull;
  24341. } mem0 = { 0, 0, 0 };
  24342. #define mem0 GLOBAL(struct Mem0Global, mem0)
  24343. /*
  24344. ** Return the memory allocator mutex. sqlite3_status() needs it.
  24345. */
  24346. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  24347. return mem0.mutex;
  24348. }
  24349. #ifndef SQLITE_OMIT_DEPRECATED
  24350. /*
  24351. ** Deprecated external interface. It used to set an alarm callback
  24352. ** that was invoked when memory usage grew too large. Now it is a
  24353. ** no-op.
  24354. */
  24355. SQLITE_API int sqlite3_memory_alarm(
  24356. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  24357. void *pArg,
  24358. sqlite3_int64 iThreshold
  24359. ){
  24360. (void)xCallback;
  24361. (void)pArg;
  24362. (void)iThreshold;
  24363. return SQLITE_OK;
  24364. }
  24365. #endif
  24366. /*
  24367. ** Set the soft heap-size limit for the library. Passing a zero or
  24368. ** negative value indicates no limit.
  24369. */
  24370. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  24371. sqlite3_int64 priorLimit;
  24372. sqlite3_int64 excess;
  24373. sqlite3_int64 nUsed;
  24374. #ifndef SQLITE_OMIT_AUTOINIT
  24375. int rc = sqlite3_initialize();
  24376. if( rc ) return -1;
  24377. #endif
  24378. sqlite3_mutex_enter(mem0.mutex);
  24379. priorLimit = mem0.alarmThreshold;
  24380. if( n<0 ){
  24381. sqlite3_mutex_leave(mem0.mutex);
  24382. return priorLimit;
  24383. }
  24384. mem0.alarmThreshold = n;
  24385. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  24386. mem0.nearlyFull = (n>0 && n<=nUsed);
  24387. sqlite3_mutex_leave(mem0.mutex);
  24388. excess = sqlite3_memory_used() - n;
  24389. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  24390. return priorLimit;
  24391. }
  24392. SQLITE_API void sqlite3_soft_heap_limit(int n){
  24393. if( n<0 ) n = 0;
  24394. sqlite3_soft_heap_limit64(n);
  24395. }
  24396. /*
  24397. ** Initialize the memory allocation subsystem.
  24398. */
  24399. SQLITE_PRIVATE int sqlite3MallocInit(void){
  24400. int rc;
  24401. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  24402. sqlite3MemSetDefault();
  24403. }
  24404. memset(&mem0, 0, sizeof(mem0));
  24405. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  24406. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  24407. || sqlite3GlobalConfig.nPage<=0 ){
  24408. sqlite3GlobalConfig.pPage = 0;
  24409. sqlite3GlobalConfig.szPage = 0;
  24410. }
  24411. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  24412. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  24413. return rc;
  24414. }
  24415. /*
  24416. ** Return true if the heap is currently under memory pressure - in other
  24417. ** words if the amount of heap used is close to the limit set by
  24418. ** sqlite3_soft_heap_limit().
  24419. */
  24420. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  24421. return mem0.nearlyFull;
  24422. }
  24423. /*
  24424. ** Deinitialize the memory allocation subsystem.
  24425. */
  24426. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  24427. if( sqlite3GlobalConfig.m.xShutdown ){
  24428. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  24429. }
  24430. memset(&mem0, 0, sizeof(mem0));
  24431. }
  24432. /*
  24433. ** Return the amount of memory currently checked out.
  24434. */
  24435. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  24436. sqlite3_int64 res, mx;
  24437. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  24438. return res;
  24439. }
  24440. /*
  24441. ** Return the maximum amount of memory that has ever been
  24442. ** checked out since either the beginning of this process
  24443. ** or since the most recent reset.
  24444. */
  24445. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  24446. sqlite3_int64 res, mx;
  24447. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  24448. return mx;
  24449. }
  24450. /*
  24451. ** Trigger the alarm
  24452. */
  24453. static void sqlite3MallocAlarm(int nByte){
  24454. if( mem0.alarmThreshold<=0 ) return;
  24455. sqlite3_mutex_leave(mem0.mutex);
  24456. sqlite3_release_memory(nByte);
  24457. sqlite3_mutex_enter(mem0.mutex);
  24458. }
  24459. /*
  24460. ** Do a memory allocation with statistics and alarms. Assume the
  24461. ** lock is already held.
  24462. */
  24463. static void mallocWithAlarm(int n, void **pp){
  24464. void *p;
  24465. int nFull;
  24466. assert( sqlite3_mutex_held(mem0.mutex) );
  24467. assert( n>0 );
  24468. /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
  24469. ** implementation of malloc_good_size(), which must be called in debug
  24470. ** mode and specifically when the DMD "Dark Matter Detector" is enabled
  24471. ** or else a crash results. Hence, do not attempt to optimize out the
  24472. ** following xRoundup() call. */
  24473. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  24474. #ifdef SQLITE_MAX_MEMORY
  24475. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nFull>SQLITE_MAX_MEMORY ){
  24476. *pp = 0;
  24477. return;
  24478. }
  24479. #endif
  24480. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  24481. if( mem0.alarmThreshold>0 ){
  24482. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  24483. if( nUsed >= mem0.alarmThreshold - nFull ){
  24484. mem0.nearlyFull = 1;
  24485. sqlite3MallocAlarm(nFull);
  24486. }else{
  24487. mem0.nearlyFull = 0;
  24488. }
  24489. }
  24490. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  24491. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  24492. if( p==0 && mem0.alarmThreshold>0 ){
  24493. sqlite3MallocAlarm(nFull);
  24494. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  24495. }
  24496. #endif
  24497. if( p ){
  24498. nFull = sqlite3MallocSize(p);
  24499. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  24500. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  24501. }
  24502. *pp = p;
  24503. }
  24504. /*
  24505. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  24506. ** assumes the memory subsystem has already been initialized.
  24507. */
  24508. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  24509. void *p;
  24510. if( n==0 || n>=0x7fffff00 ){
  24511. /* A memory allocation of a number of bytes which is near the maximum
  24512. ** signed integer value might cause an integer overflow inside of the
  24513. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  24514. ** 255 bytes of overhead. SQLite itself will never use anything near
  24515. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  24516. p = 0;
  24517. }else if( sqlite3GlobalConfig.bMemstat ){
  24518. sqlite3_mutex_enter(mem0.mutex);
  24519. mallocWithAlarm((int)n, &p);
  24520. sqlite3_mutex_leave(mem0.mutex);
  24521. }else{
  24522. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  24523. }
  24524. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  24525. return p;
  24526. }
  24527. /*
  24528. ** This version of the memory allocation is for use by the application.
  24529. ** First make sure the memory subsystem is initialized, then do the
  24530. ** allocation.
  24531. */
  24532. SQLITE_API void *sqlite3_malloc(int n){
  24533. #ifndef SQLITE_OMIT_AUTOINIT
  24534. if( sqlite3_initialize() ) return 0;
  24535. #endif
  24536. return n<=0 ? 0 : sqlite3Malloc(n);
  24537. }
  24538. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  24539. #ifndef SQLITE_OMIT_AUTOINIT
  24540. if( sqlite3_initialize() ) return 0;
  24541. #endif
  24542. return sqlite3Malloc(n);
  24543. }
  24544. /*
  24545. ** TRUE if p is a lookaside memory allocation from db
  24546. */
  24547. #ifndef SQLITE_OMIT_LOOKASIDE
  24548. static int isLookaside(sqlite3 *db, void *p){
  24549. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  24550. }
  24551. #else
  24552. #define isLookaside(A,B) 0
  24553. #endif
  24554. /*
  24555. ** Return the size of a memory allocation previously obtained from
  24556. ** sqlite3Malloc() or sqlite3_malloc().
  24557. */
  24558. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  24559. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  24560. return sqlite3GlobalConfig.m.xSize(p);
  24561. }
  24562. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  24563. assert( p!=0 );
  24564. if( db==0 || !isLookaside(db,p) ){
  24565. #ifdef SQLITE_DEBUG
  24566. if( db==0 ){
  24567. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  24568. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  24569. }else{
  24570. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24571. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24572. }
  24573. #endif
  24574. return sqlite3GlobalConfig.m.xSize(p);
  24575. }else{
  24576. assert( sqlite3_mutex_held(db->mutex) );
  24577. return db->lookaside.sz;
  24578. }
  24579. }
  24580. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  24581. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  24582. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  24583. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  24584. }
  24585. /*
  24586. ** Free memory previously obtained from sqlite3Malloc().
  24587. */
  24588. SQLITE_API void sqlite3_free(void *p){
  24589. if( p==0 ) return; /* IMP: R-49053-54554 */
  24590. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  24591. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  24592. if( sqlite3GlobalConfig.bMemstat ){
  24593. sqlite3_mutex_enter(mem0.mutex);
  24594. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  24595. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  24596. sqlite3GlobalConfig.m.xFree(p);
  24597. sqlite3_mutex_leave(mem0.mutex);
  24598. }else{
  24599. sqlite3GlobalConfig.m.xFree(p);
  24600. }
  24601. }
  24602. /*
  24603. ** Add the size of memory allocation "p" to the count in
  24604. ** *db->pnBytesFreed.
  24605. */
  24606. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  24607. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  24608. }
  24609. /*
  24610. ** Free memory that might be associated with a particular database
  24611. ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
  24612. ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
  24613. */
  24614. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
  24615. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  24616. assert( p!=0 );
  24617. if( db ){
  24618. if( db->pnBytesFreed ){
  24619. measureAllocationSize(db, p);
  24620. return;
  24621. }
  24622. if( isLookaside(db, p) ){
  24623. LookasideSlot *pBuf = (LookasideSlot*)p;
  24624. #ifdef SQLITE_DEBUG
  24625. /* Trash all content in the buffer being freed */
  24626. memset(p, 0xaa, db->lookaside.sz);
  24627. #endif
  24628. pBuf->pNext = db->lookaside.pFree;
  24629. db->lookaside.pFree = pBuf;
  24630. return;
  24631. }
  24632. }
  24633. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24634. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24635. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  24636. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  24637. sqlite3_free(p);
  24638. }
  24639. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  24640. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  24641. if( p ) sqlite3DbFreeNN(db, p);
  24642. }
  24643. /*
  24644. ** Change the size of an existing memory allocation
  24645. */
  24646. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  24647. int nOld, nNew, nDiff;
  24648. void *pNew;
  24649. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  24650. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  24651. if( pOld==0 ){
  24652. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  24653. }
  24654. if( nBytes==0 ){
  24655. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  24656. return 0;
  24657. }
  24658. if( nBytes>=0x7fffff00 ){
  24659. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  24660. return 0;
  24661. }
  24662. nOld = sqlite3MallocSize(pOld);
  24663. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  24664. ** argument to xRealloc is always a value returned by a prior call to
  24665. ** xRoundup. */
  24666. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  24667. if( nOld==nNew ){
  24668. pNew = pOld;
  24669. }else if( sqlite3GlobalConfig.bMemstat ){
  24670. sqlite3_mutex_enter(mem0.mutex);
  24671. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  24672. nDiff = nNew - nOld;
  24673. if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  24674. mem0.alarmThreshold-nDiff ){
  24675. sqlite3MallocAlarm(nDiff);
  24676. }
  24677. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  24678. if( pNew==0 && mem0.alarmThreshold>0 ){
  24679. sqlite3MallocAlarm((int)nBytes);
  24680. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  24681. }
  24682. if( pNew ){
  24683. nNew = sqlite3MallocSize(pNew);
  24684. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  24685. }
  24686. sqlite3_mutex_leave(mem0.mutex);
  24687. }else{
  24688. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  24689. }
  24690. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  24691. return pNew;
  24692. }
  24693. /*
  24694. ** The public interface to sqlite3Realloc. Make sure that the memory
  24695. ** subsystem is initialized prior to invoking sqliteRealloc.
  24696. */
  24697. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  24698. #ifndef SQLITE_OMIT_AUTOINIT
  24699. if( sqlite3_initialize() ) return 0;
  24700. #endif
  24701. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  24702. return sqlite3Realloc(pOld, n);
  24703. }
  24704. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  24705. #ifndef SQLITE_OMIT_AUTOINIT
  24706. if( sqlite3_initialize() ) return 0;
  24707. #endif
  24708. return sqlite3Realloc(pOld, n);
  24709. }
  24710. /*
  24711. ** Allocate and zero memory.
  24712. */
  24713. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  24714. void *p = sqlite3Malloc(n);
  24715. if( p ){
  24716. memset(p, 0, (size_t)n);
  24717. }
  24718. return p;
  24719. }
  24720. /*
  24721. ** Allocate and zero memory. If the allocation fails, make
  24722. ** the mallocFailed flag in the connection pointer.
  24723. */
  24724. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  24725. void *p;
  24726. testcase( db==0 );
  24727. p = sqlite3DbMallocRaw(db, n);
  24728. if( p ) memset(p, 0, (size_t)n);
  24729. return p;
  24730. }
  24731. /* Finish the work of sqlite3DbMallocRawNN for the unusual and
  24732. ** slower case when the allocation cannot be fulfilled using lookaside.
  24733. */
  24734. static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
  24735. void *p;
  24736. assert( db!=0 );
  24737. p = sqlite3Malloc(n);
  24738. if( !p ) sqlite3OomFault(db);
  24739. sqlite3MemdebugSetType(p,
  24740. (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  24741. return p;
  24742. }
  24743. /*
  24744. ** Allocate memory, either lookaside (if possible) or heap.
  24745. ** If the allocation fails, set the mallocFailed flag in
  24746. ** the connection pointer.
  24747. **
  24748. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  24749. ** failure on the same database connection) then always return 0.
  24750. ** Hence for a particular database connection, once malloc starts
  24751. ** failing, it fails consistently until mallocFailed is reset.
  24752. ** This is an important assumption. There are many places in the
  24753. ** code that do things like this:
  24754. **
  24755. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  24756. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  24757. ** if( b ) a[10] = 9;
  24758. **
  24759. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  24760. ** that all prior mallocs (ex: "a") worked too.
  24761. **
  24762. ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
  24763. ** not a NULL pointer.
  24764. */
  24765. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  24766. void *p;
  24767. if( db ) return sqlite3DbMallocRawNN(db, n);
  24768. p = sqlite3Malloc(n);
  24769. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  24770. return p;
  24771. }
  24772. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
  24773. #ifndef SQLITE_OMIT_LOOKASIDE
  24774. LookasideSlot *pBuf;
  24775. assert( db!=0 );
  24776. assert( sqlite3_mutex_held(db->mutex) );
  24777. assert( db->pnBytesFreed==0 );
  24778. if( db->lookaside.bDisable==0 ){
  24779. assert( db->mallocFailed==0 );
  24780. if( n>db->lookaside.sz ){
  24781. db->lookaside.anStat[1]++;
  24782. }else if( (pBuf = db->lookaside.pFree)!=0 ){
  24783. db->lookaside.pFree = pBuf->pNext;
  24784. db->lookaside.anStat[0]++;
  24785. return (void*)pBuf;
  24786. }else if( (pBuf = db->lookaside.pInit)!=0 ){
  24787. db->lookaside.pInit = pBuf->pNext;
  24788. db->lookaside.anStat[0]++;
  24789. return (void*)pBuf;
  24790. }else{
  24791. db->lookaside.anStat[2]++;
  24792. }
  24793. }else if( db->mallocFailed ){
  24794. return 0;
  24795. }
  24796. #else
  24797. assert( db!=0 );
  24798. assert( sqlite3_mutex_held(db->mutex) );
  24799. assert( db->pnBytesFreed==0 );
  24800. if( db->mallocFailed ){
  24801. return 0;
  24802. }
  24803. #endif
  24804. return dbMallocRawFinish(db, n);
  24805. }
  24806. /* Forward declaration */
  24807. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
  24808. /*
  24809. ** Resize the block of memory pointed to by p to n bytes. If the
  24810. ** resize fails, set the mallocFailed flag in the connection object.
  24811. */
  24812. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  24813. assert( db!=0 );
  24814. if( p==0 ) return sqlite3DbMallocRawNN(db, n);
  24815. assert( sqlite3_mutex_held(db->mutex) );
  24816. if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
  24817. return dbReallocFinish(db, p, n);
  24818. }
  24819. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
  24820. void *pNew = 0;
  24821. assert( db!=0 );
  24822. assert( p!=0 );
  24823. if( db->mallocFailed==0 ){
  24824. if( isLookaside(db, p) ){
  24825. pNew = sqlite3DbMallocRawNN(db, n);
  24826. if( pNew ){
  24827. memcpy(pNew, p, db->lookaside.sz);
  24828. sqlite3DbFree(db, p);
  24829. }
  24830. }else{
  24831. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24832. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  24833. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  24834. pNew = sqlite3_realloc64(p, n);
  24835. if( !pNew ){
  24836. sqlite3OomFault(db);
  24837. }
  24838. sqlite3MemdebugSetType(pNew,
  24839. (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  24840. }
  24841. }
  24842. return pNew;
  24843. }
  24844. /*
  24845. ** Attempt to reallocate p. If the reallocation fails, then free p
  24846. ** and set the mallocFailed flag in the database connection.
  24847. */
  24848. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  24849. void *pNew;
  24850. pNew = sqlite3DbRealloc(db, p, n);
  24851. if( !pNew ){
  24852. sqlite3DbFree(db, p);
  24853. }
  24854. return pNew;
  24855. }
  24856. /*
  24857. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  24858. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  24859. ** is because when memory debugging is turned on, these two functions are
  24860. ** called via macros that record the current file and line number in the
  24861. ** ThreadData structure.
  24862. */
  24863. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  24864. char *zNew;
  24865. size_t n;
  24866. if( z==0 ){
  24867. return 0;
  24868. }
  24869. n = strlen(z) + 1;
  24870. zNew = sqlite3DbMallocRaw(db, n);
  24871. if( zNew ){
  24872. memcpy(zNew, z, n);
  24873. }
  24874. return zNew;
  24875. }
  24876. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  24877. char *zNew;
  24878. assert( db!=0 );
  24879. if( z==0 ){
  24880. return 0;
  24881. }
  24882. assert( (n&0x7fffffff)==n );
  24883. zNew = sqlite3DbMallocRawNN(db, n+1);
  24884. if( zNew ){
  24885. memcpy(zNew, z, (size_t)n);
  24886. zNew[n] = 0;
  24887. }
  24888. return zNew;
  24889. }
  24890. /*
  24891. ** The text between zStart and zEnd represents a phrase within a larger
  24892. ** SQL statement. Make a copy of this phrase in space obtained form
  24893. ** sqlite3DbMalloc(). Omit leading and trailing whitespace.
  24894. */
  24895. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  24896. int n;
  24897. while( sqlite3Isspace(zStart[0]) ) zStart++;
  24898. n = (int)(zEnd - zStart);
  24899. while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
  24900. return sqlite3DbStrNDup(db, zStart, n);
  24901. }
  24902. /*
  24903. ** Free any prior content in *pz and replace it with a copy of zNew.
  24904. */
  24905. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  24906. sqlite3DbFree(db, *pz);
  24907. *pz = sqlite3DbStrDup(db, zNew);
  24908. }
  24909. /*
  24910. ** Call this routine to record the fact that an OOM (out-of-memory) error
  24911. ** has happened. This routine will set db->mallocFailed, and also
  24912. ** temporarily disable the lookaside memory allocator and interrupt
  24913. ** any running VDBEs.
  24914. */
  24915. SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
  24916. if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
  24917. db->mallocFailed = 1;
  24918. if( db->nVdbeExec>0 ){
  24919. db->u1.isInterrupted = 1;
  24920. }
  24921. db->lookaside.bDisable++;
  24922. }
  24923. }
  24924. /*
  24925. ** This routine reactivates the memory allocator and clears the
  24926. ** db->mallocFailed flag as necessary.
  24927. **
  24928. ** The memory allocator is not restarted if there are running
  24929. ** VDBEs.
  24930. */
  24931. SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
  24932. if( db->mallocFailed && db->nVdbeExec==0 ){
  24933. db->mallocFailed = 0;
  24934. db->u1.isInterrupted = 0;
  24935. assert( db->lookaside.bDisable>0 );
  24936. db->lookaside.bDisable--;
  24937. }
  24938. }
  24939. /*
  24940. ** Take actions at the end of an API call to indicate an OOM error
  24941. */
  24942. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  24943. sqlite3OomClear(db);
  24944. sqlite3Error(db, SQLITE_NOMEM);
  24945. return SQLITE_NOMEM_BKPT;
  24946. }
  24947. /*
  24948. ** This function must be called before exiting any API function (i.e.
  24949. ** returning control to the user) that has called sqlite3_malloc or
  24950. ** sqlite3_realloc.
  24951. **
  24952. ** The returned value is normally a copy of the second argument to this
  24953. ** function. However, if a malloc() failure has occurred since the previous
  24954. ** invocation SQLITE_NOMEM is returned instead.
  24955. **
  24956. ** If an OOM as occurred, then the connection error-code (the value
  24957. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  24958. */
  24959. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  24960. /* If the db handle must hold the connection handle mutex here.
  24961. ** Otherwise the read (and possible write) of db->mallocFailed
  24962. ** is unsafe, as is the call to sqlite3Error().
  24963. */
  24964. assert( db!=0 );
  24965. assert( sqlite3_mutex_held(db->mutex) );
  24966. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  24967. return apiOomError(db);
  24968. }
  24969. return rc & db->errMask;
  24970. }
  24971. /************** End of malloc.c **********************************************/
  24972. /************** Begin file printf.c ******************************************/
  24973. /*
  24974. ** The "printf" code that follows dates from the 1980's. It is in
  24975. ** the public domain.
  24976. **
  24977. **************************************************************************
  24978. **
  24979. ** This file contains code for a set of "printf"-like routines. These
  24980. ** routines format strings much like the printf() from the standard C
  24981. ** library, though the implementation here has enhancements to support
  24982. ** SQLite.
  24983. */
  24984. /* #include "sqliteInt.h" */
  24985. /*
  24986. ** Conversion types fall into various categories as defined by the
  24987. ** following enumeration.
  24988. */
  24989. #define etRADIX 0 /* non-decimal integer types. %x %o */
  24990. #define etFLOAT 1 /* Floating point. %f */
  24991. #define etEXP 2 /* Exponentional notation. %e and %E */
  24992. #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
  24993. #define etSIZE 4 /* Return number of characters processed so far. %n */
  24994. #define etSTRING 5 /* Strings. %s */
  24995. #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
  24996. #define etPERCENT 7 /* Percent symbol. %% */
  24997. #define etCHARX 8 /* Characters. %c */
  24998. /* The rest are extensions, not normally found in printf() */
  24999. #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
  25000. #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
  25001. NULL pointers replaced by SQL NULL. %Q */
  25002. #define etTOKEN 11 /* a pointer to a Token structure */
  25003. #define etSRCLIST 12 /* a pointer to a SrcList */
  25004. #define etPOINTER 13 /* The %p conversion */
  25005. #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
  25006. #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  25007. #define etDECIMAL 16 /* %d or %u, but not %x, %o */
  25008. #define etINVALID 17 /* Any unrecognized conversion type */
  25009. /*
  25010. ** An "etByte" is an 8-bit unsigned value.
  25011. */
  25012. typedef unsigned char etByte;
  25013. /*
  25014. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  25015. ** by an instance of the following structure
  25016. */
  25017. typedef struct et_info { /* Information about each format field */
  25018. char fmttype; /* The format field code letter */
  25019. etByte base; /* The base for radix conversion */
  25020. etByte flags; /* One or more of FLAG_ constants below */
  25021. etByte type; /* Conversion paradigm */
  25022. etByte charset; /* Offset into aDigits[] of the digits string */
  25023. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  25024. } et_info;
  25025. /*
  25026. ** Allowed values for et_info.flags
  25027. */
  25028. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  25029. #define FLAG_STRING 4 /* Allow infinite precision */
  25030. /*
  25031. ** The following table is searched linearly, so it is good to put the
  25032. ** most frequently used conversion types first.
  25033. */
  25034. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  25035. static const char aPrefix[] = "-x0\000X0";
  25036. static const et_info fmtinfo[] = {
  25037. { 'd', 10, 1, etDECIMAL, 0, 0 },
  25038. { 's', 0, 4, etSTRING, 0, 0 },
  25039. { 'g', 0, 1, etGENERIC, 30, 0 },
  25040. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  25041. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  25042. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  25043. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  25044. { 'c', 0, 0, etCHARX, 0, 0 },
  25045. { 'o', 8, 0, etRADIX, 0, 2 },
  25046. { 'u', 10, 0, etDECIMAL, 0, 0 },
  25047. { 'x', 16, 0, etRADIX, 16, 1 },
  25048. { 'X', 16, 0, etRADIX, 0, 4 },
  25049. #ifndef SQLITE_OMIT_FLOATING_POINT
  25050. { 'f', 0, 1, etFLOAT, 0, 0 },
  25051. { 'e', 0, 1, etEXP, 30, 0 },
  25052. { 'E', 0, 1, etEXP, 14, 0 },
  25053. { 'G', 0, 1, etGENERIC, 14, 0 },
  25054. #endif
  25055. { 'i', 10, 1, etDECIMAL, 0, 0 },
  25056. { 'n', 0, 0, etSIZE, 0, 0 },
  25057. { '%', 0, 0, etPERCENT, 0, 0 },
  25058. { 'p', 16, 0, etPOINTER, 0, 1 },
  25059. /* All the rest are undocumented and are for internal use only */
  25060. { 'T', 0, 0, etTOKEN, 0, 0 },
  25061. { 'S', 0, 0, etSRCLIST, 0, 0 },
  25062. { 'r', 10, 1, etORDINAL, 0, 0 },
  25063. };
  25064. /*
  25065. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  25066. ** conversions will work.
  25067. */
  25068. #ifndef SQLITE_OMIT_FLOATING_POINT
  25069. /*
  25070. ** "*val" is a double such that 0.1 <= *val < 10.0
  25071. ** Return the ascii code for the leading digit of *val, then
  25072. ** multiply "*val" by 10.0 to renormalize.
  25073. **
  25074. ** Example:
  25075. ** input: *val = 3.14159
  25076. ** output: *val = 1.4159 function return = '3'
  25077. **
  25078. ** The counter *cnt is incremented each time. After counter exceeds
  25079. ** 16 (the number of significant digits in a 64-bit float) '0' is
  25080. ** always returned.
  25081. */
  25082. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  25083. int digit;
  25084. LONGDOUBLE_TYPE d;
  25085. if( (*cnt)<=0 ) return '0';
  25086. (*cnt)--;
  25087. digit = (int)*val;
  25088. d = digit;
  25089. digit += '0';
  25090. *val = (*val - d)*10.0;
  25091. return (char)digit;
  25092. }
  25093. #endif /* SQLITE_OMIT_FLOATING_POINT */
  25094. /*
  25095. ** Set the StrAccum object to an error mode.
  25096. */
  25097. static void setStrAccumError(StrAccum *p, u8 eError){
  25098. assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
  25099. p->accError = eError;
  25100. p->nAlloc = 0;
  25101. }
  25102. /*
  25103. ** Extra argument values from a PrintfArguments object
  25104. */
  25105. static sqlite3_int64 getIntArg(PrintfArguments *p){
  25106. if( p->nArg<=p->nUsed ) return 0;
  25107. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  25108. }
  25109. static double getDoubleArg(PrintfArguments *p){
  25110. if( p->nArg<=p->nUsed ) return 0.0;
  25111. return sqlite3_value_double(p->apArg[p->nUsed++]);
  25112. }
  25113. static char *getTextArg(PrintfArguments *p){
  25114. if( p->nArg<=p->nUsed ) return 0;
  25115. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  25116. }
  25117. /*
  25118. ** On machines with a small stack size, you can redefine the
  25119. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  25120. */
  25121. #ifndef SQLITE_PRINT_BUF_SIZE
  25122. # define SQLITE_PRINT_BUF_SIZE 70
  25123. #endif
  25124. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  25125. /*
  25126. ** Render a string given by "fmt" into the StrAccum object.
  25127. */
  25128. SQLITE_PRIVATE void sqlite3VXPrintf(
  25129. StrAccum *pAccum, /* Accumulate results here */
  25130. const char *fmt, /* Format string */
  25131. va_list ap /* arguments */
  25132. ){
  25133. int c; /* Next character in the format string */
  25134. char *bufpt; /* Pointer to the conversion buffer */
  25135. int precision; /* Precision of the current field */
  25136. int length; /* Length of the field */
  25137. int idx; /* A general purpose loop counter */
  25138. int width; /* Width of the current field */
  25139. etByte flag_leftjustify; /* True if "-" flag is present */
  25140. etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
  25141. etByte flag_alternateform; /* True if "#" flag is present */
  25142. etByte flag_altform2; /* True if "!" flag is present */
  25143. etByte flag_zeropad; /* True if field width constant starts with zero */
  25144. etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
  25145. etByte done; /* Loop termination flag */
  25146. etByte cThousand; /* Thousands separator for %d and %u */
  25147. etByte xtype = etINVALID; /* Conversion paradigm */
  25148. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  25149. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  25150. sqlite_uint64 longvalue; /* Value for integer types */
  25151. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  25152. const et_info *infop; /* Pointer to the appropriate info structure */
  25153. char *zOut; /* Rendering buffer */
  25154. int nOut; /* Size of the rendering buffer */
  25155. char *zExtra = 0; /* Malloced memory used by some conversion */
  25156. #ifndef SQLITE_OMIT_FLOATING_POINT
  25157. int exp, e2; /* exponent of real numbers */
  25158. int nsd; /* Number of significant digits returned */
  25159. double rounder; /* Used for rounding floating point values */
  25160. etByte flag_dp; /* True if decimal point should be shown */
  25161. etByte flag_rtz; /* True if trailing zeros should be removed */
  25162. #endif
  25163. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  25164. char buf[etBUFSIZE]; /* Conversion buffer */
  25165. /* pAccum never starts out with an empty buffer that was obtained from
  25166. ** malloc(). This precondition is required by the mprintf("%z...")
  25167. ** optimization. */
  25168. assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  25169. bufpt = 0;
  25170. if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
  25171. pArgList = va_arg(ap, PrintfArguments*);
  25172. bArgList = 1;
  25173. }else{
  25174. bArgList = 0;
  25175. }
  25176. for(; (c=(*fmt))!=0; ++fmt){
  25177. if( c!='%' ){
  25178. bufpt = (char *)fmt;
  25179. #if HAVE_STRCHRNUL
  25180. fmt = strchrnul(fmt, '%');
  25181. #else
  25182. do{ fmt++; }while( *fmt && *fmt != '%' );
  25183. #endif
  25184. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  25185. if( *fmt==0 ) break;
  25186. }
  25187. if( (c=(*++fmt))==0 ){
  25188. sqlite3StrAccumAppend(pAccum, "%", 1);
  25189. break;
  25190. }
  25191. /* Find out what flags are present */
  25192. flag_leftjustify = flag_prefix = cThousand =
  25193. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  25194. done = 0;
  25195. do{
  25196. switch( c ){
  25197. case '-': flag_leftjustify = 1; break;
  25198. case '+': flag_prefix = '+'; break;
  25199. case ' ': flag_prefix = ' '; break;
  25200. case '#': flag_alternateform = 1; break;
  25201. case '!': flag_altform2 = 1; break;
  25202. case '0': flag_zeropad = 1; break;
  25203. case ',': cThousand = ','; break;
  25204. default: done = 1; break;
  25205. }
  25206. }while( !done && (c=(*++fmt))!=0 );
  25207. /* Get the field width */
  25208. if( c=='*' ){
  25209. if( bArgList ){
  25210. width = (int)getIntArg(pArgList);
  25211. }else{
  25212. width = va_arg(ap,int);
  25213. }
  25214. if( width<0 ){
  25215. flag_leftjustify = 1;
  25216. width = width >= -2147483647 ? -width : 0;
  25217. }
  25218. c = *++fmt;
  25219. }else{
  25220. unsigned wx = 0;
  25221. while( c>='0' && c<='9' ){
  25222. wx = wx*10 + c - '0';
  25223. c = *++fmt;
  25224. }
  25225. testcase( wx>0x7fffffff );
  25226. width = wx & 0x7fffffff;
  25227. }
  25228. assert( width>=0 );
  25229. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  25230. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  25231. width = SQLITE_PRINTF_PRECISION_LIMIT;
  25232. }
  25233. #endif
  25234. /* Get the precision */
  25235. if( c=='.' ){
  25236. c = *++fmt;
  25237. if( c=='*' ){
  25238. if( bArgList ){
  25239. precision = (int)getIntArg(pArgList);
  25240. }else{
  25241. precision = va_arg(ap,int);
  25242. }
  25243. c = *++fmt;
  25244. if( precision<0 ){
  25245. precision = precision >= -2147483647 ? -precision : -1;
  25246. }
  25247. }else{
  25248. unsigned px = 0;
  25249. while( c>='0' && c<='9' ){
  25250. px = px*10 + c - '0';
  25251. c = *++fmt;
  25252. }
  25253. testcase( px>0x7fffffff );
  25254. precision = px & 0x7fffffff;
  25255. }
  25256. }else{
  25257. precision = -1;
  25258. }
  25259. assert( precision>=(-1) );
  25260. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  25261. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  25262. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  25263. }
  25264. #endif
  25265. /* Get the conversion type modifier */
  25266. if( c=='l' ){
  25267. flag_long = 1;
  25268. c = *++fmt;
  25269. if( c=='l' ){
  25270. flag_long = 2;
  25271. c = *++fmt;
  25272. }
  25273. }else{
  25274. flag_long = 0;
  25275. }
  25276. /* Fetch the info entry for the field */
  25277. infop = &fmtinfo[0];
  25278. xtype = etINVALID;
  25279. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  25280. if( c==fmtinfo[idx].fmttype ){
  25281. infop = &fmtinfo[idx];
  25282. xtype = infop->type;
  25283. break;
  25284. }
  25285. }
  25286. /*
  25287. ** At this point, variables are initialized as follows:
  25288. **
  25289. ** flag_alternateform TRUE if a '#' is present.
  25290. ** flag_altform2 TRUE if a '!' is present.
  25291. ** flag_prefix '+' or ' ' or zero
  25292. ** flag_leftjustify TRUE if a '-' is present or if the
  25293. ** field width was negative.
  25294. ** flag_zeropad TRUE if the width began with 0.
  25295. ** flag_long 1 for "l", 2 for "ll"
  25296. ** width The specified field width. This is
  25297. ** always non-negative. Zero is the default.
  25298. ** precision The specified precision. The default
  25299. ** is -1.
  25300. ** xtype The class of the conversion.
  25301. ** infop Pointer to the appropriate info struct.
  25302. */
  25303. switch( xtype ){
  25304. case etPOINTER:
  25305. flag_long = sizeof(char*)==sizeof(i64) ? 2 :
  25306. sizeof(char*)==sizeof(long int) ? 1 : 0;
  25307. /* Fall through into the next case */
  25308. case etORDINAL:
  25309. case etRADIX:
  25310. cThousand = 0;
  25311. /* Fall through into the next case */
  25312. case etDECIMAL:
  25313. if( infop->flags & FLAG_SIGNED ){
  25314. i64 v;
  25315. if( bArgList ){
  25316. v = getIntArg(pArgList);
  25317. }else if( flag_long ){
  25318. if( flag_long==2 ){
  25319. v = va_arg(ap,i64) ;
  25320. }else{
  25321. v = va_arg(ap,long int);
  25322. }
  25323. }else{
  25324. v = va_arg(ap,int);
  25325. }
  25326. if( v<0 ){
  25327. if( v==SMALLEST_INT64 ){
  25328. longvalue = ((u64)1)<<63;
  25329. }else{
  25330. longvalue = -v;
  25331. }
  25332. prefix = '-';
  25333. }else{
  25334. longvalue = v;
  25335. prefix = flag_prefix;
  25336. }
  25337. }else{
  25338. if( bArgList ){
  25339. longvalue = (u64)getIntArg(pArgList);
  25340. }else if( flag_long ){
  25341. if( flag_long==2 ){
  25342. longvalue = va_arg(ap,u64);
  25343. }else{
  25344. longvalue = va_arg(ap,unsigned long int);
  25345. }
  25346. }else{
  25347. longvalue = va_arg(ap,unsigned int);
  25348. }
  25349. prefix = 0;
  25350. }
  25351. if( longvalue==0 ) flag_alternateform = 0;
  25352. if( flag_zeropad && precision<width-(prefix!=0) ){
  25353. precision = width-(prefix!=0);
  25354. }
  25355. if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
  25356. nOut = etBUFSIZE;
  25357. zOut = buf;
  25358. }else{
  25359. u64 n = (u64)precision + 10 + precision/3;
  25360. zOut = zExtra = sqlite3Malloc( n );
  25361. if( zOut==0 ){
  25362. setStrAccumError(pAccum, STRACCUM_NOMEM);
  25363. return;
  25364. }
  25365. nOut = (int)n;
  25366. }
  25367. bufpt = &zOut[nOut-1];
  25368. if( xtype==etORDINAL ){
  25369. static const char zOrd[] = "thstndrd";
  25370. int x = (int)(longvalue % 10);
  25371. if( x>=4 || (longvalue/10)%10==1 ){
  25372. x = 0;
  25373. }
  25374. *(--bufpt) = zOrd[x*2+1];
  25375. *(--bufpt) = zOrd[x*2];
  25376. }
  25377. {
  25378. const char *cset = &aDigits[infop->charset];
  25379. u8 base = infop->base;
  25380. do{ /* Convert to ascii */
  25381. *(--bufpt) = cset[longvalue%base];
  25382. longvalue = longvalue/base;
  25383. }while( longvalue>0 );
  25384. }
  25385. length = (int)(&zOut[nOut-1]-bufpt);
  25386. while( precision>length ){
  25387. *(--bufpt) = '0'; /* Zero pad */
  25388. length++;
  25389. }
  25390. if( cThousand ){
  25391. int nn = (length - 1)/3; /* Number of "," to insert */
  25392. int ix = (length - 1)%3 + 1;
  25393. bufpt -= nn;
  25394. for(idx=0; nn>0; idx++){
  25395. bufpt[idx] = bufpt[idx+nn];
  25396. ix--;
  25397. if( ix==0 ){
  25398. bufpt[++idx] = cThousand;
  25399. nn--;
  25400. ix = 3;
  25401. }
  25402. }
  25403. }
  25404. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  25405. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  25406. const char *pre;
  25407. char x;
  25408. pre = &aPrefix[infop->prefix];
  25409. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  25410. }
  25411. length = (int)(&zOut[nOut-1]-bufpt);
  25412. break;
  25413. case etFLOAT:
  25414. case etEXP:
  25415. case etGENERIC:
  25416. if( bArgList ){
  25417. realvalue = getDoubleArg(pArgList);
  25418. }else{
  25419. realvalue = va_arg(ap,double);
  25420. }
  25421. #ifdef SQLITE_OMIT_FLOATING_POINT
  25422. length = 0;
  25423. #else
  25424. if( precision<0 ) precision = 6; /* Set default precision */
  25425. if( realvalue<0.0 ){
  25426. realvalue = -realvalue;
  25427. prefix = '-';
  25428. }else{
  25429. prefix = flag_prefix;
  25430. }
  25431. if( xtype==etGENERIC && precision>0 ) precision--;
  25432. testcase( precision>0xfff );
  25433. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  25434. if( xtype==etFLOAT ) realvalue += rounder;
  25435. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  25436. exp = 0;
  25437. if( sqlite3IsNaN((double)realvalue) ){
  25438. bufpt = "NaN";
  25439. length = 3;
  25440. break;
  25441. }
  25442. if( realvalue>0.0 ){
  25443. LONGDOUBLE_TYPE scale = 1.0;
  25444. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  25445. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  25446. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  25447. realvalue /= scale;
  25448. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  25449. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  25450. if( exp>350 ){
  25451. bufpt = buf;
  25452. buf[0] = prefix;
  25453. memcpy(buf+(prefix!=0),"Inf",4);
  25454. length = 3+(prefix!=0);
  25455. break;
  25456. }
  25457. }
  25458. bufpt = buf;
  25459. /*
  25460. ** If the field type is etGENERIC, then convert to either etEXP
  25461. ** or etFLOAT, as appropriate.
  25462. */
  25463. if( xtype!=etFLOAT ){
  25464. realvalue += rounder;
  25465. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  25466. }
  25467. if( xtype==etGENERIC ){
  25468. flag_rtz = !flag_alternateform;
  25469. if( exp<-4 || exp>precision ){
  25470. xtype = etEXP;
  25471. }else{
  25472. precision = precision - exp;
  25473. xtype = etFLOAT;
  25474. }
  25475. }else{
  25476. flag_rtz = flag_altform2;
  25477. }
  25478. if( xtype==etEXP ){
  25479. e2 = 0;
  25480. }else{
  25481. e2 = exp;
  25482. }
  25483. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  25484. bufpt = zExtra
  25485. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  25486. if( bufpt==0 ){
  25487. setStrAccumError(pAccum, STRACCUM_NOMEM);
  25488. return;
  25489. }
  25490. }
  25491. zOut = bufpt;
  25492. nsd = 16 + flag_altform2*10;
  25493. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  25494. /* The sign in front of the number */
  25495. if( prefix ){
  25496. *(bufpt++) = prefix;
  25497. }
  25498. /* Digits prior to the decimal point */
  25499. if( e2<0 ){
  25500. *(bufpt++) = '0';
  25501. }else{
  25502. for(; e2>=0; e2--){
  25503. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  25504. }
  25505. }
  25506. /* The decimal point */
  25507. if( flag_dp ){
  25508. *(bufpt++) = '.';
  25509. }
  25510. /* "0" digits after the decimal point but before the first
  25511. ** significant digit of the number */
  25512. for(e2++; e2<0; precision--, e2++){
  25513. assert( precision>0 );
  25514. *(bufpt++) = '0';
  25515. }
  25516. /* Significant digits after the decimal point */
  25517. while( (precision--)>0 ){
  25518. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  25519. }
  25520. /* Remove trailing zeros and the "." if no digits follow the "." */
  25521. if( flag_rtz && flag_dp ){
  25522. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  25523. assert( bufpt>zOut );
  25524. if( bufpt[-1]=='.' ){
  25525. if( flag_altform2 ){
  25526. *(bufpt++) = '0';
  25527. }else{
  25528. *(--bufpt) = 0;
  25529. }
  25530. }
  25531. }
  25532. /* Add the "eNNN" suffix */
  25533. if( xtype==etEXP ){
  25534. *(bufpt++) = aDigits[infop->charset];
  25535. if( exp<0 ){
  25536. *(bufpt++) = '-'; exp = -exp;
  25537. }else{
  25538. *(bufpt++) = '+';
  25539. }
  25540. if( exp>=100 ){
  25541. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  25542. exp %= 100;
  25543. }
  25544. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  25545. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  25546. }
  25547. *bufpt = 0;
  25548. /* The converted number is in buf[] and zero terminated. Output it.
  25549. ** Note that the number is in the usual order, not reversed as with
  25550. ** integer conversions. */
  25551. length = (int)(bufpt-zOut);
  25552. bufpt = zOut;
  25553. /* Special case: Add leading zeros if the flag_zeropad flag is
  25554. ** set and we are not left justified */
  25555. if( flag_zeropad && !flag_leftjustify && length < width){
  25556. int i;
  25557. int nPad = width - length;
  25558. for(i=width; i>=nPad; i--){
  25559. bufpt[i] = bufpt[i-nPad];
  25560. }
  25561. i = prefix!=0;
  25562. while( nPad-- ) bufpt[i++] = '0';
  25563. length = width;
  25564. }
  25565. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  25566. break;
  25567. case etSIZE:
  25568. if( !bArgList ){
  25569. *(va_arg(ap,int*)) = pAccum->nChar;
  25570. }
  25571. length = width = 0;
  25572. break;
  25573. case etPERCENT:
  25574. buf[0] = '%';
  25575. bufpt = buf;
  25576. length = 1;
  25577. break;
  25578. case etCHARX:
  25579. if( bArgList ){
  25580. bufpt = getTextArg(pArgList);
  25581. length = 1;
  25582. if( bufpt ){
  25583. buf[0] = c = *(bufpt++);
  25584. if( (c&0xc0)==0xc0 ){
  25585. while( length<4 && (bufpt[0]&0xc0)==0x80 ){
  25586. buf[length++] = *(bufpt++);
  25587. }
  25588. }
  25589. }else{
  25590. buf[0] = 0;
  25591. }
  25592. }else{
  25593. unsigned int ch = va_arg(ap,unsigned int);
  25594. if( ch<0x00080 ){
  25595. buf[0] = ch & 0xff;
  25596. length = 1;
  25597. }else if( ch<0x00800 ){
  25598. buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
  25599. buf[1] = 0x80 + (u8)(ch & 0x3f);
  25600. length = 2;
  25601. }else if( ch<0x10000 ){
  25602. buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
  25603. buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
  25604. buf[2] = 0x80 + (u8)(ch & 0x3f);
  25605. length = 3;
  25606. }else{
  25607. buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
  25608. buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
  25609. buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
  25610. buf[3] = 0x80 + (u8)(ch & 0x3f);
  25611. length = 4;
  25612. }
  25613. }
  25614. if( precision>1 ){
  25615. width -= precision-1;
  25616. if( width>1 && !flag_leftjustify ){
  25617. sqlite3AppendChar(pAccum, width-1, ' ');
  25618. width = 0;
  25619. }
  25620. while( precision-- > 1 ){
  25621. sqlite3StrAccumAppend(pAccum, buf, length);
  25622. }
  25623. }
  25624. bufpt = buf;
  25625. flag_altform2 = 1;
  25626. goto adjust_width_for_utf8;
  25627. case etSTRING:
  25628. case etDYNSTRING:
  25629. if( bArgList ){
  25630. bufpt = getTextArg(pArgList);
  25631. xtype = etSTRING;
  25632. }else{
  25633. bufpt = va_arg(ap,char*);
  25634. }
  25635. if( bufpt==0 ){
  25636. bufpt = "";
  25637. }else if( xtype==etDYNSTRING ){
  25638. if( pAccum->nChar==0 && pAccum->mxAlloc && width==0 && precision<0 ){
  25639. /* Special optimization for sqlite3_mprintf("%z..."):
  25640. ** Extend an existing memory allocation rather than creating
  25641. ** a new one. */
  25642. assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  25643. pAccum->zText = bufpt;
  25644. pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
  25645. pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
  25646. pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
  25647. length = 0;
  25648. break;
  25649. }
  25650. zExtra = bufpt;
  25651. }
  25652. if( precision>=0 ){
  25653. if( flag_altform2 ){
  25654. /* Set length to the number of bytes needed in order to display
  25655. ** precision characters */
  25656. unsigned char *z = (unsigned char*)bufpt;
  25657. while( precision-- > 0 && z[0] ){
  25658. SQLITE_SKIP_UTF8(z);
  25659. }
  25660. length = (int)(z - (unsigned char*)bufpt);
  25661. }else{
  25662. for(length=0; length<precision && bufpt[length]; length++){}
  25663. }
  25664. }else{
  25665. length = 0x7fffffff & (int)strlen(bufpt);
  25666. }
  25667. adjust_width_for_utf8:
  25668. if( flag_altform2 && width>0 ){
  25669. /* Adjust width to account for extra bytes in UTF-8 characters */
  25670. int ii = length - 1;
  25671. while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
  25672. }
  25673. break;
  25674. case etSQLESCAPE: /* %q: Escape ' characters */
  25675. case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
  25676. case etSQLESCAPE3: { /* %w: Escape " characters */
  25677. int i, j, k, n, isnull;
  25678. int needQuote;
  25679. char ch;
  25680. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  25681. char *escarg;
  25682. if( bArgList ){
  25683. escarg = getTextArg(pArgList);
  25684. }else{
  25685. escarg = va_arg(ap,char*);
  25686. }
  25687. isnull = escarg==0;
  25688. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  25689. /* For %q, %Q, and %w, the precision is the number of byte (or
  25690. ** characters if the ! flags is present) to use from the input.
  25691. ** Because of the extra quoting characters inserted, the number
  25692. ** of output characters may be larger than the precision.
  25693. */
  25694. k = precision;
  25695. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  25696. if( ch==q ) n++;
  25697. if( flag_altform2 && (ch&0xc0)==0xc0 ){
  25698. while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
  25699. }
  25700. }
  25701. needQuote = !isnull && xtype==etSQLESCAPE2;
  25702. n += i + 3;
  25703. if( n>etBUFSIZE ){
  25704. bufpt = zExtra = sqlite3Malloc( n );
  25705. if( bufpt==0 ){
  25706. setStrAccumError(pAccum, STRACCUM_NOMEM);
  25707. return;
  25708. }
  25709. }else{
  25710. bufpt = buf;
  25711. }
  25712. j = 0;
  25713. if( needQuote ) bufpt[j++] = q;
  25714. k = i;
  25715. for(i=0; i<k; i++){
  25716. bufpt[j++] = ch = escarg[i];
  25717. if( ch==q ) bufpt[j++] = ch;
  25718. }
  25719. if( needQuote ) bufpt[j++] = q;
  25720. bufpt[j] = 0;
  25721. length = j;
  25722. goto adjust_width_for_utf8;
  25723. }
  25724. case etTOKEN: {
  25725. Token *pToken;
  25726. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  25727. pToken = va_arg(ap, Token*);
  25728. assert( bArgList==0 );
  25729. if( pToken && pToken->n ){
  25730. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  25731. }
  25732. length = width = 0;
  25733. break;
  25734. }
  25735. case etSRCLIST: {
  25736. SrcList *pSrc;
  25737. int k;
  25738. struct SrcList_item *pItem;
  25739. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  25740. pSrc = va_arg(ap, SrcList*);
  25741. k = va_arg(ap, int);
  25742. pItem = &pSrc->a[k];
  25743. assert( bArgList==0 );
  25744. assert( k>=0 && k<pSrc->nSrc );
  25745. if( pItem->zDatabase ){
  25746. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  25747. sqlite3StrAccumAppend(pAccum, ".", 1);
  25748. }
  25749. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  25750. length = width = 0;
  25751. break;
  25752. }
  25753. default: {
  25754. assert( xtype==etINVALID );
  25755. return;
  25756. }
  25757. }/* End switch over the format type */
  25758. /*
  25759. ** The text of the conversion is pointed to by "bufpt" and is
  25760. ** "length" characters long. The field width is "width". Do
  25761. ** the output. Both length and width are in bytes, not characters,
  25762. ** at this point. If the "!" flag was present on string conversions
  25763. ** indicating that width and precision should be expressed in characters,
  25764. ** then the values have been translated prior to reaching this point.
  25765. */
  25766. width -= length;
  25767. if( width>0 ){
  25768. if( !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  25769. sqlite3StrAccumAppend(pAccum, bufpt, length);
  25770. if( flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  25771. }else{
  25772. sqlite3StrAccumAppend(pAccum, bufpt, length);
  25773. }
  25774. if( zExtra ){
  25775. sqlite3DbFree(pAccum->db, zExtra);
  25776. zExtra = 0;
  25777. }
  25778. }/* End for loop over the format string */
  25779. } /* End of function */
  25780. /*
  25781. ** Enlarge the memory allocation on a StrAccum object so that it is
  25782. ** able to accept at least N more bytes of text.
  25783. **
  25784. ** Return the number of bytes of text that StrAccum is able to accept
  25785. ** after the attempted enlargement. The value returned might be zero.
  25786. */
  25787. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  25788. char *zNew;
  25789. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  25790. if( p->accError ){
  25791. testcase(p->accError==STRACCUM_TOOBIG);
  25792. testcase(p->accError==STRACCUM_NOMEM);
  25793. return 0;
  25794. }
  25795. if( p->mxAlloc==0 ){
  25796. N = p->nAlloc - p->nChar - 1;
  25797. setStrAccumError(p, STRACCUM_TOOBIG);
  25798. return N;
  25799. }else{
  25800. char *zOld = isMalloced(p) ? p->zText : 0;
  25801. i64 szNew = p->nChar;
  25802. szNew += N + 1;
  25803. if( szNew+p->nChar<=p->mxAlloc ){
  25804. /* Force exponential buffer size growth as long as it does not overflow,
  25805. ** to avoid having to call this routine too often */
  25806. szNew += p->nChar;
  25807. }
  25808. if( szNew > p->mxAlloc ){
  25809. sqlite3StrAccumReset(p);
  25810. setStrAccumError(p, STRACCUM_TOOBIG);
  25811. return 0;
  25812. }else{
  25813. p->nAlloc = (int)szNew;
  25814. }
  25815. if( p->db ){
  25816. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  25817. }else{
  25818. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  25819. }
  25820. if( zNew ){
  25821. assert( p->zText!=0 || p->nChar==0 );
  25822. if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  25823. p->zText = zNew;
  25824. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  25825. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  25826. }else{
  25827. sqlite3StrAccumReset(p);
  25828. setStrAccumError(p, STRACCUM_NOMEM);
  25829. return 0;
  25830. }
  25831. }
  25832. return N;
  25833. }
  25834. /*
  25835. ** Append N copies of character c to the given string buffer.
  25836. */
  25837. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
  25838. testcase( p->nChar + (i64)N > 0x7fffffff );
  25839. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  25840. return;
  25841. }
  25842. while( (N--)>0 ) p->zText[p->nChar++] = c;
  25843. }
  25844. /*
  25845. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  25846. ** So enlarge if first, then do the append.
  25847. **
  25848. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  25849. ** work (enlarging the buffer) using tail recursion, so that the
  25850. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  25851. */
  25852. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  25853. N = sqlite3StrAccumEnlarge(p, N);
  25854. if( N>0 ){
  25855. memcpy(&p->zText[p->nChar], z, N);
  25856. p->nChar += N;
  25857. }
  25858. }
  25859. /*
  25860. ** Append N bytes of text from z to the StrAccum object. Increase the
  25861. ** size of the memory allocation for StrAccum if necessary.
  25862. */
  25863. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  25864. assert( z!=0 || N==0 );
  25865. assert( p->zText!=0 || p->nChar==0 || p->accError );
  25866. assert( N>=0 );
  25867. assert( p->accError==0 || p->nAlloc==0 );
  25868. if( p->nChar+N >= p->nAlloc ){
  25869. enlargeAndAppend(p,z,N);
  25870. }else if( N ){
  25871. assert( p->zText );
  25872. p->nChar += N;
  25873. memcpy(&p->zText[p->nChar-N], z, N);
  25874. }
  25875. }
  25876. /*
  25877. ** Append the complete text of zero-terminated string z[] to the p string.
  25878. */
  25879. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  25880. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  25881. }
  25882. /*
  25883. ** Finish off a string by making sure it is zero-terminated.
  25884. ** Return a pointer to the resulting string. Return a NULL
  25885. ** pointer if any kind of error was encountered.
  25886. */
  25887. static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
  25888. char *zText;
  25889. assert( p->mxAlloc>0 && !isMalloced(p) );
  25890. zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  25891. if( zText ){
  25892. memcpy(zText, p->zText, p->nChar+1);
  25893. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  25894. }else{
  25895. setStrAccumError(p, STRACCUM_NOMEM);
  25896. }
  25897. p->zText = zText;
  25898. return zText;
  25899. }
  25900. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  25901. if( p->zText ){
  25902. p->zText[p->nChar] = 0;
  25903. if( p->mxAlloc>0 && !isMalloced(p) ){
  25904. return strAccumFinishRealloc(p);
  25905. }
  25906. }
  25907. return p->zText;
  25908. }
  25909. /*
  25910. ** Reset an StrAccum string. Reclaim all malloced memory.
  25911. */
  25912. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  25913. if( isMalloced(p) ){
  25914. sqlite3DbFree(p->db, p->zText);
  25915. p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
  25916. }
  25917. p->zText = 0;
  25918. }
  25919. /*
  25920. ** Initialize a string accumulator.
  25921. **
  25922. ** p: The accumulator to be initialized.
  25923. ** db: Pointer to a database connection. May be NULL. Lookaside
  25924. ** memory is used if not NULL. db->mallocFailed is set appropriately
  25925. ** when not NULL.
  25926. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  25927. ** is malloced.
  25928. ** n: Size of zBase in bytes. If total space requirements never exceed
  25929. ** n then no memory allocations ever occur.
  25930. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  25931. ** allocations will ever occur.
  25932. */
  25933. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  25934. p->zText = zBase;
  25935. p->db = db;
  25936. p->nAlloc = n;
  25937. p->mxAlloc = mx;
  25938. p->nChar = 0;
  25939. p->accError = 0;
  25940. p->printfFlags = 0;
  25941. }
  25942. /*
  25943. ** Print into memory obtained from sqliteMalloc(). Use the internal
  25944. ** %-conversion extensions.
  25945. */
  25946. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  25947. char *z;
  25948. char zBase[SQLITE_PRINT_BUF_SIZE];
  25949. StrAccum acc;
  25950. assert( db!=0 );
  25951. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  25952. db->aLimit[SQLITE_LIMIT_LENGTH]);
  25953. acc.printfFlags = SQLITE_PRINTF_INTERNAL;
  25954. sqlite3VXPrintf(&acc, zFormat, ap);
  25955. z = sqlite3StrAccumFinish(&acc);
  25956. if( acc.accError==STRACCUM_NOMEM ){
  25957. sqlite3OomFault(db);
  25958. }
  25959. return z;
  25960. }
  25961. /*
  25962. ** Print into memory obtained from sqliteMalloc(). Use the internal
  25963. ** %-conversion extensions.
  25964. */
  25965. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  25966. va_list ap;
  25967. char *z;
  25968. va_start(ap, zFormat);
  25969. z = sqlite3VMPrintf(db, zFormat, ap);
  25970. va_end(ap);
  25971. return z;
  25972. }
  25973. /*
  25974. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  25975. ** %-conversion extensions.
  25976. */
  25977. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  25978. char *z;
  25979. char zBase[SQLITE_PRINT_BUF_SIZE];
  25980. StrAccum acc;
  25981. #ifdef SQLITE_ENABLE_API_ARMOR
  25982. if( zFormat==0 ){
  25983. (void)SQLITE_MISUSE_BKPT;
  25984. return 0;
  25985. }
  25986. #endif
  25987. #ifndef SQLITE_OMIT_AUTOINIT
  25988. if( sqlite3_initialize() ) return 0;
  25989. #endif
  25990. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  25991. sqlite3VXPrintf(&acc, zFormat, ap);
  25992. z = sqlite3StrAccumFinish(&acc);
  25993. return z;
  25994. }
  25995. /*
  25996. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  25997. ** %-conversion extensions.
  25998. */
  25999. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  26000. va_list ap;
  26001. char *z;
  26002. #ifndef SQLITE_OMIT_AUTOINIT
  26003. if( sqlite3_initialize() ) return 0;
  26004. #endif
  26005. va_start(ap, zFormat);
  26006. z = sqlite3_vmprintf(zFormat, ap);
  26007. va_end(ap);
  26008. return z;
  26009. }
  26010. /*
  26011. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  26012. ** current locale settings. This is important for SQLite because we
  26013. ** are not able to use a "," as the decimal point in place of "." as
  26014. ** specified by some locales.
  26015. **
  26016. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  26017. ** from the snprintf() standard. Unfortunately, it is too late to change
  26018. ** this without breaking compatibility, so we just have to live with the
  26019. ** mistake.
  26020. **
  26021. ** sqlite3_vsnprintf() is the varargs version.
  26022. */
  26023. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  26024. StrAccum acc;
  26025. if( n<=0 ) return zBuf;
  26026. #ifdef SQLITE_ENABLE_API_ARMOR
  26027. if( zBuf==0 || zFormat==0 ) {
  26028. (void)SQLITE_MISUSE_BKPT;
  26029. if( zBuf ) zBuf[0] = 0;
  26030. return zBuf;
  26031. }
  26032. #endif
  26033. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  26034. sqlite3VXPrintf(&acc, zFormat, ap);
  26035. zBuf[acc.nChar] = 0;
  26036. return zBuf;
  26037. }
  26038. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  26039. char *z;
  26040. va_list ap;
  26041. va_start(ap,zFormat);
  26042. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  26043. va_end(ap);
  26044. return z;
  26045. }
  26046. /*
  26047. ** This is the routine that actually formats the sqlite3_log() message.
  26048. ** We house it in a separate routine from sqlite3_log() to avoid using
  26049. ** stack space on small-stack systems when logging is disabled.
  26050. **
  26051. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  26052. ** allocate memory because it might be called while the memory allocator
  26053. ** mutex is held.
  26054. **
  26055. ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
  26056. ** certain format characters (%q) or for very large precisions or widths.
  26057. ** Care must be taken that any sqlite3_log() calls that occur while the
  26058. ** memory mutex is held do not use these mechanisms.
  26059. */
  26060. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  26061. StrAccum acc; /* String accumulator */
  26062. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  26063. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  26064. sqlite3VXPrintf(&acc, zFormat, ap);
  26065. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  26066. sqlite3StrAccumFinish(&acc));
  26067. }
  26068. /*
  26069. ** Format and write a message to the log if logging is enabled.
  26070. */
  26071. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  26072. va_list ap; /* Vararg list */
  26073. if( sqlite3GlobalConfig.xLog ){
  26074. va_start(ap, zFormat);
  26075. renderLogMsg(iErrCode, zFormat, ap);
  26076. va_end(ap);
  26077. }
  26078. }
  26079. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  26080. /*
  26081. ** A version of printf() that understands %lld. Used for debugging.
  26082. ** The printf() built into some versions of windows does not understand %lld
  26083. ** and segfaults if you give it a long long int.
  26084. */
  26085. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  26086. va_list ap;
  26087. StrAccum acc;
  26088. char zBuf[500];
  26089. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  26090. va_start(ap,zFormat);
  26091. sqlite3VXPrintf(&acc, zFormat, ap);
  26092. va_end(ap);
  26093. sqlite3StrAccumFinish(&acc);
  26094. #ifdef SQLITE_OS_TRACE_PROC
  26095. {
  26096. extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
  26097. SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
  26098. }
  26099. #else
  26100. fprintf(stdout,"%s", zBuf);
  26101. fflush(stdout);
  26102. #endif
  26103. }
  26104. #endif
  26105. /*
  26106. ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
  26107. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  26108. */
  26109. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  26110. va_list ap;
  26111. va_start(ap,zFormat);
  26112. sqlite3VXPrintf(p, zFormat, ap);
  26113. va_end(ap);
  26114. }
  26115. /************** End of printf.c **********************************************/
  26116. /************** Begin file treeview.c ****************************************/
  26117. /*
  26118. ** 2015-06-08
  26119. **
  26120. ** The author disclaims copyright to this source code. In place of
  26121. ** a legal notice, here is a blessing:
  26122. **
  26123. ** May you do good and not evil.
  26124. ** May you find forgiveness for yourself and forgive others.
  26125. ** May you share freely, never taking more than you give.
  26126. **
  26127. *************************************************************************
  26128. **
  26129. ** This file contains C code to implement the TreeView debugging routines.
  26130. ** These routines print a parse tree to standard output for debugging and
  26131. ** analysis.
  26132. **
  26133. ** The interfaces in this file is only available when compiling
  26134. ** with SQLITE_DEBUG.
  26135. */
  26136. /* #include "sqliteInt.h" */
  26137. #ifdef SQLITE_DEBUG
  26138. /*
  26139. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  26140. ** is not the last item in the tree.
  26141. */
  26142. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  26143. if( p==0 ){
  26144. p = sqlite3_malloc64( sizeof(*p) );
  26145. if( p==0 ) return 0;
  26146. memset(p, 0, sizeof(*p));
  26147. }else{
  26148. p->iLevel++;
  26149. }
  26150. assert( moreToFollow==0 || moreToFollow==1 );
  26151. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  26152. return p;
  26153. }
  26154. /*
  26155. ** Finished with one layer of the tree
  26156. */
  26157. static void sqlite3TreeViewPop(TreeView *p){
  26158. if( p==0 ) return;
  26159. p->iLevel--;
  26160. if( p->iLevel<0 ) sqlite3_free(p);
  26161. }
  26162. /*
  26163. ** Generate a single line of output for the tree, with a prefix that contains
  26164. ** all the appropriate tree lines
  26165. */
  26166. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  26167. va_list ap;
  26168. int i;
  26169. StrAccum acc;
  26170. char zBuf[500];
  26171. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  26172. if( p ){
  26173. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  26174. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  26175. }
  26176. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  26177. }
  26178. va_start(ap, zFormat);
  26179. sqlite3VXPrintf(&acc, zFormat, ap);
  26180. va_end(ap);
  26181. assert( acc.nChar>0 );
  26182. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  26183. sqlite3StrAccumFinish(&acc);
  26184. fprintf(stdout,"%s", zBuf);
  26185. fflush(stdout);
  26186. }
  26187. /*
  26188. ** Shorthand for starting a new tree item that consists of a single label
  26189. */
  26190. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  26191. p = sqlite3TreeViewPush(p, moreFollows);
  26192. sqlite3TreeViewLine(p, "%s", zLabel);
  26193. }
  26194. /*
  26195. ** Generate a human-readable description of a WITH clause.
  26196. */
  26197. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  26198. int i;
  26199. if( pWith==0 ) return;
  26200. if( pWith->nCte==0 ) return;
  26201. if( pWith->pOuter ){
  26202. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  26203. }else{
  26204. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  26205. }
  26206. if( pWith->nCte>0 ){
  26207. pView = sqlite3TreeViewPush(pView, 1);
  26208. for(i=0; i<pWith->nCte; i++){
  26209. StrAccum x;
  26210. char zLine[1000];
  26211. const struct Cte *pCte = &pWith->a[i];
  26212. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  26213. sqlite3XPrintf(&x, "%s", pCte->zName);
  26214. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  26215. char cSep = '(';
  26216. int j;
  26217. for(j=0; j<pCte->pCols->nExpr; j++){
  26218. sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
  26219. cSep = ',';
  26220. }
  26221. sqlite3XPrintf(&x, ")");
  26222. }
  26223. sqlite3XPrintf(&x, " AS");
  26224. sqlite3StrAccumFinish(&x);
  26225. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  26226. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  26227. sqlite3TreeViewPop(pView);
  26228. }
  26229. sqlite3TreeViewPop(pView);
  26230. }
  26231. }
  26232. /*
  26233. ** Generate a human-readable description of a Select object.
  26234. */
  26235. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  26236. int n = 0;
  26237. int cnt = 0;
  26238. if( p==0 ){
  26239. sqlite3TreeViewLine(pView, "nil-SELECT");
  26240. return;
  26241. }
  26242. pView = sqlite3TreeViewPush(pView, moreToFollow);
  26243. if( p->pWith ){
  26244. sqlite3TreeViewWith(pView, p->pWith, 1);
  26245. cnt = 1;
  26246. sqlite3TreeViewPush(pView, 1);
  26247. }
  26248. do{
  26249. #if SELECTTRACE_ENABLED
  26250. sqlite3TreeViewLine(pView,
  26251. "SELECT%s%s (%s/%p) selFlags=0x%x nSelectRow=%d",
  26252. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  26253. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
  26254. p->zSelName, p, p->selFlags,
  26255. (int)p->nSelectRow
  26256. );
  26257. #else
  26258. sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
  26259. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  26260. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
  26261. (int)p->nSelectRow
  26262. );
  26263. #endif
  26264. if( cnt++ ) sqlite3TreeViewPop(pView);
  26265. if( p->pPrior ){
  26266. n = 1000;
  26267. }else{
  26268. n = 0;
  26269. if( p->pSrc && p->pSrc->nSrc ) n++;
  26270. if( p->pWhere ) n++;
  26271. if( p->pGroupBy ) n++;
  26272. if( p->pHaving ) n++;
  26273. if( p->pOrderBy ) n++;
  26274. if( p->pLimit ) n++;
  26275. }
  26276. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  26277. if( p->pSrc && p->pSrc->nSrc ){
  26278. int i;
  26279. pView = sqlite3TreeViewPush(pView, (n--)>0);
  26280. sqlite3TreeViewLine(pView, "FROM");
  26281. for(i=0; i<p->pSrc->nSrc; i++){
  26282. struct SrcList_item *pItem = &p->pSrc->a[i];
  26283. StrAccum x;
  26284. char zLine[100];
  26285. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  26286. sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
  26287. if( pItem->zDatabase ){
  26288. sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
  26289. }else if( pItem->zName ){
  26290. sqlite3XPrintf(&x, " %s", pItem->zName);
  26291. }
  26292. if( pItem->pTab ){
  26293. sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
  26294. }
  26295. if( pItem->zAlias ){
  26296. sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
  26297. }
  26298. if( pItem->fg.jointype & JT_LEFT ){
  26299. sqlite3XPrintf(&x, " LEFT-JOIN");
  26300. }
  26301. sqlite3StrAccumFinish(&x);
  26302. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  26303. if( pItem->pSelect ){
  26304. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  26305. }
  26306. if( pItem->fg.isTabFunc ){
  26307. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  26308. }
  26309. sqlite3TreeViewPop(pView);
  26310. }
  26311. sqlite3TreeViewPop(pView);
  26312. }
  26313. if( p->pWhere ){
  26314. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  26315. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  26316. sqlite3TreeViewPop(pView);
  26317. }
  26318. if( p->pGroupBy ){
  26319. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  26320. }
  26321. if( p->pHaving ){
  26322. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  26323. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  26324. sqlite3TreeViewPop(pView);
  26325. }
  26326. if( p->pOrderBy ){
  26327. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  26328. }
  26329. if( p->pLimit ){
  26330. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  26331. sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
  26332. if( p->pLimit->pRight ){
  26333. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  26334. sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
  26335. sqlite3TreeViewPop(pView);
  26336. }
  26337. sqlite3TreeViewPop(pView);
  26338. }
  26339. if( p->pPrior ){
  26340. const char *zOp = "UNION";
  26341. switch( p->op ){
  26342. case TK_ALL: zOp = "UNION ALL"; break;
  26343. case TK_INTERSECT: zOp = "INTERSECT"; break;
  26344. case TK_EXCEPT: zOp = "EXCEPT"; break;
  26345. }
  26346. sqlite3TreeViewItem(pView, zOp, 1);
  26347. }
  26348. p = p->pPrior;
  26349. }while( p!=0 );
  26350. sqlite3TreeViewPop(pView);
  26351. }
  26352. /*
  26353. ** Generate a human-readable explanation of an expression tree.
  26354. */
  26355. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  26356. const char *zBinOp = 0; /* Binary operator */
  26357. const char *zUniOp = 0; /* Unary operator */
  26358. char zFlgs[60];
  26359. pView = sqlite3TreeViewPush(pView, moreToFollow);
  26360. if( pExpr==0 ){
  26361. sqlite3TreeViewLine(pView, "nil");
  26362. sqlite3TreeViewPop(pView);
  26363. return;
  26364. }
  26365. if( pExpr->flags ){
  26366. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  26367. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x iRJT=%d",
  26368. pExpr->flags, pExpr->iRightJoinTable);
  26369. }else{
  26370. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  26371. }
  26372. }else{
  26373. zFlgs[0] = 0;
  26374. }
  26375. switch( pExpr->op ){
  26376. case TK_AGG_COLUMN: {
  26377. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  26378. pExpr->iTable, pExpr->iColumn, zFlgs);
  26379. break;
  26380. }
  26381. case TK_COLUMN: {
  26382. if( pExpr->iTable<0 ){
  26383. /* This only happens when coding check constraints */
  26384. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  26385. }else{
  26386. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  26387. pExpr->iTable, pExpr->iColumn, zFlgs);
  26388. }
  26389. break;
  26390. }
  26391. case TK_INTEGER: {
  26392. if( pExpr->flags & EP_IntValue ){
  26393. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  26394. }else{
  26395. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  26396. }
  26397. break;
  26398. }
  26399. #ifndef SQLITE_OMIT_FLOATING_POINT
  26400. case TK_FLOAT: {
  26401. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  26402. break;
  26403. }
  26404. #endif
  26405. case TK_STRING: {
  26406. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  26407. break;
  26408. }
  26409. case TK_NULL: {
  26410. sqlite3TreeViewLine(pView,"NULL");
  26411. break;
  26412. }
  26413. case TK_TRUEFALSE: {
  26414. sqlite3TreeViewLine(pView,
  26415. sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE");
  26416. break;
  26417. }
  26418. #ifndef SQLITE_OMIT_BLOB_LITERAL
  26419. case TK_BLOB: {
  26420. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  26421. break;
  26422. }
  26423. #endif
  26424. case TK_VARIABLE: {
  26425. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  26426. pExpr->u.zToken, pExpr->iColumn);
  26427. break;
  26428. }
  26429. case TK_REGISTER: {
  26430. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  26431. break;
  26432. }
  26433. case TK_ID: {
  26434. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  26435. break;
  26436. }
  26437. #ifndef SQLITE_OMIT_CAST
  26438. case TK_CAST: {
  26439. /* Expressions of the form: CAST(pLeft AS token) */
  26440. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  26441. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  26442. break;
  26443. }
  26444. #endif /* SQLITE_OMIT_CAST */
  26445. case TK_LT: zBinOp = "LT"; break;
  26446. case TK_LE: zBinOp = "LE"; break;
  26447. case TK_GT: zBinOp = "GT"; break;
  26448. case TK_GE: zBinOp = "GE"; break;
  26449. case TK_NE: zBinOp = "NE"; break;
  26450. case TK_EQ: zBinOp = "EQ"; break;
  26451. case TK_IS: zBinOp = "IS"; break;
  26452. case TK_ISNOT: zBinOp = "ISNOT"; break;
  26453. case TK_AND: zBinOp = "AND"; break;
  26454. case TK_OR: zBinOp = "OR"; break;
  26455. case TK_PLUS: zBinOp = "ADD"; break;
  26456. case TK_STAR: zBinOp = "MUL"; break;
  26457. case TK_MINUS: zBinOp = "SUB"; break;
  26458. case TK_REM: zBinOp = "REM"; break;
  26459. case TK_BITAND: zBinOp = "BITAND"; break;
  26460. case TK_BITOR: zBinOp = "BITOR"; break;
  26461. case TK_SLASH: zBinOp = "DIV"; break;
  26462. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  26463. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  26464. case TK_CONCAT: zBinOp = "CONCAT"; break;
  26465. case TK_DOT: zBinOp = "DOT"; break;
  26466. case TK_UMINUS: zUniOp = "UMINUS"; break;
  26467. case TK_UPLUS: zUniOp = "UPLUS"; break;
  26468. case TK_BITNOT: zUniOp = "BITNOT"; break;
  26469. case TK_NOT: zUniOp = "NOT"; break;
  26470. case TK_ISNULL: zUniOp = "ISNULL"; break;
  26471. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  26472. case TK_TRUTH: {
  26473. int x;
  26474. const char *azOp[] = {
  26475. "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
  26476. };
  26477. assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
  26478. assert( pExpr->pRight );
  26479. assert( pExpr->pRight->op==TK_TRUEFALSE );
  26480. x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
  26481. zUniOp = azOp[x];
  26482. break;
  26483. }
  26484. case TK_SPAN: {
  26485. sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
  26486. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  26487. break;
  26488. }
  26489. case TK_COLLATE: {
  26490. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  26491. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  26492. break;
  26493. }
  26494. case TK_AGG_FUNCTION:
  26495. case TK_FUNCTION: {
  26496. ExprList *pFarg; /* List of function arguments */
  26497. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  26498. pFarg = 0;
  26499. }else{
  26500. pFarg = pExpr->x.pList;
  26501. }
  26502. if( pExpr->op==TK_AGG_FUNCTION ){
  26503. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  26504. pExpr->op2, pExpr->u.zToken);
  26505. }else{
  26506. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  26507. }
  26508. if( pFarg ){
  26509. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  26510. }
  26511. break;
  26512. }
  26513. #ifndef SQLITE_OMIT_SUBQUERY
  26514. case TK_EXISTS: {
  26515. sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
  26516. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  26517. break;
  26518. }
  26519. case TK_SELECT: {
  26520. sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
  26521. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  26522. break;
  26523. }
  26524. case TK_IN: {
  26525. sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
  26526. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  26527. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  26528. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  26529. }else{
  26530. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  26531. }
  26532. break;
  26533. }
  26534. #endif /* SQLITE_OMIT_SUBQUERY */
  26535. /*
  26536. ** x BETWEEN y AND z
  26537. **
  26538. ** This is equivalent to
  26539. **
  26540. ** x>=y AND x<=z
  26541. **
  26542. ** X is stored in pExpr->pLeft.
  26543. ** Y is stored in pExpr->pList->a[0].pExpr.
  26544. ** Z is stored in pExpr->pList->a[1].pExpr.
  26545. */
  26546. case TK_BETWEEN: {
  26547. Expr *pX = pExpr->pLeft;
  26548. Expr *pY = pExpr->x.pList->a[0].pExpr;
  26549. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  26550. sqlite3TreeViewLine(pView, "BETWEEN");
  26551. sqlite3TreeViewExpr(pView, pX, 1);
  26552. sqlite3TreeViewExpr(pView, pY, 1);
  26553. sqlite3TreeViewExpr(pView, pZ, 0);
  26554. break;
  26555. }
  26556. case TK_TRIGGER: {
  26557. /* If the opcode is TK_TRIGGER, then the expression is a reference
  26558. ** to a column in the new.* or old.* pseudo-tables available to
  26559. ** trigger programs. In this case Expr.iTable is set to 1 for the
  26560. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  26561. ** is set to the column of the pseudo-table to read, or to -1 to
  26562. ** read the rowid field.
  26563. */
  26564. sqlite3TreeViewLine(pView, "%s(%d)",
  26565. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  26566. break;
  26567. }
  26568. case TK_CASE: {
  26569. sqlite3TreeViewLine(pView, "CASE");
  26570. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  26571. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  26572. break;
  26573. }
  26574. #ifndef SQLITE_OMIT_TRIGGER
  26575. case TK_RAISE: {
  26576. const char *zType = "unk";
  26577. switch( pExpr->affinity ){
  26578. case OE_Rollback: zType = "rollback"; break;
  26579. case OE_Abort: zType = "abort"; break;
  26580. case OE_Fail: zType = "fail"; break;
  26581. case OE_Ignore: zType = "ignore"; break;
  26582. }
  26583. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  26584. break;
  26585. }
  26586. #endif
  26587. case TK_MATCH: {
  26588. sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
  26589. pExpr->iTable, pExpr->iColumn, zFlgs);
  26590. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  26591. break;
  26592. }
  26593. case TK_VECTOR: {
  26594. sqlite3TreeViewBareExprList(pView, pExpr->x.pList, "VECTOR");
  26595. break;
  26596. }
  26597. case TK_SELECT_COLUMN: {
  26598. sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
  26599. sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
  26600. break;
  26601. }
  26602. case TK_IF_NULL_ROW: {
  26603. sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
  26604. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  26605. break;
  26606. }
  26607. default: {
  26608. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  26609. break;
  26610. }
  26611. }
  26612. if( zBinOp ){
  26613. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  26614. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  26615. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  26616. }else if( zUniOp ){
  26617. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  26618. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  26619. }
  26620. sqlite3TreeViewPop(pView);
  26621. }
  26622. /*
  26623. ** Generate a human-readable explanation of an expression list.
  26624. */
  26625. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
  26626. TreeView *pView,
  26627. const ExprList *pList,
  26628. const char *zLabel
  26629. ){
  26630. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  26631. if( pList==0 ){
  26632. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  26633. }else{
  26634. int i;
  26635. sqlite3TreeViewLine(pView, "%s", zLabel);
  26636. for(i=0; i<pList->nExpr; i++){
  26637. int j = pList->a[i].u.x.iOrderByCol;
  26638. char *zName = pList->a[i].zName;
  26639. if( j || zName ){
  26640. sqlite3TreeViewPush(pView, 0);
  26641. }
  26642. if( zName ){
  26643. sqlite3TreeViewLine(pView, "AS %s", zName);
  26644. }
  26645. if( j ){
  26646. sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
  26647. }
  26648. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  26649. if( j || zName ){
  26650. sqlite3TreeViewPop(pView);
  26651. }
  26652. }
  26653. }
  26654. }
  26655. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  26656. TreeView *pView,
  26657. const ExprList *pList,
  26658. u8 moreToFollow,
  26659. const char *zLabel
  26660. ){
  26661. pView = sqlite3TreeViewPush(pView, moreToFollow);
  26662. sqlite3TreeViewBareExprList(pView, pList, zLabel);
  26663. sqlite3TreeViewPop(pView);
  26664. }
  26665. #endif /* SQLITE_DEBUG */
  26666. /************** End of treeview.c ********************************************/
  26667. /************** Begin file random.c ******************************************/
  26668. /*
  26669. ** 2001 September 15
  26670. **
  26671. ** The author disclaims copyright to this source code. In place of
  26672. ** a legal notice, here is a blessing:
  26673. **
  26674. ** May you do good and not evil.
  26675. ** May you find forgiveness for yourself and forgive others.
  26676. ** May you share freely, never taking more than you give.
  26677. **
  26678. *************************************************************************
  26679. ** This file contains code to implement a pseudo-random number
  26680. ** generator (PRNG) for SQLite.
  26681. **
  26682. ** Random numbers are used by some of the database backends in order
  26683. ** to generate random integer keys for tables or random filenames.
  26684. */
  26685. /* #include "sqliteInt.h" */
  26686. /* All threads share a single random number generator.
  26687. ** This structure is the current state of the generator.
  26688. */
  26689. static SQLITE_WSD struct sqlite3PrngType {
  26690. unsigned char isInit; /* True if initialized */
  26691. unsigned char i, j; /* State variables */
  26692. unsigned char s[256]; /* State variables */
  26693. } sqlite3Prng;
  26694. /*
  26695. ** Return N random bytes.
  26696. */
  26697. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  26698. unsigned char t;
  26699. unsigned char *zBuf = pBuf;
  26700. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  26701. ** state vector. If writable static data is unsupported on the target,
  26702. ** we have to locate the state vector at run-time. In the more common
  26703. ** case where writable static data is supported, wsdPrng can refer directly
  26704. ** to the "sqlite3Prng" state vector declared above.
  26705. */
  26706. #ifdef SQLITE_OMIT_WSD
  26707. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  26708. # define wsdPrng p[0]
  26709. #else
  26710. # define wsdPrng sqlite3Prng
  26711. #endif
  26712. #if SQLITE_THREADSAFE
  26713. sqlite3_mutex *mutex;
  26714. #endif
  26715. #ifndef SQLITE_OMIT_AUTOINIT
  26716. if( sqlite3_initialize() ) return;
  26717. #endif
  26718. #if SQLITE_THREADSAFE
  26719. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  26720. #endif
  26721. sqlite3_mutex_enter(mutex);
  26722. if( N<=0 || pBuf==0 ){
  26723. wsdPrng.isInit = 0;
  26724. sqlite3_mutex_leave(mutex);
  26725. return;
  26726. }
  26727. /* Initialize the state of the random number generator once,
  26728. ** the first time this routine is called. The seed value does
  26729. ** not need to contain a lot of randomness since we are not
  26730. ** trying to do secure encryption or anything like that...
  26731. **
  26732. ** Nothing in this file or anywhere else in SQLite does any kind of
  26733. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  26734. ** number generator) not as an encryption device.
  26735. */
  26736. if( !wsdPrng.isInit ){
  26737. int i;
  26738. char k[256];
  26739. wsdPrng.j = 0;
  26740. wsdPrng.i = 0;
  26741. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  26742. for(i=0; i<256; i++){
  26743. wsdPrng.s[i] = (u8)i;
  26744. }
  26745. for(i=0; i<256; i++){
  26746. wsdPrng.j += wsdPrng.s[i] + k[i];
  26747. t = wsdPrng.s[wsdPrng.j];
  26748. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  26749. wsdPrng.s[i] = t;
  26750. }
  26751. wsdPrng.isInit = 1;
  26752. }
  26753. assert( N>0 );
  26754. do{
  26755. wsdPrng.i++;
  26756. t = wsdPrng.s[wsdPrng.i];
  26757. wsdPrng.j += t;
  26758. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  26759. wsdPrng.s[wsdPrng.j] = t;
  26760. t += wsdPrng.s[wsdPrng.i];
  26761. *(zBuf++) = wsdPrng.s[t];
  26762. }while( --N );
  26763. sqlite3_mutex_leave(mutex);
  26764. }
  26765. #ifndef SQLITE_UNTESTABLE
  26766. /*
  26767. ** For testing purposes, we sometimes want to preserve the state of
  26768. ** PRNG and restore the PRNG to its saved state at a later time, or
  26769. ** to reset the PRNG to its initial state. These routines accomplish
  26770. ** those tasks.
  26771. **
  26772. ** The sqlite3_test_control() interface calls these routines to
  26773. ** control the PRNG.
  26774. */
  26775. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  26776. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  26777. memcpy(
  26778. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  26779. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  26780. sizeof(sqlite3Prng)
  26781. );
  26782. }
  26783. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  26784. memcpy(
  26785. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  26786. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  26787. sizeof(sqlite3Prng)
  26788. );
  26789. }
  26790. #endif /* SQLITE_UNTESTABLE */
  26791. /************** End of random.c **********************************************/
  26792. /************** Begin file threads.c *****************************************/
  26793. /*
  26794. ** 2012 July 21
  26795. **
  26796. ** The author disclaims copyright to this source code. In place of
  26797. ** a legal notice, here is a blessing:
  26798. **
  26799. ** May you do good and not evil.
  26800. ** May you find forgiveness for yourself and forgive others.
  26801. ** May you share freely, never taking more than you give.
  26802. **
  26803. ******************************************************************************
  26804. **
  26805. ** This file presents a simple cross-platform threading interface for
  26806. ** use internally by SQLite.
  26807. **
  26808. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  26809. ** runs independently of its creator until it is joined using
  26810. ** sqlite3ThreadJoin(), at which point it terminates.
  26811. **
  26812. ** Threads do not have to be real. It could be that the work of the
  26813. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  26814. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  26815. ** single threaded systems. Nothing in SQLite requires multiple threads.
  26816. ** This interface exists so that applications that want to take advantage
  26817. ** of multiple cores can do so, while also allowing applications to stay
  26818. ** single-threaded if desired.
  26819. */
  26820. /* #include "sqliteInt.h" */
  26821. #if SQLITE_OS_WIN
  26822. /* # include "os_win.h" */
  26823. #endif
  26824. #if SQLITE_MAX_WORKER_THREADS>0
  26825. /********************************* Unix Pthreads ****************************/
  26826. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  26827. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  26828. /* #include <pthread.h> */
  26829. /* A running thread */
  26830. struct SQLiteThread {
  26831. pthread_t tid; /* Thread ID */
  26832. int done; /* Set to true when thread finishes */
  26833. void *pOut; /* Result returned by the thread */
  26834. void *(*xTask)(void*); /* The thread routine */
  26835. void *pIn; /* Argument to the thread */
  26836. };
  26837. /* Create a new thread */
  26838. SQLITE_PRIVATE int sqlite3ThreadCreate(
  26839. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  26840. void *(*xTask)(void*), /* Routine to run in a separate thread */
  26841. void *pIn /* Argument passed into xTask() */
  26842. ){
  26843. SQLiteThread *p;
  26844. int rc;
  26845. assert( ppThread!=0 );
  26846. assert( xTask!=0 );
  26847. /* This routine is never used in single-threaded mode */
  26848. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  26849. *ppThread = 0;
  26850. p = sqlite3Malloc(sizeof(*p));
  26851. if( p==0 ) return SQLITE_NOMEM_BKPT;
  26852. memset(p, 0, sizeof(*p));
  26853. p->xTask = xTask;
  26854. p->pIn = pIn;
  26855. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  26856. ** function that returns SQLITE_ERROR when passed the argument 200, that
  26857. ** forces worker threads to run sequentially and deterministically
  26858. ** for testing purposes. */
  26859. if( sqlite3FaultSim(200) ){
  26860. rc = 1;
  26861. }else{
  26862. rc = pthread_create(&p->tid, 0, xTask, pIn);
  26863. }
  26864. if( rc ){
  26865. p->done = 1;
  26866. p->pOut = xTask(pIn);
  26867. }
  26868. *ppThread = p;
  26869. return SQLITE_OK;
  26870. }
  26871. /* Get the results of the thread */
  26872. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  26873. int rc;
  26874. assert( ppOut!=0 );
  26875. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  26876. if( p->done ){
  26877. *ppOut = p->pOut;
  26878. rc = SQLITE_OK;
  26879. }else{
  26880. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  26881. }
  26882. sqlite3_free(p);
  26883. return rc;
  26884. }
  26885. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  26886. /******************************** End Unix Pthreads *************************/
  26887. /********************************* Win32 Threads ****************************/
  26888. #if SQLITE_OS_WIN_THREADS
  26889. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  26890. #include <process.h>
  26891. /* A running thread */
  26892. struct SQLiteThread {
  26893. void *tid; /* The thread handle */
  26894. unsigned id; /* The thread identifier */
  26895. void *(*xTask)(void*); /* The routine to run as a thread */
  26896. void *pIn; /* Argument to xTask */
  26897. void *pResult; /* Result of xTask */
  26898. };
  26899. /* Thread procedure Win32 compatibility shim */
  26900. static unsigned __stdcall sqlite3ThreadProc(
  26901. void *pArg /* IN: Pointer to the SQLiteThread structure */
  26902. ){
  26903. SQLiteThread *p = (SQLiteThread *)pArg;
  26904. assert( p!=0 );
  26905. #if 0
  26906. /*
  26907. ** This assert appears to trigger spuriously on certain
  26908. ** versions of Windows, possibly due to _beginthreadex()
  26909. ** and/or CreateThread() not fully setting their thread
  26910. ** ID parameter before starting the thread.
  26911. */
  26912. assert( p->id==GetCurrentThreadId() );
  26913. #endif
  26914. assert( p->xTask!=0 );
  26915. p->pResult = p->xTask(p->pIn);
  26916. _endthreadex(0);
  26917. return 0; /* NOT REACHED */
  26918. }
  26919. /* Create a new thread */
  26920. SQLITE_PRIVATE int sqlite3ThreadCreate(
  26921. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  26922. void *(*xTask)(void*), /* Routine to run in a separate thread */
  26923. void *pIn /* Argument passed into xTask() */
  26924. ){
  26925. SQLiteThread *p;
  26926. assert( ppThread!=0 );
  26927. assert( xTask!=0 );
  26928. *ppThread = 0;
  26929. p = sqlite3Malloc(sizeof(*p));
  26930. if( p==0 ) return SQLITE_NOMEM_BKPT;
  26931. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  26932. ** function that returns SQLITE_ERROR when passed the argument 200, that
  26933. ** forces worker threads to run sequentially and deterministically
  26934. ** (via the sqlite3FaultSim() term of the conditional) for testing
  26935. ** purposes. */
  26936. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  26937. memset(p, 0, sizeof(*p));
  26938. }else{
  26939. p->xTask = xTask;
  26940. p->pIn = pIn;
  26941. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  26942. if( p->tid==0 ){
  26943. memset(p, 0, sizeof(*p));
  26944. }
  26945. }
  26946. if( p->xTask==0 ){
  26947. p->id = GetCurrentThreadId();
  26948. p->pResult = xTask(pIn);
  26949. }
  26950. *ppThread = p;
  26951. return SQLITE_OK;
  26952. }
  26953. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  26954. /* Get the results of the thread */
  26955. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  26956. DWORD rc;
  26957. BOOL bRc;
  26958. assert( ppOut!=0 );
  26959. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  26960. if( p->xTask==0 ){
  26961. /* assert( p->id==GetCurrentThreadId() ); */
  26962. rc = WAIT_OBJECT_0;
  26963. assert( p->tid==0 );
  26964. }else{
  26965. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  26966. rc = sqlite3Win32Wait((HANDLE)p->tid);
  26967. assert( rc!=WAIT_IO_COMPLETION );
  26968. bRc = CloseHandle((HANDLE)p->tid);
  26969. assert( bRc );
  26970. }
  26971. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  26972. sqlite3_free(p);
  26973. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  26974. }
  26975. #endif /* SQLITE_OS_WIN_THREADS */
  26976. /******************************** End Win32 Threads *************************/
  26977. /********************************* Single-Threaded **************************/
  26978. #ifndef SQLITE_THREADS_IMPLEMENTED
  26979. /*
  26980. ** This implementation does not actually create a new thread. It does the
  26981. ** work of the thread in the main thread, when either the thread is created
  26982. ** or when it is joined
  26983. */
  26984. /* A running thread */
  26985. struct SQLiteThread {
  26986. void *(*xTask)(void*); /* The routine to run as a thread */
  26987. void *pIn; /* Argument to xTask */
  26988. void *pResult; /* Result of xTask */
  26989. };
  26990. /* Create a new thread */
  26991. SQLITE_PRIVATE int sqlite3ThreadCreate(
  26992. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  26993. void *(*xTask)(void*), /* Routine to run in a separate thread */
  26994. void *pIn /* Argument passed into xTask() */
  26995. ){
  26996. SQLiteThread *p;
  26997. assert( ppThread!=0 );
  26998. assert( xTask!=0 );
  26999. *ppThread = 0;
  27000. p = sqlite3Malloc(sizeof(*p));
  27001. if( p==0 ) return SQLITE_NOMEM_BKPT;
  27002. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  27003. p->xTask = xTask;
  27004. p->pIn = pIn;
  27005. }else{
  27006. p->xTask = 0;
  27007. p->pResult = xTask(pIn);
  27008. }
  27009. *ppThread = p;
  27010. return SQLITE_OK;
  27011. }
  27012. /* Get the results of the thread */
  27013. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  27014. assert( ppOut!=0 );
  27015. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  27016. if( p->xTask ){
  27017. *ppOut = p->xTask(p->pIn);
  27018. }else{
  27019. *ppOut = p->pResult;
  27020. }
  27021. sqlite3_free(p);
  27022. #if defined(SQLITE_TEST)
  27023. {
  27024. void *pTstAlloc = sqlite3Malloc(10);
  27025. if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
  27026. sqlite3_free(pTstAlloc);
  27027. }
  27028. #endif
  27029. return SQLITE_OK;
  27030. }
  27031. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  27032. /****************************** End Single-Threaded *************************/
  27033. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  27034. /************** End of threads.c *********************************************/
  27035. /************** Begin file utf.c *********************************************/
  27036. /*
  27037. ** 2004 April 13
  27038. **
  27039. ** The author disclaims copyright to this source code. In place of
  27040. ** a legal notice, here is a blessing:
  27041. **
  27042. ** May you do good and not evil.
  27043. ** May you find forgiveness for yourself and forgive others.
  27044. ** May you share freely, never taking more than you give.
  27045. **
  27046. *************************************************************************
  27047. ** This file contains routines used to translate between UTF-8,
  27048. ** UTF-16, UTF-16BE, and UTF-16LE.
  27049. **
  27050. ** Notes on UTF-8:
  27051. **
  27052. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  27053. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  27054. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  27055. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  27056. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  27057. **
  27058. **
  27059. ** Notes on UTF-16: (with wwww+1==uuuuu)
  27060. **
  27061. ** Word-0 Word-1 Value
  27062. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  27063. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  27064. **
  27065. **
  27066. ** BOM or Byte Order Mark:
  27067. ** 0xff 0xfe little-endian utf-16 follows
  27068. ** 0xfe 0xff big-endian utf-16 follows
  27069. **
  27070. */
  27071. /* #include "sqliteInt.h" */
  27072. /* #include <assert.h> */
  27073. /* #include "vdbeInt.h" */
  27074. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  27075. /*
  27076. ** The following constant value is used by the SQLITE_BIGENDIAN and
  27077. ** SQLITE_LITTLEENDIAN macros.
  27078. */
  27079. SQLITE_PRIVATE const int sqlite3one = 1;
  27080. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  27081. /*
  27082. ** This lookup table is used to help decode the first byte of
  27083. ** a multi-byte UTF8 character.
  27084. */
  27085. static const unsigned char sqlite3Utf8Trans1[] = {
  27086. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  27087. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  27088. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  27089. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  27090. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  27091. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  27092. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  27093. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  27094. };
  27095. #define WRITE_UTF8(zOut, c) { \
  27096. if( c<0x00080 ){ \
  27097. *zOut++ = (u8)(c&0xFF); \
  27098. } \
  27099. else if( c<0x00800 ){ \
  27100. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  27101. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  27102. } \
  27103. else if( c<0x10000 ){ \
  27104. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  27105. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  27106. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  27107. }else{ \
  27108. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  27109. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  27110. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  27111. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  27112. } \
  27113. }
  27114. #define WRITE_UTF16LE(zOut, c) { \
  27115. if( c<=0xFFFF ){ \
  27116. *zOut++ = (u8)(c&0x00FF); \
  27117. *zOut++ = (u8)((c>>8)&0x00FF); \
  27118. }else{ \
  27119. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  27120. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  27121. *zOut++ = (u8)(c&0x00FF); \
  27122. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  27123. } \
  27124. }
  27125. #define WRITE_UTF16BE(zOut, c) { \
  27126. if( c<=0xFFFF ){ \
  27127. *zOut++ = (u8)((c>>8)&0x00FF); \
  27128. *zOut++ = (u8)(c&0x00FF); \
  27129. }else{ \
  27130. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  27131. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  27132. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  27133. *zOut++ = (u8)(c&0x00FF); \
  27134. } \
  27135. }
  27136. #define READ_UTF16LE(zIn, TERM, c){ \
  27137. c = (*zIn++); \
  27138. c += ((*zIn++)<<8); \
  27139. if( c>=0xD800 && c<0xE000 && TERM ){ \
  27140. int c2 = (*zIn++); \
  27141. c2 += ((*zIn++)<<8); \
  27142. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  27143. } \
  27144. }
  27145. #define READ_UTF16BE(zIn, TERM, c){ \
  27146. c = ((*zIn++)<<8); \
  27147. c += (*zIn++); \
  27148. if( c>=0xD800 && c<0xE000 && TERM ){ \
  27149. int c2 = ((*zIn++)<<8); \
  27150. c2 += (*zIn++); \
  27151. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  27152. } \
  27153. }
  27154. /*
  27155. ** Translate a single UTF-8 character. Return the unicode value.
  27156. **
  27157. ** During translation, assume that the byte that zTerm points
  27158. ** is a 0x00.
  27159. **
  27160. ** Write a pointer to the next unread byte back into *pzNext.
  27161. **
  27162. ** Notes On Invalid UTF-8:
  27163. **
  27164. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  27165. ** be encoded as a multi-byte character. Any multi-byte character that
  27166. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  27167. **
  27168. ** * This routine never allows a UTF16 surrogate value to be encoded.
  27169. ** If a multi-byte character attempts to encode a value between
  27170. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  27171. **
  27172. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  27173. ** byte of a character are interpreted as single-byte characters
  27174. ** and rendered as themselves even though they are technically
  27175. ** invalid characters.
  27176. **
  27177. ** * This routine accepts over-length UTF8 encodings
  27178. ** for unicode values 0x80 and greater. It does not change over-length
  27179. ** encodings to 0xfffd as some systems recommend.
  27180. */
  27181. #define READ_UTF8(zIn, zTerm, c) \
  27182. c = *(zIn++); \
  27183. if( c>=0xc0 ){ \
  27184. c = sqlite3Utf8Trans1[c-0xc0]; \
  27185. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  27186. c = (c<<6) + (0x3f & *(zIn++)); \
  27187. } \
  27188. if( c<0x80 \
  27189. || (c&0xFFFFF800)==0xD800 \
  27190. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  27191. }
  27192. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  27193. const unsigned char **pz /* Pointer to string from which to read char */
  27194. ){
  27195. unsigned int c;
  27196. /* Same as READ_UTF8() above but without the zTerm parameter.
  27197. ** For this routine, we assume the UTF8 string is always zero-terminated.
  27198. */
  27199. c = *((*pz)++);
  27200. if( c>=0xc0 ){
  27201. c = sqlite3Utf8Trans1[c-0xc0];
  27202. while( (*(*pz) & 0xc0)==0x80 ){
  27203. c = (c<<6) + (0x3f & *((*pz)++));
  27204. }
  27205. if( c<0x80
  27206. || (c&0xFFFFF800)==0xD800
  27207. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  27208. }
  27209. return c;
  27210. }
  27211. /*
  27212. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  27213. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  27214. */
  27215. /* #define TRANSLATE_TRACE 1 */
  27216. #ifndef SQLITE_OMIT_UTF16
  27217. /*
  27218. ** This routine transforms the internal text encoding used by pMem to
  27219. ** desiredEnc. It is an error if the string is already of the desired
  27220. ** encoding, or if *pMem does not contain a string value.
  27221. */
  27222. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  27223. int len; /* Maximum length of output string in bytes */
  27224. unsigned char *zOut; /* Output buffer */
  27225. unsigned char *zIn; /* Input iterator */
  27226. unsigned char *zTerm; /* End of input */
  27227. unsigned char *z; /* Output iterator */
  27228. unsigned int c;
  27229. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  27230. assert( pMem->flags&MEM_Str );
  27231. assert( pMem->enc!=desiredEnc );
  27232. assert( pMem->enc!=0 );
  27233. assert( pMem->n>=0 );
  27234. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  27235. {
  27236. char zBuf[100];
  27237. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  27238. fprintf(stderr, "INPUT: %s\n", zBuf);
  27239. }
  27240. #endif
  27241. /* If the translation is between UTF-16 little and big endian, then
  27242. ** all that is required is to swap the byte order. This case is handled
  27243. ** differently from the others.
  27244. */
  27245. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  27246. u8 temp;
  27247. int rc;
  27248. rc = sqlite3VdbeMemMakeWriteable(pMem);
  27249. if( rc!=SQLITE_OK ){
  27250. assert( rc==SQLITE_NOMEM );
  27251. return SQLITE_NOMEM_BKPT;
  27252. }
  27253. zIn = (u8*)pMem->z;
  27254. zTerm = &zIn[pMem->n&~1];
  27255. while( zIn<zTerm ){
  27256. temp = *zIn;
  27257. *zIn = *(zIn+1);
  27258. zIn++;
  27259. *zIn++ = temp;
  27260. }
  27261. pMem->enc = desiredEnc;
  27262. goto translate_out;
  27263. }
  27264. /* Set len to the maximum number of bytes required in the output buffer. */
  27265. if( desiredEnc==SQLITE_UTF8 ){
  27266. /* When converting from UTF-16, the maximum growth results from
  27267. ** translating a 2-byte character to a 4-byte UTF-8 character.
  27268. ** A single byte is required for the output string
  27269. ** nul-terminator.
  27270. */
  27271. pMem->n &= ~1;
  27272. len = pMem->n * 2 + 1;
  27273. }else{
  27274. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  27275. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  27276. ** character. Two bytes are required in the output buffer for the
  27277. ** nul-terminator.
  27278. */
  27279. len = pMem->n * 2 + 2;
  27280. }
  27281. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  27282. ** byte past the end.
  27283. **
  27284. ** Variable zOut is set to point at the output buffer, space obtained
  27285. ** from sqlite3_malloc().
  27286. */
  27287. zIn = (u8*)pMem->z;
  27288. zTerm = &zIn[pMem->n];
  27289. zOut = sqlite3DbMallocRaw(pMem->db, len);
  27290. if( !zOut ){
  27291. return SQLITE_NOMEM_BKPT;
  27292. }
  27293. z = zOut;
  27294. if( pMem->enc==SQLITE_UTF8 ){
  27295. if( desiredEnc==SQLITE_UTF16LE ){
  27296. /* UTF-8 -> UTF-16 Little-endian */
  27297. while( zIn<zTerm ){
  27298. READ_UTF8(zIn, zTerm, c);
  27299. WRITE_UTF16LE(z, c);
  27300. }
  27301. }else{
  27302. assert( desiredEnc==SQLITE_UTF16BE );
  27303. /* UTF-8 -> UTF-16 Big-endian */
  27304. while( zIn<zTerm ){
  27305. READ_UTF8(zIn, zTerm, c);
  27306. WRITE_UTF16BE(z, c);
  27307. }
  27308. }
  27309. pMem->n = (int)(z - zOut);
  27310. *z++ = 0;
  27311. }else{
  27312. assert( desiredEnc==SQLITE_UTF8 );
  27313. if( pMem->enc==SQLITE_UTF16LE ){
  27314. /* UTF-16 Little-endian -> UTF-8 */
  27315. while( zIn<zTerm ){
  27316. READ_UTF16LE(zIn, zIn<zTerm, c);
  27317. WRITE_UTF8(z, c);
  27318. }
  27319. }else{
  27320. /* UTF-16 Big-endian -> UTF-8 */
  27321. while( zIn<zTerm ){
  27322. READ_UTF16BE(zIn, zIn<zTerm, c);
  27323. WRITE_UTF8(z, c);
  27324. }
  27325. }
  27326. pMem->n = (int)(z - zOut);
  27327. }
  27328. *z = 0;
  27329. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  27330. c = pMem->flags;
  27331. sqlite3VdbeMemRelease(pMem);
  27332. pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
  27333. pMem->enc = desiredEnc;
  27334. pMem->z = (char*)zOut;
  27335. pMem->zMalloc = pMem->z;
  27336. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  27337. translate_out:
  27338. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  27339. {
  27340. char zBuf[100];
  27341. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  27342. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  27343. }
  27344. #endif
  27345. return SQLITE_OK;
  27346. }
  27347. #endif /* SQLITE_OMIT_UTF16 */
  27348. #ifndef SQLITE_OMIT_UTF16
  27349. /*
  27350. ** This routine checks for a byte-order mark at the beginning of the
  27351. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  27352. ** the encoding of the Mem adjusted. This routine does not do any
  27353. ** byte-swapping, it just sets Mem.enc appropriately.
  27354. **
  27355. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  27356. ** changed by this function.
  27357. */
  27358. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  27359. int rc = SQLITE_OK;
  27360. u8 bom = 0;
  27361. assert( pMem->n>=0 );
  27362. if( pMem->n>1 ){
  27363. u8 b1 = *(u8 *)pMem->z;
  27364. u8 b2 = *(((u8 *)pMem->z) + 1);
  27365. if( b1==0xFE && b2==0xFF ){
  27366. bom = SQLITE_UTF16BE;
  27367. }
  27368. if( b1==0xFF && b2==0xFE ){
  27369. bom = SQLITE_UTF16LE;
  27370. }
  27371. }
  27372. if( bom ){
  27373. rc = sqlite3VdbeMemMakeWriteable(pMem);
  27374. if( rc==SQLITE_OK ){
  27375. pMem->n -= 2;
  27376. memmove(pMem->z, &pMem->z[2], pMem->n);
  27377. pMem->z[pMem->n] = '\0';
  27378. pMem->z[pMem->n+1] = '\0';
  27379. pMem->flags |= MEM_Term;
  27380. pMem->enc = bom;
  27381. }
  27382. }
  27383. return rc;
  27384. }
  27385. #endif /* SQLITE_OMIT_UTF16 */
  27386. /*
  27387. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  27388. ** return the number of unicode characters in pZ up to (but not including)
  27389. ** the first 0x00 byte. If nByte is not less than zero, return the
  27390. ** number of unicode characters in the first nByte of pZ (or up to
  27391. ** the first 0x00, whichever comes first).
  27392. */
  27393. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  27394. int r = 0;
  27395. const u8 *z = (const u8*)zIn;
  27396. const u8 *zTerm;
  27397. if( nByte>=0 ){
  27398. zTerm = &z[nByte];
  27399. }else{
  27400. zTerm = (const u8*)(-1);
  27401. }
  27402. assert( z<=zTerm );
  27403. while( *z!=0 && z<zTerm ){
  27404. SQLITE_SKIP_UTF8(z);
  27405. r++;
  27406. }
  27407. return r;
  27408. }
  27409. /* This test function is not currently used by the automated test-suite.
  27410. ** Hence it is only available in debug builds.
  27411. */
  27412. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  27413. /*
  27414. ** Translate UTF-8 to UTF-8.
  27415. **
  27416. ** This has the effect of making sure that the string is well-formed
  27417. ** UTF-8. Miscoded characters are removed.
  27418. **
  27419. ** The translation is done in-place and aborted if the output
  27420. ** overruns the input.
  27421. */
  27422. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  27423. unsigned char *zOut = zIn;
  27424. unsigned char *zStart = zIn;
  27425. u32 c;
  27426. while( zIn[0] && zOut<=zIn ){
  27427. c = sqlite3Utf8Read((const u8**)&zIn);
  27428. if( c!=0xfffd ){
  27429. WRITE_UTF8(zOut, c);
  27430. }
  27431. }
  27432. *zOut = 0;
  27433. return (int)(zOut - zStart);
  27434. }
  27435. #endif
  27436. #ifndef SQLITE_OMIT_UTF16
  27437. /*
  27438. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  27439. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  27440. ** be freed by the calling function.
  27441. **
  27442. ** NULL is returned if there is an allocation error.
  27443. */
  27444. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  27445. Mem m;
  27446. memset(&m, 0, sizeof(m));
  27447. m.db = db;
  27448. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  27449. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  27450. if( db->mallocFailed ){
  27451. sqlite3VdbeMemRelease(&m);
  27452. m.z = 0;
  27453. }
  27454. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  27455. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  27456. assert( m.z || db->mallocFailed );
  27457. return m.z;
  27458. }
  27459. /*
  27460. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  27461. ** Return the number of bytes in the first nChar unicode characters
  27462. ** in pZ. nChar must be non-negative.
  27463. */
  27464. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  27465. int c;
  27466. unsigned char const *z = zIn;
  27467. int n = 0;
  27468. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  27469. while( n<nChar ){
  27470. READ_UTF16BE(z, 1, c);
  27471. n++;
  27472. }
  27473. }else{
  27474. while( n<nChar ){
  27475. READ_UTF16LE(z, 1, c);
  27476. n++;
  27477. }
  27478. }
  27479. return (int)(z-(unsigned char const *)zIn);
  27480. }
  27481. #if defined(SQLITE_TEST)
  27482. /*
  27483. ** This routine is called from the TCL test function "translate_selftest".
  27484. ** It checks that the primitives for serializing and deserializing
  27485. ** characters in each encoding are inverses of each other.
  27486. */
  27487. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  27488. unsigned int i, t;
  27489. unsigned char zBuf[20];
  27490. unsigned char *z;
  27491. int n;
  27492. unsigned int c;
  27493. for(i=0; i<0x00110000; i++){
  27494. z = zBuf;
  27495. WRITE_UTF8(z, i);
  27496. n = (int)(z-zBuf);
  27497. assert( n>0 && n<=4 );
  27498. z[0] = 0;
  27499. z = zBuf;
  27500. c = sqlite3Utf8Read((const u8**)&z);
  27501. t = i;
  27502. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  27503. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  27504. assert( c==t );
  27505. assert( (z-zBuf)==n );
  27506. }
  27507. for(i=0; i<0x00110000; i++){
  27508. if( i>=0xD800 && i<0xE000 ) continue;
  27509. z = zBuf;
  27510. WRITE_UTF16LE(z, i);
  27511. n = (int)(z-zBuf);
  27512. assert( n>0 && n<=4 );
  27513. z[0] = 0;
  27514. z = zBuf;
  27515. READ_UTF16LE(z, 1, c);
  27516. assert( c==i );
  27517. assert( (z-zBuf)==n );
  27518. }
  27519. for(i=0; i<0x00110000; i++){
  27520. if( i>=0xD800 && i<0xE000 ) continue;
  27521. z = zBuf;
  27522. WRITE_UTF16BE(z, i);
  27523. n = (int)(z-zBuf);
  27524. assert( n>0 && n<=4 );
  27525. z[0] = 0;
  27526. z = zBuf;
  27527. READ_UTF16BE(z, 1, c);
  27528. assert( c==i );
  27529. assert( (z-zBuf)==n );
  27530. }
  27531. }
  27532. #endif /* SQLITE_TEST */
  27533. #endif /* SQLITE_OMIT_UTF16 */
  27534. /************** End of utf.c *************************************************/
  27535. /************** Begin file util.c ********************************************/
  27536. /*
  27537. ** 2001 September 15
  27538. **
  27539. ** The author disclaims copyright to this source code. In place of
  27540. ** a legal notice, here is a blessing:
  27541. **
  27542. ** May you do good and not evil.
  27543. ** May you find forgiveness for yourself and forgive others.
  27544. ** May you share freely, never taking more than you give.
  27545. **
  27546. *************************************************************************
  27547. ** Utility functions used throughout sqlite.
  27548. **
  27549. ** This file contains functions for allocating memory, comparing
  27550. ** strings, and stuff like that.
  27551. **
  27552. */
  27553. /* #include "sqliteInt.h" */
  27554. /* #include <stdarg.h> */
  27555. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  27556. # include <math.h>
  27557. #endif
  27558. /*
  27559. ** Routine needed to support the testcase() macro.
  27560. */
  27561. #ifdef SQLITE_COVERAGE_TEST
  27562. SQLITE_PRIVATE void sqlite3Coverage(int x){
  27563. static unsigned dummy = 0;
  27564. dummy += (unsigned)x;
  27565. }
  27566. #endif
  27567. /*
  27568. ** Give a callback to the test harness that can be used to simulate faults
  27569. ** in places where it is difficult or expensive to do so purely by means
  27570. ** of inputs.
  27571. **
  27572. ** The intent of the integer argument is to let the fault simulator know
  27573. ** which of multiple sqlite3FaultSim() calls has been hit.
  27574. **
  27575. ** Return whatever integer value the test callback returns, or return
  27576. ** SQLITE_OK if no test callback is installed.
  27577. */
  27578. #ifndef SQLITE_UNTESTABLE
  27579. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  27580. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  27581. return xCallback ? xCallback(iTest) : SQLITE_OK;
  27582. }
  27583. #endif
  27584. #ifndef SQLITE_OMIT_FLOATING_POINT
  27585. /*
  27586. ** Return true if the floating point value is Not a Number (NaN).
  27587. **
  27588. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  27589. ** Otherwise, we have our own implementation that works on most systems.
  27590. */
  27591. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  27592. int rc; /* The value return */
  27593. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  27594. /*
  27595. ** Systems that support the isnan() library function should probably
  27596. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  27597. ** found that many systems do not have a working isnan() function so
  27598. ** this implementation is provided as an alternative.
  27599. **
  27600. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  27601. ** On the other hand, the use of -ffast-math comes with the following
  27602. ** warning:
  27603. **
  27604. ** This option [-ffast-math] should never be turned on by any
  27605. ** -O option since it can result in incorrect output for programs
  27606. ** which depend on an exact implementation of IEEE or ISO
  27607. ** rules/specifications for math functions.
  27608. **
  27609. ** Under MSVC, this NaN test may fail if compiled with a floating-
  27610. ** point precision mode other than /fp:precise. From the MSDN
  27611. ** documentation:
  27612. **
  27613. ** The compiler [with /fp:precise] will properly handle comparisons
  27614. ** involving NaN. For example, x != x evaluates to true if x is NaN
  27615. ** ...
  27616. */
  27617. #ifdef __FAST_MATH__
  27618. # error SQLite will not work correctly with the -ffast-math option of GCC.
  27619. #endif
  27620. volatile double y = x;
  27621. volatile double z = y;
  27622. rc = (y!=z);
  27623. #else /* if HAVE_ISNAN */
  27624. rc = isnan(x);
  27625. #endif /* HAVE_ISNAN */
  27626. testcase( rc );
  27627. return rc;
  27628. }
  27629. #endif /* SQLITE_OMIT_FLOATING_POINT */
  27630. /*
  27631. ** Compute a string length that is limited to what can be stored in
  27632. ** lower 30 bits of a 32-bit signed integer.
  27633. **
  27634. ** The value returned will never be negative. Nor will it ever be greater
  27635. ** than the actual length of the string. For very long strings (greater
  27636. ** than 1GiB) the value returned might be less than the true string length.
  27637. */
  27638. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  27639. if( z==0 ) return 0;
  27640. return 0x3fffffff & (int)strlen(z);
  27641. }
  27642. /*
  27643. ** Return the declared type of a column. Or return zDflt if the column
  27644. ** has no declared type.
  27645. **
  27646. ** The column type is an extra string stored after the zero-terminator on
  27647. ** the column name if and only if the COLFLAG_HASTYPE flag is set.
  27648. */
  27649. SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
  27650. if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
  27651. return pCol->zName + strlen(pCol->zName) + 1;
  27652. }
  27653. /*
  27654. ** Helper function for sqlite3Error() - called rarely. Broken out into
  27655. ** a separate routine to avoid unnecessary register saves on entry to
  27656. ** sqlite3Error().
  27657. */
  27658. static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
  27659. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  27660. sqlite3SystemError(db, err_code);
  27661. }
  27662. /*
  27663. ** Set the current error code to err_code and clear any prior error message.
  27664. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
  27665. ** that would be appropriate.
  27666. */
  27667. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  27668. assert( db!=0 );
  27669. db->errCode = err_code;
  27670. if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
  27671. }
  27672. /*
  27673. ** Load the sqlite3.iSysErrno field if that is an appropriate thing
  27674. ** to do based on the SQLite error code in rc.
  27675. */
  27676. SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
  27677. if( rc==SQLITE_IOERR_NOMEM ) return;
  27678. rc &= 0xff;
  27679. if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
  27680. db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
  27681. }
  27682. }
  27683. /*
  27684. ** Set the most recent error code and error string for the sqlite
  27685. ** handle "db". The error code is set to "err_code".
  27686. **
  27687. ** If it is not NULL, string zFormat specifies the format of the
  27688. ** error string in the style of the printf functions: The following
  27689. ** format characters are allowed:
  27690. **
  27691. ** %s Insert a string
  27692. ** %z A string that should be freed after use
  27693. ** %d Insert an integer
  27694. ** %T Insert a token
  27695. ** %S Insert the first element of a SrcList
  27696. **
  27697. ** zFormat and any string tokens that follow it are assumed to be
  27698. ** encoded in UTF-8.
  27699. **
  27700. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  27701. ** should be called with err_code set to SQLITE_OK and zFormat set
  27702. ** to NULL.
  27703. */
  27704. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  27705. assert( db!=0 );
  27706. db->errCode = err_code;
  27707. sqlite3SystemError(db, err_code);
  27708. if( zFormat==0 ){
  27709. sqlite3Error(db, err_code);
  27710. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  27711. char *z;
  27712. va_list ap;
  27713. va_start(ap, zFormat);
  27714. z = sqlite3VMPrintf(db, zFormat, ap);
  27715. va_end(ap);
  27716. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  27717. }
  27718. }
  27719. /*
  27720. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  27721. ** The following formatting characters are allowed:
  27722. **
  27723. ** %s Insert a string
  27724. ** %z A string that should be freed after use
  27725. ** %d Insert an integer
  27726. ** %T Insert a token
  27727. ** %S Insert the first element of a SrcList
  27728. **
  27729. ** This function should be used to report any error that occurs while
  27730. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  27731. ** last thing the sqlite3_prepare() function does is copy the error
  27732. ** stored by this function into the database handle using sqlite3Error().
  27733. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  27734. ** during statement execution (sqlite3_step() etc.).
  27735. */
  27736. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  27737. char *zMsg;
  27738. va_list ap;
  27739. sqlite3 *db = pParse->db;
  27740. va_start(ap, zFormat);
  27741. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  27742. va_end(ap);
  27743. if( db->suppressErr ){
  27744. sqlite3DbFree(db, zMsg);
  27745. }else{
  27746. pParse->nErr++;
  27747. sqlite3DbFree(db, pParse->zErrMsg);
  27748. pParse->zErrMsg = zMsg;
  27749. pParse->rc = SQLITE_ERROR;
  27750. }
  27751. }
  27752. /*
  27753. ** Convert an SQL-style quoted string into a normal string by removing
  27754. ** the quote characters. The conversion is done in-place. If the
  27755. ** input does not begin with a quote character, then this routine
  27756. ** is a no-op.
  27757. **
  27758. ** The input string must be zero-terminated. A new zero-terminator
  27759. ** is added to the dequoted string.
  27760. **
  27761. ** The return value is -1 if no dequoting occurs or the length of the
  27762. ** dequoted string, exclusive of the zero terminator, if dequoting does
  27763. ** occur.
  27764. **
  27765. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  27766. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  27767. ** "a-b-c".
  27768. */
  27769. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  27770. char quote;
  27771. int i, j;
  27772. if( z==0 ) return;
  27773. quote = z[0];
  27774. if( !sqlite3Isquote(quote) ) return;
  27775. if( quote=='[' ) quote = ']';
  27776. for(i=1, j=0;; i++){
  27777. assert( z[i] );
  27778. if( z[i]==quote ){
  27779. if( z[i+1]==quote ){
  27780. z[j++] = quote;
  27781. i++;
  27782. }else{
  27783. break;
  27784. }
  27785. }else{
  27786. z[j++] = z[i];
  27787. }
  27788. }
  27789. z[j] = 0;
  27790. }
  27791. /*
  27792. ** Generate a Token object from a string
  27793. */
  27794. SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
  27795. p->z = z;
  27796. p->n = sqlite3Strlen30(z);
  27797. }
  27798. /* Convenient short-hand */
  27799. #define UpperToLower sqlite3UpperToLower
  27800. /*
  27801. ** Some systems have stricmp(). Others have strcasecmp(). Because
  27802. ** there is no consistency, we will define our own.
  27803. **
  27804. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  27805. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  27806. ** the contents of two buffers containing UTF-8 strings in a
  27807. ** case-independent fashion, using the same definition of "case
  27808. ** independence" that SQLite uses internally when comparing identifiers.
  27809. */
  27810. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  27811. if( zLeft==0 ){
  27812. return zRight ? -1 : 0;
  27813. }else if( zRight==0 ){
  27814. return 1;
  27815. }
  27816. return sqlite3StrICmp(zLeft, zRight);
  27817. }
  27818. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  27819. unsigned char *a, *b;
  27820. int c;
  27821. a = (unsigned char *)zLeft;
  27822. b = (unsigned char *)zRight;
  27823. for(;;){
  27824. c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
  27825. if( c || *a==0 ) break;
  27826. a++;
  27827. b++;
  27828. }
  27829. return c;
  27830. }
  27831. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  27832. register unsigned char *a, *b;
  27833. if( zLeft==0 ){
  27834. return zRight ? -1 : 0;
  27835. }else if( zRight==0 ){
  27836. return 1;
  27837. }
  27838. a = (unsigned char *)zLeft;
  27839. b = (unsigned char *)zRight;
  27840. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  27841. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  27842. }
  27843. /*
  27844. ** Compute 10 to the E-th power. Examples: E==1 results in 10.
  27845. ** E==2 results in 100. E==50 results in 1.0e50.
  27846. **
  27847. ** This routine only works for values of E between 1 and 341.
  27848. */
  27849. static LONGDOUBLE_TYPE sqlite3Pow10(int E){
  27850. #if defined(_MSC_VER)
  27851. static const LONGDOUBLE_TYPE x[] = {
  27852. 1.0e+001,
  27853. 1.0e+002,
  27854. 1.0e+004,
  27855. 1.0e+008,
  27856. 1.0e+016,
  27857. 1.0e+032,
  27858. 1.0e+064,
  27859. 1.0e+128,
  27860. 1.0e+256
  27861. };
  27862. LONGDOUBLE_TYPE r = 1.0;
  27863. int i;
  27864. assert( E>=0 && E<=307 );
  27865. for(i=0; E!=0; i++, E >>=1){
  27866. if( E & 1 ) r *= x[i];
  27867. }
  27868. return r;
  27869. #else
  27870. LONGDOUBLE_TYPE x = 10.0;
  27871. LONGDOUBLE_TYPE r = 1.0;
  27872. while(1){
  27873. if( E & 1 ) r *= x;
  27874. E >>= 1;
  27875. if( E==0 ) break;
  27876. x *= x;
  27877. }
  27878. return r;
  27879. #endif
  27880. }
  27881. /*
  27882. ** The string z[] is an text representation of a real number.
  27883. ** Convert this string to a double and write it into *pResult.
  27884. **
  27885. ** The string z[] is length bytes in length (bytes, not characters) and
  27886. ** uses the encoding enc. The string is not necessarily zero-terminated.
  27887. **
  27888. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  27889. ** if the string is empty or contains extraneous text. Valid numbers
  27890. ** are in one of these formats:
  27891. **
  27892. ** [+-]digits[E[+-]digits]
  27893. ** [+-]digits.[digits][E[+-]digits]
  27894. ** [+-].digits[E[+-]digits]
  27895. **
  27896. ** Leading and trailing whitespace is ignored for the purpose of determining
  27897. ** validity.
  27898. **
  27899. ** If some prefix of the input string is a valid number, this routine
  27900. ** returns FALSE but it still converts the prefix and writes the result
  27901. ** into *pResult.
  27902. */
  27903. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  27904. #ifndef SQLITE_OMIT_FLOATING_POINT
  27905. int incr;
  27906. const char *zEnd = z + length;
  27907. /* sign * significand * (10 ^ (esign * exponent)) */
  27908. int sign = 1; /* sign of significand */
  27909. i64 s = 0; /* significand */
  27910. int d = 0; /* adjust exponent for shifting decimal point */
  27911. int esign = 1; /* sign of exponent */
  27912. int e = 0; /* exponent */
  27913. int eValid = 1; /* True exponent is either not used or is well-formed */
  27914. double result;
  27915. int nDigits = 0;
  27916. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  27917. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  27918. *pResult = 0.0; /* Default return value, in case of an error */
  27919. if( enc==SQLITE_UTF8 ){
  27920. incr = 1;
  27921. }else{
  27922. int i;
  27923. incr = 2;
  27924. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  27925. for(i=3-enc; i<length && z[i]==0; i+=2){}
  27926. nonNum = i<length;
  27927. zEnd = &z[i^1];
  27928. z += (enc&1);
  27929. }
  27930. /* skip leading spaces */
  27931. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  27932. if( z>=zEnd ) return 0;
  27933. /* get sign of significand */
  27934. if( *z=='-' ){
  27935. sign = -1;
  27936. z+=incr;
  27937. }else if( *z=='+' ){
  27938. z+=incr;
  27939. }
  27940. /* copy max significant digits to significand */
  27941. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  27942. s = s*10 + (*z - '0');
  27943. z+=incr; nDigits++;
  27944. }
  27945. /* skip non-significant significand digits
  27946. ** (increase exponent by d to shift decimal left) */
  27947. while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; nDigits++; d++; }
  27948. if( z>=zEnd ) goto do_atof_calc;
  27949. /* if decimal point is present */
  27950. if( *z=='.' ){
  27951. z+=incr;
  27952. /* copy digits from after decimal to significand
  27953. ** (decrease exponent by d to shift decimal right) */
  27954. while( z<zEnd && sqlite3Isdigit(*z) ){
  27955. if( s<((LARGEST_INT64-9)/10) ){
  27956. s = s*10 + (*z - '0');
  27957. d--;
  27958. }
  27959. z+=incr; nDigits++;
  27960. }
  27961. }
  27962. if( z>=zEnd ) goto do_atof_calc;
  27963. /* if exponent is present */
  27964. if( *z=='e' || *z=='E' ){
  27965. z+=incr;
  27966. eValid = 0;
  27967. /* This branch is needed to avoid a (harmless) buffer overread. The
  27968. ** special comment alerts the mutation tester that the correct answer
  27969. ** is obtained even if the branch is omitted */
  27970. if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
  27971. /* get sign of exponent */
  27972. if( *z=='-' ){
  27973. esign = -1;
  27974. z+=incr;
  27975. }else if( *z=='+' ){
  27976. z+=incr;
  27977. }
  27978. /* copy digits to exponent */
  27979. while( z<zEnd && sqlite3Isdigit(*z) ){
  27980. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  27981. z+=incr;
  27982. eValid = 1;
  27983. }
  27984. }
  27985. /* skip trailing spaces */
  27986. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  27987. do_atof_calc:
  27988. /* adjust exponent by d, and update sign */
  27989. e = (e*esign) + d;
  27990. if( e<0 ) {
  27991. esign = -1;
  27992. e *= -1;
  27993. } else {
  27994. esign = 1;
  27995. }
  27996. if( s==0 ) {
  27997. /* In the IEEE 754 standard, zero is signed. */
  27998. result = sign<0 ? -(double)0 : (double)0;
  27999. } else {
  28000. /* Attempt to reduce exponent.
  28001. **
  28002. ** Branches that are not required for the correct answer but which only
  28003. ** help to obtain the correct answer faster are marked with special
  28004. ** comments, as a hint to the mutation tester.
  28005. */
  28006. while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
  28007. if( esign>0 ){
  28008. if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
  28009. s *= 10;
  28010. }else{
  28011. if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
  28012. s /= 10;
  28013. }
  28014. e--;
  28015. }
  28016. /* adjust the sign of significand */
  28017. s = sign<0 ? -s : s;
  28018. if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
  28019. result = (double)s;
  28020. }else{
  28021. /* attempt to handle extremely small/large numbers better */
  28022. if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
  28023. if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
  28024. LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
  28025. if( esign<0 ){
  28026. result = s / scale;
  28027. result /= 1.0e+308;
  28028. }else{
  28029. result = s * scale;
  28030. result *= 1.0e+308;
  28031. }
  28032. }else{ assert( e>=342 );
  28033. if( esign<0 ){
  28034. result = 0.0*s;
  28035. }else{
  28036. #ifdef INFINITY
  28037. result = INFINITY*s;
  28038. #else
  28039. result = 1e308*1e308*s; /* Infinity */
  28040. #endif
  28041. }
  28042. }
  28043. }else{
  28044. LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
  28045. if( esign<0 ){
  28046. result = s / scale;
  28047. }else{
  28048. result = s * scale;
  28049. }
  28050. }
  28051. }
  28052. }
  28053. /* store the result */
  28054. *pResult = result;
  28055. /* return true if number and no extra non-whitespace chracters after */
  28056. return z==zEnd && nDigits>0 && eValid && nonNum==0;
  28057. #else
  28058. return !sqlite3Atoi64(z, pResult, length, enc);
  28059. #endif /* SQLITE_OMIT_FLOATING_POINT */
  28060. }
  28061. /*
  28062. ** Compare the 19-character string zNum against the text representation
  28063. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  28064. ** if zNum is less than, equal to, or greater than the string.
  28065. ** Note that zNum must contain exactly 19 characters.
  28066. **
  28067. ** Unlike memcmp() this routine is guaranteed to return the difference
  28068. ** in the values of the last digit if the only difference is in the
  28069. ** last digit. So, for example,
  28070. **
  28071. ** compare2pow63("9223372036854775800", 1)
  28072. **
  28073. ** will return -8.
  28074. */
  28075. static int compare2pow63(const char *zNum, int incr){
  28076. int c = 0;
  28077. int i;
  28078. /* 012345678901234567 */
  28079. const char *pow63 = "922337203685477580";
  28080. for(i=0; c==0 && i<18; i++){
  28081. c = (zNum[i*incr]-pow63[i])*10;
  28082. }
  28083. if( c==0 ){
  28084. c = zNum[18*incr] - '8';
  28085. testcase( c==(-1) );
  28086. testcase( c==0 );
  28087. testcase( c==(+1) );
  28088. }
  28089. return c;
  28090. }
  28091. /*
  28092. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  28093. ** routine does *not* accept hexadecimal notation.
  28094. **
  28095. ** Returns:
  28096. **
  28097. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  28098. ** 1 Excess non-space text after the integer value
  28099. ** 2 Integer too large for a 64-bit signed integer or is malformed
  28100. ** 3 Special case of 9223372036854775808
  28101. **
  28102. ** length is the number of bytes in the string (bytes, not characters).
  28103. ** The string is not necessarily zero-terminated. The encoding is
  28104. ** given by enc.
  28105. */
  28106. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  28107. int incr;
  28108. u64 u = 0;
  28109. int neg = 0; /* assume positive */
  28110. int i;
  28111. int c = 0;
  28112. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  28113. int rc; /* Baseline return code */
  28114. const char *zStart;
  28115. const char *zEnd = zNum + length;
  28116. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  28117. if( enc==SQLITE_UTF8 ){
  28118. incr = 1;
  28119. }else{
  28120. incr = 2;
  28121. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  28122. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  28123. nonNum = i<length;
  28124. zEnd = &zNum[i^1];
  28125. zNum += (enc&1);
  28126. }
  28127. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  28128. if( zNum<zEnd ){
  28129. if( *zNum=='-' ){
  28130. neg = 1;
  28131. zNum+=incr;
  28132. }else if( *zNum=='+' ){
  28133. zNum+=incr;
  28134. }
  28135. }
  28136. zStart = zNum;
  28137. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  28138. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  28139. u = u*10 + c - '0';
  28140. }
  28141. testcase( i==18*incr );
  28142. testcase( i==19*incr );
  28143. testcase( i==20*incr );
  28144. if( u>LARGEST_INT64 ){
  28145. /* This test and assignment is needed only to suppress UB warnings
  28146. ** from clang and -fsanitize=undefined. This test and assignment make
  28147. ** the code a little larger and slower, and no harm comes from omitting
  28148. ** them, but we must appaise the undefined-behavior pharisees. */
  28149. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  28150. }else if( neg ){
  28151. *pNum = -(i64)u;
  28152. }else{
  28153. *pNum = (i64)u;
  28154. }
  28155. rc = 0;
  28156. if( (i==0 && zStart==zNum) /* No digits */
  28157. || nonNum /* UTF16 with high-order bytes non-zero */
  28158. ){
  28159. rc = 1;
  28160. }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
  28161. int jj = i;
  28162. do{
  28163. if( !sqlite3Isspace(zNum[jj]) ){
  28164. rc = 1; /* Extra non-space text after the integer */
  28165. break;
  28166. }
  28167. jj += incr;
  28168. }while( &zNum[jj]<zEnd );
  28169. }
  28170. if( i<19*incr ){
  28171. /* Less than 19 digits, so we know that it fits in 64 bits */
  28172. assert( u<=LARGEST_INT64 );
  28173. return rc;
  28174. }else{
  28175. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  28176. c = i>19*incr ? 1 : compare2pow63(zNum, incr);
  28177. if( c<0 ){
  28178. /* zNum is less than 9223372036854775808 so it fits */
  28179. assert( u<=LARGEST_INT64 );
  28180. return rc;
  28181. }else{
  28182. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  28183. if( c>0 ){
  28184. /* zNum is greater than 9223372036854775808 so it overflows */
  28185. return 2;
  28186. }else{
  28187. /* zNum is exactly 9223372036854775808. Fits if negative. The
  28188. ** special case 2 overflow if positive */
  28189. assert( u-1==LARGEST_INT64 );
  28190. return neg ? rc : 3;
  28191. }
  28192. }
  28193. }
  28194. }
  28195. /*
  28196. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  28197. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  28198. ** whereas sqlite3Atoi64() does not.
  28199. **
  28200. ** Returns:
  28201. **
  28202. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  28203. ** 1 Excess text after the integer value
  28204. ** 2 Integer too large for a 64-bit signed integer or is malformed
  28205. ** 3 Special case of 9223372036854775808
  28206. */
  28207. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  28208. #ifndef SQLITE_OMIT_HEX_INTEGER
  28209. if( z[0]=='0'
  28210. && (z[1]=='x' || z[1]=='X')
  28211. ){
  28212. u64 u = 0;
  28213. int i, k;
  28214. for(i=2; z[i]=='0'; i++){}
  28215. for(k=i; sqlite3Isxdigit(z[k]); k++){
  28216. u = u*16 + sqlite3HexToInt(z[k]);
  28217. }
  28218. memcpy(pOut, &u, 8);
  28219. return (z[k]==0 && k-i<=16) ? 0 : 2;
  28220. }else
  28221. #endif /* SQLITE_OMIT_HEX_INTEGER */
  28222. {
  28223. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  28224. }
  28225. }
  28226. /*
  28227. ** If zNum represents an integer that will fit in 32-bits, then set
  28228. ** *pValue to that integer and return true. Otherwise return false.
  28229. **
  28230. ** This routine accepts both decimal and hexadecimal notation for integers.
  28231. **
  28232. ** Any non-numeric characters that following zNum are ignored.
  28233. ** This is different from sqlite3Atoi64() which requires the
  28234. ** input number to be zero-terminated.
  28235. */
  28236. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  28237. sqlite_int64 v = 0;
  28238. int i, c;
  28239. int neg = 0;
  28240. if( zNum[0]=='-' ){
  28241. neg = 1;
  28242. zNum++;
  28243. }else if( zNum[0]=='+' ){
  28244. zNum++;
  28245. }
  28246. #ifndef SQLITE_OMIT_HEX_INTEGER
  28247. else if( zNum[0]=='0'
  28248. && (zNum[1]=='x' || zNum[1]=='X')
  28249. && sqlite3Isxdigit(zNum[2])
  28250. ){
  28251. u32 u = 0;
  28252. zNum += 2;
  28253. while( zNum[0]=='0' ) zNum++;
  28254. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  28255. u = u*16 + sqlite3HexToInt(zNum[i]);
  28256. }
  28257. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  28258. memcpy(pValue, &u, 4);
  28259. return 1;
  28260. }else{
  28261. return 0;
  28262. }
  28263. }
  28264. #endif
  28265. if( !sqlite3Isdigit(zNum[0]) ) return 0;
  28266. while( zNum[0]=='0' ) zNum++;
  28267. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  28268. v = v*10 + c;
  28269. }
  28270. /* The longest decimal representation of a 32 bit integer is 10 digits:
  28271. **
  28272. ** 1234567890
  28273. ** 2^31 -> 2147483648
  28274. */
  28275. testcase( i==10 );
  28276. if( i>10 ){
  28277. return 0;
  28278. }
  28279. testcase( v-neg==2147483647 );
  28280. if( v-neg>2147483647 ){
  28281. return 0;
  28282. }
  28283. if( neg ){
  28284. v = -v;
  28285. }
  28286. *pValue = (int)v;
  28287. return 1;
  28288. }
  28289. /*
  28290. ** Return a 32-bit integer value extracted from a string. If the
  28291. ** string is not an integer, just return 0.
  28292. */
  28293. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  28294. int x = 0;
  28295. if( z ) sqlite3GetInt32(z, &x);
  28296. return x;
  28297. }
  28298. /*
  28299. ** The variable-length integer encoding is as follows:
  28300. **
  28301. ** KEY:
  28302. ** A = 0xxxxxxx 7 bits of data and one flag bit
  28303. ** B = 1xxxxxxx 7 bits of data and one flag bit
  28304. ** C = xxxxxxxx 8 bits of data
  28305. **
  28306. ** 7 bits - A
  28307. ** 14 bits - BA
  28308. ** 21 bits - BBA
  28309. ** 28 bits - BBBA
  28310. ** 35 bits - BBBBA
  28311. ** 42 bits - BBBBBA
  28312. ** 49 bits - BBBBBBA
  28313. ** 56 bits - BBBBBBBA
  28314. ** 64 bits - BBBBBBBBC
  28315. */
  28316. /*
  28317. ** Write a 64-bit variable-length integer to memory starting at p[0].
  28318. ** The length of data write will be between 1 and 9 bytes. The number
  28319. ** of bytes written is returned.
  28320. **
  28321. ** A variable-length integer consists of the lower 7 bits of each byte
  28322. ** for all bytes that have the 8th bit set and one byte with the 8th
  28323. ** bit clear. Except, if we get to the 9th byte, it stores the full
  28324. ** 8 bits and is the last byte.
  28325. */
  28326. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  28327. int i, j, n;
  28328. u8 buf[10];
  28329. if( v & (((u64)0xff000000)<<32) ){
  28330. p[8] = (u8)v;
  28331. v >>= 8;
  28332. for(i=7; i>=0; i--){
  28333. p[i] = (u8)((v & 0x7f) | 0x80);
  28334. v >>= 7;
  28335. }
  28336. return 9;
  28337. }
  28338. n = 0;
  28339. do{
  28340. buf[n++] = (u8)((v & 0x7f) | 0x80);
  28341. v >>= 7;
  28342. }while( v!=0 );
  28343. buf[0] &= 0x7f;
  28344. assert( n<=9 );
  28345. for(i=0, j=n-1; j>=0; j--, i++){
  28346. p[i] = buf[j];
  28347. }
  28348. return n;
  28349. }
  28350. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  28351. if( v<=0x7f ){
  28352. p[0] = v&0x7f;
  28353. return 1;
  28354. }
  28355. if( v<=0x3fff ){
  28356. p[0] = ((v>>7)&0x7f)|0x80;
  28357. p[1] = v&0x7f;
  28358. return 2;
  28359. }
  28360. return putVarint64(p,v);
  28361. }
  28362. /*
  28363. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  28364. ** are defined here rather than simply putting the constant expressions
  28365. ** inline in order to work around bugs in the RVT compiler.
  28366. **
  28367. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  28368. **
  28369. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  28370. */
  28371. #define SLOT_2_0 0x001fc07f
  28372. #define SLOT_4_2_0 0xf01fc07f
  28373. /*
  28374. ** Read a 64-bit variable-length integer from memory starting at p[0].
  28375. ** Return the number of bytes read. The value is stored in *v.
  28376. */
  28377. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  28378. u32 a,b,s;
  28379. a = *p;
  28380. /* a: p0 (unmasked) */
  28381. if (!(a&0x80))
  28382. {
  28383. *v = a;
  28384. return 1;
  28385. }
  28386. p++;
  28387. b = *p;
  28388. /* b: p1 (unmasked) */
  28389. if (!(b&0x80))
  28390. {
  28391. a &= 0x7f;
  28392. a = a<<7;
  28393. a |= b;
  28394. *v = a;
  28395. return 2;
  28396. }
  28397. /* Verify that constants are precomputed correctly */
  28398. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  28399. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  28400. p++;
  28401. a = a<<14;
  28402. a |= *p;
  28403. /* a: p0<<14 | p2 (unmasked) */
  28404. if (!(a&0x80))
  28405. {
  28406. a &= SLOT_2_0;
  28407. b &= 0x7f;
  28408. b = b<<7;
  28409. a |= b;
  28410. *v = a;
  28411. return 3;
  28412. }
  28413. /* CSE1 from below */
  28414. a &= SLOT_2_0;
  28415. p++;
  28416. b = b<<14;
  28417. b |= *p;
  28418. /* b: p1<<14 | p3 (unmasked) */
  28419. if (!(b&0x80))
  28420. {
  28421. b &= SLOT_2_0;
  28422. /* moved CSE1 up */
  28423. /* a &= (0x7f<<14)|(0x7f); */
  28424. a = a<<7;
  28425. a |= b;
  28426. *v = a;
  28427. return 4;
  28428. }
  28429. /* a: p0<<14 | p2 (masked) */
  28430. /* b: p1<<14 | p3 (unmasked) */
  28431. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  28432. /* moved CSE1 up */
  28433. /* a &= (0x7f<<14)|(0x7f); */
  28434. b &= SLOT_2_0;
  28435. s = a;
  28436. /* s: p0<<14 | p2 (masked) */
  28437. p++;
  28438. a = a<<14;
  28439. a |= *p;
  28440. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  28441. if (!(a&0x80))
  28442. {
  28443. /* we can skip these cause they were (effectively) done above
  28444. ** while calculating s */
  28445. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  28446. /* b &= (0x7f<<14)|(0x7f); */
  28447. b = b<<7;
  28448. a |= b;
  28449. s = s>>18;
  28450. *v = ((u64)s)<<32 | a;
  28451. return 5;
  28452. }
  28453. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  28454. s = s<<7;
  28455. s |= b;
  28456. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  28457. p++;
  28458. b = b<<14;
  28459. b |= *p;
  28460. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  28461. if (!(b&0x80))
  28462. {
  28463. /* we can skip this cause it was (effectively) done above in calc'ing s */
  28464. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  28465. a &= SLOT_2_0;
  28466. a = a<<7;
  28467. a |= b;
  28468. s = s>>18;
  28469. *v = ((u64)s)<<32 | a;
  28470. return 6;
  28471. }
  28472. p++;
  28473. a = a<<14;
  28474. a |= *p;
  28475. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  28476. if (!(a&0x80))
  28477. {
  28478. a &= SLOT_4_2_0;
  28479. b &= SLOT_2_0;
  28480. b = b<<7;
  28481. a |= b;
  28482. s = s>>11;
  28483. *v = ((u64)s)<<32 | a;
  28484. return 7;
  28485. }
  28486. /* CSE2 from below */
  28487. a &= SLOT_2_0;
  28488. p++;
  28489. b = b<<14;
  28490. b |= *p;
  28491. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  28492. if (!(b&0x80))
  28493. {
  28494. b &= SLOT_4_2_0;
  28495. /* moved CSE2 up */
  28496. /* a &= (0x7f<<14)|(0x7f); */
  28497. a = a<<7;
  28498. a |= b;
  28499. s = s>>4;
  28500. *v = ((u64)s)<<32 | a;
  28501. return 8;
  28502. }
  28503. p++;
  28504. a = a<<15;
  28505. a |= *p;
  28506. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  28507. /* moved CSE2 up */
  28508. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  28509. b &= SLOT_2_0;
  28510. b = b<<8;
  28511. a |= b;
  28512. s = s<<4;
  28513. b = p[-4];
  28514. b &= 0x7f;
  28515. b = b>>3;
  28516. s |= b;
  28517. *v = ((u64)s)<<32 | a;
  28518. return 9;
  28519. }
  28520. /*
  28521. ** Read a 32-bit variable-length integer from memory starting at p[0].
  28522. ** Return the number of bytes read. The value is stored in *v.
  28523. **
  28524. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  28525. ** integer, then set *v to 0xffffffff.
  28526. **
  28527. ** A MACRO version, getVarint32, is provided which inlines the
  28528. ** single-byte case. All code should use the MACRO version as
  28529. ** this function assumes the single-byte case has already been handled.
  28530. */
  28531. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  28532. u32 a,b;
  28533. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  28534. ** by the getVarin32() macro */
  28535. a = *p;
  28536. /* a: p0 (unmasked) */
  28537. #ifndef getVarint32
  28538. if (!(a&0x80))
  28539. {
  28540. /* Values between 0 and 127 */
  28541. *v = a;
  28542. return 1;
  28543. }
  28544. #endif
  28545. /* The 2-byte case */
  28546. p++;
  28547. b = *p;
  28548. /* b: p1 (unmasked) */
  28549. if (!(b&0x80))
  28550. {
  28551. /* Values between 128 and 16383 */
  28552. a &= 0x7f;
  28553. a = a<<7;
  28554. *v = a | b;
  28555. return 2;
  28556. }
  28557. /* The 3-byte case */
  28558. p++;
  28559. a = a<<14;
  28560. a |= *p;
  28561. /* a: p0<<14 | p2 (unmasked) */
  28562. if (!(a&0x80))
  28563. {
  28564. /* Values between 16384 and 2097151 */
  28565. a &= (0x7f<<14)|(0x7f);
  28566. b &= 0x7f;
  28567. b = b<<7;
  28568. *v = a | b;
  28569. return 3;
  28570. }
  28571. /* A 32-bit varint is used to store size information in btrees.
  28572. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  28573. ** A 3-byte varint is sufficient, for example, to record the size
  28574. ** of a 1048569-byte BLOB or string.
  28575. **
  28576. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  28577. ** rare larger cases can be handled by the slower 64-bit varint
  28578. ** routine.
  28579. */
  28580. #if 1
  28581. {
  28582. u64 v64;
  28583. u8 n;
  28584. p -= 2;
  28585. n = sqlite3GetVarint(p, &v64);
  28586. assert( n>3 && n<=9 );
  28587. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  28588. *v = 0xffffffff;
  28589. }else{
  28590. *v = (u32)v64;
  28591. }
  28592. return n;
  28593. }
  28594. #else
  28595. /* For following code (kept for historical record only) shows an
  28596. ** unrolling for the 3- and 4-byte varint cases. This code is
  28597. ** slightly faster, but it is also larger and much harder to test.
  28598. */
  28599. p++;
  28600. b = b<<14;
  28601. b |= *p;
  28602. /* b: p1<<14 | p3 (unmasked) */
  28603. if (!(b&0x80))
  28604. {
  28605. /* Values between 2097152 and 268435455 */
  28606. b &= (0x7f<<14)|(0x7f);
  28607. a &= (0x7f<<14)|(0x7f);
  28608. a = a<<7;
  28609. *v = a | b;
  28610. return 4;
  28611. }
  28612. p++;
  28613. a = a<<14;
  28614. a |= *p;
  28615. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  28616. if (!(a&0x80))
  28617. {
  28618. /* Values between 268435456 and 34359738367 */
  28619. a &= SLOT_4_2_0;
  28620. b &= SLOT_4_2_0;
  28621. b = b<<7;
  28622. *v = a | b;
  28623. return 5;
  28624. }
  28625. /* We can only reach this point when reading a corrupt database
  28626. ** file. In that case we are not in any hurry. Use the (relatively
  28627. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  28628. ** value. */
  28629. {
  28630. u64 v64;
  28631. u8 n;
  28632. p -= 4;
  28633. n = sqlite3GetVarint(p, &v64);
  28634. assert( n>5 && n<=9 );
  28635. *v = (u32)v64;
  28636. return n;
  28637. }
  28638. #endif
  28639. }
  28640. /*
  28641. ** Return the number of bytes that will be needed to store the given
  28642. ** 64-bit integer.
  28643. */
  28644. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  28645. int i;
  28646. for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
  28647. return i;
  28648. }
  28649. /*
  28650. ** Read or write a four-byte big-endian integer value.
  28651. */
  28652. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  28653. #if SQLITE_BYTEORDER==4321
  28654. u32 x;
  28655. memcpy(&x,p,4);
  28656. return x;
  28657. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  28658. u32 x;
  28659. memcpy(&x,p,4);
  28660. return __builtin_bswap32(x);
  28661. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  28662. u32 x;
  28663. memcpy(&x,p,4);
  28664. return _byteswap_ulong(x);
  28665. #else
  28666. testcase( p[0]&0x80 );
  28667. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  28668. #endif
  28669. }
  28670. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  28671. #if SQLITE_BYTEORDER==4321
  28672. memcpy(p,&v,4);
  28673. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  28674. u32 x = __builtin_bswap32(v);
  28675. memcpy(p,&x,4);
  28676. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  28677. u32 x = _byteswap_ulong(v);
  28678. memcpy(p,&x,4);
  28679. #else
  28680. p[0] = (u8)(v>>24);
  28681. p[1] = (u8)(v>>16);
  28682. p[2] = (u8)(v>>8);
  28683. p[3] = (u8)v;
  28684. #endif
  28685. }
  28686. /*
  28687. ** Translate a single byte of Hex into an integer.
  28688. ** This routine only works if h really is a valid hexadecimal
  28689. ** character: 0..9a..fA..F
  28690. */
  28691. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  28692. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  28693. #ifdef SQLITE_ASCII
  28694. h += 9*(1&(h>>6));
  28695. #endif
  28696. #ifdef SQLITE_EBCDIC
  28697. h += 9*(1&~(h>>4));
  28698. #endif
  28699. return (u8)(h & 0xf);
  28700. }
  28701. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  28702. /*
  28703. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  28704. ** value. Return a pointer to its binary value. Space to hold the
  28705. ** binary value has been obtained from malloc and must be freed by
  28706. ** the calling routine.
  28707. */
  28708. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  28709. char *zBlob;
  28710. int i;
  28711. zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  28712. n--;
  28713. if( zBlob ){
  28714. for(i=0; i<n; i+=2){
  28715. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  28716. }
  28717. zBlob[i/2] = 0;
  28718. }
  28719. return zBlob;
  28720. }
  28721. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  28722. /*
  28723. ** Log an error that is an API call on a connection pointer that should
  28724. ** not have been used. The "type" of connection pointer is given as the
  28725. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  28726. */
  28727. static void logBadConnection(const char *zType){
  28728. sqlite3_log(SQLITE_MISUSE,
  28729. "API call with %s database connection pointer",
  28730. zType
  28731. );
  28732. }
  28733. /*
  28734. ** Check to make sure we have a valid db pointer. This test is not
  28735. ** foolproof but it does provide some measure of protection against
  28736. ** misuse of the interface such as passing in db pointers that are
  28737. ** NULL or which have been previously closed. If this routine returns
  28738. ** 1 it means that the db pointer is valid and 0 if it should not be
  28739. ** dereferenced for any reason. The calling function should invoke
  28740. ** SQLITE_MISUSE immediately.
  28741. **
  28742. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  28743. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  28744. ** open properly and is not fit for general use but which can be
  28745. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  28746. */
  28747. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  28748. u32 magic;
  28749. if( db==0 ){
  28750. logBadConnection("NULL");
  28751. return 0;
  28752. }
  28753. magic = db->magic;
  28754. if( magic!=SQLITE_MAGIC_OPEN ){
  28755. if( sqlite3SafetyCheckSickOrOk(db) ){
  28756. testcase( sqlite3GlobalConfig.xLog!=0 );
  28757. logBadConnection("unopened");
  28758. }
  28759. return 0;
  28760. }else{
  28761. return 1;
  28762. }
  28763. }
  28764. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  28765. u32 magic;
  28766. magic = db->magic;
  28767. if( magic!=SQLITE_MAGIC_SICK &&
  28768. magic!=SQLITE_MAGIC_OPEN &&
  28769. magic!=SQLITE_MAGIC_BUSY ){
  28770. testcase( sqlite3GlobalConfig.xLog!=0 );
  28771. logBadConnection("invalid");
  28772. return 0;
  28773. }else{
  28774. return 1;
  28775. }
  28776. }
  28777. /*
  28778. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  28779. ** the other 64-bit signed integer at *pA and store the result in *pA.
  28780. ** Return 0 on success. Or if the operation would have resulted in an
  28781. ** overflow, leave *pA unchanged and return 1.
  28782. */
  28783. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  28784. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  28785. return __builtin_add_overflow(*pA, iB, pA);
  28786. #else
  28787. i64 iA = *pA;
  28788. testcase( iA==0 ); testcase( iA==1 );
  28789. testcase( iB==-1 ); testcase( iB==0 );
  28790. if( iB>=0 ){
  28791. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  28792. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  28793. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  28794. }else{
  28795. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  28796. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  28797. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  28798. }
  28799. *pA += iB;
  28800. return 0;
  28801. #endif
  28802. }
  28803. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  28804. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  28805. return __builtin_sub_overflow(*pA, iB, pA);
  28806. #else
  28807. testcase( iB==SMALLEST_INT64+1 );
  28808. if( iB==SMALLEST_INT64 ){
  28809. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  28810. if( (*pA)>=0 ) return 1;
  28811. *pA -= iB;
  28812. return 0;
  28813. }else{
  28814. return sqlite3AddInt64(pA, -iB);
  28815. }
  28816. #endif
  28817. }
  28818. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  28819. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  28820. return __builtin_mul_overflow(*pA, iB, pA);
  28821. #else
  28822. i64 iA = *pA;
  28823. if( iB>0 ){
  28824. if( iA>LARGEST_INT64/iB ) return 1;
  28825. if( iA<SMALLEST_INT64/iB ) return 1;
  28826. }else if( iB<0 ){
  28827. if( iA>0 ){
  28828. if( iB<SMALLEST_INT64/iA ) return 1;
  28829. }else if( iA<0 ){
  28830. if( iB==SMALLEST_INT64 ) return 1;
  28831. if( iA==SMALLEST_INT64 ) return 1;
  28832. if( -iA>LARGEST_INT64/-iB ) return 1;
  28833. }
  28834. }
  28835. *pA = iA*iB;
  28836. return 0;
  28837. #endif
  28838. }
  28839. /*
  28840. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  28841. ** if the integer has a value of -2147483648, return +2147483647
  28842. */
  28843. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  28844. if( x>=0 ) return x;
  28845. if( x==(int)0x80000000 ) return 0x7fffffff;
  28846. return -x;
  28847. }
  28848. #ifdef SQLITE_ENABLE_8_3_NAMES
  28849. /*
  28850. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  28851. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  28852. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  28853. ** three characters, then shorten the suffix on z[] to be the last three
  28854. ** characters of the original suffix.
  28855. **
  28856. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  28857. ** do the suffix shortening regardless of URI parameter.
  28858. **
  28859. ** Examples:
  28860. **
  28861. ** test.db-journal => test.nal
  28862. ** test.db-wal => test.wal
  28863. ** test.db-shm => test.shm
  28864. ** test.db-mj7f3319fa => test.9fa
  28865. */
  28866. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  28867. #if SQLITE_ENABLE_8_3_NAMES<2
  28868. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  28869. #endif
  28870. {
  28871. int i, sz;
  28872. sz = sqlite3Strlen30(z);
  28873. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  28874. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  28875. }
  28876. }
  28877. #endif
  28878. /*
  28879. ** Find (an approximate) sum of two LogEst values. This computation is
  28880. ** not a simple "+" operator because LogEst is stored as a logarithmic
  28881. ** value.
  28882. **
  28883. */
  28884. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  28885. static const unsigned char x[] = {
  28886. 10, 10, /* 0,1 */
  28887. 9, 9, /* 2,3 */
  28888. 8, 8, /* 4,5 */
  28889. 7, 7, 7, /* 6,7,8 */
  28890. 6, 6, 6, /* 9,10,11 */
  28891. 5, 5, 5, /* 12-14 */
  28892. 4, 4, 4, 4, /* 15-18 */
  28893. 3, 3, 3, 3, 3, 3, /* 19-24 */
  28894. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  28895. };
  28896. if( a>=b ){
  28897. if( a>b+49 ) return a;
  28898. if( a>b+31 ) return a+1;
  28899. return a+x[a-b];
  28900. }else{
  28901. if( b>a+49 ) return b;
  28902. if( b>a+31 ) return b+1;
  28903. return b+x[b-a];
  28904. }
  28905. }
  28906. /*
  28907. ** Convert an integer into a LogEst. In other words, compute an
  28908. ** approximation for 10*log2(x).
  28909. */
  28910. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  28911. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  28912. LogEst y = 40;
  28913. if( x<8 ){
  28914. if( x<2 ) return 0;
  28915. while( x<8 ){ y -= 10; x <<= 1; }
  28916. }else{
  28917. #if GCC_VERSION>=5004000
  28918. int i = 60 - __builtin_clzll(x);
  28919. y += i*10;
  28920. x >>= i;
  28921. #else
  28922. while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
  28923. while( x>15 ){ y += 10; x >>= 1; }
  28924. #endif
  28925. }
  28926. return a[x&7] + y - 10;
  28927. }
  28928. #ifndef SQLITE_OMIT_VIRTUALTABLE
  28929. /*
  28930. ** Convert a double into a LogEst
  28931. ** In other words, compute an approximation for 10*log2(x).
  28932. */
  28933. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  28934. u64 a;
  28935. LogEst e;
  28936. assert( sizeof(x)==8 && sizeof(a)==8 );
  28937. if( x<=1 ) return 0;
  28938. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  28939. memcpy(&a, &x, 8);
  28940. e = (a>>52) - 1022;
  28941. return e*10;
  28942. }
  28943. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  28944. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  28945. defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
  28946. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  28947. /*
  28948. ** Convert a LogEst into an integer.
  28949. **
  28950. ** Note that this routine is only used when one or more of various
  28951. ** non-standard compile-time options is enabled.
  28952. */
  28953. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  28954. u64 n;
  28955. n = x%10;
  28956. x /= 10;
  28957. if( n>=5 ) n -= 2;
  28958. else if( n>=1 ) n -= 1;
  28959. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  28960. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  28961. if( x>60 ) return (u64)LARGEST_INT64;
  28962. #else
  28963. /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
  28964. ** possible to this routine is 310, resulting in a maximum x of 31 */
  28965. assert( x<=60 );
  28966. #endif
  28967. return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
  28968. }
  28969. #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
  28970. /*
  28971. ** Add a new name/number pair to a VList. This might require that the
  28972. ** VList object be reallocated, so return the new VList. If an OOM
  28973. ** error occurs, the original VList returned and the
  28974. ** db->mallocFailed flag is set.
  28975. **
  28976. ** A VList is really just an array of integers. To destroy a VList,
  28977. ** simply pass it to sqlite3DbFree().
  28978. **
  28979. ** The first integer is the number of integers allocated for the whole
  28980. ** VList. The second integer is the number of integers actually used.
  28981. ** Each name/number pair is encoded by subsequent groups of 3 or more
  28982. ** integers.
  28983. **
  28984. ** Each name/number pair starts with two integers which are the numeric
  28985. ** value for the pair and the size of the name/number pair, respectively.
  28986. ** The text name overlays one or more following integers. The text name
  28987. ** is always zero-terminated.
  28988. **
  28989. ** Conceptually:
  28990. **
  28991. ** struct VList {
  28992. ** int nAlloc; // Number of allocated slots
  28993. ** int nUsed; // Number of used slots
  28994. ** struct VListEntry {
  28995. ** int iValue; // Value for this entry
  28996. ** int nSlot; // Slots used by this entry
  28997. ** // ... variable name goes here
  28998. ** } a[0];
  28999. ** }
  29000. **
  29001. ** During code generation, pointers to the variable names within the
  29002. ** VList are taken. When that happens, nAlloc is set to zero as an
  29003. ** indication that the VList may never again be enlarged, since the
  29004. ** accompanying realloc() would invalidate the pointers.
  29005. */
  29006. SQLITE_PRIVATE VList *sqlite3VListAdd(
  29007. sqlite3 *db, /* The database connection used for malloc() */
  29008. VList *pIn, /* The input VList. Might be NULL */
  29009. const char *zName, /* Name of symbol to add */
  29010. int nName, /* Bytes of text in zName */
  29011. int iVal /* Value to associate with zName */
  29012. ){
  29013. int nInt; /* number of sizeof(int) objects needed for zName */
  29014. char *z; /* Pointer to where zName will be stored */
  29015. int i; /* Index in pIn[] where zName is stored */
  29016. nInt = nName/4 + 3;
  29017. assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
  29018. if( pIn==0 || pIn[1]+nInt > pIn[0] ){
  29019. /* Enlarge the allocation */
  29020. int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt;
  29021. VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
  29022. if( pOut==0 ) return pIn;
  29023. if( pIn==0 ) pOut[1] = 2;
  29024. pIn = pOut;
  29025. pIn[0] = nAlloc;
  29026. }
  29027. i = pIn[1];
  29028. pIn[i] = iVal;
  29029. pIn[i+1] = nInt;
  29030. z = (char*)&pIn[i+2];
  29031. pIn[1] = i+nInt;
  29032. assert( pIn[1]<=pIn[0] );
  29033. memcpy(z, zName, nName);
  29034. z[nName] = 0;
  29035. return pIn;
  29036. }
  29037. /*
  29038. ** Return a pointer to the name of a variable in the given VList that
  29039. ** has the value iVal. Or return a NULL if there is no such variable in
  29040. ** the list
  29041. */
  29042. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
  29043. int i, mx;
  29044. if( pIn==0 ) return 0;
  29045. mx = pIn[1];
  29046. i = 2;
  29047. do{
  29048. if( pIn[i]==iVal ) return (char*)&pIn[i+2];
  29049. i += pIn[i+1];
  29050. }while( i<mx );
  29051. return 0;
  29052. }
  29053. /*
  29054. ** Return the number of the variable named zName, if it is in VList.
  29055. ** or return 0 if there is no such variable.
  29056. */
  29057. SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
  29058. int i, mx;
  29059. if( pIn==0 ) return 0;
  29060. mx = pIn[1];
  29061. i = 2;
  29062. do{
  29063. const char *z = (const char*)&pIn[i+2];
  29064. if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
  29065. i += pIn[i+1];
  29066. }while( i<mx );
  29067. return 0;
  29068. }
  29069. /************** End of util.c ************************************************/
  29070. /************** Begin file hash.c ********************************************/
  29071. /*
  29072. ** 2001 September 22
  29073. **
  29074. ** The author disclaims copyright to this source code. In place of
  29075. ** a legal notice, here is a blessing:
  29076. **
  29077. ** May you do good and not evil.
  29078. ** May you find forgiveness for yourself and forgive others.
  29079. ** May you share freely, never taking more than you give.
  29080. **
  29081. *************************************************************************
  29082. ** This is the implementation of generic hash-tables
  29083. ** used in SQLite.
  29084. */
  29085. /* #include "sqliteInt.h" */
  29086. /* #include <assert.h> */
  29087. /* Turn bulk memory into a hash table object by initializing the
  29088. ** fields of the Hash structure.
  29089. **
  29090. ** "pNew" is a pointer to the hash table that is to be initialized.
  29091. */
  29092. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  29093. assert( pNew!=0 );
  29094. pNew->first = 0;
  29095. pNew->count = 0;
  29096. pNew->htsize = 0;
  29097. pNew->ht = 0;
  29098. }
  29099. /* Remove all entries from a hash table. Reclaim all memory.
  29100. ** Call this routine to delete a hash table or to reset a hash table
  29101. ** to the empty state.
  29102. */
  29103. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  29104. HashElem *elem; /* For looping over all elements of the table */
  29105. assert( pH!=0 );
  29106. elem = pH->first;
  29107. pH->first = 0;
  29108. sqlite3_free(pH->ht);
  29109. pH->ht = 0;
  29110. pH->htsize = 0;
  29111. while( elem ){
  29112. HashElem *next_elem = elem->next;
  29113. sqlite3_free(elem);
  29114. elem = next_elem;
  29115. }
  29116. pH->count = 0;
  29117. }
  29118. /*
  29119. ** The hashing function.
  29120. */
  29121. static unsigned int strHash(const char *z){
  29122. unsigned int h = 0;
  29123. unsigned char c;
  29124. while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
  29125. /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
  29126. ** 0x9e3779b1 is 2654435761 which is the closest prime number to
  29127. ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
  29128. h += sqlite3UpperToLower[c];
  29129. h *= 0x9e3779b1;
  29130. }
  29131. return h;
  29132. }
  29133. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  29134. ** insert pNew into the pEntry hash bucket.
  29135. */
  29136. static void insertElement(
  29137. Hash *pH, /* The complete hash table */
  29138. struct _ht *pEntry, /* The entry into which pNew is inserted */
  29139. HashElem *pNew /* The element to be inserted */
  29140. ){
  29141. HashElem *pHead; /* First element already in pEntry */
  29142. if( pEntry ){
  29143. pHead = pEntry->count ? pEntry->chain : 0;
  29144. pEntry->count++;
  29145. pEntry->chain = pNew;
  29146. }else{
  29147. pHead = 0;
  29148. }
  29149. if( pHead ){
  29150. pNew->next = pHead;
  29151. pNew->prev = pHead->prev;
  29152. if( pHead->prev ){ pHead->prev->next = pNew; }
  29153. else { pH->first = pNew; }
  29154. pHead->prev = pNew;
  29155. }else{
  29156. pNew->next = pH->first;
  29157. if( pH->first ){ pH->first->prev = pNew; }
  29158. pNew->prev = 0;
  29159. pH->first = pNew;
  29160. }
  29161. }
  29162. /* Resize the hash table so that it cantains "new_size" buckets.
  29163. **
  29164. ** The hash table might fail to resize if sqlite3_malloc() fails or
  29165. ** if the new size is the same as the prior size.
  29166. ** Return TRUE if the resize occurs and false if not.
  29167. */
  29168. static int rehash(Hash *pH, unsigned int new_size){
  29169. struct _ht *new_ht; /* The new hash table */
  29170. HashElem *elem, *next_elem; /* For looping over existing elements */
  29171. #if SQLITE_MALLOC_SOFT_LIMIT>0
  29172. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  29173. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  29174. }
  29175. if( new_size==pH->htsize ) return 0;
  29176. #endif
  29177. /* The inability to allocates space for a larger hash table is
  29178. ** a performance hit but it is not a fatal error. So mark the
  29179. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  29180. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  29181. ** only zeroes the requested number of bytes whereas this module will
  29182. ** use the actual amount of space allocated for the hash table (which
  29183. ** may be larger than the requested amount).
  29184. */
  29185. sqlite3BeginBenignMalloc();
  29186. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  29187. sqlite3EndBenignMalloc();
  29188. if( new_ht==0 ) return 0;
  29189. sqlite3_free(pH->ht);
  29190. pH->ht = new_ht;
  29191. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  29192. memset(new_ht, 0, new_size*sizeof(struct _ht));
  29193. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  29194. unsigned int h = strHash(elem->pKey) % new_size;
  29195. next_elem = elem->next;
  29196. insertElement(pH, &new_ht[h], elem);
  29197. }
  29198. return 1;
  29199. }
  29200. /* This function (for internal use only) locates an element in an
  29201. ** hash table that matches the given key. If no element is found,
  29202. ** a pointer to a static null element with HashElem.data==0 is returned.
  29203. ** If pH is not NULL, then the hash for this key is written to *pH.
  29204. */
  29205. static HashElem *findElementWithHash(
  29206. const Hash *pH, /* The pH to be searched */
  29207. const char *pKey, /* The key we are searching for */
  29208. unsigned int *pHash /* Write the hash value here */
  29209. ){
  29210. HashElem *elem; /* Used to loop thru the element list */
  29211. int count; /* Number of elements left to test */
  29212. unsigned int h; /* The computed hash */
  29213. static HashElem nullElement = { 0, 0, 0, 0 };
  29214. if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
  29215. struct _ht *pEntry;
  29216. h = strHash(pKey) % pH->htsize;
  29217. pEntry = &pH->ht[h];
  29218. elem = pEntry->chain;
  29219. count = pEntry->count;
  29220. }else{
  29221. h = 0;
  29222. elem = pH->first;
  29223. count = pH->count;
  29224. }
  29225. if( pHash ) *pHash = h;
  29226. while( count-- ){
  29227. assert( elem!=0 );
  29228. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  29229. return elem;
  29230. }
  29231. elem = elem->next;
  29232. }
  29233. return &nullElement;
  29234. }
  29235. /* Remove a single entry from the hash table given a pointer to that
  29236. ** element and a hash on the element's key.
  29237. */
  29238. static void removeElementGivenHash(
  29239. Hash *pH, /* The pH containing "elem" */
  29240. HashElem* elem, /* The element to be removed from the pH */
  29241. unsigned int h /* Hash value for the element */
  29242. ){
  29243. struct _ht *pEntry;
  29244. if( elem->prev ){
  29245. elem->prev->next = elem->next;
  29246. }else{
  29247. pH->first = elem->next;
  29248. }
  29249. if( elem->next ){
  29250. elem->next->prev = elem->prev;
  29251. }
  29252. if( pH->ht ){
  29253. pEntry = &pH->ht[h];
  29254. if( pEntry->chain==elem ){
  29255. pEntry->chain = elem->next;
  29256. }
  29257. pEntry->count--;
  29258. assert( pEntry->count>=0 );
  29259. }
  29260. sqlite3_free( elem );
  29261. pH->count--;
  29262. if( pH->count==0 ){
  29263. assert( pH->first==0 );
  29264. assert( pH->count==0 );
  29265. sqlite3HashClear(pH);
  29266. }
  29267. }
  29268. /* Attempt to locate an element of the hash table pH with a key
  29269. ** that matches pKey. Return the data for this element if it is
  29270. ** found, or NULL if there is no match.
  29271. */
  29272. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  29273. assert( pH!=0 );
  29274. assert( pKey!=0 );
  29275. return findElementWithHash(pH, pKey, 0)->data;
  29276. }
  29277. /* Insert an element into the hash table pH. The key is pKey
  29278. ** and the data is "data".
  29279. **
  29280. ** If no element exists with a matching key, then a new
  29281. ** element is created and NULL is returned.
  29282. **
  29283. ** If another element already exists with the same key, then the
  29284. ** new data replaces the old data and the old data is returned.
  29285. ** The key is not copied in this instance. If a malloc fails, then
  29286. ** the new data is returned and the hash table is unchanged.
  29287. **
  29288. ** If the "data" parameter to this function is NULL, then the
  29289. ** element corresponding to "key" is removed from the hash table.
  29290. */
  29291. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  29292. unsigned int h; /* the hash of the key modulo hash table size */
  29293. HashElem *elem; /* Used to loop thru the element list */
  29294. HashElem *new_elem; /* New element added to the pH */
  29295. assert( pH!=0 );
  29296. assert( pKey!=0 );
  29297. elem = findElementWithHash(pH,pKey,&h);
  29298. if( elem->data ){
  29299. void *old_data = elem->data;
  29300. if( data==0 ){
  29301. removeElementGivenHash(pH,elem,h);
  29302. }else{
  29303. elem->data = data;
  29304. elem->pKey = pKey;
  29305. }
  29306. return old_data;
  29307. }
  29308. if( data==0 ) return 0;
  29309. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  29310. if( new_elem==0 ) return data;
  29311. new_elem->pKey = pKey;
  29312. new_elem->data = data;
  29313. pH->count++;
  29314. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  29315. if( rehash(pH, pH->count*2) ){
  29316. assert( pH->htsize>0 );
  29317. h = strHash(pKey) % pH->htsize;
  29318. }
  29319. }
  29320. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  29321. return 0;
  29322. }
  29323. /************** End of hash.c ************************************************/
  29324. /************** Begin file opcodes.c *****************************************/
  29325. /* Automatically generated. Do not edit */
  29326. /* See the tool/mkopcodec.tcl script for details. */
  29327. #if !defined(SQLITE_OMIT_EXPLAIN) \
  29328. || defined(VDBE_PROFILE) \
  29329. || defined(SQLITE_DEBUG)
  29330. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  29331. # define OpHelp(X) "\0" X
  29332. #else
  29333. # define OpHelp(X)
  29334. #endif
  29335. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  29336. static const char *const azName[] = {
  29337. /* 0 */ "Savepoint" OpHelp(""),
  29338. /* 1 */ "AutoCommit" OpHelp(""),
  29339. /* 2 */ "Transaction" OpHelp(""),
  29340. /* 3 */ "SorterNext" OpHelp(""),
  29341. /* 4 */ "PrevIfOpen" OpHelp(""),
  29342. /* 5 */ "NextIfOpen" OpHelp(""),
  29343. /* 6 */ "Prev" OpHelp(""),
  29344. /* 7 */ "Next" OpHelp(""),
  29345. /* 8 */ "Checkpoint" OpHelp(""),
  29346. /* 9 */ "JournalMode" OpHelp(""),
  29347. /* 10 */ "Vacuum" OpHelp(""),
  29348. /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  29349. /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  29350. /* 13 */ "Goto" OpHelp(""),
  29351. /* 14 */ "Gosub" OpHelp(""),
  29352. /* 15 */ "InitCoroutine" OpHelp(""),
  29353. /* 16 */ "Yield" OpHelp(""),
  29354. /* 17 */ "MustBeInt" OpHelp(""),
  29355. /* 18 */ "Jump" OpHelp(""),
  29356. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  29357. /* 20 */ "Once" OpHelp(""),
  29358. /* 21 */ "If" OpHelp(""),
  29359. /* 22 */ "IfNot" OpHelp(""),
  29360. /* 23 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
  29361. /* 24 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  29362. /* 25 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  29363. /* 26 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  29364. /* 27 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  29365. /* 28 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  29366. /* 29 */ "NotFound" OpHelp("key=r[P3@P4]"),
  29367. /* 30 */ "Found" OpHelp("key=r[P3@P4]"),
  29368. /* 31 */ "SeekRowid" OpHelp("intkey=r[P3]"),
  29369. /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
  29370. /* 33 */ "Last" OpHelp(""),
  29371. /* 34 */ "IfSmaller" OpHelp(""),
  29372. /* 35 */ "SorterSort" OpHelp(""),
  29373. /* 36 */ "Sort" OpHelp(""),
  29374. /* 37 */ "Rewind" OpHelp(""),
  29375. /* 38 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  29376. /* 39 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  29377. /* 40 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  29378. /* 41 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  29379. /* 42 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  29380. /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  29381. /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  29382. /* 45 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  29383. /* 46 */ "Program" OpHelp(""),
  29384. /* 47 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  29385. /* 48 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  29386. /* 49 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
  29387. /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  29388. /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  29389. /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
  29390. /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
  29391. /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
  29392. /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
  29393. /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
  29394. /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
  29395. /* 58 */ "ElseNotEq" OpHelp(""),
  29396. /* 59 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  29397. /* 60 */ "IncrVacuum" OpHelp(""),
  29398. /* 61 */ "VNext" OpHelp(""),
  29399. /* 62 */ "Init" OpHelp("Start at P2"),
  29400. /* 63 */ "Return" OpHelp(""),
  29401. /* 64 */ "EndCoroutine" OpHelp(""),
  29402. /* 65 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  29403. /* 66 */ "Halt" OpHelp(""),
  29404. /* 67 */ "Integer" OpHelp("r[P2]=P1"),
  29405. /* 68 */ "Int64" OpHelp("r[P2]=P4"),
  29406. /* 69 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  29407. /* 70 */ "Null" OpHelp("r[P2..P3]=NULL"),
  29408. /* 71 */ "SoftNull" OpHelp("r[P1]=NULL"),
  29409. /* 72 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  29410. /* 73 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  29411. /* 74 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  29412. /* 75 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  29413. /* 76 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  29414. /* 77 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  29415. /* 78 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  29416. /* 79 */ "CollSeq" OpHelp(""),
  29417. /* 80 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  29418. /* 81 */ "RealAffinity" OpHelp(""),
  29419. /* 82 */ "Cast" OpHelp("affinity(r[P1])"),
  29420. /* 83 */ "Permutation" OpHelp(""),
  29421. /* 84 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  29422. /* 85 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  29423. /* 86 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  29424. /* 87 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  29425. /* 88 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  29426. /* 89 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  29427. /* 90 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  29428. /* 91 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  29429. /* 92 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  29430. /* 93 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  29431. /* 94 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  29432. /* 95 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  29433. /* 96 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
  29434. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  29435. /* 98 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),
  29436. /* 99 */ "Column" OpHelp("r[P3]=PX"),
  29437. /* 100 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  29438. /* 101 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  29439. /* 102 */ "Count" OpHelp("r[P2]=count()"),
  29440. /* 103 */ "ReadCookie" OpHelp(""),
  29441. /* 104 */ "SetCookie" OpHelp(""),
  29442. /* 105 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  29443. /* 106 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  29444. /* 107 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  29445. /* 108 */ "OpenDup" OpHelp(""),
  29446. /* 109 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  29447. /* 110 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  29448. /* 111 */ "SorterOpen" OpHelp(""),
  29449. /* 112 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  29450. /* 113 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  29451. /* 114 */ "Close" OpHelp(""),
  29452. /* 115 */ "ColumnsUsed" OpHelp(""),
  29453. /* 116 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  29454. /* 117 */ "NewRowid" OpHelp("r[P2]=rowid"),
  29455. /* 118 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  29456. /* 119 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  29457. /* 120 */ "Delete" OpHelp(""),
  29458. /* 121 */ "ResetCount" OpHelp(""),
  29459. /* 122 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  29460. /* 123 */ "SorterData" OpHelp("r[P2]=data"),
  29461. /* 124 */ "RowData" OpHelp("r[P2]=data"),
  29462. /* 125 */ "Rowid" OpHelp("r[P2]=rowid"),
  29463. /* 126 */ "NullRow" OpHelp(""),
  29464. /* 127 */ "SeekEnd" OpHelp(""),
  29465. /* 128 */ "SorterInsert" OpHelp("key=r[P2]"),
  29466. /* 129 */ "IdxInsert" OpHelp("key=r[P2]"),
  29467. /* 130 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  29468. /* 131 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
  29469. /* 132 */ "Real" OpHelp("r[P2]=P4"),
  29470. /* 133 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  29471. /* 134 */ "Destroy" OpHelp(""),
  29472. /* 135 */ "Clear" OpHelp(""),
  29473. /* 136 */ "ResetSorter" OpHelp(""),
  29474. /* 137 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
  29475. /* 138 */ "SqlExec" OpHelp(""),
  29476. /* 139 */ "ParseSchema" OpHelp(""),
  29477. /* 140 */ "LoadAnalysis" OpHelp(""),
  29478. /* 141 */ "DropTable" OpHelp(""),
  29479. /* 142 */ "DropIndex" OpHelp(""),
  29480. /* 143 */ "DropTrigger" OpHelp(""),
  29481. /* 144 */ "IntegrityCk" OpHelp(""),
  29482. /* 145 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  29483. /* 146 */ "Param" OpHelp(""),
  29484. /* 147 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  29485. /* 148 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  29486. /* 149 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
  29487. /* 150 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
  29488. /* 151 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  29489. /* 152 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  29490. /* 153 */ "Expire" OpHelp(""),
  29491. /* 154 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  29492. /* 155 */ "VBegin" OpHelp(""),
  29493. /* 156 */ "VCreate" OpHelp(""),
  29494. /* 157 */ "VDestroy" OpHelp(""),
  29495. /* 158 */ "VOpen" OpHelp(""),
  29496. /* 159 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  29497. /* 160 */ "VRename" OpHelp(""),
  29498. /* 161 */ "Pagecount" OpHelp(""),
  29499. /* 162 */ "MaxPgcnt" OpHelp(""),
  29500. /* 163 */ "PureFunc0" OpHelp(""),
  29501. /* 164 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  29502. /* 165 */ "PureFunc" OpHelp(""),
  29503. /* 166 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  29504. /* 167 */ "Trace" OpHelp(""),
  29505. /* 168 */ "CursorHint" OpHelp(""),
  29506. /* 169 */ "Noop" OpHelp(""),
  29507. /* 170 */ "Explain" OpHelp(""),
  29508. };
  29509. return azName[i];
  29510. }
  29511. #endif
  29512. /************** End of opcodes.c *********************************************/
  29513. /************** Begin file os_unix.c *****************************************/
  29514. /*
  29515. ** 2004 May 22
  29516. **
  29517. ** The author disclaims copyright to this source code. In place of
  29518. ** a legal notice, here is a blessing:
  29519. **
  29520. ** May you do good and not evil.
  29521. ** May you find forgiveness for yourself and forgive others.
  29522. ** May you share freely, never taking more than you give.
  29523. **
  29524. ******************************************************************************
  29525. **
  29526. ** This file contains the VFS implementation for unix-like operating systems
  29527. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  29528. **
  29529. ** There are actually several different VFS implementations in this file.
  29530. ** The differences are in the way that file locking is done. The default
  29531. ** implementation uses Posix Advisory Locks. Alternative implementations
  29532. ** use flock(), dot-files, various proprietary locking schemas, or simply
  29533. ** skip locking all together.
  29534. **
  29535. ** This source file is organized into divisions where the logic for various
  29536. ** subfunctions is contained within the appropriate division. PLEASE
  29537. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  29538. ** in the correct division and should be clearly labeled.
  29539. **
  29540. ** The layout of divisions is as follows:
  29541. **
  29542. ** * General-purpose declarations and utility functions.
  29543. ** * Unique file ID logic used by VxWorks.
  29544. ** * Various locking primitive implementations (all except proxy locking):
  29545. ** + for Posix Advisory Locks
  29546. ** + for no-op locks
  29547. ** + for dot-file locks
  29548. ** + for flock() locking
  29549. ** + for named semaphore locks (VxWorks only)
  29550. ** + for AFP filesystem locks (MacOSX only)
  29551. ** * sqlite3_file methods not associated with locking.
  29552. ** * Definitions of sqlite3_io_methods objects for all locking
  29553. ** methods plus "finder" functions for each locking method.
  29554. ** * sqlite3_vfs method implementations.
  29555. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  29556. ** * Definitions of sqlite3_vfs objects for all locking methods
  29557. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  29558. */
  29559. /* #include "sqliteInt.h" */
  29560. #if SQLITE_OS_UNIX /* This file is used on unix only */
  29561. /*
  29562. ** There are various methods for file locking used for concurrency
  29563. ** control:
  29564. **
  29565. ** 1. POSIX locking (the default),
  29566. ** 2. No locking,
  29567. ** 3. Dot-file locking,
  29568. ** 4. flock() locking,
  29569. ** 5. AFP locking (OSX only),
  29570. ** 6. Named POSIX semaphores (VXWorks only),
  29571. ** 7. proxy locking. (OSX only)
  29572. **
  29573. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  29574. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  29575. ** selection of the appropriate locking style based on the filesystem
  29576. ** where the database is located.
  29577. */
  29578. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  29579. # if defined(__APPLE__)
  29580. # define SQLITE_ENABLE_LOCKING_STYLE 1
  29581. # else
  29582. # define SQLITE_ENABLE_LOCKING_STYLE 0
  29583. # endif
  29584. #endif
  29585. /* Use pread() and pwrite() if they are available */
  29586. #if defined(__APPLE__)
  29587. # define HAVE_PREAD 1
  29588. # define HAVE_PWRITE 1
  29589. #endif
  29590. #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
  29591. # undef USE_PREAD
  29592. # define USE_PREAD64 1
  29593. #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
  29594. # undef USE_PREAD64
  29595. # define USE_PREAD 1
  29596. #endif
  29597. /*
  29598. ** standard include files.
  29599. */
  29600. #include <sys/types.h>
  29601. #include <sys/stat.h>
  29602. #include <fcntl.h>
  29603. #include <sys/ioctl.h>
  29604. #include <unistd.h>
  29605. /* #include <time.h> */
  29606. #include <sys/time.h>
  29607. #include <errno.h>
  29608. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  29609. # include <sys/mman.h>
  29610. #endif
  29611. #if SQLITE_ENABLE_LOCKING_STYLE
  29612. /* # include <sys/ioctl.h> */
  29613. # include <sys/file.h>
  29614. # include <sys/param.h>
  29615. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  29616. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  29617. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  29618. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  29619. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  29620. # define HAVE_GETHOSTUUID 1
  29621. # else
  29622. # warning "gethostuuid() is disabled."
  29623. # endif
  29624. #endif
  29625. #if OS_VXWORKS
  29626. /* # include <sys/ioctl.h> */
  29627. # include <semaphore.h>
  29628. # include <limits.h>
  29629. #endif /* OS_VXWORKS */
  29630. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  29631. # include <sys/mount.h>
  29632. #endif
  29633. #ifdef HAVE_UTIME
  29634. # include <utime.h>
  29635. #endif
  29636. /*
  29637. ** Allowed values of unixFile.fsFlags
  29638. */
  29639. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  29640. /*
  29641. ** If we are to be thread-safe, include the pthreads header and define
  29642. ** the SQLITE_UNIX_THREADS macro.
  29643. */
  29644. #if SQLITE_THREADSAFE
  29645. /* # include <pthread.h> */
  29646. # define SQLITE_UNIX_THREADS 1
  29647. #endif
  29648. /*
  29649. ** Default permissions when creating a new file
  29650. */
  29651. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  29652. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  29653. #endif
  29654. /*
  29655. ** Default permissions when creating auto proxy dir
  29656. */
  29657. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  29658. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  29659. #endif
  29660. /*
  29661. ** Maximum supported path-length.
  29662. */
  29663. #define MAX_PATHNAME 512
  29664. /*
  29665. ** Maximum supported symbolic links
  29666. */
  29667. #define SQLITE_MAX_SYMLINKS 100
  29668. /* Always cast the getpid() return type for compatibility with
  29669. ** kernel modules in VxWorks. */
  29670. #define osGetpid(X) (pid_t)getpid()
  29671. /*
  29672. ** Only set the lastErrno if the error code is a real error and not
  29673. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  29674. */
  29675. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  29676. /* Forward references */
  29677. typedef struct unixShm unixShm; /* Connection shared memory */
  29678. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  29679. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  29680. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  29681. /*
  29682. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  29683. ** cannot be closed immediately. In these cases, instances of the following
  29684. ** structure are used to store the file descriptor while waiting for an
  29685. ** opportunity to either close or reuse it.
  29686. */
  29687. struct UnixUnusedFd {
  29688. int fd; /* File descriptor to close */
  29689. int flags; /* Flags this file descriptor was opened with */
  29690. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  29691. };
  29692. /*
  29693. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  29694. ** VFS implementations.
  29695. */
  29696. typedef struct unixFile unixFile;
  29697. struct unixFile {
  29698. sqlite3_io_methods const *pMethod; /* Always the first entry */
  29699. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  29700. unixInodeInfo *pInode; /* Info about locks on this inode */
  29701. int h; /* The file descriptor */
  29702. unsigned char eFileLock; /* The type of lock held on this fd */
  29703. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  29704. int lastErrno; /* The unix errno from last I/O error */
  29705. void *lockingContext; /* Locking style specific state */
  29706. UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
  29707. const char *zPath; /* Name of the file */
  29708. unixShm *pShm; /* Shared memory segment information */
  29709. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  29710. #if SQLITE_MAX_MMAP_SIZE>0
  29711. int nFetchOut; /* Number of outstanding xFetch refs */
  29712. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  29713. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  29714. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  29715. void *pMapRegion; /* Memory mapped region */
  29716. #endif
  29717. int sectorSize; /* Device sector size */
  29718. int deviceCharacteristics; /* Precomputed device characteristics */
  29719. #if SQLITE_ENABLE_LOCKING_STYLE
  29720. int openFlags; /* The flags specified at open() */
  29721. #endif
  29722. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  29723. unsigned fsFlags; /* cached details from statfs() */
  29724. #endif
  29725. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  29726. unsigned iBusyTimeout; /* Wait this many millisec on locks */
  29727. #endif
  29728. #if OS_VXWORKS
  29729. struct vxworksFileId *pId; /* Unique file ID */
  29730. #endif
  29731. #ifdef SQLITE_DEBUG
  29732. /* The next group of variables are used to track whether or not the
  29733. ** transaction counter in bytes 24-27 of database files are updated
  29734. ** whenever any part of the database changes. An assertion fault will
  29735. ** occur if a file is updated without also updating the transaction
  29736. ** counter. This test is made to avoid new problems similar to the
  29737. ** one described by ticket #3584.
  29738. */
  29739. unsigned char transCntrChng; /* True if the transaction counter changed */
  29740. unsigned char dbUpdate; /* True if any part of database file changed */
  29741. unsigned char inNormalWrite; /* True if in a normal write operation */
  29742. #endif
  29743. #ifdef SQLITE_TEST
  29744. /* In test mode, increase the size of this structure a bit so that
  29745. ** it is larger than the struct CrashFile defined in test6.c.
  29746. */
  29747. char aPadding[32];
  29748. #endif
  29749. };
  29750. /* This variable holds the process id (pid) from when the xRandomness()
  29751. ** method was called. If xOpen() is called from a different process id,
  29752. ** indicating that a fork() has occurred, the PRNG will be reset.
  29753. */
  29754. static pid_t randomnessPid = 0;
  29755. /*
  29756. ** Allowed values for the unixFile.ctrlFlags bitmask:
  29757. */
  29758. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  29759. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  29760. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  29761. #ifndef SQLITE_DISABLE_DIRSYNC
  29762. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  29763. #else
  29764. # define UNIXFILE_DIRSYNC 0x00
  29765. #endif
  29766. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  29767. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  29768. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  29769. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  29770. /*
  29771. ** Include code that is common to all os_*.c files
  29772. */
  29773. /************** Include os_common.h in the middle of os_unix.c ***************/
  29774. /************** Begin file os_common.h ***************************************/
  29775. /*
  29776. ** 2004 May 22
  29777. **
  29778. ** The author disclaims copyright to this source code. In place of
  29779. ** a legal notice, here is a blessing:
  29780. **
  29781. ** May you do good and not evil.
  29782. ** May you find forgiveness for yourself and forgive others.
  29783. ** May you share freely, never taking more than you give.
  29784. **
  29785. ******************************************************************************
  29786. **
  29787. ** This file contains macros and a little bit of code that is common to
  29788. ** all of the platform-specific files (os_*.c) and is #included into those
  29789. ** files.
  29790. **
  29791. ** This file should be #included by the os_*.c files only. It is not a
  29792. ** general purpose header file.
  29793. */
  29794. #ifndef _OS_COMMON_H_
  29795. #define _OS_COMMON_H_
  29796. /*
  29797. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  29798. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  29799. ** switch. The following code should catch this problem at compile-time.
  29800. */
  29801. #ifdef MEMORY_DEBUG
  29802. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  29803. #endif
  29804. /*
  29805. ** Macros for performance tracing. Normally turned off. Only works
  29806. ** on i486 hardware.
  29807. */
  29808. #ifdef SQLITE_PERFORMANCE_TRACE
  29809. /*
  29810. ** hwtime.h contains inline assembler code for implementing
  29811. ** high-performance timing routines.
  29812. */
  29813. /************** Include hwtime.h in the middle of os_common.h ****************/
  29814. /************** Begin file hwtime.h ******************************************/
  29815. /*
  29816. ** 2008 May 27
  29817. **
  29818. ** The author disclaims copyright to this source code. In place of
  29819. ** a legal notice, here is a blessing:
  29820. **
  29821. ** May you do good and not evil.
  29822. ** May you find forgiveness for yourself and forgive others.
  29823. ** May you share freely, never taking more than you give.
  29824. **
  29825. ******************************************************************************
  29826. **
  29827. ** This file contains inline asm code for retrieving "high-performance"
  29828. ** counters for x86 class CPUs.
  29829. */
  29830. #ifndef SQLITE_HWTIME_H
  29831. #define SQLITE_HWTIME_H
  29832. /*
  29833. ** The following routine only works on pentium-class (or newer) processors.
  29834. ** It uses the RDTSC opcode to read the cycle count value out of the
  29835. ** processor and returns that value. This can be used for high-res
  29836. ** profiling.
  29837. */
  29838. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  29839. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  29840. #if defined(__GNUC__)
  29841. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29842. unsigned int lo, hi;
  29843. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  29844. return (sqlite_uint64)hi << 32 | lo;
  29845. }
  29846. #elif defined(_MSC_VER)
  29847. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  29848. __asm {
  29849. rdtsc
  29850. ret ; return value at EDX:EAX
  29851. }
  29852. }
  29853. #endif
  29854. #elif (defined(__GNUC__) && defined(__x86_64__))
  29855. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29856. unsigned long val;
  29857. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  29858. return val;
  29859. }
  29860. #elif (defined(__GNUC__) && defined(__ppc__))
  29861. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29862. unsigned long long retval;
  29863. unsigned long junk;
  29864. __asm__ __volatile__ ("\n\
  29865. 1: mftbu %1\n\
  29866. mftb %L0\n\
  29867. mftbu %0\n\
  29868. cmpw %0,%1\n\
  29869. bne 1b"
  29870. : "=r" (retval), "=r" (junk));
  29871. return retval;
  29872. }
  29873. #else
  29874. #error Need implementation of sqlite3Hwtime() for your platform.
  29875. /*
  29876. ** To compile without implementing sqlite3Hwtime() for your platform,
  29877. ** you can remove the above #error and use the following
  29878. ** stub function. You will lose timing support for many
  29879. ** of the debugging and testing utilities, but it should at
  29880. ** least compile and run.
  29881. */
  29882. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  29883. #endif
  29884. #endif /* !defined(SQLITE_HWTIME_H) */
  29885. /************** End of hwtime.h **********************************************/
  29886. /************** Continuing where we left off in os_common.h ******************/
  29887. static sqlite_uint64 g_start;
  29888. static sqlite_uint64 g_elapsed;
  29889. #define TIMER_START g_start=sqlite3Hwtime()
  29890. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  29891. #define TIMER_ELAPSED g_elapsed
  29892. #else
  29893. #define TIMER_START
  29894. #define TIMER_END
  29895. #define TIMER_ELAPSED ((sqlite_uint64)0)
  29896. #endif
  29897. /*
  29898. ** If we compile with the SQLITE_TEST macro set, then the following block
  29899. ** of code will give us the ability to simulate a disk I/O error. This
  29900. ** is used for testing the I/O recovery logic.
  29901. */
  29902. #if defined(SQLITE_TEST)
  29903. SQLITE_API extern int sqlite3_io_error_hit;
  29904. SQLITE_API extern int sqlite3_io_error_hardhit;
  29905. SQLITE_API extern int sqlite3_io_error_pending;
  29906. SQLITE_API extern int sqlite3_io_error_persist;
  29907. SQLITE_API extern int sqlite3_io_error_benign;
  29908. SQLITE_API extern int sqlite3_diskfull_pending;
  29909. SQLITE_API extern int sqlite3_diskfull;
  29910. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  29911. #define SimulateIOError(CODE) \
  29912. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  29913. || sqlite3_io_error_pending-- == 1 ) \
  29914. { local_ioerr(); CODE; }
  29915. static void local_ioerr(){
  29916. IOTRACE(("IOERR\n"));
  29917. sqlite3_io_error_hit++;
  29918. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  29919. }
  29920. #define SimulateDiskfullError(CODE) \
  29921. if( sqlite3_diskfull_pending ){ \
  29922. if( sqlite3_diskfull_pending == 1 ){ \
  29923. local_ioerr(); \
  29924. sqlite3_diskfull = 1; \
  29925. sqlite3_io_error_hit = 1; \
  29926. CODE; \
  29927. }else{ \
  29928. sqlite3_diskfull_pending--; \
  29929. } \
  29930. }
  29931. #else
  29932. #define SimulateIOErrorBenign(X)
  29933. #define SimulateIOError(A)
  29934. #define SimulateDiskfullError(A)
  29935. #endif /* defined(SQLITE_TEST) */
  29936. /*
  29937. ** When testing, keep a count of the number of open files.
  29938. */
  29939. #if defined(SQLITE_TEST)
  29940. SQLITE_API extern int sqlite3_open_file_count;
  29941. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  29942. #else
  29943. #define OpenCounter(X)
  29944. #endif /* defined(SQLITE_TEST) */
  29945. #endif /* !defined(_OS_COMMON_H_) */
  29946. /************** End of os_common.h *******************************************/
  29947. /************** Continuing where we left off in os_unix.c ********************/
  29948. /*
  29949. ** Define various macros that are missing from some systems.
  29950. */
  29951. #ifndef O_LARGEFILE
  29952. # define O_LARGEFILE 0
  29953. #endif
  29954. #ifdef SQLITE_DISABLE_LFS
  29955. # undef O_LARGEFILE
  29956. # define O_LARGEFILE 0
  29957. #endif
  29958. #ifndef O_NOFOLLOW
  29959. # define O_NOFOLLOW 0
  29960. #endif
  29961. #ifndef O_BINARY
  29962. # define O_BINARY 0
  29963. #endif
  29964. /*
  29965. ** The threadid macro resolves to the thread-id or to 0. Used for
  29966. ** testing and debugging only.
  29967. */
  29968. #if SQLITE_THREADSAFE
  29969. #define threadid pthread_self()
  29970. #else
  29971. #define threadid 0
  29972. #endif
  29973. /*
  29974. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  29975. */
  29976. #if !defined(HAVE_MREMAP)
  29977. # if defined(__linux__) && defined(_GNU_SOURCE)
  29978. # define HAVE_MREMAP 1
  29979. # else
  29980. # define HAVE_MREMAP 0
  29981. # endif
  29982. #endif
  29983. /*
  29984. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  29985. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  29986. */
  29987. #ifdef __ANDROID__
  29988. # define lseek lseek64
  29989. #endif
  29990. #ifdef __linux__
  29991. /*
  29992. ** Linux-specific IOCTL magic numbers used for controlling F2FS
  29993. */
  29994. #define F2FS_IOCTL_MAGIC 0xf5
  29995. #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
  29996. #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
  29997. #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
  29998. #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
  29999. #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
  30000. #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
  30001. #endif /* __linux__ */
  30002. /*
  30003. ** Different Unix systems declare open() in different ways. Same use
  30004. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  30005. ** The difference is important when using a pointer to the function.
  30006. **
  30007. ** The safest way to deal with the problem is to always use this wrapper
  30008. ** which always has the same well-defined interface.
  30009. */
  30010. static int posixOpen(const char *zFile, int flags, int mode){
  30011. return open(zFile, flags, mode);
  30012. }
  30013. /* Forward reference */
  30014. static int openDirectory(const char*, int*);
  30015. static int unixGetpagesize(void);
  30016. /*
  30017. ** Many system calls are accessed through pointer-to-functions so that
  30018. ** they may be overridden at runtime to facilitate fault injection during
  30019. ** testing and sandboxing. The following array holds the names and pointers
  30020. ** to all overrideable system calls.
  30021. */
  30022. static struct unix_syscall {
  30023. const char *zName; /* Name of the system call */
  30024. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  30025. sqlite3_syscall_ptr pDefault; /* Default value */
  30026. } aSyscall[] = {
  30027. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  30028. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  30029. { "close", (sqlite3_syscall_ptr)close, 0 },
  30030. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  30031. { "access", (sqlite3_syscall_ptr)access, 0 },
  30032. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  30033. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  30034. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  30035. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  30036. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  30037. /*
  30038. ** The DJGPP compiler environment looks mostly like Unix, but it
  30039. ** lacks the fcntl() system call. So redefine fcntl() to be something
  30040. ** that always succeeds. This means that locking does not occur under
  30041. ** DJGPP. But it is DOS - what did you expect?
  30042. */
  30043. #ifdef __DJGPP__
  30044. { "fstat", 0, 0 },
  30045. #define osFstat(a,b,c) 0
  30046. #else
  30047. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  30048. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  30049. #endif
  30050. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  30051. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  30052. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  30053. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  30054. { "read", (sqlite3_syscall_ptr)read, 0 },
  30055. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  30056. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  30057. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  30058. #else
  30059. { "pread", (sqlite3_syscall_ptr)0, 0 },
  30060. #endif
  30061. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  30062. #if defined(USE_PREAD64)
  30063. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  30064. #else
  30065. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  30066. #endif
  30067. #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
  30068. { "write", (sqlite3_syscall_ptr)write, 0 },
  30069. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  30070. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  30071. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  30072. #else
  30073. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  30074. #endif
  30075. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  30076. aSyscall[12].pCurrent)
  30077. #if defined(USE_PREAD64)
  30078. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  30079. #else
  30080. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  30081. #endif
  30082. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
  30083. aSyscall[13].pCurrent)
  30084. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  30085. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  30086. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  30087. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  30088. #else
  30089. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  30090. #endif
  30091. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  30092. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  30093. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  30094. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  30095. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  30096. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  30097. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  30098. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  30099. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  30100. #if defined(HAVE_FCHOWN)
  30101. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  30102. #else
  30103. { "fchown", (sqlite3_syscall_ptr)0, 0 },
  30104. #endif
  30105. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  30106. #if defined(HAVE_FCHOWN)
  30107. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  30108. #else
  30109. { "geteuid", (sqlite3_syscall_ptr)0, 0 },
  30110. #endif
  30111. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  30112. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  30113. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  30114. #else
  30115. { "mmap", (sqlite3_syscall_ptr)0, 0 },
  30116. #endif
  30117. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  30118. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  30119. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  30120. #else
  30121. { "munmap", (sqlite3_syscall_ptr)0, 0 },
  30122. #endif
  30123. #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
  30124. #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  30125. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  30126. #else
  30127. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  30128. #endif
  30129. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  30130. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  30131. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  30132. #else
  30133. { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
  30134. #endif
  30135. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  30136. #if defined(HAVE_READLINK)
  30137. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  30138. #else
  30139. { "readlink", (sqlite3_syscall_ptr)0, 0 },
  30140. #endif
  30141. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  30142. #if defined(HAVE_LSTAT)
  30143. { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
  30144. #else
  30145. { "lstat", (sqlite3_syscall_ptr)0, 0 },
  30146. #endif
  30147. #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
  30148. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  30149. { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
  30150. #else
  30151. { "ioctl", (sqlite3_syscall_ptr)0, 0 },
  30152. #endif
  30153. #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
  30154. }; /* End of the overrideable system calls */
  30155. /*
  30156. ** On some systems, calls to fchown() will trigger a message in a security
  30157. ** log if they come from non-root processes. So avoid calling fchown() if
  30158. ** we are not running as root.
  30159. */
  30160. static int robustFchown(int fd, uid_t uid, gid_t gid){
  30161. #if defined(HAVE_FCHOWN)
  30162. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  30163. #else
  30164. return 0;
  30165. #endif
  30166. }
  30167. /*
  30168. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  30169. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  30170. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  30171. ** system call named zName.
  30172. */
  30173. static int unixSetSystemCall(
  30174. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  30175. const char *zName, /* Name of system call to override */
  30176. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  30177. ){
  30178. unsigned int i;
  30179. int rc = SQLITE_NOTFOUND;
  30180. UNUSED_PARAMETER(pNotUsed);
  30181. if( zName==0 ){
  30182. /* If no zName is given, restore all system calls to their default
  30183. ** settings and return NULL
  30184. */
  30185. rc = SQLITE_OK;
  30186. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30187. if( aSyscall[i].pDefault ){
  30188. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  30189. }
  30190. }
  30191. }else{
  30192. /* If zName is specified, operate on only the one system call
  30193. ** specified.
  30194. */
  30195. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30196. if( strcmp(zName, aSyscall[i].zName)==0 ){
  30197. if( aSyscall[i].pDefault==0 ){
  30198. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  30199. }
  30200. rc = SQLITE_OK;
  30201. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  30202. aSyscall[i].pCurrent = pNewFunc;
  30203. break;
  30204. }
  30205. }
  30206. }
  30207. return rc;
  30208. }
  30209. /*
  30210. ** Return the value of a system call. Return NULL if zName is not a
  30211. ** recognized system call name. NULL is also returned if the system call
  30212. ** is currently undefined.
  30213. */
  30214. static sqlite3_syscall_ptr unixGetSystemCall(
  30215. sqlite3_vfs *pNotUsed,
  30216. const char *zName
  30217. ){
  30218. unsigned int i;
  30219. UNUSED_PARAMETER(pNotUsed);
  30220. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30221. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  30222. }
  30223. return 0;
  30224. }
  30225. /*
  30226. ** Return the name of the first system call after zName. If zName==NULL
  30227. ** then return the name of the first system call. Return NULL if zName
  30228. ** is the last system call or if zName is not the name of a valid
  30229. ** system call.
  30230. */
  30231. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  30232. int i = -1;
  30233. UNUSED_PARAMETER(p);
  30234. if( zName ){
  30235. for(i=0; i<ArraySize(aSyscall)-1; i++){
  30236. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  30237. }
  30238. }
  30239. for(i++; i<ArraySize(aSyscall); i++){
  30240. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  30241. }
  30242. return 0;
  30243. }
  30244. /*
  30245. ** Do not accept any file descriptor less than this value, in order to avoid
  30246. ** opening database file using file descriptors that are commonly used for
  30247. ** standard input, output, and error.
  30248. */
  30249. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  30250. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  30251. #endif
  30252. /*
  30253. ** Invoke open(). Do so multiple times, until it either succeeds or
  30254. ** fails for some reason other than EINTR.
  30255. **
  30256. ** If the file creation mode "m" is 0 then set it to the default for
  30257. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  30258. ** 0644) as modified by the system umask. If m is not 0, then
  30259. ** make the file creation mode be exactly m ignoring the umask.
  30260. **
  30261. ** The m parameter will be non-zero only when creating -wal, -journal,
  30262. ** and -shm files. We want those files to have *exactly* the same
  30263. ** permissions as their original database, unadulterated by the umask.
  30264. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  30265. ** transaction crashes and leaves behind hot journals, then any
  30266. ** process that is able to write to the database will also be able to
  30267. ** recover the hot journals.
  30268. */
  30269. static int robust_open(const char *z, int f, mode_t m){
  30270. int fd;
  30271. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  30272. while(1){
  30273. #if defined(O_CLOEXEC)
  30274. fd = osOpen(z,f|O_CLOEXEC,m2);
  30275. #else
  30276. fd = osOpen(z,f,m2);
  30277. #endif
  30278. if( fd<0 ){
  30279. if( errno==EINTR ) continue;
  30280. break;
  30281. }
  30282. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  30283. osClose(fd);
  30284. sqlite3_log(SQLITE_WARNING,
  30285. "attempt to open \"%s\" as file descriptor %d", z, fd);
  30286. fd = -1;
  30287. if( osOpen("/dev/null", f, m)<0 ) break;
  30288. }
  30289. if( fd>=0 ){
  30290. if( m!=0 ){
  30291. struct stat statbuf;
  30292. if( osFstat(fd, &statbuf)==0
  30293. && statbuf.st_size==0
  30294. && (statbuf.st_mode&0777)!=m
  30295. ){
  30296. osFchmod(fd, m);
  30297. }
  30298. }
  30299. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  30300. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  30301. #endif
  30302. }
  30303. return fd;
  30304. }
  30305. /*
  30306. ** Helper functions to obtain and relinquish the global mutex. The
  30307. ** global mutex is used to protect the unixInodeInfo and
  30308. ** vxworksFileId objects used by this file, all of which may be
  30309. ** shared by multiple threads.
  30310. **
  30311. ** Function unixMutexHeld() is used to assert() that the global mutex
  30312. ** is held when required. This function is only used as part of assert()
  30313. ** statements. e.g.
  30314. **
  30315. ** unixEnterMutex()
  30316. ** assert( unixMutexHeld() );
  30317. ** unixEnterLeave()
  30318. */
  30319. static sqlite3_mutex *unixBigLock = 0;
  30320. static void unixEnterMutex(void){
  30321. sqlite3_mutex_enter(unixBigLock);
  30322. }
  30323. static void unixLeaveMutex(void){
  30324. sqlite3_mutex_leave(unixBigLock);
  30325. }
  30326. #ifdef SQLITE_DEBUG
  30327. static int unixMutexHeld(void) {
  30328. return sqlite3_mutex_held(unixBigLock);
  30329. }
  30330. #endif
  30331. #ifdef SQLITE_HAVE_OS_TRACE
  30332. /*
  30333. ** Helper function for printing out trace information from debugging
  30334. ** binaries. This returns the string representation of the supplied
  30335. ** integer lock-type.
  30336. */
  30337. static const char *azFileLock(int eFileLock){
  30338. switch( eFileLock ){
  30339. case NO_LOCK: return "NONE";
  30340. case SHARED_LOCK: return "SHARED";
  30341. case RESERVED_LOCK: return "RESERVED";
  30342. case PENDING_LOCK: return "PENDING";
  30343. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  30344. }
  30345. return "ERROR";
  30346. }
  30347. #endif
  30348. #ifdef SQLITE_LOCK_TRACE
  30349. /*
  30350. ** Print out information about all locking operations.
  30351. **
  30352. ** This routine is used for troubleshooting locks on multithreaded
  30353. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  30354. ** command-line option on the compiler. This code is normally
  30355. ** turned off.
  30356. */
  30357. static int lockTrace(int fd, int op, struct flock *p){
  30358. char *zOpName, *zType;
  30359. int s;
  30360. int savedErrno;
  30361. if( op==F_GETLK ){
  30362. zOpName = "GETLK";
  30363. }else if( op==F_SETLK ){
  30364. zOpName = "SETLK";
  30365. }else{
  30366. s = osFcntl(fd, op, p);
  30367. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  30368. return s;
  30369. }
  30370. if( p->l_type==F_RDLCK ){
  30371. zType = "RDLCK";
  30372. }else if( p->l_type==F_WRLCK ){
  30373. zType = "WRLCK";
  30374. }else if( p->l_type==F_UNLCK ){
  30375. zType = "UNLCK";
  30376. }else{
  30377. assert( 0 );
  30378. }
  30379. assert( p->l_whence==SEEK_SET );
  30380. s = osFcntl(fd, op, p);
  30381. savedErrno = errno;
  30382. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  30383. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  30384. (int)p->l_pid, s);
  30385. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  30386. struct flock l2;
  30387. l2 = *p;
  30388. osFcntl(fd, F_GETLK, &l2);
  30389. if( l2.l_type==F_RDLCK ){
  30390. zType = "RDLCK";
  30391. }else if( l2.l_type==F_WRLCK ){
  30392. zType = "WRLCK";
  30393. }else if( l2.l_type==F_UNLCK ){
  30394. zType = "UNLCK";
  30395. }else{
  30396. assert( 0 );
  30397. }
  30398. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  30399. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  30400. }
  30401. errno = savedErrno;
  30402. return s;
  30403. }
  30404. #undef osFcntl
  30405. #define osFcntl lockTrace
  30406. #endif /* SQLITE_LOCK_TRACE */
  30407. /*
  30408. ** Retry ftruncate() calls that fail due to EINTR
  30409. **
  30410. ** All calls to ftruncate() within this file should be made through
  30411. ** this wrapper. On the Android platform, bypassing the logic below
  30412. ** could lead to a corrupt database.
  30413. */
  30414. static int robust_ftruncate(int h, sqlite3_int64 sz){
  30415. int rc;
  30416. #ifdef __ANDROID__
  30417. /* On Android, ftruncate() always uses 32-bit offsets, even if
  30418. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  30419. ** truncate a file to any size larger than 2GiB. Silently ignore any
  30420. ** such attempts. */
  30421. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  30422. rc = SQLITE_OK;
  30423. }else
  30424. #endif
  30425. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  30426. return rc;
  30427. }
  30428. /*
  30429. ** This routine translates a standard POSIX errno code into something
  30430. ** useful to the clients of the sqlite3 functions. Specifically, it is
  30431. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  30432. ** and a variety of "please close the file descriptor NOW" errors into
  30433. ** SQLITE_IOERR
  30434. **
  30435. ** Errors during initialization of locks, or file system support for locks,
  30436. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  30437. */
  30438. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  30439. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  30440. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  30441. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  30442. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  30443. switch (posixError) {
  30444. case EACCES:
  30445. case EAGAIN:
  30446. case ETIMEDOUT:
  30447. case EBUSY:
  30448. case EINTR:
  30449. case ENOLCK:
  30450. /* random NFS retry error, unless during file system support
  30451. * introspection, in which it actually means what it says */
  30452. return SQLITE_BUSY;
  30453. case EPERM:
  30454. return SQLITE_PERM;
  30455. default:
  30456. return sqliteIOErr;
  30457. }
  30458. }
  30459. /******************************************************************************
  30460. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  30461. **
  30462. ** On most versions of unix, we can get a unique ID for a file by concatenating
  30463. ** the device number and the inode number. But this does not work on VxWorks.
  30464. ** On VxWorks, a unique file id must be based on the canonical filename.
  30465. **
  30466. ** A pointer to an instance of the following structure can be used as a
  30467. ** unique file ID in VxWorks. Each instance of this structure contains
  30468. ** a copy of the canonical filename. There is also a reference count.
  30469. ** The structure is reclaimed when the number of pointers to it drops to
  30470. ** zero.
  30471. **
  30472. ** There are never very many files open at one time and lookups are not
  30473. ** a performance-critical path, so it is sufficient to put these
  30474. ** structures on a linked list.
  30475. */
  30476. struct vxworksFileId {
  30477. struct vxworksFileId *pNext; /* Next in a list of them all */
  30478. int nRef; /* Number of references to this one */
  30479. int nName; /* Length of the zCanonicalName[] string */
  30480. char *zCanonicalName; /* Canonical filename */
  30481. };
  30482. #if OS_VXWORKS
  30483. /*
  30484. ** All unique filenames are held on a linked list headed by this
  30485. ** variable:
  30486. */
  30487. static struct vxworksFileId *vxworksFileList = 0;
  30488. /*
  30489. ** Simplify a filename into its canonical form
  30490. ** by making the following changes:
  30491. **
  30492. ** * removing any trailing and duplicate /
  30493. ** * convert /./ into just /
  30494. ** * convert /A/../ where A is any simple name into just /
  30495. **
  30496. ** Changes are made in-place. Return the new name length.
  30497. **
  30498. ** The original filename is in z[0..n-1]. Return the number of
  30499. ** characters in the simplified name.
  30500. */
  30501. static int vxworksSimplifyName(char *z, int n){
  30502. int i, j;
  30503. while( n>1 && z[n-1]=='/' ){ n--; }
  30504. for(i=j=0; i<n; i++){
  30505. if( z[i]=='/' ){
  30506. if( z[i+1]=='/' ) continue;
  30507. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  30508. i += 1;
  30509. continue;
  30510. }
  30511. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  30512. while( j>0 && z[j-1]!='/' ){ j--; }
  30513. if( j>0 ){ j--; }
  30514. i += 2;
  30515. continue;
  30516. }
  30517. }
  30518. z[j++] = z[i];
  30519. }
  30520. z[j] = 0;
  30521. return j;
  30522. }
  30523. /*
  30524. ** Find a unique file ID for the given absolute pathname. Return
  30525. ** a pointer to the vxworksFileId object. This pointer is the unique
  30526. ** file ID.
  30527. **
  30528. ** The nRef field of the vxworksFileId object is incremented before
  30529. ** the object is returned. A new vxworksFileId object is created
  30530. ** and added to the global list if necessary.
  30531. **
  30532. ** If a memory allocation error occurs, return NULL.
  30533. */
  30534. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  30535. struct vxworksFileId *pNew; /* search key and new file ID */
  30536. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  30537. int n; /* Length of zAbsoluteName string */
  30538. assert( zAbsoluteName[0]=='/' );
  30539. n = (int)strlen(zAbsoluteName);
  30540. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  30541. if( pNew==0 ) return 0;
  30542. pNew->zCanonicalName = (char*)&pNew[1];
  30543. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  30544. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  30545. /* Search for an existing entry that matching the canonical name.
  30546. ** If found, increment the reference count and return a pointer to
  30547. ** the existing file ID.
  30548. */
  30549. unixEnterMutex();
  30550. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  30551. if( pCandidate->nName==n
  30552. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  30553. ){
  30554. sqlite3_free(pNew);
  30555. pCandidate->nRef++;
  30556. unixLeaveMutex();
  30557. return pCandidate;
  30558. }
  30559. }
  30560. /* No match was found. We will make a new file ID */
  30561. pNew->nRef = 1;
  30562. pNew->nName = n;
  30563. pNew->pNext = vxworksFileList;
  30564. vxworksFileList = pNew;
  30565. unixLeaveMutex();
  30566. return pNew;
  30567. }
  30568. /*
  30569. ** Decrement the reference count on a vxworksFileId object. Free
  30570. ** the object when the reference count reaches zero.
  30571. */
  30572. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  30573. unixEnterMutex();
  30574. assert( pId->nRef>0 );
  30575. pId->nRef--;
  30576. if( pId->nRef==0 ){
  30577. struct vxworksFileId **pp;
  30578. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  30579. assert( *pp==pId );
  30580. *pp = pId->pNext;
  30581. sqlite3_free(pId);
  30582. }
  30583. unixLeaveMutex();
  30584. }
  30585. #endif /* OS_VXWORKS */
  30586. /*************** End of Unique File ID Utility Used By VxWorks ****************
  30587. ******************************************************************************/
  30588. /******************************************************************************
  30589. *************************** Posix Advisory Locking ****************************
  30590. **
  30591. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  30592. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  30593. ** sets or clears a lock, that operation overrides any prior locks set
  30594. ** by the same process. It does not explicitly say so, but this implies
  30595. ** that it overrides locks set by the same process using a different
  30596. ** file descriptor. Consider this test case:
  30597. **
  30598. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  30599. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  30600. **
  30601. ** Suppose ./file1 and ./file2 are really the same file (because
  30602. ** one is a hard or symbolic link to the other) then if you set
  30603. ** an exclusive lock on fd1, then try to get an exclusive lock
  30604. ** on fd2, it works. I would have expected the second lock to
  30605. ** fail since there was already a lock on the file due to fd1.
  30606. ** But not so. Since both locks came from the same process, the
  30607. ** second overrides the first, even though they were on different
  30608. ** file descriptors opened on different file names.
  30609. **
  30610. ** This means that we cannot use POSIX locks to synchronize file access
  30611. ** among competing threads of the same process. POSIX locks will work fine
  30612. ** to synchronize access for threads in separate processes, but not
  30613. ** threads within the same process.
  30614. **
  30615. ** To work around the problem, SQLite has to manage file locks internally
  30616. ** on its own. Whenever a new database is opened, we have to find the
  30617. ** specific inode of the database file (the inode is determined by the
  30618. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  30619. ** and check for locks already existing on that inode. When locks are
  30620. ** created or removed, we have to look at our own internal record of the
  30621. ** locks to see if another thread has previously set a lock on that same
  30622. ** inode.
  30623. **
  30624. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  30625. ** For VxWorks, we have to use the alternative unique ID system based on
  30626. ** canonical filename and implemented in the previous division.)
  30627. **
  30628. ** The sqlite3_file structure for POSIX is no longer just an integer file
  30629. ** descriptor. It is now a structure that holds the integer file
  30630. ** descriptor and a pointer to a structure that describes the internal
  30631. ** locks on the corresponding inode. There is one locking structure
  30632. ** per inode, so if the same inode is opened twice, both unixFile structures
  30633. ** point to the same locking structure. The locking structure keeps
  30634. ** a reference count (so we will know when to delete it) and a "cnt"
  30635. ** field that tells us its internal lock status. cnt==0 means the
  30636. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  30637. ** cnt>0 means there are cnt shared locks on the file.
  30638. **
  30639. ** Any attempt to lock or unlock a file first checks the locking
  30640. ** structure. The fcntl() system call is only invoked to set a
  30641. ** POSIX lock if the internal lock structure transitions between
  30642. ** a locked and an unlocked state.
  30643. **
  30644. ** But wait: there are yet more problems with POSIX advisory locks.
  30645. **
  30646. ** If you close a file descriptor that points to a file that has locks,
  30647. ** all locks on that file that are owned by the current process are
  30648. ** released. To work around this problem, each unixInodeInfo object
  30649. ** maintains a count of the number of pending locks on tha inode.
  30650. ** When an attempt is made to close an unixFile, if there are
  30651. ** other unixFile open on the same inode that are holding locks, the call
  30652. ** to close() the file descriptor is deferred until all of the locks clear.
  30653. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  30654. ** be closed and that list is walked (and cleared) when the last lock
  30655. ** clears.
  30656. **
  30657. ** Yet another problem: LinuxThreads do not play well with posix locks.
  30658. **
  30659. ** Many older versions of linux use the LinuxThreads library which is
  30660. ** not posix compliant. Under LinuxThreads, a lock created by thread
  30661. ** A cannot be modified or overridden by a different thread B.
  30662. ** Only thread A can modify the lock. Locking behavior is correct
  30663. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  30664. ** on linux - with NPTL a lock created by thread A can override locks
  30665. ** in thread B. But there is no way to know at compile-time which
  30666. ** threading library is being used. So there is no way to know at
  30667. ** compile-time whether or not thread A can override locks on thread B.
  30668. ** One has to do a run-time check to discover the behavior of the
  30669. ** current process.
  30670. **
  30671. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  30672. ** was dropped beginning with version 3.7.0. SQLite will still work with
  30673. ** LinuxThreads provided that (1) there is no more than one connection
  30674. ** per database file in the same process and (2) database connections
  30675. ** do not move across threads.
  30676. */
  30677. /*
  30678. ** An instance of the following structure serves as the key used
  30679. ** to locate a particular unixInodeInfo object.
  30680. */
  30681. struct unixFileId {
  30682. dev_t dev; /* Device number */
  30683. #if OS_VXWORKS
  30684. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  30685. #else
  30686. /* We are told that some versions of Android contain a bug that
  30687. ** sizes ino_t at only 32-bits instead of 64-bits. (See
  30688. ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
  30689. ** To work around this, always allocate 64-bits for the inode number.
  30690. ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
  30691. ** but that should not be a big deal. */
  30692. /* WAS: ino_t ino; */
  30693. u64 ino; /* Inode number */
  30694. #endif
  30695. };
  30696. /*
  30697. ** An instance of the following structure is allocated for each open
  30698. ** inode. Or, on LinuxThreads, there is one of these structures for
  30699. ** each inode opened by each thread.
  30700. **
  30701. ** A single inode can have multiple file descriptors, so each unixFile
  30702. ** structure contains a pointer to an instance of this object and this
  30703. ** object keeps a count of the number of unixFile pointing to it.
  30704. */
  30705. struct unixInodeInfo {
  30706. struct unixFileId fileId; /* The lookup key */
  30707. int nShared; /* Number of SHARED locks held */
  30708. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  30709. unsigned char bProcessLock; /* An exclusive process lock is held */
  30710. int nRef; /* Number of pointers to this structure */
  30711. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  30712. int nLock; /* Number of outstanding file locks */
  30713. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  30714. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  30715. unixInodeInfo *pPrev; /* .... doubly linked */
  30716. #if SQLITE_ENABLE_LOCKING_STYLE
  30717. unsigned long long sharedByte; /* for AFP simulated shared lock */
  30718. #endif
  30719. #if OS_VXWORKS
  30720. sem_t *pSem; /* Named POSIX semaphore */
  30721. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  30722. #endif
  30723. };
  30724. /*
  30725. ** A lists of all unixInodeInfo objects.
  30726. */
  30727. static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
  30728. static unsigned int nUnusedFd = 0; /* Total unused file descriptors */
  30729. /*
  30730. **
  30731. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  30732. ** unixLogError().
  30733. **
  30734. ** It is invoked after an error occurs in an OS function and errno has been
  30735. ** set. It logs a message using sqlite3_log() containing the current value of
  30736. ** errno and, if possible, the human-readable equivalent from strerror() or
  30737. ** strerror_r().
  30738. **
  30739. ** The first argument passed to the macro should be the error code that
  30740. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  30741. ** The two subsequent arguments should be the name of the OS function that
  30742. ** failed (e.g. "unlink", "open") and the associated file-system path,
  30743. ** if any.
  30744. */
  30745. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  30746. static int unixLogErrorAtLine(
  30747. int errcode, /* SQLite error code */
  30748. const char *zFunc, /* Name of OS function that failed */
  30749. const char *zPath, /* File path associated with error */
  30750. int iLine /* Source line number where error occurred */
  30751. ){
  30752. char *zErr; /* Message from strerror() or equivalent */
  30753. int iErrno = errno; /* Saved syscall error number */
  30754. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  30755. ** the strerror() function to obtain the human-readable error message
  30756. ** equivalent to errno. Otherwise, use strerror_r().
  30757. */
  30758. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  30759. char aErr[80];
  30760. memset(aErr, 0, sizeof(aErr));
  30761. zErr = aErr;
  30762. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  30763. ** assume that the system provides the GNU version of strerror_r() that
  30764. ** returns a pointer to a buffer containing the error message. That pointer
  30765. ** may point to aErr[], or it may point to some static storage somewhere.
  30766. ** Otherwise, assume that the system provides the POSIX version of
  30767. ** strerror_r(), which always writes an error message into aErr[].
  30768. **
  30769. ** If the code incorrectly assumes that it is the POSIX version that is
  30770. ** available, the error message will often be an empty string. Not a
  30771. ** huge problem. Incorrectly concluding that the GNU version is available
  30772. ** could lead to a segfault though.
  30773. */
  30774. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  30775. zErr =
  30776. # endif
  30777. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  30778. #elif SQLITE_THREADSAFE
  30779. /* This is a threadsafe build, but strerror_r() is not available. */
  30780. zErr = "";
  30781. #else
  30782. /* Non-threadsafe build, use strerror(). */
  30783. zErr = strerror(iErrno);
  30784. #endif
  30785. if( zPath==0 ) zPath = "";
  30786. sqlite3_log(errcode,
  30787. "os_unix.c:%d: (%d) %s(%s) - %s",
  30788. iLine, iErrno, zFunc, zPath, zErr
  30789. );
  30790. return errcode;
  30791. }
  30792. /*
  30793. ** Close a file descriptor.
  30794. **
  30795. ** We assume that close() almost always works, since it is only in a
  30796. ** very sick application or on a very sick platform that it might fail.
  30797. ** If it does fail, simply leak the file descriptor, but do log the
  30798. ** error.
  30799. **
  30800. ** Note that it is not safe to retry close() after EINTR since the
  30801. ** file descriptor might have already been reused by another thread.
  30802. ** So we don't even try to recover from an EINTR. Just log the error
  30803. ** and move on.
  30804. */
  30805. static void robust_close(unixFile *pFile, int h, int lineno){
  30806. if( osClose(h) ){
  30807. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  30808. pFile ? pFile->zPath : 0, lineno);
  30809. }
  30810. }
  30811. /*
  30812. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  30813. ** a convenient place to set a breakpoint.
  30814. */
  30815. static void storeLastErrno(unixFile *pFile, int error){
  30816. pFile->lastErrno = error;
  30817. }
  30818. /*
  30819. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  30820. */
  30821. static void closePendingFds(unixFile *pFile){
  30822. unixInodeInfo *pInode = pFile->pInode;
  30823. UnixUnusedFd *p;
  30824. UnixUnusedFd *pNext;
  30825. for(p=pInode->pUnused; p; p=pNext){
  30826. pNext = p->pNext;
  30827. robust_close(pFile, p->fd, __LINE__);
  30828. sqlite3_free(p);
  30829. nUnusedFd--;
  30830. }
  30831. pInode->pUnused = 0;
  30832. }
  30833. /*
  30834. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  30835. **
  30836. ** The mutex entered using the unixEnterMutex() function must be held
  30837. ** when this function is called.
  30838. */
  30839. static void releaseInodeInfo(unixFile *pFile){
  30840. unixInodeInfo *pInode = pFile->pInode;
  30841. assert( unixMutexHeld() );
  30842. if( ALWAYS(pInode) ){
  30843. pInode->nRef--;
  30844. if( pInode->nRef==0 ){
  30845. assert( pInode->pShmNode==0 );
  30846. closePendingFds(pFile);
  30847. if( pInode->pPrev ){
  30848. assert( pInode->pPrev->pNext==pInode );
  30849. pInode->pPrev->pNext = pInode->pNext;
  30850. }else{
  30851. assert( inodeList==pInode );
  30852. inodeList = pInode->pNext;
  30853. }
  30854. if( pInode->pNext ){
  30855. assert( pInode->pNext->pPrev==pInode );
  30856. pInode->pNext->pPrev = pInode->pPrev;
  30857. }
  30858. sqlite3_free(pInode);
  30859. }
  30860. }
  30861. assert( inodeList!=0 || nUnusedFd==0 );
  30862. }
  30863. /*
  30864. ** Given a file descriptor, locate the unixInodeInfo object that
  30865. ** describes that file descriptor. Create a new one if necessary. The
  30866. ** return value might be uninitialized if an error occurs.
  30867. **
  30868. ** The mutex entered using the unixEnterMutex() function must be held
  30869. ** when this function is called.
  30870. **
  30871. ** Return an appropriate error code.
  30872. */
  30873. static int findInodeInfo(
  30874. unixFile *pFile, /* Unix file with file desc used in the key */
  30875. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  30876. ){
  30877. int rc; /* System call return code */
  30878. int fd; /* The file descriptor for pFile */
  30879. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  30880. struct stat statbuf; /* Low-level file information */
  30881. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  30882. assert( unixMutexHeld() );
  30883. /* Get low-level information about the file that we can used to
  30884. ** create a unique name for the file.
  30885. */
  30886. fd = pFile->h;
  30887. rc = osFstat(fd, &statbuf);
  30888. if( rc!=0 ){
  30889. storeLastErrno(pFile, errno);
  30890. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  30891. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  30892. #endif
  30893. return SQLITE_IOERR;
  30894. }
  30895. #ifdef __APPLE__
  30896. /* On OS X on an msdos filesystem, the inode number is reported
  30897. ** incorrectly for zero-size files. See ticket #3260. To work
  30898. ** around this problem (we consider it a bug in OS X, not SQLite)
  30899. ** we always increase the file size to 1 by writing a single byte
  30900. ** prior to accessing the inode number. The one byte written is
  30901. ** an ASCII 'S' character which also happens to be the first byte
  30902. ** in the header of every SQLite database. In this way, if there
  30903. ** is a race condition such that another thread has already populated
  30904. ** the first page of the database, no damage is done.
  30905. */
  30906. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  30907. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  30908. if( rc!=1 ){
  30909. storeLastErrno(pFile, errno);
  30910. return SQLITE_IOERR;
  30911. }
  30912. rc = osFstat(fd, &statbuf);
  30913. if( rc!=0 ){
  30914. storeLastErrno(pFile, errno);
  30915. return SQLITE_IOERR;
  30916. }
  30917. }
  30918. #endif
  30919. memset(&fileId, 0, sizeof(fileId));
  30920. fileId.dev = statbuf.st_dev;
  30921. #if OS_VXWORKS
  30922. fileId.pId = pFile->pId;
  30923. #else
  30924. fileId.ino = (u64)statbuf.st_ino;
  30925. #endif
  30926. assert( inodeList!=0 || nUnusedFd==0 );
  30927. pInode = inodeList;
  30928. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  30929. pInode = pInode->pNext;
  30930. }
  30931. if( pInode==0 ){
  30932. pInode = sqlite3_malloc64( sizeof(*pInode) );
  30933. if( pInode==0 ){
  30934. return SQLITE_NOMEM_BKPT;
  30935. }
  30936. memset(pInode, 0, sizeof(*pInode));
  30937. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  30938. pInode->nRef = 1;
  30939. pInode->pNext = inodeList;
  30940. pInode->pPrev = 0;
  30941. if( inodeList ) inodeList->pPrev = pInode;
  30942. inodeList = pInode;
  30943. }else{
  30944. pInode->nRef++;
  30945. }
  30946. *ppInode = pInode;
  30947. return SQLITE_OK;
  30948. }
  30949. /*
  30950. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  30951. */
  30952. static int fileHasMoved(unixFile *pFile){
  30953. #if OS_VXWORKS
  30954. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  30955. #else
  30956. struct stat buf;
  30957. return pFile->pInode!=0 &&
  30958. (osStat(pFile->zPath, &buf)!=0
  30959. || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
  30960. #endif
  30961. }
  30962. /*
  30963. ** Check a unixFile that is a database. Verify the following:
  30964. **
  30965. ** (1) There is exactly one hard link on the file
  30966. ** (2) The file is not a symbolic link
  30967. ** (3) The file has not been renamed or unlinked
  30968. **
  30969. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  30970. */
  30971. static void verifyDbFile(unixFile *pFile){
  30972. struct stat buf;
  30973. int rc;
  30974. /* These verifications occurs for the main database only */
  30975. if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
  30976. rc = osFstat(pFile->h, &buf);
  30977. if( rc!=0 ){
  30978. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  30979. return;
  30980. }
  30981. if( buf.st_nlink==0 ){
  30982. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  30983. return;
  30984. }
  30985. if( buf.st_nlink>1 ){
  30986. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  30987. return;
  30988. }
  30989. if( fileHasMoved(pFile) ){
  30990. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  30991. return;
  30992. }
  30993. }
  30994. /*
  30995. ** This routine checks if there is a RESERVED lock held on the specified
  30996. ** file by this or any other process. If such a lock is held, set *pResOut
  30997. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30998. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30999. */
  31000. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  31001. int rc = SQLITE_OK;
  31002. int reserved = 0;
  31003. unixFile *pFile = (unixFile*)id;
  31004. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  31005. assert( pFile );
  31006. assert( pFile->eFileLock<=SHARED_LOCK );
  31007. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  31008. /* Check if a thread in this process holds such a lock */
  31009. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  31010. reserved = 1;
  31011. }
  31012. /* Otherwise see if some other process holds it.
  31013. */
  31014. #ifndef __DJGPP__
  31015. if( !reserved && !pFile->pInode->bProcessLock ){
  31016. struct flock lock;
  31017. lock.l_whence = SEEK_SET;
  31018. lock.l_start = RESERVED_BYTE;
  31019. lock.l_len = 1;
  31020. lock.l_type = F_WRLCK;
  31021. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  31022. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  31023. storeLastErrno(pFile, errno);
  31024. } else if( lock.l_type!=F_UNLCK ){
  31025. reserved = 1;
  31026. }
  31027. }
  31028. #endif
  31029. unixLeaveMutex();
  31030. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  31031. *pResOut = reserved;
  31032. return rc;
  31033. }
  31034. /*
  31035. ** Set a posix-advisory-lock.
  31036. **
  31037. ** There are two versions of this routine. If compiled with
  31038. ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
  31039. ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
  31040. ** value is set, then it is the number of milliseconds to wait before
  31041. ** failing the lock. The iBusyTimeout value is always reset back to
  31042. ** zero on each call.
  31043. **
  31044. ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
  31045. ** attempt to set the lock.
  31046. */
  31047. #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
  31048. # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
  31049. #else
  31050. static int osSetPosixAdvisoryLock(
  31051. int h, /* The file descriptor on which to take the lock */
  31052. struct flock *pLock, /* The description of the lock */
  31053. unixFile *pFile /* Structure holding timeout value */
  31054. ){
  31055. int rc = osFcntl(h,F_SETLK,pLock);
  31056. while( rc<0 && pFile->iBusyTimeout>0 ){
  31057. /* On systems that support some kind of blocking file lock with a timeout,
  31058. ** make appropriate changes here to invoke that blocking file lock. On
  31059. ** generic posix, however, there is no such API. So we simply try the
  31060. ** lock once every millisecond until either the timeout expires, or until
  31061. ** the lock is obtained. */
  31062. usleep(1000);
  31063. rc = osFcntl(h,F_SETLK,pLock);
  31064. pFile->iBusyTimeout--;
  31065. }
  31066. return rc;
  31067. }
  31068. #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
  31069. /*
  31070. ** Attempt to set a system-lock on the file pFile. The lock is
  31071. ** described by pLock.
  31072. **
  31073. ** If the pFile was opened read/write from unix-excl, then the only lock
  31074. ** ever obtained is an exclusive lock, and it is obtained exactly once
  31075. ** the first time any lock is attempted. All subsequent system locking
  31076. ** operations become no-ops. Locking operations still happen internally,
  31077. ** in order to coordinate access between separate database connections
  31078. ** within this process, but all of that is handled in memory and the
  31079. ** operating system does not participate.
  31080. **
  31081. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  31082. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  31083. ** and is read-only.
  31084. **
  31085. ** Zero is returned if the call completes successfully, or -1 if a call
  31086. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  31087. */
  31088. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  31089. int rc;
  31090. unixInodeInfo *pInode = pFile->pInode;
  31091. assert( unixMutexHeld() );
  31092. assert( pInode!=0 );
  31093. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  31094. if( pInode->bProcessLock==0 ){
  31095. struct flock lock;
  31096. assert( pInode->nLock==0 );
  31097. lock.l_whence = SEEK_SET;
  31098. lock.l_start = SHARED_FIRST;
  31099. lock.l_len = SHARED_SIZE;
  31100. lock.l_type = F_WRLCK;
  31101. rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
  31102. if( rc<0 ) return rc;
  31103. pInode->bProcessLock = 1;
  31104. pInode->nLock++;
  31105. }else{
  31106. rc = 0;
  31107. }
  31108. }else{
  31109. rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
  31110. }
  31111. return rc;
  31112. }
  31113. /*
  31114. ** Lock the file with the lock specified by parameter eFileLock - one
  31115. ** of the following:
  31116. **
  31117. ** (1) SHARED_LOCK
  31118. ** (2) RESERVED_LOCK
  31119. ** (3) PENDING_LOCK
  31120. ** (4) EXCLUSIVE_LOCK
  31121. **
  31122. ** Sometimes when requesting one lock state, additional lock states
  31123. ** are inserted in between. The locking might fail on one of the later
  31124. ** transitions leaving the lock state different from what it started but
  31125. ** still short of its goal. The following chart shows the allowed
  31126. ** transitions and the inserted intermediate states:
  31127. **
  31128. ** UNLOCKED -> SHARED
  31129. ** SHARED -> RESERVED
  31130. ** SHARED -> (PENDING) -> EXCLUSIVE
  31131. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31132. ** PENDING -> EXCLUSIVE
  31133. **
  31134. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  31135. ** routine to lower a locking level.
  31136. */
  31137. static int unixLock(sqlite3_file *id, int eFileLock){
  31138. /* The following describes the implementation of the various locks and
  31139. ** lock transitions in terms of the POSIX advisory shared and exclusive
  31140. ** lock primitives (called read-locks and write-locks below, to avoid
  31141. ** confusion with SQLite lock names). The algorithms are complicated
  31142. ** slightly in order to be compatible with Windows95 systems simultaneously
  31143. ** accessing the same database file, in case that is ever required.
  31144. **
  31145. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  31146. ** byte', each single bytes at well known offsets, and the 'shared byte
  31147. ** range', a range of 510 bytes at a well known offset.
  31148. **
  31149. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  31150. ** byte'. If this is successful, 'shared byte range' is read-locked
  31151. ** and the lock on the 'pending byte' released. (Legacy note: When
  31152. ** SQLite was first developed, Windows95 systems were still very common,
  31153. ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
  31154. ** single randomly selected by from the 'shared byte range' is locked.
  31155. ** Windows95 is now pretty much extinct, but this work-around for the
  31156. ** lack of shared-locks on Windows95 lives on, for backwards
  31157. ** compatibility.)
  31158. **
  31159. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  31160. ** A RESERVED lock is implemented by grabbing a write-lock on the
  31161. ** 'reserved byte'.
  31162. **
  31163. ** A process may only obtain a PENDING lock after it has obtained a
  31164. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  31165. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  31166. ** obtained, but existing SHARED locks are allowed to persist. A process
  31167. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  31168. ** This property is used by the algorithm for rolling back a journal file
  31169. ** after a crash.
  31170. **
  31171. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  31172. ** implemented by obtaining a write-lock on the entire 'shared byte
  31173. ** range'. Since all other locks require a read-lock on one of the bytes
  31174. ** within this range, this ensures that no other locks are held on the
  31175. ** database.
  31176. */
  31177. int rc = SQLITE_OK;
  31178. unixFile *pFile = (unixFile*)id;
  31179. unixInodeInfo *pInode;
  31180. struct flock lock;
  31181. int tErrno = 0;
  31182. assert( pFile );
  31183. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  31184. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  31185. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  31186. osGetpid(0)));
  31187. /* If there is already a lock of this type or more restrictive on the
  31188. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  31189. ** unixEnterMutex() hasn't been called yet.
  31190. */
  31191. if( pFile->eFileLock>=eFileLock ){
  31192. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  31193. azFileLock(eFileLock)));
  31194. return SQLITE_OK;
  31195. }
  31196. /* Make sure the locking sequence is correct.
  31197. ** (1) We never move from unlocked to anything higher than shared lock.
  31198. ** (2) SQLite never explicitly requests a pendig lock.
  31199. ** (3) A shared lock is always held when a reserve lock is requested.
  31200. */
  31201. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  31202. assert( eFileLock!=PENDING_LOCK );
  31203. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  31204. /* This mutex is needed because pFile->pInode is shared across threads
  31205. */
  31206. unixEnterMutex();
  31207. pInode = pFile->pInode;
  31208. /* If some thread using this PID has a lock via a different unixFile*
  31209. ** handle that precludes the requested lock, return BUSY.
  31210. */
  31211. if( (pFile->eFileLock!=pInode->eFileLock &&
  31212. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  31213. ){
  31214. rc = SQLITE_BUSY;
  31215. goto end_lock;
  31216. }
  31217. /* If a SHARED lock is requested, and some thread using this PID already
  31218. ** has a SHARED or RESERVED lock, then increment reference counts and
  31219. ** return SQLITE_OK.
  31220. */
  31221. if( eFileLock==SHARED_LOCK &&
  31222. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  31223. assert( eFileLock==SHARED_LOCK );
  31224. assert( pFile->eFileLock==0 );
  31225. assert( pInode->nShared>0 );
  31226. pFile->eFileLock = SHARED_LOCK;
  31227. pInode->nShared++;
  31228. pInode->nLock++;
  31229. goto end_lock;
  31230. }
  31231. /* A PENDING lock is needed before acquiring a SHARED lock and before
  31232. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  31233. ** be released.
  31234. */
  31235. lock.l_len = 1L;
  31236. lock.l_whence = SEEK_SET;
  31237. if( eFileLock==SHARED_LOCK
  31238. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  31239. ){
  31240. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  31241. lock.l_start = PENDING_BYTE;
  31242. if( unixFileLock(pFile, &lock) ){
  31243. tErrno = errno;
  31244. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  31245. if( rc!=SQLITE_BUSY ){
  31246. storeLastErrno(pFile, tErrno);
  31247. }
  31248. goto end_lock;
  31249. }
  31250. }
  31251. /* If control gets to this point, then actually go ahead and make
  31252. ** operating system calls for the specified lock.
  31253. */
  31254. if( eFileLock==SHARED_LOCK ){
  31255. assert( pInode->nShared==0 );
  31256. assert( pInode->eFileLock==0 );
  31257. assert( rc==SQLITE_OK );
  31258. /* Now get the read-lock */
  31259. lock.l_start = SHARED_FIRST;
  31260. lock.l_len = SHARED_SIZE;
  31261. if( unixFileLock(pFile, &lock) ){
  31262. tErrno = errno;
  31263. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  31264. }
  31265. /* Drop the temporary PENDING lock */
  31266. lock.l_start = PENDING_BYTE;
  31267. lock.l_len = 1L;
  31268. lock.l_type = F_UNLCK;
  31269. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  31270. /* This could happen with a network mount */
  31271. tErrno = errno;
  31272. rc = SQLITE_IOERR_UNLOCK;
  31273. }
  31274. if( rc ){
  31275. if( rc!=SQLITE_BUSY ){
  31276. storeLastErrno(pFile, tErrno);
  31277. }
  31278. goto end_lock;
  31279. }else{
  31280. pFile->eFileLock = SHARED_LOCK;
  31281. pInode->nLock++;
  31282. pInode->nShared = 1;
  31283. }
  31284. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  31285. /* We are trying for an exclusive lock but another thread in this
  31286. ** same process is still holding a shared lock. */
  31287. rc = SQLITE_BUSY;
  31288. }else{
  31289. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  31290. ** assumed that there is a SHARED or greater lock on the file
  31291. ** already.
  31292. */
  31293. assert( 0!=pFile->eFileLock );
  31294. lock.l_type = F_WRLCK;
  31295. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  31296. if( eFileLock==RESERVED_LOCK ){
  31297. lock.l_start = RESERVED_BYTE;
  31298. lock.l_len = 1L;
  31299. }else{
  31300. lock.l_start = SHARED_FIRST;
  31301. lock.l_len = SHARED_SIZE;
  31302. }
  31303. if( unixFileLock(pFile, &lock) ){
  31304. tErrno = errno;
  31305. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  31306. if( rc!=SQLITE_BUSY ){
  31307. storeLastErrno(pFile, tErrno);
  31308. }
  31309. }
  31310. }
  31311. #ifdef SQLITE_DEBUG
  31312. /* Set up the transaction-counter change checking flags when
  31313. ** transitioning from a SHARED to a RESERVED lock. The change
  31314. ** from SHARED to RESERVED marks the beginning of a normal
  31315. ** write operation (not a hot journal rollback).
  31316. */
  31317. if( rc==SQLITE_OK
  31318. && pFile->eFileLock<=SHARED_LOCK
  31319. && eFileLock==RESERVED_LOCK
  31320. ){
  31321. pFile->transCntrChng = 0;
  31322. pFile->dbUpdate = 0;
  31323. pFile->inNormalWrite = 1;
  31324. }
  31325. #endif
  31326. if( rc==SQLITE_OK ){
  31327. pFile->eFileLock = eFileLock;
  31328. pInode->eFileLock = eFileLock;
  31329. }else if( eFileLock==EXCLUSIVE_LOCK ){
  31330. pFile->eFileLock = PENDING_LOCK;
  31331. pInode->eFileLock = PENDING_LOCK;
  31332. }
  31333. end_lock:
  31334. unixLeaveMutex();
  31335. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  31336. rc==SQLITE_OK ? "ok" : "failed"));
  31337. return rc;
  31338. }
  31339. /*
  31340. ** Add the file descriptor used by file handle pFile to the corresponding
  31341. ** pUnused list.
  31342. */
  31343. static void setPendingFd(unixFile *pFile){
  31344. unixInodeInfo *pInode = pFile->pInode;
  31345. UnixUnusedFd *p = pFile->pPreallocatedUnused;
  31346. p->pNext = pInode->pUnused;
  31347. pInode->pUnused = p;
  31348. pFile->h = -1;
  31349. pFile->pPreallocatedUnused = 0;
  31350. nUnusedFd++;
  31351. }
  31352. /*
  31353. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31354. ** must be either NO_LOCK or SHARED_LOCK.
  31355. **
  31356. ** If the locking level of the file descriptor is already at or below
  31357. ** the requested locking level, this routine is a no-op.
  31358. **
  31359. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  31360. ** the byte range is divided into 2 parts and the first part is unlocked then
  31361. ** set to a read lock, then the other part is simply unlocked. This works
  31362. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  31363. ** remove the write lock on a region when a read lock is set.
  31364. */
  31365. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  31366. unixFile *pFile = (unixFile*)id;
  31367. unixInodeInfo *pInode;
  31368. struct flock lock;
  31369. int rc = SQLITE_OK;
  31370. assert( pFile );
  31371. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  31372. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  31373. osGetpid(0)));
  31374. assert( eFileLock<=SHARED_LOCK );
  31375. if( pFile->eFileLock<=eFileLock ){
  31376. return SQLITE_OK;
  31377. }
  31378. unixEnterMutex();
  31379. pInode = pFile->pInode;
  31380. assert( pInode->nShared!=0 );
  31381. if( pFile->eFileLock>SHARED_LOCK ){
  31382. assert( pInode->eFileLock==pFile->eFileLock );
  31383. #ifdef SQLITE_DEBUG
  31384. /* When reducing a lock such that other processes can start
  31385. ** reading the database file again, make sure that the
  31386. ** transaction counter was updated if any part of the database
  31387. ** file changed. If the transaction counter is not updated,
  31388. ** other connections to the same file might not realize that
  31389. ** the file has changed and hence might not know to flush their
  31390. ** cache. The use of a stale cache can lead to database corruption.
  31391. */
  31392. pFile->inNormalWrite = 0;
  31393. #endif
  31394. /* downgrading to a shared lock on NFS involves clearing the write lock
  31395. ** before establishing the readlock - to avoid a race condition we downgrade
  31396. ** the lock in 2 blocks, so that part of the range will be covered by a
  31397. ** write lock until the rest is covered by a read lock:
  31398. ** 1: [WWWWW]
  31399. ** 2: [....W]
  31400. ** 3: [RRRRW]
  31401. ** 4: [RRRR.]
  31402. */
  31403. if( eFileLock==SHARED_LOCK ){
  31404. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  31405. (void)handleNFSUnlock;
  31406. assert( handleNFSUnlock==0 );
  31407. #endif
  31408. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  31409. if( handleNFSUnlock ){
  31410. int tErrno; /* Error code from system call errors */
  31411. off_t divSize = SHARED_SIZE - 1;
  31412. lock.l_type = F_UNLCK;
  31413. lock.l_whence = SEEK_SET;
  31414. lock.l_start = SHARED_FIRST;
  31415. lock.l_len = divSize;
  31416. if( unixFileLock(pFile, &lock)==(-1) ){
  31417. tErrno = errno;
  31418. rc = SQLITE_IOERR_UNLOCK;
  31419. storeLastErrno(pFile, tErrno);
  31420. goto end_unlock;
  31421. }
  31422. lock.l_type = F_RDLCK;
  31423. lock.l_whence = SEEK_SET;
  31424. lock.l_start = SHARED_FIRST;
  31425. lock.l_len = divSize;
  31426. if( unixFileLock(pFile, &lock)==(-1) ){
  31427. tErrno = errno;
  31428. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  31429. if( IS_LOCK_ERROR(rc) ){
  31430. storeLastErrno(pFile, tErrno);
  31431. }
  31432. goto end_unlock;
  31433. }
  31434. lock.l_type = F_UNLCK;
  31435. lock.l_whence = SEEK_SET;
  31436. lock.l_start = SHARED_FIRST+divSize;
  31437. lock.l_len = SHARED_SIZE-divSize;
  31438. if( unixFileLock(pFile, &lock)==(-1) ){
  31439. tErrno = errno;
  31440. rc = SQLITE_IOERR_UNLOCK;
  31441. storeLastErrno(pFile, tErrno);
  31442. goto end_unlock;
  31443. }
  31444. }else
  31445. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  31446. {
  31447. lock.l_type = F_RDLCK;
  31448. lock.l_whence = SEEK_SET;
  31449. lock.l_start = SHARED_FIRST;
  31450. lock.l_len = SHARED_SIZE;
  31451. if( unixFileLock(pFile, &lock) ){
  31452. /* In theory, the call to unixFileLock() cannot fail because another
  31453. ** process is holding an incompatible lock. If it does, this
  31454. ** indicates that the other process is not following the locking
  31455. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  31456. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  31457. ** an assert to fail). */
  31458. rc = SQLITE_IOERR_RDLOCK;
  31459. storeLastErrno(pFile, errno);
  31460. goto end_unlock;
  31461. }
  31462. }
  31463. }
  31464. lock.l_type = F_UNLCK;
  31465. lock.l_whence = SEEK_SET;
  31466. lock.l_start = PENDING_BYTE;
  31467. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  31468. if( unixFileLock(pFile, &lock)==0 ){
  31469. pInode->eFileLock = SHARED_LOCK;
  31470. }else{
  31471. rc = SQLITE_IOERR_UNLOCK;
  31472. storeLastErrno(pFile, errno);
  31473. goto end_unlock;
  31474. }
  31475. }
  31476. if( eFileLock==NO_LOCK ){
  31477. /* Decrement the shared lock counter. Release the lock using an
  31478. ** OS call only when all threads in this same process have released
  31479. ** the lock.
  31480. */
  31481. pInode->nShared--;
  31482. if( pInode->nShared==0 ){
  31483. lock.l_type = F_UNLCK;
  31484. lock.l_whence = SEEK_SET;
  31485. lock.l_start = lock.l_len = 0L;
  31486. if( unixFileLock(pFile, &lock)==0 ){
  31487. pInode->eFileLock = NO_LOCK;
  31488. }else{
  31489. rc = SQLITE_IOERR_UNLOCK;
  31490. storeLastErrno(pFile, errno);
  31491. pInode->eFileLock = NO_LOCK;
  31492. pFile->eFileLock = NO_LOCK;
  31493. }
  31494. }
  31495. /* Decrement the count of locks against this same file. When the
  31496. ** count reaches zero, close any other file descriptors whose close
  31497. ** was deferred because of outstanding locks.
  31498. */
  31499. pInode->nLock--;
  31500. assert( pInode->nLock>=0 );
  31501. if( pInode->nLock==0 ){
  31502. closePendingFds(pFile);
  31503. }
  31504. }
  31505. end_unlock:
  31506. unixLeaveMutex();
  31507. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  31508. return rc;
  31509. }
  31510. /*
  31511. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31512. ** must be either NO_LOCK or SHARED_LOCK.
  31513. **
  31514. ** If the locking level of the file descriptor is already at or below
  31515. ** the requested locking level, this routine is a no-op.
  31516. */
  31517. static int unixUnlock(sqlite3_file *id, int eFileLock){
  31518. #if SQLITE_MAX_MMAP_SIZE>0
  31519. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  31520. #endif
  31521. return posixUnlock(id, eFileLock, 0);
  31522. }
  31523. #if SQLITE_MAX_MMAP_SIZE>0
  31524. static int unixMapfile(unixFile *pFd, i64 nByte);
  31525. static void unixUnmapfile(unixFile *pFd);
  31526. #endif
  31527. /*
  31528. ** This function performs the parts of the "close file" operation
  31529. ** common to all locking schemes. It closes the directory and file
  31530. ** handles, if they are valid, and sets all fields of the unixFile
  31531. ** structure to 0.
  31532. **
  31533. ** It is *not* necessary to hold the mutex when this routine is called,
  31534. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  31535. ** vxworksReleaseFileId() routine.
  31536. */
  31537. static int closeUnixFile(sqlite3_file *id){
  31538. unixFile *pFile = (unixFile*)id;
  31539. #if SQLITE_MAX_MMAP_SIZE>0
  31540. unixUnmapfile(pFile);
  31541. #endif
  31542. if( pFile->h>=0 ){
  31543. robust_close(pFile, pFile->h, __LINE__);
  31544. pFile->h = -1;
  31545. }
  31546. #if OS_VXWORKS
  31547. if( pFile->pId ){
  31548. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  31549. osUnlink(pFile->pId->zCanonicalName);
  31550. }
  31551. vxworksReleaseFileId(pFile->pId);
  31552. pFile->pId = 0;
  31553. }
  31554. #endif
  31555. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  31556. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  31557. osUnlink(pFile->zPath);
  31558. sqlite3_free(*(char**)&pFile->zPath);
  31559. pFile->zPath = 0;
  31560. }
  31561. #endif
  31562. OSTRACE(("CLOSE %-3d\n", pFile->h));
  31563. OpenCounter(-1);
  31564. sqlite3_free(pFile->pPreallocatedUnused);
  31565. memset(pFile, 0, sizeof(unixFile));
  31566. return SQLITE_OK;
  31567. }
  31568. /*
  31569. ** Close a file.
  31570. */
  31571. static int unixClose(sqlite3_file *id){
  31572. int rc = SQLITE_OK;
  31573. unixFile *pFile = (unixFile *)id;
  31574. verifyDbFile(pFile);
  31575. unixUnlock(id, NO_LOCK);
  31576. unixEnterMutex();
  31577. /* unixFile.pInode is always valid here. Otherwise, a different close
  31578. ** routine (e.g. nolockClose()) would be called instead.
  31579. */
  31580. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  31581. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  31582. /* If there are outstanding locks, do not actually close the file just
  31583. ** yet because that would clear those locks. Instead, add the file
  31584. ** descriptor to pInode->pUnused list. It will be automatically closed
  31585. ** when the last lock is cleared.
  31586. */
  31587. setPendingFd(pFile);
  31588. }
  31589. releaseInodeInfo(pFile);
  31590. rc = closeUnixFile(id);
  31591. unixLeaveMutex();
  31592. return rc;
  31593. }
  31594. /************** End of the posix advisory lock implementation *****************
  31595. ******************************************************************************/
  31596. /******************************************************************************
  31597. ****************************** No-op Locking **********************************
  31598. **
  31599. ** Of the various locking implementations available, this is by far the
  31600. ** simplest: locking is ignored. No attempt is made to lock the database
  31601. ** file for reading or writing.
  31602. **
  31603. ** This locking mode is appropriate for use on read-only databases
  31604. ** (ex: databases that are burned into CD-ROM, for example.) It can
  31605. ** also be used if the application employs some external mechanism to
  31606. ** prevent simultaneous access of the same database by two or more
  31607. ** database connections. But there is a serious risk of database
  31608. ** corruption if this locking mode is used in situations where multiple
  31609. ** database connections are accessing the same database file at the same
  31610. ** time and one or more of those connections are writing.
  31611. */
  31612. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  31613. UNUSED_PARAMETER(NotUsed);
  31614. *pResOut = 0;
  31615. return SQLITE_OK;
  31616. }
  31617. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  31618. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  31619. return SQLITE_OK;
  31620. }
  31621. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  31622. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  31623. return SQLITE_OK;
  31624. }
  31625. /*
  31626. ** Close the file.
  31627. */
  31628. static int nolockClose(sqlite3_file *id) {
  31629. return closeUnixFile(id);
  31630. }
  31631. /******************* End of the no-op lock implementation *********************
  31632. ******************************************************************************/
  31633. /******************************************************************************
  31634. ************************* Begin dot-file Locking ******************************
  31635. **
  31636. ** The dotfile locking implementation uses the existence of separate lock
  31637. ** files (really a directory) to control access to the database. This works
  31638. ** on just about every filesystem imaginable. But there are serious downsides:
  31639. **
  31640. ** (1) There is zero concurrency. A single reader blocks all other
  31641. ** connections from reading or writing the database.
  31642. **
  31643. ** (2) An application crash or power loss can leave stale lock files
  31644. ** sitting around that need to be cleared manually.
  31645. **
  31646. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  31647. ** other locking strategy is available.
  31648. **
  31649. ** Dotfile locking works by creating a subdirectory in the same directory as
  31650. ** the database and with the same name but with a ".lock" extension added.
  31651. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  31652. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  31653. */
  31654. /*
  31655. ** The file suffix added to the data base filename in order to create the
  31656. ** lock directory.
  31657. */
  31658. #define DOTLOCK_SUFFIX ".lock"
  31659. /*
  31660. ** This routine checks if there is a RESERVED lock held on the specified
  31661. ** file by this or any other process. If such a lock is held, set *pResOut
  31662. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  31663. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  31664. **
  31665. ** In dotfile locking, either a lock exists or it does not. So in this
  31666. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  31667. ** is held on the file and false if the file is unlocked.
  31668. */
  31669. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  31670. int rc = SQLITE_OK;
  31671. int reserved = 0;
  31672. unixFile *pFile = (unixFile*)id;
  31673. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  31674. assert( pFile );
  31675. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  31676. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  31677. *pResOut = reserved;
  31678. return rc;
  31679. }
  31680. /*
  31681. ** Lock the file with the lock specified by parameter eFileLock - one
  31682. ** of the following:
  31683. **
  31684. ** (1) SHARED_LOCK
  31685. ** (2) RESERVED_LOCK
  31686. ** (3) PENDING_LOCK
  31687. ** (4) EXCLUSIVE_LOCK
  31688. **
  31689. ** Sometimes when requesting one lock state, additional lock states
  31690. ** are inserted in between. The locking might fail on one of the later
  31691. ** transitions leaving the lock state different from what it started but
  31692. ** still short of its goal. The following chart shows the allowed
  31693. ** transitions and the inserted intermediate states:
  31694. **
  31695. ** UNLOCKED -> SHARED
  31696. ** SHARED -> RESERVED
  31697. ** SHARED -> (PENDING) -> EXCLUSIVE
  31698. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31699. ** PENDING -> EXCLUSIVE
  31700. **
  31701. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  31702. ** routine to lower a locking level.
  31703. **
  31704. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  31705. ** But we track the other locking levels internally.
  31706. */
  31707. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  31708. unixFile *pFile = (unixFile*)id;
  31709. char *zLockFile = (char *)pFile->lockingContext;
  31710. int rc = SQLITE_OK;
  31711. /* If we have any lock, then the lock file already exists. All we have
  31712. ** to do is adjust our internal record of the lock level.
  31713. */
  31714. if( pFile->eFileLock > NO_LOCK ){
  31715. pFile->eFileLock = eFileLock;
  31716. /* Always update the timestamp on the old file */
  31717. #ifdef HAVE_UTIME
  31718. utime(zLockFile, NULL);
  31719. #else
  31720. utimes(zLockFile, NULL);
  31721. #endif
  31722. return SQLITE_OK;
  31723. }
  31724. /* grab an exclusive lock */
  31725. rc = osMkdir(zLockFile, 0777);
  31726. if( rc<0 ){
  31727. /* failed to open/create the lock directory */
  31728. int tErrno = errno;
  31729. if( EEXIST == tErrno ){
  31730. rc = SQLITE_BUSY;
  31731. } else {
  31732. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  31733. if( rc!=SQLITE_BUSY ){
  31734. storeLastErrno(pFile, tErrno);
  31735. }
  31736. }
  31737. return rc;
  31738. }
  31739. /* got it, set the type and return ok */
  31740. pFile->eFileLock = eFileLock;
  31741. return rc;
  31742. }
  31743. /*
  31744. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31745. ** must be either NO_LOCK or SHARED_LOCK.
  31746. **
  31747. ** If the locking level of the file descriptor is already at or below
  31748. ** the requested locking level, this routine is a no-op.
  31749. **
  31750. ** When the locking level reaches NO_LOCK, delete the lock file.
  31751. */
  31752. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  31753. unixFile *pFile = (unixFile*)id;
  31754. char *zLockFile = (char *)pFile->lockingContext;
  31755. int rc;
  31756. assert( pFile );
  31757. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  31758. pFile->eFileLock, osGetpid(0)));
  31759. assert( eFileLock<=SHARED_LOCK );
  31760. /* no-op if possible */
  31761. if( pFile->eFileLock==eFileLock ){
  31762. return SQLITE_OK;
  31763. }
  31764. /* To downgrade to shared, simply update our internal notion of the
  31765. ** lock state. No need to mess with the file on disk.
  31766. */
  31767. if( eFileLock==SHARED_LOCK ){
  31768. pFile->eFileLock = SHARED_LOCK;
  31769. return SQLITE_OK;
  31770. }
  31771. /* To fully unlock the database, delete the lock file */
  31772. assert( eFileLock==NO_LOCK );
  31773. rc = osRmdir(zLockFile);
  31774. if( rc<0 ){
  31775. int tErrno = errno;
  31776. if( tErrno==ENOENT ){
  31777. rc = SQLITE_OK;
  31778. }else{
  31779. rc = SQLITE_IOERR_UNLOCK;
  31780. storeLastErrno(pFile, tErrno);
  31781. }
  31782. return rc;
  31783. }
  31784. pFile->eFileLock = NO_LOCK;
  31785. return SQLITE_OK;
  31786. }
  31787. /*
  31788. ** Close a file. Make sure the lock has been released before closing.
  31789. */
  31790. static int dotlockClose(sqlite3_file *id) {
  31791. unixFile *pFile = (unixFile*)id;
  31792. assert( id!=0 );
  31793. dotlockUnlock(id, NO_LOCK);
  31794. sqlite3_free(pFile->lockingContext);
  31795. return closeUnixFile(id);
  31796. }
  31797. /****************** End of the dot-file lock implementation *******************
  31798. ******************************************************************************/
  31799. /******************************************************************************
  31800. ************************** Begin flock Locking ********************************
  31801. **
  31802. ** Use the flock() system call to do file locking.
  31803. **
  31804. ** flock() locking is like dot-file locking in that the various
  31805. ** fine-grain locking levels supported by SQLite are collapsed into
  31806. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  31807. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  31808. ** still works when you do this, but concurrency is reduced since
  31809. ** only a single process can be reading the database at a time.
  31810. **
  31811. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  31812. */
  31813. #if SQLITE_ENABLE_LOCKING_STYLE
  31814. /*
  31815. ** Retry flock() calls that fail with EINTR
  31816. */
  31817. #ifdef EINTR
  31818. static int robust_flock(int fd, int op){
  31819. int rc;
  31820. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  31821. return rc;
  31822. }
  31823. #else
  31824. # define robust_flock(a,b) flock(a,b)
  31825. #endif
  31826. /*
  31827. ** This routine checks if there is a RESERVED lock held on the specified
  31828. ** file by this or any other process. If such a lock is held, set *pResOut
  31829. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  31830. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  31831. */
  31832. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  31833. int rc = SQLITE_OK;
  31834. int reserved = 0;
  31835. unixFile *pFile = (unixFile*)id;
  31836. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  31837. assert( pFile );
  31838. /* Check if a thread in this process holds such a lock */
  31839. if( pFile->eFileLock>SHARED_LOCK ){
  31840. reserved = 1;
  31841. }
  31842. /* Otherwise see if some other process holds it. */
  31843. if( !reserved ){
  31844. /* attempt to get the lock */
  31845. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  31846. if( !lrc ){
  31847. /* got the lock, unlock it */
  31848. lrc = robust_flock(pFile->h, LOCK_UN);
  31849. if ( lrc ) {
  31850. int tErrno = errno;
  31851. /* unlock failed with an error */
  31852. lrc = SQLITE_IOERR_UNLOCK;
  31853. storeLastErrno(pFile, tErrno);
  31854. rc = lrc;
  31855. }
  31856. } else {
  31857. int tErrno = errno;
  31858. reserved = 1;
  31859. /* someone else might have it reserved */
  31860. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  31861. if( IS_LOCK_ERROR(lrc) ){
  31862. storeLastErrno(pFile, tErrno);
  31863. rc = lrc;
  31864. }
  31865. }
  31866. }
  31867. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  31868. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  31869. if( (rc & 0xff) == SQLITE_IOERR ){
  31870. rc = SQLITE_OK;
  31871. reserved=1;
  31872. }
  31873. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  31874. *pResOut = reserved;
  31875. return rc;
  31876. }
  31877. /*
  31878. ** Lock the file with the lock specified by parameter eFileLock - one
  31879. ** of the following:
  31880. **
  31881. ** (1) SHARED_LOCK
  31882. ** (2) RESERVED_LOCK
  31883. ** (3) PENDING_LOCK
  31884. ** (4) EXCLUSIVE_LOCK
  31885. **
  31886. ** Sometimes when requesting one lock state, additional lock states
  31887. ** are inserted in between. The locking might fail on one of the later
  31888. ** transitions leaving the lock state different from what it started but
  31889. ** still short of its goal. The following chart shows the allowed
  31890. ** transitions and the inserted intermediate states:
  31891. **
  31892. ** UNLOCKED -> SHARED
  31893. ** SHARED -> RESERVED
  31894. ** SHARED -> (PENDING) -> EXCLUSIVE
  31895. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31896. ** PENDING -> EXCLUSIVE
  31897. **
  31898. ** flock() only really support EXCLUSIVE locks. We track intermediate
  31899. ** lock states in the sqlite3_file structure, but all locks SHARED or
  31900. ** above are really EXCLUSIVE locks and exclude all other processes from
  31901. ** access the file.
  31902. **
  31903. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  31904. ** routine to lower a locking level.
  31905. */
  31906. static int flockLock(sqlite3_file *id, int eFileLock) {
  31907. int rc = SQLITE_OK;
  31908. unixFile *pFile = (unixFile*)id;
  31909. assert( pFile );
  31910. /* if we already have a lock, it is exclusive.
  31911. ** Just adjust level and punt on outta here. */
  31912. if (pFile->eFileLock > NO_LOCK) {
  31913. pFile->eFileLock = eFileLock;
  31914. return SQLITE_OK;
  31915. }
  31916. /* grab an exclusive lock */
  31917. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  31918. int tErrno = errno;
  31919. /* didn't get, must be busy */
  31920. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  31921. if( IS_LOCK_ERROR(rc) ){
  31922. storeLastErrno(pFile, tErrno);
  31923. }
  31924. } else {
  31925. /* got it, set the type and return ok */
  31926. pFile->eFileLock = eFileLock;
  31927. }
  31928. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  31929. rc==SQLITE_OK ? "ok" : "failed"));
  31930. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  31931. if( (rc & 0xff) == SQLITE_IOERR ){
  31932. rc = SQLITE_BUSY;
  31933. }
  31934. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  31935. return rc;
  31936. }
  31937. /*
  31938. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31939. ** must be either NO_LOCK or SHARED_LOCK.
  31940. **
  31941. ** If the locking level of the file descriptor is already at or below
  31942. ** the requested locking level, this routine is a no-op.
  31943. */
  31944. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  31945. unixFile *pFile = (unixFile*)id;
  31946. assert( pFile );
  31947. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  31948. pFile->eFileLock, osGetpid(0)));
  31949. assert( eFileLock<=SHARED_LOCK );
  31950. /* no-op if possible */
  31951. if( pFile->eFileLock==eFileLock ){
  31952. return SQLITE_OK;
  31953. }
  31954. /* shared can just be set because we always have an exclusive */
  31955. if (eFileLock==SHARED_LOCK) {
  31956. pFile->eFileLock = eFileLock;
  31957. return SQLITE_OK;
  31958. }
  31959. /* no, really, unlock. */
  31960. if( robust_flock(pFile->h, LOCK_UN) ){
  31961. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  31962. return SQLITE_OK;
  31963. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  31964. return SQLITE_IOERR_UNLOCK;
  31965. }else{
  31966. pFile->eFileLock = NO_LOCK;
  31967. return SQLITE_OK;
  31968. }
  31969. }
  31970. /*
  31971. ** Close a file.
  31972. */
  31973. static int flockClose(sqlite3_file *id) {
  31974. assert( id!=0 );
  31975. flockUnlock(id, NO_LOCK);
  31976. return closeUnixFile(id);
  31977. }
  31978. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  31979. /******************* End of the flock lock implementation *********************
  31980. ******************************************************************************/
  31981. /******************************************************************************
  31982. ************************ Begin Named Semaphore Locking ************************
  31983. **
  31984. ** Named semaphore locking is only supported on VxWorks.
  31985. **
  31986. ** Semaphore locking is like dot-lock and flock in that it really only
  31987. ** supports EXCLUSIVE locking. Only a single process can read or write
  31988. ** the database file at a time. This reduces potential concurrency, but
  31989. ** makes the lock implementation much easier.
  31990. */
  31991. #if OS_VXWORKS
  31992. /*
  31993. ** This routine checks if there is a RESERVED lock held on the specified
  31994. ** file by this or any other process. If such a lock is held, set *pResOut
  31995. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  31996. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  31997. */
  31998. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  31999. int rc = SQLITE_OK;
  32000. int reserved = 0;
  32001. unixFile *pFile = (unixFile*)id;
  32002. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32003. assert( pFile );
  32004. /* Check if a thread in this process holds such a lock */
  32005. if( pFile->eFileLock>SHARED_LOCK ){
  32006. reserved = 1;
  32007. }
  32008. /* Otherwise see if some other process holds it. */
  32009. if( !reserved ){
  32010. sem_t *pSem = pFile->pInode->pSem;
  32011. if( sem_trywait(pSem)==-1 ){
  32012. int tErrno = errno;
  32013. if( EAGAIN != tErrno ){
  32014. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  32015. storeLastErrno(pFile, tErrno);
  32016. } else {
  32017. /* someone else has the lock when we are in NO_LOCK */
  32018. reserved = (pFile->eFileLock < SHARED_LOCK);
  32019. }
  32020. }else{
  32021. /* we could have it if we want it */
  32022. sem_post(pSem);
  32023. }
  32024. }
  32025. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  32026. *pResOut = reserved;
  32027. return rc;
  32028. }
  32029. /*
  32030. ** Lock the file with the lock specified by parameter eFileLock - one
  32031. ** of the following:
  32032. **
  32033. ** (1) SHARED_LOCK
  32034. ** (2) RESERVED_LOCK
  32035. ** (3) PENDING_LOCK
  32036. ** (4) EXCLUSIVE_LOCK
  32037. **
  32038. ** Sometimes when requesting one lock state, additional lock states
  32039. ** are inserted in between. The locking might fail on one of the later
  32040. ** transitions leaving the lock state different from what it started but
  32041. ** still short of its goal. The following chart shows the allowed
  32042. ** transitions and the inserted intermediate states:
  32043. **
  32044. ** UNLOCKED -> SHARED
  32045. ** SHARED -> RESERVED
  32046. ** SHARED -> (PENDING) -> EXCLUSIVE
  32047. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32048. ** PENDING -> EXCLUSIVE
  32049. **
  32050. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  32051. ** lock states in the sqlite3_file structure, but all locks SHARED or
  32052. ** above are really EXCLUSIVE locks and exclude all other processes from
  32053. ** access the file.
  32054. **
  32055. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32056. ** routine to lower a locking level.
  32057. */
  32058. static int semXLock(sqlite3_file *id, int eFileLock) {
  32059. unixFile *pFile = (unixFile*)id;
  32060. sem_t *pSem = pFile->pInode->pSem;
  32061. int rc = SQLITE_OK;
  32062. /* if we already have a lock, it is exclusive.
  32063. ** Just adjust level and punt on outta here. */
  32064. if (pFile->eFileLock > NO_LOCK) {
  32065. pFile->eFileLock = eFileLock;
  32066. rc = SQLITE_OK;
  32067. goto sem_end_lock;
  32068. }
  32069. /* lock semaphore now but bail out when already locked. */
  32070. if( sem_trywait(pSem)==-1 ){
  32071. rc = SQLITE_BUSY;
  32072. goto sem_end_lock;
  32073. }
  32074. /* got it, set the type and return ok */
  32075. pFile->eFileLock = eFileLock;
  32076. sem_end_lock:
  32077. return rc;
  32078. }
  32079. /*
  32080. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32081. ** must be either NO_LOCK or SHARED_LOCK.
  32082. **
  32083. ** If the locking level of the file descriptor is already at or below
  32084. ** the requested locking level, this routine is a no-op.
  32085. */
  32086. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  32087. unixFile *pFile = (unixFile*)id;
  32088. sem_t *pSem = pFile->pInode->pSem;
  32089. assert( pFile );
  32090. assert( pSem );
  32091. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  32092. pFile->eFileLock, osGetpid(0)));
  32093. assert( eFileLock<=SHARED_LOCK );
  32094. /* no-op if possible */
  32095. if( pFile->eFileLock==eFileLock ){
  32096. return SQLITE_OK;
  32097. }
  32098. /* shared can just be set because we always have an exclusive */
  32099. if (eFileLock==SHARED_LOCK) {
  32100. pFile->eFileLock = eFileLock;
  32101. return SQLITE_OK;
  32102. }
  32103. /* no, really unlock. */
  32104. if ( sem_post(pSem)==-1 ) {
  32105. int rc, tErrno = errno;
  32106. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  32107. if( IS_LOCK_ERROR(rc) ){
  32108. storeLastErrno(pFile, tErrno);
  32109. }
  32110. return rc;
  32111. }
  32112. pFile->eFileLock = NO_LOCK;
  32113. return SQLITE_OK;
  32114. }
  32115. /*
  32116. ** Close a file.
  32117. */
  32118. static int semXClose(sqlite3_file *id) {
  32119. if( id ){
  32120. unixFile *pFile = (unixFile*)id;
  32121. semXUnlock(id, NO_LOCK);
  32122. assert( pFile );
  32123. unixEnterMutex();
  32124. releaseInodeInfo(pFile);
  32125. unixLeaveMutex();
  32126. closeUnixFile(id);
  32127. }
  32128. return SQLITE_OK;
  32129. }
  32130. #endif /* OS_VXWORKS */
  32131. /*
  32132. ** Named semaphore locking is only available on VxWorks.
  32133. **
  32134. *************** End of the named semaphore lock implementation ****************
  32135. ******************************************************************************/
  32136. /******************************************************************************
  32137. *************************** Begin AFP Locking *********************************
  32138. **
  32139. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  32140. ** on Apple Macintosh computers - both OS9 and OSX.
  32141. **
  32142. ** Third-party implementations of AFP are available. But this code here
  32143. ** only works on OSX.
  32144. */
  32145. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  32146. /*
  32147. ** The afpLockingContext structure contains all afp lock specific state
  32148. */
  32149. typedef struct afpLockingContext afpLockingContext;
  32150. struct afpLockingContext {
  32151. int reserved;
  32152. const char *dbPath; /* Name of the open file */
  32153. };
  32154. struct ByteRangeLockPB2
  32155. {
  32156. unsigned long long offset; /* offset to first byte to lock */
  32157. unsigned long long length; /* nbr of bytes to lock */
  32158. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  32159. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  32160. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  32161. int fd; /* file desc to assoc this lock with */
  32162. };
  32163. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  32164. /*
  32165. ** This is a utility for setting or clearing a bit-range lock on an
  32166. ** AFP filesystem.
  32167. **
  32168. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  32169. */
  32170. static int afpSetLock(
  32171. const char *path, /* Name of the file to be locked or unlocked */
  32172. unixFile *pFile, /* Open file descriptor on path */
  32173. unsigned long long offset, /* First byte to be locked */
  32174. unsigned long long length, /* Number of bytes to lock */
  32175. int setLockFlag /* True to set lock. False to clear lock */
  32176. ){
  32177. struct ByteRangeLockPB2 pb;
  32178. int err;
  32179. pb.unLockFlag = setLockFlag ? 0 : 1;
  32180. pb.startEndFlag = 0;
  32181. pb.offset = offset;
  32182. pb.length = length;
  32183. pb.fd = pFile->h;
  32184. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  32185. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  32186. offset, length));
  32187. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  32188. if ( err==-1 ) {
  32189. int rc;
  32190. int tErrno = errno;
  32191. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  32192. path, tErrno, strerror(tErrno)));
  32193. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  32194. rc = SQLITE_BUSY;
  32195. #else
  32196. rc = sqliteErrorFromPosixError(tErrno,
  32197. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  32198. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  32199. if( IS_LOCK_ERROR(rc) ){
  32200. storeLastErrno(pFile, tErrno);
  32201. }
  32202. return rc;
  32203. } else {
  32204. return SQLITE_OK;
  32205. }
  32206. }
  32207. /*
  32208. ** This routine checks if there is a RESERVED lock held on the specified
  32209. ** file by this or any other process. If such a lock is held, set *pResOut
  32210. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  32211. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  32212. */
  32213. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  32214. int rc = SQLITE_OK;
  32215. int reserved = 0;
  32216. unixFile *pFile = (unixFile*)id;
  32217. afpLockingContext *context;
  32218. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  32219. assert( pFile );
  32220. context = (afpLockingContext *) pFile->lockingContext;
  32221. if( context->reserved ){
  32222. *pResOut = 1;
  32223. return SQLITE_OK;
  32224. }
  32225. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  32226. /* Check if a thread in this process holds such a lock */
  32227. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  32228. reserved = 1;
  32229. }
  32230. /* Otherwise see if some other process holds it.
  32231. */
  32232. if( !reserved ){
  32233. /* lock the RESERVED byte */
  32234. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  32235. if( SQLITE_OK==lrc ){
  32236. /* if we succeeded in taking the reserved lock, unlock it to restore
  32237. ** the original state */
  32238. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  32239. } else {
  32240. /* if we failed to get the lock then someone else must have it */
  32241. reserved = 1;
  32242. }
  32243. if( IS_LOCK_ERROR(lrc) ){
  32244. rc=lrc;
  32245. }
  32246. }
  32247. unixLeaveMutex();
  32248. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  32249. *pResOut = reserved;
  32250. return rc;
  32251. }
  32252. /*
  32253. ** Lock the file with the lock specified by parameter eFileLock - one
  32254. ** of the following:
  32255. **
  32256. ** (1) SHARED_LOCK
  32257. ** (2) RESERVED_LOCK
  32258. ** (3) PENDING_LOCK
  32259. ** (4) EXCLUSIVE_LOCK
  32260. **
  32261. ** Sometimes when requesting one lock state, additional lock states
  32262. ** are inserted in between. The locking might fail on one of the later
  32263. ** transitions leaving the lock state different from what it started but
  32264. ** still short of its goal. The following chart shows the allowed
  32265. ** transitions and the inserted intermediate states:
  32266. **
  32267. ** UNLOCKED -> SHARED
  32268. ** SHARED -> RESERVED
  32269. ** SHARED -> (PENDING) -> EXCLUSIVE
  32270. ** RESERVED -> (PENDING) -> EXCLUSIVE
  32271. ** PENDING -> EXCLUSIVE
  32272. **
  32273. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  32274. ** routine to lower a locking level.
  32275. */
  32276. static int afpLock(sqlite3_file *id, int eFileLock){
  32277. int rc = SQLITE_OK;
  32278. unixFile *pFile = (unixFile*)id;
  32279. unixInodeInfo *pInode = pFile->pInode;
  32280. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  32281. assert( pFile );
  32282. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  32283. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  32284. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  32285. /* If there is already a lock of this type or more restrictive on the
  32286. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  32287. ** unixEnterMutex() hasn't been called yet.
  32288. */
  32289. if( pFile->eFileLock>=eFileLock ){
  32290. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  32291. azFileLock(eFileLock)));
  32292. return SQLITE_OK;
  32293. }
  32294. /* Make sure the locking sequence is correct
  32295. ** (1) We never move from unlocked to anything higher than shared lock.
  32296. ** (2) SQLite never explicitly requests a pendig lock.
  32297. ** (3) A shared lock is always held when a reserve lock is requested.
  32298. */
  32299. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  32300. assert( eFileLock!=PENDING_LOCK );
  32301. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  32302. /* This mutex is needed because pFile->pInode is shared across threads
  32303. */
  32304. unixEnterMutex();
  32305. pInode = pFile->pInode;
  32306. /* If some thread using this PID has a lock via a different unixFile*
  32307. ** handle that precludes the requested lock, return BUSY.
  32308. */
  32309. if( (pFile->eFileLock!=pInode->eFileLock &&
  32310. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  32311. ){
  32312. rc = SQLITE_BUSY;
  32313. goto afp_end_lock;
  32314. }
  32315. /* If a SHARED lock is requested, and some thread using this PID already
  32316. ** has a SHARED or RESERVED lock, then increment reference counts and
  32317. ** return SQLITE_OK.
  32318. */
  32319. if( eFileLock==SHARED_LOCK &&
  32320. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  32321. assert( eFileLock==SHARED_LOCK );
  32322. assert( pFile->eFileLock==0 );
  32323. assert( pInode->nShared>0 );
  32324. pFile->eFileLock = SHARED_LOCK;
  32325. pInode->nShared++;
  32326. pInode->nLock++;
  32327. goto afp_end_lock;
  32328. }
  32329. /* A PENDING lock is needed before acquiring a SHARED lock and before
  32330. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  32331. ** be released.
  32332. */
  32333. if( eFileLock==SHARED_LOCK
  32334. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  32335. ){
  32336. int failed;
  32337. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  32338. if (failed) {
  32339. rc = failed;
  32340. goto afp_end_lock;
  32341. }
  32342. }
  32343. /* If control gets to this point, then actually go ahead and make
  32344. ** operating system calls for the specified lock.
  32345. */
  32346. if( eFileLock==SHARED_LOCK ){
  32347. int lrc1, lrc2, lrc1Errno = 0;
  32348. long lk, mask;
  32349. assert( pInode->nShared==0 );
  32350. assert( pInode->eFileLock==0 );
  32351. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  32352. /* Now get the read-lock SHARED_LOCK */
  32353. /* note that the quality of the randomness doesn't matter that much */
  32354. lk = random();
  32355. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  32356. lrc1 = afpSetLock(context->dbPath, pFile,
  32357. SHARED_FIRST+pInode->sharedByte, 1, 1);
  32358. if( IS_LOCK_ERROR(lrc1) ){
  32359. lrc1Errno = pFile->lastErrno;
  32360. }
  32361. /* Drop the temporary PENDING lock */
  32362. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  32363. if( IS_LOCK_ERROR(lrc1) ) {
  32364. storeLastErrno(pFile, lrc1Errno);
  32365. rc = lrc1;
  32366. goto afp_end_lock;
  32367. } else if( IS_LOCK_ERROR(lrc2) ){
  32368. rc = lrc2;
  32369. goto afp_end_lock;
  32370. } else if( lrc1 != SQLITE_OK ) {
  32371. rc = lrc1;
  32372. } else {
  32373. pFile->eFileLock = SHARED_LOCK;
  32374. pInode->nLock++;
  32375. pInode->nShared = 1;
  32376. }
  32377. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  32378. /* We are trying for an exclusive lock but another thread in this
  32379. ** same process is still holding a shared lock. */
  32380. rc = SQLITE_BUSY;
  32381. }else{
  32382. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  32383. ** assumed that there is a SHARED or greater lock on the file
  32384. ** already.
  32385. */
  32386. int failed = 0;
  32387. assert( 0!=pFile->eFileLock );
  32388. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  32389. /* Acquire a RESERVED lock */
  32390. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  32391. if( !failed ){
  32392. context->reserved = 1;
  32393. }
  32394. }
  32395. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  32396. /* Acquire an EXCLUSIVE lock */
  32397. /* Remove the shared lock before trying the range. we'll need to
  32398. ** reestablish the shared lock if we can't get the afpUnlock
  32399. */
  32400. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  32401. pInode->sharedByte, 1, 0)) ){
  32402. int failed2 = SQLITE_OK;
  32403. /* now attemmpt to get the exclusive lock range */
  32404. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  32405. SHARED_SIZE, 1);
  32406. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  32407. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  32408. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  32409. ** a critical I/O error
  32410. */
  32411. rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
  32412. SQLITE_IOERR_LOCK;
  32413. goto afp_end_lock;
  32414. }
  32415. }else{
  32416. rc = failed;
  32417. }
  32418. }
  32419. if( failed ){
  32420. rc = failed;
  32421. }
  32422. }
  32423. if( rc==SQLITE_OK ){
  32424. pFile->eFileLock = eFileLock;
  32425. pInode->eFileLock = eFileLock;
  32426. }else if( eFileLock==EXCLUSIVE_LOCK ){
  32427. pFile->eFileLock = PENDING_LOCK;
  32428. pInode->eFileLock = PENDING_LOCK;
  32429. }
  32430. afp_end_lock:
  32431. unixLeaveMutex();
  32432. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  32433. rc==SQLITE_OK ? "ok" : "failed"));
  32434. return rc;
  32435. }
  32436. /*
  32437. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32438. ** must be either NO_LOCK or SHARED_LOCK.
  32439. **
  32440. ** If the locking level of the file descriptor is already at or below
  32441. ** the requested locking level, this routine is a no-op.
  32442. */
  32443. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  32444. int rc = SQLITE_OK;
  32445. unixFile *pFile = (unixFile*)id;
  32446. unixInodeInfo *pInode;
  32447. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  32448. int skipShared = 0;
  32449. #ifdef SQLITE_TEST
  32450. int h = pFile->h;
  32451. #endif
  32452. assert( pFile );
  32453. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  32454. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  32455. osGetpid(0)));
  32456. assert( eFileLock<=SHARED_LOCK );
  32457. if( pFile->eFileLock<=eFileLock ){
  32458. return SQLITE_OK;
  32459. }
  32460. unixEnterMutex();
  32461. pInode = pFile->pInode;
  32462. assert( pInode->nShared!=0 );
  32463. if( pFile->eFileLock>SHARED_LOCK ){
  32464. assert( pInode->eFileLock==pFile->eFileLock );
  32465. SimulateIOErrorBenign(1);
  32466. SimulateIOError( h=(-1) )
  32467. SimulateIOErrorBenign(0);
  32468. #ifdef SQLITE_DEBUG
  32469. /* When reducing a lock such that other processes can start
  32470. ** reading the database file again, make sure that the
  32471. ** transaction counter was updated if any part of the database
  32472. ** file changed. If the transaction counter is not updated,
  32473. ** other connections to the same file might not realize that
  32474. ** the file has changed and hence might not know to flush their
  32475. ** cache. The use of a stale cache can lead to database corruption.
  32476. */
  32477. assert( pFile->inNormalWrite==0
  32478. || pFile->dbUpdate==0
  32479. || pFile->transCntrChng==1 );
  32480. pFile->inNormalWrite = 0;
  32481. #endif
  32482. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  32483. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  32484. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  32485. /* only re-establish the shared lock if necessary */
  32486. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  32487. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  32488. } else {
  32489. skipShared = 1;
  32490. }
  32491. }
  32492. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  32493. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  32494. }
  32495. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  32496. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  32497. if( !rc ){
  32498. context->reserved = 0;
  32499. }
  32500. }
  32501. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  32502. pInode->eFileLock = SHARED_LOCK;
  32503. }
  32504. }
  32505. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  32506. /* Decrement the shared lock counter. Release the lock using an
  32507. ** OS call only when all threads in this same process have released
  32508. ** the lock.
  32509. */
  32510. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  32511. pInode->nShared--;
  32512. if( pInode->nShared==0 ){
  32513. SimulateIOErrorBenign(1);
  32514. SimulateIOError( h=(-1) )
  32515. SimulateIOErrorBenign(0);
  32516. if( !skipShared ){
  32517. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  32518. }
  32519. if( !rc ){
  32520. pInode->eFileLock = NO_LOCK;
  32521. pFile->eFileLock = NO_LOCK;
  32522. }
  32523. }
  32524. if( rc==SQLITE_OK ){
  32525. pInode->nLock--;
  32526. assert( pInode->nLock>=0 );
  32527. if( pInode->nLock==0 ){
  32528. closePendingFds(pFile);
  32529. }
  32530. }
  32531. }
  32532. unixLeaveMutex();
  32533. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  32534. return rc;
  32535. }
  32536. /*
  32537. ** Close a file & cleanup AFP specific locking context
  32538. */
  32539. static int afpClose(sqlite3_file *id) {
  32540. int rc = SQLITE_OK;
  32541. unixFile *pFile = (unixFile*)id;
  32542. assert( id!=0 );
  32543. afpUnlock(id, NO_LOCK);
  32544. unixEnterMutex();
  32545. if( pFile->pInode && pFile->pInode->nLock ){
  32546. /* If there are outstanding locks, do not actually close the file just
  32547. ** yet because that would clear those locks. Instead, add the file
  32548. ** descriptor to pInode->aPending. It will be automatically closed when
  32549. ** the last lock is cleared.
  32550. */
  32551. setPendingFd(pFile);
  32552. }
  32553. releaseInodeInfo(pFile);
  32554. sqlite3_free(pFile->lockingContext);
  32555. rc = closeUnixFile(id);
  32556. unixLeaveMutex();
  32557. return rc;
  32558. }
  32559. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  32560. /*
  32561. ** The code above is the AFP lock implementation. The code is specific
  32562. ** to MacOSX and does not work on other unix platforms. No alternative
  32563. ** is available. If you don't compile for a mac, then the "unix-afp"
  32564. ** VFS is not available.
  32565. **
  32566. ********************* End of the AFP lock implementation **********************
  32567. ******************************************************************************/
  32568. /******************************************************************************
  32569. *************************** Begin NFS Locking ********************************/
  32570. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  32571. /*
  32572. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  32573. ** must be either NO_LOCK or SHARED_LOCK.
  32574. **
  32575. ** If the locking level of the file descriptor is already at or below
  32576. ** the requested locking level, this routine is a no-op.
  32577. */
  32578. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  32579. return posixUnlock(id, eFileLock, 1);
  32580. }
  32581. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  32582. /*
  32583. ** The code above is the NFS lock implementation. The code is specific
  32584. ** to MacOSX and does not work on other unix platforms. No alternative
  32585. ** is available.
  32586. **
  32587. ********************* End of the NFS lock implementation **********************
  32588. ******************************************************************************/
  32589. /******************************************************************************
  32590. **************** Non-locking sqlite3_file methods *****************************
  32591. **
  32592. ** The next division contains implementations for all methods of the
  32593. ** sqlite3_file object other than the locking methods. The locking
  32594. ** methods were defined in divisions above (one locking method per
  32595. ** division). Those methods that are common to all locking modes
  32596. ** are gather together into this division.
  32597. */
  32598. /*
  32599. ** Seek to the offset passed as the second argument, then read cnt
  32600. ** bytes into pBuf. Return the number of bytes actually read.
  32601. **
  32602. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  32603. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  32604. ** one system to another. Since SQLite does not define USE_PREAD
  32605. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  32606. ** See tickets #2741 and #2681.
  32607. **
  32608. ** To avoid stomping the errno value on a failed read the lastErrno value
  32609. ** is set before returning.
  32610. */
  32611. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  32612. int got;
  32613. int prior = 0;
  32614. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  32615. i64 newOffset;
  32616. #endif
  32617. TIMER_START;
  32618. assert( cnt==(cnt&0x1ffff) );
  32619. assert( id->h>2 );
  32620. do{
  32621. #if defined(USE_PREAD)
  32622. got = osPread(id->h, pBuf, cnt, offset);
  32623. SimulateIOError( got = -1 );
  32624. #elif defined(USE_PREAD64)
  32625. got = osPread64(id->h, pBuf, cnt, offset);
  32626. SimulateIOError( got = -1 );
  32627. #else
  32628. newOffset = lseek(id->h, offset, SEEK_SET);
  32629. SimulateIOError( newOffset = -1 );
  32630. if( newOffset<0 ){
  32631. storeLastErrno((unixFile*)id, errno);
  32632. return -1;
  32633. }
  32634. got = osRead(id->h, pBuf, cnt);
  32635. #endif
  32636. if( got==cnt ) break;
  32637. if( got<0 ){
  32638. if( errno==EINTR ){ got = 1; continue; }
  32639. prior = 0;
  32640. storeLastErrno((unixFile*)id, errno);
  32641. break;
  32642. }else if( got>0 ){
  32643. cnt -= got;
  32644. offset += got;
  32645. prior += got;
  32646. pBuf = (void*)(got + (char*)pBuf);
  32647. }
  32648. }while( got>0 );
  32649. TIMER_END;
  32650. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  32651. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  32652. return got+prior;
  32653. }
  32654. /*
  32655. ** Read data from a file into a buffer. Return SQLITE_OK if all
  32656. ** bytes were read successfully and SQLITE_IOERR if anything goes
  32657. ** wrong.
  32658. */
  32659. static int unixRead(
  32660. sqlite3_file *id,
  32661. void *pBuf,
  32662. int amt,
  32663. sqlite3_int64 offset
  32664. ){
  32665. unixFile *pFile = (unixFile *)id;
  32666. int got;
  32667. assert( id );
  32668. assert( offset>=0 );
  32669. assert( amt>0 );
  32670. /* If this is a database file (not a journal, master-journal or temp
  32671. ** file), the bytes in the locking range should never be read or written. */
  32672. #if 0
  32673. assert( pFile->pPreallocatedUnused==0
  32674. || offset>=PENDING_BYTE+512
  32675. || offset+amt<=PENDING_BYTE
  32676. );
  32677. #endif
  32678. #if SQLITE_MAX_MMAP_SIZE>0
  32679. /* Deal with as much of this read request as possible by transfering
  32680. ** data from the memory mapping using memcpy(). */
  32681. if( offset<pFile->mmapSize ){
  32682. if( offset+amt <= pFile->mmapSize ){
  32683. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  32684. return SQLITE_OK;
  32685. }else{
  32686. int nCopy = pFile->mmapSize - offset;
  32687. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  32688. pBuf = &((u8 *)pBuf)[nCopy];
  32689. amt -= nCopy;
  32690. offset += nCopy;
  32691. }
  32692. }
  32693. #endif
  32694. got = seekAndRead(pFile, offset, pBuf, amt);
  32695. if( got==amt ){
  32696. return SQLITE_OK;
  32697. }else if( got<0 ){
  32698. /* lastErrno set by seekAndRead */
  32699. return SQLITE_IOERR_READ;
  32700. }else{
  32701. storeLastErrno(pFile, 0); /* not a system error */
  32702. /* Unread parts of the buffer must be zero-filled */
  32703. memset(&((char*)pBuf)[got], 0, amt-got);
  32704. return SQLITE_IOERR_SHORT_READ;
  32705. }
  32706. }
  32707. /*
  32708. ** Attempt to seek the file-descriptor passed as the first argument to
  32709. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  32710. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  32711. ** return the actual number of bytes written (which may be less than
  32712. ** nBuf).
  32713. */
  32714. static int seekAndWriteFd(
  32715. int fd, /* File descriptor to write to */
  32716. i64 iOff, /* File offset to begin writing at */
  32717. const void *pBuf, /* Copy data from this buffer to the file */
  32718. int nBuf, /* Size of buffer pBuf in bytes */
  32719. int *piErrno /* OUT: Error number if error occurs */
  32720. ){
  32721. int rc = 0; /* Value returned by system call */
  32722. assert( nBuf==(nBuf&0x1ffff) );
  32723. assert( fd>2 );
  32724. assert( piErrno!=0 );
  32725. nBuf &= 0x1ffff;
  32726. TIMER_START;
  32727. #if defined(USE_PREAD)
  32728. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  32729. #elif defined(USE_PREAD64)
  32730. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  32731. #else
  32732. do{
  32733. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  32734. SimulateIOError( iSeek = -1 );
  32735. if( iSeek<0 ){
  32736. rc = -1;
  32737. break;
  32738. }
  32739. rc = osWrite(fd, pBuf, nBuf);
  32740. }while( rc<0 && errno==EINTR );
  32741. #endif
  32742. TIMER_END;
  32743. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  32744. if( rc<0 ) *piErrno = errno;
  32745. return rc;
  32746. }
  32747. /*
  32748. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  32749. ** Return the number of bytes actually read. Update the offset.
  32750. **
  32751. ** To avoid stomping the errno value on a failed write the lastErrno value
  32752. ** is set before returning.
  32753. */
  32754. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  32755. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  32756. }
  32757. /*
  32758. ** Write data from a buffer into a file. Return SQLITE_OK on success
  32759. ** or some other error code on failure.
  32760. */
  32761. static int unixWrite(
  32762. sqlite3_file *id,
  32763. const void *pBuf,
  32764. int amt,
  32765. sqlite3_int64 offset
  32766. ){
  32767. unixFile *pFile = (unixFile*)id;
  32768. int wrote = 0;
  32769. assert( id );
  32770. assert( amt>0 );
  32771. /* If this is a database file (not a journal, master-journal or temp
  32772. ** file), the bytes in the locking range should never be read or written. */
  32773. #if 0
  32774. assert( pFile->pPreallocatedUnused==0
  32775. || offset>=PENDING_BYTE+512
  32776. || offset+amt<=PENDING_BYTE
  32777. );
  32778. #endif
  32779. #ifdef SQLITE_DEBUG
  32780. /* If we are doing a normal write to a database file (as opposed to
  32781. ** doing a hot-journal rollback or a write to some file other than a
  32782. ** normal database file) then record the fact that the database
  32783. ** has changed. If the transaction counter is modified, record that
  32784. ** fact too.
  32785. */
  32786. if( pFile->inNormalWrite ){
  32787. pFile->dbUpdate = 1; /* The database has been modified */
  32788. if( offset<=24 && offset+amt>=27 ){
  32789. int rc;
  32790. char oldCntr[4];
  32791. SimulateIOErrorBenign(1);
  32792. rc = seekAndRead(pFile, 24, oldCntr, 4);
  32793. SimulateIOErrorBenign(0);
  32794. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  32795. pFile->transCntrChng = 1; /* The transaction counter has changed */
  32796. }
  32797. }
  32798. }
  32799. #endif
  32800. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  32801. /* Deal with as much of this write request as possible by transfering
  32802. ** data from the memory mapping using memcpy(). */
  32803. if( offset<pFile->mmapSize ){
  32804. if( offset+amt <= pFile->mmapSize ){
  32805. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  32806. return SQLITE_OK;
  32807. }else{
  32808. int nCopy = pFile->mmapSize - offset;
  32809. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  32810. pBuf = &((u8 *)pBuf)[nCopy];
  32811. amt -= nCopy;
  32812. offset += nCopy;
  32813. }
  32814. }
  32815. #endif
  32816. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  32817. amt -= wrote;
  32818. offset += wrote;
  32819. pBuf = &((char*)pBuf)[wrote];
  32820. }
  32821. SimulateIOError(( wrote=(-1), amt=1 ));
  32822. SimulateDiskfullError(( wrote=0, amt=1 ));
  32823. if( amt>wrote ){
  32824. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  32825. /* lastErrno set by seekAndWrite */
  32826. return SQLITE_IOERR_WRITE;
  32827. }else{
  32828. storeLastErrno(pFile, 0); /* not a system error */
  32829. return SQLITE_FULL;
  32830. }
  32831. }
  32832. return SQLITE_OK;
  32833. }
  32834. #ifdef SQLITE_TEST
  32835. /*
  32836. ** Count the number of fullsyncs and normal syncs. This is used to test
  32837. ** that syncs and fullsyncs are occurring at the right times.
  32838. */
  32839. SQLITE_API int sqlite3_sync_count = 0;
  32840. SQLITE_API int sqlite3_fullsync_count = 0;
  32841. #endif
  32842. /*
  32843. ** We do not trust systems to provide a working fdatasync(). Some do.
  32844. ** Others do no. To be safe, we will stick with the (slightly slower)
  32845. ** fsync(). If you know that your system does support fdatasync() correctly,
  32846. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  32847. */
  32848. #if !defined(fdatasync) && !HAVE_FDATASYNC
  32849. # define fdatasync fsync
  32850. #endif
  32851. /*
  32852. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  32853. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  32854. ** only available on Mac OS X. But that could change.
  32855. */
  32856. #ifdef F_FULLFSYNC
  32857. # define HAVE_FULLFSYNC 1
  32858. #else
  32859. # define HAVE_FULLFSYNC 0
  32860. #endif
  32861. /*
  32862. ** The fsync() system call does not work as advertised on many
  32863. ** unix systems. The following procedure is an attempt to make
  32864. ** it work better.
  32865. **
  32866. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  32867. ** for testing when we want to run through the test suite quickly.
  32868. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  32869. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  32870. ** or power failure will likely corrupt the database file.
  32871. **
  32872. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  32873. ** The idea behind dataOnly is that it should only write the file content
  32874. ** to disk, not the inode. We only set dataOnly if the file size is
  32875. ** unchanged since the file size is part of the inode. However,
  32876. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  32877. ** file size has changed. The only real difference between fdatasync()
  32878. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  32879. ** inode if the mtime or owner or other inode attributes have changed.
  32880. ** We only care about the file size, not the other file attributes, so
  32881. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  32882. ** So, we always use fdatasync() if it is available, regardless of
  32883. ** the value of the dataOnly flag.
  32884. */
  32885. static int full_fsync(int fd, int fullSync, int dataOnly){
  32886. int rc;
  32887. /* The following "ifdef/elif/else/" block has the same structure as
  32888. ** the one below. It is replicated here solely to avoid cluttering
  32889. ** up the real code with the UNUSED_PARAMETER() macros.
  32890. */
  32891. #ifdef SQLITE_NO_SYNC
  32892. UNUSED_PARAMETER(fd);
  32893. UNUSED_PARAMETER(fullSync);
  32894. UNUSED_PARAMETER(dataOnly);
  32895. #elif HAVE_FULLFSYNC
  32896. UNUSED_PARAMETER(dataOnly);
  32897. #else
  32898. UNUSED_PARAMETER(fullSync);
  32899. UNUSED_PARAMETER(dataOnly);
  32900. #endif
  32901. /* Record the number of times that we do a normal fsync() and
  32902. ** FULLSYNC. This is used during testing to verify that this procedure
  32903. ** gets called with the correct arguments.
  32904. */
  32905. #ifdef SQLITE_TEST
  32906. if( fullSync ) sqlite3_fullsync_count++;
  32907. sqlite3_sync_count++;
  32908. #endif
  32909. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  32910. ** no-op. But go ahead and call fstat() to validate the file
  32911. ** descriptor as we need a method to provoke a failure during
  32912. ** coverate testing.
  32913. */
  32914. #ifdef SQLITE_NO_SYNC
  32915. {
  32916. struct stat buf;
  32917. rc = osFstat(fd, &buf);
  32918. }
  32919. #elif HAVE_FULLFSYNC
  32920. if( fullSync ){
  32921. rc = osFcntl(fd, F_FULLFSYNC, 0);
  32922. }else{
  32923. rc = 1;
  32924. }
  32925. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  32926. ** It shouldn't be possible for fullfsync to fail on the local
  32927. ** file system (on OSX), so failure indicates that FULLFSYNC
  32928. ** isn't supported for this file system. So, attempt an fsync
  32929. ** and (for now) ignore the overhead of a superfluous fcntl call.
  32930. ** It'd be better to detect fullfsync support once and avoid
  32931. ** the fcntl call every time sync is called.
  32932. */
  32933. if( rc ) rc = fsync(fd);
  32934. #elif defined(__APPLE__)
  32935. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  32936. ** so currently we default to the macro that redefines fdatasync to fsync
  32937. */
  32938. rc = fsync(fd);
  32939. #else
  32940. rc = fdatasync(fd);
  32941. #if OS_VXWORKS
  32942. if( rc==-1 && errno==ENOTSUP ){
  32943. rc = fsync(fd);
  32944. }
  32945. #endif /* OS_VXWORKS */
  32946. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  32947. if( OS_VXWORKS && rc!= -1 ){
  32948. rc = 0;
  32949. }
  32950. return rc;
  32951. }
  32952. /*
  32953. ** Open a file descriptor to the directory containing file zFilename.
  32954. ** If successful, *pFd is set to the opened file descriptor and
  32955. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  32956. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  32957. ** value.
  32958. **
  32959. ** The directory file descriptor is used for only one thing - to
  32960. ** fsync() a directory to make sure file creation and deletion events
  32961. ** are flushed to disk. Such fsyncs are not needed on newer
  32962. ** journaling filesystems, but are required on older filesystems.
  32963. **
  32964. ** This routine can be overridden using the xSetSysCall interface.
  32965. ** The ability to override this routine was added in support of the
  32966. ** chromium sandbox. Opening a directory is a security risk (we are
  32967. ** told) so making it overrideable allows the chromium sandbox to
  32968. ** replace this routine with a harmless no-op. To make this routine
  32969. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  32970. ** *pFd set to a negative number.
  32971. **
  32972. ** If SQLITE_OK is returned, the caller is responsible for closing
  32973. ** the file descriptor *pFd using close().
  32974. */
  32975. static int openDirectory(const char *zFilename, int *pFd){
  32976. int ii;
  32977. int fd = -1;
  32978. char zDirname[MAX_PATHNAME+1];
  32979. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  32980. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  32981. if( ii>0 ){
  32982. zDirname[ii] = '\0';
  32983. }else{
  32984. if( zDirname[0]!='/' ) zDirname[0] = '.';
  32985. zDirname[1] = 0;
  32986. }
  32987. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  32988. if( fd>=0 ){
  32989. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  32990. }
  32991. *pFd = fd;
  32992. if( fd>=0 ) return SQLITE_OK;
  32993. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  32994. }
  32995. /*
  32996. ** Make sure all writes to a particular file are committed to disk.
  32997. **
  32998. ** If dataOnly==0 then both the file itself and its metadata (file
  32999. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  33000. ** file data is synced.
  33001. **
  33002. ** Under Unix, also make sure that the directory entry for the file
  33003. ** has been created by fsync-ing the directory that contains the file.
  33004. ** If we do not do this and we encounter a power failure, the directory
  33005. ** entry for the journal might not exist after we reboot. The next
  33006. ** SQLite to access the file will not know that the journal exists (because
  33007. ** the directory entry for the journal was never created) and the transaction
  33008. ** will not roll back - possibly leading to database corruption.
  33009. */
  33010. static int unixSync(sqlite3_file *id, int flags){
  33011. int rc;
  33012. unixFile *pFile = (unixFile*)id;
  33013. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  33014. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  33015. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  33016. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  33017. || (flags&0x0F)==SQLITE_SYNC_FULL
  33018. );
  33019. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  33020. ** line is to test that doing so does not cause any problems.
  33021. */
  33022. SimulateDiskfullError( return SQLITE_FULL );
  33023. assert( pFile );
  33024. OSTRACE(("SYNC %-3d\n", pFile->h));
  33025. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  33026. SimulateIOError( rc=1 );
  33027. if( rc ){
  33028. storeLastErrno(pFile, errno);
  33029. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  33030. }
  33031. /* Also fsync the directory containing the file if the DIRSYNC flag
  33032. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  33033. ** are unable to fsync a directory, so ignore errors on the fsync.
  33034. */
  33035. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  33036. int dirfd;
  33037. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  33038. HAVE_FULLFSYNC, isFullsync));
  33039. rc = osOpenDirectory(pFile->zPath, &dirfd);
  33040. if( rc==SQLITE_OK ){
  33041. full_fsync(dirfd, 0, 0);
  33042. robust_close(pFile, dirfd, __LINE__);
  33043. }else{
  33044. assert( rc==SQLITE_CANTOPEN );
  33045. rc = SQLITE_OK;
  33046. }
  33047. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  33048. }
  33049. return rc;
  33050. }
  33051. /*
  33052. ** Truncate an open file to a specified size
  33053. */
  33054. static int unixTruncate(sqlite3_file *id, i64 nByte){
  33055. unixFile *pFile = (unixFile *)id;
  33056. int rc;
  33057. assert( pFile );
  33058. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  33059. /* If the user has configured a chunk-size for this file, truncate the
  33060. ** file so that it consists of an integer number of chunks (i.e. the
  33061. ** actual file size after the operation may be larger than the requested
  33062. ** size).
  33063. */
  33064. if( pFile->szChunk>0 ){
  33065. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  33066. }
  33067. rc = robust_ftruncate(pFile->h, nByte);
  33068. if( rc ){
  33069. storeLastErrno(pFile, errno);
  33070. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  33071. }else{
  33072. #ifdef SQLITE_DEBUG
  33073. /* If we are doing a normal write to a database file (as opposed to
  33074. ** doing a hot-journal rollback or a write to some file other than a
  33075. ** normal database file) and we truncate the file to zero length,
  33076. ** that effectively updates the change counter. This might happen
  33077. ** when restoring a database using the backup API from a zero-length
  33078. ** source.
  33079. */
  33080. if( pFile->inNormalWrite && nByte==0 ){
  33081. pFile->transCntrChng = 1;
  33082. }
  33083. #endif
  33084. #if SQLITE_MAX_MMAP_SIZE>0
  33085. /* If the file was just truncated to a size smaller than the currently
  33086. ** mapped region, reduce the effective mapping size as well. SQLite will
  33087. ** use read() and write() to access data beyond this point from now on.
  33088. */
  33089. if( nByte<pFile->mmapSize ){
  33090. pFile->mmapSize = nByte;
  33091. }
  33092. #endif
  33093. return SQLITE_OK;
  33094. }
  33095. }
  33096. /*
  33097. ** Determine the current size of a file in bytes
  33098. */
  33099. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  33100. int rc;
  33101. struct stat buf;
  33102. assert( id );
  33103. rc = osFstat(((unixFile*)id)->h, &buf);
  33104. SimulateIOError( rc=1 );
  33105. if( rc!=0 ){
  33106. storeLastErrno((unixFile*)id, errno);
  33107. return SQLITE_IOERR_FSTAT;
  33108. }
  33109. *pSize = buf.st_size;
  33110. /* When opening a zero-size database, the findInodeInfo() procedure
  33111. ** writes a single byte into that file in order to work around a bug
  33112. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  33113. ** layers, we need to report this file size as zero even though it is
  33114. ** really 1. Ticket #3260.
  33115. */
  33116. if( *pSize==1 ) *pSize = 0;
  33117. return SQLITE_OK;
  33118. }
  33119. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33120. /*
  33121. ** Handler for proxy-locking file-control verbs. Defined below in the
  33122. ** proxying locking division.
  33123. */
  33124. static int proxyFileControl(sqlite3_file*,int,void*);
  33125. #endif
  33126. /*
  33127. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  33128. ** file-control operation. Enlarge the database to nBytes in size
  33129. ** (rounded up to the next chunk-size). If the database is already
  33130. ** nBytes or larger, this routine is a no-op.
  33131. */
  33132. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  33133. if( pFile->szChunk>0 ){
  33134. i64 nSize; /* Required file size */
  33135. struct stat buf; /* Used to hold return values of fstat() */
  33136. if( osFstat(pFile->h, &buf) ){
  33137. return SQLITE_IOERR_FSTAT;
  33138. }
  33139. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  33140. if( nSize>(i64)buf.st_size ){
  33141. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  33142. /* The code below is handling the return value of osFallocate()
  33143. ** correctly. posix_fallocate() is defined to "returns zero on success,
  33144. ** or an error number on failure". See the manpage for details. */
  33145. int err;
  33146. do{
  33147. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  33148. }while( err==EINTR );
  33149. if( err ) return SQLITE_IOERR_WRITE;
  33150. #else
  33151. /* If the OS does not have posix_fallocate(), fake it. Write a
  33152. ** single byte to the last byte in each block that falls entirely
  33153. ** within the extended region. Then, if required, a single byte
  33154. ** at offset (nSize-1), to set the size of the file correctly.
  33155. ** This is a similar technique to that used by glibc on systems
  33156. ** that do not have a real fallocate() call.
  33157. */
  33158. int nBlk = buf.st_blksize; /* File-system block size */
  33159. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  33160. i64 iWrite; /* Next offset to write to */
  33161. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  33162. assert( iWrite>=buf.st_size );
  33163. assert( ((iWrite+1)%nBlk)==0 );
  33164. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  33165. if( iWrite>=nSize ) iWrite = nSize - 1;
  33166. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  33167. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  33168. }
  33169. #endif
  33170. }
  33171. }
  33172. #if SQLITE_MAX_MMAP_SIZE>0
  33173. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  33174. int rc;
  33175. if( pFile->szChunk<=0 ){
  33176. if( robust_ftruncate(pFile->h, nByte) ){
  33177. storeLastErrno(pFile, errno);
  33178. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  33179. }
  33180. }
  33181. rc = unixMapfile(pFile, nByte);
  33182. return rc;
  33183. }
  33184. #endif
  33185. return SQLITE_OK;
  33186. }
  33187. /*
  33188. ** If *pArg is initially negative then this is a query. Set *pArg to
  33189. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  33190. **
  33191. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  33192. */
  33193. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  33194. if( *pArg<0 ){
  33195. *pArg = (pFile->ctrlFlags & mask)!=0;
  33196. }else if( (*pArg)==0 ){
  33197. pFile->ctrlFlags &= ~mask;
  33198. }else{
  33199. pFile->ctrlFlags |= mask;
  33200. }
  33201. }
  33202. /* Forward declaration */
  33203. static int unixGetTempname(int nBuf, char *zBuf);
  33204. /*
  33205. ** Information and control of an open file handle.
  33206. */
  33207. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  33208. unixFile *pFile = (unixFile*)id;
  33209. switch( op ){
  33210. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  33211. case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
  33212. int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
  33213. return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
  33214. }
  33215. case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
  33216. int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
  33217. return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
  33218. }
  33219. case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
  33220. int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
  33221. return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
  33222. }
  33223. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  33224. case SQLITE_FCNTL_LOCKSTATE: {
  33225. *(int*)pArg = pFile->eFileLock;
  33226. return SQLITE_OK;
  33227. }
  33228. case SQLITE_FCNTL_LAST_ERRNO: {
  33229. *(int*)pArg = pFile->lastErrno;
  33230. return SQLITE_OK;
  33231. }
  33232. case SQLITE_FCNTL_CHUNK_SIZE: {
  33233. pFile->szChunk = *(int *)pArg;
  33234. return SQLITE_OK;
  33235. }
  33236. case SQLITE_FCNTL_SIZE_HINT: {
  33237. int rc;
  33238. SimulateIOErrorBenign(1);
  33239. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  33240. SimulateIOErrorBenign(0);
  33241. return rc;
  33242. }
  33243. case SQLITE_FCNTL_PERSIST_WAL: {
  33244. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  33245. return SQLITE_OK;
  33246. }
  33247. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  33248. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  33249. return SQLITE_OK;
  33250. }
  33251. case SQLITE_FCNTL_VFSNAME: {
  33252. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  33253. return SQLITE_OK;
  33254. }
  33255. case SQLITE_FCNTL_TEMPFILENAME: {
  33256. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  33257. if( zTFile ){
  33258. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  33259. *(char**)pArg = zTFile;
  33260. }
  33261. return SQLITE_OK;
  33262. }
  33263. case SQLITE_FCNTL_HAS_MOVED: {
  33264. *(int*)pArg = fileHasMoved(pFile);
  33265. return SQLITE_OK;
  33266. }
  33267. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  33268. case SQLITE_FCNTL_LOCK_TIMEOUT: {
  33269. pFile->iBusyTimeout = *(int*)pArg;
  33270. return SQLITE_OK;
  33271. }
  33272. #endif
  33273. #if SQLITE_MAX_MMAP_SIZE>0
  33274. case SQLITE_FCNTL_MMAP_SIZE: {
  33275. i64 newLimit = *(i64*)pArg;
  33276. int rc = SQLITE_OK;
  33277. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  33278. newLimit = sqlite3GlobalConfig.mxMmap;
  33279. }
  33280. /* The value of newLimit may be eventually cast to (size_t) and passed
  33281. ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
  33282. ** 64-bit type. */
  33283. if( newLimit>0 && sizeof(size_t)<8 ){
  33284. newLimit = (newLimit & 0x7FFFFFFF);
  33285. }
  33286. *(i64*)pArg = pFile->mmapSizeMax;
  33287. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  33288. pFile->mmapSizeMax = newLimit;
  33289. if( pFile->mmapSize>0 ){
  33290. unixUnmapfile(pFile);
  33291. rc = unixMapfile(pFile, -1);
  33292. }
  33293. }
  33294. return rc;
  33295. }
  33296. #endif
  33297. #ifdef SQLITE_DEBUG
  33298. /* The pager calls this method to signal that it has done
  33299. ** a rollback and that the database is therefore unchanged and
  33300. ** it hence it is OK for the transaction change counter to be
  33301. ** unchanged.
  33302. */
  33303. case SQLITE_FCNTL_DB_UNCHANGED: {
  33304. ((unixFile*)id)->dbUpdate = 0;
  33305. return SQLITE_OK;
  33306. }
  33307. #endif
  33308. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  33309. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  33310. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  33311. return proxyFileControl(id,op,pArg);
  33312. }
  33313. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  33314. }
  33315. return SQLITE_NOTFOUND;
  33316. }
  33317. /*
  33318. ** If pFd->sectorSize is non-zero when this function is called, it is a
  33319. ** no-op. Otherwise, the values of pFd->sectorSize and
  33320. ** pFd->deviceCharacteristics are set according to the file-system
  33321. ** characteristics.
  33322. **
  33323. ** There are two versions of this function. One for QNX and one for all
  33324. ** other systems.
  33325. */
  33326. #ifndef __QNXNTO__
  33327. static void setDeviceCharacteristics(unixFile *pFd){
  33328. assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
  33329. if( pFd->sectorSize==0 ){
  33330. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  33331. int res;
  33332. u32 f = 0;
  33333. /* Check for support for F2FS atomic batch writes. */
  33334. res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
  33335. if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
  33336. pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
  33337. }
  33338. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  33339. /* Set the POWERSAFE_OVERWRITE flag if requested. */
  33340. if( pFd->ctrlFlags & UNIXFILE_PSOW ){
  33341. pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  33342. }
  33343. pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  33344. }
  33345. }
  33346. #else
  33347. #include <sys/dcmd_blk.h>
  33348. #include <sys/statvfs.h>
  33349. static void setDeviceCharacteristics(unixFile *pFile){
  33350. if( pFile->sectorSize == 0 ){
  33351. struct statvfs fsInfo;
  33352. /* Set defaults for non-supported filesystems */
  33353. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  33354. pFile->deviceCharacteristics = 0;
  33355. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  33356. return;
  33357. }
  33358. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  33359. pFile->sectorSize = fsInfo.f_bsize;
  33360. pFile->deviceCharacteristics =
  33361. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  33362. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  33363. ** the write succeeds */
  33364. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  33365. ** so it is ordered */
  33366. 0;
  33367. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  33368. pFile->sectorSize = fsInfo.f_bsize;
  33369. pFile->deviceCharacteristics =
  33370. /* etfs cluster size writes are atomic */
  33371. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  33372. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  33373. ** the write succeeds */
  33374. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  33375. ** so it is ordered */
  33376. 0;
  33377. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  33378. pFile->sectorSize = fsInfo.f_bsize;
  33379. pFile->deviceCharacteristics =
  33380. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  33381. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  33382. ** the write succeeds */
  33383. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  33384. ** so it is ordered */
  33385. 0;
  33386. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  33387. pFile->sectorSize = fsInfo.f_bsize;
  33388. pFile->deviceCharacteristics =
  33389. /* full bitset of atomics from max sector size and smaller */
  33390. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  33391. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  33392. ** so it is ordered */
  33393. 0;
  33394. }else if( strstr(fsInfo.f_basetype, "dos") ){
  33395. pFile->sectorSize = fsInfo.f_bsize;
  33396. pFile->deviceCharacteristics =
  33397. /* full bitset of atomics from max sector size and smaller */
  33398. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  33399. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  33400. ** so it is ordered */
  33401. 0;
  33402. }else{
  33403. pFile->deviceCharacteristics =
  33404. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  33405. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  33406. ** the write succeeds */
  33407. 0;
  33408. }
  33409. }
  33410. /* Last chance verification. If the sector size isn't a multiple of 512
  33411. ** then it isn't valid.*/
  33412. if( pFile->sectorSize % 512 != 0 ){
  33413. pFile->deviceCharacteristics = 0;
  33414. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  33415. }
  33416. }
  33417. #endif
  33418. /*
  33419. ** Return the sector size in bytes of the underlying block device for
  33420. ** the specified file. This is almost always 512 bytes, but may be
  33421. ** larger for some devices.
  33422. **
  33423. ** SQLite code assumes this function cannot fail. It also assumes that
  33424. ** if two files are created in the same file-system directory (i.e.
  33425. ** a database and its journal file) that the sector size will be the
  33426. ** same for both.
  33427. */
  33428. static int unixSectorSize(sqlite3_file *id){
  33429. unixFile *pFd = (unixFile*)id;
  33430. setDeviceCharacteristics(pFd);
  33431. return pFd->sectorSize;
  33432. }
  33433. /*
  33434. ** Return the device characteristics for the file.
  33435. **
  33436. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  33437. ** However, that choice is controversial since technically the underlying
  33438. ** file system does not always provide powersafe overwrites. (In other
  33439. ** words, after a power-loss event, parts of the file that were never
  33440. ** written might end up being altered.) However, non-PSOW behavior is very,
  33441. ** very rare. And asserting PSOW makes a large reduction in the amount
  33442. ** of required I/O for journaling, since a lot of padding is eliminated.
  33443. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  33444. ** available to turn it off and URI query parameter available to turn it off.
  33445. */
  33446. static int unixDeviceCharacteristics(sqlite3_file *id){
  33447. unixFile *pFd = (unixFile*)id;
  33448. setDeviceCharacteristics(pFd);
  33449. return pFd->deviceCharacteristics;
  33450. }
  33451. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  33452. /*
  33453. ** Return the system page size.
  33454. **
  33455. ** This function should not be called directly by other code in this file.
  33456. ** Instead, it should be called via macro osGetpagesize().
  33457. */
  33458. static int unixGetpagesize(void){
  33459. #if OS_VXWORKS
  33460. return 1024;
  33461. #elif defined(_BSD_SOURCE)
  33462. return getpagesize();
  33463. #else
  33464. return (int)sysconf(_SC_PAGESIZE);
  33465. #endif
  33466. }
  33467. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  33468. #ifndef SQLITE_OMIT_WAL
  33469. /*
  33470. ** Object used to represent an shared memory buffer.
  33471. **
  33472. ** When multiple threads all reference the same wal-index, each thread
  33473. ** has its own unixShm object, but they all point to a single instance
  33474. ** of this unixShmNode object. In other words, each wal-index is opened
  33475. ** only once per process.
  33476. **
  33477. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  33478. ** We could coalesce this object into unixInodeInfo, but that would mean
  33479. ** every open file that does not use shared memory (in other words, most
  33480. ** open files) would have to carry around this extra information. So
  33481. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  33482. ** and the unixShmNode object is created only when needed.
  33483. **
  33484. ** unixMutexHeld() must be true when creating or destroying
  33485. ** this object or while reading or writing the following fields:
  33486. **
  33487. ** nRef
  33488. **
  33489. ** The following fields are read-only after the object is created:
  33490. **
  33491. ** fid
  33492. ** zFilename
  33493. **
  33494. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  33495. ** unixMutexHeld() is true when reading or writing any other field
  33496. ** in this structure.
  33497. */
  33498. struct unixShmNode {
  33499. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  33500. sqlite3_mutex *mutex; /* Mutex to access this object */
  33501. char *zFilename; /* Name of the mmapped file */
  33502. int h; /* Open file descriptor */
  33503. int szRegion; /* Size of shared-memory regions */
  33504. u16 nRegion; /* Size of array apRegion */
  33505. u8 isReadonly; /* True if read-only */
  33506. u8 isUnlocked; /* True if no DMS lock held */
  33507. char **apRegion; /* Array of mapped shared-memory regions */
  33508. int nRef; /* Number of unixShm objects pointing to this */
  33509. unixShm *pFirst; /* All unixShm objects pointing to this */
  33510. #ifdef SQLITE_DEBUG
  33511. u8 exclMask; /* Mask of exclusive locks held */
  33512. u8 sharedMask; /* Mask of shared locks held */
  33513. u8 nextShmId; /* Next available unixShm.id value */
  33514. #endif
  33515. };
  33516. /*
  33517. ** Structure used internally by this VFS to record the state of an
  33518. ** open shared memory connection.
  33519. **
  33520. ** The following fields are initialized when this object is created and
  33521. ** are read-only thereafter:
  33522. **
  33523. ** unixShm.pFile
  33524. ** unixShm.id
  33525. **
  33526. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  33527. ** while accessing any read/write fields.
  33528. */
  33529. struct unixShm {
  33530. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  33531. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  33532. u8 hasMutex; /* True if holding the unixShmNode mutex */
  33533. u8 id; /* Id of this connection within its unixShmNode */
  33534. u16 sharedMask; /* Mask of shared locks held */
  33535. u16 exclMask; /* Mask of exclusive locks held */
  33536. };
  33537. /*
  33538. ** Constants used for locking
  33539. */
  33540. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  33541. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  33542. /*
  33543. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  33544. **
  33545. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  33546. ** otherwise.
  33547. */
  33548. static int unixShmSystemLock(
  33549. unixFile *pFile, /* Open connection to the WAL file */
  33550. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  33551. int ofst, /* First byte of the locking range */
  33552. int n /* Number of bytes to lock */
  33553. ){
  33554. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  33555. struct flock f; /* The posix advisory locking structure */
  33556. int rc = SQLITE_OK; /* Result code form fcntl() */
  33557. /* Access to the unixShmNode object is serialized by the caller */
  33558. pShmNode = pFile->pInode->pShmNode;
  33559. assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->mutex) );
  33560. /* Shared locks never span more than one byte */
  33561. assert( n==1 || lockType!=F_RDLCK );
  33562. /* Locks are within range */
  33563. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  33564. if( pShmNode->h>=0 ){
  33565. /* Initialize the locking parameters */
  33566. f.l_type = lockType;
  33567. f.l_whence = SEEK_SET;
  33568. f.l_start = ofst;
  33569. f.l_len = n;
  33570. rc = osSetPosixAdvisoryLock(pShmNode->h, &f, pFile);
  33571. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  33572. }
  33573. /* Update the global lock state and do debug tracing */
  33574. #ifdef SQLITE_DEBUG
  33575. { u16 mask;
  33576. OSTRACE(("SHM-LOCK "));
  33577. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  33578. if( rc==SQLITE_OK ){
  33579. if( lockType==F_UNLCK ){
  33580. OSTRACE(("unlock %d ok", ofst));
  33581. pShmNode->exclMask &= ~mask;
  33582. pShmNode->sharedMask &= ~mask;
  33583. }else if( lockType==F_RDLCK ){
  33584. OSTRACE(("read-lock %d ok", ofst));
  33585. pShmNode->exclMask &= ~mask;
  33586. pShmNode->sharedMask |= mask;
  33587. }else{
  33588. assert( lockType==F_WRLCK );
  33589. OSTRACE(("write-lock %d ok", ofst));
  33590. pShmNode->exclMask |= mask;
  33591. pShmNode->sharedMask &= ~mask;
  33592. }
  33593. }else{
  33594. if( lockType==F_UNLCK ){
  33595. OSTRACE(("unlock %d failed", ofst));
  33596. }else if( lockType==F_RDLCK ){
  33597. OSTRACE(("read-lock failed"));
  33598. }else{
  33599. assert( lockType==F_WRLCK );
  33600. OSTRACE(("write-lock %d failed", ofst));
  33601. }
  33602. }
  33603. OSTRACE((" - afterwards %03x,%03x\n",
  33604. pShmNode->sharedMask, pShmNode->exclMask));
  33605. }
  33606. #endif
  33607. return rc;
  33608. }
  33609. /*
  33610. ** Return the minimum number of 32KB shm regions that should be mapped at
  33611. ** a time, assuming that each mapping must be an integer multiple of the
  33612. ** current system page-size.
  33613. **
  33614. ** Usually, this is 1. The exception seems to be systems that are configured
  33615. ** to use 64KB pages - in this case each mapping must cover at least two
  33616. ** shm regions.
  33617. */
  33618. static int unixShmRegionPerMap(void){
  33619. int shmsz = 32*1024; /* SHM region size */
  33620. int pgsz = osGetpagesize(); /* System page size */
  33621. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  33622. if( pgsz<shmsz ) return 1;
  33623. return pgsz/shmsz;
  33624. }
  33625. /*
  33626. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  33627. **
  33628. ** This is not a VFS shared-memory method; it is a utility function called
  33629. ** by VFS shared-memory methods.
  33630. */
  33631. static void unixShmPurge(unixFile *pFd){
  33632. unixShmNode *p = pFd->pInode->pShmNode;
  33633. assert( unixMutexHeld() );
  33634. if( p && ALWAYS(p->nRef==0) ){
  33635. int nShmPerMap = unixShmRegionPerMap();
  33636. int i;
  33637. assert( p->pInode==pFd->pInode );
  33638. sqlite3_mutex_free(p->mutex);
  33639. for(i=0; i<p->nRegion; i+=nShmPerMap){
  33640. if( p->h>=0 ){
  33641. osMunmap(p->apRegion[i], p->szRegion);
  33642. }else{
  33643. sqlite3_free(p->apRegion[i]);
  33644. }
  33645. }
  33646. sqlite3_free(p->apRegion);
  33647. if( p->h>=0 ){
  33648. robust_close(pFd, p->h, __LINE__);
  33649. p->h = -1;
  33650. }
  33651. p->pInode->pShmNode = 0;
  33652. sqlite3_free(p);
  33653. }
  33654. }
  33655. /*
  33656. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  33657. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  33658. ** code otherwise.
  33659. **
  33660. ** If the DMS cannot be locked because this is a readonly_shm=1
  33661. ** connection and no other process already holds a lock, return
  33662. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  33663. */
  33664. static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
  33665. struct flock lock;
  33666. int rc = SQLITE_OK;
  33667. /* Use F_GETLK to determine the locks other processes are holding
  33668. ** on the DMS byte. If it indicates that another process is holding
  33669. ** a SHARED lock, then this process may also take a SHARED lock
  33670. ** and proceed with opening the *-shm file.
  33671. **
  33672. ** Or, if no other process is holding any lock, then this process
  33673. ** is the first to open it. In this case take an EXCLUSIVE lock on the
  33674. ** DMS byte and truncate the *-shm file to zero bytes in size. Then
  33675. ** downgrade to a SHARED lock on the DMS byte.
  33676. **
  33677. ** If another process is holding an EXCLUSIVE lock on the DMS byte,
  33678. ** return SQLITE_BUSY to the caller (it will try again). An earlier
  33679. ** version of this code attempted the SHARED lock at this point. But
  33680. ** this introduced a subtle race condition: if the process holding
  33681. ** EXCLUSIVE failed just before truncating the *-shm file, then this
  33682. ** process might open and use the *-shm file without truncating it.
  33683. ** And if the *-shm file has been corrupted by a power failure or
  33684. ** system crash, the database itself may also become corrupt. */
  33685. lock.l_whence = SEEK_SET;
  33686. lock.l_start = UNIX_SHM_DMS;
  33687. lock.l_len = 1;
  33688. lock.l_type = F_WRLCK;
  33689. if( osFcntl(pShmNode->h, F_GETLK, &lock)!=0 ) {
  33690. rc = SQLITE_IOERR_LOCK;
  33691. }else if( lock.l_type==F_UNLCK ){
  33692. if( pShmNode->isReadonly ){
  33693. pShmNode->isUnlocked = 1;
  33694. rc = SQLITE_READONLY_CANTINIT;
  33695. }else{
  33696. rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
  33697. if( rc==SQLITE_OK && robust_ftruncate(pShmNode->h, 0) ){
  33698. rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
  33699. }
  33700. }
  33701. }else if( lock.l_type==F_WRLCK ){
  33702. rc = SQLITE_BUSY;
  33703. }
  33704. if( rc==SQLITE_OK ){
  33705. assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
  33706. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  33707. }
  33708. return rc;
  33709. }
  33710. /*
  33711. ** Open a shared-memory area associated with open database file pDbFd.
  33712. ** This particular implementation uses mmapped files.
  33713. **
  33714. ** The file used to implement shared-memory is in the same directory
  33715. ** as the open database file and has the same name as the open database
  33716. ** file with the "-shm" suffix added. For example, if the database file
  33717. ** is "/home/user1/config.db" then the file that is created and mmapped
  33718. ** for shared memory will be called "/home/user1/config.db-shm".
  33719. **
  33720. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  33721. ** some other tmpfs mount. But if a file in a different directory
  33722. ** from the database file is used, then differing access permissions
  33723. ** or a chroot() might cause two different processes on the same
  33724. ** database to end up using different files for shared memory -
  33725. ** meaning that their memory would not really be shared - resulting
  33726. ** in database corruption. Nevertheless, this tmpfs file usage
  33727. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  33728. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  33729. ** option results in an incompatible build of SQLite; builds of SQLite
  33730. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  33731. ** same database file at the same time, database corruption will likely
  33732. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  33733. ** "unsupported" and may go away in a future SQLite release.
  33734. **
  33735. ** When opening a new shared-memory file, if no other instances of that
  33736. ** file are currently open, in this process or in other processes, then
  33737. ** the file must be truncated to zero length or have its header cleared.
  33738. **
  33739. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  33740. ** that means that an exclusive lock is held on the database file and
  33741. ** that no other processes are able to read or write the database. In
  33742. ** that case, we do not really need shared memory. No shared memory
  33743. ** file is created. The shared memory will be simulated with heap memory.
  33744. */
  33745. static int unixOpenSharedMemory(unixFile *pDbFd){
  33746. struct unixShm *p = 0; /* The connection to be opened */
  33747. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  33748. int rc = SQLITE_OK; /* Result code */
  33749. unixInodeInfo *pInode; /* The inode of fd */
  33750. char *zShm; /* Name of the file used for SHM */
  33751. int nShmFilename; /* Size of the SHM filename in bytes */
  33752. /* Allocate space for the new unixShm object. */
  33753. p = sqlite3_malloc64( sizeof(*p) );
  33754. if( p==0 ) return SQLITE_NOMEM_BKPT;
  33755. memset(p, 0, sizeof(*p));
  33756. assert( pDbFd->pShm==0 );
  33757. /* Check to see if a unixShmNode object already exists. Reuse an existing
  33758. ** one if present. Create a new one if necessary.
  33759. */
  33760. unixEnterMutex();
  33761. pInode = pDbFd->pInode;
  33762. pShmNode = pInode->pShmNode;
  33763. if( pShmNode==0 ){
  33764. struct stat sStat; /* fstat() info for database file */
  33765. #ifndef SQLITE_SHM_DIRECTORY
  33766. const char *zBasePath = pDbFd->zPath;
  33767. #endif
  33768. /* Call fstat() to figure out the permissions on the database file. If
  33769. ** a new *-shm file is created, an attempt will be made to create it
  33770. ** with the same permissions.
  33771. */
  33772. if( osFstat(pDbFd->h, &sStat) ){
  33773. rc = SQLITE_IOERR_FSTAT;
  33774. goto shm_open_err;
  33775. }
  33776. #ifdef SQLITE_SHM_DIRECTORY
  33777. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  33778. #else
  33779. nShmFilename = 6 + (int)strlen(zBasePath);
  33780. #endif
  33781. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  33782. if( pShmNode==0 ){
  33783. rc = SQLITE_NOMEM_BKPT;
  33784. goto shm_open_err;
  33785. }
  33786. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  33787. zShm = pShmNode->zFilename = (char*)&pShmNode[1];
  33788. #ifdef SQLITE_SHM_DIRECTORY
  33789. sqlite3_snprintf(nShmFilename, zShm,
  33790. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  33791. (u32)sStat.st_ino, (u32)sStat.st_dev);
  33792. #else
  33793. sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
  33794. sqlite3FileSuffix3(pDbFd->zPath, zShm);
  33795. #endif
  33796. pShmNode->h = -1;
  33797. pDbFd->pInode->pShmNode = pShmNode;
  33798. pShmNode->pInode = pDbFd->pInode;
  33799. if( sqlite3GlobalConfig.bCoreMutex ){
  33800. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  33801. if( pShmNode->mutex==0 ){
  33802. rc = SQLITE_NOMEM_BKPT;
  33803. goto shm_open_err;
  33804. }
  33805. }
  33806. if( pInode->bProcessLock==0 ){
  33807. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  33808. pShmNode->h = robust_open(zShm, O_RDWR|O_CREAT, (sStat.st_mode&0777));
  33809. }
  33810. if( pShmNode->h<0 ){
  33811. pShmNode->h = robust_open(zShm, O_RDONLY, (sStat.st_mode&0777));
  33812. if( pShmNode->h<0 ){
  33813. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
  33814. goto shm_open_err;
  33815. }
  33816. pShmNode->isReadonly = 1;
  33817. }
  33818. /* If this process is running as root, make sure that the SHM file
  33819. ** is owned by the same user that owns the original database. Otherwise,
  33820. ** the original owner will not be able to connect.
  33821. */
  33822. robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  33823. rc = unixLockSharedMemory(pDbFd, pShmNode);
  33824. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  33825. }
  33826. }
  33827. /* Make the new connection a child of the unixShmNode */
  33828. p->pShmNode = pShmNode;
  33829. #ifdef SQLITE_DEBUG
  33830. p->id = pShmNode->nextShmId++;
  33831. #endif
  33832. pShmNode->nRef++;
  33833. pDbFd->pShm = p;
  33834. unixLeaveMutex();
  33835. /* The reference count on pShmNode has already been incremented under
  33836. ** the cover of the unixEnterMutex() mutex and the pointer from the
  33837. ** new (struct unixShm) object to the pShmNode has been set. All that is
  33838. ** left to do is to link the new object into the linked list starting
  33839. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  33840. ** mutex.
  33841. */
  33842. sqlite3_mutex_enter(pShmNode->mutex);
  33843. p->pNext = pShmNode->pFirst;
  33844. pShmNode->pFirst = p;
  33845. sqlite3_mutex_leave(pShmNode->mutex);
  33846. return rc;
  33847. /* Jump here on any error */
  33848. shm_open_err:
  33849. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  33850. sqlite3_free(p);
  33851. unixLeaveMutex();
  33852. return rc;
  33853. }
  33854. /*
  33855. ** This function is called to obtain a pointer to region iRegion of the
  33856. ** shared-memory associated with the database file fd. Shared-memory regions
  33857. ** are numbered starting from zero. Each shared-memory region is szRegion
  33858. ** bytes in size.
  33859. **
  33860. ** If an error occurs, an error code is returned and *pp is set to NULL.
  33861. **
  33862. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  33863. ** region has not been allocated (by any client, including one running in a
  33864. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  33865. ** bExtend is non-zero and the requested shared-memory region has not yet
  33866. ** been allocated, it is allocated by this function.
  33867. **
  33868. ** If the shared-memory region has already been allocated or is allocated by
  33869. ** this call as described above, then it is mapped into this processes
  33870. ** address space (if it is not already), *pp is set to point to the mapped
  33871. ** memory and SQLITE_OK returned.
  33872. */
  33873. static int unixShmMap(
  33874. sqlite3_file *fd, /* Handle open on database file */
  33875. int iRegion, /* Region to retrieve */
  33876. int szRegion, /* Size of regions */
  33877. int bExtend, /* True to extend file if necessary */
  33878. void volatile **pp /* OUT: Mapped memory */
  33879. ){
  33880. unixFile *pDbFd = (unixFile*)fd;
  33881. unixShm *p;
  33882. unixShmNode *pShmNode;
  33883. int rc = SQLITE_OK;
  33884. int nShmPerMap = unixShmRegionPerMap();
  33885. int nReqRegion;
  33886. /* If the shared-memory file has not yet been opened, open it now. */
  33887. if( pDbFd->pShm==0 ){
  33888. rc = unixOpenSharedMemory(pDbFd);
  33889. if( rc!=SQLITE_OK ) return rc;
  33890. }
  33891. p = pDbFd->pShm;
  33892. pShmNode = p->pShmNode;
  33893. sqlite3_mutex_enter(pShmNode->mutex);
  33894. if( pShmNode->isUnlocked ){
  33895. rc = unixLockSharedMemory(pDbFd, pShmNode);
  33896. if( rc!=SQLITE_OK ) goto shmpage_out;
  33897. pShmNode->isUnlocked = 0;
  33898. }
  33899. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  33900. assert( pShmNode->pInode==pDbFd->pInode );
  33901. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  33902. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  33903. /* Minimum number of regions required to be mapped. */
  33904. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  33905. if( pShmNode->nRegion<nReqRegion ){
  33906. char **apNew; /* New apRegion[] array */
  33907. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  33908. struct stat sStat; /* Used by fstat() */
  33909. pShmNode->szRegion = szRegion;
  33910. if( pShmNode->h>=0 ){
  33911. /* The requested region is not mapped into this processes address space.
  33912. ** Check to see if it has been allocated (i.e. if the wal-index file is
  33913. ** large enough to contain the requested region).
  33914. */
  33915. if( osFstat(pShmNode->h, &sStat) ){
  33916. rc = SQLITE_IOERR_SHMSIZE;
  33917. goto shmpage_out;
  33918. }
  33919. if( sStat.st_size<nByte ){
  33920. /* The requested memory region does not exist. If bExtend is set to
  33921. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  33922. */
  33923. if( !bExtend ){
  33924. goto shmpage_out;
  33925. }
  33926. /* Alternatively, if bExtend is true, extend the file. Do this by
  33927. ** writing a single byte to the end of each (OS) page being
  33928. ** allocated or extended. Technically, we need only write to the
  33929. ** last page in order to extend the file. But writing to all new
  33930. ** pages forces the OS to allocate them immediately, which reduces
  33931. ** the chances of SIGBUS while accessing the mapped region later on.
  33932. */
  33933. else{
  33934. static const int pgsz = 4096;
  33935. int iPg;
  33936. /* Write to the last byte of each newly allocated or extended page */
  33937. assert( (nByte % pgsz)==0 );
  33938. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  33939. int x = 0;
  33940. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
  33941. const char *zFile = pShmNode->zFilename;
  33942. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  33943. goto shmpage_out;
  33944. }
  33945. }
  33946. }
  33947. }
  33948. }
  33949. /* Map the requested memory region into this processes address space. */
  33950. apNew = (char **)sqlite3_realloc(
  33951. pShmNode->apRegion, nReqRegion*sizeof(char *)
  33952. );
  33953. if( !apNew ){
  33954. rc = SQLITE_IOERR_NOMEM_BKPT;
  33955. goto shmpage_out;
  33956. }
  33957. pShmNode->apRegion = apNew;
  33958. while( pShmNode->nRegion<nReqRegion ){
  33959. int nMap = szRegion*nShmPerMap;
  33960. int i;
  33961. void *pMem;
  33962. if( pShmNode->h>=0 ){
  33963. pMem = osMmap(0, nMap,
  33964. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  33965. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  33966. );
  33967. if( pMem==MAP_FAILED ){
  33968. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  33969. goto shmpage_out;
  33970. }
  33971. }else{
  33972. pMem = sqlite3_malloc64(szRegion);
  33973. if( pMem==0 ){
  33974. rc = SQLITE_NOMEM_BKPT;
  33975. goto shmpage_out;
  33976. }
  33977. memset(pMem, 0, szRegion);
  33978. }
  33979. for(i=0; i<nShmPerMap; i++){
  33980. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  33981. }
  33982. pShmNode->nRegion += nShmPerMap;
  33983. }
  33984. }
  33985. shmpage_out:
  33986. if( pShmNode->nRegion>iRegion ){
  33987. *pp = pShmNode->apRegion[iRegion];
  33988. }else{
  33989. *pp = 0;
  33990. }
  33991. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  33992. sqlite3_mutex_leave(pShmNode->mutex);
  33993. return rc;
  33994. }
  33995. /*
  33996. ** Change the lock state for a shared-memory segment.
  33997. **
  33998. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  33999. ** different here than in posix. In xShmLock(), one can go from unlocked
  34000. ** to shared and back or from unlocked to exclusive and back. But one may
  34001. ** not go from shared to exclusive or from exclusive to shared.
  34002. */
  34003. static int unixShmLock(
  34004. sqlite3_file *fd, /* Database file holding the shared memory */
  34005. int ofst, /* First lock to acquire or release */
  34006. int n, /* Number of locks to acquire or release */
  34007. int flags /* What to do with the lock */
  34008. ){
  34009. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  34010. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  34011. unixShm *pX; /* For looping over all siblings */
  34012. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  34013. int rc = SQLITE_OK; /* Result code */
  34014. u16 mask; /* Mask of locks to take or release */
  34015. assert( pShmNode==pDbFd->pInode->pShmNode );
  34016. assert( pShmNode->pInode==pDbFd->pInode );
  34017. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  34018. assert( n>=1 );
  34019. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  34020. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  34021. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  34022. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  34023. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  34024. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  34025. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  34026. mask = (1<<(ofst+n)) - (1<<ofst);
  34027. assert( n>1 || mask==(1<<ofst) );
  34028. sqlite3_mutex_enter(pShmNode->mutex);
  34029. if( flags & SQLITE_SHM_UNLOCK ){
  34030. u16 allMask = 0; /* Mask of locks held by siblings */
  34031. /* See if any siblings hold this same lock */
  34032. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  34033. if( pX==p ) continue;
  34034. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  34035. allMask |= pX->sharedMask;
  34036. }
  34037. /* Unlock the system-level locks */
  34038. if( (mask & allMask)==0 ){
  34039. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  34040. }else{
  34041. rc = SQLITE_OK;
  34042. }
  34043. /* Undo the local locks */
  34044. if( rc==SQLITE_OK ){
  34045. p->exclMask &= ~mask;
  34046. p->sharedMask &= ~mask;
  34047. }
  34048. }else if( flags & SQLITE_SHM_SHARED ){
  34049. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  34050. /* Find out which shared locks are already held by sibling connections.
  34051. ** If any sibling already holds an exclusive lock, go ahead and return
  34052. ** SQLITE_BUSY.
  34053. */
  34054. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  34055. if( (pX->exclMask & mask)!=0 ){
  34056. rc = SQLITE_BUSY;
  34057. break;
  34058. }
  34059. allShared |= pX->sharedMask;
  34060. }
  34061. /* Get shared locks at the system level, if necessary */
  34062. if( rc==SQLITE_OK ){
  34063. if( (allShared & mask)==0 ){
  34064. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  34065. }else{
  34066. rc = SQLITE_OK;
  34067. }
  34068. }
  34069. /* Get the local shared locks */
  34070. if( rc==SQLITE_OK ){
  34071. p->sharedMask |= mask;
  34072. }
  34073. }else{
  34074. /* Make sure no sibling connections hold locks that will block this
  34075. ** lock. If any do, return SQLITE_BUSY right away.
  34076. */
  34077. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  34078. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  34079. rc = SQLITE_BUSY;
  34080. break;
  34081. }
  34082. }
  34083. /* Get the exclusive locks at the system level. Then if successful
  34084. ** also mark the local connection as being locked.
  34085. */
  34086. if( rc==SQLITE_OK ){
  34087. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  34088. if( rc==SQLITE_OK ){
  34089. assert( (p->sharedMask & mask)==0 );
  34090. p->exclMask |= mask;
  34091. }
  34092. }
  34093. }
  34094. sqlite3_mutex_leave(pShmNode->mutex);
  34095. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  34096. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  34097. return rc;
  34098. }
  34099. /*
  34100. ** Implement a memory barrier or memory fence on shared memory.
  34101. **
  34102. ** All loads and stores begun before the barrier must complete before
  34103. ** any load or store begun after the barrier.
  34104. */
  34105. static void unixShmBarrier(
  34106. sqlite3_file *fd /* Database file holding the shared memory */
  34107. ){
  34108. UNUSED_PARAMETER(fd);
  34109. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  34110. unixEnterMutex(); /* Also mutex, for redundancy */
  34111. unixLeaveMutex();
  34112. }
  34113. /*
  34114. ** Close a connection to shared-memory. Delete the underlying
  34115. ** storage if deleteFlag is true.
  34116. **
  34117. ** If there is no shared memory associated with the connection then this
  34118. ** routine is a harmless no-op.
  34119. */
  34120. static int unixShmUnmap(
  34121. sqlite3_file *fd, /* The underlying database file */
  34122. int deleteFlag /* Delete shared-memory if true */
  34123. ){
  34124. unixShm *p; /* The connection to be closed */
  34125. unixShmNode *pShmNode; /* The underlying shared-memory file */
  34126. unixShm **pp; /* For looping over sibling connections */
  34127. unixFile *pDbFd; /* The underlying database file */
  34128. pDbFd = (unixFile*)fd;
  34129. p = pDbFd->pShm;
  34130. if( p==0 ) return SQLITE_OK;
  34131. pShmNode = p->pShmNode;
  34132. assert( pShmNode==pDbFd->pInode->pShmNode );
  34133. assert( pShmNode->pInode==pDbFd->pInode );
  34134. /* Remove connection p from the set of connections associated
  34135. ** with pShmNode */
  34136. sqlite3_mutex_enter(pShmNode->mutex);
  34137. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  34138. *pp = p->pNext;
  34139. /* Free the connection p */
  34140. sqlite3_free(p);
  34141. pDbFd->pShm = 0;
  34142. sqlite3_mutex_leave(pShmNode->mutex);
  34143. /* If pShmNode->nRef has reached 0, then close the underlying
  34144. ** shared-memory file, too */
  34145. unixEnterMutex();
  34146. assert( pShmNode->nRef>0 );
  34147. pShmNode->nRef--;
  34148. if( pShmNode->nRef==0 ){
  34149. if( deleteFlag && pShmNode->h>=0 ){
  34150. osUnlink(pShmNode->zFilename);
  34151. }
  34152. unixShmPurge(pDbFd);
  34153. }
  34154. unixLeaveMutex();
  34155. return SQLITE_OK;
  34156. }
  34157. #else
  34158. # define unixShmMap 0
  34159. # define unixShmLock 0
  34160. # define unixShmBarrier 0
  34161. # define unixShmUnmap 0
  34162. #endif /* #ifndef SQLITE_OMIT_WAL */
  34163. #if SQLITE_MAX_MMAP_SIZE>0
  34164. /*
  34165. ** If it is currently memory mapped, unmap file pFd.
  34166. */
  34167. static void unixUnmapfile(unixFile *pFd){
  34168. assert( pFd->nFetchOut==0 );
  34169. if( pFd->pMapRegion ){
  34170. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  34171. pFd->pMapRegion = 0;
  34172. pFd->mmapSize = 0;
  34173. pFd->mmapSizeActual = 0;
  34174. }
  34175. }
  34176. /*
  34177. ** Attempt to set the size of the memory mapping maintained by file
  34178. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  34179. **
  34180. ** If successful, this function sets the following variables:
  34181. **
  34182. ** unixFile.pMapRegion
  34183. ** unixFile.mmapSize
  34184. ** unixFile.mmapSizeActual
  34185. **
  34186. ** If unsuccessful, an error message is logged via sqlite3_log() and
  34187. ** the three variables above are zeroed. In this case SQLite should
  34188. ** continue accessing the database using the xRead() and xWrite()
  34189. ** methods.
  34190. */
  34191. static void unixRemapfile(
  34192. unixFile *pFd, /* File descriptor object */
  34193. i64 nNew /* Required mapping size */
  34194. ){
  34195. const char *zErr = "mmap";
  34196. int h = pFd->h; /* File descriptor open on db file */
  34197. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  34198. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  34199. u8 *pNew = 0; /* Location of new mapping */
  34200. int flags = PROT_READ; /* Flags to pass to mmap() */
  34201. assert( pFd->nFetchOut==0 );
  34202. assert( nNew>pFd->mmapSize );
  34203. assert( nNew<=pFd->mmapSizeMax );
  34204. assert( nNew>0 );
  34205. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  34206. assert( MAP_FAILED!=0 );
  34207. #ifdef SQLITE_MMAP_READWRITE
  34208. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  34209. #endif
  34210. if( pOrig ){
  34211. #if HAVE_MREMAP
  34212. i64 nReuse = pFd->mmapSize;
  34213. #else
  34214. const int szSyspage = osGetpagesize();
  34215. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  34216. #endif
  34217. u8 *pReq = &pOrig[nReuse];
  34218. /* Unmap any pages of the existing mapping that cannot be reused. */
  34219. if( nReuse!=nOrig ){
  34220. osMunmap(pReq, nOrig-nReuse);
  34221. }
  34222. #if HAVE_MREMAP
  34223. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  34224. zErr = "mremap";
  34225. #else
  34226. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  34227. if( pNew!=MAP_FAILED ){
  34228. if( pNew!=pReq ){
  34229. osMunmap(pNew, nNew - nReuse);
  34230. pNew = 0;
  34231. }else{
  34232. pNew = pOrig;
  34233. }
  34234. }
  34235. #endif
  34236. /* The attempt to extend the existing mapping failed. Free it. */
  34237. if( pNew==MAP_FAILED || pNew==0 ){
  34238. osMunmap(pOrig, nReuse);
  34239. }
  34240. }
  34241. /* If pNew is still NULL, try to create an entirely new mapping. */
  34242. if( pNew==0 ){
  34243. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  34244. }
  34245. if( pNew==MAP_FAILED ){
  34246. pNew = 0;
  34247. nNew = 0;
  34248. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  34249. /* If the mmap() above failed, assume that all subsequent mmap() calls
  34250. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  34251. ** in this case. */
  34252. pFd->mmapSizeMax = 0;
  34253. }
  34254. pFd->pMapRegion = (void *)pNew;
  34255. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  34256. }
  34257. /*
  34258. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  34259. ** is already mapped, the existing mapping is replaced by the new). Or, if
  34260. ** there already exists a mapping for this file, and there are still
  34261. ** outstanding xFetch() references to it, this function is a no-op.
  34262. **
  34263. ** If parameter nByte is non-negative, then it is the requested size of
  34264. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  34265. ** requested size is the size of the file on disk. The actual size of the
  34266. ** created mapping is either the requested size or the value configured
  34267. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  34268. **
  34269. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  34270. ** recreated as a result of outstanding references) or an SQLite error
  34271. ** code otherwise.
  34272. */
  34273. static int unixMapfile(unixFile *pFd, i64 nMap){
  34274. assert( nMap>=0 || pFd->nFetchOut==0 );
  34275. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  34276. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  34277. if( nMap<0 ){
  34278. struct stat statbuf; /* Low-level file information */
  34279. if( osFstat(pFd->h, &statbuf) ){
  34280. return SQLITE_IOERR_FSTAT;
  34281. }
  34282. nMap = statbuf.st_size;
  34283. }
  34284. if( nMap>pFd->mmapSizeMax ){
  34285. nMap = pFd->mmapSizeMax;
  34286. }
  34287. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  34288. if( nMap!=pFd->mmapSize ){
  34289. unixRemapfile(pFd, nMap);
  34290. }
  34291. return SQLITE_OK;
  34292. }
  34293. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  34294. /*
  34295. ** If possible, return a pointer to a mapping of file fd starting at offset
  34296. ** iOff. The mapping must be valid for at least nAmt bytes.
  34297. **
  34298. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  34299. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  34300. ** Finally, if an error does occur, return an SQLite error code. The final
  34301. ** value of *pp is undefined in this case.
  34302. **
  34303. ** If this function does return a pointer, the caller must eventually
  34304. ** release the reference by calling unixUnfetch().
  34305. */
  34306. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  34307. #if SQLITE_MAX_MMAP_SIZE>0
  34308. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  34309. #endif
  34310. *pp = 0;
  34311. #if SQLITE_MAX_MMAP_SIZE>0
  34312. if( pFd->mmapSizeMax>0 ){
  34313. if( pFd->pMapRegion==0 ){
  34314. int rc = unixMapfile(pFd, -1);
  34315. if( rc!=SQLITE_OK ) return rc;
  34316. }
  34317. if( pFd->mmapSize >= iOff+nAmt ){
  34318. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  34319. pFd->nFetchOut++;
  34320. }
  34321. }
  34322. #endif
  34323. return SQLITE_OK;
  34324. }
  34325. /*
  34326. ** If the third argument is non-NULL, then this function releases a
  34327. ** reference obtained by an earlier call to unixFetch(). The second
  34328. ** argument passed to this function must be the same as the corresponding
  34329. ** argument that was passed to the unixFetch() invocation.
  34330. **
  34331. ** Or, if the third argument is NULL, then this function is being called
  34332. ** to inform the VFS layer that, according to POSIX, any existing mapping
  34333. ** may now be invalid and should be unmapped.
  34334. */
  34335. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  34336. #if SQLITE_MAX_MMAP_SIZE>0
  34337. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  34338. UNUSED_PARAMETER(iOff);
  34339. /* If p==0 (unmap the entire file) then there must be no outstanding
  34340. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  34341. ** then there must be at least one outstanding. */
  34342. assert( (p==0)==(pFd->nFetchOut==0) );
  34343. /* If p!=0, it must match the iOff value. */
  34344. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  34345. if( p ){
  34346. pFd->nFetchOut--;
  34347. }else{
  34348. unixUnmapfile(pFd);
  34349. }
  34350. assert( pFd->nFetchOut>=0 );
  34351. #else
  34352. UNUSED_PARAMETER(fd);
  34353. UNUSED_PARAMETER(p);
  34354. UNUSED_PARAMETER(iOff);
  34355. #endif
  34356. return SQLITE_OK;
  34357. }
  34358. /*
  34359. ** Here ends the implementation of all sqlite3_file methods.
  34360. **
  34361. ********************** End sqlite3_file Methods *******************************
  34362. ******************************************************************************/
  34363. /*
  34364. ** This division contains definitions of sqlite3_io_methods objects that
  34365. ** implement various file locking strategies. It also contains definitions
  34366. ** of "finder" functions. A finder-function is used to locate the appropriate
  34367. ** sqlite3_io_methods object for a particular database file. The pAppData
  34368. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  34369. ** the correct finder-function for that VFS.
  34370. **
  34371. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  34372. ** object. The only interesting finder-function is autolockIoFinder, which
  34373. ** looks at the filesystem type and tries to guess the best locking
  34374. ** strategy from that.
  34375. **
  34376. ** For finder-function F, two objects are created:
  34377. **
  34378. ** (1) The real finder-function named "FImpt()".
  34379. **
  34380. ** (2) A constant pointer to this function named just "F".
  34381. **
  34382. **
  34383. ** A pointer to the F pointer is used as the pAppData value for VFS
  34384. ** objects. We have to do this instead of letting pAppData point
  34385. ** directly at the finder-function since C90 rules prevent a void*
  34386. ** from be cast into a function pointer.
  34387. **
  34388. **
  34389. ** Each instance of this macro generates two objects:
  34390. **
  34391. ** * A constant sqlite3_io_methods object call METHOD that has locking
  34392. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  34393. **
  34394. ** * An I/O method finder function called FINDER that returns a pointer
  34395. ** to the METHOD object in the previous bullet.
  34396. */
  34397. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  34398. static const sqlite3_io_methods METHOD = { \
  34399. VERSION, /* iVersion */ \
  34400. CLOSE, /* xClose */ \
  34401. unixRead, /* xRead */ \
  34402. unixWrite, /* xWrite */ \
  34403. unixTruncate, /* xTruncate */ \
  34404. unixSync, /* xSync */ \
  34405. unixFileSize, /* xFileSize */ \
  34406. LOCK, /* xLock */ \
  34407. UNLOCK, /* xUnlock */ \
  34408. CKLOCK, /* xCheckReservedLock */ \
  34409. unixFileControl, /* xFileControl */ \
  34410. unixSectorSize, /* xSectorSize */ \
  34411. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  34412. SHMMAP, /* xShmMap */ \
  34413. unixShmLock, /* xShmLock */ \
  34414. unixShmBarrier, /* xShmBarrier */ \
  34415. unixShmUnmap, /* xShmUnmap */ \
  34416. unixFetch, /* xFetch */ \
  34417. unixUnfetch, /* xUnfetch */ \
  34418. }; \
  34419. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  34420. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  34421. return &METHOD; \
  34422. } \
  34423. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  34424. = FINDER##Impl;
  34425. /*
  34426. ** Here are all of the sqlite3_io_methods objects for each of the
  34427. ** locking strategies. Functions that return pointers to these methods
  34428. ** are also created.
  34429. */
  34430. IOMETHODS(
  34431. posixIoFinder, /* Finder function name */
  34432. posixIoMethods, /* sqlite3_io_methods object name */
  34433. 3, /* shared memory and mmap are enabled */
  34434. unixClose, /* xClose method */
  34435. unixLock, /* xLock method */
  34436. unixUnlock, /* xUnlock method */
  34437. unixCheckReservedLock, /* xCheckReservedLock method */
  34438. unixShmMap /* xShmMap method */
  34439. )
  34440. IOMETHODS(
  34441. nolockIoFinder, /* Finder function name */
  34442. nolockIoMethods, /* sqlite3_io_methods object name */
  34443. 3, /* shared memory is disabled */
  34444. nolockClose, /* xClose method */
  34445. nolockLock, /* xLock method */
  34446. nolockUnlock, /* xUnlock method */
  34447. nolockCheckReservedLock, /* xCheckReservedLock method */
  34448. 0 /* xShmMap method */
  34449. )
  34450. IOMETHODS(
  34451. dotlockIoFinder, /* Finder function name */
  34452. dotlockIoMethods, /* sqlite3_io_methods object name */
  34453. 1, /* shared memory is disabled */
  34454. dotlockClose, /* xClose method */
  34455. dotlockLock, /* xLock method */
  34456. dotlockUnlock, /* xUnlock method */
  34457. dotlockCheckReservedLock, /* xCheckReservedLock method */
  34458. 0 /* xShmMap method */
  34459. )
  34460. #if SQLITE_ENABLE_LOCKING_STYLE
  34461. IOMETHODS(
  34462. flockIoFinder, /* Finder function name */
  34463. flockIoMethods, /* sqlite3_io_methods object name */
  34464. 1, /* shared memory is disabled */
  34465. flockClose, /* xClose method */
  34466. flockLock, /* xLock method */
  34467. flockUnlock, /* xUnlock method */
  34468. flockCheckReservedLock, /* xCheckReservedLock method */
  34469. 0 /* xShmMap method */
  34470. )
  34471. #endif
  34472. #if OS_VXWORKS
  34473. IOMETHODS(
  34474. semIoFinder, /* Finder function name */
  34475. semIoMethods, /* sqlite3_io_methods object name */
  34476. 1, /* shared memory is disabled */
  34477. semXClose, /* xClose method */
  34478. semXLock, /* xLock method */
  34479. semXUnlock, /* xUnlock method */
  34480. semXCheckReservedLock, /* xCheckReservedLock method */
  34481. 0 /* xShmMap method */
  34482. )
  34483. #endif
  34484. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34485. IOMETHODS(
  34486. afpIoFinder, /* Finder function name */
  34487. afpIoMethods, /* sqlite3_io_methods object name */
  34488. 1, /* shared memory is disabled */
  34489. afpClose, /* xClose method */
  34490. afpLock, /* xLock method */
  34491. afpUnlock, /* xUnlock method */
  34492. afpCheckReservedLock, /* xCheckReservedLock method */
  34493. 0 /* xShmMap method */
  34494. )
  34495. #endif
  34496. /*
  34497. ** The proxy locking method is a "super-method" in the sense that it
  34498. ** opens secondary file descriptors for the conch and lock files and
  34499. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  34500. ** secondary files. For this reason, the division that implements
  34501. ** proxy locking is located much further down in the file. But we need
  34502. ** to go ahead and define the sqlite3_io_methods and finder function
  34503. ** for proxy locking here. So we forward declare the I/O methods.
  34504. */
  34505. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34506. static int proxyClose(sqlite3_file*);
  34507. static int proxyLock(sqlite3_file*, int);
  34508. static int proxyUnlock(sqlite3_file*, int);
  34509. static int proxyCheckReservedLock(sqlite3_file*, int*);
  34510. IOMETHODS(
  34511. proxyIoFinder, /* Finder function name */
  34512. proxyIoMethods, /* sqlite3_io_methods object name */
  34513. 1, /* shared memory is disabled */
  34514. proxyClose, /* xClose method */
  34515. proxyLock, /* xLock method */
  34516. proxyUnlock, /* xUnlock method */
  34517. proxyCheckReservedLock, /* xCheckReservedLock method */
  34518. 0 /* xShmMap method */
  34519. )
  34520. #endif
  34521. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  34522. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34523. IOMETHODS(
  34524. nfsIoFinder, /* Finder function name */
  34525. nfsIoMethods, /* sqlite3_io_methods object name */
  34526. 1, /* shared memory is disabled */
  34527. unixClose, /* xClose method */
  34528. unixLock, /* xLock method */
  34529. nfsUnlock, /* xUnlock method */
  34530. unixCheckReservedLock, /* xCheckReservedLock method */
  34531. 0 /* xShmMap method */
  34532. )
  34533. #endif
  34534. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34535. /*
  34536. ** This "finder" function attempts to determine the best locking strategy
  34537. ** for the database file "filePath". It then returns the sqlite3_io_methods
  34538. ** object that implements that strategy.
  34539. **
  34540. ** This is for MacOSX only.
  34541. */
  34542. static const sqlite3_io_methods *autolockIoFinderImpl(
  34543. const char *filePath, /* name of the database file */
  34544. unixFile *pNew /* open file object for the database file */
  34545. ){
  34546. static const struct Mapping {
  34547. const char *zFilesystem; /* Filesystem type name */
  34548. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  34549. } aMap[] = {
  34550. { "hfs", &posixIoMethods },
  34551. { "ufs", &posixIoMethods },
  34552. { "afpfs", &afpIoMethods },
  34553. { "smbfs", &afpIoMethods },
  34554. { "webdav", &nolockIoMethods },
  34555. { 0, 0 }
  34556. };
  34557. int i;
  34558. struct statfs fsInfo;
  34559. struct flock lockInfo;
  34560. if( !filePath ){
  34561. /* If filePath==NULL that means we are dealing with a transient file
  34562. ** that does not need to be locked. */
  34563. return &nolockIoMethods;
  34564. }
  34565. if( statfs(filePath, &fsInfo) != -1 ){
  34566. if( fsInfo.f_flags & MNT_RDONLY ){
  34567. return &nolockIoMethods;
  34568. }
  34569. for(i=0; aMap[i].zFilesystem; i++){
  34570. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  34571. return aMap[i].pMethods;
  34572. }
  34573. }
  34574. }
  34575. /* Default case. Handles, amongst others, "nfs".
  34576. ** Test byte-range lock using fcntl(). If the call succeeds,
  34577. ** assume that the file-system supports POSIX style locks.
  34578. */
  34579. lockInfo.l_len = 1;
  34580. lockInfo.l_start = 0;
  34581. lockInfo.l_whence = SEEK_SET;
  34582. lockInfo.l_type = F_RDLCK;
  34583. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  34584. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  34585. return &nfsIoMethods;
  34586. } else {
  34587. return &posixIoMethods;
  34588. }
  34589. }else{
  34590. return &dotlockIoMethods;
  34591. }
  34592. }
  34593. static const sqlite3_io_methods
  34594. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  34595. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  34596. #if OS_VXWORKS
  34597. /*
  34598. ** This "finder" function for VxWorks checks to see if posix advisory
  34599. ** locking works. If it does, then that is what is used. If it does not
  34600. ** work, then fallback to named semaphore locking.
  34601. */
  34602. static const sqlite3_io_methods *vxworksIoFinderImpl(
  34603. const char *filePath, /* name of the database file */
  34604. unixFile *pNew /* the open file object */
  34605. ){
  34606. struct flock lockInfo;
  34607. if( !filePath ){
  34608. /* If filePath==NULL that means we are dealing with a transient file
  34609. ** that does not need to be locked. */
  34610. return &nolockIoMethods;
  34611. }
  34612. /* Test if fcntl() is supported and use POSIX style locks.
  34613. ** Otherwise fall back to the named semaphore method.
  34614. */
  34615. lockInfo.l_len = 1;
  34616. lockInfo.l_start = 0;
  34617. lockInfo.l_whence = SEEK_SET;
  34618. lockInfo.l_type = F_RDLCK;
  34619. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  34620. return &posixIoMethods;
  34621. }else{
  34622. return &semIoMethods;
  34623. }
  34624. }
  34625. static const sqlite3_io_methods
  34626. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  34627. #endif /* OS_VXWORKS */
  34628. /*
  34629. ** An abstract type for a pointer to an IO method finder function:
  34630. */
  34631. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  34632. /****************************************************************************
  34633. **************************** sqlite3_vfs methods ****************************
  34634. **
  34635. ** This division contains the implementation of methods on the
  34636. ** sqlite3_vfs object.
  34637. */
  34638. /*
  34639. ** Initialize the contents of the unixFile structure pointed to by pId.
  34640. */
  34641. static int fillInUnixFile(
  34642. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  34643. int h, /* Open file descriptor of file being opened */
  34644. sqlite3_file *pId, /* Write to the unixFile structure here */
  34645. const char *zFilename, /* Name of the file being opened */
  34646. int ctrlFlags /* Zero or more UNIXFILE_* values */
  34647. ){
  34648. const sqlite3_io_methods *pLockingStyle;
  34649. unixFile *pNew = (unixFile *)pId;
  34650. int rc = SQLITE_OK;
  34651. assert( pNew->pInode==NULL );
  34652. /* No locking occurs in temporary files */
  34653. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  34654. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  34655. pNew->h = h;
  34656. pNew->pVfs = pVfs;
  34657. pNew->zPath = zFilename;
  34658. pNew->ctrlFlags = (u8)ctrlFlags;
  34659. #if SQLITE_MAX_MMAP_SIZE>0
  34660. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  34661. #endif
  34662. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  34663. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  34664. pNew->ctrlFlags |= UNIXFILE_PSOW;
  34665. }
  34666. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  34667. pNew->ctrlFlags |= UNIXFILE_EXCL;
  34668. }
  34669. #if OS_VXWORKS
  34670. pNew->pId = vxworksFindFileId(zFilename);
  34671. if( pNew->pId==0 ){
  34672. ctrlFlags |= UNIXFILE_NOLOCK;
  34673. rc = SQLITE_NOMEM_BKPT;
  34674. }
  34675. #endif
  34676. if( ctrlFlags & UNIXFILE_NOLOCK ){
  34677. pLockingStyle = &nolockIoMethods;
  34678. }else{
  34679. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  34680. #if SQLITE_ENABLE_LOCKING_STYLE
  34681. /* Cache zFilename in the locking context (AFP and dotlock override) for
  34682. ** proxyLock activation is possible (remote proxy is based on db name)
  34683. ** zFilename remains valid until file is closed, to support */
  34684. pNew->lockingContext = (void*)zFilename;
  34685. #endif
  34686. }
  34687. if( pLockingStyle == &posixIoMethods
  34688. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34689. || pLockingStyle == &nfsIoMethods
  34690. #endif
  34691. ){
  34692. unixEnterMutex();
  34693. rc = findInodeInfo(pNew, &pNew->pInode);
  34694. if( rc!=SQLITE_OK ){
  34695. /* If an error occurred in findInodeInfo(), close the file descriptor
  34696. ** immediately, before releasing the mutex. findInodeInfo() may fail
  34697. ** in two scenarios:
  34698. **
  34699. ** (a) A call to fstat() failed.
  34700. ** (b) A malloc failed.
  34701. **
  34702. ** Scenario (b) may only occur if the process is holding no other
  34703. ** file descriptors open on the same file. If there were other file
  34704. ** descriptors on this file, then no malloc would be required by
  34705. ** findInodeInfo(). If this is the case, it is quite safe to close
  34706. ** handle h - as it is guaranteed that no posix locks will be released
  34707. ** by doing so.
  34708. **
  34709. ** If scenario (a) caused the error then things are not so safe. The
  34710. ** implicit assumption here is that if fstat() fails, things are in
  34711. ** such bad shape that dropping a lock or two doesn't matter much.
  34712. */
  34713. robust_close(pNew, h, __LINE__);
  34714. h = -1;
  34715. }
  34716. unixLeaveMutex();
  34717. }
  34718. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  34719. else if( pLockingStyle == &afpIoMethods ){
  34720. /* AFP locking uses the file path so it needs to be included in
  34721. ** the afpLockingContext.
  34722. */
  34723. afpLockingContext *pCtx;
  34724. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  34725. if( pCtx==0 ){
  34726. rc = SQLITE_NOMEM_BKPT;
  34727. }else{
  34728. /* NB: zFilename exists and remains valid until the file is closed
  34729. ** according to requirement F11141. So we do not need to make a
  34730. ** copy of the filename. */
  34731. pCtx->dbPath = zFilename;
  34732. pCtx->reserved = 0;
  34733. srandomdev();
  34734. unixEnterMutex();
  34735. rc = findInodeInfo(pNew, &pNew->pInode);
  34736. if( rc!=SQLITE_OK ){
  34737. sqlite3_free(pNew->lockingContext);
  34738. robust_close(pNew, h, __LINE__);
  34739. h = -1;
  34740. }
  34741. unixLeaveMutex();
  34742. }
  34743. }
  34744. #endif
  34745. else if( pLockingStyle == &dotlockIoMethods ){
  34746. /* Dotfile locking uses the file path so it needs to be included in
  34747. ** the dotlockLockingContext
  34748. */
  34749. char *zLockFile;
  34750. int nFilename;
  34751. assert( zFilename!=0 );
  34752. nFilename = (int)strlen(zFilename) + 6;
  34753. zLockFile = (char *)sqlite3_malloc64(nFilename);
  34754. if( zLockFile==0 ){
  34755. rc = SQLITE_NOMEM_BKPT;
  34756. }else{
  34757. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  34758. }
  34759. pNew->lockingContext = zLockFile;
  34760. }
  34761. #if OS_VXWORKS
  34762. else if( pLockingStyle == &semIoMethods ){
  34763. /* Named semaphore locking uses the file path so it needs to be
  34764. ** included in the semLockingContext
  34765. */
  34766. unixEnterMutex();
  34767. rc = findInodeInfo(pNew, &pNew->pInode);
  34768. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  34769. char *zSemName = pNew->pInode->aSemName;
  34770. int n;
  34771. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  34772. pNew->pId->zCanonicalName);
  34773. for( n=1; zSemName[n]; n++ )
  34774. if( zSemName[n]=='/' ) zSemName[n] = '_';
  34775. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  34776. if( pNew->pInode->pSem == SEM_FAILED ){
  34777. rc = SQLITE_NOMEM_BKPT;
  34778. pNew->pInode->aSemName[0] = '\0';
  34779. }
  34780. }
  34781. unixLeaveMutex();
  34782. }
  34783. #endif
  34784. storeLastErrno(pNew, 0);
  34785. #if OS_VXWORKS
  34786. if( rc!=SQLITE_OK ){
  34787. if( h>=0 ) robust_close(pNew, h, __LINE__);
  34788. h = -1;
  34789. osUnlink(zFilename);
  34790. pNew->ctrlFlags |= UNIXFILE_DELETE;
  34791. }
  34792. #endif
  34793. if( rc!=SQLITE_OK ){
  34794. if( h>=0 ) robust_close(pNew, h, __LINE__);
  34795. }else{
  34796. pNew->pMethod = pLockingStyle;
  34797. OpenCounter(+1);
  34798. verifyDbFile(pNew);
  34799. }
  34800. return rc;
  34801. }
  34802. /*
  34803. ** Return the name of a directory in which to put temporary files.
  34804. ** If no suitable temporary file directory can be found, return NULL.
  34805. */
  34806. static const char *unixTempFileDir(void){
  34807. static const char *azDirs[] = {
  34808. 0,
  34809. 0,
  34810. "/var/tmp",
  34811. "/usr/tmp",
  34812. "/tmp",
  34813. "."
  34814. };
  34815. unsigned int i = 0;
  34816. struct stat buf;
  34817. const char *zDir = sqlite3_temp_directory;
  34818. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  34819. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  34820. while(1){
  34821. if( zDir!=0
  34822. && osStat(zDir, &buf)==0
  34823. && S_ISDIR(buf.st_mode)
  34824. && osAccess(zDir, 03)==0
  34825. ){
  34826. return zDir;
  34827. }
  34828. if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
  34829. zDir = azDirs[i++];
  34830. }
  34831. return 0;
  34832. }
  34833. /*
  34834. ** Create a temporary file name in zBuf. zBuf must be allocated
  34835. ** by the calling process and must be big enough to hold at least
  34836. ** pVfs->mxPathname bytes.
  34837. */
  34838. static int unixGetTempname(int nBuf, char *zBuf){
  34839. const char *zDir;
  34840. int iLimit = 0;
  34841. /* It's odd to simulate an io-error here, but really this is just
  34842. ** using the io-error infrastructure to test that SQLite handles this
  34843. ** function failing.
  34844. */
  34845. zBuf[0] = 0;
  34846. SimulateIOError( return SQLITE_IOERR );
  34847. zDir = unixTempFileDir();
  34848. if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
  34849. do{
  34850. u64 r;
  34851. sqlite3_randomness(sizeof(r), &r);
  34852. assert( nBuf>2 );
  34853. zBuf[nBuf-2] = 0;
  34854. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  34855. zDir, r, 0);
  34856. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  34857. }while( osAccess(zBuf,0)==0 );
  34858. return SQLITE_OK;
  34859. }
  34860. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  34861. /*
  34862. ** Routine to transform a unixFile into a proxy-locking unixFile.
  34863. ** Implementation in the proxy-lock division, but used by unixOpen()
  34864. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  34865. */
  34866. static int proxyTransformUnixFile(unixFile*, const char*);
  34867. #endif
  34868. /*
  34869. ** Search for an unused file descriptor that was opened on the database
  34870. ** file (not a journal or master-journal file) identified by pathname
  34871. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  34872. ** argument to this function.
  34873. **
  34874. ** Such a file descriptor may exist if a database connection was closed
  34875. ** but the associated file descriptor could not be closed because some
  34876. ** other file descriptor open on the same file is holding a file-lock.
  34877. ** Refer to comments in the unixClose() function and the lengthy comment
  34878. ** describing "Posix Advisory Locking" at the start of this file for
  34879. ** further details. Also, ticket #4018.
  34880. **
  34881. ** If a suitable file descriptor is found, then it is returned. If no
  34882. ** such file descriptor is located, -1 is returned.
  34883. */
  34884. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  34885. UnixUnusedFd *pUnused = 0;
  34886. /* Do not search for an unused file descriptor on vxworks. Not because
  34887. ** vxworks would not benefit from the change (it might, we're not sure),
  34888. ** but because no way to test it is currently available. It is better
  34889. ** not to risk breaking vxworks support for the sake of such an obscure
  34890. ** feature. */
  34891. #if !OS_VXWORKS
  34892. struct stat sStat; /* Results of stat() call */
  34893. unixEnterMutex();
  34894. /* A stat() call may fail for various reasons. If this happens, it is
  34895. ** almost certain that an open() call on the same path will also fail.
  34896. ** For this reason, if an error occurs in the stat() call here, it is
  34897. ** ignored and -1 is returned. The caller will try to open a new file
  34898. ** descriptor on the same path, fail, and return an error to SQLite.
  34899. **
  34900. ** Even if a subsequent open() call does succeed, the consequences of
  34901. ** not searching for a reusable file descriptor are not dire. */
  34902. if( nUnusedFd>0 && 0==osStat(zPath, &sStat) ){
  34903. unixInodeInfo *pInode;
  34904. pInode = inodeList;
  34905. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  34906. || pInode->fileId.ino!=(u64)sStat.st_ino) ){
  34907. pInode = pInode->pNext;
  34908. }
  34909. if( pInode ){
  34910. UnixUnusedFd **pp;
  34911. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  34912. pUnused = *pp;
  34913. if( pUnused ){
  34914. nUnusedFd--;
  34915. *pp = pUnused->pNext;
  34916. }
  34917. }
  34918. }
  34919. unixLeaveMutex();
  34920. #endif /* if !OS_VXWORKS */
  34921. return pUnused;
  34922. }
  34923. /*
  34924. ** Find the mode, uid and gid of file zFile.
  34925. */
  34926. static int getFileMode(
  34927. const char *zFile, /* File name */
  34928. mode_t *pMode, /* OUT: Permissions of zFile */
  34929. uid_t *pUid, /* OUT: uid of zFile. */
  34930. gid_t *pGid /* OUT: gid of zFile. */
  34931. ){
  34932. struct stat sStat; /* Output of stat() on database file */
  34933. int rc = SQLITE_OK;
  34934. if( 0==osStat(zFile, &sStat) ){
  34935. *pMode = sStat.st_mode & 0777;
  34936. *pUid = sStat.st_uid;
  34937. *pGid = sStat.st_gid;
  34938. }else{
  34939. rc = SQLITE_IOERR_FSTAT;
  34940. }
  34941. return rc;
  34942. }
  34943. /*
  34944. ** This function is called by unixOpen() to determine the unix permissions
  34945. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  34946. ** and a value suitable for passing as the third argument to open(2) is
  34947. ** written to *pMode. If an IO error occurs, an SQLite error code is
  34948. ** returned and the value of *pMode is not modified.
  34949. **
  34950. ** In most cases, this routine sets *pMode to 0, which will become
  34951. ** an indication to robust_open() to create the file using
  34952. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  34953. ** But if the file being opened is a WAL or regular journal file, then
  34954. ** this function queries the file-system for the permissions on the
  34955. ** corresponding database file and sets *pMode to this value. Whenever
  34956. ** possible, WAL and journal files are created using the same permissions
  34957. ** as the associated database file.
  34958. **
  34959. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  34960. ** original filename is unavailable. But 8_3_NAMES is only used for
  34961. ** FAT filesystems and permissions do not matter there, so just use
  34962. ** the default permissions.
  34963. */
  34964. static int findCreateFileMode(
  34965. const char *zPath, /* Path of file (possibly) being created */
  34966. int flags, /* Flags passed as 4th argument to xOpen() */
  34967. mode_t *pMode, /* OUT: Permissions to open file with */
  34968. uid_t *pUid, /* OUT: uid to set on the file */
  34969. gid_t *pGid /* OUT: gid to set on the file */
  34970. ){
  34971. int rc = SQLITE_OK; /* Return Code */
  34972. *pMode = 0;
  34973. *pUid = 0;
  34974. *pGid = 0;
  34975. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  34976. char zDb[MAX_PATHNAME+1]; /* Database file path */
  34977. int nDb; /* Number of valid bytes in zDb */
  34978. /* zPath is a path to a WAL or journal file. The following block derives
  34979. ** the path to the associated database file from zPath. This block handles
  34980. ** the following naming conventions:
  34981. **
  34982. ** "<path to db>-journal"
  34983. ** "<path to db>-wal"
  34984. ** "<path to db>-journalNN"
  34985. ** "<path to db>-walNN"
  34986. **
  34987. ** where NN is a decimal number. The NN naming schemes are
  34988. ** used by the test_multiplex.c module.
  34989. */
  34990. nDb = sqlite3Strlen30(zPath) - 1;
  34991. while( zPath[nDb]!='-' ){
  34992. /* In normal operation, the journal file name will always contain
  34993. ** a '-' character. However in 8+3 filename mode, or if a corrupt
  34994. ** rollback journal specifies a master journal with a goofy name, then
  34995. ** the '-' might be missing. */
  34996. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  34997. nDb--;
  34998. }
  34999. memcpy(zDb, zPath, nDb);
  35000. zDb[nDb] = '\0';
  35001. rc = getFileMode(zDb, pMode, pUid, pGid);
  35002. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  35003. *pMode = 0600;
  35004. }else if( flags & SQLITE_OPEN_URI ){
  35005. /* If this is a main database file and the file was opened using a URI
  35006. ** filename, check for the "modeof" parameter. If present, interpret
  35007. ** its value as a filename and try to copy the mode, uid and gid from
  35008. ** that file. */
  35009. const char *z = sqlite3_uri_parameter(zPath, "modeof");
  35010. if( z ){
  35011. rc = getFileMode(z, pMode, pUid, pGid);
  35012. }
  35013. }
  35014. return rc;
  35015. }
  35016. /*
  35017. ** Open the file zPath.
  35018. **
  35019. ** Previously, the SQLite OS layer used three functions in place of this
  35020. ** one:
  35021. **
  35022. ** sqlite3OsOpenReadWrite();
  35023. ** sqlite3OsOpenReadOnly();
  35024. ** sqlite3OsOpenExclusive();
  35025. **
  35026. ** These calls correspond to the following combinations of flags:
  35027. **
  35028. ** ReadWrite() -> (READWRITE | CREATE)
  35029. ** ReadOnly() -> (READONLY)
  35030. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  35031. **
  35032. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  35033. ** true, the file was configured to be automatically deleted when the
  35034. ** file handle closed. To achieve the same effect using this new
  35035. ** interface, add the DELETEONCLOSE flag to those specified above for
  35036. ** OpenExclusive().
  35037. */
  35038. static int unixOpen(
  35039. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  35040. const char *zPath, /* Pathname of file to be opened */
  35041. sqlite3_file *pFile, /* The file descriptor to be filled in */
  35042. int flags, /* Input flags to control the opening */
  35043. int *pOutFlags /* Output flags returned to SQLite core */
  35044. ){
  35045. unixFile *p = (unixFile *)pFile;
  35046. int fd = -1; /* File descriptor returned by open() */
  35047. int openFlags = 0; /* Flags to pass to open() */
  35048. int eType = flags&0xFFFFFF00; /* Type of file to open */
  35049. int noLock; /* True to omit locking primitives */
  35050. int rc = SQLITE_OK; /* Function Return Code */
  35051. int ctrlFlags = 0; /* UNIXFILE_* flags */
  35052. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  35053. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  35054. int isCreate = (flags & SQLITE_OPEN_CREATE);
  35055. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  35056. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  35057. #if SQLITE_ENABLE_LOCKING_STYLE
  35058. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  35059. #endif
  35060. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  35061. struct statfs fsInfo;
  35062. #endif
  35063. /* If creating a master or main-file journal, this function will open
  35064. ** a file-descriptor on the directory too. The first time unixSync()
  35065. ** is called the directory file descriptor will be fsync()ed and close()d.
  35066. */
  35067. int isNewJrnl = (isCreate && (
  35068. eType==SQLITE_OPEN_MASTER_JOURNAL
  35069. || eType==SQLITE_OPEN_MAIN_JOURNAL
  35070. || eType==SQLITE_OPEN_WAL
  35071. ));
  35072. /* If argument zPath is a NULL pointer, this function is required to open
  35073. ** a temporary file. Use this buffer to store the file name in.
  35074. */
  35075. char zTmpname[MAX_PATHNAME+2];
  35076. const char *zName = zPath;
  35077. /* Check the following statements are true:
  35078. **
  35079. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  35080. ** (b) if CREATE is set, then READWRITE must also be set, and
  35081. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  35082. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  35083. */
  35084. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  35085. assert(isCreate==0 || isReadWrite);
  35086. assert(isExclusive==0 || isCreate);
  35087. assert(isDelete==0 || isCreate);
  35088. /* The main DB, main journal, WAL file and master journal are never
  35089. ** automatically deleted. Nor are they ever temporary files. */
  35090. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  35091. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  35092. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  35093. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  35094. /* Assert that the upper layer has set one of the "file-type" flags. */
  35095. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  35096. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  35097. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  35098. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  35099. );
  35100. /* Detect a pid change and reset the PRNG. There is a race condition
  35101. ** here such that two or more threads all trying to open databases at
  35102. ** the same instant might all reset the PRNG. But multiple resets
  35103. ** are harmless.
  35104. */
  35105. if( randomnessPid!=osGetpid(0) ){
  35106. randomnessPid = osGetpid(0);
  35107. sqlite3_randomness(0,0);
  35108. }
  35109. memset(p, 0, sizeof(unixFile));
  35110. if( eType==SQLITE_OPEN_MAIN_DB ){
  35111. UnixUnusedFd *pUnused;
  35112. pUnused = findReusableFd(zName, flags);
  35113. if( pUnused ){
  35114. fd = pUnused->fd;
  35115. }else{
  35116. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  35117. if( !pUnused ){
  35118. return SQLITE_NOMEM_BKPT;
  35119. }
  35120. }
  35121. p->pPreallocatedUnused = pUnused;
  35122. /* Database filenames are double-zero terminated if they are not
  35123. ** URIs with parameters. Hence, they can always be passed into
  35124. ** sqlite3_uri_parameter(). */
  35125. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  35126. }else if( !zName ){
  35127. /* If zName is NULL, the upper layer is requesting a temp file. */
  35128. assert(isDelete && !isNewJrnl);
  35129. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  35130. if( rc!=SQLITE_OK ){
  35131. return rc;
  35132. }
  35133. zName = zTmpname;
  35134. /* Generated temporary filenames are always double-zero terminated
  35135. ** for use by sqlite3_uri_parameter(). */
  35136. assert( zName[strlen(zName)+1]==0 );
  35137. }
  35138. /* Determine the value of the flags parameter passed to POSIX function
  35139. ** open(). These must be calculated even if open() is not called, as
  35140. ** they may be stored as part of the file handle and used by the
  35141. ** 'conch file' locking functions later on. */
  35142. if( isReadonly ) openFlags |= O_RDONLY;
  35143. if( isReadWrite ) openFlags |= O_RDWR;
  35144. if( isCreate ) openFlags |= O_CREAT;
  35145. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  35146. openFlags |= (O_LARGEFILE|O_BINARY);
  35147. if( fd<0 ){
  35148. mode_t openMode; /* Permissions to create file with */
  35149. uid_t uid; /* Userid for the file */
  35150. gid_t gid; /* Groupid for the file */
  35151. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  35152. if( rc!=SQLITE_OK ){
  35153. assert( !p->pPreallocatedUnused );
  35154. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  35155. return rc;
  35156. }
  35157. fd = robust_open(zName, openFlags, openMode);
  35158. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  35159. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  35160. if( fd<0 ){
  35161. if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
  35162. /* If unable to create a journal because the directory is not
  35163. ** writable, change the error code to indicate that. */
  35164. rc = SQLITE_READONLY_DIRECTORY;
  35165. }else if( errno!=EISDIR && isReadWrite ){
  35166. /* Failed to open the file for read/write access. Try read-only. */
  35167. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  35168. openFlags &= ~(O_RDWR|O_CREAT);
  35169. flags |= SQLITE_OPEN_READONLY;
  35170. openFlags |= O_RDONLY;
  35171. isReadonly = 1;
  35172. fd = robust_open(zName, openFlags, openMode);
  35173. }
  35174. }
  35175. if( fd<0 ){
  35176. int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  35177. if( rc==SQLITE_OK ) rc = rc2;
  35178. goto open_finished;
  35179. }
  35180. /* If this process is running as root and if creating a new rollback
  35181. ** journal or WAL file, set the ownership of the journal or WAL to be
  35182. ** the same as the original database.
  35183. */
  35184. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  35185. robustFchown(fd, uid, gid);
  35186. }
  35187. }
  35188. assert( fd>=0 );
  35189. if( pOutFlags ){
  35190. *pOutFlags = flags;
  35191. }
  35192. if( p->pPreallocatedUnused ){
  35193. p->pPreallocatedUnused->fd = fd;
  35194. p->pPreallocatedUnused->flags = flags;
  35195. }
  35196. if( isDelete ){
  35197. #if OS_VXWORKS
  35198. zPath = zName;
  35199. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  35200. zPath = sqlite3_mprintf("%s", zName);
  35201. if( zPath==0 ){
  35202. robust_close(p, fd, __LINE__);
  35203. return SQLITE_NOMEM_BKPT;
  35204. }
  35205. #else
  35206. osUnlink(zName);
  35207. #endif
  35208. }
  35209. #if SQLITE_ENABLE_LOCKING_STYLE
  35210. else{
  35211. p->openFlags = openFlags;
  35212. }
  35213. #endif
  35214. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  35215. if( fstatfs(fd, &fsInfo) == -1 ){
  35216. storeLastErrno(p, errno);
  35217. robust_close(p, fd, __LINE__);
  35218. return SQLITE_IOERR_ACCESS;
  35219. }
  35220. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  35221. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  35222. }
  35223. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  35224. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  35225. }
  35226. #endif
  35227. /* Set up appropriate ctrlFlags */
  35228. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  35229. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  35230. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  35231. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  35232. if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
  35233. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  35234. #if SQLITE_ENABLE_LOCKING_STYLE
  35235. #if SQLITE_PREFER_PROXY_LOCKING
  35236. isAutoProxy = 1;
  35237. #endif
  35238. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  35239. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  35240. int useProxy = 0;
  35241. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  35242. ** never use proxy, NULL means use proxy for non-local files only. */
  35243. if( envforce!=NULL ){
  35244. useProxy = atoi(envforce)>0;
  35245. }else{
  35246. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  35247. }
  35248. if( useProxy ){
  35249. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  35250. if( rc==SQLITE_OK ){
  35251. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  35252. if( rc!=SQLITE_OK ){
  35253. /* Use unixClose to clean up the resources added in fillInUnixFile
  35254. ** and clear all the structure's references. Specifically,
  35255. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  35256. */
  35257. unixClose(pFile);
  35258. return rc;
  35259. }
  35260. }
  35261. goto open_finished;
  35262. }
  35263. }
  35264. #endif
  35265. assert( zPath==0 || zPath[0]=='/'
  35266. || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
  35267. );
  35268. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  35269. open_finished:
  35270. if( rc!=SQLITE_OK ){
  35271. sqlite3_free(p->pPreallocatedUnused);
  35272. }
  35273. return rc;
  35274. }
  35275. /*
  35276. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  35277. ** the directory after deleting the file.
  35278. */
  35279. static int unixDelete(
  35280. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  35281. const char *zPath, /* Name of file to be deleted */
  35282. int dirSync /* If true, fsync() directory after deleting file */
  35283. ){
  35284. int rc = SQLITE_OK;
  35285. UNUSED_PARAMETER(NotUsed);
  35286. SimulateIOError(return SQLITE_IOERR_DELETE);
  35287. if( osUnlink(zPath)==(-1) ){
  35288. if( errno==ENOENT
  35289. #if OS_VXWORKS
  35290. || osAccess(zPath,0)!=0
  35291. #endif
  35292. ){
  35293. rc = SQLITE_IOERR_DELETE_NOENT;
  35294. }else{
  35295. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  35296. }
  35297. return rc;
  35298. }
  35299. #ifndef SQLITE_DISABLE_DIRSYNC
  35300. if( (dirSync & 1)!=0 ){
  35301. int fd;
  35302. rc = osOpenDirectory(zPath, &fd);
  35303. if( rc==SQLITE_OK ){
  35304. if( full_fsync(fd,0,0) ){
  35305. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  35306. }
  35307. robust_close(0, fd, __LINE__);
  35308. }else{
  35309. assert( rc==SQLITE_CANTOPEN );
  35310. rc = SQLITE_OK;
  35311. }
  35312. }
  35313. #endif
  35314. return rc;
  35315. }
  35316. /*
  35317. ** Test the existence of or access permissions of file zPath. The
  35318. ** test performed depends on the value of flags:
  35319. **
  35320. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  35321. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  35322. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  35323. **
  35324. ** Otherwise return 0.
  35325. */
  35326. static int unixAccess(
  35327. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  35328. const char *zPath, /* Path of the file to examine */
  35329. int flags, /* What do we want to learn about the zPath file? */
  35330. int *pResOut /* Write result boolean here */
  35331. ){
  35332. UNUSED_PARAMETER(NotUsed);
  35333. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  35334. assert( pResOut!=0 );
  35335. /* The spec says there are three possible values for flags. But only
  35336. ** two of them are actually used */
  35337. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  35338. if( flags==SQLITE_ACCESS_EXISTS ){
  35339. struct stat buf;
  35340. *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
  35341. }else{
  35342. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  35343. }
  35344. return SQLITE_OK;
  35345. }
  35346. /*
  35347. **
  35348. */
  35349. static int mkFullPathname(
  35350. const char *zPath, /* Input path */
  35351. char *zOut, /* Output buffer */
  35352. int nOut /* Allocated size of buffer zOut */
  35353. ){
  35354. int nPath = sqlite3Strlen30(zPath);
  35355. int iOff = 0;
  35356. if( zPath[0]!='/' ){
  35357. if( osGetcwd(zOut, nOut-2)==0 ){
  35358. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  35359. }
  35360. iOff = sqlite3Strlen30(zOut);
  35361. zOut[iOff++] = '/';
  35362. }
  35363. if( (iOff+nPath+1)>nOut ){
  35364. /* SQLite assumes that xFullPathname() nul-terminates the output buffer
  35365. ** even if it returns an error. */
  35366. zOut[iOff] = '\0';
  35367. return SQLITE_CANTOPEN_BKPT;
  35368. }
  35369. sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
  35370. return SQLITE_OK;
  35371. }
  35372. /*
  35373. ** Turn a relative pathname into a full pathname. The relative path
  35374. ** is stored as a nul-terminated string in the buffer pointed to by
  35375. ** zPath.
  35376. **
  35377. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  35378. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  35379. ** this buffer before returning.
  35380. */
  35381. static int unixFullPathname(
  35382. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  35383. const char *zPath, /* Possibly relative input path */
  35384. int nOut, /* Size of output buffer in bytes */
  35385. char *zOut /* Output buffer */
  35386. ){
  35387. #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
  35388. return mkFullPathname(zPath, zOut, nOut);
  35389. #else
  35390. int rc = SQLITE_OK;
  35391. int nByte;
  35392. int nLink = 1; /* Number of symbolic links followed so far */
  35393. const char *zIn = zPath; /* Input path for each iteration of loop */
  35394. char *zDel = 0;
  35395. assert( pVfs->mxPathname==MAX_PATHNAME );
  35396. UNUSED_PARAMETER(pVfs);
  35397. /* It's odd to simulate an io-error here, but really this is just
  35398. ** using the io-error infrastructure to test that SQLite handles this
  35399. ** function failing. This function could fail if, for example, the
  35400. ** current working directory has been unlinked.
  35401. */
  35402. SimulateIOError( return SQLITE_ERROR );
  35403. do {
  35404. /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
  35405. ** link, or false otherwise. */
  35406. int bLink = 0;
  35407. struct stat buf;
  35408. if( osLstat(zIn, &buf)!=0 ){
  35409. if( errno!=ENOENT ){
  35410. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
  35411. }
  35412. }else{
  35413. bLink = S_ISLNK(buf.st_mode);
  35414. }
  35415. if( bLink ){
  35416. if( zDel==0 ){
  35417. zDel = sqlite3_malloc(nOut);
  35418. if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
  35419. }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
  35420. rc = SQLITE_CANTOPEN_BKPT;
  35421. }
  35422. if( rc==SQLITE_OK ){
  35423. nByte = osReadlink(zIn, zDel, nOut-1);
  35424. if( nByte<0 ){
  35425. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
  35426. }else{
  35427. if( zDel[0]!='/' ){
  35428. int n;
  35429. for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
  35430. if( nByte+n+1>nOut ){
  35431. rc = SQLITE_CANTOPEN_BKPT;
  35432. }else{
  35433. memmove(&zDel[n], zDel, nByte+1);
  35434. memcpy(zDel, zIn, n);
  35435. nByte += n;
  35436. }
  35437. }
  35438. zDel[nByte] = '\0';
  35439. }
  35440. }
  35441. zIn = zDel;
  35442. }
  35443. assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
  35444. if( rc==SQLITE_OK && zIn!=zOut ){
  35445. rc = mkFullPathname(zIn, zOut, nOut);
  35446. }
  35447. if( bLink==0 ) break;
  35448. zIn = zOut;
  35449. }while( rc==SQLITE_OK );
  35450. sqlite3_free(zDel);
  35451. return rc;
  35452. #endif /* HAVE_READLINK && HAVE_LSTAT */
  35453. }
  35454. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  35455. /*
  35456. ** Interfaces for opening a shared library, finding entry points
  35457. ** within the shared library, and closing the shared library.
  35458. */
  35459. #include <dlfcn.h>
  35460. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  35461. UNUSED_PARAMETER(NotUsed);
  35462. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  35463. }
  35464. /*
  35465. ** SQLite calls this function immediately after a call to unixDlSym() or
  35466. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  35467. ** message is available, it is written to zBufOut. If no error message
  35468. ** is available, zBufOut is left unmodified and SQLite uses a default
  35469. ** error message.
  35470. */
  35471. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  35472. const char *zErr;
  35473. UNUSED_PARAMETER(NotUsed);
  35474. unixEnterMutex();
  35475. zErr = dlerror();
  35476. if( zErr ){
  35477. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  35478. }
  35479. unixLeaveMutex();
  35480. }
  35481. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  35482. /*
  35483. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  35484. ** cast into a pointer to a function. And yet the library dlsym() routine
  35485. ** returns a void* which is really a pointer to a function. So how do we
  35486. ** use dlsym() with -pedantic-errors?
  35487. **
  35488. ** Variable x below is defined to be a pointer to a function taking
  35489. ** parameters void* and const char* and returning a pointer to a function.
  35490. ** We initialize x by assigning it a pointer to the dlsym() function.
  35491. ** (That assignment requires a cast.) Then we call the function that
  35492. ** x points to.
  35493. **
  35494. ** This work-around is unlikely to work correctly on any system where
  35495. ** you really cannot cast a function pointer into void*. But then, on the
  35496. ** other hand, dlsym() will not work on such a system either, so we have
  35497. ** not really lost anything.
  35498. */
  35499. void (*(*x)(void*,const char*))(void);
  35500. UNUSED_PARAMETER(NotUsed);
  35501. x = (void(*(*)(void*,const char*))(void))dlsym;
  35502. return (*x)(p, zSym);
  35503. }
  35504. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  35505. UNUSED_PARAMETER(NotUsed);
  35506. dlclose(pHandle);
  35507. }
  35508. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  35509. #define unixDlOpen 0
  35510. #define unixDlError 0
  35511. #define unixDlSym 0
  35512. #define unixDlClose 0
  35513. #endif
  35514. /*
  35515. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  35516. */
  35517. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  35518. UNUSED_PARAMETER(NotUsed);
  35519. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  35520. /* We have to initialize zBuf to prevent valgrind from reporting
  35521. ** errors. The reports issued by valgrind are incorrect - we would
  35522. ** prefer that the randomness be increased by making use of the
  35523. ** uninitialized space in zBuf - but valgrind errors tend to worry
  35524. ** some users. Rather than argue, it seems easier just to initialize
  35525. ** the whole array and silence valgrind, even if that means less randomness
  35526. ** in the random seed.
  35527. **
  35528. ** When testing, initializing zBuf[] to zero is all we do. That means
  35529. ** that we always use the same random number sequence. This makes the
  35530. ** tests repeatable.
  35531. */
  35532. memset(zBuf, 0, nBuf);
  35533. randomnessPid = osGetpid(0);
  35534. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  35535. {
  35536. int fd, got;
  35537. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  35538. if( fd<0 ){
  35539. time_t t;
  35540. time(&t);
  35541. memcpy(zBuf, &t, sizeof(t));
  35542. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  35543. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  35544. nBuf = sizeof(t) + sizeof(randomnessPid);
  35545. }else{
  35546. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  35547. robust_close(0, fd, __LINE__);
  35548. }
  35549. }
  35550. #endif
  35551. return nBuf;
  35552. }
  35553. /*
  35554. ** Sleep for a little while. Return the amount of time slept.
  35555. ** The argument is the number of microseconds we want to sleep.
  35556. ** The return value is the number of microseconds of sleep actually
  35557. ** requested from the underlying operating system, a number which
  35558. ** might be greater than or equal to the argument, but not less
  35559. ** than the argument.
  35560. */
  35561. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  35562. #if OS_VXWORKS
  35563. struct timespec sp;
  35564. sp.tv_sec = microseconds / 1000000;
  35565. sp.tv_nsec = (microseconds % 1000000) * 1000;
  35566. nanosleep(&sp, NULL);
  35567. UNUSED_PARAMETER(NotUsed);
  35568. return microseconds;
  35569. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  35570. usleep(microseconds);
  35571. UNUSED_PARAMETER(NotUsed);
  35572. return microseconds;
  35573. #else
  35574. int seconds = (microseconds+999999)/1000000;
  35575. sleep(seconds);
  35576. UNUSED_PARAMETER(NotUsed);
  35577. return seconds*1000000;
  35578. #endif
  35579. }
  35580. /*
  35581. ** The following variable, if set to a non-zero value, is interpreted as
  35582. ** the number of seconds since 1970 and is used to set the result of
  35583. ** sqlite3OsCurrentTime() during testing.
  35584. */
  35585. #ifdef SQLITE_TEST
  35586. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  35587. #endif
  35588. /*
  35589. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  35590. ** the current time and date as a Julian Day number times 86_400_000. In
  35591. ** other words, write into *piNow the number of milliseconds since the Julian
  35592. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  35593. ** proleptic Gregorian calendar.
  35594. **
  35595. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  35596. ** cannot be found.
  35597. */
  35598. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  35599. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  35600. int rc = SQLITE_OK;
  35601. #if defined(NO_GETTOD)
  35602. time_t t;
  35603. time(&t);
  35604. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  35605. #elif OS_VXWORKS
  35606. struct timespec sNow;
  35607. clock_gettime(CLOCK_REALTIME, &sNow);
  35608. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  35609. #else
  35610. struct timeval sNow;
  35611. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  35612. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  35613. #endif
  35614. #ifdef SQLITE_TEST
  35615. if( sqlite3_current_time ){
  35616. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  35617. }
  35618. #endif
  35619. UNUSED_PARAMETER(NotUsed);
  35620. return rc;
  35621. }
  35622. #ifndef SQLITE_OMIT_DEPRECATED
  35623. /*
  35624. ** Find the current time (in Universal Coordinated Time). Write the
  35625. ** current time and date as a Julian Day number into *prNow and
  35626. ** return 0. Return 1 if the time and date cannot be found.
  35627. */
  35628. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  35629. sqlite3_int64 i = 0;
  35630. int rc;
  35631. UNUSED_PARAMETER(NotUsed);
  35632. rc = unixCurrentTimeInt64(0, &i);
  35633. *prNow = i/86400000.0;
  35634. return rc;
  35635. }
  35636. #else
  35637. # define unixCurrentTime 0
  35638. #endif
  35639. /*
  35640. ** The xGetLastError() method is designed to return a better
  35641. ** low-level error message when operating-system problems come up
  35642. ** during SQLite operation. Only the integer return code is currently
  35643. ** used.
  35644. */
  35645. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  35646. UNUSED_PARAMETER(NotUsed);
  35647. UNUSED_PARAMETER(NotUsed2);
  35648. UNUSED_PARAMETER(NotUsed3);
  35649. return errno;
  35650. }
  35651. /*
  35652. ************************ End of sqlite3_vfs methods ***************************
  35653. ******************************************************************************/
  35654. /******************************************************************************
  35655. ************************** Begin Proxy Locking ********************************
  35656. **
  35657. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  35658. ** other locking methods on secondary lock files. Proxy locking is a
  35659. ** meta-layer over top of the primitive locking implemented above. For
  35660. ** this reason, the division that implements of proxy locking is deferred
  35661. ** until late in the file (here) after all of the other I/O methods have
  35662. ** been defined - so that the primitive locking methods are available
  35663. ** as services to help with the implementation of proxy locking.
  35664. **
  35665. ****
  35666. **
  35667. ** The default locking schemes in SQLite use byte-range locks on the
  35668. ** database file to coordinate safe, concurrent access by multiple readers
  35669. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  35670. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  35671. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  35672. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  35673. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  35674. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  35675. ** address in the shared range is taken for a SHARED lock, the entire
  35676. ** shared range is taken for an EXCLUSIVE lock):
  35677. **
  35678. ** PENDING_BYTE 0x40000000
  35679. ** RESERVED_BYTE 0x40000001
  35680. ** SHARED_RANGE 0x40000002 -> 0x40000200
  35681. **
  35682. ** This works well on the local file system, but shows a nearly 100x
  35683. ** slowdown in read performance on AFP because the AFP client disables
  35684. ** the read cache when byte-range locks are present. Enabling the read
  35685. ** cache exposes a cache coherency problem that is present on all OS X
  35686. ** supported network file systems. NFS and AFP both observe the
  35687. ** close-to-open semantics for ensuring cache coherency
  35688. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  35689. ** address the requirements for concurrent database access by multiple
  35690. ** readers and writers
  35691. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  35692. **
  35693. ** To address the performance and cache coherency issues, proxy file locking
  35694. ** changes the way database access is controlled by limiting access to a
  35695. ** single host at a time and moving file locks off of the database file
  35696. ** and onto a proxy file on the local file system.
  35697. **
  35698. **
  35699. ** Using proxy locks
  35700. ** -----------------
  35701. **
  35702. ** C APIs
  35703. **
  35704. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  35705. ** <proxy_path> | ":auto:");
  35706. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  35707. ** &<proxy_path>);
  35708. **
  35709. **
  35710. ** SQL pragmas
  35711. **
  35712. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  35713. ** PRAGMA [database.]lock_proxy_file
  35714. **
  35715. ** Specifying ":auto:" means that if there is a conch file with a matching
  35716. ** host ID in it, the proxy path in the conch file will be used, otherwise
  35717. ** a proxy path based on the user's temp dir
  35718. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  35719. ** actual proxy file name is generated from the name and path of the
  35720. ** database file. For example:
  35721. **
  35722. ** For database path "/Users/me/foo.db"
  35723. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  35724. **
  35725. ** Once a lock proxy is configured for a database connection, it can not
  35726. ** be removed, however it may be switched to a different proxy path via
  35727. ** the above APIs (assuming the conch file is not being held by another
  35728. ** connection or process).
  35729. **
  35730. **
  35731. ** How proxy locking works
  35732. ** -----------------------
  35733. **
  35734. ** Proxy file locking relies primarily on two new supporting files:
  35735. **
  35736. ** * conch file to limit access to the database file to a single host
  35737. ** at a time
  35738. **
  35739. ** * proxy file to act as a proxy for the advisory locks normally
  35740. ** taken on the database
  35741. **
  35742. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  35743. ** by taking an sqlite-style shared lock on the conch file, reading the
  35744. ** contents and comparing the host's unique host ID (see below) and lock
  35745. ** proxy path against the values stored in the conch. The conch file is
  35746. ** stored in the same directory as the database file and the file name
  35747. ** is patterned after the database file name as ".<databasename>-conch".
  35748. ** If the conch file does not exist, or its contents do not match the
  35749. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  35750. ** lock and the conch file contents is updated with the host ID and proxy
  35751. ** path and the lock is downgraded to a shared lock again. If the conch
  35752. ** is held by another process (with a shared lock), the exclusive lock
  35753. ** will fail and SQLITE_BUSY is returned.
  35754. **
  35755. ** The proxy file - a single-byte file used for all advisory file locks
  35756. ** normally taken on the database file. This allows for safe sharing
  35757. ** of the database file for multiple readers and writers on the same
  35758. ** host (the conch ensures that they all use the same local lock file).
  35759. **
  35760. ** Requesting the lock proxy does not immediately take the conch, it is
  35761. ** only taken when the first request to lock database file is made.
  35762. ** This matches the semantics of the traditional locking behavior, where
  35763. ** opening a connection to a database file does not take a lock on it.
  35764. ** The shared lock and an open file descriptor are maintained until
  35765. ** the connection to the database is closed.
  35766. **
  35767. ** The proxy file and the lock file are never deleted so they only need
  35768. ** to be created the first time they are used.
  35769. **
  35770. ** Configuration options
  35771. ** ---------------------
  35772. **
  35773. ** SQLITE_PREFER_PROXY_LOCKING
  35774. **
  35775. ** Database files accessed on non-local file systems are
  35776. ** automatically configured for proxy locking, lock files are
  35777. ** named automatically using the same logic as
  35778. ** PRAGMA lock_proxy_file=":auto:"
  35779. **
  35780. ** SQLITE_PROXY_DEBUG
  35781. **
  35782. ** Enables the logging of error messages during host id file
  35783. ** retrieval and creation
  35784. **
  35785. ** LOCKPROXYDIR
  35786. **
  35787. ** Overrides the default directory used for lock proxy files that
  35788. ** are named automatically via the ":auto:" setting
  35789. **
  35790. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  35791. **
  35792. ** Permissions to use when creating a directory for storing the
  35793. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  35794. **
  35795. **
  35796. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  35797. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  35798. ** force proxy locking to be used for every database file opened, and 0
  35799. ** will force automatic proxy locking to be disabled for all database
  35800. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  35801. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  35802. */
  35803. /*
  35804. ** Proxy locking is only available on MacOSX
  35805. */
  35806. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  35807. /*
  35808. ** The proxyLockingContext has the path and file structures for the remote
  35809. ** and local proxy files in it
  35810. */
  35811. typedef struct proxyLockingContext proxyLockingContext;
  35812. struct proxyLockingContext {
  35813. unixFile *conchFile; /* Open conch file */
  35814. char *conchFilePath; /* Name of the conch file */
  35815. unixFile *lockProxy; /* Open proxy lock file */
  35816. char *lockProxyPath; /* Name of the proxy lock file */
  35817. char *dbPath; /* Name of the open file */
  35818. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  35819. int nFails; /* Number of conch taking failures */
  35820. void *oldLockingContext; /* Original lockingcontext to restore on close */
  35821. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  35822. };
  35823. /*
  35824. ** The proxy lock file path for the database at dbPath is written into lPath,
  35825. ** which must point to valid, writable memory large enough for a maxLen length
  35826. ** file path.
  35827. */
  35828. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  35829. int len;
  35830. int dbLen;
  35831. int i;
  35832. #ifdef LOCKPROXYDIR
  35833. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  35834. #else
  35835. # ifdef _CS_DARWIN_USER_TEMP_DIR
  35836. {
  35837. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  35838. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  35839. lPath, errno, osGetpid(0)));
  35840. return SQLITE_IOERR_LOCK;
  35841. }
  35842. len = strlcat(lPath, "sqliteplocks", maxLen);
  35843. }
  35844. # else
  35845. len = strlcpy(lPath, "/tmp/", maxLen);
  35846. # endif
  35847. #endif
  35848. if( lPath[len-1]!='/' ){
  35849. len = strlcat(lPath, "/", maxLen);
  35850. }
  35851. /* transform the db path to a unique cache name */
  35852. dbLen = (int)strlen(dbPath);
  35853. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  35854. char c = dbPath[i];
  35855. lPath[i+len] = (c=='/')?'_':c;
  35856. }
  35857. lPath[i+len]='\0';
  35858. strlcat(lPath, ":auto:", maxLen);
  35859. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  35860. return SQLITE_OK;
  35861. }
  35862. /*
  35863. ** Creates the lock file and any missing directories in lockPath
  35864. */
  35865. static int proxyCreateLockPath(const char *lockPath){
  35866. int i, len;
  35867. char buf[MAXPATHLEN];
  35868. int start = 0;
  35869. assert(lockPath!=NULL);
  35870. /* try to create all the intermediate directories */
  35871. len = (int)strlen(lockPath);
  35872. buf[0] = lockPath[0];
  35873. for( i=1; i<len; i++ ){
  35874. if( lockPath[i] == '/' && (i - start > 0) ){
  35875. /* only mkdir if leaf dir != "." or "/" or ".." */
  35876. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  35877. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  35878. buf[i]='\0';
  35879. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  35880. int err=errno;
  35881. if( err!=EEXIST ) {
  35882. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  35883. "'%s' proxy lock path=%s pid=%d\n",
  35884. buf, strerror(err), lockPath, osGetpid(0)));
  35885. return err;
  35886. }
  35887. }
  35888. }
  35889. start=i+1;
  35890. }
  35891. buf[i] = lockPath[i];
  35892. }
  35893. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  35894. return 0;
  35895. }
  35896. /*
  35897. ** Create a new VFS file descriptor (stored in memory obtained from
  35898. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  35899. **
  35900. ** The caller is responsible not only for closing the file descriptor
  35901. ** but also for freeing the memory associated with the file descriptor.
  35902. */
  35903. static int proxyCreateUnixFile(
  35904. const char *path, /* path for the new unixFile */
  35905. unixFile **ppFile, /* unixFile created and returned by ref */
  35906. int islockfile /* if non zero missing dirs will be created */
  35907. ) {
  35908. int fd = -1;
  35909. unixFile *pNew;
  35910. int rc = SQLITE_OK;
  35911. int openFlags = O_RDWR | O_CREAT;
  35912. sqlite3_vfs dummyVfs;
  35913. int terrno = 0;
  35914. UnixUnusedFd *pUnused = NULL;
  35915. /* 1. first try to open/create the file
  35916. ** 2. if that fails, and this is a lock file (not-conch), try creating
  35917. ** the parent directories and then try again.
  35918. ** 3. if that fails, try to open the file read-only
  35919. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  35920. */
  35921. pUnused = findReusableFd(path, openFlags);
  35922. if( pUnused ){
  35923. fd = pUnused->fd;
  35924. }else{
  35925. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  35926. if( !pUnused ){
  35927. return SQLITE_NOMEM_BKPT;
  35928. }
  35929. }
  35930. if( fd<0 ){
  35931. fd = robust_open(path, openFlags, 0);
  35932. terrno = errno;
  35933. if( fd<0 && errno==ENOENT && islockfile ){
  35934. if( proxyCreateLockPath(path) == SQLITE_OK ){
  35935. fd = robust_open(path, openFlags, 0);
  35936. }
  35937. }
  35938. }
  35939. if( fd<0 ){
  35940. openFlags = O_RDONLY;
  35941. fd = robust_open(path, openFlags, 0);
  35942. terrno = errno;
  35943. }
  35944. if( fd<0 ){
  35945. if( islockfile ){
  35946. return SQLITE_BUSY;
  35947. }
  35948. switch (terrno) {
  35949. case EACCES:
  35950. return SQLITE_PERM;
  35951. case EIO:
  35952. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  35953. default:
  35954. return SQLITE_CANTOPEN_BKPT;
  35955. }
  35956. }
  35957. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  35958. if( pNew==NULL ){
  35959. rc = SQLITE_NOMEM_BKPT;
  35960. goto end_create_proxy;
  35961. }
  35962. memset(pNew, 0, sizeof(unixFile));
  35963. pNew->openFlags = openFlags;
  35964. memset(&dummyVfs, 0, sizeof(dummyVfs));
  35965. dummyVfs.pAppData = (void*)&autolockIoFinder;
  35966. dummyVfs.zName = "dummy";
  35967. pUnused->fd = fd;
  35968. pUnused->flags = openFlags;
  35969. pNew->pPreallocatedUnused = pUnused;
  35970. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  35971. if( rc==SQLITE_OK ){
  35972. *ppFile = pNew;
  35973. return SQLITE_OK;
  35974. }
  35975. end_create_proxy:
  35976. robust_close(pNew, fd, __LINE__);
  35977. sqlite3_free(pNew);
  35978. sqlite3_free(pUnused);
  35979. return rc;
  35980. }
  35981. #ifdef SQLITE_TEST
  35982. /* simulate multiple hosts by creating unique hostid file paths */
  35983. SQLITE_API int sqlite3_hostid_num = 0;
  35984. #endif
  35985. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  35986. #ifdef HAVE_GETHOSTUUID
  35987. /* Not always defined in the headers as it ought to be */
  35988. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  35989. #endif
  35990. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  35991. ** bytes of writable memory.
  35992. */
  35993. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  35994. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  35995. memset(pHostID, 0, PROXY_HOSTIDLEN);
  35996. #ifdef HAVE_GETHOSTUUID
  35997. {
  35998. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  35999. if( gethostuuid(pHostID, &timeout) ){
  36000. int err = errno;
  36001. if( pError ){
  36002. *pError = err;
  36003. }
  36004. return SQLITE_IOERR;
  36005. }
  36006. }
  36007. #else
  36008. UNUSED_PARAMETER(pError);
  36009. #endif
  36010. #ifdef SQLITE_TEST
  36011. /* simulate multiple hosts by creating unique hostid file paths */
  36012. if( sqlite3_hostid_num != 0){
  36013. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  36014. }
  36015. #endif
  36016. return SQLITE_OK;
  36017. }
  36018. /* The conch file contains the header, host id and lock file path
  36019. */
  36020. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  36021. #define PROXY_HEADERLEN 1 /* conch file header length */
  36022. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  36023. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  36024. /*
  36025. ** Takes an open conch file, copies the contents to a new path and then moves
  36026. ** it back. The newly created file's file descriptor is assigned to the
  36027. ** conch file structure and finally the original conch file descriptor is
  36028. ** closed. Returns zero if successful.
  36029. */
  36030. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  36031. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  36032. unixFile *conchFile = pCtx->conchFile;
  36033. char tPath[MAXPATHLEN];
  36034. char buf[PROXY_MAXCONCHLEN];
  36035. char *cPath = pCtx->conchFilePath;
  36036. size_t readLen = 0;
  36037. size_t pathLen = 0;
  36038. char errmsg[64] = "";
  36039. int fd = -1;
  36040. int rc = -1;
  36041. UNUSED_PARAMETER(myHostID);
  36042. /* create a new path by replace the trailing '-conch' with '-break' */
  36043. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  36044. if( pathLen>MAXPATHLEN || pathLen<6 ||
  36045. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  36046. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  36047. goto end_breaklock;
  36048. }
  36049. /* read the conch content */
  36050. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  36051. if( readLen<PROXY_PATHINDEX ){
  36052. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  36053. goto end_breaklock;
  36054. }
  36055. /* write it out to the temporary break file */
  36056. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  36057. if( fd<0 ){
  36058. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  36059. goto end_breaklock;
  36060. }
  36061. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  36062. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  36063. goto end_breaklock;
  36064. }
  36065. if( rename(tPath, cPath) ){
  36066. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  36067. goto end_breaklock;
  36068. }
  36069. rc = 0;
  36070. fprintf(stderr, "broke stale lock on %s\n", cPath);
  36071. robust_close(pFile, conchFile->h, __LINE__);
  36072. conchFile->h = fd;
  36073. conchFile->openFlags = O_RDWR | O_CREAT;
  36074. end_breaklock:
  36075. if( rc ){
  36076. if( fd>=0 ){
  36077. osUnlink(tPath);
  36078. robust_close(pFile, fd, __LINE__);
  36079. }
  36080. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  36081. }
  36082. return rc;
  36083. }
  36084. /* Take the requested lock on the conch file and break a stale lock if the
  36085. ** host id matches.
  36086. */
  36087. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  36088. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  36089. unixFile *conchFile = pCtx->conchFile;
  36090. int rc = SQLITE_OK;
  36091. int nTries = 0;
  36092. struct timespec conchModTime;
  36093. memset(&conchModTime, 0, sizeof(conchModTime));
  36094. do {
  36095. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  36096. nTries ++;
  36097. if( rc==SQLITE_BUSY ){
  36098. /* If the lock failed (busy):
  36099. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  36100. * 2nd try: fail if the mod time changed or host id is different, wait
  36101. * 10 sec and try again
  36102. * 3rd try: break the lock unless the mod time has changed.
  36103. */
  36104. struct stat buf;
  36105. if( osFstat(conchFile->h, &buf) ){
  36106. storeLastErrno(pFile, errno);
  36107. return SQLITE_IOERR_LOCK;
  36108. }
  36109. if( nTries==1 ){
  36110. conchModTime = buf.st_mtimespec;
  36111. usleep(500000); /* wait 0.5 sec and try the lock again*/
  36112. continue;
  36113. }
  36114. assert( nTries>1 );
  36115. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  36116. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  36117. return SQLITE_BUSY;
  36118. }
  36119. if( nTries==2 ){
  36120. char tBuf[PROXY_MAXCONCHLEN];
  36121. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  36122. if( len<0 ){
  36123. storeLastErrno(pFile, errno);
  36124. return SQLITE_IOERR_LOCK;
  36125. }
  36126. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  36127. /* don't break the lock if the host id doesn't match */
  36128. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  36129. return SQLITE_BUSY;
  36130. }
  36131. }else{
  36132. /* don't break the lock on short read or a version mismatch */
  36133. return SQLITE_BUSY;
  36134. }
  36135. usleep(10000000); /* wait 10 sec and try the lock again */
  36136. continue;
  36137. }
  36138. assert( nTries==3 );
  36139. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  36140. rc = SQLITE_OK;
  36141. if( lockType==EXCLUSIVE_LOCK ){
  36142. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  36143. }
  36144. if( !rc ){
  36145. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  36146. }
  36147. }
  36148. }
  36149. } while( rc==SQLITE_BUSY && nTries<3 );
  36150. return rc;
  36151. }
  36152. /* Takes the conch by taking a shared lock and read the contents conch, if
  36153. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  36154. ** lockPath means that the lockPath in the conch file will be used if the
  36155. ** host IDs match, or a new lock path will be generated automatically
  36156. ** and written to the conch file.
  36157. */
  36158. static int proxyTakeConch(unixFile *pFile){
  36159. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  36160. if( pCtx->conchHeld!=0 ){
  36161. return SQLITE_OK;
  36162. }else{
  36163. unixFile *conchFile = pCtx->conchFile;
  36164. uuid_t myHostID;
  36165. int pError = 0;
  36166. char readBuf[PROXY_MAXCONCHLEN];
  36167. char lockPath[MAXPATHLEN];
  36168. char *tempLockPath = NULL;
  36169. int rc = SQLITE_OK;
  36170. int createConch = 0;
  36171. int hostIdMatch = 0;
  36172. int readLen = 0;
  36173. int tryOldLockPath = 0;
  36174. int forceNewLockPath = 0;
  36175. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  36176. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  36177. osGetpid(0)));
  36178. rc = proxyGetHostID(myHostID, &pError);
  36179. if( (rc&0xff)==SQLITE_IOERR ){
  36180. storeLastErrno(pFile, pError);
  36181. goto end_takeconch;
  36182. }
  36183. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  36184. if( rc!=SQLITE_OK ){
  36185. goto end_takeconch;
  36186. }
  36187. /* read the existing conch file */
  36188. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  36189. if( readLen<0 ){
  36190. /* I/O error: lastErrno set by seekAndRead */
  36191. storeLastErrno(pFile, conchFile->lastErrno);
  36192. rc = SQLITE_IOERR_READ;
  36193. goto end_takeconch;
  36194. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  36195. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  36196. /* a short read or version format mismatch means we need to create a new
  36197. ** conch file.
  36198. */
  36199. createConch = 1;
  36200. }
  36201. /* if the host id matches and the lock path already exists in the conch
  36202. ** we'll try to use the path there, if we can't open that path, we'll
  36203. ** retry with a new auto-generated path
  36204. */
  36205. do { /* in case we need to try again for an :auto: named lock file */
  36206. if( !createConch && !forceNewLockPath ){
  36207. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  36208. PROXY_HOSTIDLEN);
  36209. /* if the conch has data compare the contents */
  36210. if( !pCtx->lockProxyPath ){
  36211. /* for auto-named local lock file, just check the host ID and we'll
  36212. ** use the local lock file path that's already in there
  36213. */
  36214. if( hostIdMatch ){
  36215. size_t pathLen = (readLen - PROXY_PATHINDEX);
  36216. if( pathLen>=MAXPATHLEN ){
  36217. pathLen=MAXPATHLEN-1;
  36218. }
  36219. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  36220. lockPath[pathLen] = 0;
  36221. tempLockPath = lockPath;
  36222. tryOldLockPath = 1;
  36223. /* create a copy of the lock path if the conch is taken */
  36224. goto end_takeconch;
  36225. }
  36226. }else if( hostIdMatch
  36227. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  36228. readLen-PROXY_PATHINDEX)
  36229. ){
  36230. /* conch host and lock path match */
  36231. goto end_takeconch;
  36232. }
  36233. }
  36234. /* if the conch isn't writable and doesn't match, we can't take it */
  36235. if( (conchFile->openFlags&O_RDWR) == 0 ){
  36236. rc = SQLITE_BUSY;
  36237. goto end_takeconch;
  36238. }
  36239. /* either the conch didn't match or we need to create a new one */
  36240. if( !pCtx->lockProxyPath ){
  36241. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  36242. tempLockPath = lockPath;
  36243. /* create a copy of the lock path _only_ if the conch is taken */
  36244. }
  36245. /* update conch with host and path (this will fail if other process
  36246. ** has a shared lock already), if the host id matches, use the big
  36247. ** stick.
  36248. */
  36249. futimes(conchFile->h, NULL);
  36250. if( hostIdMatch && !createConch ){
  36251. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  36252. /* We are trying for an exclusive lock but another thread in this
  36253. ** same process is still holding a shared lock. */
  36254. rc = SQLITE_BUSY;
  36255. } else {
  36256. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  36257. }
  36258. }else{
  36259. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  36260. }
  36261. if( rc==SQLITE_OK ){
  36262. char writeBuffer[PROXY_MAXCONCHLEN];
  36263. int writeSize = 0;
  36264. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  36265. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  36266. if( pCtx->lockProxyPath!=NULL ){
  36267. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  36268. MAXPATHLEN);
  36269. }else{
  36270. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  36271. }
  36272. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  36273. robust_ftruncate(conchFile->h, writeSize);
  36274. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  36275. full_fsync(conchFile->h,0,0);
  36276. /* If we created a new conch file (not just updated the contents of a
  36277. ** valid conch file), try to match the permissions of the database
  36278. */
  36279. if( rc==SQLITE_OK && createConch ){
  36280. struct stat buf;
  36281. int err = osFstat(pFile->h, &buf);
  36282. if( err==0 ){
  36283. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  36284. S_IROTH|S_IWOTH);
  36285. /* try to match the database file R/W permissions, ignore failure */
  36286. #ifndef SQLITE_PROXY_DEBUG
  36287. osFchmod(conchFile->h, cmode);
  36288. #else
  36289. do{
  36290. rc = osFchmod(conchFile->h, cmode);
  36291. }while( rc==(-1) && errno==EINTR );
  36292. if( rc!=0 ){
  36293. int code = errno;
  36294. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  36295. cmode, code, strerror(code));
  36296. } else {
  36297. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  36298. }
  36299. }else{
  36300. int code = errno;
  36301. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  36302. err, code, strerror(code));
  36303. #endif
  36304. }
  36305. }
  36306. }
  36307. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  36308. end_takeconch:
  36309. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  36310. if( rc==SQLITE_OK && pFile->openFlags ){
  36311. int fd;
  36312. if( pFile->h>=0 ){
  36313. robust_close(pFile, pFile->h, __LINE__);
  36314. }
  36315. pFile->h = -1;
  36316. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  36317. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  36318. if( fd>=0 ){
  36319. pFile->h = fd;
  36320. }else{
  36321. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  36322. during locking */
  36323. }
  36324. }
  36325. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  36326. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  36327. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  36328. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  36329. /* we couldn't create the proxy lock file with the old lock file path
  36330. ** so try again via auto-naming
  36331. */
  36332. forceNewLockPath = 1;
  36333. tryOldLockPath = 0;
  36334. continue; /* go back to the do {} while start point, try again */
  36335. }
  36336. }
  36337. if( rc==SQLITE_OK ){
  36338. /* Need to make a copy of path if we extracted the value
  36339. ** from the conch file or the path was allocated on the stack
  36340. */
  36341. if( tempLockPath ){
  36342. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  36343. if( !pCtx->lockProxyPath ){
  36344. rc = SQLITE_NOMEM_BKPT;
  36345. }
  36346. }
  36347. }
  36348. if( rc==SQLITE_OK ){
  36349. pCtx->conchHeld = 1;
  36350. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  36351. afpLockingContext *afpCtx;
  36352. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  36353. afpCtx->dbPath = pCtx->lockProxyPath;
  36354. }
  36355. } else {
  36356. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  36357. }
  36358. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  36359. rc==SQLITE_OK?"ok":"failed"));
  36360. return rc;
  36361. } while (1); /* in case we need to retry the :auto: lock file -
  36362. ** we should never get here except via the 'continue' call. */
  36363. }
  36364. }
  36365. /*
  36366. ** If pFile holds a lock on a conch file, then release that lock.
  36367. */
  36368. static int proxyReleaseConch(unixFile *pFile){
  36369. int rc = SQLITE_OK; /* Subroutine return code */
  36370. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  36371. unixFile *conchFile; /* Name of the conch file */
  36372. pCtx = (proxyLockingContext *)pFile->lockingContext;
  36373. conchFile = pCtx->conchFile;
  36374. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  36375. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  36376. osGetpid(0)));
  36377. if( pCtx->conchHeld>0 ){
  36378. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  36379. }
  36380. pCtx->conchHeld = 0;
  36381. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  36382. (rc==SQLITE_OK ? "ok" : "failed")));
  36383. return rc;
  36384. }
  36385. /*
  36386. ** Given the name of a database file, compute the name of its conch file.
  36387. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  36388. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  36389. ** or SQLITE_NOMEM if unable to obtain memory.
  36390. **
  36391. ** The caller is responsible for ensuring that the allocated memory
  36392. ** space is eventually freed.
  36393. **
  36394. ** *pConchPath is set to NULL if a memory allocation error occurs.
  36395. */
  36396. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  36397. int i; /* Loop counter */
  36398. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  36399. char *conchPath; /* buffer in which to construct conch name */
  36400. /* Allocate space for the conch filename and initialize the name to
  36401. ** the name of the original database file. */
  36402. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  36403. if( conchPath==0 ){
  36404. return SQLITE_NOMEM_BKPT;
  36405. }
  36406. memcpy(conchPath, dbPath, len+1);
  36407. /* now insert a "." before the last / character */
  36408. for( i=(len-1); i>=0; i-- ){
  36409. if( conchPath[i]=='/' ){
  36410. i++;
  36411. break;
  36412. }
  36413. }
  36414. conchPath[i]='.';
  36415. while ( i<len ){
  36416. conchPath[i+1]=dbPath[i];
  36417. i++;
  36418. }
  36419. /* append the "-conch" suffix to the file */
  36420. memcpy(&conchPath[i+1], "-conch", 7);
  36421. assert( (int)strlen(conchPath) == len+7 );
  36422. return SQLITE_OK;
  36423. }
  36424. /* Takes a fully configured proxy locking-style unix file and switches
  36425. ** the local lock file path
  36426. */
  36427. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  36428. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  36429. char *oldPath = pCtx->lockProxyPath;
  36430. int rc = SQLITE_OK;
  36431. if( pFile->eFileLock!=NO_LOCK ){
  36432. return SQLITE_BUSY;
  36433. }
  36434. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  36435. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  36436. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  36437. return SQLITE_OK;
  36438. }else{
  36439. unixFile *lockProxy = pCtx->lockProxy;
  36440. pCtx->lockProxy=NULL;
  36441. pCtx->conchHeld = 0;
  36442. if( lockProxy!=NULL ){
  36443. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  36444. if( rc ) return rc;
  36445. sqlite3_free(lockProxy);
  36446. }
  36447. sqlite3_free(oldPath);
  36448. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  36449. }
  36450. return rc;
  36451. }
  36452. /*
  36453. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  36454. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  36455. **
  36456. ** This routine find the filename associated with pFile and writes it
  36457. ** int dbPath.
  36458. */
  36459. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  36460. #if defined(__APPLE__)
  36461. if( pFile->pMethod == &afpIoMethods ){
  36462. /* afp style keeps a reference to the db path in the filePath field
  36463. ** of the struct */
  36464. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  36465. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  36466. MAXPATHLEN);
  36467. } else
  36468. #endif
  36469. if( pFile->pMethod == &dotlockIoMethods ){
  36470. /* dot lock style uses the locking context to store the dot lock
  36471. ** file path */
  36472. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  36473. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  36474. }else{
  36475. /* all other styles use the locking context to store the db file path */
  36476. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  36477. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  36478. }
  36479. return SQLITE_OK;
  36480. }
  36481. /*
  36482. ** Takes an already filled in unix file and alters it so all file locking
  36483. ** will be performed on the local proxy lock file. The following fields
  36484. ** are preserved in the locking context so that they can be restored and
  36485. ** the unix structure properly cleaned up at close time:
  36486. ** ->lockingContext
  36487. ** ->pMethod
  36488. */
  36489. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  36490. proxyLockingContext *pCtx;
  36491. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  36492. char *lockPath=NULL;
  36493. int rc = SQLITE_OK;
  36494. if( pFile->eFileLock!=NO_LOCK ){
  36495. return SQLITE_BUSY;
  36496. }
  36497. proxyGetDbPathForUnixFile(pFile, dbPath);
  36498. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  36499. lockPath=NULL;
  36500. }else{
  36501. lockPath=(char *)path;
  36502. }
  36503. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  36504. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  36505. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  36506. if( pCtx==0 ){
  36507. return SQLITE_NOMEM_BKPT;
  36508. }
  36509. memset(pCtx, 0, sizeof(*pCtx));
  36510. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  36511. if( rc==SQLITE_OK ){
  36512. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  36513. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  36514. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  36515. ** (c) the file system is read-only, then enable no-locking access.
  36516. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  36517. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  36518. */
  36519. struct statfs fsInfo;
  36520. struct stat conchInfo;
  36521. int goLockless = 0;
  36522. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  36523. int err = errno;
  36524. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  36525. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  36526. }
  36527. }
  36528. if( goLockless ){
  36529. pCtx->conchHeld = -1; /* read only FS/ lockless */
  36530. rc = SQLITE_OK;
  36531. }
  36532. }
  36533. }
  36534. if( rc==SQLITE_OK && lockPath ){
  36535. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  36536. }
  36537. if( rc==SQLITE_OK ){
  36538. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  36539. if( pCtx->dbPath==NULL ){
  36540. rc = SQLITE_NOMEM_BKPT;
  36541. }
  36542. }
  36543. if( rc==SQLITE_OK ){
  36544. /* all memory is allocated, proxys are created and assigned,
  36545. ** switch the locking context and pMethod then return.
  36546. */
  36547. pCtx->oldLockingContext = pFile->lockingContext;
  36548. pFile->lockingContext = pCtx;
  36549. pCtx->pOldMethod = pFile->pMethod;
  36550. pFile->pMethod = &proxyIoMethods;
  36551. }else{
  36552. if( pCtx->conchFile ){
  36553. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  36554. sqlite3_free(pCtx->conchFile);
  36555. }
  36556. sqlite3DbFree(0, pCtx->lockProxyPath);
  36557. sqlite3_free(pCtx->conchFilePath);
  36558. sqlite3_free(pCtx);
  36559. }
  36560. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  36561. (rc==SQLITE_OK ? "ok" : "failed")));
  36562. return rc;
  36563. }
  36564. /*
  36565. ** This routine handles sqlite3_file_control() calls that are specific
  36566. ** to proxy locking.
  36567. */
  36568. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  36569. switch( op ){
  36570. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  36571. unixFile *pFile = (unixFile*)id;
  36572. if( pFile->pMethod == &proxyIoMethods ){
  36573. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  36574. proxyTakeConch(pFile);
  36575. if( pCtx->lockProxyPath ){
  36576. *(const char **)pArg = pCtx->lockProxyPath;
  36577. }else{
  36578. *(const char **)pArg = ":auto: (not held)";
  36579. }
  36580. } else {
  36581. *(const char **)pArg = NULL;
  36582. }
  36583. return SQLITE_OK;
  36584. }
  36585. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  36586. unixFile *pFile = (unixFile*)id;
  36587. int rc = SQLITE_OK;
  36588. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  36589. if( pArg==NULL || (const char *)pArg==0 ){
  36590. if( isProxyStyle ){
  36591. /* turn off proxy locking - not supported. If support is added for
  36592. ** switching proxy locking mode off then it will need to fail if
  36593. ** the journal mode is WAL mode.
  36594. */
  36595. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  36596. }else{
  36597. /* turn off proxy locking - already off - NOOP */
  36598. rc = SQLITE_OK;
  36599. }
  36600. }else{
  36601. const char *proxyPath = (const char *)pArg;
  36602. if( isProxyStyle ){
  36603. proxyLockingContext *pCtx =
  36604. (proxyLockingContext*)pFile->lockingContext;
  36605. if( !strcmp(pArg, ":auto:")
  36606. || (pCtx->lockProxyPath &&
  36607. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  36608. ){
  36609. rc = SQLITE_OK;
  36610. }else{
  36611. rc = switchLockProxyPath(pFile, proxyPath);
  36612. }
  36613. }else{
  36614. /* turn on proxy file locking */
  36615. rc = proxyTransformUnixFile(pFile, proxyPath);
  36616. }
  36617. }
  36618. return rc;
  36619. }
  36620. default: {
  36621. assert( 0 ); /* The call assures that only valid opcodes are sent */
  36622. }
  36623. }
  36624. /*NOTREACHED*/
  36625. return SQLITE_ERROR;
  36626. }
  36627. /*
  36628. ** Within this division (the proxying locking implementation) the procedures
  36629. ** above this point are all utilities. The lock-related methods of the
  36630. ** proxy-locking sqlite3_io_method object follow.
  36631. */
  36632. /*
  36633. ** This routine checks if there is a RESERVED lock held on the specified
  36634. ** file by this or any other process. If such a lock is held, set *pResOut
  36635. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  36636. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  36637. */
  36638. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  36639. unixFile *pFile = (unixFile*)id;
  36640. int rc = proxyTakeConch(pFile);
  36641. if( rc==SQLITE_OK ){
  36642. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  36643. if( pCtx->conchHeld>0 ){
  36644. unixFile *proxy = pCtx->lockProxy;
  36645. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  36646. }else{ /* conchHeld < 0 is lockless */
  36647. pResOut=0;
  36648. }
  36649. }
  36650. return rc;
  36651. }
  36652. /*
  36653. ** Lock the file with the lock specified by parameter eFileLock - one
  36654. ** of the following:
  36655. **
  36656. ** (1) SHARED_LOCK
  36657. ** (2) RESERVED_LOCK
  36658. ** (3) PENDING_LOCK
  36659. ** (4) EXCLUSIVE_LOCK
  36660. **
  36661. ** Sometimes when requesting one lock state, additional lock states
  36662. ** are inserted in between. The locking might fail on one of the later
  36663. ** transitions leaving the lock state different from what it started but
  36664. ** still short of its goal. The following chart shows the allowed
  36665. ** transitions and the inserted intermediate states:
  36666. **
  36667. ** UNLOCKED -> SHARED
  36668. ** SHARED -> RESERVED
  36669. ** SHARED -> (PENDING) -> EXCLUSIVE
  36670. ** RESERVED -> (PENDING) -> EXCLUSIVE
  36671. ** PENDING -> EXCLUSIVE
  36672. **
  36673. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  36674. ** routine to lower a locking level.
  36675. */
  36676. static int proxyLock(sqlite3_file *id, int eFileLock) {
  36677. unixFile *pFile = (unixFile*)id;
  36678. int rc = proxyTakeConch(pFile);
  36679. if( rc==SQLITE_OK ){
  36680. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  36681. if( pCtx->conchHeld>0 ){
  36682. unixFile *proxy = pCtx->lockProxy;
  36683. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  36684. pFile->eFileLock = proxy->eFileLock;
  36685. }else{
  36686. /* conchHeld < 0 is lockless */
  36687. }
  36688. }
  36689. return rc;
  36690. }
  36691. /*
  36692. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  36693. ** must be either NO_LOCK or SHARED_LOCK.
  36694. **
  36695. ** If the locking level of the file descriptor is already at or below
  36696. ** the requested locking level, this routine is a no-op.
  36697. */
  36698. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  36699. unixFile *pFile = (unixFile*)id;
  36700. int rc = proxyTakeConch(pFile);
  36701. if( rc==SQLITE_OK ){
  36702. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  36703. if( pCtx->conchHeld>0 ){
  36704. unixFile *proxy = pCtx->lockProxy;
  36705. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  36706. pFile->eFileLock = proxy->eFileLock;
  36707. }else{
  36708. /* conchHeld < 0 is lockless */
  36709. }
  36710. }
  36711. return rc;
  36712. }
  36713. /*
  36714. ** Close a file that uses proxy locks.
  36715. */
  36716. static int proxyClose(sqlite3_file *id) {
  36717. if( ALWAYS(id) ){
  36718. unixFile *pFile = (unixFile*)id;
  36719. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  36720. unixFile *lockProxy = pCtx->lockProxy;
  36721. unixFile *conchFile = pCtx->conchFile;
  36722. int rc = SQLITE_OK;
  36723. if( lockProxy ){
  36724. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  36725. if( rc ) return rc;
  36726. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  36727. if( rc ) return rc;
  36728. sqlite3_free(lockProxy);
  36729. pCtx->lockProxy = 0;
  36730. }
  36731. if( conchFile ){
  36732. if( pCtx->conchHeld ){
  36733. rc = proxyReleaseConch(pFile);
  36734. if( rc ) return rc;
  36735. }
  36736. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  36737. if( rc ) return rc;
  36738. sqlite3_free(conchFile);
  36739. }
  36740. sqlite3DbFree(0, pCtx->lockProxyPath);
  36741. sqlite3_free(pCtx->conchFilePath);
  36742. sqlite3DbFree(0, pCtx->dbPath);
  36743. /* restore the original locking context and pMethod then close it */
  36744. pFile->lockingContext = pCtx->oldLockingContext;
  36745. pFile->pMethod = pCtx->pOldMethod;
  36746. sqlite3_free(pCtx);
  36747. return pFile->pMethod->xClose(id);
  36748. }
  36749. return SQLITE_OK;
  36750. }
  36751. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  36752. /*
  36753. ** The proxy locking style is intended for use with AFP filesystems.
  36754. ** And since AFP is only supported on MacOSX, the proxy locking is also
  36755. ** restricted to MacOSX.
  36756. **
  36757. **
  36758. ******************* End of the proxy lock implementation **********************
  36759. ******************************************************************************/
  36760. /*
  36761. ** Initialize the operating system interface.
  36762. **
  36763. ** This routine registers all VFS implementations for unix-like operating
  36764. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  36765. ** should be the only routines in this file that are visible from other
  36766. ** files.
  36767. **
  36768. ** This routine is called once during SQLite initialization and by a
  36769. ** single thread. The memory allocation and mutex subsystems have not
  36770. ** necessarily been initialized when this routine is called, and so they
  36771. ** should not be used.
  36772. */
  36773. SQLITE_API int sqlite3_os_init(void){
  36774. /*
  36775. ** The following macro defines an initializer for an sqlite3_vfs object.
  36776. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  36777. ** to the "finder" function. (pAppData is a pointer to a pointer because
  36778. ** silly C90 rules prohibit a void* from being cast to a function pointer
  36779. ** and so we have to go through the intermediate pointer to avoid problems
  36780. ** when compiling with -pedantic-errors on GCC.)
  36781. **
  36782. ** The FINDER parameter to this macro is the name of the pointer to the
  36783. ** finder-function. The finder-function returns a pointer to the
  36784. ** sqlite_io_methods object that implements the desired locking
  36785. ** behaviors. See the division above that contains the IOMETHODS
  36786. ** macro for addition information on finder-functions.
  36787. **
  36788. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  36789. ** object. But the "autolockIoFinder" available on MacOSX does a little
  36790. ** more than that; it looks at the filesystem type that hosts the
  36791. ** database file and tries to choose an locking method appropriate for
  36792. ** that filesystem time.
  36793. */
  36794. #define UNIXVFS(VFSNAME, FINDER) { \
  36795. 3, /* iVersion */ \
  36796. sizeof(unixFile), /* szOsFile */ \
  36797. MAX_PATHNAME, /* mxPathname */ \
  36798. 0, /* pNext */ \
  36799. VFSNAME, /* zName */ \
  36800. (void*)&FINDER, /* pAppData */ \
  36801. unixOpen, /* xOpen */ \
  36802. unixDelete, /* xDelete */ \
  36803. unixAccess, /* xAccess */ \
  36804. unixFullPathname, /* xFullPathname */ \
  36805. unixDlOpen, /* xDlOpen */ \
  36806. unixDlError, /* xDlError */ \
  36807. unixDlSym, /* xDlSym */ \
  36808. unixDlClose, /* xDlClose */ \
  36809. unixRandomness, /* xRandomness */ \
  36810. unixSleep, /* xSleep */ \
  36811. unixCurrentTime, /* xCurrentTime */ \
  36812. unixGetLastError, /* xGetLastError */ \
  36813. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  36814. unixSetSystemCall, /* xSetSystemCall */ \
  36815. unixGetSystemCall, /* xGetSystemCall */ \
  36816. unixNextSystemCall, /* xNextSystemCall */ \
  36817. }
  36818. /*
  36819. ** All default VFSes for unix are contained in the following array.
  36820. **
  36821. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  36822. ** by the SQLite core when the VFS is registered. So the following
  36823. ** array cannot be const.
  36824. */
  36825. static sqlite3_vfs aVfs[] = {
  36826. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  36827. UNIXVFS("unix", autolockIoFinder ),
  36828. #elif OS_VXWORKS
  36829. UNIXVFS("unix", vxworksIoFinder ),
  36830. #else
  36831. UNIXVFS("unix", posixIoFinder ),
  36832. #endif
  36833. UNIXVFS("unix-none", nolockIoFinder ),
  36834. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  36835. UNIXVFS("unix-excl", posixIoFinder ),
  36836. #if OS_VXWORKS
  36837. UNIXVFS("unix-namedsem", semIoFinder ),
  36838. #endif
  36839. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  36840. UNIXVFS("unix-posix", posixIoFinder ),
  36841. #endif
  36842. #if SQLITE_ENABLE_LOCKING_STYLE
  36843. UNIXVFS("unix-flock", flockIoFinder ),
  36844. #endif
  36845. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  36846. UNIXVFS("unix-afp", afpIoFinder ),
  36847. UNIXVFS("unix-nfs", nfsIoFinder ),
  36848. UNIXVFS("unix-proxy", proxyIoFinder ),
  36849. #endif
  36850. };
  36851. unsigned int i; /* Loop counter */
  36852. /* Double-check that the aSyscall[] array has been constructed
  36853. ** correctly. See ticket [bb3a86e890c8e96ab] */
  36854. assert( ArraySize(aSyscall)==29 );
  36855. /* Register all VFSes defined in the aVfs[] array */
  36856. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  36857. sqlite3_vfs_register(&aVfs[i], i==0);
  36858. }
  36859. unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  36860. return SQLITE_OK;
  36861. }
  36862. /*
  36863. ** Shutdown the operating system interface.
  36864. **
  36865. ** Some operating systems might need to do some cleanup in this routine,
  36866. ** to release dynamically allocated objects. But not on unix.
  36867. ** This routine is a no-op for unix.
  36868. */
  36869. SQLITE_API int sqlite3_os_end(void){
  36870. unixBigLock = 0;
  36871. return SQLITE_OK;
  36872. }
  36873. #endif /* SQLITE_OS_UNIX */
  36874. /************** End of os_unix.c *********************************************/
  36875. /************** Begin file os_win.c ******************************************/
  36876. /*
  36877. ** 2004 May 22
  36878. **
  36879. ** The author disclaims copyright to this source code. In place of
  36880. ** a legal notice, here is a blessing:
  36881. **
  36882. ** May you do good and not evil.
  36883. ** May you find forgiveness for yourself and forgive others.
  36884. ** May you share freely, never taking more than you give.
  36885. **
  36886. ******************************************************************************
  36887. **
  36888. ** This file contains code that is specific to Windows.
  36889. */
  36890. /* #include "sqliteInt.h" */
  36891. #if SQLITE_OS_WIN /* This file is used for Windows only */
  36892. /*
  36893. ** Include code that is common to all os_*.c files
  36894. */
  36895. /************** Include os_common.h in the middle of os_win.c ****************/
  36896. /************** Begin file os_common.h ***************************************/
  36897. /*
  36898. ** 2004 May 22
  36899. **
  36900. ** The author disclaims copyright to this source code. In place of
  36901. ** a legal notice, here is a blessing:
  36902. **
  36903. ** May you do good and not evil.
  36904. ** May you find forgiveness for yourself and forgive others.
  36905. ** May you share freely, never taking more than you give.
  36906. **
  36907. ******************************************************************************
  36908. **
  36909. ** This file contains macros and a little bit of code that is common to
  36910. ** all of the platform-specific files (os_*.c) and is #included into those
  36911. ** files.
  36912. **
  36913. ** This file should be #included by the os_*.c files only. It is not a
  36914. ** general purpose header file.
  36915. */
  36916. #ifndef _OS_COMMON_H_
  36917. #define _OS_COMMON_H_
  36918. /*
  36919. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  36920. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  36921. ** switch. The following code should catch this problem at compile-time.
  36922. */
  36923. #ifdef MEMORY_DEBUG
  36924. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  36925. #endif
  36926. /*
  36927. ** Macros for performance tracing. Normally turned off. Only works
  36928. ** on i486 hardware.
  36929. */
  36930. #ifdef SQLITE_PERFORMANCE_TRACE
  36931. /*
  36932. ** hwtime.h contains inline assembler code for implementing
  36933. ** high-performance timing routines.
  36934. */
  36935. /************** Include hwtime.h in the middle of os_common.h ****************/
  36936. /************** Begin file hwtime.h ******************************************/
  36937. /*
  36938. ** 2008 May 27
  36939. **
  36940. ** The author disclaims copyright to this source code. In place of
  36941. ** a legal notice, here is a blessing:
  36942. **
  36943. ** May you do good and not evil.
  36944. ** May you find forgiveness for yourself and forgive others.
  36945. ** May you share freely, never taking more than you give.
  36946. **
  36947. ******************************************************************************
  36948. **
  36949. ** This file contains inline asm code for retrieving "high-performance"
  36950. ** counters for x86 class CPUs.
  36951. */
  36952. #ifndef SQLITE_HWTIME_H
  36953. #define SQLITE_HWTIME_H
  36954. /*
  36955. ** The following routine only works on pentium-class (or newer) processors.
  36956. ** It uses the RDTSC opcode to read the cycle count value out of the
  36957. ** processor and returns that value. This can be used for high-res
  36958. ** profiling.
  36959. */
  36960. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  36961. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  36962. #if defined(__GNUC__)
  36963. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  36964. unsigned int lo, hi;
  36965. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  36966. return (sqlite_uint64)hi << 32 | lo;
  36967. }
  36968. #elif defined(_MSC_VER)
  36969. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  36970. __asm {
  36971. rdtsc
  36972. ret ; return value at EDX:EAX
  36973. }
  36974. }
  36975. #endif
  36976. #elif (defined(__GNUC__) && defined(__x86_64__))
  36977. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  36978. unsigned long val;
  36979. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  36980. return val;
  36981. }
  36982. #elif (defined(__GNUC__) && defined(__ppc__))
  36983. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  36984. unsigned long long retval;
  36985. unsigned long junk;
  36986. __asm__ __volatile__ ("\n\
  36987. 1: mftbu %1\n\
  36988. mftb %L0\n\
  36989. mftbu %0\n\
  36990. cmpw %0,%1\n\
  36991. bne 1b"
  36992. : "=r" (retval), "=r" (junk));
  36993. return retval;
  36994. }
  36995. #else
  36996. #error Need implementation of sqlite3Hwtime() for your platform.
  36997. /*
  36998. ** To compile without implementing sqlite3Hwtime() for your platform,
  36999. ** you can remove the above #error and use the following
  37000. ** stub function. You will lose timing support for many
  37001. ** of the debugging and testing utilities, but it should at
  37002. ** least compile and run.
  37003. */
  37004. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  37005. #endif
  37006. #endif /* !defined(SQLITE_HWTIME_H) */
  37007. /************** End of hwtime.h **********************************************/
  37008. /************** Continuing where we left off in os_common.h ******************/
  37009. static sqlite_uint64 g_start;
  37010. static sqlite_uint64 g_elapsed;
  37011. #define TIMER_START g_start=sqlite3Hwtime()
  37012. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  37013. #define TIMER_ELAPSED g_elapsed
  37014. #else
  37015. #define TIMER_START
  37016. #define TIMER_END
  37017. #define TIMER_ELAPSED ((sqlite_uint64)0)
  37018. #endif
  37019. /*
  37020. ** If we compile with the SQLITE_TEST macro set, then the following block
  37021. ** of code will give us the ability to simulate a disk I/O error. This
  37022. ** is used for testing the I/O recovery logic.
  37023. */
  37024. #if defined(SQLITE_TEST)
  37025. SQLITE_API extern int sqlite3_io_error_hit;
  37026. SQLITE_API extern int sqlite3_io_error_hardhit;
  37027. SQLITE_API extern int sqlite3_io_error_pending;
  37028. SQLITE_API extern int sqlite3_io_error_persist;
  37029. SQLITE_API extern int sqlite3_io_error_benign;
  37030. SQLITE_API extern int sqlite3_diskfull_pending;
  37031. SQLITE_API extern int sqlite3_diskfull;
  37032. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  37033. #define SimulateIOError(CODE) \
  37034. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  37035. || sqlite3_io_error_pending-- == 1 ) \
  37036. { local_ioerr(); CODE; }
  37037. static void local_ioerr(){
  37038. IOTRACE(("IOERR\n"));
  37039. sqlite3_io_error_hit++;
  37040. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  37041. }
  37042. #define SimulateDiskfullError(CODE) \
  37043. if( sqlite3_diskfull_pending ){ \
  37044. if( sqlite3_diskfull_pending == 1 ){ \
  37045. local_ioerr(); \
  37046. sqlite3_diskfull = 1; \
  37047. sqlite3_io_error_hit = 1; \
  37048. CODE; \
  37049. }else{ \
  37050. sqlite3_diskfull_pending--; \
  37051. } \
  37052. }
  37053. #else
  37054. #define SimulateIOErrorBenign(X)
  37055. #define SimulateIOError(A)
  37056. #define SimulateDiskfullError(A)
  37057. #endif /* defined(SQLITE_TEST) */
  37058. /*
  37059. ** When testing, keep a count of the number of open files.
  37060. */
  37061. #if defined(SQLITE_TEST)
  37062. SQLITE_API extern int sqlite3_open_file_count;
  37063. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  37064. #else
  37065. #define OpenCounter(X)
  37066. #endif /* defined(SQLITE_TEST) */
  37067. #endif /* !defined(_OS_COMMON_H_) */
  37068. /************** End of os_common.h *******************************************/
  37069. /************** Continuing where we left off in os_win.c *********************/
  37070. /*
  37071. ** Include the header file for the Windows VFS.
  37072. */
  37073. /* #include "os_win.h" */
  37074. /*
  37075. ** Compiling and using WAL mode requires several APIs that are only
  37076. ** available in Windows platforms based on the NT kernel.
  37077. */
  37078. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  37079. # error "WAL mode requires support from the Windows NT kernel, compile\
  37080. with SQLITE_OMIT_WAL."
  37081. #endif
  37082. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  37083. # error "Memory mapped files require support from the Windows NT kernel,\
  37084. compile with SQLITE_MAX_MMAP_SIZE=0."
  37085. #endif
  37086. /*
  37087. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  37088. ** based on the sub-platform)?
  37089. */
  37090. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  37091. # define SQLITE_WIN32_HAS_ANSI
  37092. #endif
  37093. /*
  37094. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  37095. ** based on the sub-platform)?
  37096. */
  37097. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  37098. !defined(SQLITE_WIN32_NO_WIDE)
  37099. # define SQLITE_WIN32_HAS_WIDE
  37100. #endif
  37101. /*
  37102. ** Make sure at least one set of Win32 APIs is available.
  37103. */
  37104. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  37105. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  37106. must be defined."
  37107. #endif
  37108. /*
  37109. ** Define the required Windows SDK version constants if they are not
  37110. ** already available.
  37111. */
  37112. #ifndef NTDDI_WIN8
  37113. # define NTDDI_WIN8 0x06020000
  37114. #endif
  37115. #ifndef NTDDI_WINBLUE
  37116. # define NTDDI_WINBLUE 0x06030000
  37117. #endif
  37118. #ifndef NTDDI_WINTHRESHOLD
  37119. # define NTDDI_WINTHRESHOLD 0x06040000
  37120. #endif
  37121. /*
  37122. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  37123. ** target system. GetVersionEx was first deprecated in Win8.1.
  37124. */
  37125. #ifndef SQLITE_WIN32_GETVERSIONEX
  37126. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  37127. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  37128. # else
  37129. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  37130. # endif
  37131. #endif
  37132. /*
  37133. ** Check to see if the CreateFileMappingA function is supported on the
  37134. ** target system. It is unavailable when using "mincore.lib" on Win10.
  37135. ** When compiling for Windows 10, always assume "mincore.lib" is in use.
  37136. */
  37137. #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
  37138. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
  37139. # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
  37140. # else
  37141. # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
  37142. # endif
  37143. #endif
  37144. /*
  37145. ** This constant should already be defined (in the "WinDef.h" SDK file).
  37146. */
  37147. #ifndef MAX_PATH
  37148. # define MAX_PATH (260)
  37149. #endif
  37150. /*
  37151. ** Maximum pathname length (in chars) for Win32. This should normally be
  37152. ** MAX_PATH.
  37153. */
  37154. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  37155. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  37156. #endif
  37157. /*
  37158. ** This constant should already be defined (in the "WinNT.h" SDK file).
  37159. */
  37160. #ifndef UNICODE_STRING_MAX_CHARS
  37161. # define UNICODE_STRING_MAX_CHARS (32767)
  37162. #endif
  37163. /*
  37164. ** Maximum pathname length (in chars) for WinNT. This should normally be
  37165. ** UNICODE_STRING_MAX_CHARS.
  37166. */
  37167. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  37168. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  37169. #endif
  37170. /*
  37171. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  37172. ** characters, so we allocate 4 bytes per character assuming worst-case of
  37173. ** 4-bytes-per-character for UTF8.
  37174. */
  37175. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  37176. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  37177. #endif
  37178. /*
  37179. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  37180. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  37181. */
  37182. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  37183. # define SQLITE_WINNT_MAX_PATH_BYTES \
  37184. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  37185. #endif
  37186. /*
  37187. ** Maximum error message length (in chars) for WinRT.
  37188. */
  37189. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  37190. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  37191. #endif
  37192. /*
  37193. ** Returns non-zero if the character should be treated as a directory
  37194. ** separator.
  37195. */
  37196. #ifndef winIsDirSep
  37197. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  37198. #endif
  37199. /*
  37200. ** This macro is used when a local variable is set to a value that is
  37201. ** [sometimes] not used by the code (e.g. via conditional compilation).
  37202. */
  37203. #ifndef UNUSED_VARIABLE_VALUE
  37204. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  37205. #endif
  37206. /*
  37207. ** Returns the character that should be used as the directory separator.
  37208. */
  37209. #ifndef winGetDirSep
  37210. # define winGetDirSep() '\\'
  37211. #endif
  37212. /*
  37213. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  37214. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  37215. ** CE SDK; however, they are not present in the header file)?
  37216. */
  37217. #if SQLITE_WIN32_FILEMAPPING_API && \
  37218. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  37219. /*
  37220. ** Two of the file mapping APIs are different under WinRT. Figure out which
  37221. ** set we need.
  37222. */
  37223. #if SQLITE_OS_WINRT
  37224. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  37225. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  37226. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  37227. #else
  37228. #if defined(SQLITE_WIN32_HAS_ANSI)
  37229. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  37230. DWORD, DWORD, DWORD, LPCSTR);
  37231. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  37232. #if defined(SQLITE_WIN32_HAS_WIDE)
  37233. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  37234. DWORD, DWORD, DWORD, LPCWSTR);
  37235. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  37236. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  37237. #endif /* SQLITE_OS_WINRT */
  37238. /*
  37239. ** These file mapping APIs are common to both Win32 and WinRT.
  37240. */
  37241. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  37242. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  37243. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  37244. /*
  37245. ** Some Microsoft compilers lack this definition.
  37246. */
  37247. #ifndef INVALID_FILE_ATTRIBUTES
  37248. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  37249. #endif
  37250. #ifndef FILE_FLAG_MASK
  37251. # define FILE_FLAG_MASK (0xFF3C0000)
  37252. #endif
  37253. #ifndef FILE_ATTRIBUTE_MASK
  37254. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  37255. #endif
  37256. #ifndef SQLITE_OMIT_WAL
  37257. /* Forward references to structures used for WAL */
  37258. typedef struct winShm winShm; /* A connection to shared-memory */
  37259. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  37260. #endif
  37261. /*
  37262. ** WinCE lacks native support for file locking so we have to fake it
  37263. ** with some code of our own.
  37264. */
  37265. #if SQLITE_OS_WINCE
  37266. typedef struct winceLock {
  37267. int nReaders; /* Number of reader locks obtained */
  37268. BOOL bPending; /* Indicates a pending lock has been obtained */
  37269. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  37270. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  37271. } winceLock;
  37272. #endif
  37273. /*
  37274. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  37275. ** portability layer.
  37276. */
  37277. typedef struct winFile winFile;
  37278. struct winFile {
  37279. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  37280. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  37281. HANDLE h; /* Handle for accessing the file */
  37282. u8 locktype; /* Type of lock currently held on this file */
  37283. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  37284. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  37285. DWORD lastErrno; /* The Windows errno from the last I/O error */
  37286. #ifndef SQLITE_OMIT_WAL
  37287. winShm *pShm; /* Instance of shared memory on this file */
  37288. #endif
  37289. const char *zPath; /* Full pathname of this file */
  37290. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  37291. #if SQLITE_OS_WINCE
  37292. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  37293. HANDLE hMutex; /* Mutex used to control access to shared lock */
  37294. HANDLE hShared; /* Shared memory segment used for locking */
  37295. winceLock local; /* Locks obtained by this instance of winFile */
  37296. winceLock *shared; /* Global shared lock memory for the file */
  37297. #endif
  37298. #if SQLITE_MAX_MMAP_SIZE>0
  37299. int nFetchOut; /* Number of outstanding xFetch references */
  37300. HANDLE hMap; /* Handle for accessing memory mapping */
  37301. void *pMapRegion; /* Area memory mapped */
  37302. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  37303. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  37304. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  37305. #endif
  37306. };
  37307. /*
  37308. ** The winVfsAppData structure is used for the pAppData member for all of the
  37309. ** Win32 VFS variants.
  37310. */
  37311. typedef struct winVfsAppData winVfsAppData;
  37312. struct winVfsAppData {
  37313. const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
  37314. void *pAppData; /* The extra pAppData, if any. */
  37315. BOOL bNoLock; /* Non-zero if locking is disabled. */
  37316. };
  37317. /*
  37318. ** Allowed values for winFile.ctrlFlags
  37319. */
  37320. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  37321. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  37322. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  37323. /*
  37324. * The size of the buffer used by sqlite3_win32_write_debug().
  37325. */
  37326. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  37327. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  37328. #endif
  37329. /*
  37330. * The value used with sqlite3_win32_set_directory() to specify that
  37331. * the data directory should be changed.
  37332. */
  37333. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  37334. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  37335. #endif
  37336. /*
  37337. * The value used with sqlite3_win32_set_directory() to specify that
  37338. * the temporary directory should be changed.
  37339. */
  37340. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  37341. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  37342. #endif
  37343. /*
  37344. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  37345. * various Win32 API heap functions instead of our own.
  37346. */
  37347. #ifdef SQLITE_WIN32_MALLOC
  37348. /*
  37349. * If this is non-zero, an isolated heap will be created by the native Win32
  37350. * allocator subsystem; otherwise, the default process heap will be used. This
  37351. * setting has no effect when compiling for WinRT. By default, this is enabled
  37352. * and an isolated heap will be created to store all allocated data.
  37353. *
  37354. ******************************************************************************
  37355. * WARNING: It is important to note that when this setting is non-zero and the
  37356. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  37357. * function), all data that was allocated using the isolated heap will
  37358. * be freed immediately and any attempt to access any of that freed
  37359. * data will almost certainly result in an immediate access violation.
  37360. ******************************************************************************
  37361. */
  37362. #ifndef SQLITE_WIN32_HEAP_CREATE
  37363. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  37364. #endif
  37365. /*
  37366. * This is the maximum possible initial size of the Win32-specific heap, in
  37367. * bytes.
  37368. */
  37369. #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
  37370. # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
  37371. #endif
  37372. /*
  37373. * This is the extra space for the initial size of the Win32-specific heap,
  37374. * in bytes. This value may be zero.
  37375. */
  37376. #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
  37377. # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
  37378. #endif
  37379. /*
  37380. * Calculate the maximum legal cache size, in pages, based on the maximum
  37381. * possible initial heap size and the default page size, setting aside the
  37382. * needed extra space.
  37383. */
  37384. #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
  37385. # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
  37386. (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
  37387. (SQLITE_DEFAULT_PAGE_SIZE))
  37388. #endif
  37389. /*
  37390. * This is cache size used in the calculation of the initial size of the
  37391. * Win32-specific heap. It cannot be negative.
  37392. */
  37393. #ifndef SQLITE_WIN32_CACHE_SIZE
  37394. # if SQLITE_DEFAULT_CACHE_SIZE>=0
  37395. # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
  37396. # else
  37397. # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
  37398. # endif
  37399. #endif
  37400. /*
  37401. * Make sure that the calculated cache size, in pages, cannot cause the
  37402. * initial size of the Win32-specific heap to exceed the maximum amount
  37403. * of memory that can be specified in the call to HeapCreate.
  37404. */
  37405. #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
  37406. # undef SQLITE_WIN32_CACHE_SIZE
  37407. # define SQLITE_WIN32_CACHE_SIZE (2000)
  37408. #endif
  37409. /*
  37410. * The initial size of the Win32-specific heap. This value may be zero.
  37411. */
  37412. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  37413. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
  37414. (SQLITE_DEFAULT_PAGE_SIZE) + \
  37415. (SQLITE_WIN32_HEAP_INIT_EXTRA))
  37416. #endif
  37417. /*
  37418. * The maximum size of the Win32-specific heap. This value may be zero.
  37419. */
  37420. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  37421. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  37422. #endif
  37423. /*
  37424. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  37425. * zero for the default behavior.
  37426. */
  37427. #ifndef SQLITE_WIN32_HEAP_FLAGS
  37428. # define SQLITE_WIN32_HEAP_FLAGS (0)
  37429. #endif
  37430. /*
  37431. ** The winMemData structure stores information required by the Win32-specific
  37432. ** sqlite3_mem_methods implementation.
  37433. */
  37434. typedef struct winMemData winMemData;
  37435. struct winMemData {
  37436. #ifndef NDEBUG
  37437. u32 magic1; /* Magic number to detect structure corruption. */
  37438. #endif
  37439. HANDLE hHeap; /* The handle to our heap. */
  37440. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  37441. #ifndef NDEBUG
  37442. u32 magic2; /* Magic number to detect structure corruption. */
  37443. #endif
  37444. };
  37445. #ifndef NDEBUG
  37446. #define WINMEM_MAGIC1 0x42b2830b
  37447. #define WINMEM_MAGIC2 0xbd4d7cf4
  37448. #endif
  37449. static struct winMemData win_mem_data = {
  37450. #ifndef NDEBUG
  37451. WINMEM_MAGIC1,
  37452. #endif
  37453. NULL, FALSE
  37454. #ifndef NDEBUG
  37455. ,WINMEM_MAGIC2
  37456. #endif
  37457. };
  37458. #ifndef NDEBUG
  37459. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  37460. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  37461. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  37462. #else
  37463. #define winMemAssertMagic()
  37464. #endif
  37465. #define winMemGetDataPtr() &win_mem_data
  37466. #define winMemGetHeap() win_mem_data.hHeap
  37467. #define winMemGetOwned() win_mem_data.bOwned
  37468. static void *winMemMalloc(int nBytes);
  37469. static void winMemFree(void *pPrior);
  37470. static void *winMemRealloc(void *pPrior, int nBytes);
  37471. static int winMemSize(void *p);
  37472. static int winMemRoundup(int n);
  37473. static int winMemInit(void *pAppData);
  37474. static void winMemShutdown(void *pAppData);
  37475. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  37476. #endif /* SQLITE_WIN32_MALLOC */
  37477. /*
  37478. ** The following variable is (normally) set once and never changes
  37479. ** thereafter. It records whether the operating system is Win9x
  37480. ** or WinNT.
  37481. **
  37482. ** 0: Operating system unknown.
  37483. ** 1: Operating system is Win9x.
  37484. ** 2: Operating system is WinNT.
  37485. **
  37486. ** In order to facilitate testing on a WinNT system, the test fixture
  37487. ** can manually set this value to 1 to emulate Win98 behavior.
  37488. */
  37489. #ifdef SQLITE_TEST
  37490. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  37491. #else
  37492. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  37493. #endif
  37494. #ifndef SYSCALL
  37495. # define SYSCALL sqlite3_syscall_ptr
  37496. #endif
  37497. /*
  37498. ** This function is not available on Windows CE or WinRT.
  37499. */
  37500. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  37501. # define osAreFileApisANSI() 1
  37502. #endif
  37503. /*
  37504. ** Many system calls are accessed through pointer-to-functions so that
  37505. ** they may be overridden at runtime to facilitate fault injection during
  37506. ** testing and sandboxing. The following array holds the names and pointers
  37507. ** to all overrideable system calls.
  37508. */
  37509. static struct win_syscall {
  37510. const char *zName; /* Name of the system call */
  37511. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  37512. sqlite3_syscall_ptr pDefault; /* Default value */
  37513. } aSyscall[] = {
  37514. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  37515. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  37516. #else
  37517. { "AreFileApisANSI", (SYSCALL)0, 0 },
  37518. #endif
  37519. #ifndef osAreFileApisANSI
  37520. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  37521. #endif
  37522. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  37523. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  37524. #else
  37525. { "CharLowerW", (SYSCALL)0, 0 },
  37526. #endif
  37527. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  37528. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  37529. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  37530. #else
  37531. { "CharUpperW", (SYSCALL)0, 0 },
  37532. #endif
  37533. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  37534. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  37535. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  37536. #if defined(SQLITE_WIN32_HAS_ANSI)
  37537. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  37538. #else
  37539. { "CreateFileA", (SYSCALL)0, 0 },
  37540. #endif
  37541. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  37542. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  37543. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  37544. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  37545. #else
  37546. { "CreateFileW", (SYSCALL)0, 0 },
  37547. #endif
  37548. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  37549. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  37550. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  37551. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
  37552. SQLITE_WIN32_CREATEFILEMAPPINGA
  37553. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  37554. #else
  37555. { "CreateFileMappingA", (SYSCALL)0, 0 },
  37556. #endif
  37557. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  37558. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  37559. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  37560. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  37561. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  37562. #else
  37563. { "CreateFileMappingW", (SYSCALL)0, 0 },
  37564. #endif
  37565. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  37566. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  37567. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  37568. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  37569. #else
  37570. { "CreateMutexW", (SYSCALL)0, 0 },
  37571. #endif
  37572. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  37573. LPCWSTR))aSyscall[8].pCurrent)
  37574. #if defined(SQLITE_WIN32_HAS_ANSI)
  37575. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  37576. #else
  37577. { "DeleteFileA", (SYSCALL)0, 0 },
  37578. #endif
  37579. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  37580. #if defined(SQLITE_WIN32_HAS_WIDE)
  37581. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  37582. #else
  37583. { "DeleteFileW", (SYSCALL)0, 0 },
  37584. #endif
  37585. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  37586. #if SQLITE_OS_WINCE
  37587. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  37588. #else
  37589. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  37590. #endif
  37591. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  37592. LPFILETIME))aSyscall[11].pCurrent)
  37593. #if SQLITE_OS_WINCE
  37594. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  37595. #else
  37596. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  37597. #endif
  37598. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  37599. LPSYSTEMTIME))aSyscall[12].pCurrent)
  37600. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  37601. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  37602. #if defined(SQLITE_WIN32_HAS_ANSI)
  37603. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  37604. #else
  37605. { "FormatMessageA", (SYSCALL)0, 0 },
  37606. #endif
  37607. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  37608. DWORD,va_list*))aSyscall[14].pCurrent)
  37609. #if defined(SQLITE_WIN32_HAS_WIDE)
  37610. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  37611. #else
  37612. { "FormatMessageW", (SYSCALL)0, 0 },
  37613. #endif
  37614. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  37615. DWORD,va_list*))aSyscall[15].pCurrent)
  37616. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  37617. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  37618. #else
  37619. { "FreeLibrary", (SYSCALL)0, 0 },
  37620. #endif
  37621. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  37622. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  37623. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  37624. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  37625. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  37626. #else
  37627. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  37628. #endif
  37629. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  37630. LPDWORD))aSyscall[18].pCurrent)
  37631. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  37632. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  37633. #else
  37634. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  37635. #endif
  37636. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  37637. LPDWORD))aSyscall[19].pCurrent)
  37638. #if defined(SQLITE_WIN32_HAS_ANSI)
  37639. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  37640. #else
  37641. { "GetFileAttributesA", (SYSCALL)0, 0 },
  37642. #endif
  37643. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  37644. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  37645. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  37646. #else
  37647. { "GetFileAttributesW", (SYSCALL)0, 0 },
  37648. #endif
  37649. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  37650. #if defined(SQLITE_WIN32_HAS_WIDE)
  37651. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  37652. #else
  37653. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  37654. #endif
  37655. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  37656. LPVOID))aSyscall[22].pCurrent)
  37657. #if !SQLITE_OS_WINRT
  37658. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  37659. #else
  37660. { "GetFileSize", (SYSCALL)0, 0 },
  37661. #endif
  37662. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  37663. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  37664. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  37665. #else
  37666. { "GetFullPathNameA", (SYSCALL)0, 0 },
  37667. #endif
  37668. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  37669. LPSTR*))aSyscall[24].pCurrent)
  37670. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  37671. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  37672. #else
  37673. { "GetFullPathNameW", (SYSCALL)0, 0 },
  37674. #endif
  37675. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  37676. LPWSTR*))aSyscall[25].pCurrent)
  37677. { "GetLastError", (SYSCALL)GetLastError, 0 },
  37678. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  37679. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  37680. #if SQLITE_OS_WINCE
  37681. /* The GetProcAddressA() routine is only available on Windows CE. */
  37682. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  37683. #else
  37684. /* All other Windows platforms expect GetProcAddress() to take
  37685. ** an ANSI string regardless of the _UNICODE setting */
  37686. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  37687. #endif
  37688. #else
  37689. { "GetProcAddressA", (SYSCALL)0, 0 },
  37690. #endif
  37691. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  37692. LPCSTR))aSyscall[27].pCurrent)
  37693. #if !SQLITE_OS_WINRT
  37694. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  37695. #else
  37696. { "GetSystemInfo", (SYSCALL)0, 0 },
  37697. #endif
  37698. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  37699. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  37700. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  37701. #if !SQLITE_OS_WINCE
  37702. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  37703. #else
  37704. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  37705. #endif
  37706. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  37707. LPFILETIME))aSyscall[30].pCurrent)
  37708. #if defined(SQLITE_WIN32_HAS_ANSI)
  37709. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  37710. #else
  37711. { "GetTempPathA", (SYSCALL)0, 0 },
  37712. #endif
  37713. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  37714. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  37715. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  37716. #else
  37717. { "GetTempPathW", (SYSCALL)0, 0 },
  37718. #endif
  37719. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  37720. #if !SQLITE_OS_WINRT
  37721. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  37722. #else
  37723. { "GetTickCount", (SYSCALL)0, 0 },
  37724. #endif
  37725. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  37726. #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
  37727. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  37728. #else
  37729. { "GetVersionExA", (SYSCALL)0, 0 },
  37730. #endif
  37731. #define osGetVersionExA ((BOOL(WINAPI*)( \
  37732. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  37733. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  37734. SQLITE_WIN32_GETVERSIONEX
  37735. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  37736. #else
  37737. { "GetVersionExW", (SYSCALL)0, 0 },
  37738. #endif
  37739. #define osGetVersionExW ((BOOL(WINAPI*)( \
  37740. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  37741. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  37742. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  37743. SIZE_T))aSyscall[36].pCurrent)
  37744. #if !SQLITE_OS_WINRT
  37745. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  37746. #else
  37747. { "HeapCreate", (SYSCALL)0, 0 },
  37748. #endif
  37749. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  37750. SIZE_T))aSyscall[37].pCurrent)
  37751. #if !SQLITE_OS_WINRT
  37752. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  37753. #else
  37754. { "HeapDestroy", (SYSCALL)0, 0 },
  37755. #endif
  37756. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  37757. { "HeapFree", (SYSCALL)HeapFree, 0 },
  37758. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  37759. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  37760. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  37761. SIZE_T))aSyscall[40].pCurrent)
  37762. { "HeapSize", (SYSCALL)HeapSize, 0 },
  37763. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  37764. LPCVOID))aSyscall[41].pCurrent)
  37765. #if !SQLITE_OS_WINRT
  37766. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  37767. #else
  37768. { "HeapValidate", (SYSCALL)0, 0 },
  37769. #endif
  37770. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  37771. LPCVOID))aSyscall[42].pCurrent)
  37772. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  37773. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  37774. #else
  37775. { "HeapCompact", (SYSCALL)0, 0 },
  37776. #endif
  37777. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  37778. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  37779. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  37780. #else
  37781. { "LoadLibraryA", (SYSCALL)0, 0 },
  37782. #endif
  37783. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  37784. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  37785. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  37786. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  37787. #else
  37788. { "LoadLibraryW", (SYSCALL)0, 0 },
  37789. #endif
  37790. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  37791. #if !SQLITE_OS_WINRT
  37792. { "LocalFree", (SYSCALL)LocalFree, 0 },
  37793. #else
  37794. { "LocalFree", (SYSCALL)0, 0 },
  37795. #endif
  37796. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  37797. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  37798. { "LockFile", (SYSCALL)LockFile, 0 },
  37799. #else
  37800. { "LockFile", (SYSCALL)0, 0 },
  37801. #endif
  37802. #ifndef osLockFile
  37803. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  37804. DWORD))aSyscall[47].pCurrent)
  37805. #endif
  37806. #if !SQLITE_OS_WINCE
  37807. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  37808. #else
  37809. { "LockFileEx", (SYSCALL)0, 0 },
  37810. #endif
  37811. #ifndef osLockFileEx
  37812. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  37813. LPOVERLAPPED))aSyscall[48].pCurrent)
  37814. #endif
  37815. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  37816. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  37817. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  37818. #else
  37819. { "MapViewOfFile", (SYSCALL)0, 0 },
  37820. #endif
  37821. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  37822. SIZE_T))aSyscall[49].pCurrent)
  37823. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  37824. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  37825. int))aSyscall[50].pCurrent)
  37826. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  37827. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  37828. LARGE_INTEGER*))aSyscall[51].pCurrent)
  37829. { "ReadFile", (SYSCALL)ReadFile, 0 },
  37830. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  37831. LPOVERLAPPED))aSyscall[52].pCurrent)
  37832. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  37833. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  37834. #if !SQLITE_OS_WINRT
  37835. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  37836. #else
  37837. { "SetFilePointer", (SYSCALL)0, 0 },
  37838. #endif
  37839. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  37840. DWORD))aSyscall[54].pCurrent)
  37841. #if !SQLITE_OS_WINRT
  37842. { "Sleep", (SYSCALL)Sleep, 0 },
  37843. #else
  37844. { "Sleep", (SYSCALL)0, 0 },
  37845. #endif
  37846. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  37847. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  37848. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  37849. LPFILETIME))aSyscall[56].pCurrent)
  37850. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  37851. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  37852. #else
  37853. { "UnlockFile", (SYSCALL)0, 0 },
  37854. #endif
  37855. #ifndef osUnlockFile
  37856. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  37857. DWORD))aSyscall[57].pCurrent)
  37858. #endif
  37859. #if !SQLITE_OS_WINCE
  37860. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  37861. #else
  37862. { "UnlockFileEx", (SYSCALL)0, 0 },
  37863. #endif
  37864. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  37865. LPOVERLAPPED))aSyscall[58].pCurrent)
  37866. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  37867. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  37868. #else
  37869. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  37870. #endif
  37871. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  37872. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  37873. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  37874. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  37875. { "WriteFile", (SYSCALL)WriteFile, 0 },
  37876. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  37877. LPOVERLAPPED))aSyscall[61].pCurrent)
  37878. #if SQLITE_OS_WINRT
  37879. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  37880. #else
  37881. { "CreateEventExW", (SYSCALL)0, 0 },
  37882. #endif
  37883. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  37884. DWORD,DWORD))aSyscall[62].pCurrent)
  37885. #if !SQLITE_OS_WINRT
  37886. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  37887. #else
  37888. { "WaitForSingleObject", (SYSCALL)0, 0 },
  37889. #endif
  37890. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  37891. DWORD))aSyscall[63].pCurrent)
  37892. #if !SQLITE_OS_WINCE
  37893. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  37894. #else
  37895. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  37896. #endif
  37897. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  37898. BOOL))aSyscall[64].pCurrent)
  37899. #if SQLITE_OS_WINRT
  37900. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  37901. #else
  37902. { "SetFilePointerEx", (SYSCALL)0, 0 },
  37903. #endif
  37904. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  37905. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  37906. #if SQLITE_OS_WINRT
  37907. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  37908. #else
  37909. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  37910. #endif
  37911. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  37912. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  37913. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  37914. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  37915. #else
  37916. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  37917. #endif
  37918. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  37919. SIZE_T))aSyscall[67].pCurrent)
  37920. #if SQLITE_OS_WINRT
  37921. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  37922. #else
  37923. { "CreateFile2", (SYSCALL)0, 0 },
  37924. #endif
  37925. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  37926. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  37927. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  37928. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  37929. #else
  37930. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  37931. #endif
  37932. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  37933. DWORD))aSyscall[69].pCurrent)
  37934. #if SQLITE_OS_WINRT
  37935. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  37936. #else
  37937. { "GetTickCount64", (SYSCALL)0, 0 },
  37938. #endif
  37939. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  37940. #if SQLITE_OS_WINRT
  37941. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  37942. #else
  37943. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  37944. #endif
  37945. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  37946. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  37947. #if defined(SQLITE_WIN32_HAS_ANSI)
  37948. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  37949. #else
  37950. { "OutputDebugStringA", (SYSCALL)0, 0 },
  37951. #endif
  37952. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  37953. #if defined(SQLITE_WIN32_HAS_WIDE)
  37954. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  37955. #else
  37956. { "OutputDebugStringW", (SYSCALL)0, 0 },
  37957. #endif
  37958. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  37959. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  37960. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  37961. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  37962. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  37963. #else
  37964. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  37965. #endif
  37966. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  37967. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  37968. /*
  37969. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  37970. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  37971. ** So do not try to make this is into a redefinable interface.
  37972. */
  37973. #if defined(InterlockedCompareExchange)
  37974. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  37975. #define osInterlockedCompareExchange InterlockedCompareExchange
  37976. #else
  37977. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  37978. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  37979. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  37980. #endif /* defined(InterlockedCompareExchange) */
  37981. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  37982. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  37983. #else
  37984. { "UuidCreate", (SYSCALL)0, 0 },
  37985. #endif
  37986. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  37987. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  37988. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  37989. #else
  37990. { "UuidCreateSequential", (SYSCALL)0, 0 },
  37991. #endif
  37992. #define osUuidCreateSequential \
  37993. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  37994. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  37995. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  37996. #else
  37997. { "FlushViewOfFile", (SYSCALL)0, 0 },
  37998. #endif
  37999. #define osFlushViewOfFile \
  38000. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  38001. }; /* End of the overrideable system calls */
  38002. /*
  38003. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  38004. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  38005. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  38006. ** system call named zName.
  38007. */
  38008. static int winSetSystemCall(
  38009. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  38010. const char *zName, /* Name of system call to override */
  38011. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  38012. ){
  38013. unsigned int i;
  38014. int rc = SQLITE_NOTFOUND;
  38015. UNUSED_PARAMETER(pNotUsed);
  38016. if( zName==0 ){
  38017. /* If no zName is given, restore all system calls to their default
  38018. ** settings and return NULL
  38019. */
  38020. rc = SQLITE_OK;
  38021. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  38022. if( aSyscall[i].pDefault ){
  38023. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  38024. }
  38025. }
  38026. }else{
  38027. /* If zName is specified, operate on only the one system call
  38028. ** specified.
  38029. */
  38030. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  38031. if( strcmp(zName, aSyscall[i].zName)==0 ){
  38032. if( aSyscall[i].pDefault==0 ){
  38033. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  38034. }
  38035. rc = SQLITE_OK;
  38036. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  38037. aSyscall[i].pCurrent = pNewFunc;
  38038. break;
  38039. }
  38040. }
  38041. }
  38042. return rc;
  38043. }
  38044. /*
  38045. ** Return the value of a system call. Return NULL if zName is not a
  38046. ** recognized system call name. NULL is also returned if the system call
  38047. ** is currently undefined.
  38048. */
  38049. static sqlite3_syscall_ptr winGetSystemCall(
  38050. sqlite3_vfs *pNotUsed,
  38051. const char *zName
  38052. ){
  38053. unsigned int i;
  38054. UNUSED_PARAMETER(pNotUsed);
  38055. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  38056. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  38057. }
  38058. return 0;
  38059. }
  38060. /*
  38061. ** Return the name of the first system call after zName. If zName==NULL
  38062. ** then return the name of the first system call. Return NULL if zName
  38063. ** is the last system call or if zName is not the name of a valid
  38064. ** system call.
  38065. */
  38066. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  38067. int i = -1;
  38068. UNUSED_PARAMETER(p);
  38069. if( zName ){
  38070. for(i=0; i<ArraySize(aSyscall)-1; i++){
  38071. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  38072. }
  38073. }
  38074. for(i++; i<ArraySize(aSyscall); i++){
  38075. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  38076. }
  38077. return 0;
  38078. }
  38079. #ifdef SQLITE_WIN32_MALLOC
  38080. /*
  38081. ** If a Win32 native heap has been configured, this function will attempt to
  38082. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  38083. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  38084. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  38085. ** largest committed free block in the heap, in bytes.
  38086. */
  38087. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  38088. int rc = SQLITE_OK;
  38089. UINT nLargest = 0;
  38090. HANDLE hHeap;
  38091. winMemAssertMagic();
  38092. hHeap = winMemGetHeap();
  38093. assert( hHeap!=0 );
  38094. assert( hHeap!=INVALID_HANDLE_VALUE );
  38095. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38096. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  38097. #endif
  38098. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  38099. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  38100. DWORD lastErrno = osGetLastError();
  38101. if( lastErrno==NO_ERROR ){
  38102. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  38103. (void*)hHeap);
  38104. rc = SQLITE_NOMEM_BKPT;
  38105. }else{
  38106. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  38107. osGetLastError(), (void*)hHeap);
  38108. rc = SQLITE_ERROR;
  38109. }
  38110. }
  38111. #else
  38112. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  38113. (void*)hHeap);
  38114. rc = SQLITE_NOTFOUND;
  38115. #endif
  38116. if( pnLargest ) *pnLargest = nLargest;
  38117. return rc;
  38118. }
  38119. /*
  38120. ** If a Win32 native heap has been configured, this function will attempt to
  38121. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  38122. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  38123. ** be returned and no changes will be made to the Win32 native heap.
  38124. */
  38125. SQLITE_API int sqlite3_win32_reset_heap(){
  38126. int rc;
  38127. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  38128. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  38129. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  38130. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  38131. sqlite3_mutex_enter(pMaster);
  38132. sqlite3_mutex_enter(pMem);
  38133. winMemAssertMagic();
  38134. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  38135. /*
  38136. ** At this point, there should be no outstanding memory allocations on
  38137. ** the heap. Also, since both the master and memsys locks are currently
  38138. ** being held by us, no other function (i.e. from another thread) should
  38139. ** be able to even access the heap. Attempt to destroy and recreate our
  38140. ** isolated Win32 native heap now.
  38141. */
  38142. assert( winMemGetHeap()!=NULL );
  38143. assert( winMemGetOwned() );
  38144. assert( sqlite3_memory_used()==0 );
  38145. winMemShutdown(winMemGetDataPtr());
  38146. assert( winMemGetHeap()==NULL );
  38147. assert( !winMemGetOwned() );
  38148. assert( sqlite3_memory_used()==0 );
  38149. rc = winMemInit(winMemGetDataPtr());
  38150. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  38151. assert( rc!=SQLITE_OK || winMemGetOwned() );
  38152. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  38153. }else{
  38154. /*
  38155. ** The Win32 native heap cannot be modified because it may be in use.
  38156. */
  38157. rc = SQLITE_BUSY;
  38158. }
  38159. sqlite3_mutex_leave(pMem);
  38160. sqlite3_mutex_leave(pMaster);
  38161. return rc;
  38162. }
  38163. #endif /* SQLITE_WIN32_MALLOC */
  38164. /*
  38165. ** This function outputs the specified (ANSI) string to the Win32 debugger
  38166. ** (if available).
  38167. */
  38168. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  38169. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  38170. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  38171. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  38172. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  38173. #ifdef SQLITE_ENABLE_API_ARMOR
  38174. if( !zBuf ){
  38175. (void)SQLITE_MISUSE_BKPT;
  38176. return;
  38177. }
  38178. #endif
  38179. #if defined(SQLITE_WIN32_HAS_ANSI)
  38180. if( nMin>0 ){
  38181. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  38182. memcpy(zDbgBuf, zBuf, nMin);
  38183. osOutputDebugStringA(zDbgBuf);
  38184. }else{
  38185. osOutputDebugStringA(zBuf);
  38186. }
  38187. #elif defined(SQLITE_WIN32_HAS_WIDE)
  38188. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  38189. if ( osMultiByteToWideChar(
  38190. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  38191. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  38192. return;
  38193. }
  38194. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  38195. #else
  38196. if( nMin>0 ){
  38197. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  38198. memcpy(zDbgBuf, zBuf, nMin);
  38199. fprintf(stderr, "%s", zDbgBuf);
  38200. }else{
  38201. fprintf(stderr, "%s", zBuf);
  38202. }
  38203. #endif
  38204. }
  38205. /*
  38206. ** The following routine suspends the current thread for at least ms
  38207. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  38208. */
  38209. #if SQLITE_OS_WINRT
  38210. static HANDLE sleepObj = NULL;
  38211. #endif
  38212. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  38213. #if SQLITE_OS_WINRT
  38214. if ( sleepObj==NULL ){
  38215. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  38216. SYNCHRONIZE);
  38217. }
  38218. assert( sleepObj!=NULL );
  38219. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  38220. #else
  38221. osSleep(milliseconds);
  38222. #endif
  38223. }
  38224. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  38225. SQLITE_THREADSAFE>0
  38226. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  38227. DWORD rc;
  38228. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  38229. TRUE))==WAIT_IO_COMPLETION ){}
  38230. return rc;
  38231. }
  38232. #endif
  38233. /*
  38234. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  38235. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  38236. **
  38237. ** Here is an interesting observation: Win95, Win98, and WinME lack
  38238. ** the LockFileEx() API. But we can still statically link against that
  38239. ** API as long as we don't call it when running Win95/98/ME. A call to
  38240. ** this routine is used to determine if the host is Win95/98/ME or
  38241. ** WinNT/2K/XP so that we will know whether or not we can safely call
  38242. ** the LockFileEx() API.
  38243. */
  38244. #if !SQLITE_WIN32_GETVERSIONEX
  38245. # define osIsNT() (1)
  38246. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  38247. # define osIsNT() (1)
  38248. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  38249. # define osIsNT() (0)
  38250. #else
  38251. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  38252. #endif
  38253. /*
  38254. ** This function determines if the machine is running a version of Windows
  38255. ** based on the NT kernel.
  38256. */
  38257. SQLITE_API int sqlite3_win32_is_nt(void){
  38258. #if SQLITE_OS_WINRT
  38259. /*
  38260. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  38261. ** kernel.
  38262. */
  38263. return 1;
  38264. #elif SQLITE_WIN32_GETVERSIONEX
  38265. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  38266. #if defined(SQLITE_WIN32_HAS_ANSI)
  38267. OSVERSIONINFOA sInfo;
  38268. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  38269. osGetVersionExA(&sInfo);
  38270. osInterlockedCompareExchange(&sqlite3_os_type,
  38271. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  38272. #elif defined(SQLITE_WIN32_HAS_WIDE)
  38273. OSVERSIONINFOW sInfo;
  38274. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  38275. osGetVersionExW(&sInfo);
  38276. osInterlockedCompareExchange(&sqlite3_os_type,
  38277. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  38278. #endif
  38279. }
  38280. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  38281. #elif SQLITE_TEST
  38282. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  38283. #else
  38284. /*
  38285. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  38286. ** deprecated are always assumed to be based on the NT kernel.
  38287. */
  38288. return 1;
  38289. #endif
  38290. }
  38291. #ifdef SQLITE_WIN32_MALLOC
  38292. /*
  38293. ** Allocate nBytes of memory.
  38294. */
  38295. static void *winMemMalloc(int nBytes){
  38296. HANDLE hHeap;
  38297. void *p;
  38298. winMemAssertMagic();
  38299. hHeap = winMemGetHeap();
  38300. assert( hHeap!=0 );
  38301. assert( hHeap!=INVALID_HANDLE_VALUE );
  38302. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38303. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  38304. #endif
  38305. assert( nBytes>=0 );
  38306. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  38307. if( !p ){
  38308. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  38309. nBytes, osGetLastError(), (void*)hHeap);
  38310. }
  38311. return p;
  38312. }
  38313. /*
  38314. ** Free memory.
  38315. */
  38316. static void winMemFree(void *pPrior){
  38317. HANDLE hHeap;
  38318. winMemAssertMagic();
  38319. hHeap = winMemGetHeap();
  38320. assert( hHeap!=0 );
  38321. assert( hHeap!=INVALID_HANDLE_VALUE );
  38322. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38323. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  38324. #endif
  38325. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  38326. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  38327. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  38328. pPrior, osGetLastError(), (void*)hHeap);
  38329. }
  38330. }
  38331. /*
  38332. ** Change the size of an existing memory allocation
  38333. */
  38334. static void *winMemRealloc(void *pPrior, int nBytes){
  38335. HANDLE hHeap;
  38336. void *p;
  38337. winMemAssertMagic();
  38338. hHeap = winMemGetHeap();
  38339. assert( hHeap!=0 );
  38340. assert( hHeap!=INVALID_HANDLE_VALUE );
  38341. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38342. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  38343. #endif
  38344. assert( nBytes>=0 );
  38345. if( !pPrior ){
  38346. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  38347. }else{
  38348. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  38349. }
  38350. if( !p ){
  38351. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  38352. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  38353. (void*)hHeap);
  38354. }
  38355. return p;
  38356. }
  38357. /*
  38358. ** Return the size of an outstanding allocation, in bytes.
  38359. */
  38360. static int winMemSize(void *p){
  38361. HANDLE hHeap;
  38362. SIZE_T n;
  38363. winMemAssertMagic();
  38364. hHeap = winMemGetHeap();
  38365. assert( hHeap!=0 );
  38366. assert( hHeap!=INVALID_HANDLE_VALUE );
  38367. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38368. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  38369. #endif
  38370. if( !p ) return 0;
  38371. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  38372. if( n==(SIZE_T)-1 ){
  38373. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  38374. p, osGetLastError(), (void*)hHeap);
  38375. return 0;
  38376. }
  38377. return (int)n;
  38378. }
  38379. /*
  38380. ** Round up a request size to the next valid allocation size.
  38381. */
  38382. static int winMemRoundup(int n){
  38383. return n;
  38384. }
  38385. /*
  38386. ** Initialize this module.
  38387. */
  38388. static int winMemInit(void *pAppData){
  38389. winMemData *pWinMemData = (winMemData *)pAppData;
  38390. if( !pWinMemData ) return SQLITE_ERROR;
  38391. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  38392. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  38393. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  38394. if( !pWinMemData->hHeap ){
  38395. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  38396. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  38397. if( dwMaximumSize==0 ){
  38398. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  38399. }else if( dwInitialSize>dwMaximumSize ){
  38400. dwInitialSize = dwMaximumSize;
  38401. }
  38402. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  38403. dwInitialSize, dwMaximumSize);
  38404. if( !pWinMemData->hHeap ){
  38405. sqlite3_log(SQLITE_NOMEM,
  38406. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  38407. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  38408. dwMaximumSize);
  38409. return SQLITE_NOMEM_BKPT;
  38410. }
  38411. pWinMemData->bOwned = TRUE;
  38412. assert( pWinMemData->bOwned );
  38413. }
  38414. #else
  38415. pWinMemData->hHeap = osGetProcessHeap();
  38416. if( !pWinMemData->hHeap ){
  38417. sqlite3_log(SQLITE_NOMEM,
  38418. "failed to GetProcessHeap (%lu)", osGetLastError());
  38419. return SQLITE_NOMEM_BKPT;
  38420. }
  38421. pWinMemData->bOwned = FALSE;
  38422. assert( !pWinMemData->bOwned );
  38423. #endif
  38424. assert( pWinMemData->hHeap!=0 );
  38425. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  38426. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38427. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  38428. #endif
  38429. return SQLITE_OK;
  38430. }
  38431. /*
  38432. ** Deinitialize this module.
  38433. */
  38434. static void winMemShutdown(void *pAppData){
  38435. winMemData *pWinMemData = (winMemData *)pAppData;
  38436. if( !pWinMemData ) return;
  38437. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  38438. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  38439. if( pWinMemData->hHeap ){
  38440. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  38441. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  38442. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  38443. #endif
  38444. if( pWinMemData->bOwned ){
  38445. if( !osHeapDestroy(pWinMemData->hHeap) ){
  38446. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  38447. osGetLastError(), (void*)pWinMemData->hHeap);
  38448. }
  38449. pWinMemData->bOwned = FALSE;
  38450. }
  38451. pWinMemData->hHeap = NULL;
  38452. }
  38453. }
  38454. /*
  38455. ** Populate the low-level memory allocation function pointers in
  38456. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  38457. ** arguments specify the block of memory to manage.
  38458. **
  38459. ** This routine is only called by sqlite3_config(), and therefore
  38460. ** is not required to be threadsafe (it is not).
  38461. */
  38462. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  38463. static const sqlite3_mem_methods winMemMethods = {
  38464. winMemMalloc,
  38465. winMemFree,
  38466. winMemRealloc,
  38467. winMemSize,
  38468. winMemRoundup,
  38469. winMemInit,
  38470. winMemShutdown,
  38471. &win_mem_data
  38472. };
  38473. return &winMemMethods;
  38474. }
  38475. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  38476. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  38477. }
  38478. #endif /* SQLITE_WIN32_MALLOC */
  38479. /*
  38480. ** Convert a UTF-8 string to Microsoft Unicode.
  38481. **
  38482. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38483. */
  38484. static LPWSTR winUtf8ToUnicode(const char *zText){
  38485. int nChar;
  38486. LPWSTR zWideText;
  38487. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
  38488. if( nChar==0 ){
  38489. return 0;
  38490. }
  38491. zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
  38492. if( zWideText==0 ){
  38493. return 0;
  38494. }
  38495. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
  38496. nChar);
  38497. if( nChar==0 ){
  38498. sqlite3_free(zWideText);
  38499. zWideText = 0;
  38500. }
  38501. return zWideText;
  38502. }
  38503. /*
  38504. ** Convert a Microsoft Unicode string to UTF-8.
  38505. **
  38506. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38507. */
  38508. static char *winUnicodeToUtf8(LPCWSTR zWideText){
  38509. int nByte;
  38510. char *zText;
  38511. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
  38512. if( nByte == 0 ){
  38513. return 0;
  38514. }
  38515. zText = sqlite3MallocZero( nByte );
  38516. if( zText==0 ){
  38517. return 0;
  38518. }
  38519. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
  38520. 0, 0);
  38521. if( nByte == 0 ){
  38522. sqlite3_free(zText);
  38523. zText = 0;
  38524. }
  38525. return zText;
  38526. }
  38527. /*
  38528. ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
  38529. ** code page.
  38530. **
  38531. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38532. */
  38533. static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
  38534. int nByte;
  38535. LPWSTR zMbcsText;
  38536. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  38537. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
  38538. 0)*sizeof(WCHAR);
  38539. if( nByte==0 ){
  38540. return 0;
  38541. }
  38542. zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
  38543. if( zMbcsText==0 ){
  38544. return 0;
  38545. }
  38546. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
  38547. nByte);
  38548. if( nByte==0 ){
  38549. sqlite3_free(zMbcsText);
  38550. zMbcsText = 0;
  38551. }
  38552. return zMbcsText;
  38553. }
  38554. /*
  38555. ** Convert a Microsoft Unicode string to a multi-byte character string,
  38556. ** using the ANSI or OEM code page.
  38557. **
  38558. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38559. */
  38560. static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
  38561. int nByte;
  38562. char *zText;
  38563. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  38564. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
  38565. if( nByte == 0 ){
  38566. return 0;
  38567. }
  38568. zText = sqlite3MallocZero( nByte );
  38569. if( zText==0 ){
  38570. return 0;
  38571. }
  38572. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
  38573. nByte, 0, 0);
  38574. if( nByte == 0 ){
  38575. sqlite3_free(zText);
  38576. zText = 0;
  38577. }
  38578. return zText;
  38579. }
  38580. /*
  38581. ** Convert a multi-byte character string to UTF-8.
  38582. **
  38583. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38584. */
  38585. static char *winMbcsToUtf8(const char *zText, int useAnsi){
  38586. char *zTextUtf8;
  38587. LPWSTR zTmpWide;
  38588. zTmpWide = winMbcsToUnicode(zText, useAnsi);
  38589. if( zTmpWide==0 ){
  38590. return 0;
  38591. }
  38592. zTextUtf8 = winUnicodeToUtf8(zTmpWide);
  38593. sqlite3_free(zTmpWide);
  38594. return zTextUtf8;
  38595. }
  38596. /*
  38597. ** Convert a UTF-8 string to a multi-byte character string.
  38598. **
  38599. ** Space to hold the returned string is obtained from sqlite3_malloc().
  38600. */
  38601. static char *winUtf8ToMbcs(const char *zText, int useAnsi){
  38602. char *zTextMbcs;
  38603. LPWSTR zTmpWide;
  38604. zTmpWide = winUtf8ToUnicode(zText);
  38605. if( zTmpWide==0 ){
  38606. return 0;
  38607. }
  38608. zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
  38609. sqlite3_free(zTmpWide);
  38610. return zTextMbcs;
  38611. }
  38612. /*
  38613. ** This is a public wrapper for the winUtf8ToUnicode() function.
  38614. */
  38615. SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
  38616. #ifdef SQLITE_ENABLE_API_ARMOR
  38617. if( !zText ){
  38618. (void)SQLITE_MISUSE_BKPT;
  38619. return 0;
  38620. }
  38621. #endif
  38622. #ifndef SQLITE_OMIT_AUTOINIT
  38623. if( sqlite3_initialize() ) return 0;
  38624. #endif
  38625. return winUtf8ToUnicode(zText);
  38626. }
  38627. /*
  38628. ** This is a public wrapper for the winUnicodeToUtf8() function.
  38629. */
  38630. SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
  38631. #ifdef SQLITE_ENABLE_API_ARMOR
  38632. if( !zWideText ){
  38633. (void)SQLITE_MISUSE_BKPT;
  38634. return 0;
  38635. }
  38636. #endif
  38637. #ifndef SQLITE_OMIT_AUTOINIT
  38638. if( sqlite3_initialize() ) return 0;
  38639. #endif
  38640. return winUnicodeToUtf8(zWideText);
  38641. }
  38642. /*
  38643. ** This is a public wrapper for the winMbcsToUtf8() function.
  38644. */
  38645. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
  38646. #ifdef SQLITE_ENABLE_API_ARMOR
  38647. if( !zText ){
  38648. (void)SQLITE_MISUSE_BKPT;
  38649. return 0;
  38650. }
  38651. #endif
  38652. #ifndef SQLITE_OMIT_AUTOINIT
  38653. if( sqlite3_initialize() ) return 0;
  38654. #endif
  38655. return winMbcsToUtf8(zText, osAreFileApisANSI());
  38656. }
  38657. /*
  38658. ** This is a public wrapper for the winMbcsToUtf8() function.
  38659. */
  38660. SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
  38661. #ifdef SQLITE_ENABLE_API_ARMOR
  38662. if( !zText ){
  38663. (void)SQLITE_MISUSE_BKPT;
  38664. return 0;
  38665. }
  38666. #endif
  38667. #ifndef SQLITE_OMIT_AUTOINIT
  38668. if( sqlite3_initialize() ) return 0;
  38669. #endif
  38670. return winMbcsToUtf8(zText, useAnsi);
  38671. }
  38672. /*
  38673. ** This is a public wrapper for the winUtf8ToMbcs() function.
  38674. */
  38675. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
  38676. #ifdef SQLITE_ENABLE_API_ARMOR
  38677. if( !zText ){
  38678. (void)SQLITE_MISUSE_BKPT;
  38679. return 0;
  38680. }
  38681. #endif
  38682. #ifndef SQLITE_OMIT_AUTOINIT
  38683. if( sqlite3_initialize() ) return 0;
  38684. #endif
  38685. return winUtf8ToMbcs(zText, osAreFileApisANSI());
  38686. }
  38687. /*
  38688. ** This is a public wrapper for the winUtf8ToMbcs() function.
  38689. */
  38690. SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
  38691. #ifdef SQLITE_ENABLE_API_ARMOR
  38692. if( !zText ){
  38693. (void)SQLITE_MISUSE_BKPT;
  38694. return 0;
  38695. }
  38696. #endif
  38697. #ifndef SQLITE_OMIT_AUTOINIT
  38698. if( sqlite3_initialize() ) return 0;
  38699. #endif
  38700. return winUtf8ToMbcs(zText, useAnsi);
  38701. }
  38702. /*
  38703. ** This function sets the data directory or the temporary directory based on
  38704. ** the provided arguments. The type argument must be 1 in order to set the
  38705. ** data directory or 2 in order to set the temporary directory. The zValue
  38706. ** argument is the name of the directory to use. The return value will be
  38707. ** SQLITE_OK if successful.
  38708. */
  38709. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  38710. char **ppDirectory = 0;
  38711. #ifndef SQLITE_OMIT_AUTOINIT
  38712. int rc = sqlite3_initialize();
  38713. if( rc ) return rc;
  38714. #endif
  38715. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  38716. ppDirectory = &sqlite3_data_directory;
  38717. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  38718. ppDirectory = &sqlite3_temp_directory;
  38719. }
  38720. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  38721. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  38722. );
  38723. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  38724. if( ppDirectory ){
  38725. char *zValueUtf8 = 0;
  38726. if( zValue && zValue[0] ){
  38727. zValueUtf8 = winUnicodeToUtf8(zValue);
  38728. if ( zValueUtf8==0 ){
  38729. return SQLITE_NOMEM_BKPT;
  38730. }
  38731. }
  38732. sqlite3_free(*ppDirectory);
  38733. *ppDirectory = zValueUtf8;
  38734. return SQLITE_OK;
  38735. }
  38736. return SQLITE_ERROR;
  38737. }
  38738. /*
  38739. ** The return value of winGetLastErrorMsg
  38740. ** is zero if the error message fits in the buffer, or non-zero
  38741. ** otherwise (if the message was truncated).
  38742. */
  38743. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  38744. /* FormatMessage returns 0 on failure. Otherwise it
  38745. ** returns the number of TCHARs written to the output
  38746. ** buffer, excluding the terminating null char.
  38747. */
  38748. DWORD dwLen = 0;
  38749. char *zOut = 0;
  38750. if( osIsNT() ){
  38751. #if SQLITE_OS_WINRT
  38752. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  38753. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  38754. FORMAT_MESSAGE_IGNORE_INSERTS,
  38755. NULL,
  38756. lastErrno,
  38757. 0,
  38758. zTempWide,
  38759. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  38760. 0);
  38761. #else
  38762. LPWSTR zTempWide = NULL;
  38763. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  38764. FORMAT_MESSAGE_FROM_SYSTEM |
  38765. FORMAT_MESSAGE_IGNORE_INSERTS,
  38766. NULL,
  38767. lastErrno,
  38768. 0,
  38769. (LPWSTR) &zTempWide,
  38770. 0,
  38771. 0);
  38772. #endif
  38773. if( dwLen > 0 ){
  38774. /* allocate a buffer and convert to UTF8 */
  38775. sqlite3BeginBenignMalloc();
  38776. zOut = winUnicodeToUtf8(zTempWide);
  38777. sqlite3EndBenignMalloc();
  38778. #if !SQLITE_OS_WINRT
  38779. /* free the system buffer allocated by FormatMessage */
  38780. osLocalFree(zTempWide);
  38781. #endif
  38782. }
  38783. }
  38784. #ifdef SQLITE_WIN32_HAS_ANSI
  38785. else{
  38786. char *zTemp = NULL;
  38787. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  38788. FORMAT_MESSAGE_FROM_SYSTEM |
  38789. FORMAT_MESSAGE_IGNORE_INSERTS,
  38790. NULL,
  38791. lastErrno,
  38792. 0,
  38793. (LPSTR) &zTemp,
  38794. 0,
  38795. 0);
  38796. if( dwLen > 0 ){
  38797. /* allocate a buffer and convert to UTF8 */
  38798. sqlite3BeginBenignMalloc();
  38799. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  38800. sqlite3EndBenignMalloc();
  38801. /* free the system buffer allocated by FormatMessage */
  38802. osLocalFree(zTemp);
  38803. }
  38804. }
  38805. #endif
  38806. if( 0 == dwLen ){
  38807. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  38808. }else{
  38809. /* copy a maximum of nBuf chars to output buffer */
  38810. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  38811. /* free the UTF8 buffer */
  38812. sqlite3_free(zOut);
  38813. }
  38814. return 0;
  38815. }
  38816. /*
  38817. **
  38818. ** This function - winLogErrorAtLine() - is only ever called via the macro
  38819. ** winLogError().
  38820. **
  38821. ** This routine is invoked after an error occurs in an OS function.
  38822. ** It logs a message using sqlite3_log() containing the current value of
  38823. ** error code and, if possible, the human-readable equivalent from
  38824. ** FormatMessage.
  38825. **
  38826. ** The first argument passed to the macro should be the error code that
  38827. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  38828. ** The two subsequent arguments should be the name of the OS function that
  38829. ** failed and the associated file-system path, if any.
  38830. */
  38831. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  38832. static int winLogErrorAtLine(
  38833. int errcode, /* SQLite error code */
  38834. DWORD lastErrno, /* Win32 last error */
  38835. const char *zFunc, /* Name of OS function that failed */
  38836. const char *zPath, /* File path associated with error */
  38837. int iLine /* Source line number where error occurred */
  38838. ){
  38839. char zMsg[500]; /* Human readable error text */
  38840. int i; /* Loop counter */
  38841. zMsg[0] = 0;
  38842. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  38843. assert( errcode!=SQLITE_OK );
  38844. if( zPath==0 ) zPath = "";
  38845. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  38846. zMsg[i] = 0;
  38847. sqlite3_log(errcode,
  38848. "os_win.c:%d: (%lu) %s(%s) - %s",
  38849. iLine, lastErrno, zFunc, zPath, zMsg
  38850. );
  38851. return errcode;
  38852. }
  38853. /*
  38854. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  38855. ** will be retried following a locking error - probably caused by
  38856. ** antivirus software. Also the initial delay before the first retry.
  38857. ** The delay increases linearly with each retry.
  38858. */
  38859. #ifndef SQLITE_WIN32_IOERR_RETRY
  38860. # define SQLITE_WIN32_IOERR_RETRY 10
  38861. #endif
  38862. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  38863. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  38864. #endif
  38865. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  38866. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  38867. /*
  38868. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  38869. ** error code obtained via GetLastError() is eligible to be retried. It
  38870. ** must accept the error code DWORD as its only argument and should return
  38871. ** non-zero if the error code is transient in nature and the operation
  38872. ** responsible for generating the original error might succeed upon being
  38873. ** retried. The argument to this macro should be a variable.
  38874. **
  38875. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  38876. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  38877. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  38878. ** may be used to include additional error codes in the set that should
  38879. ** result in the failing I/O operation being retried by the caller. If
  38880. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  38881. ** identical to those of the "winIoerrCanRetry1" macro.
  38882. */
  38883. #if !defined(winIoerrCanRetry1)
  38884. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  38885. ((a)==ERROR_SHARING_VIOLATION) || \
  38886. ((a)==ERROR_LOCK_VIOLATION) || \
  38887. ((a)==ERROR_DEV_NOT_EXIST) || \
  38888. ((a)==ERROR_NETNAME_DELETED) || \
  38889. ((a)==ERROR_SEM_TIMEOUT) || \
  38890. ((a)==ERROR_NETWORK_UNREACHABLE))
  38891. #endif
  38892. /*
  38893. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  38894. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  38895. ** to give up with an error.
  38896. */
  38897. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  38898. DWORD e = osGetLastError();
  38899. if( *pnRetry>=winIoerrRetry ){
  38900. if( pError ){
  38901. *pError = e;
  38902. }
  38903. return 0;
  38904. }
  38905. if( winIoerrCanRetry1(e) ){
  38906. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  38907. ++*pnRetry;
  38908. return 1;
  38909. }
  38910. #if defined(winIoerrCanRetry2)
  38911. else if( winIoerrCanRetry2(e) ){
  38912. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  38913. ++*pnRetry;
  38914. return 1;
  38915. }
  38916. #endif
  38917. if( pError ){
  38918. *pError = e;
  38919. }
  38920. return 0;
  38921. }
  38922. /*
  38923. ** Log a I/O error retry episode.
  38924. */
  38925. static void winLogIoerr(int nRetry, int lineno){
  38926. if( nRetry ){
  38927. sqlite3_log(SQLITE_NOTICE,
  38928. "delayed %dms for lock/sharing conflict at line %d",
  38929. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  38930. );
  38931. }
  38932. }
  38933. /*
  38934. ** This #if does not rely on the SQLITE_OS_WINCE define because the
  38935. ** corresponding section in "date.c" cannot use it.
  38936. */
  38937. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  38938. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  38939. /*
  38940. ** The MSVC CRT on Windows CE may not have a localtime() function.
  38941. ** So define a substitute.
  38942. */
  38943. /* # include <time.h> */
  38944. struct tm *__cdecl localtime(const time_t *t)
  38945. {
  38946. static struct tm y;
  38947. FILETIME uTm, lTm;
  38948. SYSTEMTIME pTm;
  38949. sqlite3_int64 t64;
  38950. t64 = *t;
  38951. t64 = (t64 + 11644473600)*10000000;
  38952. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  38953. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  38954. osFileTimeToLocalFileTime(&uTm,&lTm);
  38955. osFileTimeToSystemTime(&lTm,&pTm);
  38956. y.tm_year = pTm.wYear - 1900;
  38957. y.tm_mon = pTm.wMonth - 1;
  38958. y.tm_wday = pTm.wDayOfWeek;
  38959. y.tm_mday = pTm.wDay;
  38960. y.tm_hour = pTm.wHour;
  38961. y.tm_min = pTm.wMinute;
  38962. y.tm_sec = pTm.wSecond;
  38963. return &y;
  38964. }
  38965. #endif
  38966. #if SQLITE_OS_WINCE
  38967. /*************************************************************************
  38968. ** This section contains code for WinCE only.
  38969. */
  38970. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  38971. /*
  38972. ** Acquire a lock on the handle h
  38973. */
  38974. static void winceMutexAcquire(HANDLE h){
  38975. DWORD dwErr;
  38976. do {
  38977. dwErr = osWaitForSingleObject(h, INFINITE);
  38978. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  38979. }
  38980. /*
  38981. ** Release a lock acquired by winceMutexAcquire()
  38982. */
  38983. #define winceMutexRelease(h) ReleaseMutex(h)
  38984. /*
  38985. ** Create the mutex and shared memory used for locking in the file
  38986. ** descriptor pFile
  38987. */
  38988. static int winceCreateLock(const char *zFilename, winFile *pFile){
  38989. LPWSTR zTok;
  38990. LPWSTR zName;
  38991. DWORD lastErrno;
  38992. BOOL bLogged = FALSE;
  38993. BOOL bInit = TRUE;
  38994. zName = winUtf8ToUnicode(zFilename);
  38995. if( zName==0 ){
  38996. /* out of memory */
  38997. return SQLITE_IOERR_NOMEM_BKPT;
  38998. }
  38999. /* Initialize the local lockdata */
  39000. memset(&pFile->local, 0, sizeof(pFile->local));
  39001. /* Replace the backslashes from the filename and lowercase it
  39002. ** to derive a mutex name. */
  39003. zTok = osCharLowerW(zName);
  39004. for (;*zTok;zTok++){
  39005. if (*zTok == '\\') *zTok = '_';
  39006. }
  39007. /* Create/open the named mutex */
  39008. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  39009. if (!pFile->hMutex){
  39010. pFile->lastErrno = osGetLastError();
  39011. sqlite3_free(zName);
  39012. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  39013. "winceCreateLock1", zFilename);
  39014. }
  39015. /* Acquire the mutex before continuing */
  39016. winceMutexAcquire(pFile->hMutex);
  39017. /* Since the names of named mutexes, semaphores, file mappings etc are
  39018. ** case-sensitive, take advantage of that by uppercasing the mutex name
  39019. ** and using that as the shared filemapping name.
  39020. */
  39021. osCharUpperW(zName);
  39022. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  39023. PAGE_READWRITE, 0, sizeof(winceLock),
  39024. zName);
  39025. /* Set a flag that indicates we're the first to create the memory so it
  39026. ** must be zero-initialized */
  39027. lastErrno = osGetLastError();
  39028. if (lastErrno == ERROR_ALREADY_EXISTS){
  39029. bInit = FALSE;
  39030. }
  39031. sqlite3_free(zName);
  39032. /* If we succeeded in making the shared memory handle, map it. */
  39033. if( pFile->hShared ){
  39034. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  39035. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  39036. /* If mapping failed, close the shared memory handle and erase it */
  39037. if( !pFile->shared ){
  39038. pFile->lastErrno = osGetLastError();
  39039. winLogError(SQLITE_IOERR, pFile->lastErrno,
  39040. "winceCreateLock2", zFilename);
  39041. bLogged = TRUE;
  39042. osCloseHandle(pFile->hShared);
  39043. pFile->hShared = NULL;
  39044. }
  39045. }
  39046. /* If shared memory could not be created, then close the mutex and fail */
  39047. if( pFile->hShared==NULL ){
  39048. if( !bLogged ){
  39049. pFile->lastErrno = lastErrno;
  39050. winLogError(SQLITE_IOERR, pFile->lastErrno,
  39051. "winceCreateLock3", zFilename);
  39052. bLogged = TRUE;
  39053. }
  39054. winceMutexRelease(pFile->hMutex);
  39055. osCloseHandle(pFile->hMutex);
  39056. pFile->hMutex = NULL;
  39057. return SQLITE_IOERR;
  39058. }
  39059. /* Initialize the shared memory if we're supposed to */
  39060. if( bInit ){
  39061. memset(pFile->shared, 0, sizeof(winceLock));
  39062. }
  39063. winceMutexRelease(pFile->hMutex);
  39064. return SQLITE_OK;
  39065. }
  39066. /*
  39067. ** Destroy the part of winFile that deals with wince locks
  39068. */
  39069. static void winceDestroyLock(winFile *pFile){
  39070. if (pFile->hMutex){
  39071. /* Acquire the mutex */
  39072. winceMutexAcquire(pFile->hMutex);
  39073. /* The following blocks should probably assert in debug mode, but they
  39074. are to cleanup in case any locks remained open */
  39075. if (pFile->local.nReaders){
  39076. pFile->shared->nReaders --;
  39077. }
  39078. if (pFile->local.bReserved){
  39079. pFile->shared->bReserved = FALSE;
  39080. }
  39081. if (pFile->local.bPending){
  39082. pFile->shared->bPending = FALSE;
  39083. }
  39084. if (pFile->local.bExclusive){
  39085. pFile->shared->bExclusive = FALSE;
  39086. }
  39087. /* De-reference and close our copy of the shared memory handle */
  39088. osUnmapViewOfFile(pFile->shared);
  39089. osCloseHandle(pFile->hShared);
  39090. /* Done with the mutex */
  39091. winceMutexRelease(pFile->hMutex);
  39092. osCloseHandle(pFile->hMutex);
  39093. pFile->hMutex = NULL;
  39094. }
  39095. }
  39096. /*
  39097. ** An implementation of the LockFile() API of Windows for CE
  39098. */
  39099. static BOOL winceLockFile(
  39100. LPHANDLE phFile,
  39101. DWORD dwFileOffsetLow,
  39102. DWORD dwFileOffsetHigh,
  39103. DWORD nNumberOfBytesToLockLow,
  39104. DWORD nNumberOfBytesToLockHigh
  39105. ){
  39106. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  39107. BOOL bReturn = FALSE;
  39108. UNUSED_PARAMETER(dwFileOffsetHigh);
  39109. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  39110. if (!pFile->hMutex) return TRUE;
  39111. winceMutexAcquire(pFile->hMutex);
  39112. /* Wanting an exclusive lock? */
  39113. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  39114. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  39115. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  39116. pFile->shared->bExclusive = TRUE;
  39117. pFile->local.bExclusive = TRUE;
  39118. bReturn = TRUE;
  39119. }
  39120. }
  39121. /* Want a read-only lock? */
  39122. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  39123. nNumberOfBytesToLockLow == 1){
  39124. if (pFile->shared->bExclusive == 0){
  39125. pFile->local.nReaders ++;
  39126. if (pFile->local.nReaders == 1){
  39127. pFile->shared->nReaders ++;
  39128. }
  39129. bReturn = TRUE;
  39130. }
  39131. }
  39132. /* Want a pending lock? */
  39133. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  39134. && nNumberOfBytesToLockLow == 1){
  39135. /* If no pending lock has been acquired, then acquire it */
  39136. if (pFile->shared->bPending == 0) {
  39137. pFile->shared->bPending = TRUE;
  39138. pFile->local.bPending = TRUE;
  39139. bReturn = TRUE;
  39140. }
  39141. }
  39142. /* Want a reserved lock? */
  39143. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  39144. && nNumberOfBytesToLockLow == 1){
  39145. if (pFile->shared->bReserved == 0) {
  39146. pFile->shared->bReserved = TRUE;
  39147. pFile->local.bReserved = TRUE;
  39148. bReturn = TRUE;
  39149. }
  39150. }
  39151. winceMutexRelease(pFile->hMutex);
  39152. return bReturn;
  39153. }
  39154. /*
  39155. ** An implementation of the UnlockFile API of Windows for CE
  39156. */
  39157. static BOOL winceUnlockFile(
  39158. LPHANDLE phFile,
  39159. DWORD dwFileOffsetLow,
  39160. DWORD dwFileOffsetHigh,
  39161. DWORD nNumberOfBytesToUnlockLow,
  39162. DWORD nNumberOfBytesToUnlockHigh
  39163. ){
  39164. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  39165. BOOL bReturn = FALSE;
  39166. UNUSED_PARAMETER(dwFileOffsetHigh);
  39167. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  39168. if (!pFile->hMutex) return TRUE;
  39169. winceMutexAcquire(pFile->hMutex);
  39170. /* Releasing a reader lock or an exclusive lock */
  39171. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  39172. /* Did we have an exclusive lock? */
  39173. if (pFile->local.bExclusive){
  39174. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  39175. pFile->local.bExclusive = FALSE;
  39176. pFile->shared->bExclusive = FALSE;
  39177. bReturn = TRUE;
  39178. }
  39179. /* Did we just have a reader lock? */
  39180. else if (pFile->local.nReaders){
  39181. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  39182. || nNumberOfBytesToUnlockLow == 1);
  39183. pFile->local.nReaders --;
  39184. if (pFile->local.nReaders == 0)
  39185. {
  39186. pFile->shared->nReaders --;
  39187. }
  39188. bReturn = TRUE;
  39189. }
  39190. }
  39191. /* Releasing a pending lock */
  39192. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  39193. && nNumberOfBytesToUnlockLow == 1){
  39194. if (pFile->local.bPending){
  39195. pFile->local.bPending = FALSE;
  39196. pFile->shared->bPending = FALSE;
  39197. bReturn = TRUE;
  39198. }
  39199. }
  39200. /* Releasing a reserved lock */
  39201. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  39202. && nNumberOfBytesToUnlockLow == 1){
  39203. if (pFile->local.bReserved) {
  39204. pFile->local.bReserved = FALSE;
  39205. pFile->shared->bReserved = FALSE;
  39206. bReturn = TRUE;
  39207. }
  39208. }
  39209. winceMutexRelease(pFile->hMutex);
  39210. return bReturn;
  39211. }
  39212. /*
  39213. ** End of the special code for wince
  39214. *****************************************************************************/
  39215. #endif /* SQLITE_OS_WINCE */
  39216. /*
  39217. ** Lock a file region.
  39218. */
  39219. static BOOL winLockFile(
  39220. LPHANDLE phFile,
  39221. DWORD flags,
  39222. DWORD offsetLow,
  39223. DWORD offsetHigh,
  39224. DWORD numBytesLow,
  39225. DWORD numBytesHigh
  39226. ){
  39227. #if SQLITE_OS_WINCE
  39228. /*
  39229. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  39230. ** API LockFile.
  39231. */
  39232. return winceLockFile(phFile, offsetLow, offsetHigh,
  39233. numBytesLow, numBytesHigh);
  39234. #else
  39235. if( osIsNT() ){
  39236. OVERLAPPED ovlp;
  39237. memset(&ovlp, 0, sizeof(OVERLAPPED));
  39238. ovlp.Offset = offsetLow;
  39239. ovlp.OffsetHigh = offsetHigh;
  39240. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  39241. }else{
  39242. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  39243. numBytesHigh);
  39244. }
  39245. #endif
  39246. }
  39247. /*
  39248. ** Unlock a file region.
  39249. */
  39250. static BOOL winUnlockFile(
  39251. LPHANDLE phFile,
  39252. DWORD offsetLow,
  39253. DWORD offsetHigh,
  39254. DWORD numBytesLow,
  39255. DWORD numBytesHigh
  39256. ){
  39257. #if SQLITE_OS_WINCE
  39258. /*
  39259. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  39260. ** API UnlockFile.
  39261. */
  39262. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  39263. numBytesLow, numBytesHigh);
  39264. #else
  39265. if( osIsNT() ){
  39266. OVERLAPPED ovlp;
  39267. memset(&ovlp, 0, sizeof(OVERLAPPED));
  39268. ovlp.Offset = offsetLow;
  39269. ovlp.OffsetHigh = offsetHigh;
  39270. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  39271. }else{
  39272. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  39273. numBytesHigh);
  39274. }
  39275. #endif
  39276. }
  39277. /*****************************************************************************
  39278. ** The next group of routines implement the I/O methods specified
  39279. ** by the sqlite3_io_methods object.
  39280. ******************************************************************************/
  39281. /*
  39282. ** Some Microsoft compilers lack this definition.
  39283. */
  39284. #ifndef INVALID_SET_FILE_POINTER
  39285. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  39286. #endif
  39287. /*
  39288. ** Move the current position of the file handle passed as the first
  39289. ** argument to offset iOffset within the file. If successful, return 0.
  39290. ** Otherwise, set pFile->lastErrno and return non-zero.
  39291. */
  39292. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  39293. #if !SQLITE_OS_WINRT
  39294. LONG upperBits; /* Most sig. 32 bits of new offset */
  39295. LONG lowerBits; /* Least sig. 32 bits of new offset */
  39296. DWORD dwRet; /* Value returned by SetFilePointer() */
  39297. DWORD lastErrno; /* Value returned by GetLastError() */
  39298. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  39299. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  39300. lowerBits = (LONG)(iOffset & 0xffffffff);
  39301. /* API oddity: If successful, SetFilePointer() returns a dword
  39302. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  39303. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  39304. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  39305. ** whether an error has actually occurred, it is also necessary to call
  39306. ** GetLastError().
  39307. */
  39308. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  39309. if( (dwRet==INVALID_SET_FILE_POINTER
  39310. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  39311. pFile->lastErrno = lastErrno;
  39312. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  39313. "winSeekFile", pFile->zPath);
  39314. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  39315. return 1;
  39316. }
  39317. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  39318. return 0;
  39319. #else
  39320. /*
  39321. ** Same as above, except that this implementation works for WinRT.
  39322. */
  39323. LARGE_INTEGER x; /* The new offset */
  39324. BOOL bRet; /* Value returned by SetFilePointerEx() */
  39325. x.QuadPart = iOffset;
  39326. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  39327. if(!bRet){
  39328. pFile->lastErrno = osGetLastError();
  39329. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  39330. "winSeekFile", pFile->zPath);
  39331. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  39332. return 1;
  39333. }
  39334. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  39335. return 0;
  39336. #endif
  39337. }
  39338. #if SQLITE_MAX_MMAP_SIZE>0
  39339. /* Forward references to VFS helper methods used for memory mapped files */
  39340. static int winMapfile(winFile*, sqlite3_int64);
  39341. static int winUnmapfile(winFile*);
  39342. #endif
  39343. /*
  39344. ** Close a file.
  39345. **
  39346. ** It is reported that an attempt to close a handle might sometimes
  39347. ** fail. This is a very unreasonable result, but Windows is notorious
  39348. ** for being unreasonable so I do not doubt that it might happen. If
  39349. ** the close fails, we pause for 100 milliseconds and try again. As
  39350. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  39351. ** giving up and returning an error.
  39352. */
  39353. #define MX_CLOSE_ATTEMPT 3
  39354. static int winClose(sqlite3_file *id){
  39355. int rc, cnt = 0;
  39356. winFile *pFile = (winFile*)id;
  39357. assert( id!=0 );
  39358. #ifndef SQLITE_OMIT_WAL
  39359. assert( pFile->pShm==0 );
  39360. #endif
  39361. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  39362. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  39363. osGetCurrentProcessId(), pFile, pFile->h));
  39364. #if SQLITE_MAX_MMAP_SIZE>0
  39365. winUnmapfile(pFile);
  39366. #endif
  39367. do{
  39368. rc = osCloseHandle(pFile->h);
  39369. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  39370. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  39371. #if SQLITE_OS_WINCE
  39372. #define WINCE_DELETION_ATTEMPTS 3
  39373. {
  39374. winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
  39375. if( pAppData==NULL || !pAppData->bNoLock ){
  39376. winceDestroyLock(pFile);
  39377. }
  39378. }
  39379. if( pFile->zDeleteOnClose ){
  39380. int cnt = 0;
  39381. while(
  39382. osDeleteFileW(pFile->zDeleteOnClose)==0
  39383. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  39384. && cnt++ < WINCE_DELETION_ATTEMPTS
  39385. ){
  39386. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  39387. }
  39388. sqlite3_free(pFile->zDeleteOnClose);
  39389. }
  39390. #endif
  39391. if( rc ){
  39392. pFile->h = NULL;
  39393. }
  39394. OpenCounter(-1);
  39395. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  39396. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  39397. return rc ? SQLITE_OK
  39398. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  39399. "winClose", pFile->zPath);
  39400. }
  39401. /*
  39402. ** Read data from a file into a buffer. Return SQLITE_OK if all
  39403. ** bytes were read successfully and SQLITE_IOERR if anything goes
  39404. ** wrong.
  39405. */
  39406. static int winRead(
  39407. sqlite3_file *id, /* File to read from */
  39408. void *pBuf, /* Write content into this buffer */
  39409. int amt, /* Number of bytes to read */
  39410. sqlite3_int64 offset /* Begin reading at this offset */
  39411. ){
  39412. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  39413. OVERLAPPED overlapped; /* The offset for ReadFile. */
  39414. #endif
  39415. winFile *pFile = (winFile*)id; /* file handle */
  39416. DWORD nRead; /* Number of bytes actually read from file */
  39417. int nRetry = 0; /* Number of retrys */
  39418. assert( id!=0 );
  39419. assert( amt>0 );
  39420. assert( offset>=0 );
  39421. SimulateIOError(return SQLITE_IOERR_READ);
  39422. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  39423. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  39424. pFile->h, pBuf, amt, offset, pFile->locktype));
  39425. #if SQLITE_MAX_MMAP_SIZE>0
  39426. /* Deal with as much of this read request as possible by transfering
  39427. ** data from the memory mapping using memcpy(). */
  39428. if( offset<pFile->mmapSize ){
  39429. if( offset+amt <= pFile->mmapSize ){
  39430. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  39431. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  39432. osGetCurrentProcessId(), pFile, pFile->h));
  39433. return SQLITE_OK;
  39434. }else{
  39435. int nCopy = (int)(pFile->mmapSize - offset);
  39436. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  39437. pBuf = &((u8 *)pBuf)[nCopy];
  39438. amt -= nCopy;
  39439. offset += nCopy;
  39440. }
  39441. }
  39442. #endif
  39443. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  39444. if( winSeekFile(pFile, offset) ){
  39445. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  39446. osGetCurrentProcessId(), pFile, pFile->h));
  39447. return SQLITE_FULL;
  39448. }
  39449. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  39450. #else
  39451. memset(&overlapped, 0, sizeof(OVERLAPPED));
  39452. overlapped.Offset = (LONG)(offset & 0xffffffff);
  39453. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  39454. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  39455. osGetLastError()!=ERROR_HANDLE_EOF ){
  39456. #endif
  39457. DWORD lastErrno;
  39458. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  39459. pFile->lastErrno = lastErrno;
  39460. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  39461. osGetCurrentProcessId(), pFile, pFile->h));
  39462. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  39463. "winRead", pFile->zPath);
  39464. }
  39465. winLogIoerr(nRetry, __LINE__);
  39466. if( nRead<(DWORD)amt ){
  39467. /* Unread parts of the buffer must be zero-filled */
  39468. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  39469. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  39470. osGetCurrentProcessId(), pFile, pFile->h));
  39471. return SQLITE_IOERR_SHORT_READ;
  39472. }
  39473. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  39474. osGetCurrentProcessId(), pFile, pFile->h));
  39475. return SQLITE_OK;
  39476. }
  39477. /*
  39478. ** Write data from a buffer into a file. Return SQLITE_OK on success
  39479. ** or some other error code on failure.
  39480. */
  39481. static int winWrite(
  39482. sqlite3_file *id, /* File to write into */
  39483. const void *pBuf, /* The bytes to be written */
  39484. int amt, /* Number of bytes to write */
  39485. sqlite3_int64 offset /* Offset into the file to begin writing at */
  39486. ){
  39487. int rc = 0; /* True if error has occurred, else false */
  39488. winFile *pFile = (winFile*)id; /* File handle */
  39489. int nRetry = 0; /* Number of retries */
  39490. assert( amt>0 );
  39491. assert( pFile );
  39492. SimulateIOError(return SQLITE_IOERR_WRITE);
  39493. SimulateDiskfullError(return SQLITE_FULL);
  39494. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  39495. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  39496. pFile->h, pBuf, amt, offset, pFile->locktype));
  39497. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  39498. /* Deal with as much of this write request as possible by transfering
  39499. ** data from the memory mapping using memcpy(). */
  39500. if( offset<pFile->mmapSize ){
  39501. if( offset+amt <= pFile->mmapSize ){
  39502. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  39503. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  39504. osGetCurrentProcessId(), pFile, pFile->h));
  39505. return SQLITE_OK;
  39506. }else{
  39507. int nCopy = (int)(pFile->mmapSize - offset);
  39508. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  39509. pBuf = &((u8 *)pBuf)[nCopy];
  39510. amt -= nCopy;
  39511. offset += nCopy;
  39512. }
  39513. }
  39514. #endif
  39515. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  39516. rc = winSeekFile(pFile, offset);
  39517. if( rc==0 ){
  39518. #else
  39519. {
  39520. #endif
  39521. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  39522. OVERLAPPED overlapped; /* The offset for WriteFile. */
  39523. #endif
  39524. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  39525. int nRem = amt; /* Number of bytes yet to be written */
  39526. DWORD nWrite; /* Bytes written by each WriteFile() call */
  39527. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  39528. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  39529. memset(&overlapped, 0, sizeof(OVERLAPPED));
  39530. overlapped.Offset = (LONG)(offset & 0xffffffff);
  39531. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  39532. #endif
  39533. while( nRem>0 ){
  39534. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  39535. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  39536. #else
  39537. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  39538. #endif
  39539. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  39540. break;
  39541. }
  39542. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  39543. if( nWrite==0 || nWrite>(DWORD)nRem ){
  39544. lastErrno = osGetLastError();
  39545. break;
  39546. }
  39547. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  39548. offset += nWrite;
  39549. overlapped.Offset = (LONG)(offset & 0xffffffff);
  39550. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  39551. #endif
  39552. aRem += nWrite;
  39553. nRem -= nWrite;
  39554. }
  39555. if( nRem>0 ){
  39556. pFile->lastErrno = lastErrno;
  39557. rc = 1;
  39558. }
  39559. }
  39560. if( rc ){
  39561. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  39562. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  39563. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  39564. osGetCurrentProcessId(), pFile, pFile->h));
  39565. return winLogError(SQLITE_FULL, pFile->lastErrno,
  39566. "winWrite1", pFile->zPath);
  39567. }
  39568. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  39569. osGetCurrentProcessId(), pFile, pFile->h));
  39570. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  39571. "winWrite2", pFile->zPath);
  39572. }else{
  39573. winLogIoerr(nRetry, __LINE__);
  39574. }
  39575. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  39576. osGetCurrentProcessId(), pFile, pFile->h));
  39577. return SQLITE_OK;
  39578. }
  39579. /*
  39580. ** Truncate an open file to a specified size
  39581. */
  39582. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  39583. winFile *pFile = (winFile*)id; /* File handle object */
  39584. int rc = SQLITE_OK; /* Return code for this function */
  39585. DWORD lastErrno;
  39586. assert( pFile );
  39587. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  39588. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  39589. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  39590. /* If the user has configured a chunk-size for this file, truncate the
  39591. ** file so that it consists of an integer number of chunks (i.e. the
  39592. ** actual file size after the operation may be larger than the requested
  39593. ** size).
  39594. */
  39595. if( pFile->szChunk>0 ){
  39596. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  39597. }
  39598. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  39599. if( winSeekFile(pFile, nByte) ){
  39600. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  39601. "winTruncate1", pFile->zPath);
  39602. }else if( 0==osSetEndOfFile(pFile->h) &&
  39603. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  39604. pFile->lastErrno = lastErrno;
  39605. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  39606. "winTruncate2", pFile->zPath);
  39607. }
  39608. #if SQLITE_MAX_MMAP_SIZE>0
  39609. /* If the file was truncated to a size smaller than the currently
  39610. ** mapped region, reduce the effective mapping size as well. SQLite will
  39611. ** use read() and write() to access data beyond this point from now on.
  39612. */
  39613. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  39614. pFile->mmapSize = nByte;
  39615. }
  39616. #endif
  39617. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  39618. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  39619. return rc;
  39620. }
  39621. #ifdef SQLITE_TEST
  39622. /*
  39623. ** Count the number of fullsyncs and normal syncs. This is used to test
  39624. ** that syncs and fullsyncs are occuring at the right times.
  39625. */
  39626. SQLITE_API int sqlite3_sync_count = 0;
  39627. SQLITE_API int sqlite3_fullsync_count = 0;
  39628. #endif
  39629. /*
  39630. ** Make sure all writes to a particular file are committed to disk.
  39631. */
  39632. static int winSync(sqlite3_file *id, int flags){
  39633. #ifndef SQLITE_NO_SYNC
  39634. /*
  39635. ** Used only when SQLITE_NO_SYNC is not defined.
  39636. */
  39637. BOOL rc;
  39638. #endif
  39639. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  39640. defined(SQLITE_HAVE_OS_TRACE)
  39641. /*
  39642. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  39643. ** OSTRACE() macros.
  39644. */
  39645. winFile *pFile = (winFile*)id;
  39646. #else
  39647. UNUSED_PARAMETER(id);
  39648. #endif
  39649. assert( pFile );
  39650. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  39651. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  39652. || (flags&0x0F)==SQLITE_SYNC_FULL
  39653. );
  39654. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  39655. ** line is to test that doing so does not cause any problems.
  39656. */
  39657. SimulateDiskfullError( return SQLITE_FULL );
  39658. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  39659. osGetCurrentProcessId(), pFile, pFile->h, flags,
  39660. pFile->locktype));
  39661. #ifndef SQLITE_TEST
  39662. UNUSED_PARAMETER(flags);
  39663. #else
  39664. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  39665. sqlite3_fullsync_count++;
  39666. }
  39667. sqlite3_sync_count++;
  39668. #endif
  39669. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  39670. ** no-op
  39671. */
  39672. #ifdef SQLITE_NO_SYNC
  39673. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  39674. osGetCurrentProcessId(), pFile, pFile->h));
  39675. return SQLITE_OK;
  39676. #else
  39677. #if SQLITE_MAX_MMAP_SIZE>0
  39678. if( pFile->pMapRegion ){
  39679. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  39680. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  39681. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  39682. pFile, pFile->pMapRegion));
  39683. }else{
  39684. pFile->lastErrno = osGetLastError();
  39685. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  39686. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  39687. pFile, pFile->pMapRegion));
  39688. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  39689. "winSync1", pFile->zPath);
  39690. }
  39691. }
  39692. #endif
  39693. rc = osFlushFileBuffers(pFile->h);
  39694. SimulateIOError( rc=FALSE );
  39695. if( rc ){
  39696. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  39697. osGetCurrentProcessId(), pFile, pFile->h));
  39698. return SQLITE_OK;
  39699. }else{
  39700. pFile->lastErrno = osGetLastError();
  39701. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  39702. osGetCurrentProcessId(), pFile, pFile->h));
  39703. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  39704. "winSync2", pFile->zPath);
  39705. }
  39706. #endif
  39707. }
  39708. /*
  39709. ** Determine the current size of a file in bytes
  39710. */
  39711. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  39712. winFile *pFile = (winFile*)id;
  39713. int rc = SQLITE_OK;
  39714. assert( id!=0 );
  39715. assert( pSize!=0 );
  39716. SimulateIOError(return SQLITE_IOERR_FSTAT);
  39717. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  39718. #if SQLITE_OS_WINRT
  39719. {
  39720. FILE_STANDARD_INFO info;
  39721. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  39722. &info, sizeof(info)) ){
  39723. *pSize = info.EndOfFile.QuadPart;
  39724. }else{
  39725. pFile->lastErrno = osGetLastError();
  39726. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  39727. "winFileSize", pFile->zPath);
  39728. }
  39729. }
  39730. #else
  39731. {
  39732. DWORD upperBits;
  39733. DWORD lowerBits;
  39734. DWORD lastErrno;
  39735. lowerBits = osGetFileSize(pFile->h, &upperBits);
  39736. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  39737. if( (lowerBits == INVALID_FILE_SIZE)
  39738. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  39739. pFile->lastErrno = lastErrno;
  39740. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  39741. "winFileSize", pFile->zPath);
  39742. }
  39743. }
  39744. #endif
  39745. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  39746. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  39747. return rc;
  39748. }
  39749. /*
  39750. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  39751. */
  39752. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  39753. # define LOCKFILE_FAIL_IMMEDIATELY 1
  39754. #endif
  39755. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  39756. # define LOCKFILE_EXCLUSIVE_LOCK 2
  39757. #endif
  39758. /*
  39759. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  39760. ** When the LockFile function was used, it was always expected to fail
  39761. ** immediately if the lock could not be obtained. Also, it always expected to
  39762. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  39763. ** and reflect those expectations; therefore, they should not be changed.
  39764. */
  39765. #ifndef SQLITE_LOCKFILE_FLAGS
  39766. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  39767. LOCKFILE_EXCLUSIVE_LOCK)
  39768. #endif
  39769. /*
  39770. ** Currently, SQLite never calls the LockFileEx function without wanting the
  39771. ** call to fail immediately if the lock cannot be obtained.
  39772. */
  39773. #ifndef SQLITE_LOCKFILEEX_FLAGS
  39774. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  39775. #endif
  39776. /*
  39777. ** Acquire a reader lock.
  39778. ** Different API routines are called depending on whether or not this
  39779. ** is Win9x or WinNT.
  39780. */
  39781. static int winGetReadLock(winFile *pFile){
  39782. int res;
  39783. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  39784. if( osIsNT() ){
  39785. #if SQLITE_OS_WINCE
  39786. /*
  39787. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  39788. ** API LockFileEx.
  39789. */
  39790. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  39791. #else
  39792. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  39793. SHARED_SIZE, 0);
  39794. #endif
  39795. }
  39796. #ifdef SQLITE_WIN32_HAS_ANSI
  39797. else{
  39798. int lk;
  39799. sqlite3_randomness(sizeof(lk), &lk);
  39800. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  39801. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  39802. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  39803. }
  39804. #endif
  39805. if( res == 0 ){
  39806. pFile->lastErrno = osGetLastError();
  39807. /* No need to log a failure to lock */
  39808. }
  39809. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  39810. return res;
  39811. }
  39812. /*
  39813. ** Undo a readlock
  39814. */
  39815. static int winUnlockReadLock(winFile *pFile){
  39816. int res;
  39817. DWORD lastErrno;
  39818. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  39819. if( osIsNT() ){
  39820. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  39821. }
  39822. #ifdef SQLITE_WIN32_HAS_ANSI
  39823. else{
  39824. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  39825. }
  39826. #endif
  39827. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  39828. pFile->lastErrno = lastErrno;
  39829. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  39830. "winUnlockReadLock", pFile->zPath);
  39831. }
  39832. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  39833. return res;
  39834. }
  39835. /*
  39836. ** Lock the file with the lock specified by parameter locktype - one
  39837. ** of the following:
  39838. **
  39839. ** (1) SHARED_LOCK
  39840. ** (2) RESERVED_LOCK
  39841. ** (3) PENDING_LOCK
  39842. ** (4) EXCLUSIVE_LOCK
  39843. **
  39844. ** Sometimes when requesting one lock state, additional lock states
  39845. ** are inserted in between. The locking might fail on one of the later
  39846. ** transitions leaving the lock state different from what it started but
  39847. ** still short of its goal. The following chart shows the allowed
  39848. ** transitions and the inserted intermediate states:
  39849. **
  39850. ** UNLOCKED -> SHARED
  39851. ** SHARED -> RESERVED
  39852. ** SHARED -> (PENDING) -> EXCLUSIVE
  39853. ** RESERVED -> (PENDING) -> EXCLUSIVE
  39854. ** PENDING -> EXCLUSIVE
  39855. **
  39856. ** This routine will only increase a lock. The winUnlock() routine
  39857. ** erases all locks at once and returns us immediately to locking level 0.
  39858. ** It is not possible to lower the locking level one step at a time. You
  39859. ** must go straight to locking level 0.
  39860. */
  39861. static int winLock(sqlite3_file *id, int locktype){
  39862. int rc = SQLITE_OK; /* Return code from subroutines */
  39863. int res = 1; /* Result of a Windows lock call */
  39864. int newLocktype; /* Set pFile->locktype to this value before exiting */
  39865. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  39866. winFile *pFile = (winFile*)id;
  39867. DWORD lastErrno = NO_ERROR;
  39868. assert( id!=0 );
  39869. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  39870. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  39871. /* If there is already a lock of this type or more restrictive on the
  39872. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  39873. ** sqlite3OsEnterMutex() hasn't been called yet.
  39874. */
  39875. if( pFile->locktype>=locktype ){
  39876. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  39877. return SQLITE_OK;
  39878. }
  39879. /* Do not allow any kind of write-lock on a read-only database
  39880. */
  39881. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  39882. return SQLITE_IOERR_LOCK;
  39883. }
  39884. /* Make sure the locking sequence is correct
  39885. */
  39886. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  39887. assert( locktype!=PENDING_LOCK );
  39888. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  39889. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  39890. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  39891. ** the PENDING_LOCK byte is temporary.
  39892. */
  39893. newLocktype = pFile->locktype;
  39894. if( pFile->locktype==NO_LOCK
  39895. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
  39896. ){
  39897. int cnt = 3;
  39898. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  39899. PENDING_BYTE, 0, 1, 0))==0 ){
  39900. /* Try 3 times to get the pending lock. This is needed to work
  39901. ** around problems caused by indexing and/or anti-virus software on
  39902. ** Windows systems.
  39903. ** If you are using this code as a model for alternative VFSes, do not
  39904. ** copy this retry logic. It is a hack intended for Windows only.
  39905. */
  39906. lastErrno = osGetLastError();
  39907. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  39908. pFile->h, cnt, res));
  39909. if( lastErrno==ERROR_INVALID_HANDLE ){
  39910. pFile->lastErrno = lastErrno;
  39911. rc = SQLITE_IOERR_LOCK;
  39912. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  39913. pFile->h, cnt, sqlite3ErrName(rc)));
  39914. return rc;
  39915. }
  39916. if( cnt ) sqlite3_win32_sleep(1);
  39917. }
  39918. gotPendingLock = res;
  39919. if( !res ){
  39920. lastErrno = osGetLastError();
  39921. }
  39922. }
  39923. /* Acquire a shared lock
  39924. */
  39925. if( locktype==SHARED_LOCK && res ){
  39926. assert( pFile->locktype==NO_LOCK );
  39927. res = winGetReadLock(pFile);
  39928. if( res ){
  39929. newLocktype = SHARED_LOCK;
  39930. }else{
  39931. lastErrno = osGetLastError();
  39932. }
  39933. }
  39934. /* Acquire a RESERVED lock
  39935. */
  39936. if( locktype==RESERVED_LOCK && res ){
  39937. assert( pFile->locktype==SHARED_LOCK );
  39938. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  39939. if( res ){
  39940. newLocktype = RESERVED_LOCK;
  39941. }else{
  39942. lastErrno = osGetLastError();
  39943. }
  39944. }
  39945. /* Acquire a PENDING lock
  39946. */
  39947. if( locktype==EXCLUSIVE_LOCK && res ){
  39948. newLocktype = PENDING_LOCK;
  39949. gotPendingLock = 0;
  39950. }
  39951. /* Acquire an EXCLUSIVE lock
  39952. */
  39953. if( locktype==EXCLUSIVE_LOCK && res ){
  39954. assert( pFile->locktype>=SHARED_LOCK );
  39955. res = winUnlockReadLock(pFile);
  39956. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  39957. SHARED_SIZE, 0);
  39958. if( res ){
  39959. newLocktype = EXCLUSIVE_LOCK;
  39960. }else{
  39961. lastErrno = osGetLastError();
  39962. winGetReadLock(pFile);
  39963. }
  39964. }
  39965. /* If we are holding a PENDING lock that ought to be released, then
  39966. ** release it now.
  39967. */
  39968. if( gotPendingLock && locktype==SHARED_LOCK ){
  39969. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  39970. }
  39971. /* Update the state of the lock has held in the file descriptor then
  39972. ** return the appropriate result code.
  39973. */
  39974. if( res ){
  39975. rc = SQLITE_OK;
  39976. }else{
  39977. pFile->lastErrno = lastErrno;
  39978. rc = SQLITE_BUSY;
  39979. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  39980. pFile->h, locktype, newLocktype));
  39981. }
  39982. pFile->locktype = (u8)newLocktype;
  39983. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  39984. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  39985. return rc;
  39986. }
  39987. /*
  39988. ** This routine checks if there is a RESERVED lock held on the specified
  39989. ** file by this or any other process. If such a lock is held, return
  39990. ** non-zero, otherwise zero.
  39991. */
  39992. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  39993. int res;
  39994. winFile *pFile = (winFile*)id;
  39995. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  39996. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  39997. assert( id!=0 );
  39998. if( pFile->locktype>=RESERVED_LOCK ){
  39999. res = 1;
  40000. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  40001. }else{
  40002. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  40003. if( res ){
  40004. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  40005. }
  40006. res = !res;
  40007. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  40008. }
  40009. *pResOut = res;
  40010. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  40011. pFile->h, pResOut, *pResOut));
  40012. return SQLITE_OK;
  40013. }
  40014. /*
  40015. ** Lower the locking level on file descriptor id to locktype. locktype
  40016. ** must be either NO_LOCK or SHARED_LOCK.
  40017. **
  40018. ** If the locking level of the file descriptor is already at or below
  40019. ** the requested locking level, this routine is a no-op.
  40020. **
  40021. ** It is not possible for this routine to fail if the second argument
  40022. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  40023. ** might return SQLITE_IOERR;
  40024. */
  40025. static int winUnlock(sqlite3_file *id, int locktype){
  40026. int type;
  40027. winFile *pFile = (winFile*)id;
  40028. int rc = SQLITE_OK;
  40029. assert( pFile!=0 );
  40030. assert( locktype<=SHARED_LOCK );
  40031. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  40032. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  40033. type = pFile->locktype;
  40034. if( type>=EXCLUSIVE_LOCK ){
  40035. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  40036. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  40037. /* This should never happen. We should always be able to
  40038. ** reacquire the read lock */
  40039. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  40040. "winUnlock", pFile->zPath);
  40041. }
  40042. }
  40043. if( type>=RESERVED_LOCK ){
  40044. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  40045. }
  40046. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  40047. winUnlockReadLock(pFile);
  40048. }
  40049. if( type>=PENDING_LOCK ){
  40050. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  40051. }
  40052. pFile->locktype = (u8)locktype;
  40053. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  40054. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  40055. return rc;
  40056. }
  40057. /******************************************************************************
  40058. ****************************** No-op Locking **********************************
  40059. **
  40060. ** Of the various locking implementations available, this is by far the
  40061. ** simplest: locking is ignored. No attempt is made to lock the database
  40062. ** file for reading or writing.
  40063. **
  40064. ** This locking mode is appropriate for use on read-only databases
  40065. ** (ex: databases that are burned into CD-ROM, for example.) It can
  40066. ** also be used if the application employs some external mechanism to
  40067. ** prevent simultaneous access of the same database by two or more
  40068. ** database connections. But there is a serious risk of database
  40069. ** corruption if this locking mode is used in situations where multiple
  40070. ** database connections are accessing the same database file at the same
  40071. ** time and one or more of those connections are writing.
  40072. */
  40073. static int winNolockLock(sqlite3_file *id, int locktype){
  40074. UNUSED_PARAMETER(id);
  40075. UNUSED_PARAMETER(locktype);
  40076. return SQLITE_OK;
  40077. }
  40078. static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
  40079. UNUSED_PARAMETER(id);
  40080. UNUSED_PARAMETER(pResOut);
  40081. return SQLITE_OK;
  40082. }
  40083. static int winNolockUnlock(sqlite3_file *id, int locktype){
  40084. UNUSED_PARAMETER(id);
  40085. UNUSED_PARAMETER(locktype);
  40086. return SQLITE_OK;
  40087. }
  40088. /******************* End of the no-op lock implementation *********************
  40089. ******************************************************************************/
  40090. /*
  40091. ** If *pArg is initially negative then this is a query. Set *pArg to
  40092. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  40093. **
  40094. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  40095. */
  40096. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  40097. if( *pArg<0 ){
  40098. *pArg = (pFile->ctrlFlags & mask)!=0;
  40099. }else if( (*pArg)==0 ){
  40100. pFile->ctrlFlags &= ~mask;
  40101. }else{
  40102. pFile->ctrlFlags |= mask;
  40103. }
  40104. }
  40105. /* Forward references to VFS helper methods used for temporary files */
  40106. static int winGetTempname(sqlite3_vfs *, char **);
  40107. static int winIsDir(const void *);
  40108. static BOOL winIsDriveLetterAndColon(const char *);
  40109. /*
  40110. ** Control and query of the open file handle.
  40111. */
  40112. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  40113. winFile *pFile = (winFile*)id;
  40114. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  40115. switch( op ){
  40116. case SQLITE_FCNTL_LOCKSTATE: {
  40117. *(int*)pArg = pFile->locktype;
  40118. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40119. return SQLITE_OK;
  40120. }
  40121. case SQLITE_FCNTL_LAST_ERRNO: {
  40122. *(int*)pArg = (int)pFile->lastErrno;
  40123. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40124. return SQLITE_OK;
  40125. }
  40126. case SQLITE_FCNTL_CHUNK_SIZE: {
  40127. pFile->szChunk = *(int *)pArg;
  40128. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40129. return SQLITE_OK;
  40130. }
  40131. case SQLITE_FCNTL_SIZE_HINT: {
  40132. if( pFile->szChunk>0 ){
  40133. sqlite3_int64 oldSz;
  40134. int rc = winFileSize(id, &oldSz);
  40135. if( rc==SQLITE_OK ){
  40136. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  40137. if( newSz>oldSz ){
  40138. SimulateIOErrorBenign(1);
  40139. rc = winTruncate(id, newSz);
  40140. SimulateIOErrorBenign(0);
  40141. }
  40142. }
  40143. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  40144. return rc;
  40145. }
  40146. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40147. return SQLITE_OK;
  40148. }
  40149. case SQLITE_FCNTL_PERSIST_WAL: {
  40150. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  40151. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40152. return SQLITE_OK;
  40153. }
  40154. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  40155. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  40156. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40157. return SQLITE_OK;
  40158. }
  40159. case SQLITE_FCNTL_VFSNAME: {
  40160. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  40161. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40162. return SQLITE_OK;
  40163. }
  40164. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  40165. int *a = (int*)pArg;
  40166. if( a[0]>0 ){
  40167. winIoerrRetry = a[0];
  40168. }else{
  40169. a[0] = winIoerrRetry;
  40170. }
  40171. if( a[1]>0 ){
  40172. winIoerrRetryDelay = a[1];
  40173. }else{
  40174. a[1] = winIoerrRetryDelay;
  40175. }
  40176. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40177. return SQLITE_OK;
  40178. }
  40179. case SQLITE_FCNTL_WIN32_GET_HANDLE: {
  40180. LPHANDLE phFile = (LPHANDLE)pArg;
  40181. *phFile = pFile->h;
  40182. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  40183. return SQLITE_OK;
  40184. }
  40185. #ifdef SQLITE_TEST
  40186. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  40187. LPHANDLE phFile = (LPHANDLE)pArg;
  40188. HANDLE hOldFile = pFile->h;
  40189. pFile->h = *phFile;
  40190. *phFile = hOldFile;
  40191. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  40192. hOldFile, pFile->h));
  40193. return SQLITE_OK;
  40194. }
  40195. #endif
  40196. case SQLITE_FCNTL_TEMPFILENAME: {
  40197. char *zTFile = 0;
  40198. int rc = winGetTempname(pFile->pVfs, &zTFile);
  40199. if( rc==SQLITE_OK ){
  40200. *(char**)pArg = zTFile;
  40201. }
  40202. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  40203. return rc;
  40204. }
  40205. #if SQLITE_MAX_MMAP_SIZE>0
  40206. case SQLITE_FCNTL_MMAP_SIZE: {
  40207. i64 newLimit = *(i64*)pArg;
  40208. int rc = SQLITE_OK;
  40209. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  40210. newLimit = sqlite3GlobalConfig.mxMmap;
  40211. }
  40212. /* The value of newLimit may be eventually cast to (SIZE_T) and passed
  40213. ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
  40214. ** least a 64-bit type. */
  40215. if( newLimit>0 && sizeof(SIZE_T)<8 ){
  40216. newLimit = (newLimit & 0x7FFFFFFF);
  40217. }
  40218. *(i64*)pArg = pFile->mmapSizeMax;
  40219. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  40220. pFile->mmapSizeMax = newLimit;
  40221. if( pFile->mmapSize>0 ){
  40222. winUnmapfile(pFile);
  40223. rc = winMapfile(pFile, -1);
  40224. }
  40225. }
  40226. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  40227. return rc;
  40228. }
  40229. #endif
  40230. }
  40231. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  40232. return SQLITE_NOTFOUND;
  40233. }
  40234. /*
  40235. ** Return the sector size in bytes of the underlying block device for
  40236. ** the specified file. This is almost always 512 bytes, but may be
  40237. ** larger for some devices.
  40238. **
  40239. ** SQLite code assumes this function cannot fail. It also assumes that
  40240. ** if two files are created in the same file-system directory (i.e.
  40241. ** a database and its journal file) that the sector size will be the
  40242. ** same for both.
  40243. */
  40244. static int winSectorSize(sqlite3_file *id){
  40245. (void)id;
  40246. return SQLITE_DEFAULT_SECTOR_SIZE;
  40247. }
  40248. /*
  40249. ** Return a vector of device characteristics.
  40250. */
  40251. static int winDeviceCharacteristics(sqlite3_file *id){
  40252. winFile *p = (winFile*)id;
  40253. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  40254. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  40255. }
  40256. /*
  40257. ** Windows will only let you create file view mappings
  40258. ** on allocation size granularity boundaries.
  40259. ** During sqlite3_os_init() we do a GetSystemInfo()
  40260. ** to get the granularity size.
  40261. */
  40262. static SYSTEM_INFO winSysInfo;
  40263. #ifndef SQLITE_OMIT_WAL
  40264. /*
  40265. ** Helper functions to obtain and relinquish the global mutex. The
  40266. ** global mutex is used to protect the winLockInfo objects used by
  40267. ** this file, all of which may be shared by multiple threads.
  40268. **
  40269. ** Function winShmMutexHeld() is used to assert() that the global mutex
  40270. ** is held when required. This function is only used as part of assert()
  40271. ** statements. e.g.
  40272. **
  40273. ** winShmEnterMutex()
  40274. ** assert( winShmMutexHeld() );
  40275. ** winShmLeaveMutex()
  40276. */
  40277. static sqlite3_mutex *winBigLock = 0;
  40278. static void winShmEnterMutex(void){
  40279. sqlite3_mutex_enter(winBigLock);
  40280. }
  40281. static void winShmLeaveMutex(void){
  40282. sqlite3_mutex_leave(winBigLock);
  40283. }
  40284. #ifndef NDEBUG
  40285. static int winShmMutexHeld(void) {
  40286. return sqlite3_mutex_held(winBigLock);
  40287. }
  40288. #endif
  40289. /*
  40290. ** Object used to represent a single file opened and mmapped to provide
  40291. ** shared memory. When multiple threads all reference the same
  40292. ** log-summary, each thread has its own winFile object, but they all
  40293. ** point to a single instance of this object. In other words, each
  40294. ** log-summary is opened only once per process.
  40295. **
  40296. ** winShmMutexHeld() must be true when creating or destroying
  40297. ** this object or while reading or writing the following fields:
  40298. **
  40299. ** nRef
  40300. ** pNext
  40301. **
  40302. ** The following fields are read-only after the object is created:
  40303. **
  40304. ** fid
  40305. ** zFilename
  40306. **
  40307. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  40308. ** winShmMutexHeld() is true when reading or writing any other field
  40309. ** in this structure.
  40310. **
  40311. */
  40312. struct winShmNode {
  40313. sqlite3_mutex *mutex; /* Mutex to access this object */
  40314. char *zFilename; /* Name of the file */
  40315. winFile hFile; /* File handle from winOpen */
  40316. int szRegion; /* Size of shared-memory regions */
  40317. int nRegion; /* Size of array apRegion */
  40318. u8 isReadonly; /* True if read-only */
  40319. u8 isUnlocked; /* True if no DMS lock held */
  40320. struct ShmRegion {
  40321. HANDLE hMap; /* File handle from CreateFileMapping */
  40322. void *pMap;
  40323. } *aRegion;
  40324. DWORD lastErrno; /* The Windows errno from the last I/O error */
  40325. int nRef; /* Number of winShm objects pointing to this */
  40326. winShm *pFirst; /* All winShm objects pointing to this */
  40327. winShmNode *pNext; /* Next in list of all winShmNode objects */
  40328. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  40329. u8 nextShmId; /* Next available winShm.id value */
  40330. #endif
  40331. };
  40332. /*
  40333. ** A global array of all winShmNode objects.
  40334. **
  40335. ** The winShmMutexHeld() must be true while reading or writing this list.
  40336. */
  40337. static winShmNode *winShmNodeList = 0;
  40338. /*
  40339. ** Structure used internally by this VFS to record the state of an
  40340. ** open shared memory connection.
  40341. **
  40342. ** The following fields are initialized when this object is created and
  40343. ** are read-only thereafter:
  40344. **
  40345. ** winShm.pShmNode
  40346. ** winShm.id
  40347. **
  40348. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  40349. ** while accessing any read/write fields.
  40350. */
  40351. struct winShm {
  40352. winShmNode *pShmNode; /* The underlying winShmNode object */
  40353. winShm *pNext; /* Next winShm with the same winShmNode */
  40354. u8 hasMutex; /* True if holding the winShmNode mutex */
  40355. u16 sharedMask; /* Mask of shared locks held */
  40356. u16 exclMask; /* Mask of exclusive locks held */
  40357. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  40358. u8 id; /* Id of this connection with its winShmNode */
  40359. #endif
  40360. };
  40361. /*
  40362. ** Constants used for locking
  40363. */
  40364. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  40365. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  40366. /*
  40367. ** Apply advisory locks for all n bytes beginning at ofst.
  40368. */
  40369. #define WINSHM_UNLCK 1
  40370. #define WINSHM_RDLCK 2
  40371. #define WINSHM_WRLCK 3
  40372. static int winShmSystemLock(
  40373. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  40374. int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
  40375. int ofst, /* Offset to first byte to be locked/unlocked */
  40376. int nByte /* Number of bytes to lock or unlock */
  40377. ){
  40378. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  40379. /* Access to the winShmNode object is serialized by the caller */
  40380. assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
  40381. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  40382. pFile->hFile.h, lockType, ofst, nByte));
  40383. /* Release/Acquire the system-level lock */
  40384. if( lockType==WINSHM_UNLCK ){
  40385. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  40386. }else{
  40387. /* Initialize the locking parameters */
  40388. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  40389. if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  40390. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  40391. }
  40392. if( rc!= 0 ){
  40393. rc = SQLITE_OK;
  40394. }else{
  40395. pFile->lastErrno = osGetLastError();
  40396. rc = SQLITE_BUSY;
  40397. }
  40398. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  40399. pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
  40400. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  40401. return rc;
  40402. }
  40403. /* Forward references to VFS methods */
  40404. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  40405. static int winDelete(sqlite3_vfs *,const char*,int);
  40406. /*
  40407. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  40408. **
  40409. ** This is not a VFS shared-memory method; it is a utility function called
  40410. ** by VFS shared-memory methods.
  40411. */
  40412. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  40413. winShmNode **pp;
  40414. winShmNode *p;
  40415. assert( winShmMutexHeld() );
  40416. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  40417. osGetCurrentProcessId(), deleteFlag));
  40418. pp = &winShmNodeList;
  40419. while( (p = *pp)!=0 ){
  40420. if( p->nRef==0 ){
  40421. int i;
  40422. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  40423. for(i=0; i<p->nRegion; i++){
  40424. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  40425. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  40426. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  40427. UNUSED_VARIABLE_VALUE(bRc);
  40428. bRc = osCloseHandle(p->aRegion[i].hMap);
  40429. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  40430. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  40431. UNUSED_VARIABLE_VALUE(bRc);
  40432. }
  40433. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  40434. SimulateIOErrorBenign(1);
  40435. winClose((sqlite3_file *)&p->hFile);
  40436. SimulateIOErrorBenign(0);
  40437. }
  40438. if( deleteFlag ){
  40439. SimulateIOErrorBenign(1);
  40440. sqlite3BeginBenignMalloc();
  40441. winDelete(pVfs, p->zFilename, 0);
  40442. sqlite3EndBenignMalloc();
  40443. SimulateIOErrorBenign(0);
  40444. }
  40445. *pp = p->pNext;
  40446. sqlite3_free(p->aRegion);
  40447. sqlite3_free(p);
  40448. }else{
  40449. pp = &p->pNext;
  40450. }
  40451. }
  40452. }
  40453. /*
  40454. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  40455. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  40456. ** code otherwise.
  40457. **
  40458. ** If the DMS cannot be locked because this is a readonly_shm=1
  40459. ** connection and no other process already holds a lock, return
  40460. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  40461. */
  40462. static int winLockSharedMemory(winShmNode *pShmNode){
  40463. int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
  40464. if( rc==SQLITE_OK ){
  40465. if( pShmNode->isReadonly ){
  40466. pShmNode->isUnlocked = 1;
  40467. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  40468. return SQLITE_READONLY_CANTINIT;
  40469. }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
  40470. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  40471. return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  40472. "winLockSharedMemory", pShmNode->zFilename);
  40473. }
  40474. }
  40475. if( rc==SQLITE_OK ){
  40476. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  40477. }
  40478. return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
  40479. }
  40480. /*
  40481. ** Open the shared-memory area associated with database file pDbFd.
  40482. **
  40483. ** When opening a new shared-memory file, if no other instances of that
  40484. ** file are currently open, in this process or in other processes, then
  40485. ** the file must be truncated to zero length or have its header cleared.
  40486. */
  40487. static int winOpenSharedMemory(winFile *pDbFd){
  40488. struct winShm *p; /* The connection to be opened */
  40489. winShmNode *pShmNode = 0; /* The underlying mmapped file */
  40490. int rc = SQLITE_OK; /* Result code */
  40491. winShmNode *pNew; /* Newly allocated winShmNode */
  40492. int nName; /* Size of zName in bytes */
  40493. assert( pDbFd->pShm==0 ); /* Not previously opened */
  40494. /* Allocate space for the new sqlite3_shm object. Also speculatively
  40495. ** allocate space for a new winShmNode and filename.
  40496. */
  40497. p = sqlite3MallocZero( sizeof(*p) );
  40498. if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  40499. nName = sqlite3Strlen30(pDbFd->zPath);
  40500. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  40501. if( pNew==0 ){
  40502. sqlite3_free(p);
  40503. return SQLITE_IOERR_NOMEM_BKPT;
  40504. }
  40505. pNew->zFilename = (char*)&pNew[1];
  40506. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  40507. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  40508. /* Look to see if there is an existing winShmNode that can be used.
  40509. ** If no matching winShmNode currently exists, create a new one.
  40510. */
  40511. winShmEnterMutex();
  40512. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  40513. /* TBD need to come up with better match here. Perhaps
  40514. ** use FILE_ID_BOTH_DIR_INFO Structure.
  40515. */
  40516. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  40517. }
  40518. if( pShmNode ){
  40519. sqlite3_free(pNew);
  40520. }else{
  40521. int inFlags = SQLITE_OPEN_WAL;
  40522. int outFlags = 0;
  40523. pShmNode = pNew;
  40524. pNew = 0;
  40525. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  40526. pShmNode->pNext = winShmNodeList;
  40527. winShmNodeList = pShmNode;
  40528. if( sqlite3GlobalConfig.bCoreMutex ){
  40529. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  40530. if( pShmNode->mutex==0 ){
  40531. rc = SQLITE_IOERR_NOMEM_BKPT;
  40532. goto shm_open_err;
  40533. }
  40534. }
  40535. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  40536. inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  40537. }else{
  40538. inFlags |= SQLITE_OPEN_READONLY;
  40539. }
  40540. rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
  40541. (sqlite3_file*)&pShmNode->hFile,
  40542. inFlags, &outFlags);
  40543. if( rc!=SQLITE_OK ){
  40544. rc = winLogError(rc, osGetLastError(), "winOpenShm",
  40545. pShmNode->zFilename);
  40546. goto shm_open_err;
  40547. }
  40548. if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
  40549. rc = winLockSharedMemory(pShmNode);
  40550. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  40551. }
  40552. /* Make the new connection a child of the winShmNode */
  40553. p->pShmNode = pShmNode;
  40554. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  40555. p->id = pShmNode->nextShmId++;
  40556. #endif
  40557. pShmNode->nRef++;
  40558. pDbFd->pShm = p;
  40559. winShmLeaveMutex();
  40560. /* The reference count on pShmNode has already been incremented under
  40561. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  40562. ** new (struct winShm) object to the pShmNode has been set. All that is
  40563. ** left to do is to link the new object into the linked list starting
  40564. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  40565. ** mutex.
  40566. */
  40567. sqlite3_mutex_enter(pShmNode->mutex);
  40568. p->pNext = pShmNode->pFirst;
  40569. pShmNode->pFirst = p;
  40570. sqlite3_mutex_leave(pShmNode->mutex);
  40571. return rc;
  40572. /* Jump here on any error */
  40573. shm_open_err:
  40574. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  40575. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  40576. sqlite3_free(p);
  40577. sqlite3_free(pNew);
  40578. winShmLeaveMutex();
  40579. return rc;
  40580. }
  40581. /*
  40582. ** Close a connection to shared-memory. Delete the underlying
  40583. ** storage if deleteFlag is true.
  40584. */
  40585. static int winShmUnmap(
  40586. sqlite3_file *fd, /* Database holding shared memory */
  40587. int deleteFlag /* Delete after closing if true */
  40588. ){
  40589. winFile *pDbFd; /* Database holding shared-memory */
  40590. winShm *p; /* The connection to be closed */
  40591. winShmNode *pShmNode; /* The underlying shared-memory file */
  40592. winShm **pp; /* For looping over sibling connections */
  40593. pDbFd = (winFile*)fd;
  40594. p = pDbFd->pShm;
  40595. if( p==0 ) return SQLITE_OK;
  40596. pShmNode = p->pShmNode;
  40597. /* Remove connection p from the set of connections associated
  40598. ** with pShmNode */
  40599. sqlite3_mutex_enter(pShmNode->mutex);
  40600. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  40601. *pp = p->pNext;
  40602. /* Free the connection p */
  40603. sqlite3_free(p);
  40604. pDbFd->pShm = 0;
  40605. sqlite3_mutex_leave(pShmNode->mutex);
  40606. /* If pShmNode->nRef has reached 0, then close the underlying
  40607. ** shared-memory file, too */
  40608. winShmEnterMutex();
  40609. assert( pShmNode->nRef>0 );
  40610. pShmNode->nRef--;
  40611. if( pShmNode->nRef==0 ){
  40612. winShmPurge(pDbFd->pVfs, deleteFlag);
  40613. }
  40614. winShmLeaveMutex();
  40615. return SQLITE_OK;
  40616. }
  40617. /*
  40618. ** Change the lock state for a shared-memory segment.
  40619. */
  40620. static int winShmLock(
  40621. sqlite3_file *fd, /* Database file holding the shared memory */
  40622. int ofst, /* First lock to acquire or release */
  40623. int n, /* Number of locks to acquire or release */
  40624. int flags /* What to do with the lock */
  40625. ){
  40626. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  40627. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  40628. winShm *pX; /* For looping over all siblings */
  40629. winShmNode *pShmNode = p->pShmNode;
  40630. int rc = SQLITE_OK; /* Result code */
  40631. u16 mask; /* Mask of locks to take or release */
  40632. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  40633. assert( n>=1 );
  40634. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  40635. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  40636. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  40637. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  40638. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  40639. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  40640. assert( n>1 || mask==(1<<ofst) );
  40641. sqlite3_mutex_enter(pShmNode->mutex);
  40642. if( flags & SQLITE_SHM_UNLOCK ){
  40643. u16 allMask = 0; /* Mask of locks held by siblings */
  40644. /* See if any siblings hold this same lock */
  40645. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  40646. if( pX==p ) continue;
  40647. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  40648. allMask |= pX->sharedMask;
  40649. }
  40650. /* Unlock the system-level locks */
  40651. if( (mask & allMask)==0 ){
  40652. rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
  40653. }else{
  40654. rc = SQLITE_OK;
  40655. }
  40656. /* Undo the local locks */
  40657. if( rc==SQLITE_OK ){
  40658. p->exclMask &= ~mask;
  40659. p->sharedMask &= ~mask;
  40660. }
  40661. }else if( flags & SQLITE_SHM_SHARED ){
  40662. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  40663. /* Find out which shared locks are already held by sibling connections.
  40664. ** If any sibling already holds an exclusive lock, go ahead and return
  40665. ** SQLITE_BUSY.
  40666. */
  40667. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  40668. if( (pX->exclMask & mask)!=0 ){
  40669. rc = SQLITE_BUSY;
  40670. break;
  40671. }
  40672. allShared |= pX->sharedMask;
  40673. }
  40674. /* Get shared locks at the system level, if necessary */
  40675. if( rc==SQLITE_OK ){
  40676. if( (allShared & mask)==0 ){
  40677. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
  40678. }else{
  40679. rc = SQLITE_OK;
  40680. }
  40681. }
  40682. /* Get the local shared locks */
  40683. if( rc==SQLITE_OK ){
  40684. p->sharedMask |= mask;
  40685. }
  40686. }else{
  40687. /* Make sure no sibling connections hold locks that will block this
  40688. ** lock. If any do, return SQLITE_BUSY right away.
  40689. */
  40690. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  40691. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  40692. rc = SQLITE_BUSY;
  40693. break;
  40694. }
  40695. }
  40696. /* Get the exclusive locks at the system level. Then if successful
  40697. ** also mark the local connection as being locked.
  40698. */
  40699. if( rc==SQLITE_OK ){
  40700. rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
  40701. if( rc==SQLITE_OK ){
  40702. assert( (p->sharedMask & mask)==0 );
  40703. p->exclMask |= mask;
  40704. }
  40705. }
  40706. }
  40707. sqlite3_mutex_leave(pShmNode->mutex);
  40708. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  40709. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  40710. sqlite3ErrName(rc)));
  40711. return rc;
  40712. }
  40713. /*
  40714. ** Implement a memory barrier or memory fence on shared memory.
  40715. **
  40716. ** All loads and stores begun before the barrier must complete before
  40717. ** any load or store begun after the barrier.
  40718. */
  40719. static void winShmBarrier(
  40720. sqlite3_file *fd /* Database holding the shared memory */
  40721. ){
  40722. UNUSED_PARAMETER(fd);
  40723. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  40724. winShmEnterMutex(); /* Also mutex, for redundancy */
  40725. winShmLeaveMutex();
  40726. }
  40727. /*
  40728. ** This function is called to obtain a pointer to region iRegion of the
  40729. ** shared-memory associated with the database file fd. Shared-memory regions
  40730. ** are numbered starting from zero. Each shared-memory region is szRegion
  40731. ** bytes in size.
  40732. **
  40733. ** If an error occurs, an error code is returned and *pp is set to NULL.
  40734. **
  40735. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  40736. ** region has not been allocated (by any client, including one running in a
  40737. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  40738. ** isWrite is non-zero and the requested shared-memory region has not yet
  40739. ** been allocated, it is allocated by this function.
  40740. **
  40741. ** If the shared-memory region has already been allocated or is allocated by
  40742. ** this call as described above, then it is mapped into this processes
  40743. ** address space (if it is not already), *pp is set to point to the mapped
  40744. ** memory and SQLITE_OK returned.
  40745. */
  40746. static int winShmMap(
  40747. sqlite3_file *fd, /* Handle open on database file */
  40748. int iRegion, /* Region to retrieve */
  40749. int szRegion, /* Size of regions */
  40750. int isWrite, /* True to extend file if necessary */
  40751. void volatile **pp /* OUT: Mapped memory */
  40752. ){
  40753. winFile *pDbFd = (winFile*)fd;
  40754. winShm *pShm = pDbFd->pShm;
  40755. winShmNode *pShmNode;
  40756. DWORD protect = PAGE_READWRITE;
  40757. DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
  40758. int rc = SQLITE_OK;
  40759. if( !pShm ){
  40760. rc = winOpenSharedMemory(pDbFd);
  40761. if( rc!=SQLITE_OK ) return rc;
  40762. pShm = pDbFd->pShm;
  40763. }
  40764. pShmNode = pShm->pShmNode;
  40765. sqlite3_mutex_enter(pShmNode->mutex);
  40766. if( pShmNode->isUnlocked ){
  40767. rc = winLockSharedMemory(pShmNode);
  40768. if( rc!=SQLITE_OK ) goto shmpage_out;
  40769. pShmNode->isUnlocked = 0;
  40770. }
  40771. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  40772. if( pShmNode->nRegion<=iRegion ){
  40773. struct ShmRegion *apNew; /* New aRegion[] array */
  40774. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  40775. sqlite3_int64 sz; /* Current size of wal-index file */
  40776. pShmNode->szRegion = szRegion;
  40777. /* The requested region is not mapped into this processes address space.
  40778. ** Check to see if it has been allocated (i.e. if the wal-index file is
  40779. ** large enough to contain the requested region).
  40780. */
  40781. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  40782. if( rc!=SQLITE_OK ){
  40783. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  40784. "winShmMap1", pDbFd->zPath);
  40785. goto shmpage_out;
  40786. }
  40787. if( sz<nByte ){
  40788. /* The requested memory region does not exist. If isWrite is set to
  40789. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  40790. **
  40791. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  40792. ** the requested memory region.
  40793. */
  40794. if( !isWrite ) goto shmpage_out;
  40795. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  40796. if( rc!=SQLITE_OK ){
  40797. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  40798. "winShmMap2", pDbFd->zPath);
  40799. goto shmpage_out;
  40800. }
  40801. }
  40802. /* Map the requested memory region into this processes address space. */
  40803. apNew = (struct ShmRegion *)sqlite3_realloc64(
  40804. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  40805. );
  40806. if( !apNew ){
  40807. rc = SQLITE_IOERR_NOMEM_BKPT;
  40808. goto shmpage_out;
  40809. }
  40810. pShmNode->aRegion = apNew;
  40811. if( pShmNode->isReadonly ){
  40812. protect = PAGE_READONLY;
  40813. flags = FILE_MAP_READ;
  40814. }
  40815. while( pShmNode->nRegion<=iRegion ){
  40816. HANDLE hMap = NULL; /* file-mapping handle */
  40817. void *pMap = 0; /* Mapped memory region */
  40818. #if SQLITE_OS_WINRT
  40819. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  40820. NULL, protect, nByte, NULL
  40821. );
  40822. #elif defined(SQLITE_WIN32_HAS_WIDE)
  40823. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  40824. NULL, protect, 0, nByte, NULL
  40825. );
  40826. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  40827. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  40828. NULL, protect, 0, nByte, NULL
  40829. );
  40830. #endif
  40831. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  40832. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  40833. hMap ? "ok" : "failed"));
  40834. if( hMap ){
  40835. int iOffset = pShmNode->nRegion*szRegion;
  40836. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  40837. #if SQLITE_OS_WINRT
  40838. pMap = osMapViewOfFileFromApp(hMap, flags,
  40839. iOffset - iOffsetShift, szRegion + iOffsetShift
  40840. );
  40841. #else
  40842. pMap = osMapViewOfFile(hMap, flags,
  40843. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  40844. );
  40845. #endif
  40846. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  40847. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  40848. szRegion, pMap ? "ok" : "failed"));
  40849. }
  40850. if( !pMap ){
  40851. pShmNode->lastErrno = osGetLastError();
  40852. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  40853. "winShmMap3", pDbFd->zPath);
  40854. if( hMap ) osCloseHandle(hMap);
  40855. goto shmpage_out;
  40856. }
  40857. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  40858. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  40859. pShmNode->nRegion++;
  40860. }
  40861. }
  40862. shmpage_out:
  40863. if( pShmNode->nRegion>iRegion ){
  40864. int iOffset = iRegion*szRegion;
  40865. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  40866. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  40867. *pp = (void *)&p[iOffsetShift];
  40868. }else{
  40869. *pp = 0;
  40870. }
  40871. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  40872. sqlite3_mutex_leave(pShmNode->mutex);
  40873. return rc;
  40874. }
  40875. #else
  40876. # define winShmMap 0
  40877. # define winShmLock 0
  40878. # define winShmBarrier 0
  40879. # define winShmUnmap 0
  40880. #endif /* #ifndef SQLITE_OMIT_WAL */
  40881. /*
  40882. ** Cleans up the mapped region of the specified file, if any.
  40883. */
  40884. #if SQLITE_MAX_MMAP_SIZE>0
  40885. static int winUnmapfile(winFile *pFile){
  40886. assert( pFile!=0 );
  40887. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  40888. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  40889. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  40890. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  40891. if( pFile->pMapRegion ){
  40892. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  40893. pFile->lastErrno = osGetLastError();
  40894. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  40895. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  40896. pFile->pMapRegion));
  40897. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  40898. "winUnmapfile1", pFile->zPath);
  40899. }
  40900. pFile->pMapRegion = 0;
  40901. pFile->mmapSize = 0;
  40902. pFile->mmapSizeActual = 0;
  40903. }
  40904. if( pFile->hMap!=NULL ){
  40905. if( !osCloseHandle(pFile->hMap) ){
  40906. pFile->lastErrno = osGetLastError();
  40907. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  40908. osGetCurrentProcessId(), pFile, pFile->hMap));
  40909. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  40910. "winUnmapfile2", pFile->zPath);
  40911. }
  40912. pFile->hMap = NULL;
  40913. }
  40914. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  40915. osGetCurrentProcessId(), pFile));
  40916. return SQLITE_OK;
  40917. }
  40918. /*
  40919. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  40920. ** is already mapped, the existing mapping is replaced by the new). Or, if
  40921. ** there already exists a mapping for this file, and there are still
  40922. ** outstanding xFetch() references to it, this function is a no-op.
  40923. **
  40924. ** If parameter nByte is non-negative, then it is the requested size of
  40925. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  40926. ** requested size is the size of the file on disk. The actual size of the
  40927. ** created mapping is either the requested size or the value configured
  40928. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  40929. **
  40930. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  40931. ** recreated as a result of outstanding references) or an SQLite error
  40932. ** code otherwise.
  40933. */
  40934. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  40935. sqlite3_int64 nMap = nByte;
  40936. int rc;
  40937. assert( nMap>=0 || pFd->nFetchOut==0 );
  40938. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  40939. osGetCurrentProcessId(), pFd, nByte));
  40940. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  40941. if( nMap<0 ){
  40942. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  40943. if( rc ){
  40944. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  40945. osGetCurrentProcessId(), pFd));
  40946. return SQLITE_IOERR_FSTAT;
  40947. }
  40948. }
  40949. if( nMap>pFd->mmapSizeMax ){
  40950. nMap = pFd->mmapSizeMax;
  40951. }
  40952. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  40953. if( nMap==0 && pFd->mmapSize>0 ){
  40954. winUnmapfile(pFd);
  40955. }
  40956. if( nMap!=pFd->mmapSize ){
  40957. void *pNew = 0;
  40958. DWORD protect = PAGE_READONLY;
  40959. DWORD flags = FILE_MAP_READ;
  40960. winUnmapfile(pFd);
  40961. #ifdef SQLITE_MMAP_READWRITE
  40962. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  40963. protect = PAGE_READWRITE;
  40964. flags |= FILE_MAP_WRITE;
  40965. }
  40966. #endif
  40967. #if SQLITE_OS_WINRT
  40968. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  40969. #elif defined(SQLITE_WIN32_HAS_WIDE)
  40970. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  40971. (DWORD)((nMap>>32) & 0xffffffff),
  40972. (DWORD)(nMap & 0xffffffff), NULL);
  40973. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  40974. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  40975. (DWORD)((nMap>>32) & 0xffffffff),
  40976. (DWORD)(nMap & 0xffffffff), NULL);
  40977. #endif
  40978. if( pFd->hMap==NULL ){
  40979. pFd->lastErrno = osGetLastError();
  40980. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  40981. "winMapfile1", pFd->zPath);
  40982. /* Log the error, but continue normal operation using xRead/xWrite */
  40983. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  40984. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  40985. return SQLITE_OK;
  40986. }
  40987. assert( (nMap % winSysInfo.dwPageSize)==0 );
  40988. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  40989. #if SQLITE_OS_WINRT
  40990. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  40991. #else
  40992. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  40993. #endif
  40994. if( pNew==NULL ){
  40995. osCloseHandle(pFd->hMap);
  40996. pFd->hMap = NULL;
  40997. pFd->lastErrno = osGetLastError();
  40998. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  40999. "winMapfile2", pFd->zPath);
  41000. /* Log the error, but continue normal operation using xRead/xWrite */
  41001. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  41002. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  41003. return SQLITE_OK;
  41004. }
  41005. pFd->pMapRegion = pNew;
  41006. pFd->mmapSize = nMap;
  41007. pFd->mmapSizeActual = nMap;
  41008. }
  41009. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  41010. osGetCurrentProcessId(), pFd));
  41011. return SQLITE_OK;
  41012. }
  41013. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  41014. /*
  41015. ** If possible, return a pointer to a mapping of file fd starting at offset
  41016. ** iOff. The mapping must be valid for at least nAmt bytes.
  41017. **
  41018. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  41019. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  41020. ** Finally, if an error does occur, return an SQLite error code. The final
  41021. ** value of *pp is undefined in this case.
  41022. **
  41023. ** If this function does return a pointer, the caller must eventually
  41024. ** release the reference by calling winUnfetch().
  41025. */
  41026. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  41027. #if SQLITE_MAX_MMAP_SIZE>0
  41028. winFile *pFd = (winFile*)fd; /* The underlying database file */
  41029. #endif
  41030. *pp = 0;
  41031. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  41032. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  41033. #if SQLITE_MAX_MMAP_SIZE>0
  41034. if( pFd->mmapSizeMax>0 ){
  41035. if( pFd->pMapRegion==0 ){
  41036. int rc = winMapfile(pFd, -1);
  41037. if( rc!=SQLITE_OK ){
  41038. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  41039. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  41040. return rc;
  41041. }
  41042. }
  41043. if( pFd->mmapSize >= iOff+nAmt ){
  41044. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  41045. pFd->nFetchOut++;
  41046. }
  41047. }
  41048. #endif
  41049. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  41050. osGetCurrentProcessId(), fd, pp, *pp));
  41051. return SQLITE_OK;
  41052. }
  41053. /*
  41054. ** If the third argument is non-NULL, then this function releases a
  41055. ** reference obtained by an earlier call to winFetch(). The second
  41056. ** argument passed to this function must be the same as the corresponding
  41057. ** argument that was passed to the winFetch() invocation.
  41058. **
  41059. ** Or, if the third argument is NULL, then this function is being called
  41060. ** to inform the VFS layer that, according to POSIX, any existing mapping
  41061. ** may now be invalid and should be unmapped.
  41062. */
  41063. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  41064. #if SQLITE_MAX_MMAP_SIZE>0
  41065. winFile *pFd = (winFile*)fd; /* The underlying database file */
  41066. /* If p==0 (unmap the entire file) then there must be no outstanding
  41067. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  41068. ** then there must be at least one outstanding. */
  41069. assert( (p==0)==(pFd->nFetchOut==0) );
  41070. /* If p!=0, it must match the iOff value. */
  41071. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  41072. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  41073. osGetCurrentProcessId(), pFd, iOff, p));
  41074. if( p ){
  41075. pFd->nFetchOut--;
  41076. }else{
  41077. /* FIXME: If Windows truly always prevents truncating or deleting a
  41078. ** file while a mapping is held, then the following winUnmapfile() call
  41079. ** is unnecessary can be omitted - potentially improving
  41080. ** performance. */
  41081. winUnmapfile(pFd);
  41082. }
  41083. assert( pFd->nFetchOut>=0 );
  41084. #endif
  41085. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  41086. osGetCurrentProcessId(), fd));
  41087. return SQLITE_OK;
  41088. }
  41089. /*
  41090. ** Here ends the implementation of all sqlite3_file methods.
  41091. **
  41092. ********************** End sqlite3_file Methods *******************************
  41093. ******************************************************************************/
  41094. /*
  41095. ** This vector defines all the methods that can operate on an
  41096. ** sqlite3_file for win32.
  41097. */
  41098. static const sqlite3_io_methods winIoMethod = {
  41099. 3, /* iVersion */
  41100. winClose, /* xClose */
  41101. winRead, /* xRead */
  41102. winWrite, /* xWrite */
  41103. winTruncate, /* xTruncate */
  41104. winSync, /* xSync */
  41105. winFileSize, /* xFileSize */
  41106. winLock, /* xLock */
  41107. winUnlock, /* xUnlock */
  41108. winCheckReservedLock, /* xCheckReservedLock */
  41109. winFileControl, /* xFileControl */
  41110. winSectorSize, /* xSectorSize */
  41111. winDeviceCharacteristics, /* xDeviceCharacteristics */
  41112. winShmMap, /* xShmMap */
  41113. winShmLock, /* xShmLock */
  41114. winShmBarrier, /* xShmBarrier */
  41115. winShmUnmap, /* xShmUnmap */
  41116. winFetch, /* xFetch */
  41117. winUnfetch /* xUnfetch */
  41118. };
  41119. /*
  41120. ** This vector defines all the methods that can operate on an
  41121. ** sqlite3_file for win32 without performing any locking.
  41122. */
  41123. static const sqlite3_io_methods winIoNolockMethod = {
  41124. 3, /* iVersion */
  41125. winClose, /* xClose */
  41126. winRead, /* xRead */
  41127. winWrite, /* xWrite */
  41128. winTruncate, /* xTruncate */
  41129. winSync, /* xSync */
  41130. winFileSize, /* xFileSize */
  41131. winNolockLock, /* xLock */
  41132. winNolockUnlock, /* xUnlock */
  41133. winNolockCheckReservedLock, /* xCheckReservedLock */
  41134. winFileControl, /* xFileControl */
  41135. winSectorSize, /* xSectorSize */
  41136. winDeviceCharacteristics, /* xDeviceCharacteristics */
  41137. winShmMap, /* xShmMap */
  41138. winShmLock, /* xShmLock */
  41139. winShmBarrier, /* xShmBarrier */
  41140. winShmUnmap, /* xShmUnmap */
  41141. winFetch, /* xFetch */
  41142. winUnfetch /* xUnfetch */
  41143. };
  41144. static winVfsAppData winAppData = {
  41145. &winIoMethod, /* pMethod */
  41146. 0, /* pAppData */
  41147. 0 /* bNoLock */
  41148. };
  41149. static winVfsAppData winNolockAppData = {
  41150. &winIoNolockMethod, /* pMethod */
  41151. 0, /* pAppData */
  41152. 1 /* bNoLock */
  41153. };
  41154. /****************************************************************************
  41155. **************************** sqlite3_vfs methods ****************************
  41156. **
  41157. ** This division contains the implementation of methods on the
  41158. ** sqlite3_vfs object.
  41159. */
  41160. #if defined(__CYGWIN__)
  41161. /*
  41162. ** Convert a filename from whatever the underlying operating system
  41163. ** supports for filenames into UTF-8. Space to hold the result is
  41164. ** obtained from malloc and must be freed by the calling function.
  41165. */
  41166. static char *winConvertToUtf8Filename(const void *zFilename){
  41167. char *zConverted = 0;
  41168. if( osIsNT() ){
  41169. zConverted = winUnicodeToUtf8(zFilename);
  41170. }
  41171. #ifdef SQLITE_WIN32_HAS_ANSI
  41172. else{
  41173. zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
  41174. }
  41175. #endif
  41176. /* caller will handle out of memory */
  41177. return zConverted;
  41178. }
  41179. #endif
  41180. /*
  41181. ** Convert a UTF-8 filename into whatever form the underlying
  41182. ** operating system wants filenames in. Space to hold the result
  41183. ** is obtained from malloc and must be freed by the calling
  41184. ** function.
  41185. */
  41186. static void *winConvertFromUtf8Filename(const char *zFilename){
  41187. void *zConverted = 0;
  41188. if( osIsNT() ){
  41189. zConverted = winUtf8ToUnicode(zFilename);
  41190. }
  41191. #ifdef SQLITE_WIN32_HAS_ANSI
  41192. else{
  41193. zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  41194. }
  41195. #endif
  41196. /* caller will handle out of memory */
  41197. return zConverted;
  41198. }
  41199. /*
  41200. ** This function returns non-zero if the specified UTF-8 string buffer
  41201. ** ends with a directory separator character or one was successfully
  41202. ** added to it.
  41203. */
  41204. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  41205. if( zBuf ){
  41206. int nLen = sqlite3Strlen30(zBuf);
  41207. if( nLen>0 ){
  41208. if( winIsDirSep(zBuf[nLen-1]) ){
  41209. return 1;
  41210. }else if( nLen+1<nBuf ){
  41211. zBuf[nLen] = winGetDirSep();
  41212. zBuf[nLen+1] = '\0';
  41213. return 1;
  41214. }
  41215. }
  41216. }
  41217. return 0;
  41218. }
  41219. /*
  41220. ** Create a temporary file name and store the resulting pointer into pzBuf.
  41221. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  41222. */
  41223. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  41224. static char zChars[] =
  41225. "abcdefghijklmnopqrstuvwxyz"
  41226. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  41227. "0123456789";
  41228. size_t i, j;
  41229. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  41230. int nMax, nBuf, nDir, nLen;
  41231. char *zBuf;
  41232. /* It's odd to simulate an io-error here, but really this is just
  41233. ** using the io-error infrastructure to test that SQLite handles this
  41234. ** function failing.
  41235. */
  41236. SimulateIOError( return SQLITE_IOERR );
  41237. /* Allocate a temporary buffer to store the fully qualified file
  41238. ** name for the temporary file. If this fails, we cannot continue.
  41239. */
  41240. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  41241. zBuf = sqlite3MallocZero( nBuf );
  41242. if( !zBuf ){
  41243. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41244. return SQLITE_IOERR_NOMEM_BKPT;
  41245. }
  41246. /* Figure out the effective temporary directory. First, check if one
  41247. ** has been explicitly set by the application; otherwise, use the one
  41248. ** configured by the operating system.
  41249. */
  41250. nDir = nMax - (nPre + 15);
  41251. assert( nDir>0 );
  41252. if( sqlite3_temp_directory ){
  41253. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  41254. if( nDirLen>0 ){
  41255. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  41256. nDirLen++;
  41257. }
  41258. if( nDirLen>nDir ){
  41259. sqlite3_free(zBuf);
  41260. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  41261. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  41262. }
  41263. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  41264. }
  41265. }
  41266. #if defined(__CYGWIN__)
  41267. else{
  41268. static const char *azDirs[] = {
  41269. 0, /* getenv("SQLITE_TMPDIR") */
  41270. 0, /* getenv("TMPDIR") */
  41271. 0, /* getenv("TMP") */
  41272. 0, /* getenv("TEMP") */
  41273. 0, /* getenv("USERPROFILE") */
  41274. "/var/tmp",
  41275. "/usr/tmp",
  41276. "/tmp",
  41277. ".",
  41278. 0 /* List terminator */
  41279. };
  41280. unsigned int i;
  41281. const char *zDir = 0;
  41282. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  41283. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  41284. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  41285. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  41286. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  41287. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  41288. void *zConverted;
  41289. if( zDir==0 ) continue;
  41290. /* If the path starts with a drive letter followed by the colon
  41291. ** character, assume it is already a native Win32 path; otherwise,
  41292. ** it must be converted to a native Win32 path via the Cygwin API
  41293. ** prior to using it.
  41294. */
  41295. if( winIsDriveLetterAndColon(zDir) ){
  41296. zConverted = winConvertFromUtf8Filename(zDir);
  41297. if( !zConverted ){
  41298. sqlite3_free(zBuf);
  41299. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41300. return SQLITE_IOERR_NOMEM_BKPT;
  41301. }
  41302. if( winIsDir(zConverted) ){
  41303. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  41304. sqlite3_free(zConverted);
  41305. break;
  41306. }
  41307. sqlite3_free(zConverted);
  41308. }else{
  41309. zConverted = sqlite3MallocZero( nMax+1 );
  41310. if( !zConverted ){
  41311. sqlite3_free(zBuf);
  41312. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41313. return SQLITE_IOERR_NOMEM_BKPT;
  41314. }
  41315. if( cygwin_conv_path(
  41316. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  41317. zConverted, nMax+1)<0 ){
  41318. sqlite3_free(zConverted);
  41319. sqlite3_free(zBuf);
  41320. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  41321. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  41322. "winGetTempname2", zDir);
  41323. }
  41324. if( winIsDir(zConverted) ){
  41325. /* At this point, we know the candidate directory exists and should
  41326. ** be used. However, we may need to convert the string containing
  41327. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  41328. */
  41329. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  41330. if( !zUtf8 ){
  41331. sqlite3_free(zConverted);
  41332. sqlite3_free(zBuf);
  41333. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41334. return SQLITE_IOERR_NOMEM_BKPT;
  41335. }
  41336. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  41337. sqlite3_free(zUtf8);
  41338. sqlite3_free(zConverted);
  41339. break;
  41340. }
  41341. sqlite3_free(zConverted);
  41342. }
  41343. }
  41344. }
  41345. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  41346. else if( osIsNT() ){
  41347. char *zMulti;
  41348. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  41349. if( !zWidePath ){
  41350. sqlite3_free(zBuf);
  41351. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41352. return SQLITE_IOERR_NOMEM_BKPT;
  41353. }
  41354. if( osGetTempPathW(nMax, zWidePath)==0 ){
  41355. sqlite3_free(zWidePath);
  41356. sqlite3_free(zBuf);
  41357. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  41358. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  41359. "winGetTempname2", 0);
  41360. }
  41361. zMulti = winUnicodeToUtf8(zWidePath);
  41362. if( zMulti ){
  41363. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  41364. sqlite3_free(zMulti);
  41365. sqlite3_free(zWidePath);
  41366. }else{
  41367. sqlite3_free(zWidePath);
  41368. sqlite3_free(zBuf);
  41369. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41370. return SQLITE_IOERR_NOMEM_BKPT;
  41371. }
  41372. }
  41373. #ifdef SQLITE_WIN32_HAS_ANSI
  41374. else{
  41375. char *zUtf8;
  41376. char *zMbcsPath = sqlite3MallocZero( nMax );
  41377. if( !zMbcsPath ){
  41378. sqlite3_free(zBuf);
  41379. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41380. return SQLITE_IOERR_NOMEM_BKPT;
  41381. }
  41382. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  41383. sqlite3_free(zBuf);
  41384. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  41385. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  41386. "winGetTempname3", 0);
  41387. }
  41388. zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
  41389. if( zUtf8 ){
  41390. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  41391. sqlite3_free(zUtf8);
  41392. }else{
  41393. sqlite3_free(zBuf);
  41394. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  41395. return SQLITE_IOERR_NOMEM_BKPT;
  41396. }
  41397. }
  41398. #endif /* SQLITE_WIN32_HAS_ANSI */
  41399. #endif /* !SQLITE_OS_WINRT */
  41400. /*
  41401. ** Check to make sure the temporary directory ends with an appropriate
  41402. ** separator. If it does not and there is not enough space left to add
  41403. ** one, fail.
  41404. */
  41405. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  41406. sqlite3_free(zBuf);
  41407. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  41408. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  41409. }
  41410. /*
  41411. ** Check that the output buffer is large enough for the temporary file
  41412. ** name in the following format:
  41413. **
  41414. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  41415. **
  41416. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  41417. ** account for the space used by the 15 character random suffix and the
  41418. ** two trailing NUL characters. The final directory separator character
  41419. ** has already added if it was not already present.
  41420. */
  41421. nLen = sqlite3Strlen30(zBuf);
  41422. if( (nLen + nPre + 17) > nBuf ){
  41423. sqlite3_free(zBuf);
  41424. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  41425. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  41426. }
  41427. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  41428. j = sqlite3Strlen30(zBuf);
  41429. sqlite3_randomness(15, &zBuf[j]);
  41430. for(i=0; i<15; i++, j++){
  41431. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  41432. }
  41433. zBuf[j] = 0;
  41434. zBuf[j+1] = 0;
  41435. *pzBuf = zBuf;
  41436. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  41437. return SQLITE_OK;
  41438. }
  41439. /*
  41440. ** Return TRUE if the named file is really a directory. Return false if
  41441. ** it is something other than a directory, or if there is any kind of memory
  41442. ** allocation failure.
  41443. */
  41444. static int winIsDir(const void *zConverted){
  41445. DWORD attr;
  41446. int rc = 0;
  41447. DWORD lastErrno;
  41448. if( osIsNT() ){
  41449. int cnt = 0;
  41450. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  41451. memset(&sAttrData, 0, sizeof(sAttrData));
  41452. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  41453. GetFileExInfoStandard,
  41454. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  41455. if( !rc ){
  41456. return 0; /* Invalid name? */
  41457. }
  41458. attr = sAttrData.dwFileAttributes;
  41459. #if SQLITE_OS_WINCE==0
  41460. }else{
  41461. attr = osGetFileAttributesA((char*)zConverted);
  41462. #endif
  41463. }
  41464. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  41465. }
  41466. /* forward reference */
  41467. static int winAccess(
  41468. sqlite3_vfs *pVfs, /* Not used on win32 */
  41469. const char *zFilename, /* Name of file to check */
  41470. int flags, /* Type of test to make on this file */
  41471. int *pResOut /* OUT: Result */
  41472. );
  41473. /*
  41474. ** Open a file.
  41475. */
  41476. static int winOpen(
  41477. sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
  41478. const char *zName, /* Name of the file (UTF-8) */
  41479. sqlite3_file *id, /* Write the SQLite file handle here */
  41480. int flags, /* Open mode flags */
  41481. int *pOutFlags /* Status return flags */
  41482. ){
  41483. HANDLE h;
  41484. DWORD lastErrno = 0;
  41485. DWORD dwDesiredAccess;
  41486. DWORD dwShareMode;
  41487. DWORD dwCreationDisposition;
  41488. DWORD dwFlagsAndAttributes = 0;
  41489. #if SQLITE_OS_WINCE
  41490. int isTemp = 0;
  41491. #endif
  41492. winVfsAppData *pAppData;
  41493. winFile *pFile = (winFile*)id;
  41494. void *zConverted; /* Filename in OS encoding */
  41495. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  41496. int cnt = 0;
  41497. /* If argument zPath is a NULL pointer, this function is required to open
  41498. ** a temporary file. Use this buffer to store the file name in.
  41499. */
  41500. char *zTmpname = 0; /* For temporary filename, if necessary. */
  41501. int rc = SQLITE_OK; /* Function Return Code */
  41502. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  41503. int eType = flags&0xFFFFFF00; /* Type of file to open */
  41504. #endif
  41505. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  41506. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  41507. int isCreate = (flags & SQLITE_OPEN_CREATE);
  41508. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  41509. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  41510. #ifndef NDEBUG
  41511. int isOpenJournal = (isCreate && (
  41512. eType==SQLITE_OPEN_MASTER_JOURNAL
  41513. || eType==SQLITE_OPEN_MAIN_JOURNAL
  41514. || eType==SQLITE_OPEN_WAL
  41515. ));
  41516. #endif
  41517. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  41518. zUtf8Name, id, flags, pOutFlags));
  41519. /* Check the following statements are true:
  41520. **
  41521. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  41522. ** (b) if CREATE is set, then READWRITE must also be set, and
  41523. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  41524. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  41525. */
  41526. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  41527. assert(isCreate==0 || isReadWrite);
  41528. assert(isExclusive==0 || isCreate);
  41529. assert(isDelete==0 || isCreate);
  41530. /* The main DB, main journal, WAL file and master journal are never
  41531. ** automatically deleted. Nor are they ever temporary files. */
  41532. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  41533. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  41534. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  41535. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  41536. /* Assert that the upper layer has set one of the "file-type" flags. */
  41537. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  41538. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  41539. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  41540. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  41541. );
  41542. assert( pFile!=0 );
  41543. memset(pFile, 0, sizeof(winFile));
  41544. pFile->h = INVALID_HANDLE_VALUE;
  41545. #if SQLITE_OS_WINRT
  41546. if( !zUtf8Name && !sqlite3_temp_directory ){
  41547. sqlite3_log(SQLITE_ERROR,
  41548. "sqlite3_temp_directory variable should be set for WinRT");
  41549. }
  41550. #endif
  41551. /* If the second argument to this function is NULL, generate a
  41552. ** temporary file name to use
  41553. */
  41554. if( !zUtf8Name ){
  41555. assert( isDelete && !isOpenJournal );
  41556. rc = winGetTempname(pVfs, &zTmpname);
  41557. if( rc!=SQLITE_OK ){
  41558. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  41559. return rc;
  41560. }
  41561. zUtf8Name = zTmpname;
  41562. }
  41563. /* Database filenames are double-zero terminated if they are not
  41564. ** URIs with parameters. Hence, they can always be passed into
  41565. ** sqlite3_uri_parameter().
  41566. */
  41567. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  41568. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  41569. /* Convert the filename to the system encoding. */
  41570. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  41571. if( zConverted==0 ){
  41572. sqlite3_free(zTmpname);
  41573. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  41574. return SQLITE_IOERR_NOMEM_BKPT;
  41575. }
  41576. if( winIsDir(zConverted) ){
  41577. sqlite3_free(zConverted);
  41578. sqlite3_free(zTmpname);
  41579. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  41580. return SQLITE_CANTOPEN_ISDIR;
  41581. }
  41582. if( isReadWrite ){
  41583. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  41584. }else{
  41585. dwDesiredAccess = GENERIC_READ;
  41586. }
  41587. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  41588. ** created. SQLite doesn't use it to indicate "exclusive access"
  41589. ** as it is usually understood.
  41590. */
  41591. if( isExclusive ){
  41592. /* Creates a new file, only if it does not already exist. */
  41593. /* If the file exists, it fails. */
  41594. dwCreationDisposition = CREATE_NEW;
  41595. }else if( isCreate ){
  41596. /* Open existing file, or create if it doesn't exist */
  41597. dwCreationDisposition = OPEN_ALWAYS;
  41598. }else{
  41599. /* Opens a file, only if it exists. */
  41600. dwCreationDisposition = OPEN_EXISTING;
  41601. }
  41602. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  41603. if( isDelete ){
  41604. #if SQLITE_OS_WINCE
  41605. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  41606. isTemp = 1;
  41607. #else
  41608. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  41609. | FILE_ATTRIBUTE_HIDDEN
  41610. | FILE_FLAG_DELETE_ON_CLOSE;
  41611. #endif
  41612. }else{
  41613. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  41614. }
  41615. /* Reports from the internet are that performance is always
  41616. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  41617. #if SQLITE_OS_WINCE
  41618. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  41619. #endif
  41620. if( osIsNT() ){
  41621. #if SQLITE_OS_WINRT
  41622. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  41623. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  41624. extendedParameters.dwFileAttributes =
  41625. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  41626. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  41627. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  41628. extendedParameters.lpSecurityAttributes = NULL;
  41629. extendedParameters.hTemplateFile = NULL;
  41630. do{
  41631. h = osCreateFile2((LPCWSTR)zConverted,
  41632. dwDesiredAccess,
  41633. dwShareMode,
  41634. dwCreationDisposition,
  41635. &extendedParameters);
  41636. if( h!=INVALID_HANDLE_VALUE ) break;
  41637. if( isReadWrite ){
  41638. int rc2, isRO = 0;
  41639. sqlite3BeginBenignMalloc();
  41640. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  41641. sqlite3EndBenignMalloc();
  41642. if( rc2==SQLITE_OK && isRO ) break;
  41643. }
  41644. }while( winRetryIoerr(&cnt, &lastErrno) );
  41645. #else
  41646. do{
  41647. h = osCreateFileW((LPCWSTR)zConverted,
  41648. dwDesiredAccess,
  41649. dwShareMode, NULL,
  41650. dwCreationDisposition,
  41651. dwFlagsAndAttributes,
  41652. NULL);
  41653. if( h!=INVALID_HANDLE_VALUE ) break;
  41654. if( isReadWrite ){
  41655. int rc2, isRO = 0;
  41656. sqlite3BeginBenignMalloc();
  41657. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  41658. sqlite3EndBenignMalloc();
  41659. if( rc2==SQLITE_OK && isRO ) break;
  41660. }
  41661. }while( winRetryIoerr(&cnt, &lastErrno) );
  41662. #endif
  41663. }
  41664. #ifdef SQLITE_WIN32_HAS_ANSI
  41665. else{
  41666. do{
  41667. h = osCreateFileA((LPCSTR)zConverted,
  41668. dwDesiredAccess,
  41669. dwShareMode, NULL,
  41670. dwCreationDisposition,
  41671. dwFlagsAndAttributes,
  41672. NULL);
  41673. if( h!=INVALID_HANDLE_VALUE ) break;
  41674. if( isReadWrite ){
  41675. int rc2, isRO = 0;
  41676. sqlite3BeginBenignMalloc();
  41677. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  41678. sqlite3EndBenignMalloc();
  41679. if( rc2==SQLITE_OK && isRO ) break;
  41680. }
  41681. }while( winRetryIoerr(&cnt, &lastErrno) );
  41682. }
  41683. #endif
  41684. winLogIoerr(cnt, __LINE__);
  41685. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  41686. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  41687. if( h==INVALID_HANDLE_VALUE ){
  41688. sqlite3_free(zConverted);
  41689. sqlite3_free(zTmpname);
  41690. if( isReadWrite && !isExclusive ){
  41691. return winOpen(pVfs, zName, id,
  41692. ((flags|SQLITE_OPEN_READONLY) &
  41693. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  41694. pOutFlags);
  41695. }else{
  41696. pFile->lastErrno = lastErrno;
  41697. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  41698. return SQLITE_CANTOPEN_BKPT;
  41699. }
  41700. }
  41701. if( pOutFlags ){
  41702. if( isReadWrite ){
  41703. *pOutFlags = SQLITE_OPEN_READWRITE;
  41704. }else{
  41705. *pOutFlags = SQLITE_OPEN_READONLY;
  41706. }
  41707. }
  41708. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  41709. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  41710. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  41711. pAppData = (winVfsAppData*)pVfs->pAppData;
  41712. #if SQLITE_OS_WINCE
  41713. {
  41714. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  41715. && ((pAppData==NULL) || !pAppData->bNoLock)
  41716. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  41717. ){
  41718. osCloseHandle(h);
  41719. sqlite3_free(zConverted);
  41720. sqlite3_free(zTmpname);
  41721. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  41722. return rc;
  41723. }
  41724. }
  41725. if( isTemp ){
  41726. pFile->zDeleteOnClose = zConverted;
  41727. }else
  41728. #endif
  41729. {
  41730. sqlite3_free(zConverted);
  41731. }
  41732. sqlite3_free(zTmpname);
  41733. pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
  41734. pFile->pVfs = pVfs;
  41735. pFile->h = h;
  41736. if( isReadonly ){
  41737. pFile->ctrlFlags |= WINFILE_RDONLY;
  41738. }
  41739. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  41740. pFile->ctrlFlags |= WINFILE_PSOW;
  41741. }
  41742. pFile->lastErrno = NO_ERROR;
  41743. pFile->zPath = zName;
  41744. #if SQLITE_MAX_MMAP_SIZE>0
  41745. pFile->hMap = NULL;
  41746. pFile->pMapRegion = 0;
  41747. pFile->mmapSize = 0;
  41748. pFile->mmapSizeActual = 0;
  41749. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  41750. #endif
  41751. OpenCounter(+1);
  41752. return rc;
  41753. }
  41754. /*
  41755. ** Delete the named file.
  41756. **
  41757. ** Note that Windows does not allow a file to be deleted if some other
  41758. ** process has it open. Sometimes a virus scanner or indexing program
  41759. ** will open a journal file shortly after it is created in order to do
  41760. ** whatever it does. While this other process is holding the
  41761. ** file open, we will be unable to delete it. To work around this
  41762. ** problem, we delay 100 milliseconds and try to delete again. Up
  41763. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  41764. ** up and returning an error.
  41765. */
  41766. static int winDelete(
  41767. sqlite3_vfs *pVfs, /* Not used on win32 */
  41768. const char *zFilename, /* Name of file to delete */
  41769. int syncDir /* Not used on win32 */
  41770. ){
  41771. int cnt = 0;
  41772. int rc;
  41773. DWORD attr;
  41774. DWORD lastErrno = 0;
  41775. void *zConverted;
  41776. UNUSED_PARAMETER(pVfs);
  41777. UNUSED_PARAMETER(syncDir);
  41778. SimulateIOError(return SQLITE_IOERR_DELETE);
  41779. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  41780. zConverted = winConvertFromUtf8Filename(zFilename);
  41781. if( zConverted==0 ){
  41782. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  41783. return SQLITE_IOERR_NOMEM_BKPT;
  41784. }
  41785. if( osIsNT() ){
  41786. do {
  41787. #if SQLITE_OS_WINRT
  41788. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  41789. memset(&sAttrData, 0, sizeof(sAttrData));
  41790. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  41791. &sAttrData) ){
  41792. attr = sAttrData.dwFileAttributes;
  41793. }else{
  41794. lastErrno = osGetLastError();
  41795. if( lastErrno==ERROR_FILE_NOT_FOUND
  41796. || lastErrno==ERROR_PATH_NOT_FOUND ){
  41797. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  41798. }else{
  41799. rc = SQLITE_ERROR;
  41800. }
  41801. break;
  41802. }
  41803. #else
  41804. attr = osGetFileAttributesW(zConverted);
  41805. #endif
  41806. if ( attr==INVALID_FILE_ATTRIBUTES ){
  41807. lastErrno = osGetLastError();
  41808. if( lastErrno==ERROR_FILE_NOT_FOUND
  41809. || lastErrno==ERROR_PATH_NOT_FOUND ){
  41810. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  41811. }else{
  41812. rc = SQLITE_ERROR;
  41813. }
  41814. break;
  41815. }
  41816. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  41817. rc = SQLITE_ERROR; /* Files only. */
  41818. break;
  41819. }
  41820. if ( osDeleteFileW(zConverted) ){
  41821. rc = SQLITE_OK; /* Deleted OK. */
  41822. break;
  41823. }
  41824. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  41825. rc = SQLITE_ERROR; /* No more retries. */
  41826. break;
  41827. }
  41828. } while(1);
  41829. }
  41830. #ifdef SQLITE_WIN32_HAS_ANSI
  41831. else{
  41832. do {
  41833. attr = osGetFileAttributesA(zConverted);
  41834. if ( attr==INVALID_FILE_ATTRIBUTES ){
  41835. lastErrno = osGetLastError();
  41836. if( lastErrno==ERROR_FILE_NOT_FOUND
  41837. || lastErrno==ERROR_PATH_NOT_FOUND ){
  41838. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  41839. }else{
  41840. rc = SQLITE_ERROR;
  41841. }
  41842. break;
  41843. }
  41844. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  41845. rc = SQLITE_ERROR; /* Files only. */
  41846. break;
  41847. }
  41848. if ( osDeleteFileA(zConverted) ){
  41849. rc = SQLITE_OK; /* Deleted OK. */
  41850. break;
  41851. }
  41852. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  41853. rc = SQLITE_ERROR; /* No more retries. */
  41854. break;
  41855. }
  41856. } while(1);
  41857. }
  41858. #endif
  41859. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  41860. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  41861. }else{
  41862. winLogIoerr(cnt, __LINE__);
  41863. }
  41864. sqlite3_free(zConverted);
  41865. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  41866. return rc;
  41867. }
  41868. /*
  41869. ** Check the existence and status of a file.
  41870. */
  41871. static int winAccess(
  41872. sqlite3_vfs *pVfs, /* Not used on win32 */
  41873. const char *zFilename, /* Name of file to check */
  41874. int flags, /* Type of test to make on this file */
  41875. int *pResOut /* OUT: Result */
  41876. ){
  41877. DWORD attr;
  41878. int rc = 0;
  41879. DWORD lastErrno = 0;
  41880. void *zConverted;
  41881. UNUSED_PARAMETER(pVfs);
  41882. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  41883. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  41884. zFilename, flags, pResOut));
  41885. zConverted = winConvertFromUtf8Filename(zFilename);
  41886. if( zConverted==0 ){
  41887. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  41888. return SQLITE_IOERR_NOMEM_BKPT;
  41889. }
  41890. if( osIsNT() ){
  41891. int cnt = 0;
  41892. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  41893. memset(&sAttrData, 0, sizeof(sAttrData));
  41894. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  41895. GetFileExInfoStandard,
  41896. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  41897. if( rc ){
  41898. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  41899. ** as if it does not exist.
  41900. */
  41901. if( flags==SQLITE_ACCESS_EXISTS
  41902. && sAttrData.nFileSizeHigh==0
  41903. && sAttrData.nFileSizeLow==0 ){
  41904. attr = INVALID_FILE_ATTRIBUTES;
  41905. }else{
  41906. attr = sAttrData.dwFileAttributes;
  41907. }
  41908. }else{
  41909. winLogIoerr(cnt, __LINE__);
  41910. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  41911. sqlite3_free(zConverted);
  41912. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  41913. zFilename);
  41914. }else{
  41915. attr = INVALID_FILE_ATTRIBUTES;
  41916. }
  41917. }
  41918. }
  41919. #ifdef SQLITE_WIN32_HAS_ANSI
  41920. else{
  41921. attr = osGetFileAttributesA((char*)zConverted);
  41922. }
  41923. #endif
  41924. sqlite3_free(zConverted);
  41925. switch( flags ){
  41926. case SQLITE_ACCESS_READ:
  41927. case SQLITE_ACCESS_EXISTS:
  41928. rc = attr!=INVALID_FILE_ATTRIBUTES;
  41929. break;
  41930. case SQLITE_ACCESS_READWRITE:
  41931. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  41932. (attr & FILE_ATTRIBUTE_READONLY)==0;
  41933. break;
  41934. default:
  41935. assert(!"Invalid flags argument");
  41936. }
  41937. *pResOut = rc;
  41938. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  41939. zFilename, pResOut, *pResOut));
  41940. return SQLITE_OK;
  41941. }
  41942. /*
  41943. ** Returns non-zero if the specified path name starts with a drive letter
  41944. ** followed by a colon character.
  41945. */
  41946. static BOOL winIsDriveLetterAndColon(
  41947. const char *zPathname
  41948. ){
  41949. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  41950. }
  41951. /*
  41952. ** Returns non-zero if the specified path name should be used verbatim. If
  41953. ** non-zero is returned from this function, the calling function must simply
  41954. ** use the provided path name verbatim -OR- resolve it into a full path name
  41955. ** using the GetFullPathName Win32 API function (if available).
  41956. */
  41957. static BOOL winIsVerbatimPathname(
  41958. const char *zPathname
  41959. ){
  41960. /*
  41961. ** If the path name starts with a forward slash or a backslash, it is either
  41962. ** a legal UNC name, a volume relative path, or an absolute path name in the
  41963. ** "Unix" format on Windows. There is no easy way to differentiate between
  41964. ** the final two cases; therefore, we return the safer return value of TRUE
  41965. ** so that callers of this function will simply use it verbatim.
  41966. */
  41967. if ( winIsDirSep(zPathname[0]) ){
  41968. return TRUE;
  41969. }
  41970. /*
  41971. ** If the path name starts with a letter and a colon it is either a volume
  41972. ** relative path or an absolute path. Callers of this function must not
  41973. ** attempt to treat it as a relative path name (i.e. they should simply use
  41974. ** it verbatim).
  41975. */
  41976. if ( winIsDriveLetterAndColon(zPathname) ){
  41977. return TRUE;
  41978. }
  41979. /*
  41980. ** If we get to this point, the path name should almost certainly be a purely
  41981. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  41982. */
  41983. return FALSE;
  41984. }
  41985. /*
  41986. ** Turn a relative pathname into a full pathname. Write the full
  41987. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  41988. ** bytes in size.
  41989. */
  41990. static int winFullPathname(
  41991. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  41992. const char *zRelative, /* Possibly relative input path */
  41993. int nFull, /* Size of output buffer in bytes */
  41994. char *zFull /* Output buffer */
  41995. ){
  41996. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  41997. DWORD nByte;
  41998. void *zConverted;
  41999. char *zOut;
  42000. #endif
  42001. /* If this path name begins with "/X:", where "X" is any alphabetic
  42002. ** character, discard the initial "/" from the pathname.
  42003. */
  42004. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  42005. zRelative++;
  42006. }
  42007. #if defined(__CYGWIN__)
  42008. SimulateIOError( return SQLITE_ERROR );
  42009. UNUSED_PARAMETER(nFull);
  42010. assert( nFull>=pVfs->mxPathname );
  42011. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  42012. /*
  42013. ** NOTE: We are dealing with a relative path name and the data
  42014. ** directory has been set. Therefore, use it as the basis
  42015. ** for converting the relative path name to an absolute
  42016. ** one by prepending the data directory and a slash.
  42017. */
  42018. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  42019. if( !zOut ){
  42020. return SQLITE_IOERR_NOMEM_BKPT;
  42021. }
  42022. if( cygwin_conv_path(
  42023. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  42024. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  42025. sqlite3_free(zOut);
  42026. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  42027. "winFullPathname1", zRelative);
  42028. }else{
  42029. char *zUtf8 = winConvertToUtf8Filename(zOut);
  42030. if( !zUtf8 ){
  42031. sqlite3_free(zOut);
  42032. return SQLITE_IOERR_NOMEM_BKPT;
  42033. }
  42034. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  42035. sqlite3_data_directory, winGetDirSep(), zUtf8);
  42036. sqlite3_free(zUtf8);
  42037. sqlite3_free(zOut);
  42038. }
  42039. }else{
  42040. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  42041. if( !zOut ){
  42042. return SQLITE_IOERR_NOMEM_BKPT;
  42043. }
  42044. if( cygwin_conv_path(
  42045. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  42046. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  42047. sqlite3_free(zOut);
  42048. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  42049. "winFullPathname2", zRelative);
  42050. }else{
  42051. char *zUtf8 = winConvertToUtf8Filename(zOut);
  42052. if( !zUtf8 ){
  42053. sqlite3_free(zOut);
  42054. return SQLITE_IOERR_NOMEM_BKPT;
  42055. }
  42056. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  42057. sqlite3_free(zUtf8);
  42058. sqlite3_free(zOut);
  42059. }
  42060. }
  42061. return SQLITE_OK;
  42062. #endif
  42063. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  42064. SimulateIOError( return SQLITE_ERROR );
  42065. /* WinCE has no concept of a relative pathname, or so I am told. */
  42066. /* WinRT has no way to convert a relative path to an absolute one. */
  42067. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  42068. /*
  42069. ** NOTE: We are dealing with a relative path name and the data
  42070. ** directory has been set. Therefore, use it as the basis
  42071. ** for converting the relative path name to an absolute
  42072. ** one by prepending the data directory and a backslash.
  42073. */
  42074. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  42075. sqlite3_data_directory, winGetDirSep(), zRelative);
  42076. }else{
  42077. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  42078. }
  42079. return SQLITE_OK;
  42080. #endif
  42081. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  42082. /* It's odd to simulate an io-error here, but really this is just
  42083. ** using the io-error infrastructure to test that SQLite handles this
  42084. ** function failing. This function could fail if, for example, the
  42085. ** current working directory has been unlinked.
  42086. */
  42087. SimulateIOError( return SQLITE_ERROR );
  42088. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  42089. /*
  42090. ** NOTE: We are dealing with a relative path name and the data
  42091. ** directory has been set. Therefore, use it as the basis
  42092. ** for converting the relative path name to an absolute
  42093. ** one by prepending the data directory and a backslash.
  42094. */
  42095. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  42096. sqlite3_data_directory, winGetDirSep(), zRelative);
  42097. return SQLITE_OK;
  42098. }
  42099. zConverted = winConvertFromUtf8Filename(zRelative);
  42100. if( zConverted==0 ){
  42101. return SQLITE_IOERR_NOMEM_BKPT;
  42102. }
  42103. if( osIsNT() ){
  42104. LPWSTR zTemp;
  42105. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  42106. if( nByte==0 ){
  42107. sqlite3_free(zConverted);
  42108. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  42109. "winFullPathname1", zRelative);
  42110. }
  42111. nByte += 3;
  42112. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  42113. if( zTemp==0 ){
  42114. sqlite3_free(zConverted);
  42115. return SQLITE_IOERR_NOMEM_BKPT;
  42116. }
  42117. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  42118. if( nByte==0 ){
  42119. sqlite3_free(zConverted);
  42120. sqlite3_free(zTemp);
  42121. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  42122. "winFullPathname2", zRelative);
  42123. }
  42124. sqlite3_free(zConverted);
  42125. zOut = winUnicodeToUtf8(zTemp);
  42126. sqlite3_free(zTemp);
  42127. }
  42128. #ifdef SQLITE_WIN32_HAS_ANSI
  42129. else{
  42130. char *zTemp;
  42131. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  42132. if( nByte==0 ){
  42133. sqlite3_free(zConverted);
  42134. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  42135. "winFullPathname3", zRelative);
  42136. }
  42137. nByte += 3;
  42138. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  42139. if( zTemp==0 ){
  42140. sqlite3_free(zConverted);
  42141. return SQLITE_IOERR_NOMEM_BKPT;
  42142. }
  42143. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  42144. if( nByte==0 ){
  42145. sqlite3_free(zConverted);
  42146. sqlite3_free(zTemp);
  42147. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  42148. "winFullPathname4", zRelative);
  42149. }
  42150. sqlite3_free(zConverted);
  42151. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  42152. sqlite3_free(zTemp);
  42153. }
  42154. #endif
  42155. if( zOut ){
  42156. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  42157. sqlite3_free(zOut);
  42158. return SQLITE_OK;
  42159. }else{
  42160. return SQLITE_IOERR_NOMEM_BKPT;
  42161. }
  42162. #endif
  42163. }
  42164. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  42165. /*
  42166. ** Interfaces for opening a shared library, finding entry points
  42167. ** within the shared library, and closing the shared library.
  42168. */
  42169. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  42170. HANDLE h;
  42171. #if defined(__CYGWIN__)
  42172. int nFull = pVfs->mxPathname+1;
  42173. char *zFull = sqlite3MallocZero( nFull );
  42174. void *zConverted = 0;
  42175. if( zFull==0 ){
  42176. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  42177. return 0;
  42178. }
  42179. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  42180. sqlite3_free(zFull);
  42181. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  42182. return 0;
  42183. }
  42184. zConverted = winConvertFromUtf8Filename(zFull);
  42185. sqlite3_free(zFull);
  42186. #else
  42187. void *zConverted = winConvertFromUtf8Filename(zFilename);
  42188. UNUSED_PARAMETER(pVfs);
  42189. #endif
  42190. if( zConverted==0 ){
  42191. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  42192. return 0;
  42193. }
  42194. if( osIsNT() ){
  42195. #if SQLITE_OS_WINRT
  42196. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  42197. #else
  42198. h = osLoadLibraryW((LPCWSTR)zConverted);
  42199. #endif
  42200. }
  42201. #ifdef SQLITE_WIN32_HAS_ANSI
  42202. else{
  42203. h = osLoadLibraryA((char*)zConverted);
  42204. }
  42205. #endif
  42206. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  42207. sqlite3_free(zConverted);
  42208. return (void*)h;
  42209. }
  42210. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  42211. UNUSED_PARAMETER(pVfs);
  42212. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  42213. }
  42214. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  42215. FARPROC proc;
  42216. UNUSED_PARAMETER(pVfs);
  42217. proc = osGetProcAddressA((HANDLE)pH, zSym);
  42218. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  42219. (void*)pH, zSym, (void*)proc));
  42220. return (void(*)(void))proc;
  42221. }
  42222. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  42223. UNUSED_PARAMETER(pVfs);
  42224. osFreeLibrary((HANDLE)pHandle);
  42225. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  42226. }
  42227. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  42228. #define winDlOpen 0
  42229. #define winDlError 0
  42230. #define winDlSym 0
  42231. #define winDlClose 0
  42232. #endif
  42233. /* State information for the randomness gatherer. */
  42234. typedef struct EntropyGatherer EntropyGatherer;
  42235. struct EntropyGatherer {
  42236. unsigned char *a; /* Gather entropy into this buffer */
  42237. int na; /* Size of a[] in bytes */
  42238. int i; /* XOR next input into a[i] */
  42239. int nXor; /* Number of XOR operations done */
  42240. };
  42241. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  42242. /* Mix sz bytes of entropy into p. */
  42243. static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
  42244. int j, k;
  42245. for(j=0, k=p->i; j<sz; j++){
  42246. p->a[k++] ^= x[j];
  42247. if( k>=p->na ) k = 0;
  42248. }
  42249. p->i = k;
  42250. p->nXor += sz;
  42251. }
  42252. #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
  42253. /*
  42254. ** Write up to nBuf bytes of randomness into zBuf.
  42255. */
  42256. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  42257. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  42258. UNUSED_PARAMETER(pVfs);
  42259. memset(zBuf, 0, nBuf);
  42260. return nBuf;
  42261. #else
  42262. EntropyGatherer e;
  42263. UNUSED_PARAMETER(pVfs);
  42264. memset(zBuf, 0, nBuf);
  42265. e.a = (unsigned char*)zBuf;
  42266. e.na = nBuf;
  42267. e.nXor = 0;
  42268. e.i = 0;
  42269. {
  42270. SYSTEMTIME x;
  42271. osGetSystemTime(&x);
  42272. xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
  42273. }
  42274. {
  42275. DWORD pid = osGetCurrentProcessId();
  42276. xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
  42277. }
  42278. #if SQLITE_OS_WINRT
  42279. {
  42280. ULONGLONG cnt = osGetTickCount64();
  42281. xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
  42282. }
  42283. #else
  42284. {
  42285. DWORD cnt = osGetTickCount();
  42286. xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
  42287. }
  42288. #endif /* SQLITE_OS_WINRT */
  42289. {
  42290. LARGE_INTEGER i;
  42291. osQueryPerformanceCounter(&i);
  42292. xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
  42293. }
  42294. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  42295. {
  42296. UUID id;
  42297. memset(&id, 0, sizeof(UUID));
  42298. osUuidCreate(&id);
  42299. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  42300. memset(&id, 0, sizeof(UUID));
  42301. osUuidCreateSequential(&id);
  42302. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  42303. }
  42304. #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
  42305. return e.nXor>nBuf ? nBuf : e.nXor;
  42306. #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
  42307. }
  42308. /*
  42309. ** Sleep for a little while. Return the amount of time slept.
  42310. */
  42311. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  42312. sqlite3_win32_sleep((microsec+999)/1000);
  42313. UNUSED_PARAMETER(pVfs);
  42314. return ((microsec+999)/1000)*1000;
  42315. }
  42316. /*
  42317. ** The following variable, if set to a non-zero value, is interpreted as
  42318. ** the number of seconds since 1970 and is used to set the result of
  42319. ** sqlite3OsCurrentTime() during testing.
  42320. */
  42321. #ifdef SQLITE_TEST
  42322. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  42323. #endif
  42324. /*
  42325. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  42326. ** the current time and date as a Julian Day number times 86_400_000. In
  42327. ** other words, write into *piNow the number of milliseconds since the Julian
  42328. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  42329. ** proleptic Gregorian calendar.
  42330. **
  42331. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  42332. ** cannot be found.
  42333. */
  42334. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  42335. /* FILETIME structure is a 64-bit value representing the number of
  42336. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  42337. */
  42338. FILETIME ft;
  42339. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  42340. #ifdef SQLITE_TEST
  42341. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  42342. #endif
  42343. /* 2^32 - to avoid use of LL and warnings in gcc */
  42344. static const sqlite3_int64 max32BitValue =
  42345. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  42346. (sqlite3_int64)294967296;
  42347. #if SQLITE_OS_WINCE
  42348. SYSTEMTIME time;
  42349. osGetSystemTime(&time);
  42350. /* if SystemTimeToFileTime() fails, it returns zero. */
  42351. if (!osSystemTimeToFileTime(&time,&ft)){
  42352. return SQLITE_ERROR;
  42353. }
  42354. #else
  42355. osGetSystemTimeAsFileTime( &ft );
  42356. #endif
  42357. *piNow = winFiletimeEpoch +
  42358. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  42359. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  42360. #ifdef SQLITE_TEST
  42361. if( sqlite3_current_time ){
  42362. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  42363. }
  42364. #endif
  42365. UNUSED_PARAMETER(pVfs);
  42366. return SQLITE_OK;
  42367. }
  42368. /*
  42369. ** Find the current time (in Universal Coordinated Time). Write the
  42370. ** current time and date as a Julian Day number into *prNow and
  42371. ** return 0. Return 1 if the time and date cannot be found.
  42372. */
  42373. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  42374. int rc;
  42375. sqlite3_int64 i;
  42376. rc = winCurrentTimeInt64(pVfs, &i);
  42377. if( !rc ){
  42378. *prNow = i/86400000.0;
  42379. }
  42380. return rc;
  42381. }
  42382. /*
  42383. ** The idea is that this function works like a combination of
  42384. ** GetLastError() and FormatMessage() on Windows (or errno and
  42385. ** strerror_r() on Unix). After an error is returned by an OS
  42386. ** function, SQLite calls this function with zBuf pointing to
  42387. ** a buffer of nBuf bytes. The OS layer should populate the
  42388. ** buffer with a nul-terminated UTF-8 encoded error message
  42389. ** describing the last IO error to have occurred within the calling
  42390. ** thread.
  42391. **
  42392. ** If the error message is too large for the supplied buffer,
  42393. ** it should be truncated. The return value of xGetLastError
  42394. ** is zero if the error message fits in the buffer, or non-zero
  42395. ** otherwise (if the message was truncated). If non-zero is returned,
  42396. ** then it is not necessary to include the nul-terminator character
  42397. ** in the output buffer.
  42398. **
  42399. ** Not supplying an error message will have no adverse effect
  42400. ** on SQLite. It is fine to have an implementation that never
  42401. ** returns an error message:
  42402. **
  42403. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  42404. ** assert(zBuf[0]=='\0');
  42405. ** return 0;
  42406. ** }
  42407. **
  42408. ** However if an error message is supplied, it will be incorporated
  42409. ** by sqlite into the error message available to the user using
  42410. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  42411. */
  42412. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  42413. DWORD e = osGetLastError();
  42414. UNUSED_PARAMETER(pVfs);
  42415. if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
  42416. return e;
  42417. }
  42418. /*
  42419. ** Initialize and deinitialize the operating system interface.
  42420. */
  42421. SQLITE_API int sqlite3_os_init(void){
  42422. static sqlite3_vfs winVfs = {
  42423. 3, /* iVersion */
  42424. sizeof(winFile), /* szOsFile */
  42425. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  42426. 0, /* pNext */
  42427. "win32", /* zName */
  42428. &winAppData, /* pAppData */
  42429. winOpen, /* xOpen */
  42430. winDelete, /* xDelete */
  42431. winAccess, /* xAccess */
  42432. winFullPathname, /* xFullPathname */
  42433. winDlOpen, /* xDlOpen */
  42434. winDlError, /* xDlError */
  42435. winDlSym, /* xDlSym */
  42436. winDlClose, /* xDlClose */
  42437. winRandomness, /* xRandomness */
  42438. winSleep, /* xSleep */
  42439. winCurrentTime, /* xCurrentTime */
  42440. winGetLastError, /* xGetLastError */
  42441. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  42442. winSetSystemCall, /* xSetSystemCall */
  42443. winGetSystemCall, /* xGetSystemCall */
  42444. winNextSystemCall, /* xNextSystemCall */
  42445. };
  42446. #if defined(SQLITE_WIN32_HAS_WIDE)
  42447. static sqlite3_vfs winLongPathVfs = {
  42448. 3, /* iVersion */
  42449. sizeof(winFile), /* szOsFile */
  42450. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  42451. 0, /* pNext */
  42452. "win32-longpath", /* zName */
  42453. &winAppData, /* pAppData */
  42454. winOpen, /* xOpen */
  42455. winDelete, /* xDelete */
  42456. winAccess, /* xAccess */
  42457. winFullPathname, /* xFullPathname */
  42458. winDlOpen, /* xDlOpen */
  42459. winDlError, /* xDlError */
  42460. winDlSym, /* xDlSym */
  42461. winDlClose, /* xDlClose */
  42462. winRandomness, /* xRandomness */
  42463. winSleep, /* xSleep */
  42464. winCurrentTime, /* xCurrentTime */
  42465. winGetLastError, /* xGetLastError */
  42466. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  42467. winSetSystemCall, /* xSetSystemCall */
  42468. winGetSystemCall, /* xGetSystemCall */
  42469. winNextSystemCall, /* xNextSystemCall */
  42470. };
  42471. #endif
  42472. static sqlite3_vfs winNolockVfs = {
  42473. 3, /* iVersion */
  42474. sizeof(winFile), /* szOsFile */
  42475. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  42476. 0, /* pNext */
  42477. "win32-none", /* zName */
  42478. &winNolockAppData, /* pAppData */
  42479. winOpen, /* xOpen */
  42480. winDelete, /* xDelete */
  42481. winAccess, /* xAccess */
  42482. winFullPathname, /* xFullPathname */
  42483. winDlOpen, /* xDlOpen */
  42484. winDlError, /* xDlError */
  42485. winDlSym, /* xDlSym */
  42486. winDlClose, /* xDlClose */
  42487. winRandomness, /* xRandomness */
  42488. winSleep, /* xSleep */
  42489. winCurrentTime, /* xCurrentTime */
  42490. winGetLastError, /* xGetLastError */
  42491. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  42492. winSetSystemCall, /* xSetSystemCall */
  42493. winGetSystemCall, /* xGetSystemCall */
  42494. winNextSystemCall, /* xNextSystemCall */
  42495. };
  42496. #if defined(SQLITE_WIN32_HAS_WIDE)
  42497. static sqlite3_vfs winLongPathNolockVfs = {
  42498. 3, /* iVersion */
  42499. sizeof(winFile), /* szOsFile */
  42500. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  42501. 0, /* pNext */
  42502. "win32-longpath-none", /* zName */
  42503. &winNolockAppData, /* pAppData */
  42504. winOpen, /* xOpen */
  42505. winDelete, /* xDelete */
  42506. winAccess, /* xAccess */
  42507. winFullPathname, /* xFullPathname */
  42508. winDlOpen, /* xDlOpen */
  42509. winDlError, /* xDlError */
  42510. winDlSym, /* xDlSym */
  42511. winDlClose, /* xDlClose */
  42512. winRandomness, /* xRandomness */
  42513. winSleep, /* xSleep */
  42514. winCurrentTime, /* xCurrentTime */
  42515. winGetLastError, /* xGetLastError */
  42516. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  42517. winSetSystemCall, /* xSetSystemCall */
  42518. winGetSystemCall, /* xGetSystemCall */
  42519. winNextSystemCall, /* xNextSystemCall */
  42520. };
  42521. #endif
  42522. /* Double-check that the aSyscall[] array has been constructed
  42523. ** correctly. See ticket [bb3a86e890c8e96ab] */
  42524. assert( ArraySize(aSyscall)==80 );
  42525. /* get memory map allocation granularity */
  42526. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  42527. #if SQLITE_OS_WINRT
  42528. osGetNativeSystemInfo(&winSysInfo);
  42529. #else
  42530. osGetSystemInfo(&winSysInfo);
  42531. #endif
  42532. assert( winSysInfo.dwAllocationGranularity>0 );
  42533. assert( winSysInfo.dwPageSize>0 );
  42534. sqlite3_vfs_register(&winVfs, 1);
  42535. #if defined(SQLITE_WIN32_HAS_WIDE)
  42536. sqlite3_vfs_register(&winLongPathVfs, 0);
  42537. #endif
  42538. sqlite3_vfs_register(&winNolockVfs, 0);
  42539. #if defined(SQLITE_WIN32_HAS_WIDE)
  42540. sqlite3_vfs_register(&winLongPathNolockVfs, 0);
  42541. #endif
  42542. #ifndef SQLITE_OMIT_WAL
  42543. winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  42544. #endif
  42545. return SQLITE_OK;
  42546. }
  42547. SQLITE_API int sqlite3_os_end(void){
  42548. #if SQLITE_OS_WINRT
  42549. if( sleepObj!=NULL ){
  42550. osCloseHandle(sleepObj);
  42551. sleepObj = NULL;
  42552. }
  42553. #endif
  42554. #ifndef SQLITE_OMIT_WAL
  42555. winBigLock = 0;
  42556. #endif
  42557. return SQLITE_OK;
  42558. }
  42559. #endif /* SQLITE_OS_WIN */
  42560. /************** End of os_win.c **********************************************/
  42561. /************** Begin file memdb.c *******************************************/
  42562. /*
  42563. ** 2016-09-07
  42564. **
  42565. ** The author disclaims copyright to this source code. In place of
  42566. ** a legal notice, here is a blessing:
  42567. **
  42568. ** May you do good and not evil.
  42569. ** May you find forgiveness for yourself and forgive others.
  42570. ** May you share freely, never taking more than you give.
  42571. **
  42572. ******************************************************************************
  42573. **
  42574. ** This file implements an in-memory VFS. A database is held as a contiguous
  42575. ** block of memory.
  42576. **
  42577. ** This file also implements interface sqlite3_serialize() and
  42578. ** sqlite3_deserialize().
  42579. */
  42580. #ifdef SQLITE_ENABLE_DESERIALIZE
  42581. /* #include "sqliteInt.h" */
  42582. /*
  42583. ** Forward declaration of objects used by this utility
  42584. */
  42585. typedef struct sqlite3_vfs MemVfs;
  42586. typedef struct MemFile MemFile;
  42587. /* Access to a lower-level VFS that (might) implement dynamic loading,
  42588. ** access to randomness, etc.
  42589. */
  42590. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  42591. /* An open file */
  42592. struct MemFile {
  42593. sqlite3_file base; /* IO methods */
  42594. sqlite3_int64 sz; /* Size of the file */
  42595. sqlite3_int64 szMax; /* Space allocated to aData */
  42596. unsigned char *aData; /* content of the file */
  42597. int nMmap; /* Number of memory mapped pages */
  42598. unsigned mFlags; /* Flags */
  42599. int eLock; /* Most recent lock against this file */
  42600. };
  42601. /*
  42602. ** Methods for MemFile
  42603. */
  42604. static int memdbClose(sqlite3_file*);
  42605. static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  42606. static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  42607. static int memdbTruncate(sqlite3_file*, sqlite3_int64 size);
  42608. static int memdbSync(sqlite3_file*, int flags);
  42609. static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  42610. static int memdbLock(sqlite3_file*, int);
  42611. /* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */
  42612. static int memdbFileControl(sqlite3_file*, int op, void *pArg);
  42613. /* static int memdbSectorSize(sqlite3_file*); // not used */
  42614. static int memdbDeviceCharacteristics(sqlite3_file*);
  42615. static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  42616. static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  42617. /*
  42618. ** Methods for MemVfs
  42619. */
  42620. static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  42621. /* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */
  42622. static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  42623. static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  42624. static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);
  42625. static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  42626. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  42627. static void memdbDlClose(sqlite3_vfs*, void*);
  42628. static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);
  42629. static int memdbSleep(sqlite3_vfs*, int microseconds);
  42630. /* static int memdbCurrentTime(sqlite3_vfs*, double*); */
  42631. static int memdbGetLastError(sqlite3_vfs*, int, char *);
  42632. static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  42633. static sqlite3_vfs memdb_vfs = {
  42634. 2, /* iVersion */
  42635. 0, /* szOsFile (set when registered) */
  42636. 1024, /* mxPathname */
  42637. 0, /* pNext */
  42638. "memdb", /* zName */
  42639. 0, /* pAppData (set when registered) */
  42640. memdbOpen, /* xOpen */
  42641. 0, /* memdbDelete, */ /* xDelete */
  42642. memdbAccess, /* xAccess */
  42643. memdbFullPathname, /* xFullPathname */
  42644. memdbDlOpen, /* xDlOpen */
  42645. memdbDlError, /* xDlError */
  42646. memdbDlSym, /* xDlSym */
  42647. memdbDlClose, /* xDlClose */
  42648. memdbRandomness, /* xRandomness */
  42649. memdbSleep, /* xSleep */
  42650. 0, /* memdbCurrentTime, */ /* xCurrentTime */
  42651. memdbGetLastError, /* xGetLastError */
  42652. memdbCurrentTimeInt64 /* xCurrentTimeInt64 */
  42653. };
  42654. static const sqlite3_io_methods memdb_io_methods = {
  42655. 3, /* iVersion */
  42656. memdbClose, /* xClose */
  42657. memdbRead, /* xRead */
  42658. memdbWrite, /* xWrite */
  42659. memdbTruncate, /* xTruncate */
  42660. memdbSync, /* xSync */
  42661. memdbFileSize, /* xFileSize */
  42662. memdbLock, /* xLock */
  42663. memdbLock, /* xUnlock - same as xLock in this case */
  42664. 0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
  42665. memdbFileControl, /* xFileControl */
  42666. 0, /* memdbSectorSize,*/ /* xSectorSize */
  42667. memdbDeviceCharacteristics, /* xDeviceCharacteristics */
  42668. 0, /* xShmMap */
  42669. 0, /* xShmLock */
  42670. 0, /* xShmBarrier */
  42671. 0, /* xShmUnmap */
  42672. memdbFetch, /* xFetch */
  42673. memdbUnfetch /* xUnfetch */
  42674. };
  42675. /*
  42676. ** Close an memdb-file.
  42677. **
  42678. ** The pData pointer is owned by the application, so there is nothing
  42679. ** to free.
  42680. */
  42681. static int memdbClose(sqlite3_file *pFile){
  42682. MemFile *p = (MemFile *)pFile;
  42683. if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);
  42684. return SQLITE_OK;
  42685. }
  42686. /*
  42687. ** Read data from an memdb-file.
  42688. */
  42689. static int memdbRead(
  42690. sqlite3_file *pFile,
  42691. void *zBuf,
  42692. int iAmt,
  42693. sqlite_int64 iOfst
  42694. ){
  42695. MemFile *p = (MemFile *)pFile;
  42696. if( iOfst+iAmt>p->sz ){
  42697. memset(zBuf, 0, iAmt);
  42698. if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
  42699. return SQLITE_IOERR_SHORT_READ;
  42700. }
  42701. memcpy(zBuf, p->aData+iOfst, iAmt);
  42702. return SQLITE_OK;
  42703. }
  42704. /*
  42705. ** Try to enlarge the memory allocation to hold at least sz bytes
  42706. */
  42707. static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
  42708. unsigned char *pNew;
  42709. if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){
  42710. return SQLITE_FULL;
  42711. }
  42712. pNew = sqlite3_realloc64(p->aData, newSz);
  42713. if( pNew==0 ) return SQLITE_NOMEM;
  42714. p->aData = pNew;
  42715. p->szMax = newSz;
  42716. return SQLITE_OK;
  42717. }
  42718. /*
  42719. ** Write data to an memdb-file.
  42720. */
  42721. static int memdbWrite(
  42722. sqlite3_file *pFile,
  42723. const void *z,
  42724. int iAmt,
  42725. sqlite_int64 iOfst
  42726. ){
  42727. MemFile *p = (MemFile *)pFile;
  42728. if( iOfst+iAmt>p->sz ){
  42729. int rc;
  42730. if( iOfst+iAmt>p->szMax
  42731. && (rc = memdbEnlarge(p, (iOfst+iAmt)*2))!=SQLITE_OK
  42732. ){
  42733. return rc;
  42734. }
  42735. if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
  42736. p->sz = iOfst+iAmt;
  42737. }
  42738. memcpy(p->aData+iOfst, z, iAmt);
  42739. return SQLITE_OK;
  42740. }
  42741. /*
  42742. ** Truncate an memdb-file.
  42743. **
  42744. ** In rollback mode (which is always the case for memdb, as it does not
  42745. ** support WAL mode) the truncate() method is only used to reduce
  42746. ** the size of a file, never to increase the size.
  42747. */
  42748. static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
  42749. MemFile *p = (MemFile *)pFile;
  42750. if( NEVER(size>p->sz) ) return SQLITE_FULL;
  42751. p->sz = size;
  42752. return SQLITE_OK;
  42753. }
  42754. /*
  42755. ** Sync an memdb-file.
  42756. */
  42757. static int memdbSync(sqlite3_file *pFile, int flags){
  42758. return SQLITE_OK;
  42759. }
  42760. /*
  42761. ** Return the current file-size of an memdb-file.
  42762. */
  42763. static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  42764. MemFile *p = (MemFile *)pFile;
  42765. *pSize = p->sz;
  42766. return SQLITE_OK;
  42767. }
  42768. /*
  42769. ** Lock an memdb-file.
  42770. */
  42771. static int memdbLock(sqlite3_file *pFile, int eLock){
  42772. MemFile *p = (MemFile *)pFile;
  42773. p->eLock = eLock;
  42774. return SQLITE_OK;
  42775. }
  42776. #if 0 /* Never used because memdbAccess() always returns false */
  42777. /*
  42778. ** Check if another file-handle holds a RESERVED lock on an memdb-file.
  42779. */
  42780. static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  42781. *pResOut = 0;
  42782. return SQLITE_OK;
  42783. }
  42784. #endif
  42785. /*
  42786. ** File control method. For custom operations on an memdb-file.
  42787. */
  42788. static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
  42789. MemFile *p = (MemFile *)pFile;
  42790. int rc = SQLITE_NOTFOUND;
  42791. if( op==SQLITE_FCNTL_VFSNAME ){
  42792. *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
  42793. rc = SQLITE_OK;
  42794. }
  42795. return rc;
  42796. }
  42797. #if 0 /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  42798. /*
  42799. ** Return the sector-size in bytes for an memdb-file.
  42800. */
  42801. static int memdbSectorSize(sqlite3_file *pFile){
  42802. return 1024;
  42803. }
  42804. #endif
  42805. /*
  42806. ** Return the device characteristic flags supported by an memdb-file.
  42807. */
  42808. static int memdbDeviceCharacteristics(sqlite3_file *pFile){
  42809. return SQLITE_IOCAP_ATOMIC |
  42810. SQLITE_IOCAP_POWERSAFE_OVERWRITE |
  42811. SQLITE_IOCAP_SAFE_APPEND |
  42812. SQLITE_IOCAP_SEQUENTIAL;
  42813. }
  42814. /* Fetch a page of a memory-mapped file */
  42815. static int memdbFetch(
  42816. sqlite3_file *pFile,
  42817. sqlite3_int64 iOfst,
  42818. int iAmt,
  42819. void **pp
  42820. ){
  42821. MemFile *p = (MemFile *)pFile;
  42822. p->nMmap++;
  42823. *pp = (void*)(p->aData + iOfst);
  42824. return SQLITE_OK;
  42825. }
  42826. /* Release a memory-mapped page */
  42827. static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  42828. MemFile *p = (MemFile *)pFile;
  42829. p->nMmap--;
  42830. return SQLITE_OK;
  42831. }
  42832. /*
  42833. ** Open an mem file handle.
  42834. */
  42835. static int memdbOpen(
  42836. sqlite3_vfs *pVfs,
  42837. const char *zName,
  42838. sqlite3_file *pFile,
  42839. int flags,
  42840. int *pOutFlags
  42841. ){
  42842. MemFile *p = (MemFile*)pFile;
  42843. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  42844. return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);
  42845. }
  42846. memset(p, 0, sizeof(*p));
  42847. p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
  42848. assert( pOutFlags!=0 ); /* True because flags==SQLITE_OPEN_MAIN_DB */
  42849. *pOutFlags = flags | SQLITE_OPEN_MEMORY;
  42850. p->base.pMethods = &memdb_io_methods;
  42851. return SQLITE_OK;
  42852. }
  42853. #if 0 /* Only used to delete rollback journals, master journals, and WAL
  42854. ** files, none of which exist in memdb. So this routine is never used */
  42855. /*
  42856. ** Delete the file located at zPath. If the dirSync argument is true,
  42857. ** ensure the file-system modifications are synced to disk before
  42858. ** returning.
  42859. */
  42860. static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  42861. return SQLITE_IOERR_DELETE;
  42862. }
  42863. #endif
  42864. /*
  42865. ** Test for access permissions. Return true if the requested permission
  42866. ** is available, or false otherwise.
  42867. **
  42868. ** With memdb, no files ever exist on disk. So always return false.
  42869. */
  42870. static int memdbAccess(
  42871. sqlite3_vfs *pVfs,
  42872. const char *zPath,
  42873. int flags,
  42874. int *pResOut
  42875. ){
  42876. *pResOut = 0;
  42877. return SQLITE_OK;
  42878. }
  42879. /*
  42880. ** Populate buffer zOut with the full canonical pathname corresponding
  42881. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  42882. ** of at least (INST_MAX_PATHNAME+1) bytes.
  42883. */
  42884. static int memdbFullPathname(
  42885. sqlite3_vfs *pVfs,
  42886. const char *zPath,
  42887. int nOut,
  42888. char *zOut
  42889. ){
  42890. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  42891. return SQLITE_OK;
  42892. }
  42893. /*
  42894. ** Open the dynamic library located at zPath and return a handle.
  42895. */
  42896. static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  42897. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  42898. }
  42899. /*
  42900. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  42901. ** utf-8 string describing the most recent error encountered associated
  42902. ** with dynamic libraries.
  42903. */
  42904. static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  42905. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  42906. }
  42907. /*
  42908. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  42909. */
  42910. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  42911. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  42912. }
  42913. /*
  42914. ** Close the dynamic library handle pHandle.
  42915. */
  42916. static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
  42917. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  42918. }
  42919. /*
  42920. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  42921. ** random data.
  42922. */
  42923. static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  42924. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  42925. }
  42926. /*
  42927. ** Sleep for nMicro microseconds. Return the number of microseconds
  42928. ** actually slept.
  42929. */
  42930. static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
  42931. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  42932. }
  42933. #if 0 /* Never used. Modern cores only call xCurrentTimeInt64() */
  42934. /*
  42935. ** Return the current time as a Julian Day number in *pTimeOut.
  42936. */
  42937. static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  42938. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  42939. }
  42940. #endif
  42941. static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  42942. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  42943. }
  42944. static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  42945. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  42946. }
  42947. /*
  42948. ** Translate a database connection pointer and schema name into a
  42949. ** MemFile pointer.
  42950. */
  42951. static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
  42952. MemFile *p = 0;
  42953. int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
  42954. if( rc ) return 0;
  42955. if( p->base.pMethods!=&memdb_io_methods ) return 0;
  42956. return p;
  42957. }
  42958. /*
  42959. ** Return the serialization of a database
  42960. */
  42961. SQLITE_API unsigned char *sqlite3_serialize(
  42962. sqlite3 *db, /* The database connection */
  42963. const char *zSchema, /* Which database within the connection */
  42964. sqlite3_int64 *piSize, /* Write size here, if not NULL */
  42965. unsigned int mFlags /* Maybe SQLITE_SERIALIZE_NOCOPY */
  42966. ){
  42967. MemFile *p;
  42968. int iDb;
  42969. Btree *pBt;
  42970. sqlite3_int64 sz;
  42971. int szPage = 0;
  42972. sqlite3_stmt *pStmt = 0;
  42973. unsigned char *pOut;
  42974. char *zSql;
  42975. int rc;
  42976. #ifdef SQLITE_ENABLE_API_ARMOR
  42977. if( !sqlite3SafetyCheckOk(db) ){
  42978. (void)SQLITE_MISUSE_BKPT;
  42979. return 0;
  42980. }
  42981. #endif
  42982. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  42983. p = memdbFromDbSchema(db, zSchema);
  42984. iDb = sqlite3FindDbName(db, zSchema);
  42985. if( piSize ) *piSize = -1;
  42986. if( iDb<0 ) return 0;
  42987. if( p ){
  42988. if( piSize ) *piSize = p->sz;
  42989. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  42990. pOut = p->aData;
  42991. }else{
  42992. pOut = sqlite3_malloc64( p->sz );
  42993. if( pOut ) memcpy(pOut, p->aData, p->sz);
  42994. }
  42995. return pOut;
  42996. }
  42997. pBt = db->aDb[iDb].pBt;
  42998. if( pBt==0 ) return 0;
  42999. szPage = sqlite3BtreeGetPageSize(pBt);
  43000. zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
  43001. rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
  43002. sqlite3_free(zSql);
  43003. if( rc ) return 0;
  43004. rc = sqlite3_step(pStmt);
  43005. if( rc!=SQLITE_ROW ){
  43006. pOut = 0;
  43007. }else{
  43008. sz = sqlite3_column_int64(pStmt, 0)*szPage;
  43009. if( piSize ) *piSize = sz;
  43010. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  43011. pOut = 0;
  43012. }else{
  43013. pOut = sqlite3_malloc64( sz );
  43014. if( pOut ){
  43015. int nPage = sqlite3_column_int(pStmt, 0);
  43016. Pager *pPager = sqlite3BtreePager(pBt);
  43017. int pgno;
  43018. for(pgno=1; pgno<=nPage; pgno++){
  43019. DbPage *pPage = 0;
  43020. unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
  43021. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);
  43022. if( rc==SQLITE_OK ){
  43023. memcpy(pTo, sqlite3PagerGetData(pPage), szPage);
  43024. }else{
  43025. memset(pTo, 0, szPage);
  43026. }
  43027. sqlite3PagerUnref(pPage);
  43028. }
  43029. }
  43030. }
  43031. }
  43032. sqlite3_finalize(pStmt);
  43033. return pOut;
  43034. }
  43035. /* Convert zSchema to a MemDB and initialize its content.
  43036. */
  43037. SQLITE_API int sqlite3_deserialize(
  43038. sqlite3 *db, /* The database connection */
  43039. const char *zSchema, /* Which DB to reopen with the deserialization */
  43040. unsigned char *pData, /* The serialized database content */
  43041. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  43042. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  43043. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  43044. ){
  43045. MemFile *p;
  43046. char *zSql;
  43047. sqlite3_stmt *pStmt = 0;
  43048. int rc;
  43049. int iDb;
  43050. #ifdef SQLITE_ENABLE_API_ARMOR
  43051. if( !sqlite3SafetyCheckOk(db) ){
  43052. return SQLITE_MISUSE_BKPT;
  43053. }
  43054. if( szDb<0 ) return SQLITE_MISUSE_BKPT;
  43055. if( szBuf<0 ) return SQLITE_MISUSE_BKPT;
  43056. #endif
  43057. sqlite3_mutex_enter(db->mutex);
  43058. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  43059. iDb = sqlite3FindDbName(db, zSchema);
  43060. if( iDb<0 ){
  43061. rc = SQLITE_ERROR;
  43062. goto end_deserialize;
  43063. }
  43064. zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
  43065. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  43066. sqlite3_free(zSql);
  43067. if( rc ) goto end_deserialize;
  43068. db->init.iDb = (u8)iDb;
  43069. db->init.reopenMemdb = 1;
  43070. rc = sqlite3_step(pStmt);
  43071. db->init.reopenMemdb = 0;
  43072. if( rc!=SQLITE_DONE ){
  43073. rc = SQLITE_ERROR;
  43074. goto end_deserialize;
  43075. }
  43076. p = memdbFromDbSchema(db, zSchema);
  43077. if( p==0 ){
  43078. rc = SQLITE_ERROR;
  43079. }else{
  43080. p->aData = pData;
  43081. p->sz = szDb;
  43082. p->szMax = szBuf;
  43083. p->mFlags = mFlags;
  43084. rc = SQLITE_OK;
  43085. }
  43086. end_deserialize:
  43087. sqlite3_finalize(pStmt);
  43088. sqlite3_mutex_leave(db->mutex);
  43089. return rc;
  43090. }
  43091. /*
  43092. ** This routine is called when the extension is loaded.
  43093. ** Register the new VFS.
  43094. */
  43095. SQLITE_PRIVATE int sqlite3MemdbInit(void){
  43096. sqlite3_vfs *pLower = sqlite3_vfs_find(0);
  43097. int sz = pLower->szOsFile;
  43098. memdb_vfs.pAppData = pLower;
  43099. /* In all known configurations of SQLite, the size of a default
  43100. ** sqlite3_file is greater than the size of a memdb sqlite3_file.
  43101. ** Should that ever change, remove the following NEVER() */
  43102. if( NEVER(sz<sizeof(MemFile)) ) sz = sizeof(MemFile);
  43103. memdb_vfs.szOsFile = sz;
  43104. return sqlite3_vfs_register(&memdb_vfs, 0);
  43105. }
  43106. #endif /* SQLITE_ENABLE_DESERIALIZE */
  43107. /************** End of memdb.c ***********************************************/
  43108. /************** Begin file bitvec.c ******************************************/
  43109. /*
  43110. ** 2008 February 16
  43111. **
  43112. ** The author disclaims copyright to this source code. In place of
  43113. ** a legal notice, here is a blessing:
  43114. **
  43115. ** May you do good and not evil.
  43116. ** May you find forgiveness for yourself and forgive others.
  43117. ** May you share freely, never taking more than you give.
  43118. **
  43119. *************************************************************************
  43120. ** This file implements an object that represents a fixed-length
  43121. ** bitmap. Bits are numbered starting with 1.
  43122. **
  43123. ** A bitmap is used to record which pages of a database file have been
  43124. ** journalled during a transaction, or which pages have the "dont-write"
  43125. ** property. Usually only a few pages are meet either condition.
  43126. ** So the bitmap is usually sparse and has low cardinality.
  43127. ** But sometimes (for example when during a DROP of a large table) most
  43128. ** or all of the pages in a database can get journalled. In those cases,
  43129. ** the bitmap becomes dense with high cardinality. The algorithm needs
  43130. ** to handle both cases well.
  43131. **
  43132. ** The size of the bitmap is fixed when the object is created.
  43133. **
  43134. ** All bits are clear when the bitmap is created. Individual bits
  43135. ** may be set or cleared one at a time.
  43136. **
  43137. ** Test operations are about 100 times more common that set operations.
  43138. ** Clear operations are exceedingly rare. There are usually between
  43139. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  43140. ** sometimes grow into tens of thousands or larger. The size of the
  43141. ** Bitvec object is the number of pages in the database file at the
  43142. ** start of a transaction, and is thus usually less than a few thousand,
  43143. ** but can be as large as 2 billion for a really big database.
  43144. */
  43145. /* #include "sqliteInt.h" */
  43146. /* Size of the Bitvec structure in bytes. */
  43147. #define BITVEC_SZ 512
  43148. /* Round the union size down to the nearest pointer boundary, since that's how
  43149. ** it will be aligned within the Bitvec struct. */
  43150. #define BITVEC_USIZE \
  43151. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  43152. /* Type of the array "element" for the bitmap representation.
  43153. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  43154. ** Setting this to the "natural word" size of your CPU may improve
  43155. ** performance. */
  43156. #define BITVEC_TELEM u8
  43157. /* Size, in bits, of the bitmap element. */
  43158. #define BITVEC_SZELEM 8
  43159. /* Number of elements in a bitmap array. */
  43160. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  43161. /* Number of bits in the bitmap array. */
  43162. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  43163. /* Number of u32 values in hash table. */
  43164. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  43165. /* Maximum number of entries in hash table before
  43166. ** sub-dividing and re-hashing. */
  43167. #define BITVEC_MXHASH (BITVEC_NINT/2)
  43168. /* Hashing function for the aHash representation.
  43169. ** Empirical testing showed that the *37 multiplier
  43170. ** (an arbitrary prime)in the hash function provided
  43171. ** no fewer collisions than the no-op *1. */
  43172. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  43173. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  43174. /*
  43175. ** A bitmap is an instance of the following structure.
  43176. **
  43177. ** This bitmap records the existence of zero or more bits
  43178. ** with values between 1 and iSize, inclusive.
  43179. **
  43180. ** There are three possible representations of the bitmap.
  43181. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  43182. ** bitmap. The least significant bit is bit 1.
  43183. **
  43184. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  43185. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  43186. **
  43187. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  43188. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  43189. ** handles up to iDivisor separate values of i. apSub[0] holds
  43190. ** values between 1 and iDivisor. apSub[1] holds values between
  43191. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  43192. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  43193. ** to hold deal with values between 1 and iDivisor.
  43194. */
  43195. struct Bitvec {
  43196. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  43197. u32 nSet; /* Number of bits that are set - only valid for aHash
  43198. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  43199. ** this would be 125. */
  43200. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  43201. /* Should >=0 for apSub element. */
  43202. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  43203. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  43204. union {
  43205. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  43206. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  43207. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  43208. } u;
  43209. };
  43210. /*
  43211. ** Create a new bitmap object able to handle bits between 0 and iSize,
  43212. ** inclusive. Return a pointer to the new object. Return NULL if
  43213. ** malloc fails.
  43214. */
  43215. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  43216. Bitvec *p;
  43217. assert( sizeof(*p)==BITVEC_SZ );
  43218. p = sqlite3MallocZero( sizeof(*p) );
  43219. if( p ){
  43220. p->iSize = iSize;
  43221. }
  43222. return p;
  43223. }
  43224. /*
  43225. ** Check to see if the i-th bit is set. Return true or false.
  43226. ** If p is NULL (if the bitmap has not been created) or if
  43227. ** i is out of range, then return false.
  43228. */
  43229. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  43230. assert( p!=0 );
  43231. i--;
  43232. if( i>=p->iSize ) return 0;
  43233. while( p->iDivisor ){
  43234. u32 bin = i/p->iDivisor;
  43235. i = i%p->iDivisor;
  43236. p = p->u.apSub[bin];
  43237. if (!p) {
  43238. return 0;
  43239. }
  43240. }
  43241. if( p->iSize<=BITVEC_NBIT ){
  43242. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  43243. } else{
  43244. u32 h = BITVEC_HASH(i++);
  43245. while( p->u.aHash[h] ){
  43246. if( p->u.aHash[h]==i ) return 1;
  43247. h = (h+1) % BITVEC_NINT;
  43248. }
  43249. return 0;
  43250. }
  43251. }
  43252. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  43253. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  43254. }
  43255. /*
  43256. ** Set the i-th bit. Return 0 on success and an error code if
  43257. ** anything goes wrong.
  43258. **
  43259. ** This routine might cause sub-bitmaps to be allocated. Failing
  43260. ** to get the memory needed to hold the sub-bitmap is the only
  43261. ** that can go wrong with an insert, assuming p and i are valid.
  43262. **
  43263. ** The calling function must ensure that p is a valid Bitvec object
  43264. ** and that the value for "i" is within range of the Bitvec object.
  43265. ** Otherwise the behavior is undefined.
  43266. */
  43267. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  43268. u32 h;
  43269. if( p==0 ) return SQLITE_OK;
  43270. assert( i>0 );
  43271. assert( i<=p->iSize );
  43272. i--;
  43273. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  43274. u32 bin = i/p->iDivisor;
  43275. i = i%p->iDivisor;
  43276. if( p->u.apSub[bin]==0 ){
  43277. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  43278. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
  43279. }
  43280. p = p->u.apSub[bin];
  43281. }
  43282. if( p->iSize<=BITVEC_NBIT ){
  43283. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  43284. return SQLITE_OK;
  43285. }
  43286. h = BITVEC_HASH(i++);
  43287. /* if there wasn't a hash collision, and this doesn't */
  43288. /* completely fill the hash, then just add it without */
  43289. /* worring about sub-dividing and re-hashing. */
  43290. if( !p->u.aHash[h] ){
  43291. if (p->nSet<(BITVEC_NINT-1)) {
  43292. goto bitvec_set_end;
  43293. } else {
  43294. goto bitvec_set_rehash;
  43295. }
  43296. }
  43297. /* there was a collision, check to see if it's already */
  43298. /* in hash, if not, try to find a spot for it */
  43299. do {
  43300. if( p->u.aHash[h]==i ) return SQLITE_OK;
  43301. h++;
  43302. if( h>=BITVEC_NINT ) h = 0;
  43303. } while( p->u.aHash[h] );
  43304. /* we didn't find it in the hash. h points to the first */
  43305. /* available free spot. check to see if this is going to */
  43306. /* make our hash too "full". */
  43307. bitvec_set_rehash:
  43308. if( p->nSet>=BITVEC_MXHASH ){
  43309. unsigned int j;
  43310. int rc;
  43311. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  43312. if( aiValues==0 ){
  43313. return SQLITE_NOMEM_BKPT;
  43314. }else{
  43315. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  43316. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  43317. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  43318. rc = sqlite3BitvecSet(p, i);
  43319. for(j=0; j<BITVEC_NINT; j++){
  43320. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  43321. }
  43322. sqlite3StackFree(0, aiValues);
  43323. return rc;
  43324. }
  43325. }
  43326. bitvec_set_end:
  43327. p->nSet++;
  43328. p->u.aHash[h] = i;
  43329. return SQLITE_OK;
  43330. }
  43331. /*
  43332. ** Clear the i-th bit.
  43333. **
  43334. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  43335. ** that BitvecClear can use to rebuilt its hash table.
  43336. */
  43337. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  43338. if( p==0 ) return;
  43339. assert( i>0 );
  43340. i--;
  43341. while( p->iDivisor ){
  43342. u32 bin = i/p->iDivisor;
  43343. i = i%p->iDivisor;
  43344. p = p->u.apSub[bin];
  43345. if (!p) {
  43346. return;
  43347. }
  43348. }
  43349. if( p->iSize<=BITVEC_NBIT ){
  43350. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  43351. }else{
  43352. unsigned int j;
  43353. u32 *aiValues = pBuf;
  43354. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  43355. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  43356. p->nSet = 0;
  43357. for(j=0; j<BITVEC_NINT; j++){
  43358. if( aiValues[j] && aiValues[j]!=(i+1) ){
  43359. u32 h = BITVEC_HASH(aiValues[j]-1);
  43360. p->nSet++;
  43361. while( p->u.aHash[h] ){
  43362. h++;
  43363. if( h>=BITVEC_NINT ) h = 0;
  43364. }
  43365. p->u.aHash[h] = aiValues[j];
  43366. }
  43367. }
  43368. }
  43369. }
  43370. /*
  43371. ** Destroy a bitmap object. Reclaim all memory used.
  43372. */
  43373. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  43374. if( p==0 ) return;
  43375. if( p->iDivisor ){
  43376. unsigned int i;
  43377. for(i=0; i<BITVEC_NPTR; i++){
  43378. sqlite3BitvecDestroy(p->u.apSub[i]);
  43379. }
  43380. }
  43381. sqlite3_free(p);
  43382. }
  43383. /*
  43384. ** Return the value of the iSize parameter specified when Bitvec *p
  43385. ** was created.
  43386. */
  43387. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  43388. return p->iSize;
  43389. }
  43390. #ifndef SQLITE_UNTESTABLE
  43391. /*
  43392. ** Let V[] be an array of unsigned characters sufficient to hold
  43393. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  43394. ** Then the following macros can be used to set, clear, or test
  43395. ** individual bits within V.
  43396. */
  43397. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  43398. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  43399. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  43400. /*
  43401. ** This routine runs an extensive test of the Bitvec code.
  43402. **
  43403. ** The input is an array of integers that acts as a program
  43404. ** to test the Bitvec. The integers are opcodes followed
  43405. ** by 0, 1, or 3 operands, depending on the opcode. Another
  43406. ** opcode follows immediately after the last operand.
  43407. **
  43408. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  43409. ** "halt" opcode and causes the test to end.
  43410. **
  43411. ** 0 Halt and return the number of errors
  43412. ** 1 N S X Set N bits beginning with S and incrementing by X
  43413. ** 2 N S X Clear N bits beginning with S and incrementing by X
  43414. ** 3 N Set N randomly chosen bits
  43415. ** 4 N Clear N randomly chosen bits
  43416. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  43417. **
  43418. ** The opcodes 1 through 4 perform set and clear operations are performed
  43419. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  43420. ** Opcode 5 works on the linear array only, not on the Bitvec.
  43421. ** Opcode 5 is used to deliberately induce a fault in order to
  43422. ** confirm that error detection works.
  43423. **
  43424. ** At the conclusion of the test the linear array is compared
  43425. ** against the Bitvec object. If there are any differences,
  43426. ** an error is returned. If they are the same, zero is returned.
  43427. **
  43428. ** If a memory allocation error occurs, return -1.
  43429. */
  43430. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  43431. Bitvec *pBitvec = 0;
  43432. unsigned char *pV = 0;
  43433. int rc = -1;
  43434. int i, nx, pc, op;
  43435. void *pTmpSpace;
  43436. /* Allocate the Bitvec to be tested and a linear array of
  43437. ** bits to act as the reference */
  43438. pBitvec = sqlite3BitvecCreate( sz );
  43439. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  43440. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  43441. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  43442. /* NULL pBitvec tests */
  43443. sqlite3BitvecSet(0, 1);
  43444. sqlite3BitvecClear(0, 1, pTmpSpace);
  43445. /* Run the program */
  43446. pc = 0;
  43447. while( (op = aOp[pc])!=0 ){
  43448. switch( op ){
  43449. case 1:
  43450. case 2:
  43451. case 5: {
  43452. nx = 4;
  43453. i = aOp[pc+2] - 1;
  43454. aOp[pc+2] += aOp[pc+3];
  43455. break;
  43456. }
  43457. case 3:
  43458. case 4:
  43459. default: {
  43460. nx = 2;
  43461. sqlite3_randomness(sizeof(i), &i);
  43462. break;
  43463. }
  43464. }
  43465. if( (--aOp[pc+1]) > 0 ) nx = 0;
  43466. pc += nx;
  43467. i = (i & 0x7fffffff)%sz;
  43468. if( (op & 1)!=0 ){
  43469. SETBIT(pV, (i+1));
  43470. if( op!=5 ){
  43471. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  43472. }
  43473. }else{
  43474. CLEARBIT(pV, (i+1));
  43475. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  43476. }
  43477. }
  43478. /* Test to make sure the linear array exactly matches the
  43479. ** Bitvec object. Start with the assumption that they do
  43480. ** match (rc==0). Change rc to non-zero if a discrepancy
  43481. ** is found.
  43482. */
  43483. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  43484. + sqlite3BitvecTest(pBitvec, 0)
  43485. + (sqlite3BitvecSize(pBitvec) - sz);
  43486. for(i=1; i<=sz; i++){
  43487. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  43488. rc = i;
  43489. break;
  43490. }
  43491. }
  43492. /* Free allocated structure */
  43493. bitvec_end:
  43494. sqlite3_free(pTmpSpace);
  43495. sqlite3_free(pV);
  43496. sqlite3BitvecDestroy(pBitvec);
  43497. return rc;
  43498. }
  43499. #endif /* SQLITE_UNTESTABLE */
  43500. /************** End of bitvec.c **********************************************/
  43501. /************** Begin file pcache.c ******************************************/
  43502. /*
  43503. ** 2008 August 05
  43504. **
  43505. ** The author disclaims copyright to this source code. In place of
  43506. ** a legal notice, here is a blessing:
  43507. **
  43508. ** May you do good and not evil.
  43509. ** May you find forgiveness for yourself and forgive others.
  43510. ** May you share freely, never taking more than you give.
  43511. **
  43512. *************************************************************************
  43513. ** This file implements that page cache.
  43514. */
  43515. /* #include "sqliteInt.h" */
  43516. /*
  43517. ** A complete page cache is an instance of this structure. Every
  43518. ** entry in the cache holds a single page of the database file. The
  43519. ** btree layer only operates on the cached copy of the database pages.
  43520. **
  43521. ** A page cache entry is "clean" if it exactly matches what is currently
  43522. ** on disk. A page is "dirty" if it has been modified and needs to be
  43523. ** persisted to disk.
  43524. **
  43525. ** pDirty, pDirtyTail, pSynced:
  43526. ** All dirty pages are linked into the doubly linked list using
  43527. ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
  43528. ** such that p was added to the list more recently than p->pDirtyNext.
  43529. ** PCache.pDirty points to the first (newest) element in the list and
  43530. ** pDirtyTail to the last (oldest).
  43531. **
  43532. ** The PCache.pSynced variable is used to optimize searching for a dirty
  43533. ** page to eject from the cache mid-transaction. It is better to eject
  43534. ** a page that does not require a journal sync than one that does.
  43535. ** Therefore, pSynced is maintained to that it *almost* always points
  43536. ** to either the oldest page in the pDirty/pDirtyTail list that has a
  43537. ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
  43538. ** (so that the right page to eject can be found by following pDirtyPrev
  43539. ** pointers).
  43540. */
  43541. struct PCache {
  43542. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  43543. PgHdr *pSynced; /* Last synced page in dirty page list */
  43544. int nRefSum; /* Sum of ref counts over all pages */
  43545. int szCache; /* Configured cache size */
  43546. int szSpill; /* Size before spilling occurs */
  43547. int szPage; /* Size of every page in this cache */
  43548. int szExtra; /* Size of extra space for each page */
  43549. u8 bPurgeable; /* True if pages are on backing store */
  43550. u8 eCreate; /* eCreate value for for xFetch() */
  43551. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  43552. void *pStress; /* Argument to xStress */
  43553. sqlite3_pcache *pCache; /* Pluggable cache module */
  43554. };
  43555. /********************************** Test and Debug Logic **********************/
  43556. /*
  43557. ** Debug tracing macros. Enable by by changing the "0" to "1" and
  43558. ** recompiling.
  43559. **
  43560. ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
  43561. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
  43562. ** is displayed for many operations, resulting in a lot of output.
  43563. */
  43564. #if defined(SQLITE_DEBUG) && 0
  43565. int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
  43566. int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
  43567. # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  43568. void pcacheDump(PCache *pCache){
  43569. int N;
  43570. int i, j;
  43571. sqlite3_pcache_page *pLower;
  43572. PgHdr *pPg;
  43573. unsigned char *a;
  43574. if( sqlite3PcacheTrace<2 ) return;
  43575. if( pCache->pCache==0 ) return;
  43576. N = sqlite3PcachePagecount(pCache);
  43577. if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
  43578. for(i=1; i<=N; i++){
  43579. pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
  43580. if( pLower==0 ) continue;
  43581. pPg = (PgHdr*)pLower->pExtra;
  43582. printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
  43583. a = (unsigned char *)pLower->pBuf;
  43584. for(j=0; j<12; j++) printf("%02x", a[j]);
  43585. printf("\n");
  43586. if( pPg->pPage==0 ){
  43587. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
  43588. }
  43589. }
  43590. }
  43591. #else
  43592. # define pcacheTrace(X)
  43593. # define pcacheDump(X)
  43594. #endif
  43595. /*
  43596. ** Check invariants on a PgHdr entry. Return true if everything is OK.
  43597. ** Return false if any invariant is violated.
  43598. **
  43599. ** This routine is for use inside of assert() statements only. For
  43600. ** example:
  43601. **
  43602. ** assert( sqlite3PcachePageSanity(pPg) );
  43603. */
  43604. #ifdef SQLITE_DEBUG
  43605. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
  43606. PCache *pCache;
  43607. assert( pPg!=0 );
  43608. assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
  43609. pCache = pPg->pCache;
  43610. assert( pCache!=0 ); /* Every page has an associated PCache */
  43611. if( pPg->flags & PGHDR_CLEAN ){
  43612. assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
  43613. assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
  43614. assert( pCache->pDirtyTail!=pPg );
  43615. }
  43616. /* WRITEABLE pages must also be DIRTY */
  43617. if( pPg->flags & PGHDR_WRITEABLE ){
  43618. assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
  43619. }
  43620. /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
  43621. ** for example, when using the sqlite3PagerDontWrite() optimization:
  43622. ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
  43623. ** (2) Page X moved to freelist, WRITEABLE is cleared
  43624. ** (3) Page X reused, WRITEABLE is set again
  43625. ** If NEED_SYNC had been cleared in step 2, then it would not be reset
  43626. ** in step 3, and page might be written into the database without first
  43627. ** syncing the rollback journal, which might cause corruption on a power
  43628. ** loss.
  43629. **
  43630. ** Another example is when the database page size is smaller than the
  43631. ** disk sector size. When any page of a sector is journalled, all pages
  43632. ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
  43633. ** in case they are later modified, since all pages in the same sector
  43634. ** must be journalled and synced before any of those pages can be safely
  43635. ** written.
  43636. */
  43637. return 1;
  43638. }
  43639. #endif /* SQLITE_DEBUG */
  43640. /********************************** Linked List Management ********************/
  43641. /* Allowed values for second argument to pcacheManageDirtyList() */
  43642. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  43643. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  43644. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  43645. /*
  43646. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  43647. ** argument determines what operation to do. The 0x01 bit means first
  43648. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  43649. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  43650. */
  43651. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  43652. PCache *p = pPage->pCache;
  43653. pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
  43654. addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
  43655. pPage->pgno));
  43656. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  43657. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  43658. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  43659. /* Update the PCache1.pSynced variable if necessary. */
  43660. if( p->pSynced==pPage ){
  43661. p->pSynced = pPage->pDirtyPrev;
  43662. }
  43663. if( pPage->pDirtyNext ){
  43664. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  43665. }else{
  43666. assert( pPage==p->pDirtyTail );
  43667. p->pDirtyTail = pPage->pDirtyPrev;
  43668. }
  43669. if( pPage->pDirtyPrev ){
  43670. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  43671. }else{
  43672. /* If there are now no dirty pages in the cache, set eCreate to 2.
  43673. ** This is an optimization that allows sqlite3PcacheFetch() to skip
  43674. ** searching for a dirty page to eject from the cache when it might
  43675. ** otherwise have to. */
  43676. assert( pPage==p->pDirty );
  43677. p->pDirty = pPage->pDirtyNext;
  43678. assert( p->bPurgeable || p->eCreate==2 );
  43679. if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
  43680. assert( p->bPurgeable==0 || p->eCreate==1 );
  43681. p->eCreate = 2;
  43682. }
  43683. }
  43684. }
  43685. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  43686. pPage->pDirtyPrev = 0;
  43687. pPage->pDirtyNext = p->pDirty;
  43688. if( pPage->pDirtyNext ){
  43689. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  43690. pPage->pDirtyNext->pDirtyPrev = pPage;
  43691. }else{
  43692. p->pDirtyTail = pPage;
  43693. if( p->bPurgeable ){
  43694. assert( p->eCreate==2 );
  43695. p->eCreate = 1;
  43696. }
  43697. }
  43698. p->pDirty = pPage;
  43699. /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
  43700. ** pSynced to point to it. Checking the NEED_SYNC flag is an
  43701. ** optimization, as if pSynced points to a page with the NEED_SYNC
  43702. ** flag set sqlite3PcacheFetchStress() searches through all newer
  43703. ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
  43704. if( !p->pSynced
  43705. && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
  43706. ){
  43707. p->pSynced = pPage;
  43708. }
  43709. }
  43710. pcacheDump(p);
  43711. }
  43712. /*
  43713. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  43714. ** being used for an in-memory database, this function is a no-op.
  43715. */
  43716. static void pcacheUnpin(PgHdr *p){
  43717. if( p->pCache->bPurgeable ){
  43718. pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
  43719. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  43720. pcacheDump(p->pCache);
  43721. }
  43722. }
  43723. /*
  43724. ** Compute the number of pages of cache requested. p->szCache is the
  43725. ** cache size requested by the "PRAGMA cache_size" statement.
  43726. */
  43727. static int numberOfCachePages(PCache *p){
  43728. if( p->szCache>=0 ){
  43729. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  43730. ** suggested cache size is set to N. */
  43731. return p->szCache;
  43732. }else{
  43733. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  43734. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  43735. ** bytes of memory. */
  43736. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  43737. }
  43738. }
  43739. /*************************************************** General Interfaces ******
  43740. **
  43741. ** Initialize and shutdown the page cache subsystem. Neither of these
  43742. ** functions are threadsafe.
  43743. */
  43744. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  43745. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  43746. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  43747. ** built-in default page cache is used instead of the application defined
  43748. ** page cache. */
  43749. sqlite3PCacheSetDefault();
  43750. }
  43751. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  43752. }
  43753. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  43754. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  43755. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  43756. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  43757. }
  43758. }
  43759. /*
  43760. ** Return the size in bytes of a PCache object.
  43761. */
  43762. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  43763. /*
  43764. ** Create a new PCache object. Storage space to hold the object
  43765. ** has already been allocated and is passed in as the p pointer.
  43766. ** The caller discovers how much space needs to be allocated by
  43767. ** calling sqlite3PcacheSize().
  43768. **
  43769. ** szExtra is some extra space allocated for each page. The first
  43770. ** 8 bytes of the extra space will be zeroed as the page is allocated,
  43771. ** but remaining content will be uninitialized. Though it is opaque
  43772. ** to this module, the extra space really ends up being the MemPage
  43773. ** structure in the pager.
  43774. */
  43775. SQLITE_PRIVATE int sqlite3PcacheOpen(
  43776. int szPage, /* Size of every page */
  43777. int szExtra, /* Extra space associated with each page */
  43778. int bPurgeable, /* True if pages are on backing store */
  43779. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  43780. void *pStress, /* Argument to xStress */
  43781. PCache *p /* Preallocated space for the PCache */
  43782. ){
  43783. memset(p, 0, sizeof(PCache));
  43784. p->szPage = 1;
  43785. p->szExtra = szExtra;
  43786. assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
  43787. p->bPurgeable = bPurgeable;
  43788. p->eCreate = 2;
  43789. p->xStress = xStress;
  43790. p->pStress = pStress;
  43791. p->szCache = 100;
  43792. p->szSpill = 1;
  43793. pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
  43794. return sqlite3PcacheSetPageSize(p, szPage);
  43795. }
  43796. /*
  43797. ** Change the page size for PCache object. The caller must ensure that there
  43798. ** are no outstanding page references when this function is called.
  43799. */
  43800. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  43801. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  43802. if( pCache->szPage ){
  43803. sqlite3_pcache *pNew;
  43804. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  43805. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  43806. pCache->bPurgeable
  43807. );
  43808. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  43809. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  43810. if( pCache->pCache ){
  43811. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  43812. }
  43813. pCache->pCache = pNew;
  43814. pCache->szPage = szPage;
  43815. pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
  43816. }
  43817. return SQLITE_OK;
  43818. }
  43819. /*
  43820. ** Try to obtain a page from the cache.
  43821. **
  43822. ** This routine returns a pointer to an sqlite3_pcache_page object if
  43823. ** such an object is already in cache, or if a new one is created.
  43824. ** This routine returns a NULL pointer if the object was not in cache
  43825. ** and could not be created.
  43826. **
  43827. ** The createFlags should be 0 to check for existing pages and should
  43828. ** be 3 (not 1, but 3) to try to create a new page.
  43829. **
  43830. ** If the createFlag is 0, then NULL is always returned if the page
  43831. ** is not already in the cache. If createFlag is 1, then a new page
  43832. ** is created only if that can be done without spilling dirty pages
  43833. ** and without exceeding the cache size limit.
  43834. **
  43835. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  43836. ** initialize the sqlite3_pcache_page object and convert it into a
  43837. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  43838. ** routines are split this way for performance reasons. When separated
  43839. ** they can both (usually) operate without having to push values to
  43840. ** the stack on entry and pop them back off on exit, which saves a
  43841. ** lot of pushing and popping.
  43842. */
  43843. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  43844. PCache *pCache, /* Obtain the page from this cache */
  43845. Pgno pgno, /* Page number to obtain */
  43846. int createFlag /* If true, create page if it does not exist already */
  43847. ){
  43848. int eCreate;
  43849. sqlite3_pcache_page *pRes;
  43850. assert( pCache!=0 );
  43851. assert( pCache->pCache!=0 );
  43852. assert( createFlag==3 || createFlag==0 );
  43853. assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
  43854. /* eCreate defines what to do if the page does not exist.
  43855. ** 0 Do not allocate a new page. (createFlag==0)
  43856. ** 1 Allocate a new page if doing so is inexpensive.
  43857. ** (createFlag==1 AND bPurgeable AND pDirty)
  43858. ** 2 Allocate a new page even it doing so is difficult.
  43859. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  43860. */
  43861. eCreate = createFlag & pCache->eCreate;
  43862. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  43863. assert( createFlag==0 || pCache->eCreate==eCreate );
  43864. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  43865. pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  43866. pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
  43867. createFlag?" create":"",pRes));
  43868. return pRes;
  43869. }
  43870. /*
  43871. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  43872. ** page because no clean pages are available for reuse and the cache
  43873. ** size limit has been reached, then this routine can be invoked to
  43874. ** try harder to allocate a page. This routine might invoke the stress
  43875. ** callback to spill dirty pages to the journal. It will then try to
  43876. ** allocate the new page and will only fail to allocate a new page on
  43877. ** an OOM error.
  43878. **
  43879. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  43880. */
  43881. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  43882. PCache *pCache, /* Obtain the page from this cache */
  43883. Pgno pgno, /* Page number to obtain */
  43884. sqlite3_pcache_page **ppPage /* Write result here */
  43885. ){
  43886. PgHdr *pPg;
  43887. if( pCache->eCreate==2 ) return 0;
  43888. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  43889. /* Find a dirty page to write-out and recycle. First try to find a
  43890. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  43891. ** cleared), but if that is not possible settle for any other
  43892. ** unreferenced dirty page.
  43893. **
  43894. ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
  43895. ** flag is currently referenced, then the following may leave pSynced
  43896. ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
  43897. ** cleared). This is Ok, as pSynced is just an optimization. */
  43898. for(pPg=pCache->pSynced;
  43899. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  43900. pPg=pPg->pDirtyPrev
  43901. );
  43902. pCache->pSynced = pPg;
  43903. if( !pPg ){
  43904. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  43905. }
  43906. if( pPg ){
  43907. int rc;
  43908. #ifdef SQLITE_LOG_CACHE_SPILL
  43909. sqlite3_log(SQLITE_FULL,
  43910. "spill page %d making room for %d - cache used: %d/%d",
  43911. pPg->pgno, pgno,
  43912. sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
  43913. numberOfCachePages(pCache));
  43914. #endif
  43915. pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
  43916. rc = pCache->xStress(pCache->pStress, pPg);
  43917. pcacheDump(pCache);
  43918. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  43919. return rc;
  43920. }
  43921. }
  43922. }
  43923. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  43924. return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  43925. }
  43926. /*
  43927. ** This is a helper routine for sqlite3PcacheFetchFinish()
  43928. **
  43929. ** In the uncommon case where the page being fetched has not been
  43930. ** initialized, this routine is invoked to do the initialization.
  43931. ** This routine is broken out into a separate function since it
  43932. ** requires extra stack manipulation that can be avoided in the common
  43933. ** case.
  43934. */
  43935. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  43936. PCache *pCache, /* Obtain the page from this cache */
  43937. Pgno pgno, /* Page number obtained */
  43938. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  43939. ){
  43940. PgHdr *pPgHdr;
  43941. assert( pPage!=0 );
  43942. pPgHdr = (PgHdr*)pPage->pExtra;
  43943. assert( pPgHdr->pPage==0 );
  43944. memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
  43945. pPgHdr->pPage = pPage;
  43946. pPgHdr->pData = pPage->pBuf;
  43947. pPgHdr->pExtra = (void *)&pPgHdr[1];
  43948. memset(pPgHdr->pExtra, 0, 8);
  43949. pPgHdr->pCache = pCache;
  43950. pPgHdr->pgno = pgno;
  43951. pPgHdr->flags = PGHDR_CLEAN;
  43952. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  43953. }
  43954. /*
  43955. ** This routine converts the sqlite3_pcache_page object returned by
  43956. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  43957. ** must be called after sqlite3PcacheFetch() in order to get a usable
  43958. ** result.
  43959. */
  43960. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  43961. PCache *pCache, /* Obtain the page from this cache */
  43962. Pgno pgno, /* Page number obtained */
  43963. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  43964. ){
  43965. PgHdr *pPgHdr;
  43966. assert( pPage!=0 );
  43967. pPgHdr = (PgHdr *)pPage->pExtra;
  43968. if( !pPgHdr->pPage ){
  43969. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  43970. }
  43971. pCache->nRefSum++;
  43972. pPgHdr->nRef++;
  43973. assert( sqlite3PcachePageSanity(pPgHdr) );
  43974. return pPgHdr;
  43975. }
  43976. /*
  43977. ** Decrement the reference count on a page. If the page is clean and the
  43978. ** reference count drops to 0, then it is made eligible for recycling.
  43979. */
  43980. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  43981. assert( p->nRef>0 );
  43982. p->pCache->nRefSum--;
  43983. if( (--p->nRef)==0 ){
  43984. if( p->flags&PGHDR_CLEAN ){
  43985. pcacheUnpin(p);
  43986. }else{
  43987. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  43988. }
  43989. }
  43990. }
  43991. /*
  43992. ** Increase the reference count of a supplied page by 1.
  43993. */
  43994. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  43995. assert(p->nRef>0);
  43996. assert( sqlite3PcachePageSanity(p) );
  43997. p->nRef++;
  43998. p->pCache->nRefSum++;
  43999. }
  44000. /*
  44001. ** Drop a page from the cache. There must be exactly one reference to the
  44002. ** page. This function deletes that reference, so after it returns the
  44003. ** page pointed to by p is invalid.
  44004. */
  44005. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  44006. assert( p->nRef==1 );
  44007. assert( sqlite3PcachePageSanity(p) );
  44008. if( p->flags&PGHDR_DIRTY ){
  44009. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  44010. }
  44011. p->pCache->nRefSum--;
  44012. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  44013. }
  44014. /*
  44015. ** Make sure the page is marked as dirty. If it isn't dirty already,
  44016. ** make it so.
  44017. */
  44018. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  44019. assert( p->nRef>0 );
  44020. assert( sqlite3PcachePageSanity(p) );
  44021. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
  44022. p->flags &= ~PGHDR_DONT_WRITE;
  44023. if( p->flags & PGHDR_CLEAN ){
  44024. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  44025. pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
  44026. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  44027. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  44028. }
  44029. assert( sqlite3PcachePageSanity(p) );
  44030. }
  44031. }
  44032. /*
  44033. ** Make sure the page is marked as clean. If it isn't clean already,
  44034. ** make it so.
  44035. */
  44036. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  44037. assert( sqlite3PcachePageSanity(p) );
  44038. assert( (p->flags & PGHDR_DIRTY)!=0 );
  44039. assert( (p->flags & PGHDR_CLEAN)==0 );
  44040. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  44041. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  44042. p->flags |= PGHDR_CLEAN;
  44043. pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
  44044. assert( sqlite3PcachePageSanity(p) );
  44045. if( p->nRef==0 ){
  44046. pcacheUnpin(p);
  44047. }
  44048. }
  44049. /*
  44050. ** Make every page in the cache clean.
  44051. */
  44052. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  44053. PgHdr *p;
  44054. pcacheTrace(("%p.CLEAN-ALL\n",pCache));
  44055. while( (p = pCache->pDirty)!=0 ){
  44056. sqlite3PcacheMakeClean(p);
  44057. }
  44058. }
  44059. /*
  44060. ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
  44061. */
  44062. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
  44063. PgHdr *p;
  44064. pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
  44065. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  44066. p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  44067. }
  44068. pCache->pSynced = pCache->pDirtyTail;
  44069. }
  44070. /*
  44071. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  44072. */
  44073. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  44074. PgHdr *p;
  44075. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  44076. p->flags &= ~PGHDR_NEED_SYNC;
  44077. }
  44078. pCache->pSynced = pCache->pDirtyTail;
  44079. }
  44080. /*
  44081. ** Change the page number of page p to newPgno.
  44082. */
  44083. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  44084. PCache *pCache = p->pCache;
  44085. assert( p->nRef>0 );
  44086. assert( newPgno>0 );
  44087. assert( sqlite3PcachePageSanity(p) );
  44088. pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
  44089. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  44090. p->pgno = newPgno;
  44091. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  44092. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  44093. }
  44094. }
  44095. /*
  44096. ** Drop every cache entry whose page number is greater than "pgno". The
  44097. ** caller must ensure that there are no outstanding references to any pages
  44098. ** other than page 1 with a page number greater than pgno.
  44099. **
  44100. ** If there is a reference to page 1 and the pgno parameter passed to this
  44101. ** function is 0, then the data area associated with page 1 is zeroed, but
  44102. ** the page object is not dropped.
  44103. */
  44104. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  44105. if( pCache->pCache ){
  44106. PgHdr *p;
  44107. PgHdr *pNext;
  44108. pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
  44109. for(p=pCache->pDirty; p; p=pNext){
  44110. pNext = p->pDirtyNext;
  44111. /* This routine never gets call with a positive pgno except right
  44112. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  44113. ** it must be that pgno==0.
  44114. */
  44115. assert( p->pgno>0 );
  44116. if( p->pgno>pgno ){
  44117. assert( p->flags&PGHDR_DIRTY );
  44118. sqlite3PcacheMakeClean(p);
  44119. }
  44120. }
  44121. if( pgno==0 && pCache->nRefSum ){
  44122. sqlite3_pcache_page *pPage1;
  44123. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  44124. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  44125. ** pCache->nRefSum>0 */
  44126. memset(pPage1->pBuf, 0, pCache->szPage);
  44127. pgno = 1;
  44128. }
  44129. }
  44130. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  44131. }
  44132. }
  44133. /*
  44134. ** Close a cache.
  44135. */
  44136. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  44137. assert( pCache->pCache!=0 );
  44138. pcacheTrace(("%p.CLOSE\n",pCache));
  44139. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  44140. }
  44141. /*
  44142. ** Discard the contents of the cache.
  44143. */
  44144. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  44145. sqlite3PcacheTruncate(pCache, 0);
  44146. }
  44147. /*
  44148. ** Merge two lists of pages connected by pDirty and in pgno order.
  44149. ** Do not bother fixing the pDirtyPrev pointers.
  44150. */
  44151. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  44152. PgHdr result, *pTail;
  44153. pTail = &result;
  44154. assert( pA!=0 && pB!=0 );
  44155. for(;;){
  44156. if( pA->pgno<pB->pgno ){
  44157. pTail->pDirty = pA;
  44158. pTail = pA;
  44159. pA = pA->pDirty;
  44160. if( pA==0 ){
  44161. pTail->pDirty = pB;
  44162. break;
  44163. }
  44164. }else{
  44165. pTail->pDirty = pB;
  44166. pTail = pB;
  44167. pB = pB->pDirty;
  44168. if( pB==0 ){
  44169. pTail->pDirty = pA;
  44170. break;
  44171. }
  44172. }
  44173. }
  44174. return result.pDirty;
  44175. }
  44176. /*
  44177. ** Sort the list of pages in accending order by pgno. Pages are
  44178. ** connected by pDirty pointers. The pDirtyPrev pointers are
  44179. ** corrupted by this sort.
  44180. **
  44181. ** Since there cannot be more than 2^31 distinct pages in a database,
  44182. ** there cannot be more than 31 buckets required by the merge sorter.
  44183. ** One extra bucket is added to catch overflow in case something
  44184. ** ever changes to make the previous sentence incorrect.
  44185. */
  44186. #define N_SORT_BUCKET 32
  44187. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  44188. PgHdr *a[N_SORT_BUCKET], *p;
  44189. int i;
  44190. memset(a, 0, sizeof(a));
  44191. while( pIn ){
  44192. p = pIn;
  44193. pIn = p->pDirty;
  44194. p->pDirty = 0;
  44195. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  44196. if( a[i]==0 ){
  44197. a[i] = p;
  44198. break;
  44199. }else{
  44200. p = pcacheMergeDirtyList(a[i], p);
  44201. a[i] = 0;
  44202. }
  44203. }
  44204. if( NEVER(i==N_SORT_BUCKET-1) ){
  44205. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  44206. ** the input list. But that is impossible.
  44207. */
  44208. a[i] = pcacheMergeDirtyList(a[i], p);
  44209. }
  44210. }
  44211. p = a[0];
  44212. for(i=1; i<N_SORT_BUCKET; i++){
  44213. if( a[i]==0 ) continue;
  44214. p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
  44215. }
  44216. return p;
  44217. }
  44218. /*
  44219. ** Return a list of all dirty pages in the cache, sorted by page number.
  44220. */
  44221. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  44222. PgHdr *p;
  44223. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  44224. p->pDirty = p->pDirtyNext;
  44225. }
  44226. return pcacheSortDirtyList(pCache->pDirty);
  44227. }
  44228. /*
  44229. ** Return the total number of references to all pages held by the cache.
  44230. **
  44231. ** This is not the total number of pages referenced, but the sum of the
  44232. ** reference count for all pages.
  44233. */
  44234. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  44235. return pCache->nRefSum;
  44236. }
  44237. /*
  44238. ** Return the number of references to the page supplied as an argument.
  44239. */
  44240. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  44241. return p->nRef;
  44242. }
  44243. /*
  44244. ** Return the total number of pages in the cache.
  44245. */
  44246. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  44247. assert( pCache->pCache!=0 );
  44248. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  44249. }
  44250. #ifdef SQLITE_TEST
  44251. /*
  44252. ** Get the suggested cache-size value.
  44253. */
  44254. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  44255. return numberOfCachePages(pCache);
  44256. }
  44257. #endif
  44258. /*
  44259. ** Set the suggested cache-size value.
  44260. */
  44261. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  44262. assert( pCache->pCache!=0 );
  44263. pCache->szCache = mxPage;
  44264. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  44265. numberOfCachePages(pCache));
  44266. }
  44267. /*
  44268. ** Set the suggested cache-spill value. Make no changes if if the
  44269. ** argument is zero. Return the effective cache-spill size, which will
  44270. ** be the larger of the szSpill and szCache.
  44271. */
  44272. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  44273. int res;
  44274. assert( p->pCache!=0 );
  44275. if( mxPage ){
  44276. if( mxPage<0 ){
  44277. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  44278. }
  44279. p->szSpill = mxPage;
  44280. }
  44281. res = numberOfCachePages(p);
  44282. if( res<p->szSpill ) res = p->szSpill;
  44283. return res;
  44284. }
  44285. /*
  44286. ** Free up as much memory as possible from the page cache.
  44287. */
  44288. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  44289. assert( pCache->pCache!=0 );
  44290. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  44291. }
  44292. /*
  44293. ** Return the size of the header added by this middleware layer
  44294. ** in the page-cache hierarchy.
  44295. */
  44296. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  44297. /*
  44298. ** Return the number of dirty pages currently in the cache, as a percentage
  44299. ** of the configured cache size.
  44300. */
  44301. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
  44302. PgHdr *pDirty;
  44303. int nDirty = 0;
  44304. int nCache = numberOfCachePages(pCache);
  44305. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
  44306. return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
  44307. }
  44308. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  44309. /*
  44310. ** For all dirty pages currently in the cache, invoke the specified
  44311. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  44312. ** defined.
  44313. */
  44314. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  44315. PgHdr *pDirty;
  44316. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  44317. xIter(pDirty);
  44318. }
  44319. }
  44320. #endif
  44321. /************** End of pcache.c **********************************************/
  44322. /************** Begin file pcache1.c *****************************************/
  44323. /*
  44324. ** 2008 November 05
  44325. **
  44326. ** The author disclaims copyright to this source code. In place of
  44327. ** a legal notice, here is a blessing:
  44328. **
  44329. ** May you do good and not evil.
  44330. ** May you find forgiveness for yourself and forgive others.
  44331. ** May you share freely, never taking more than you give.
  44332. **
  44333. *************************************************************************
  44334. **
  44335. ** This file implements the default page cache implementation (the
  44336. ** sqlite3_pcache interface). It also contains part of the implementation
  44337. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  44338. ** If the default page cache implementation is overridden, then neither of
  44339. ** these two features are available.
  44340. **
  44341. ** A Page cache line looks like this:
  44342. **
  44343. ** -------------------------------------------------------------
  44344. ** | database page content | PgHdr1 | MemPage | PgHdr |
  44345. ** -------------------------------------------------------------
  44346. **
  44347. ** The database page content is up front (so that buffer overreads tend to
  44348. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  44349. ** is the extension added by the btree.c module containing information such
  44350. ** as the database page number and how that database page is used. PgHdr
  44351. ** is added by the pcache.c layer and contains information used to keep track
  44352. ** of which pages are "dirty". PgHdr1 is an extension added by this
  44353. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  44354. ** PgHdr1 contains information needed to look up a page by its page number.
  44355. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  44356. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  44357. **
  44358. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  44359. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  44360. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  44361. ** size can vary according to architecture, compile-time options, and
  44362. ** SQLite library version number.
  44363. **
  44364. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  44365. ** using a separate memory allocation from the database page content. This
  44366. ** seeks to overcome the "clownshoe" problem (also called "internal
  44367. ** fragmentation" in academic literature) of allocating a few bytes more
  44368. ** than a power of two with the memory allocator rounding up to the next
  44369. ** power of two, and leaving the rounded-up space unused.
  44370. **
  44371. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  44372. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  44373. **
  44374. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  44375. ** The btree.c module deals with pointers to MemPage objects.
  44376. **
  44377. ** SOURCE OF PAGE CACHE MEMORY:
  44378. **
  44379. ** Memory for a page might come from any of three sources:
  44380. **
  44381. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  44382. ** (2) Global page-cache memory provided using sqlite3_config() with
  44383. ** SQLITE_CONFIG_PAGECACHE.
  44384. ** (3) PCache-local bulk allocation.
  44385. **
  44386. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  44387. ** that is allocated when the page cache is created. The size of the local
  44388. ** bulk allocation can be adjusted using
  44389. **
  44390. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  44391. **
  44392. ** If N is positive, then N pages worth of memory are allocated using a single
  44393. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  44394. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  44395. ** for as many pages as can be accomodated.
  44396. **
  44397. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  44398. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  44399. ** memory allocator (1).
  44400. **
  44401. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  44402. ** show that method (3) with N==100 provides about a 5% performance boost for
  44403. ** common workloads.
  44404. */
  44405. /* #include "sqliteInt.h" */
  44406. typedef struct PCache1 PCache1;
  44407. typedef struct PgHdr1 PgHdr1;
  44408. typedef struct PgFreeslot PgFreeslot;
  44409. typedef struct PGroup PGroup;
  44410. /*
  44411. ** Each cache entry is represented by an instance of the following
  44412. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  44413. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  44414. ** in memory.
  44415. */
  44416. struct PgHdr1 {
  44417. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  44418. unsigned int iKey; /* Key value (page number) */
  44419. u8 isBulkLocal; /* This page from bulk local storage */
  44420. u8 isAnchor; /* This is the PGroup.lru element */
  44421. PgHdr1 *pNext; /* Next in hash table chain */
  44422. PCache1 *pCache; /* Cache that currently owns this page */
  44423. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  44424. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  44425. };
  44426. /*
  44427. ** A page is pinned if it is no on the LRU list
  44428. */
  44429. #define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
  44430. #define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
  44431. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  44432. ** of one or more PCaches that are able to recycle each other's unpinned
  44433. ** pages when they are under memory pressure. A PGroup is an instance of
  44434. ** the following object.
  44435. **
  44436. ** This page cache implementation works in one of two modes:
  44437. **
  44438. ** (1) Every PCache is the sole member of its own PGroup. There is
  44439. ** one PGroup per PCache.
  44440. **
  44441. ** (2) There is a single global PGroup that all PCaches are a member
  44442. ** of.
  44443. **
  44444. ** Mode 1 uses more memory (since PCache instances are not able to rob
  44445. ** unused pages from other PCaches) but it also operates without a mutex,
  44446. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  44447. ** threadsafe, but recycles pages more efficiently.
  44448. **
  44449. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  44450. ** PGroup which is the pcache1.grp global variable and its mutex is
  44451. ** SQLITE_MUTEX_STATIC_LRU.
  44452. */
  44453. struct PGroup {
  44454. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  44455. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  44456. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  44457. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  44458. unsigned int nPurgeable; /* Number of purgeable pages allocated */
  44459. PgHdr1 lru; /* The beginning and end of the LRU list */
  44460. };
  44461. /* Each page cache is an instance of the following object. Every
  44462. ** open database file (including each in-memory database and each
  44463. ** temporary or transient database) has a single page cache which
  44464. ** is an instance of this object.
  44465. **
  44466. ** Pointers to structures of this type are cast and returned as
  44467. ** opaque sqlite3_pcache* handles.
  44468. */
  44469. struct PCache1 {
  44470. /* Cache configuration parameters. Page size (szPage) and the purgeable
  44471. ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
  44472. ** cache is created and are never changed thereafter. nMax may be
  44473. ** modified at any time by a call to the pcache1Cachesize() method.
  44474. ** The PGroup mutex must be held when accessing nMax.
  44475. */
  44476. PGroup *pGroup; /* PGroup this cache belongs to */
  44477. unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
  44478. int szPage; /* Size of database content section */
  44479. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  44480. int szAlloc; /* Total size of one pcache line */
  44481. int bPurgeable; /* True if cache is purgeable */
  44482. unsigned int nMin; /* Minimum number of pages reserved */
  44483. unsigned int nMax; /* Configured "cache_size" value */
  44484. unsigned int n90pct; /* nMax*9/10 */
  44485. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  44486. /* Hash table of all pages. The following variables may only be accessed
  44487. ** when the accessor is holding the PGroup mutex.
  44488. */
  44489. unsigned int nRecyclable; /* Number of pages in the LRU list */
  44490. unsigned int nPage; /* Total number of pages in apHash */
  44491. unsigned int nHash; /* Number of slots in apHash[] */
  44492. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  44493. PgHdr1 *pFree; /* List of unused pcache-local pages */
  44494. void *pBulk; /* Bulk memory used by pcache-local */
  44495. };
  44496. /*
  44497. ** Free slots in the allocator used to divide up the global page cache
  44498. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  44499. */
  44500. struct PgFreeslot {
  44501. PgFreeslot *pNext; /* Next free slot */
  44502. };
  44503. /*
  44504. ** Global data used by this cache.
  44505. */
  44506. static SQLITE_WSD struct PCacheGlobal {
  44507. PGroup grp; /* The global PGroup for mode (2) */
  44508. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  44509. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  44510. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  44511. ** The nFreeSlot and pFree values do require mutex protection.
  44512. */
  44513. int isInit; /* True if initialized */
  44514. int separateCache; /* Use a new PGroup for each PCache */
  44515. int nInitPage; /* Initial bulk allocation size */
  44516. int szSlot; /* Size of each free slot */
  44517. int nSlot; /* The number of pcache slots */
  44518. int nReserve; /* Try to keep nFreeSlot above this */
  44519. void *pStart, *pEnd; /* Bounds of global page cache memory */
  44520. /* Above requires no mutex. Use mutex below for variable that follow. */
  44521. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  44522. PgFreeslot *pFree; /* Free page blocks */
  44523. int nFreeSlot; /* Number of unused pcache slots */
  44524. /* The following value requires a mutex to change. We skip the mutex on
  44525. ** reading because (1) most platforms read a 32-bit integer atomically and
  44526. ** (2) even if an incorrect value is read, no great harm is done since this
  44527. ** is really just an optimization. */
  44528. int bUnderPressure; /* True if low on PAGECACHE memory */
  44529. } pcache1_g;
  44530. /*
  44531. ** All code in this file should access the global structure above via the
  44532. ** alias "pcache1". This ensures that the WSD emulation is used when
  44533. ** compiling for systems that do not support real WSD.
  44534. */
  44535. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  44536. /*
  44537. ** Macros to enter and leave the PCache LRU mutex.
  44538. */
  44539. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  44540. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  44541. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  44542. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  44543. #else
  44544. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  44545. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  44546. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  44547. #endif
  44548. /******************************************************************************/
  44549. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  44550. /*
  44551. ** This function is called during initialization if a static buffer is
  44552. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  44553. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  44554. ** enough to contain 'n' buffers of 'sz' bytes each.
  44555. **
  44556. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  44557. ** to be serialized already. There is no need for further mutexing.
  44558. */
  44559. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  44560. if( pcache1.isInit ){
  44561. PgFreeslot *p;
  44562. if( pBuf==0 ) sz = n = 0;
  44563. if( n==0 ) sz = 0;
  44564. sz = ROUNDDOWN8(sz);
  44565. pcache1.szSlot = sz;
  44566. pcache1.nSlot = pcache1.nFreeSlot = n;
  44567. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  44568. pcache1.pStart = pBuf;
  44569. pcache1.pFree = 0;
  44570. pcache1.bUnderPressure = 0;
  44571. while( n-- ){
  44572. p = (PgFreeslot*)pBuf;
  44573. p->pNext = pcache1.pFree;
  44574. pcache1.pFree = p;
  44575. pBuf = (void*)&((char*)pBuf)[sz];
  44576. }
  44577. pcache1.pEnd = pBuf;
  44578. }
  44579. }
  44580. /*
  44581. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  44582. ** true if pCache->pFree ends up containing one or more free pages.
  44583. */
  44584. static int pcache1InitBulk(PCache1 *pCache){
  44585. i64 szBulk;
  44586. char *zBulk;
  44587. if( pcache1.nInitPage==0 ) return 0;
  44588. /* Do not bother with a bulk allocation if the cache size very small */
  44589. if( pCache->nMax<3 ) return 0;
  44590. sqlite3BeginBenignMalloc();
  44591. if( pcache1.nInitPage>0 ){
  44592. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  44593. }else{
  44594. szBulk = -1024 * (i64)pcache1.nInitPage;
  44595. }
  44596. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  44597. szBulk = pCache->szAlloc*(i64)pCache->nMax;
  44598. }
  44599. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  44600. sqlite3EndBenignMalloc();
  44601. if( zBulk ){
  44602. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  44603. do{
  44604. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  44605. pX->page.pBuf = zBulk;
  44606. pX->page.pExtra = &pX[1];
  44607. pX->isBulkLocal = 1;
  44608. pX->isAnchor = 0;
  44609. pX->pNext = pCache->pFree;
  44610. pCache->pFree = pX;
  44611. zBulk += pCache->szAlloc;
  44612. }while( --nBulk );
  44613. }
  44614. return pCache->pFree!=0;
  44615. }
  44616. /*
  44617. ** Malloc function used within this file to allocate space from the buffer
  44618. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  44619. ** such buffer exists or there is no space left in it, this function falls
  44620. ** back to sqlite3Malloc().
  44621. **
  44622. ** Multiple threads can run this routine at the same time. Global variables
  44623. ** in pcache1 need to be protected via mutex.
  44624. */
  44625. static void *pcache1Alloc(int nByte){
  44626. void *p = 0;
  44627. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  44628. if( nByte<=pcache1.szSlot ){
  44629. sqlite3_mutex_enter(pcache1.mutex);
  44630. p = (PgHdr1 *)pcache1.pFree;
  44631. if( p ){
  44632. pcache1.pFree = pcache1.pFree->pNext;
  44633. pcache1.nFreeSlot--;
  44634. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  44635. assert( pcache1.nFreeSlot>=0 );
  44636. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  44637. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  44638. }
  44639. sqlite3_mutex_leave(pcache1.mutex);
  44640. }
  44641. if( p==0 ){
  44642. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  44643. ** it from sqlite3Malloc instead.
  44644. */
  44645. p = sqlite3Malloc(nByte);
  44646. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  44647. if( p ){
  44648. int sz = sqlite3MallocSize(p);
  44649. sqlite3_mutex_enter(pcache1.mutex);
  44650. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  44651. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  44652. sqlite3_mutex_leave(pcache1.mutex);
  44653. }
  44654. #endif
  44655. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  44656. }
  44657. return p;
  44658. }
  44659. /*
  44660. ** Free an allocated buffer obtained from pcache1Alloc().
  44661. */
  44662. static void pcache1Free(void *p){
  44663. if( p==0 ) return;
  44664. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  44665. PgFreeslot *pSlot;
  44666. sqlite3_mutex_enter(pcache1.mutex);
  44667. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  44668. pSlot = (PgFreeslot*)p;
  44669. pSlot->pNext = pcache1.pFree;
  44670. pcache1.pFree = pSlot;
  44671. pcache1.nFreeSlot++;
  44672. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  44673. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  44674. sqlite3_mutex_leave(pcache1.mutex);
  44675. }else{
  44676. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  44677. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  44678. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  44679. {
  44680. int nFreed = 0;
  44681. nFreed = sqlite3MallocSize(p);
  44682. sqlite3_mutex_enter(pcache1.mutex);
  44683. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  44684. sqlite3_mutex_leave(pcache1.mutex);
  44685. }
  44686. #endif
  44687. sqlite3_free(p);
  44688. }
  44689. }
  44690. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  44691. /*
  44692. ** Return the size of a pcache allocation
  44693. */
  44694. static int pcache1MemSize(void *p){
  44695. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  44696. return pcache1.szSlot;
  44697. }else{
  44698. int iSize;
  44699. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  44700. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  44701. iSize = sqlite3MallocSize(p);
  44702. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  44703. return iSize;
  44704. }
  44705. }
  44706. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  44707. /*
  44708. ** Allocate a new page object initially associated with cache pCache.
  44709. */
  44710. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  44711. PgHdr1 *p = 0;
  44712. void *pPg;
  44713. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  44714. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  44715. p = pCache->pFree;
  44716. pCache->pFree = p->pNext;
  44717. p->pNext = 0;
  44718. }else{
  44719. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  44720. /* The group mutex must be released before pcache1Alloc() is called. This
  44721. ** is because it might call sqlite3_release_memory(), which assumes that
  44722. ** this mutex is not held. */
  44723. assert( pcache1.separateCache==0 );
  44724. assert( pCache->pGroup==&pcache1.grp );
  44725. pcache1LeaveMutex(pCache->pGroup);
  44726. #endif
  44727. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  44728. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  44729. pPg = pcache1Alloc(pCache->szPage);
  44730. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  44731. if( !pPg || !p ){
  44732. pcache1Free(pPg);
  44733. sqlite3_free(p);
  44734. pPg = 0;
  44735. }
  44736. #else
  44737. pPg = pcache1Alloc(pCache->szAlloc);
  44738. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  44739. #endif
  44740. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  44741. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  44742. pcache1EnterMutex(pCache->pGroup);
  44743. #endif
  44744. if( pPg==0 ) return 0;
  44745. p->page.pBuf = pPg;
  44746. p->page.pExtra = &p[1];
  44747. p->isBulkLocal = 0;
  44748. p->isAnchor = 0;
  44749. }
  44750. (*pCache->pnPurgeable)++;
  44751. return p;
  44752. }
  44753. /*
  44754. ** Free a page object allocated by pcache1AllocPage().
  44755. */
  44756. static void pcache1FreePage(PgHdr1 *p){
  44757. PCache1 *pCache;
  44758. assert( p!=0 );
  44759. pCache = p->pCache;
  44760. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  44761. if( p->isBulkLocal ){
  44762. p->pNext = pCache->pFree;
  44763. pCache->pFree = p;
  44764. }else{
  44765. pcache1Free(p->page.pBuf);
  44766. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  44767. sqlite3_free(p);
  44768. #endif
  44769. }
  44770. (*pCache->pnPurgeable)--;
  44771. }
  44772. /*
  44773. ** Malloc function used by SQLite to obtain space from the buffer configured
  44774. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  44775. ** exists, this function falls back to sqlite3Malloc().
  44776. */
  44777. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  44778. return pcache1Alloc(sz);
  44779. }
  44780. /*
  44781. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  44782. */
  44783. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  44784. pcache1Free(p);
  44785. }
  44786. /*
  44787. ** Return true if it desirable to avoid allocating a new page cache
  44788. ** entry.
  44789. **
  44790. ** If memory was allocated specifically to the page cache using
  44791. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  44792. ** it is desirable to avoid allocating a new page cache entry because
  44793. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  44794. ** for all page cache needs and we should not need to spill the
  44795. ** allocation onto the heap.
  44796. **
  44797. ** Or, the heap is used for all page cache memory but the heap is
  44798. ** under memory pressure, then again it is desirable to avoid
  44799. ** allocating a new page cache entry in order to avoid stressing
  44800. ** the heap even further.
  44801. */
  44802. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  44803. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  44804. return pcache1.bUnderPressure;
  44805. }else{
  44806. return sqlite3HeapNearlyFull();
  44807. }
  44808. }
  44809. /******************************************************************************/
  44810. /******** General Implementation Functions ************************************/
  44811. /*
  44812. ** This function is used to resize the hash table used by the cache passed
  44813. ** as the first argument.
  44814. **
  44815. ** The PCache mutex must be held when this function is called.
  44816. */
  44817. static void pcache1ResizeHash(PCache1 *p){
  44818. PgHdr1 **apNew;
  44819. unsigned int nNew;
  44820. unsigned int i;
  44821. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  44822. nNew = p->nHash*2;
  44823. if( nNew<256 ){
  44824. nNew = 256;
  44825. }
  44826. pcache1LeaveMutex(p->pGroup);
  44827. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  44828. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  44829. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  44830. pcache1EnterMutex(p->pGroup);
  44831. if( apNew ){
  44832. for(i=0; i<p->nHash; i++){
  44833. PgHdr1 *pPage;
  44834. PgHdr1 *pNext = p->apHash[i];
  44835. while( (pPage = pNext)!=0 ){
  44836. unsigned int h = pPage->iKey % nNew;
  44837. pNext = pPage->pNext;
  44838. pPage->pNext = apNew[h];
  44839. apNew[h] = pPage;
  44840. }
  44841. }
  44842. sqlite3_free(p->apHash);
  44843. p->apHash = apNew;
  44844. p->nHash = nNew;
  44845. }
  44846. }
  44847. /*
  44848. ** This function is used internally to remove the page pPage from the
  44849. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  44850. ** LRU list, then this function is a no-op.
  44851. **
  44852. ** The PGroup mutex must be held when this function is called.
  44853. */
  44854. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  44855. assert( pPage!=0 );
  44856. assert( PAGE_IS_UNPINNED(pPage) );
  44857. assert( pPage->pLruNext );
  44858. assert( pPage->pLruPrev );
  44859. assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
  44860. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  44861. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  44862. pPage->pLruNext = 0;
  44863. pPage->pLruPrev = 0;
  44864. assert( pPage->isAnchor==0 );
  44865. assert( pPage->pCache->pGroup->lru.isAnchor==1 );
  44866. pPage->pCache->nRecyclable--;
  44867. return pPage;
  44868. }
  44869. /*
  44870. ** Remove the page supplied as an argument from the hash table
  44871. ** (PCache1.apHash structure) that it is currently stored in.
  44872. ** Also free the page if freePage is true.
  44873. **
  44874. ** The PGroup mutex must be held when this function is called.
  44875. */
  44876. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  44877. unsigned int h;
  44878. PCache1 *pCache = pPage->pCache;
  44879. PgHdr1 **pp;
  44880. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  44881. h = pPage->iKey % pCache->nHash;
  44882. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  44883. *pp = (*pp)->pNext;
  44884. pCache->nPage--;
  44885. if( freeFlag ) pcache1FreePage(pPage);
  44886. }
  44887. /*
  44888. ** If there are currently more than nMaxPage pages allocated, try
  44889. ** to recycle pages to reduce the number allocated to nMaxPage.
  44890. */
  44891. static void pcache1EnforceMaxPage(PCache1 *pCache){
  44892. PGroup *pGroup = pCache->pGroup;
  44893. PgHdr1 *p;
  44894. assert( sqlite3_mutex_held(pGroup->mutex) );
  44895. while( pGroup->nPurgeable>pGroup->nMaxPage
  44896. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  44897. ){
  44898. assert( p->pCache->pGroup==pGroup );
  44899. assert( PAGE_IS_UNPINNED(p) );
  44900. pcache1PinPage(p);
  44901. pcache1RemoveFromHash(p, 1);
  44902. }
  44903. if( pCache->nPage==0 && pCache->pBulk ){
  44904. sqlite3_free(pCache->pBulk);
  44905. pCache->pBulk = pCache->pFree = 0;
  44906. }
  44907. }
  44908. /*
  44909. ** Discard all pages from cache pCache with a page number (key value)
  44910. ** greater than or equal to iLimit. Any pinned pages that meet this
  44911. ** criteria are unpinned before they are discarded.
  44912. **
  44913. ** The PCache mutex must be held when this function is called.
  44914. */
  44915. static void pcache1TruncateUnsafe(
  44916. PCache1 *pCache, /* The cache to truncate */
  44917. unsigned int iLimit /* Drop pages with this pgno or larger */
  44918. ){
  44919. TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
  44920. unsigned int h, iStop;
  44921. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  44922. assert( pCache->iMaxKey >= iLimit );
  44923. assert( pCache->nHash > 0 );
  44924. if( pCache->iMaxKey - iLimit < pCache->nHash ){
  44925. /* If we are just shaving the last few pages off the end of the
  44926. ** cache, then there is no point in scanning the entire hash table.
  44927. ** Only scan those hash slots that might contain pages that need to
  44928. ** be removed. */
  44929. h = iLimit % pCache->nHash;
  44930. iStop = pCache->iMaxKey % pCache->nHash;
  44931. TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
  44932. }else{
  44933. /* This is the general case where many pages are being removed.
  44934. ** It is necessary to scan the entire hash table */
  44935. h = pCache->nHash/2;
  44936. iStop = h - 1;
  44937. }
  44938. for(;;){
  44939. PgHdr1 **pp;
  44940. PgHdr1 *pPage;
  44941. assert( h<pCache->nHash );
  44942. pp = &pCache->apHash[h];
  44943. while( (pPage = *pp)!=0 ){
  44944. if( pPage->iKey>=iLimit ){
  44945. pCache->nPage--;
  44946. *pp = pPage->pNext;
  44947. if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
  44948. pcache1FreePage(pPage);
  44949. }else{
  44950. pp = &pPage->pNext;
  44951. TESTONLY( if( nPage>=0 ) nPage++; )
  44952. }
  44953. }
  44954. if( h==iStop ) break;
  44955. h = (h+1) % pCache->nHash;
  44956. }
  44957. assert( nPage<0 || pCache->nPage==(unsigned)nPage );
  44958. }
  44959. /******************************************************************************/
  44960. /******** sqlite3_pcache Methods **********************************************/
  44961. /*
  44962. ** Implementation of the sqlite3_pcache.xInit method.
  44963. */
  44964. static int pcache1Init(void *NotUsed){
  44965. UNUSED_PARAMETER(NotUsed);
  44966. assert( pcache1.isInit==0 );
  44967. memset(&pcache1, 0, sizeof(pcache1));
  44968. /*
  44969. ** The pcache1.separateCache variable is true if each PCache has its own
  44970. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  44971. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  44972. **
  44973. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  44974. **
  44975. ** * Use a unified cache in single-threaded applications that have
  44976. ** configured a start-time buffer for use as page-cache memory using
  44977. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  44978. ** pBuf argument.
  44979. **
  44980. ** * Otherwise use separate caches (mode-1)
  44981. */
  44982. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  44983. pcache1.separateCache = 0;
  44984. #elif SQLITE_THREADSAFE
  44985. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  44986. || sqlite3GlobalConfig.bCoreMutex>0;
  44987. #else
  44988. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  44989. #endif
  44990. #if SQLITE_THREADSAFE
  44991. if( sqlite3GlobalConfig.bCoreMutex ){
  44992. pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
  44993. pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
  44994. }
  44995. #endif
  44996. if( pcache1.separateCache
  44997. && sqlite3GlobalConfig.nPage!=0
  44998. && sqlite3GlobalConfig.pPage==0
  44999. ){
  45000. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  45001. }else{
  45002. pcache1.nInitPage = 0;
  45003. }
  45004. pcache1.grp.mxPinned = 10;
  45005. pcache1.isInit = 1;
  45006. return SQLITE_OK;
  45007. }
  45008. /*
  45009. ** Implementation of the sqlite3_pcache.xShutdown method.
  45010. ** Note that the static mutex allocated in xInit does
  45011. ** not need to be freed.
  45012. */
  45013. static void pcache1Shutdown(void *NotUsed){
  45014. UNUSED_PARAMETER(NotUsed);
  45015. assert( pcache1.isInit!=0 );
  45016. memset(&pcache1, 0, sizeof(pcache1));
  45017. }
  45018. /* forward declaration */
  45019. static void pcache1Destroy(sqlite3_pcache *p);
  45020. /*
  45021. ** Implementation of the sqlite3_pcache.xCreate method.
  45022. **
  45023. ** Allocate a new cache.
  45024. */
  45025. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  45026. PCache1 *pCache; /* The newly created page cache */
  45027. PGroup *pGroup; /* The group the new page cache will belong to */
  45028. int sz; /* Bytes of memory required to allocate the new cache */
  45029. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  45030. assert( szExtra < 300 );
  45031. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  45032. pCache = (PCache1 *)sqlite3MallocZero(sz);
  45033. if( pCache ){
  45034. if( pcache1.separateCache ){
  45035. pGroup = (PGroup*)&pCache[1];
  45036. pGroup->mxPinned = 10;
  45037. }else{
  45038. pGroup = &pcache1.grp;
  45039. }
  45040. if( pGroup->lru.isAnchor==0 ){
  45041. pGroup->lru.isAnchor = 1;
  45042. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  45043. }
  45044. pCache->pGroup = pGroup;
  45045. pCache->szPage = szPage;
  45046. pCache->szExtra = szExtra;
  45047. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  45048. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  45049. pcache1EnterMutex(pGroup);
  45050. pcache1ResizeHash(pCache);
  45051. if( bPurgeable ){
  45052. pCache->nMin = 10;
  45053. pGroup->nMinPage += pCache->nMin;
  45054. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  45055. pCache->pnPurgeable = &pGroup->nPurgeable;
  45056. }else{
  45057. static unsigned int dummyCurrentPage;
  45058. pCache->pnPurgeable = &dummyCurrentPage;
  45059. }
  45060. pcache1LeaveMutex(pGroup);
  45061. if( pCache->nHash==0 ){
  45062. pcache1Destroy((sqlite3_pcache*)pCache);
  45063. pCache = 0;
  45064. }
  45065. }
  45066. return (sqlite3_pcache *)pCache;
  45067. }
  45068. /*
  45069. ** Implementation of the sqlite3_pcache.xCachesize method.
  45070. **
  45071. ** Configure the cache_size limit for a cache.
  45072. */
  45073. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  45074. PCache1 *pCache = (PCache1 *)p;
  45075. if( pCache->bPurgeable ){
  45076. PGroup *pGroup = pCache->pGroup;
  45077. pcache1EnterMutex(pGroup);
  45078. pGroup->nMaxPage += (nMax - pCache->nMax);
  45079. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  45080. pCache->nMax = nMax;
  45081. pCache->n90pct = pCache->nMax*9/10;
  45082. pcache1EnforceMaxPage(pCache);
  45083. pcache1LeaveMutex(pGroup);
  45084. }
  45085. }
  45086. /*
  45087. ** Implementation of the sqlite3_pcache.xShrink method.
  45088. **
  45089. ** Free up as much memory as possible.
  45090. */
  45091. static void pcache1Shrink(sqlite3_pcache *p){
  45092. PCache1 *pCache = (PCache1*)p;
  45093. if( pCache->bPurgeable ){
  45094. PGroup *pGroup = pCache->pGroup;
  45095. int savedMaxPage;
  45096. pcache1EnterMutex(pGroup);
  45097. savedMaxPage = pGroup->nMaxPage;
  45098. pGroup->nMaxPage = 0;
  45099. pcache1EnforceMaxPage(pCache);
  45100. pGroup->nMaxPage = savedMaxPage;
  45101. pcache1LeaveMutex(pGroup);
  45102. }
  45103. }
  45104. /*
  45105. ** Implementation of the sqlite3_pcache.xPagecount method.
  45106. */
  45107. static int pcache1Pagecount(sqlite3_pcache *p){
  45108. int n;
  45109. PCache1 *pCache = (PCache1*)p;
  45110. pcache1EnterMutex(pCache->pGroup);
  45111. n = pCache->nPage;
  45112. pcache1LeaveMutex(pCache->pGroup);
  45113. return n;
  45114. }
  45115. /*
  45116. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  45117. ** in the header of the pcache1Fetch() procedure.
  45118. **
  45119. ** This steps are broken out into a separate procedure because they are
  45120. ** usually not needed, and by avoiding the stack initialization required
  45121. ** for these steps, the main pcache1Fetch() procedure can run faster.
  45122. */
  45123. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  45124. PCache1 *pCache,
  45125. unsigned int iKey,
  45126. int createFlag
  45127. ){
  45128. unsigned int nPinned;
  45129. PGroup *pGroup = pCache->pGroup;
  45130. PgHdr1 *pPage = 0;
  45131. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  45132. assert( pCache->nPage >= pCache->nRecyclable );
  45133. nPinned = pCache->nPage - pCache->nRecyclable;
  45134. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  45135. assert( pCache->n90pct == pCache->nMax*9/10 );
  45136. if( createFlag==1 && (
  45137. nPinned>=pGroup->mxPinned
  45138. || nPinned>=pCache->n90pct
  45139. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  45140. )){
  45141. return 0;
  45142. }
  45143. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  45144. assert( pCache->nHash>0 && pCache->apHash );
  45145. /* Step 4. Try to recycle a page. */
  45146. if( pCache->bPurgeable
  45147. && !pGroup->lru.pLruPrev->isAnchor
  45148. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  45149. ){
  45150. PCache1 *pOther;
  45151. pPage = pGroup->lru.pLruPrev;
  45152. assert( PAGE_IS_UNPINNED(pPage) );
  45153. pcache1RemoveFromHash(pPage, 0);
  45154. pcache1PinPage(pPage);
  45155. pOther = pPage->pCache;
  45156. if( pOther->szAlloc != pCache->szAlloc ){
  45157. pcache1FreePage(pPage);
  45158. pPage = 0;
  45159. }else{
  45160. pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
  45161. }
  45162. }
  45163. /* Step 5. If a usable page buffer has still not been found,
  45164. ** attempt to allocate a new one.
  45165. */
  45166. if( !pPage ){
  45167. pPage = pcache1AllocPage(pCache, createFlag==1);
  45168. }
  45169. if( pPage ){
  45170. unsigned int h = iKey % pCache->nHash;
  45171. pCache->nPage++;
  45172. pPage->iKey = iKey;
  45173. pPage->pNext = pCache->apHash[h];
  45174. pPage->pCache = pCache;
  45175. pPage->pLruPrev = 0;
  45176. pPage->pLruNext = 0;
  45177. *(void **)pPage->page.pExtra = 0;
  45178. pCache->apHash[h] = pPage;
  45179. if( iKey>pCache->iMaxKey ){
  45180. pCache->iMaxKey = iKey;
  45181. }
  45182. }
  45183. return pPage;
  45184. }
  45185. /*
  45186. ** Implementation of the sqlite3_pcache.xFetch method.
  45187. **
  45188. ** Fetch a page by key value.
  45189. **
  45190. ** Whether or not a new page may be allocated by this function depends on
  45191. ** the value of the createFlag argument. 0 means do not allocate a new
  45192. ** page. 1 means allocate a new page if space is easily available. 2
  45193. ** means to try really hard to allocate a new page.
  45194. **
  45195. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  45196. ** database) there is really no difference between createFlag 1 and 2. So
  45197. ** the calling function (pcache.c) will never have a createFlag of 1 on
  45198. ** a non-purgeable cache.
  45199. **
  45200. ** There are three different approaches to obtaining space for a page,
  45201. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  45202. **
  45203. ** 1. Regardless of the value of createFlag, the cache is searched for a
  45204. ** copy of the requested page. If one is found, it is returned.
  45205. **
  45206. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  45207. ** returned.
  45208. **
  45209. ** 3. If createFlag is 1, and the page is not already in the cache, then
  45210. ** return NULL (do not allocate a new page) if any of the following
  45211. ** conditions are true:
  45212. **
  45213. ** (a) the number of pages pinned by the cache is greater than
  45214. ** PCache1.nMax, or
  45215. **
  45216. ** (b) the number of pages pinned by the cache is greater than
  45217. ** the sum of nMax for all purgeable caches, less the sum of
  45218. ** nMin for all other purgeable caches, or
  45219. **
  45220. ** 4. If none of the first three conditions apply and the cache is marked
  45221. ** as purgeable, and if one of the following is true:
  45222. **
  45223. ** (a) The number of pages allocated for the cache is already
  45224. ** PCache1.nMax, or
  45225. **
  45226. ** (b) The number of pages allocated for all purgeable caches is
  45227. ** already equal to or greater than the sum of nMax for all
  45228. ** purgeable caches,
  45229. **
  45230. ** (c) The system is under memory pressure and wants to avoid
  45231. ** unnecessary pages cache entry allocations
  45232. **
  45233. ** then attempt to recycle a page from the LRU list. If it is the right
  45234. ** size, return the recycled buffer. Otherwise, free the buffer and
  45235. ** proceed to step 5.
  45236. **
  45237. ** 5. Otherwise, allocate and return a new page buffer.
  45238. **
  45239. ** There are two versions of this routine. pcache1FetchWithMutex() is
  45240. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  45241. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  45242. ** invokes the appropriate routine.
  45243. */
  45244. static PgHdr1 *pcache1FetchNoMutex(
  45245. sqlite3_pcache *p,
  45246. unsigned int iKey,
  45247. int createFlag
  45248. ){
  45249. PCache1 *pCache = (PCache1 *)p;
  45250. PgHdr1 *pPage = 0;
  45251. /* Step 1: Search the hash table for an existing entry. */
  45252. pPage = pCache->apHash[iKey % pCache->nHash];
  45253. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  45254. /* Step 2: If the page was found in the hash table, then return it.
  45255. ** If the page was not in the hash table and createFlag is 0, abort.
  45256. ** Otherwise (page not in hash and createFlag!=0) continue with
  45257. ** subsequent steps to try to create the page. */
  45258. if( pPage ){
  45259. if( PAGE_IS_UNPINNED(pPage) ){
  45260. return pcache1PinPage(pPage);
  45261. }else{
  45262. return pPage;
  45263. }
  45264. }else if( createFlag ){
  45265. /* Steps 3, 4, and 5 implemented by this subroutine */
  45266. return pcache1FetchStage2(pCache, iKey, createFlag);
  45267. }else{
  45268. return 0;
  45269. }
  45270. }
  45271. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  45272. static PgHdr1 *pcache1FetchWithMutex(
  45273. sqlite3_pcache *p,
  45274. unsigned int iKey,
  45275. int createFlag
  45276. ){
  45277. PCache1 *pCache = (PCache1 *)p;
  45278. PgHdr1 *pPage;
  45279. pcache1EnterMutex(pCache->pGroup);
  45280. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  45281. assert( pPage==0 || pCache->iMaxKey>=iKey );
  45282. pcache1LeaveMutex(pCache->pGroup);
  45283. return pPage;
  45284. }
  45285. #endif
  45286. static sqlite3_pcache_page *pcache1Fetch(
  45287. sqlite3_pcache *p,
  45288. unsigned int iKey,
  45289. int createFlag
  45290. ){
  45291. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  45292. PCache1 *pCache = (PCache1 *)p;
  45293. #endif
  45294. assert( offsetof(PgHdr1,page)==0 );
  45295. assert( pCache->bPurgeable || createFlag!=1 );
  45296. assert( pCache->bPurgeable || pCache->nMin==0 );
  45297. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  45298. assert( pCache->nMin==0 || pCache->bPurgeable );
  45299. assert( pCache->nHash>0 );
  45300. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  45301. if( pCache->pGroup->mutex ){
  45302. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  45303. }else
  45304. #endif
  45305. {
  45306. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  45307. }
  45308. }
  45309. /*
  45310. ** Implementation of the sqlite3_pcache.xUnpin method.
  45311. **
  45312. ** Mark a page as unpinned (eligible for asynchronous recycling).
  45313. */
  45314. static void pcache1Unpin(
  45315. sqlite3_pcache *p,
  45316. sqlite3_pcache_page *pPg,
  45317. int reuseUnlikely
  45318. ){
  45319. PCache1 *pCache = (PCache1 *)p;
  45320. PgHdr1 *pPage = (PgHdr1 *)pPg;
  45321. PGroup *pGroup = pCache->pGroup;
  45322. assert( pPage->pCache==pCache );
  45323. pcache1EnterMutex(pGroup);
  45324. /* It is an error to call this function if the page is already
  45325. ** part of the PGroup LRU list.
  45326. */
  45327. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  45328. assert( PAGE_IS_PINNED(pPage) );
  45329. if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
  45330. pcache1RemoveFromHash(pPage, 1);
  45331. }else{
  45332. /* Add the page to the PGroup LRU list. */
  45333. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  45334. pPage->pLruPrev = &pGroup->lru;
  45335. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  45336. *ppFirst = pPage;
  45337. pCache->nRecyclable++;
  45338. }
  45339. pcache1LeaveMutex(pCache->pGroup);
  45340. }
  45341. /*
  45342. ** Implementation of the sqlite3_pcache.xRekey method.
  45343. */
  45344. static void pcache1Rekey(
  45345. sqlite3_pcache *p,
  45346. sqlite3_pcache_page *pPg,
  45347. unsigned int iOld,
  45348. unsigned int iNew
  45349. ){
  45350. PCache1 *pCache = (PCache1 *)p;
  45351. PgHdr1 *pPage = (PgHdr1 *)pPg;
  45352. PgHdr1 **pp;
  45353. unsigned int h;
  45354. assert( pPage->iKey==iOld );
  45355. assert( pPage->pCache==pCache );
  45356. pcache1EnterMutex(pCache->pGroup);
  45357. h = iOld%pCache->nHash;
  45358. pp = &pCache->apHash[h];
  45359. while( (*pp)!=pPage ){
  45360. pp = &(*pp)->pNext;
  45361. }
  45362. *pp = pPage->pNext;
  45363. h = iNew%pCache->nHash;
  45364. pPage->iKey = iNew;
  45365. pPage->pNext = pCache->apHash[h];
  45366. pCache->apHash[h] = pPage;
  45367. if( iNew>pCache->iMaxKey ){
  45368. pCache->iMaxKey = iNew;
  45369. }
  45370. pcache1LeaveMutex(pCache->pGroup);
  45371. }
  45372. /*
  45373. ** Implementation of the sqlite3_pcache.xTruncate method.
  45374. **
  45375. ** Discard all unpinned pages in the cache with a page number equal to
  45376. ** or greater than parameter iLimit. Any pinned pages with a page number
  45377. ** equal to or greater than iLimit are implicitly unpinned.
  45378. */
  45379. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  45380. PCache1 *pCache = (PCache1 *)p;
  45381. pcache1EnterMutex(pCache->pGroup);
  45382. if( iLimit<=pCache->iMaxKey ){
  45383. pcache1TruncateUnsafe(pCache, iLimit);
  45384. pCache->iMaxKey = iLimit-1;
  45385. }
  45386. pcache1LeaveMutex(pCache->pGroup);
  45387. }
  45388. /*
  45389. ** Implementation of the sqlite3_pcache.xDestroy method.
  45390. **
  45391. ** Destroy a cache allocated using pcache1Create().
  45392. */
  45393. static void pcache1Destroy(sqlite3_pcache *p){
  45394. PCache1 *pCache = (PCache1 *)p;
  45395. PGroup *pGroup = pCache->pGroup;
  45396. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  45397. pcache1EnterMutex(pGroup);
  45398. if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
  45399. assert( pGroup->nMaxPage >= pCache->nMax );
  45400. pGroup->nMaxPage -= pCache->nMax;
  45401. assert( pGroup->nMinPage >= pCache->nMin );
  45402. pGroup->nMinPage -= pCache->nMin;
  45403. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  45404. pcache1EnforceMaxPage(pCache);
  45405. pcache1LeaveMutex(pGroup);
  45406. sqlite3_free(pCache->pBulk);
  45407. sqlite3_free(pCache->apHash);
  45408. sqlite3_free(pCache);
  45409. }
  45410. /*
  45411. ** This function is called during initialization (sqlite3_initialize()) to
  45412. ** install the default pluggable cache module, assuming the user has not
  45413. ** already provided an alternative.
  45414. */
  45415. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  45416. static const sqlite3_pcache_methods2 defaultMethods = {
  45417. 1, /* iVersion */
  45418. 0, /* pArg */
  45419. pcache1Init, /* xInit */
  45420. pcache1Shutdown, /* xShutdown */
  45421. pcache1Create, /* xCreate */
  45422. pcache1Cachesize, /* xCachesize */
  45423. pcache1Pagecount, /* xPagecount */
  45424. pcache1Fetch, /* xFetch */
  45425. pcache1Unpin, /* xUnpin */
  45426. pcache1Rekey, /* xRekey */
  45427. pcache1Truncate, /* xTruncate */
  45428. pcache1Destroy, /* xDestroy */
  45429. pcache1Shrink /* xShrink */
  45430. };
  45431. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  45432. }
  45433. /*
  45434. ** Return the size of the header on each page of this PCACHE implementation.
  45435. */
  45436. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  45437. /*
  45438. ** Return the global mutex used by this PCACHE implementation. The
  45439. ** sqlite3_status() routine needs access to this mutex.
  45440. */
  45441. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  45442. return pcache1.mutex;
  45443. }
  45444. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  45445. /*
  45446. ** This function is called to free superfluous dynamically allocated memory
  45447. ** held by the pager system. Memory in use by any SQLite pager allocated
  45448. ** by the current thread may be sqlite3_free()ed.
  45449. **
  45450. ** nReq is the number of bytes of memory required. Once this much has
  45451. ** been released, the function returns. The return value is the total number
  45452. ** of bytes of memory released.
  45453. */
  45454. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  45455. int nFree = 0;
  45456. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  45457. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  45458. if( sqlite3GlobalConfig.pPage==0 ){
  45459. PgHdr1 *p;
  45460. pcache1EnterMutex(&pcache1.grp);
  45461. while( (nReq<0 || nFree<nReq)
  45462. && (p=pcache1.grp.lru.pLruPrev)!=0
  45463. && p->isAnchor==0
  45464. ){
  45465. nFree += pcache1MemSize(p->page.pBuf);
  45466. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  45467. nFree += sqlite3MemSize(p);
  45468. #endif
  45469. assert( PAGE_IS_UNPINNED(p) );
  45470. pcache1PinPage(p);
  45471. pcache1RemoveFromHash(p, 1);
  45472. }
  45473. pcache1LeaveMutex(&pcache1.grp);
  45474. }
  45475. return nFree;
  45476. }
  45477. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  45478. #ifdef SQLITE_TEST
  45479. /*
  45480. ** This function is used by test procedures to inspect the internal state
  45481. ** of the global cache.
  45482. */
  45483. SQLITE_PRIVATE void sqlite3PcacheStats(
  45484. int *pnCurrent, /* OUT: Total number of pages cached */
  45485. int *pnMax, /* OUT: Global maximum cache size */
  45486. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  45487. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  45488. ){
  45489. PgHdr1 *p;
  45490. int nRecyclable = 0;
  45491. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  45492. assert( PAGE_IS_UNPINNED(p) );
  45493. nRecyclable++;
  45494. }
  45495. *pnCurrent = pcache1.grp.nPurgeable;
  45496. *pnMax = (int)pcache1.grp.nMaxPage;
  45497. *pnMin = (int)pcache1.grp.nMinPage;
  45498. *pnRecyclable = nRecyclable;
  45499. }
  45500. #endif
  45501. /************** End of pcache1.c *********************************************/
  45502. /************** Begin file rowset.c ******************************************/
  45503. /*
  45504. ** 2008 December 3
  45505. **
  45506. ** The author disclaims copyright to this source code. In place of
  45507. ** a legal notice, here is a blessing:
  45508. **
  45509. ** May you do good and not evil.
  45510. ** May you find forgiveness for yourself and forgive others.
  45511. ** May you share freely, never taking more than you give.
  45512. **
  45513. *************************************************************************
  45514. **
  45515. ** This module implements an object we call a "RowSet".
  45516. **
  45517. ** The RowSet object is a collection of rowids. Rowids
  45518. ** are inserted into the RowSet in an arbitrary order. Inserts
  45519. ** can be intermixed with tests to see if a given rowid has been
  45520. ** previously inserted into the RowSet.
  45521. **
  45522. ** After all inserts are finished, it is possible to extract the
  45523. ** elements of the RowSet in sorted order. Once this extraction
  45524. ** process has started, no new elements may be inserted.
  45525. **
  45526. ** Hence, the primitive operations for a RowSet are:
  45527. **
  45528. ** CREATE
  45529. ** INSERT
  45530. ** TEST
  45531. ** SMALLEST
  45532. ** DESTROY
  45533. **
  45534. ** The CREATE and DESTROY primitives are the constructor and destructor,
  45535. ** obviously. The INSERT primitive adds a new element to the RowSet.
  45536. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  45537. ** extracts the least value from the RowSet.
  45538. **
  45539. ** The INSERT primitive might allocate additional memory. Memory is
  45540. ** allocated in chunks so most INSERTs do no allocation. There is an
  45541. ** upper bound on the size of allocated memory. No memory is freed
  45542. ** until DESTROY.
  45543. **
  45544. ** The TEST primitive includes a "batch" number. The TEST primitive
  45545. ** will only see elements that were inserted before the last change
  45546. ** in the batch number. In other words, if an INSERT occurs between
  45547. ** two TESTs where the TESTs have the same batch nubmer, then the
  45548. ** value added by the INSERT will not be visible to the second TEST.
  45549. ** The initial batch number is zero, so if the very first TEST contains
  45550. ** a non-zero batch number, it will see all prior INSERTs.
  45551. **
  45552. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  45553. ** that is attempted.
  45554. **
  45555. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  45556. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  45557. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  45558. ** The cost of a TEST using the same batch number is O(logN). The cost
  45559. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  45560. ** primitives are constant time. The cost of DESTROY is O(N).
  45561. **
  45562. ** TEST and SMALLEST may not be used by the same RowSet. This used to
  45563. ** be possible, but the feature was not used, so it was removed in order
  45564. ** to simplify the code.
  45565. */
  45566. /* #include "sqliteInt.h" */
  45567. /*
  45568. ** Target size for allocation chunks.
  45569. */
  45570. #define ROWSET_ALLOCATION_SIZE 1024
  45571. /*
  45572. ** The number of rowset entries per allocation chunk.
  45573. */
  45574. #define ROWSET_ENTRY_PER_CHUNK \
  45575. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  45576. /*
  45577. ** Each entry in a RowSet is an instance of the following object.
  45578. **
  45579. ** This same object is reused to store a linked list of trees of RowSetEntry
  45580. ** objects. In that alternative use, pRight points to the next entry
  45581. ** in the list, pLeft points to the tree, and v is unused. The
  45582. ** RowSet.pForest value points to the head of this forest list.
  45583. */
  45584. struct RowSetEntry {
  45585. i64 v; /* ROWID value for this entry */
  45586. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  45587. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  45588. };
  45589. /*
  45590. ** RowSetEntry objects are allocated in large chunks (instances of the
  45591. ** following structure) to reduce memory allocation overhead. The
  45592. ** chunks are kept on a linked list so that they can be deallocated
  45593. ** when the RowSet is destroyed.
  45594. */
  45595. struct RowSetChunk {
  45596. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  45597. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  45598. };
  45599. /*
  45600. ** A RowSet in an instance of the following structure.
  45601. **
  45602. ** A typedef of this structure if found in sqliteInt.h.
  45603. */
  45604. struct RowSet {
  45605. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  45606. sqlite3 *db; /* The database connection */
  45607. struct RowSetEntry *pEntry; /* List of entries using pRight */
  45608. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  45609. struct RowSetEntry *pFresh; /* Source of new entry objects */
  45610. struct RowSetEntry *pForest; /* List of binary trees of entries */
  45611. u16 nFresh; /* Number of objects on pFresh */
  45612. u16 rsFlags; /* Various flags */
  45613. int iBatch; /* Current insert batch */
  45614. };
  45615. /*
  45616. ** Allowed values for RowSet.rsFlags
  45617. */
  45618. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  45619. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  45620. /*
  45621. ** Turn bulk memory into a RowSet object. N bytes of memory
  45622. ** are available at pSpace. The db pointer is used as a memory context
  45623. ** for any subsequent allocations that need to occur.
  45624. ** Return a pointer to the new RowSet object.
  45625. **
  45626. ** It must be the case that N is sufficient to make a Rowset. If not
  45627. ** an assertion fault occurs.
  45628. **
  45629. ** If N is larger than the minimum, use the surplus as an initial
  45630. ** allocation of entries available to be filled.
  45631. */
  45632. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  45633. RowSet *p;
  45634. assert( N >= ROUND8(sizeof(*p)) );
  45635. p = pSpace;
  45636. p->pChunk = 0;
  45637. p->db = db;
  45638. p->pEntry = 0;
  45639. p->pLast = 0;
  45640. p->pForest = 0;
  45641. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  45642. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  45643. p->rsFlags = ROWSET_SORTED;
  45644. p->iBatch = 0;
  45645. return p;
  45646. }
  45647. /*
  45648. ** Deallocate all chunks from a RowSet. This frees all memory that
  45649. ** the RowSet has allocated over its lifetime. This routine is
  45650. ** the destructor for the RowSet.
  45651. */
  45652. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  45653. struct RowSetChunk *pChunk, *pNextChunk;
  45654. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  45655. pNextChunk = pChunk->pNextChunk;
  45656. sqlite3DbFree(p->db, pChunk);
  45657. }
  45658. p->pChunk = 0;
  45659. p->nFresh = 0;
  45660. p->pEntry = 0;
  45661. p->pLast = 0;
  45662. p->pForest = 0;
  45663. p->rsFlags = ROWSET_SORTED;
  45664. }
  45665. /*
  45666. ** Allocate a new RowSetEntry object that is associated with the
  45667. ** given RowSet. Return a pointer to the new and completely uninitialized
  45668. ** objected.
  45669. **
  45670. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  45671. ** routine returns NULL.
  45672. */
  45673. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  45674. assert( p!=0 );
  45675. if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
  45676. /* We could allocate a fresh RowSetEntry each time one is needed, but it
  45677. ** is more efficient to pull a preallocated entry from the pool */
  45678. struct RowSetChunk *pNew;
  45679. pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
  45680. if( pNew==0 ){
  45681. return 0;
  45682. }
  45683. pNew->pNextChunk = p->pChunk;
  45684. p->pChunk = pNew;
  45685. p->pFresh = pNew->aEntry;
  45686. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  45687. }
  45688. p->nFresh--;
  45689. return p->pFresh++;
  45690. }
  45691. /*
  45692. ** Insert a new value into a RowSet.
  45693. **
  45694. ** The mallocFailed flag of the database connection is set if a
  45695. ** memory allocation fails.
  45696. */
  45697. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  45698. struct RowSetEntry *pEntry; /* The new entry */
  45699. struct RowSetEntry *pLast; /* The last prior entry */
  45700. /* This routine is never called after sqlite3RowSetNext() */
  45701. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  45702. pEntry = rowSetEntryAlloc(p);
  45703. if( pEntry==0 ) return;
  45704. pEntry->v = rowid;
  45705. pEntry->pRight = 0;
  45706. pLast = p->pLast;
  45707. if( pLast ){
  45708. if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
  45709. /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
  45710. ** where possible */
  45711. p->rsFlags &= ~ROWSET_SORTED;
  45712. }
  45713. pLast->pRight = pEntry;
  45714. }else{
  45715. p->pEntry = pEntry;
  45716. }
  45717. p->pLast = pEntry;
  45718. }
  45719. /*
  45720. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  45721. **
  45722. ** The input lists are connected via pRight pointers and are
  45723. ** assumed to each already be in sorted order.
  45724. */
  45725. static struct RowSetEntry *rowSetEntryMerge(
  45726. struct RowSetEntry *pA, /* First sorted list to be merged */
  45727. struct RowSetEntry *pB /* Second sorted list to be merged */
  45728. ){
  45729. struct RowSetEntry head;
  45730. struct RowSetEntry *pTail;
  45731. pTail = &head;
  45732. assert( pA!=0 && pB!=0 );
  45733. for(;;){
  45734. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  45735. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  45736. if( pA->v<=pB->v ){
  45737. if( pA->v<pB->v ) pTail = pTail->pRight = pA;
  45738. pA = pA->pRight;
  45739. if( pA==0 ){
  45740. pTail->pRight = pB;
  45741. break;
  45742. }
  45743. }else{
  45744. pTail = pTail->pRight = pB;
  45745. pB = pB->pRight;
  45746. if( pB==0 ){
  45747. pTail->pRight = pA;
  45748. break;
  45749. }
  45750. }
  45751. }
  45752. return head.pRight;
  45753. }
  45754. /*
  45755. ** Sort all elements on the list of RowSetEntry objects into order of
  45756. ** increasing v.
  45757. */
  45758. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  45759. unsigned int i;
  45760. struct RowSetEntry *pNext, *aBucket[40];
  45761. memset(aBucket, 0, sizeof(aBucket));
  45762. while( pIn ){
  45763. pNext = pIn->pRight;
  45764. pIn->pRight = 0;
  45765. for(i=0; aBucket[i]; i++){
  45766. pIn = rowSetEntryMerge(aBucket[i], pIn);
  45767. aBucket[i] = 0;
  45768. }
  45769. aBucket[i] = pIn;
  45770. pIn = pNext;
  45771. }
  45772. pIn = aBucket[0];
  45773. for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  45774. if( aBucket[i]==0 ) continue;
  45775. pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
  45776. }
  45777. return pIn;
  45778. }
  45779. /*
  45780. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  45781. ** Convert this tree into a linked list connected by the pRight pointers
  45782. ** and return pointers to the first and last elements of the new list.
  45783. */
  45784. static void rowSetTreeToList(
  45785. struct RowSetEntry *pIn, /* Root of the input tree */
  45786. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  45787. struct RowSetEntry **ppLast /* Write tail of the output list here */
  45788. ){
  45789. assert( pIn!=0 );
  45790. if( pIn->pLeft ){
  45791. struct RowSetEntry *p;
  45792. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  45793. p->pRight = pIn;
  45794. }else{
  45795. *ppFirst = pIn;
  45796. }
  45797. if( pIn->pRight ){
  45798. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  45799. }else{
  45800. *ppLast = pIn;
  45801. }
  45802. assert( (*ppLast)->pRight==0 );
  45803. }
  45804. /*
  45805. ** Convert a sorted list of elements (connected by pRight) into a binary
  45806. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  45807. ** node taken from the head of *ppList. A depth of 2 means a tree with
  45808. ** three nodes. And so forth.
  45809. **
  45810. ** Use as many entries from the input list as required and update the
  45811. ** *ppList to point to the unused elements of the list. If the input
  45812. ** list contains too few elements, then construct an incomplete tree
  45813. ** and leave *ppList set to NULL.
  45814. **
  45815. ** Return a pointer to the root of the constructed binary tree.
  45816. */
  45817. static struct RowSetEntry *rowSetNDeepTree(
  45818. struct RowSetEntry **ppList,
  45819. int iDepth
  45820. ){
  45821. struct RowSetEntry *p; /* Root of the new tree */
  45822. struct RowSetEntry *pLeft; /* Left subtree */
  45823. if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
  45824. /* Prevent unnecessary deep recursion when we run out of entries */
  45825. return 0;
  45826. }
  45827. if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
  45828. /* This branch causes a *balanced* tree to be generated. A valid tree
  45829. ** is still generated without this branch, but the tree is wildly
  45830. ** unbalanced and inefficient. */
  45831. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  45832. p = *ppList;
  45833. if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
  45834. /* It is safe to always return here, but the resulting tree
  45835. ** would be unbalanced */
  45836. return pLeft;
  45837. }
  45838. p->pLeft = pLeft;
  45839. *ppList = p->pRight;
  45840. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  45841. }else{
  45842. p = *ppList;
  45843. *ppList = p->pRight;
  45844. p->pLeft = p->pRight = 0;
  45845. }
  45846. return p;
  45847. }
  45848. /*
  45849. ** Convert a sorted list of elements into a binary tree. Make the tree
  45850. ** as deep as it needs to be in order to contain the entire list.
  45851. */
  45852. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  45853. int iDepth; /* Depth of the tree so far */
  45854. struct RowSetEntry *p; /* Current tree root */
  45855. struct RowSetEntry *pLeft; /* Left subtree */
  45856. assert( pList!=0 );
  45857. p = pList;
  45858. pList = p->pRight;
  45859. p->pLeft = p->pRight = 0;
  45860. for(iDepth=1; pList; iDepth++){
  45861. pLeft = p;
  45862. p = pList;
  45863. pList = p->pRight;
  45864. p->pLeft = pLeft;
  45865. p->pRight = rowSetNDeepTree(&pList, iDepth);
  45866. }
  45867. return p;
  45868. }
  45869. /*
  45870. ** Extract the smallest element from the RowSet.
  45871. ** Write the element into *pRowid. Return 1 on success. Return
  45872. ** 0 if the RowSet is already empty.
  45873. **
  45874. ** After this routine has been called, the sqlite3RowSetInsert()
  45875. ** routine may not be called again.
  45876. **
  45877. ** This routine may not be called after sqlite3RowSetTest() has
  45878. ** been used. Older versions of RowSet allowed that, but as the
  45879. ** capability was not used by the code generator, it was removed
  45880. ** for code economy.
  45881. */
  45882. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  45883. assert( p!=0 );
  45884. assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
  45885. /* Merge the forest into a single sorted list on first call */
  45886. if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  45887. if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  45888. p->pEntry = rowSetEntrySort(p->pEntry);
  45889. }
  45890. p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
  45891. }
  45892. /* Return the next entry on the list */
  45893. if( p->pEntry ){
  45894. *pRowid = p->pEntry->v;
  45895. p->pEntry = p->pEntry->pRight;
  45896. if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
  45897. /* Free memory immediately, rather than waiting on sqlite3_finalize() */
  45898. sqlite3RowSetClear(p);
  45899. }
  45900. return 1;
  45901. }else{
  45902. return 0;
  45903. }
  45904. }
  45905. /*
  45906. ** Check to see if element iRowid was inserted into the rowset as
  45907. ** part of any insert batch prior to iBatch. Return 1 or 0.
  45908. **
  45909. ** If this is the first test of a new batch and if there exist entries
  45910. ** on pRowSet->pEntry, then sort those entries into the forest at
  45911. ** pRowSet->pForest so that they can be tested.
  45912. */
  45913. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  45914. struct RowSetEntry *p, *pTree;
  45915. /* This routine is never called after sqlite3RowSetNext() */
  45916. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  45917. /* Sort entries into the forest on the first test of a new batch.
  45918. ** To save unnecessary work, only do this when the batch number changes.
  45919. */
  45920. if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
  45921. p = pRowSet->pEntry;
  45922. if( p ){
  45923. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  45924. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  45925. /* Only sort the current set of entiries if they need it */
  45926. p = rowSetEntrySort(p);
  45927. }
  45928. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  45929. ppPrevTree = &pTree->pRight;
  45930. if( pTree->pLeft==0 ){
  45931. pTree->pLeft = rowSetListToTree(p);
  45932. break;
  45933. }else{
  45934. struct RowSetEntry *pAux, *pTail;
  45935. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  45936. pTree->pLeft = 0;
  45937. p = rowSetEntryMerge(pAux, p);
  45938. }
  45939. }
  45940. if( pTree==0 ){
  45941. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  45942. if( pTree ){
  45943. pTree->v = 0;
  45944. pTree->pRight = 0;
  45945. pTree->pLeft = rowSetListToTree(p);
  45946. }
  45947. }
  45948. pRowSet->pEntry = 0;
  45949. pRowSet->pLast = 0;
  45950. pRowSet->rsFlags |= ROWSET_SORTED;
  45951. }
  45952. pRowSet->iBatch = iBatch;
  45953. }
  45954. /* Test to see if the iRowid value appears anywhere in the forest.
  45955. ** Return 1 if it does and 0 if not.
  45956. */
  45957. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  45958. p = pTree->pLeft;
  45959. while( p ){
  45960. if( p->v<iRowid ){
  45961. p = p->pRight;
  45962. }else if( p->v>iRowid ){
  45963. p = p->pLeft;
  45964. }else{
  45965. return 1;
  45966. }
  45967. }
  45968. }
  45969. return 0;
  45970. }
  45971. /************** End of rowset.c **********************************************/
  45972. /************** Begin file pager.c *******************************************/
  45973. /*
  45974. ** 2001 September 15
  45975. **
  45976. ** The author disclaims copyright to this source code. In place of
  45977. ** a legal notice, here is a blessing:
  45978. **
  45979. ** May you do good and not evil.
  45980. ** May you find forgiveness for yourself and forgive others.
  45981. ** May you share freely, never taking more than you give.
  45982. **
  45983. *************************************************************************
  45984. ** This is the implementation of the page cache subsystem or "pager".
  45985. **
  45986. ** The pager is used to access a database disk file. It implements
  45987. ** atomic commit and rollback through the use of a journal file that
  45988. ** is separate from the database file. The pager also implements file
  45989. ** locking to prevent two processes from writing the same database
  45990. ** file simultaneously, or one process from reading the database while
  45991. ** another is writing.
  45992. */
  45993. #ifndef SQLITE_OMIT_DISKIO
  45994. /* #include "sqliteInt.h" */
  45995. /************** Include wal.h in the middle of pager.c ***********************/
  45996. /************** Begin file wal.h *********************************************/
  45997. /*
  45998. ** 2010 February 1
  45999. **
  46000. ** The author disclaims copyright to this source code. In place of
  46001. ** a legal notice, here is a blessing:
  46002. **
  46003. ** May you do good and not evil.
  46004. ** May you find forgiveness for yourself and forgive others.
  46005. ** May you share freely, never taking more than you give.
  46006. **
  46007. *************************************************************************
  46008. ** This header file defines the interface to the write-ahead logging
  46009. ** system. Refer to the comments below and the header comment attached to
  46010. ** the implementation of each function in log.c for further details.
  46011. */
  46012. #ifndef SQLITE_WAL_H
  46013. #define SQLITE_WAL_H
  46014. /* #include "sqliteInt.h" */
  46015. /* Macros for extracting appropriate sync flags for either transaction
  46016. ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
  46017. */
  46018. #define WAL_SYNC_FLAGS(X) ((X)&0x03)
  46019. #define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03)
  46020. #ifdef SQLITE_OMIT_WAL
  46021. # define sqlite3WalOpen(x,y,z) 0
  46022. # define sqlite3WalLimit(x,y)
  46023. # define sqlite3WalClose(v,w,x,y,z) 0
  46024. # define sqlite3WalBeginReadTransaction(y,z) 0
  46025. # define sqlite3WalEndReadTransaction(z)
  46026. # define sqlite3WalDbsize(y) 0
  46027. # define sqlite3WalBeginWriteTransaction(y) 0
  46028. # define sqlite3WalEndWriteTransaction(x) 0
  46029. # define sqlite3WalUndo(x,y,z) 0
  46030. # define sqlite3WalSavepoint(y,z)
  46031. # define sqlite3WalSavepointUndo(y,z) 0
  46032. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  46033. # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
  46034. # define sqlite3WalCallback(z) 0
  46035. # define sqlite3WalExclusiveMode(y,z) 0
  46036. # define sqlite3WalHeapMemory(z) 0
  46037. # define sqlite3WalFramesize(z) 0
  46038. # define sqlite3WalFindFrame(x,y,z) 0
  46039. # define sqlite3WalFile(x) 0
  46040. #else
  46041. #define WAL_SAVEPOINT_NDATA 4
  46042. /* Connection to a write-ahead log (WAL) file.
  46043. ** There is one object of this type for each pager.
  46044. */
  46045. typedef struct Wal Wal;
  46046. /* Open and close a connection to a write-ahead log. */
  46047. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  46048. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
  46049. /* Set the limiting size of a WAL file. */
  46050. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  46051. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  46052. ** snapshot is like a read-transaction. It is the state of the database
  46053. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  46054. ** preserves the current state even if the other threads or processes
  46055. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  46056. ** transaction and releases the lock.
  46057. */
  46058. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  46059. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  46060. /* Read a page from the write-ahead log, if it is present. */
  46061. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  46062. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  46063. /* If the WAL is not empty, return the size of the database. */
  46064. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  46065. /* Obtain or release the WRITER lock. */
  46066. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  46067. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  46068. /* Undo any frames written (but not committed) to the log */
  46069. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  46070. /* Return an integer that records the current (uncommitted) write
  46071. ** position in the WAL */
  46072. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  46073. /* Move the write position of the WAL back to iFrame. Called in
  46074. ** response to a ROLLBACK TO command. */
  46075. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  46076. /* Write a frame or frames to the log. */
  46077. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  46078. /* Copy pages from the log to the database file */
  46079. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  46080. Wal *pWal, /* Write-ahead log connection */
  46081. sqlite3 *db, /* Check this handle's interrupt flag */
  46082. int eMode, /* One of PASSIVE, FULL and RESTART */
  46083. int (*xBusy)(void*), /* Function to call when busy */
  46084. void *pBusyArg, /* Context argument for xBusyHandler */
  46085. int sync_flags, /* Flags to sync db file with (or 0) */
  46086. int nBuf, /* Size of buffer nBuf */
  46087. u8 *zBuf, /* Temporary buffer to use */
  46088. int *pnLog, /* OUT: Number of frames in WAL */
  46089. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  46090. );
  46091. /* Return the value to pass to a sqlite3_wal_hook callback, the
  46092. ** number of frames in the WAL at the point of the last commit since
  46093. ** sqlite3WalCallback() was called. If no commits have occurred since
  46094. ** the last call, then return 0.
  46095. */
  46096. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  46097. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  46098. ** by the pager layer on the database file.
  46099. */
  46100. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  46101. /* Return true if the argument is non-NULL and the WAL module is using
  46102. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  46103. ** WAL module is using shared-memory, return false.
  46104. */
  46105. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  46106. #ifdef SQLITE_ENABLE_SNAPSHOT
  46107. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  46108. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  46109. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
  46110. #endif
  46111. #ifdef SQLITE_ENABLE_ZIPVFS
  46112. /* If the WAL file is not empty, return the number of bytes of content
  46113. ** stored in each frame (i.e. the db page-size when the WAL was created).
  46114. */
  46115. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  46116. #endif
  46117. /* Return the sqlite3_file object for the WAL file */
  46118. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  46119. #endif /* ifndef SQLITE_OMIT_WAL */
  46120. #endif /* SQLITE_WAL_H */
  46121. /************** End of wal.h *************************************************/
  46122. /************** Continuing where we left off in pager.c **********************/
  46123. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  46124. **
  46125. ** This comment block describes invariants that hold when using a rollback
  46126. ** journal. These invariants do not apply for journal_mode=WAL,
  46127. ** journal_mode=MEMORY, or journal_mode=OFF.
  46128. **
  46129. ** Within this comment block, a page is deemed to have been synced
  46130. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  46131. ** Otherwise, the page is not synced until the xSync method of the VFS
  46132. ** is called successfully on the file containing the page.
  46133. **
  46134. ** Definition: A page of the database file is said to be "overwriteable" if
  46135. ** one or more of the following are true about the page:
  46136. **
  46137. ** (a) The original content of the page as it was at the beginning of
  46138. ** the transaction has been written into the rollback journal and
  46139. ** synced.
  46140. **
  46141. ** (b) The page was a freelist leaf page at the start of the transaction.
  46142. **
  46143. ** (c) The page number is greater than the largest page that existed in
  46144. ** the database file at the start of the transaction.
  46145. **
  46146. ** (1) A page of the database file is never overwritten unless one of the
  46147. ** following are true:
  46148. **
  46149. ** (a) The page and all other pages on the same sector are overwriteable.
  46150. **
  46151. ** (b) The atomic page write optimization is enabled, and the entire
  46152. ** transaction other than the update of the transaction sequence
  46153. ** number consists of a single page change.
  46154. **
  46155. ** (2) The content of a page written into the rollback journal exactly matches
  46156. ** both the content in the database when the rollback journal was written
  46157. ** and the content in the database at the beginning of the current
  46158. ** transaction.
  46159. **
  46160. ** (3) Writes to the database file are an integer multiple of the page size
  46161. ** in length and are aligned on a page boundary.
  46162. **
  46163. ** (4) Reads from the database file are either aligned on a page boundary and
  46164. ** an integer multiple of the page size in length or are taken from the
  46165. ** first 100 bytes of the database file.
  46166. **
  46167. ** (5) All writes to the database file are synced prior to the rollback journal
  46168. ** being deleted, truncated, or zeroed.
  46169. **
  46170. ** (6) If a master journal file is used, then all writes to the database file
  46171. ** are synced prior to the master journal being deleted.
  46172. **
  46173. ** Definition: Two databases (or the same database at two points it time)
  46174. ** are said to be "logically equivalent" if they give the same answer to
  46175. ** all queries. Note in particular the content of freelist leaf
  46176. ** pages can be changed arbitrarily without affecting the logical equivalence
  46177. ** of the database.
  46178. **
  46179. ** (7) At any time, if any subset, including the empty set and the total set,
  46180. ** of the unsynced changes to a rollback journal are removed and the
  46181. ** journal is rolled back, the resulting database file will be logically
  46182. ** equivalent to the database file at the beginning of the transaction.
  46183. **
  46184. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  46185. ** is called to restore the database file to the same size it was at
  46186. ** the beginning of the transaction. (In some VFSes, the xTruncate
  46187. ** method is a no-op, but that does not change the fact the SQLite will
  46188. ** invoke it.)
  46189. **
  46190. ** (9) Whenever the database file is modified, at least one bit in the range
  46191. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  46192. ** the EXCLUSIVE lock, thus signaling other connections on the same
  46193. ** database to flush their caches.
  46194. **
  46195. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  46196. ** than one billion transactions.
  46197. **
  46198. ** (11) A database file is well-formed at the beginning and at the conclusion
  46199. ** of every transaction.
  46200. **
  46201. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  46202. ** the database file.
  46203. **
  46204. ** (13) A SHARED lock is held on the database file while reading any
  46205. ** content out of the database file.
  46206. **
  46207. ******************************************************************************/
  46208. /*
  46209. ** Macros for troubleshooting. Normally turned off
  46210. */
  46211. #if 0
  46212. int sqlite3PagerTrace=1; /* True to enable tracing */
  46213. #define sqlite3DebugPrintf printf
  46214. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  46215. #else
  46216. #define PAGERTRACE(X)
  46217. #endif
  46218. /*
  46219. ** The following two macros are used within the PAGERTRACE() macros above
  46220. ** to print out file-descriptors.
  46221. **
  46222. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  46223. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  46224. ** struct as its argument.
  46225. */
  46226. #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
  46227. #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
  46228. /*
  46229. ** The Pager.eState variable stores the current 'state' of a pager. A
  46230. ** pager may be in any one of the seven states shown in the following
  46231. ** state diagram.
  46232. **
  46233. ** OPEN <------+------+
  46234. ** | | |
  46235. ** V | |
  46236. ** +---------> READER-------+ |
  46237. ** | | |
  46238. ** | V |
  46239. ** |<-------WRITER_LOCKED------> ERROR
  46240. ** | | ^
  46241. ** | V |
  46242. ** |<------WRITER_CACHEMOD-------->|
  46243. ** | | |
  46244. ** | V |
  46245. ** |<-------WRITER_DBMOD---------->|
  46246. ** | | |
  46247. ** | V |
  46248. ** +<------WRITER_FINISHED-------->+
  46249. **
  46250. **
  46251. ** List of state transitions and the C [function] that performs each:
  46252. **
  46253. ** OPEN -> READER [sqlite3PagerSharedLock]
  46254. ** READER -> OPEN [pager_unlock]
  46255. **
  46256. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  46257. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  46258. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  46259. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  46260. ** WRITER_*** -> READER [pager_end_transaction]
  46261. **
  46262. ** WRITER_*** -> ERROR [pager_error]
  46263. ** ERROR -> OPEN [pager_unlock]
  46264. **
  46265. **
  46266. ** OPEN:
  46267. **
  46268. ** The pager starts up in this state. Nothing is guaranteed in this
  46269. ** state - the file may or may not be locked and the database size is
  46270. ** unknown. The database may not be read or written.
  46271. **
  46272. ** * No read or write transaction is active.
  46273. ** * Any lock, or no lock at all, may be held on the database file.
  46274. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  46275. **
  46276. ** READER:
  46277. **
  46278. ** In this state all the requirements for reading the database in
  46279. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  46280. ** was) in exclusive-locking mode, a user-level read transaction is
  46281. ** open. The database size is known in this state.
  46282. **
  46283. ** A connection running with locking_mode=normal enters this state when
  46284. ** it opens a read-transaction on the database and returns to state
  46285. ** OPEN after the read-transaction is completed. However a connection
  46286. ** running in locking_mode=exclusive (including temp databases) remains in
  46287. ** this state even after the read-transaction is closed. The only way
  46288. ** a locking_mode=exclusive connection can transition from READER to OPEN
  46289. ** is via the ERROR state (see below).
  46290. **
  46291. ** * A read transaction may be active (but a write-transaction cannot).
  46292. ** * A SHARED or greater lock is held on the database file.
  46293. ** * The dbSize variable may be trusted (even if a user-level read
  46294. ** transaction is not active). The dbOrigSize and dbFileSize variables
  46295. ** may not be trusted at this point.
  46296. ** * If the database is a WAL database, then the WAL connection is open.
  46297. ** * Even if a read-transaction is not open, it is guaranteed that
  46298. ** there is no hot-journal in the file-system.
  46299. **
  46300. ** WRITER_LOCKED:
  46301. **
  46302. ** The pager moves to this state from READER when a write-transaction
  46303. ** is first opened on the database. In WRITER_LOCKED state, all locks
  46304. ** required to start a write-transaction are held, but no actual
  46305. ** modifications to the cache or database have taken place.
  46306. **
  46307. ** In rollback mode, a RESERVED or (if the transaction was opened with
  46308. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  46309. ** moving to this state, but the journal file is not written to or opened
  46310. ** to in this state. If the transaction is committed or rolled back while
  46311. ** in WRITER_LOCKED state, all that is required is to unlock the database
  46312. ** file.
  46313. **
  46314. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  46315. ** If the connection is running with locking_mode=exclusive, an attempt
  46316. ** is made to obtain an EXCLUSIVE lock on the database file.
  46317. **
  46318. ** * A write transaction is active.
  46319. ** * If the connection is open in rollback-mode, a RESERVED or greater
  46320. ** lock is held on the database file.
  46321. ** * If the connection is open in WAL-mode, a WAL write transaction
  46322. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  46323. ** called).
  46324. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  46325. ** * The contents of the pager cache have not been modified.
  46326. ** * The journal file may or may not be open.
  46327. ** * Nothing (not even the first header) has been written to the journal.
  46328. **
  46329. ** WRITER_CACHEMOD:
  46330. **
  46331. ** A pager moves from WRITER_LOCKED state to this state when a page is
  46332. ** first modified by the upper layer. In rollback mode the journal file
  46333. ** is opened (if it is not already open) and a header written to the
  46334. ** start of it. The database file on disk has not been modified.
  46335. **
  46336. ** * A write transaction is active.
  46337. ** * A RESERVED or greater lock is held on the database file.
  46338. ** * The journal file is open and the first header has been written
  46339. ** to it, but the header has not been synced to disk.
  46340. ** * The contents of the page cache have been modified.
  46341. **
  46342. ** WRITER_DBMOD:
  46343. **
  46344. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  46345. ** when it modifies the contents of the database file. WAL connections
  46346. ** never enter this state (since they do not modify the database file,
  46347. ** just the log file).
  46348. **
  46349. ** * A write transaction is active.
  46350. ** * An EXCLUSIVE or greater lock is held on the database file.
  46351. ** * The journal file is open and the first header has been written
  46352. ** and synced to disk.
  46353. ** * The contents of the page cache have been modified (and possibly
  46354. ** written to disk).
  46355. **
  46356. ** WRITER_FINISHED:
  46357. **
  46358. ** It is not possible for a WAL connection to enter this state.
  46359. **
  46360. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  46361. ** state after the entire transaction has been successfully written into the
  46362. ** database file. In this state the transaction may be committed simply
  46363. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  46364. ** not possible to modify the database further. At this point, the upper
  46365. ** layer must either commit or rollback the transaction.
  46366. **
  46367. ** * A write transaction is active.
  46368. ** * An EXCLUSIVE or greater lock is held on the database file.
  46369. ** * All writing and syncing of journal and database data has finished.
  46370. ** If no error occurred, all that remains is to finalize the journal to
  46371. ** commit the transaction. If an error did occur, the caller will need
  46372. ** to rollback the transaction.
  46373. **
  46374. ** ERROR:
  46375. **
  46376. ** The ERROR state is entered when an IO or disk-full error (including
  46377. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  46378. ** difficult to be sure that the in-memory pager state (cache contents,
  46379. ** db size etc.) are consistent with the contents of the file-system.
  46380. **
  46381. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  46382. ** cannot.
  46383. **
  46384. ** For example, if an IO error occurs while performing a rollback,
  46385. ** the contents of the page-cache may be left in an inconsistent state.
  46386. ** At this point it would be dangerous to change back to READER state
  46387. ** (as usually happens after a rollback). Any subsequent readers might
  46388. ** report database corruption (due to the inconsistent cache), and if
  46389. ** they upgrade to writers, they may inadvertently corrupt the database
  46390. ** file. To avoid this hazard, the pager switches into the ERROR state
  46391. ** instead of READER following such an error.
  46392. **
  46393. ** Once it has entered the ERROR state, any attempt to use the pager
  46394. ** to read or write data returns an error. Eventually, once all
  46395. ** outstanding transactions have been abandoned, the pager is able to
  46396. ** transition back to OPEN state, discarding the contents of the
  46397. ** page-cache and any other in-memory state at the same time. Everything
  46398. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  46399. ** when a read-transaction is next opened on the pager (transitioning
  46400. ** the pager into READER state). At that point the system has recovered
  46401. ** from the error.
  46402. **
  46403. ** Specifically, the pager jumps into the ERROR state if:
  46404. **
  46405. ** 1. An error occurs while attempting a rollback. This happens in
  46406. ** function sqlite3PagerRollback().
  46407. **
  46408. ** 2. An error occurs while attempting to finalize a journal file
  46409. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  46410. **
  46411. ** 3. An error occurs while attempting to write to the journal or
  46412. ** database file in function pagerStress() in order to free up
  46413. ** memory.
  46414. **
  46415. ** In other cases, the error is returned to the b-tree layer. The b-tree
  46416. ** layer then attempts a rollback operation. If the error condition
  46417. ** persists, the pager enters the ERROR state via condition (1) above.
  46418. **
  46419. ** Condition (3) is necessary because it can be triggered by a read-only
  46420. ** statement executed within a transaction. In this case, if the error
  46421. ** code were simply returned to the user, the b-tree layer would not
  46422. ** automatically attempt a rollback, as it assumes that an error in a
  46423. ** read-only statement cannot leave the pager in an internally inconsistent
  46424. ** state.
  46425. **
  46426. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  46427. ** * There are one or more outstanding references to pages (after the
  46428. ** last reference is dropped the pager should move back to OPEN state).
  46429. ** * The pager is not an in-memory pager.
  46430. **
  46431. **
  46432. ** Notes:
  46433. **
  46434. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  46435. ** connection is open in WAL mode. A WAL connection is always in one
  46436. ** of the first four states.
  46437. **
  46438. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  46439. ** state. There are two exceptions: immediately after exclusive-mode has
  46440. ** been turned on (and before any read or write transactions are
  46441. ** executed), and when the pager is leaving the "error state".
  46442. **
  46443. ** * See also: assert_pager_state().
  46444. */
  46445. #define PAGER_OPEN 0
  46446. #define PAGER_READER 1
  46447. #define PAGER_WRITER_LOCKED 2
  46448. #define PAGER_WRITER_CACHEMOD 3
  46449. #define PAGER_WRITER_DBMOD 4
  46450. #define PAGER_WRITER_FINISHED 5
  46451. #define PAGER_ERROR 6
  46452. /*
  46453. ** The Pager.eLock variable is almost always set to one of the
  46454. ** following locking-states, according to the lock currently held on
  46455. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  46456. ** This variable is kept up to date as locks are taken and released by
  46457. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  46458. **
  46459. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  46460. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  46461. ** the operation was successful. In these circumstances pagerLockDb() and
  46462. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  46463. ** when unlocking the file, and only updated when locking the file if the
  46464. ** VFS call is successful. This way, the Pager.eLock variable may be set
  46465. ** to a less exclusive (lower) value than the lock that is actually held
  46466. ** at the system level, but it is never set to a more exclusive value.
  46467. **
  46468. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  46469. ** be a few redundant xLock() calls or a lock may be held for longer than
  46470. ** required, but nothing really goes wrong.
  46471. **
  46472. ** The exception is when the database file is unlocked as the pager moves
  46473. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  46474. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  46475. ** transition, by the same pager or any other). If the call to xUnlock()
  46476. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  46477. ** can confuse the call to xCheckReservedLock() call made later as part
  46478. ** of hot-journal detection.
  46479. **
  46480. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  46481. ** lock held by this process or any others". So xCheckReservedLock may
  46482. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  46483. ** doesn't know it because of a previous error in xUnlock). If this happens
  46484. ** a hot-journal may be mistaken for a journal being created by an active
  46485. ** transaction in another process, causing SQLite to read from the database
  46486. ** without rolling it back.
  46487. **
  46488. ** To work around this, if a call to xUnlock() fails when unlocking the
  46489. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  46490. ** is only changed back to a real locking state after a successful call
  46491. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  46492. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  46493. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  46494. ** lock on the database file before attempting to roll it back. See function
  46495. ** PagerSharedLock() for more detail.
  46496. **
  46497. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  46498. ** PAGER_OPEN state.
  46499. */
  46500. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  46501. /*
  46502. ** A macro used for invoking the codec if there is one
  46503. */
  46504. #ifdef SQLITE_HAS_CODEC
  46505. # define CODEC1(P,D,N,X,E) \
  46506. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  46507. # define CODEC2(P,D,N,X,E,O) \
  46508. if( P->xCodec==0 ){ O=(char*)D; }else \
  46509. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  46510. #else
  46511. # define CODEC1(P,D,N,X,E) /* NO-OP */
  46512. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  46513. #endif
  46514. /*
  46515. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  46516. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  46517. ** This could conceivably cause corruption following a power failure on
  46518. ** such a system. This is currently an undocumented limit.
  46519. */
  46520. #define MAX_SECTOR_SIZE 0x10000
  46521. /*
  46522. ** An instance of the following structure is allocated for each active
  46523. ** savepoint and statement transaction in the system. All such structures
  46524. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  46525. ** resized using sqlite3Realloc().
  46526. **
  46527. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  46528. ** set to 0. If a journal-header is written into the main journal while
  46529. ** the savepoint is active, then iHdrOffset is set to the byte offset
  46530. ** immediately following the last journal record written into the main
  46531. ** journal before the journal-header. This is required during savepoint
  46532. ** rollback (see pagerPlaybackSavepoint()).
  46533. */
  46534. typedef struct PagerSavepoint PagerSavepoint;
  46535. struct PagerSavepoint {
  46536. i64 iOffset; /* Starting offset in main journal */
  46537. i64 iHdrOffset; /* See above */
  46538. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  46539. Pgno nOrig; /* Original number of pages in file */
  46540. Pgno iSubRec; /* Index of first record in sub-journal */
  46541. #ifndef SQLITE_OMIT_WAL
  46542. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  46543. #endif
  46544. };
  46545. /*
  46546. ** Bits of the Pager.doNotSpill flag. See further description below.
  46547. */
  46548. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  46549. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  46550. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  46551. /*
  46552. ** An open page cache is an instance of struct Pager. A description of
  46553. ** some of the more important member variables follows:
  46554. **
  46555. ** eState
  46556. **
  46557. ** The current 'state' of the pager object. See the comment and state
  46558. ** diagram above for a description of the pager state.
  46559. **
  46560. ** eLock
  46561. **
  46562. ** For a real on-disk database, the current lock held on the database file -
  46563. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  46564. **
  46565. ** For a temporary or in-memory database (neither of which require any
  46566. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  46567. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  46568. ** logic into thinking that it already has all the locks it will ever
  46569. ** need (and no reason to release them).
  46570. **
  46571. ** In some (obscure) circumstances, this variable may also be set to
  46572. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  46573. ** details.
  46574. **
  46575. ** changeCountDone
  46576. **
  46577. ** This boolean variable is used to make sure that the change-counter
  46578. ** (the 4-byte header field at byte offset 24 of the database file) is
  46579. ** not updated more often than necessary.
  46580. **
  46581. ** It is set to true when the change-counter field is updated, which
  46582. ** can only happen if an exclusive lock is held on the database file.
  46583. ** It is cleared (set to false) whenever an exclusive lock is
  46584. ** relinquished on the database file. Each time a transaction is committed,
  46585. ** The changeCountDone flag is inspected. If it is true, the work of
  46586. ** updating the change-counter is omitted for the current transaction.
  46587. **
  46588. ** This mechanism means that when running in exclusive mode, a connection
  46589. ** need only update the change-counter once, for the first transaction
  46590. ** committed.
  46591. **
  46592. ** setMaster
  46593. **
  46594. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  46595. ** (or may not) specify a master-journal name to be written into the
  46596. ** journal file before it is synced to disk.
  46597. **
  46598. ** Whether or not a journal file contains a master-journal pointer affects
  46599. ** the way in which the journal file is finalized after the transaction is
  46600. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  46601. ** If a journal file does not contain a master-journal pointer, it is
  46602. ** finalized by overwriting the first journal header with zeroes. If
  46603. ** it does contain a master-journal pointer the journal file is finalized
  46604. ** by truncating it to zero bytes, just as if the connection were
  46605. ** running in "journal_mode=truncate" mode.
  46606. **
  46607. ** Journal files that contain master journal pointers cannot be finalized
  46608. ** simply by overwriting the first journal-header with zeroes, as the
  46609. ** master journal pointer could interfere with hot-journal rollback of any
  46610. ** subsequently interrupted transaction that reuses the journal file.
  46611. **
  46612. ** The flag is cleared as soon as the journal file is finalized (either
  46613. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  46614. ** journal file from being successfully finalized, the setMaster flag
  46615. ** is cleared anyway (and the pager will move to ERROR state).
  46616. **
  46617. ** doNotSpill
  46618. **
  46619. ** This variables control the behavior of cache-spills (calls made by
  46620. ** the pcache module to the pagerStress() routine to write cached data
  46621. ** to the file-system in order to free up memory).
  46622. **
  46623. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  46624. ** writing to the database from pagerStress() is disabled altogether.
  46625. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  46626. ** comes up during savepoint rollback that requires the pcache module
  46627. ** to allocate a new page to prevent the journal file from being written
  46628. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  46629. ** case is a user preference.
  46630. **
  46631. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  46632. ** pagerStress() is permitted, but syncing the journal file is not.
  46633. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  46634. ** is larger than the database page-size in order to prevent a journal sync
  46635. ** from happening in between the journalling of two pages on the same sector.
  46636. **
  46637. ** subjInMemory
  46638. **
  46639. ** This is a boolean variable. If true, then any required sub-journal
  46640. ** is opened as an in-memory journal file. If false, then in-memory
  46641. ** sub-journals are only used for in-memory pager files.
  46642. **
  46643. ** This variable is updated by the upper layer each time a new
  46644. ** write-transaction is opened.
  46645. **
  46646. ** dbSize, dbOrigSize, dbFileSize
  46647. **
  46648. ** Variable dbSize is set to the number of pages in the database file.
  46649. ** It is valid in PAGER_READER and higher states (all states except for
  46650. ** OPEN and ERROR).
  46651. **
  46652. ** dbSize is set based on the size of the database file, which may be
  46653. ** larger than the size of the database (the value stored at offset
  46654. ** 28 of the database header by the btree). If the size of the file
  46655. ** is not an integer multiple of the page-size, the value stored in
  46656. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  46657. ** Except, any file that is greater than 0 bytes in size is considered
  46658. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  46659. ** to dbSize==1).
  46660. **
  46661. ** During a write-transaction, if pages with page-numbers greater than
  46662. ** dbSize are modified in the cache, dbSize is updated accordingly.
  46663. ** Similarly, if the database is truncated using PagerTruncateImage(),
  46664. ** dbSize is updated.
  46665. **
  46666. ** Variables dbOrigSize and dbFileSize are valid in states
  46667. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  46668. ** variable at the start of the transaction. It is used during rollback,
  46669. ** and to determine whether or not pages need to be journalled before
  46670. ** being modified.
  46671. **
  46672. ** Throughout a write-transaction, dbFileSize contains the size of
  46673. ** the file on disk in pages. It is set to a copy of dbSize when the
  46674. ** write-transaction is first opened, and updated when VFS calls are made
  46675. ** to write or truncate the database file on disk.
  46676. **
  46677. ** The only reason the dbFileSize variable is required is to suppress
  46678. ** unnecessary calls to xTruncate() after committing a transaction. If,
  46679. ** when a transaction is committed, the dbFileSize variable indicates
  46680. ** that the database file is larger than the database image (Pager.dbSize),
  46681. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  46682. ** to measure the database file on disk, and then truncates it if required.
  46683. ** dbFileSize is not used when rolling back a transaction. In this case
  46684. ** pager_truncate() is called unconditionally (which means there may be
  46685. ** a call to xFilesize() that is not strictly required). In either case,
  46686. ** pager_truncate() may cause the file to become smaller or larger.
  46687. **
  46688. ** dbHintSize
  46689. **
  46690. ** The dbHintSize variable is used to limit the number of calls made to
  46691. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  46692. **
  46693. ** dbHintSize is set to a copy of the dbSize variable when a
  46694. ** write-transaction is opened (at the same time as dbFileSize and
  46695. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  46696. ** dbHintSize is increased to the number of pages that correspond to the
  46697. ** size-hint passed to the method call. See pager_write_pagelist() for
  46698. ** details.
  46699. **
  46700. ** errCode
  46701. **
  46702. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  46703. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  46704. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  46705. ** sub-codes.
  46706. **
  46707. ** syncFlags, walSyncFlags
  46708. **
  46709. ** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
  46710. ** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode
  46711. ** and contains the flags used to sync the checkpoint operations in the
  46712. ** lower two bits, and sync flags used for transaction commits in the WAL
  46713. ** file in bits 0x04 and 0x08. In other words, to get the correct sync flags
  46714. ** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
  46715. ** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note
  46716. ** that with synchronous=NORMAL in WAL mode, transaction commit is not synced
  46717. ** meaning that the 0x04 and 0x08 bits are both zero.
  46718. */
  46719. struct Pager {
  46720. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  46721. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  46722. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  46723. u8 useJournal; /* Use a rollback journal on this file */
  46724. u8 noSync; /* Do not sync the journal if true */
  46725. u8 fullSync; /* Do extra syncs of the journal for robustness */
  46726. u8 extraSync; /* sync directory after journal delete */
  46727. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  46728. u8 walSyncFlags; /* See description above */
  46729. u8 tempFile; /* zFilename is a temporary or immutable file */
  46730. u8 noLock; /* Do not lock (except in WAL mode) */
  46731. u8 readOnly; /* True for a read-only database */
  46732. u8 memDb; /* True to inhibit all file I/O */
  46733. /**************************************************************************
  46734. ** The following block contains those class members that change during
  46735. ** routine operation. Class members not in this block are either fixed
  46736. ** when the pager is first created or else only change when there is a
  46737. ** significant mode change (such as changing the page_size, locking_mode,
  46738. ** or the journal_mode). From another view, these class members describe
  46739. ** the "state" of the pager, while other class members describe the
  46740. ** "configuration" of the pager.
  46741. */
  46742. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  46743. u8 eLock; /* Current lock held on database file */
  46744. u8 changeCountDone; /* Set after incrementing the change-counter */
  46745. u8 setMaster; /* True if a m-j name has been written to jrnl */
  46746. u8 doNotSpill; /* Do not spill the cache when non-zero */
  46747. u8 subjInMemory; /* True to use in-memory sub-journals */
  46748. u8 bUseFetch; /* True to use xFetch() */
  46749. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  46750. Pgno dbSize; /* Number of pages in the database */
  46751. Pgno dbOrigSize; /* dbSize before the current transaction */
  46752. Pgno dbFileSize; /* Number of pages in the database file */
  46753. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  46754. int errCode; /* One of several kinds of errors */
  46755. int nRec; /* Pages journalled since last j-header written */
  46756. u32 cksumInit; /* Quasi-random value added to every checksum */
  46757. u32 nSubRec; /* Number of records written to sub-journal */
  46758. Bitvec *pInJournal; /* One bit for each page in the database file */
  46759. sqlite3_file *fd; /* File descriptor for database */
  46760. sqlite3_file *jfd; /* File descriptor for main journal */
  46761. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  46762. i64 journalOff; /* Current write offset in the journal file */
  46763. i64 journalHdr; /* Byte offset to previous journal header */
  46764. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  46765. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  46766. int nSavepoint; /* Number of elements in aSavepoint[] */
  46767. u32 iDataVersion; /* Changes whenever database content changes */
  46768. char dbFileVers[16]; /* Changes whenever database file changes */
  46769. int nMmapOut; /* Number of mmap pages currently outstanding */
  46770. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  46771. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  46772. /*
  46773. ** End of the routinely-changing class members
  46774. ***************************************************************************/
  46775. u16 nExtra; /* Add this many bytes to each in-memory page */
  46776. i16 nReserve; /* Number of unused bytes at end of each page */
  46777. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  46778. u32 sectorSize; /* Assumed sector size during rollback */
  46779. int pageSize; /* Number of bytes in a page */
  46780. Pgno mxPgno; /* Maximum allowed size of the database */
  46781. i64 journalSizeLimit; /* Size limit for persistent journal files */
  46782. char *zFilename; /* Name of the database file */
  46783. char *zJournal; /* Name of the journal file */
  46784. int (*xBusyHandler)(void*); /* Function to call when busy */
  46785. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  46786. int aStat[4]; /* Total cache hits, misses, writes, spills */
  46787. #ifdef SQLITE_TEST
  46788. int nRead; /* Database pages read */
  46789. #endif
  46790. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  46791. int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
  46792. #ifdef SQLITE_HAS_CODEC
  46793. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  46794. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  46795. void (*xCodecFree)(void*); /* Destructor for the codec */
  46796. void *pCodec; /* First argument to xCodec... methods */
  46797. #endif
  46798. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  46799. PCache *pPCache; /* Pointer to page cache object */
  46800. #ifndef SQLITE_OMIT_WAL
  46801. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  46802. char *zWal; /* File name for write-ahead log */
  46803. #endif
  46804. };
  46805. /*
  46806. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  46807. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  46808. ** or CACHE_WRITE to sqlite3_db_status().
  46809. */
  46810. #define PAGER_STAT_HIT 0
  46811. #define PAGER_STAT_MISS 1
  46812. #define PAGER_STAT_WRITE 2
  46813. #define PAGER_STAT_SPILL 3
  46814. /*
  46815. ** The following global variables hold counters used for
  46816. ** testing purposes only. These variables do not exist in
  46817. ** a non-testing build. These variables are not thread-safe.
  46818. */
  46819. #ifdef SQLITE_TEST
  46820. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  46821. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  46822. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  46823. # define PAGER_INCR(v) v++
  46824. #else
  46825. # define PAGER_INCR(v)
  46826. #endif
  46827. /*
  46828. ** Journal files begin with the following magic string. The data
  46829. ** was obtained from /dev/random. It is used only as a sanity check.
  46830. **
  46831. ** Since version 2.8.0, the journal format contains additional sanity
  46832. ** checking information. If the power fails while the journal is being
  46833. ** written, semi-random garbage data might appear in the journal
  46834. ** file after power is restored. If an attempt is then made
  46835. ** to roll the journal back, the database could be corrupted. The additional
  46836. ** sanity checking data is an attempt to discover the garbage in the
  46837. ** journal and ignore it.
  46838. **
  46839. ** The sanity checking information for the new journal format consists
  46840. ** of a 32-bit checksum on each page of data. The checksum covers both
  46841. ** the page number and the pPager->pageSize bytes of data for the page.
  46842. ** This cksum is initialized to a 32-bit random value that appears in the
  46843. ** journal file right after the header. The random initializer is important,
  46844. ** because garbage data that appears at the end of a journal is likely
  46845. ** data that was once in other files that have now been deleted. If the
  46846. ** garbage data came from an obsolete journal file, the checksums might
  46847. ** be correct. But by initializing the checksum to random value which
  46848. ** is different for every journal, we minimize that risk.
  46849. */
  46850. static const unsigned char aJournalMagic[] = {
  46851. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  46852. };
  46853. /*
  46854. ** The size of the of each page record in the journal is given by
  46855. ** the following macro.
  46856. */
  46857. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  46858. /*
  46859. ** The journal header size for this pager. This is usually the same
  46860. ** size as a single disk sector. See also setSectorSize().
  46861. */
  46862. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  46863. /*
  46864. ** The macro MEMDB is true if we are dealing with an in-memory database.
  46865. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  46866. ** the value of MEMDB will be a constant and the compiler will optimize
  46867. ** out code that would never execute.
  46868. */
  46869. #ifdef SQLITE_OMIT_MEMORYDB
  46870. # define MEMDB 0
  46871. #else
  46872. # define MEMDB pPager->memDb
  46873. #endif
  46874. /*
  46875. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  46876. ** interfaces to access the database using memory-mapped I/O.
  46877. */
  46878. #if SQLITE_MAX_MMAP_SIZE>0
  46879. # define USEFETCH(x) ((x)->bUseFetch)
  46880. #else
  46881. # define USEFETCH(x) 0
  46882. #endif
  46883. /*
  46884. ** The maximum legal page number is (2^31 - 1).
  46885. */
  46886. #define PAGER_MAX_PGNO 2147483647
  46887. /*
  46888. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  46889. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  46890. **
  46891. ** This is so that expressions can be written as:
  46892. **
  46893. ** if( isOpen(pPager->jfd) ){ ...
  46894. **
  46895. ** instead of
  46896. **
  46897. ** if( pPager->jfd->pMethods ){ ...
  46898. */
  46899. #define isOpen(pFd) ((pFd)->pMethods!=0)
  46900. /*
  46901. ** Return true if this pager uses a write-ahead log to read page pgno.
  46902. ** Return false if the pager reads pgno directly from the database.
  46903. */
  46904. #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_DIRECT_OVERFLOW_READ)
  46905. SQLITE_PRIVATE int sqlite3PagerUseWal(Pager *pPager, Pgno pgno){
  46906. u32 iRead = 0;
  46907. int rc;
  46908. if( pPager->pWal==0 ) return 0;
  46909. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
  46910. return rc || iRead;
  46911. }
  46912. #endif
  46913. #ifndef SQLITE_OMIT_WAL
  46914. # define pagerUseWal(x) ((x)->pWal!=0)
  46915. #else
  46916. # define pagerUseWal(x) 0
  46917. # define pagerRollbackWal(x) 0
  46918. # define pagerWalFrames(v,w,x,y) 0
  46919. # define pagerOpenWalIfPresent(z) SQLITE_OK
  46920. # define pagerBeginReadTransaction(z) SQLITE_OK
  46921. #endif
  46922. #ifndef NDEBUG
  46923. /*
  46924. ** Usage:
  46925. **
  46926. ** assert( assert_pager_state(pPager) );
  46927. **
  46928. ** This function runs many asserts to try to find inconsistencies in
  46929. ** the internal state of the Pager object.
  46930. */
  46931. static int assert_pager_state(Pager *p){
  46932. Pager *pPager = p;
  46933. /* State must be valid. */
  46934. assert( p->eState==PAGER_OPEN
  46935. || p->eState==PAGER_READER
  46936. || p->eState==PAGER_WRITER_LOCKED
  46937. || p->eState==PAGER_WRITER_CACHEMOD
  46938. || p->eState==PAGER_WRITER_DBMOD
  46939. || p->eState==PAGER_WRITER_FINISHED
  46940. || p->eState==PAGER_ERROR
  46941. );
  46942. /* Regardless of the current state, a temp-file connection always behaves
  46943. ** as if it has an exclusive lock on the database file. It never updates
  46944. ** the change-counter field, so the changeCountDone flag is always set.
  46945. */
  46946. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  46947. assert( p->tempFile==0 || pPager->changeCountDone );
  46948. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  46949. ** And if the journal-mode is "OFF", the journal file must not be open.
  46950. */
  46951. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  46952. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  46953. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  46954. ** this means an in-memory pager performs no IO at all, it cannot encounter
  46955. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  46956. ** a journal file. (although the in-memory journal implementation may
  46957. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  46958. ** is therefore not possible for an in-memory pager to enter the ERROR
  46959. ** state.
  46960. */
  46961. if( MEMDB ){
  46962. assert( !isOpen(p->fd) );
  46963. assert( p->noSync );
  46964. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  46965. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  46966. );
  46967. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  46968. assert( pagerUseWal(p)==0 );
  46969. }
  46970. /* If changeCountDone is set, a RESERVED lock or greater must be held
  46971. ** on the file.
  46972. */
  46973. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  46974. assert( p->eLock!=PENDING_LOCK );
  46975. switch( p->eState ){
  46976. case PAGER_OPEN:
  46977. assert( !MEMDB );
  46978. assert( pPager->errCode==SQLITE_OK );
  46979. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  46980. break;
  46981. case PAGER_READER:
  46982. assert( pPager->errCode==SQLITE_OK );
  46983. assert( p->eLock!=UNKNOWN_LOCK );
  46984. assert( p->eLock>=SHARED_LOCK );
  46985. break;
  46986. case PAGER_WRITER_LOCKED:
  46987. assert( p->eLock!=UNKNOWN_LOCK );
  46988. assert( pPager->errCode==SQLITE_OK );
  46989. if( !pagerUseWal(pPager) ){
  46990. assert( p->eLock>=RESERVED_LOCK );
  46991. }
  46992. assert( pPager->dbSize==pPager->dbOrigSize );
  46993. assert( pPager->dbOrigSize==pPager->dbFileSize );
  46994. assert( pPager->dbOrigSize==pPager->dbHintSize );
  46995. assert( pPager->setMaster==0 );
  46996. break;
  46997. case PAGER_WRITER_CACHEMOD:
  46998. assert( p->eLock!=UNKNOWN_LOCK );
  46999. assert( pPager->errCode==SQLITE_OK );
  47000. if( !pagerUseWal(pPager) ){
  47001. /* It is possible that if journal_mode=wal here that neither the
  47002. ** journal file nor the WAL file are open. This happens during
  47003. ** a rollback transaction that switches from journal_mode=off
  47004. ** to journal_mode=wal.
  47005. */
  47006. assert( p->eLock>=RESERVED_LOCK );
  47007. assert( isOpen(p->jfd)
  47008. || p->journalMode==PAGER_JOURNALMODE_OFF
  47009. || p->journalMode==PAGER_JOURNALMODE_WAL
  47010. );
  47011. }
  47012. assert( pPager->dbOrigSize==pPager->dbFileSize );
  47013. assert( pPager->dbOrigSize==pPager->dbHintSize );
  47014. break;
  47015. case PAGER_WRITER_DBMOD:
  47016. assert( p->eLock==EXCLUSIVE_LOCK );
  47017. assert( pPager->errCode==SQLITE_OK );
  47018. assert( !pagerUseWal(pPager) );
  47019. assert( p->eLock>=EXCLUSIVE_LOCK );
  47020. assert( isOpen(p->jfd)
  47021. || p->journalMode==PAGER_JOURNALMODE_OFF
  47022. || p->journalMode==PAGER_JOURNALMODE_WAL
  47023. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  47024. );
  47025. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  47026. break;
  47027. case PAGER_WRITER_FINISHED:
  47028. assert( p->eLock==EXCLUSIVE_LOCK );
  47029. assert( pPager->errCode==SQLITE_OK );
  47030. assert( !pagerUseWal(pPager) );
  47031. assert( isOpen(p->jfd)
  47032. || p->journalMode==PAGER_JOURNALMODE_OFF
  47033. || p->journalMode==PAGER_JOURNALMODE_WAL
  47034. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  47035. );
  47036. break;
  47037. case PAGER_ERROR:
  47038. /* There must be at least one outstanding reference to the pager if
  47039. ** in ERROR state. Otherwise the pager should have already dropped
  47040. ** back to OPEN state.
  47041. */
  47042. assert( pPager->errCode!=SQLITE_OK );
  47043. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
  47044. break;
  47045. }
  47046. return 1;
  47047. }
  47048. #endif /* ifndef NDEBUG */
  47049. #ifdef SQLITE_DEBUG
  47050. /*
  47051. ** Return a pointer to a human readable string in a static buffer
  47052. ** containing the state of the Pager object passed as an argument. This
  47053. ** is intended to be used within debuggers. For example, as an alternative
  47054. ** to "print *pPager" in gdb:
  47055. **
  47056. ** (gdb) printf "%s", print_pager_state(pPager)
  47057. */
  47058. static char *print_pager_state(Pager *p){
  47059. static char zRet[1024];
  47060. sqlite3_snprintf(1024, zRet,
  47061. "Filename: %s\n"
  47062. "State: %s errCode=%d\n"
  47063. "Lock: %s\n"
  47064. "Locking mode: locking_mode=%s\n"
  47065. "Journal mode: journal_mode=%s\n"
  47066. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  47067. "Journal: journalOff=%lld journalHdr=%lld\n"
  47068. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  47069. , p->zFilename
  47070. , p->eState==PAGER_OPEN ? "OPEN" :
  47071. p->eState==PAGER_READER ? "READER" :
  47072. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  47073. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  47074. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  47075. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  47076. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  47077. , (int)p->errCode
  47078. , p->eLock==NO_LOCK ? "NO_LOCK" :
  47079. p->eLock==RESERVED_LOCK ? "RESERVED" :
  47080. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  47081. p->eLock==SHARED_LOCK ? "SHARED" :
  47082. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  47083. , p->exclusiveMode ? "exclusive" : "normal"
  47084. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  47085. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  47086. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  47087. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  47088. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  47089. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  47090. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  47091. , p->journalOff, p->journalHdr
  47092. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  47093. );
  47094. return zRet;
  47095. }
  47096. #endif
  47097. /* Forward references to the various page getters */
  47098. static int getPageNormal(Pager*,Pgno,DbPage**,int);
  47099. static int getPageError(Pager*,Pgno,DbPage**,int);
  47100. #if SQLITE_MAX_MMAP_SIZE>0
  47101. static int getPageMMap(Pager*,Pgno,DbPage**,int);
  47102. #endif
  47103. /*
  47104. ** Set the Pager.xGet method for the appropriate routine used to fetch
  47105. ** content from the pager.
  47106. */
  47107. static void setGetterMethod(Pager *pPager){
  47108. if( pPager->errCode ){
  47109. pPager->xGet = getPageError;
  47110. #if SQLITE_MAX_MMAP_SIZE>0
  47111. }else if( USEFETCH(pPager)
  47112. #ifdef SQLITE_HAS_CODEC
  47113. && pPager->xCodec==0
  47114. #endif
  47115. ){
  47116. pPager->xGet = getPageMMap;
  47117. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  47118. }else{
  47119. pPager->xGet = getPageNormal;
  47120. }
  47121. }
  47122. /*
  47123. ** Return true if it is necessary to write page *pPg into the sub-journal.
  47124. ** A page needs to be written into the sub-journal if there exists one
  47125. ** or more open savepoints for which:
  47126. **
  47127. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  47128. ** * The bit corresponding to the page-number is not set in
  47129. ** PagerSavepoint.pInSavepoint.
  47130. */
  47131. static int subjRequiresPage(PgHdr *pPg){
  47132. Pager *pPager = pPg->pPager;
  47133. PagerSavepoint *p;
  47134. Pgno pgno = pPg->pgno;
  47135. int i;
  47136. for(i=0; i<pPager->nSavepoint; i++){
  47137. p = &pPager->aSavepoint[i];
  47138. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  47139. return 1;
  47140. }
  47141. }
  47142. return 0;
  47143. }
  47144. #ifdef SQLITE_DEBUG
  47145. /*
  47146. ** Return true if the page is already in the journal file.
  47147. */
  47148. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  47149. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  47150. }
  47151. #endif
  47152. /*
  47153. ** Read a 32-bit integer from the given file descriptor. Store the integer
  47154. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  47155. ** error code is something goes wrong.
  47156. **
  47157. ** All values are stored on disk as big-endian.
  47158. */
  47159. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  47160. unsigned char ac[4];
  47161. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  47162. if( rc==SQLITE_OK ){
  47163. *pRes = sqlite3Get4byte(ac);
  47164. }
  47165. return rc;
  47166. }
  47167. /*
  47168. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  47169. */
  47170. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  47171. /*
  47172. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  47173. ** on success or an error code is something goes wrong.
  47174. */
  47175. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  47176. char ac[4];
  47177. put32bits(ac, val);
  47178. return sqlite3OsWrite(fd, ac, 4, offset);
  47179. }
  47180. /*
  47181. ** Unlock the database file to level eLock, which must be either NO_LOCK
  47182. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  47183. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  47184. **
  47185. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  47186. ** called, do not modify it. See the comment above the #define of
  47187. ** UNKNOWN_LOCK for an explanation of this.
  47188. */
  47189. static int pagerUnlockDb(Pager *pPager, int eLock){
  47190. int rc = SQLITE_OK;
  47191. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  47192. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  47193. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  47194. if( isOpen(pPager->fd) ){
  47195. assert( pPager->eLock>=eLock );
  47196. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  47197. if( pPager->eLock!=UNKNOWN_LOCK ){
  47198. pPager->eLock = (u8)eLock;
  47199. }
  47200. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  47201. }
  47202. return rc;
  47203. }
  47204. /*
  47205. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  47206. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  47207. ** Pager.eLock variable to the new locking state.
  47208. **
  47209. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  47210. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  47211. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  47212. ** of this.
  47213. */
  47214. static int pagerLockDb(Pager *pPager, int eLock){
  47215. int rc = SQLITE_OK;
  47216. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  47217. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  47218. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  47219. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  47220. pPager->eLock = (u8)eLock;
  47221. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  47222. }
  47223. }
  47224. return rc;
  47225. }
  47226. /*
  47227. ** This function determines whether or not the atomic-write or
  47228. ** atomic-batch-write optimizations can be used with this pager. The
  47229. ** atomic-write optimization can be used if:
  47230. **
  47231. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  47232. ** a database page may be written atomically, and
  47233. ** (b) the value returned by OsSectorSize() is less than or equal
  47234. ** to the page size.
  47235. **
  47236. ** If it can be used, then the value returned is the size of the journal
  47237. ** file when it contains rollback data for exactly one page.
  47238. **
  47239. ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
  47240. ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
  47241. ** returned in this case.
  47242. **
  47243. ** If neither optimization can be used, 0 is returned.
  47244. */
  47245. static int jrnlBufferSize(Pager *pPager){
  47246. assert( !MEMDB );
  47247. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  47248. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  47249. int dc; /* Device characteristics */
  47250. assert( isOpen(pPager->fd) );
  47251. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  47252. #else
  47253. UNUSED_PARAMETER(pPager);
  47254. #endif
  47255. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  47256. if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
  47257. return -1;
  47258. }
  47259. #endif
  47260. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  47261. {
  47262. int nSector = pPager->sectorSize;
  47263. int szPage = pPager->pageSize;
  47264. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  47265. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  47266. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  47267. return 0;
  47268. }
  47269. }
  47270. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  47271. #endif
  47272. return 0;
  47273. }
  47274. /*
  47275. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  47276. ** on the cache using a hash function. This is used for testing
  47277. ** and debugging only.
  47278. */
  47279. #ifdef SQLITE_CHECK_PAGES
  47280. /*
  47281. ** Return a 32-bit hash of the page data for pPage.
  47282. */
  47283. static u32 pager_datahash(int nByte, unsigned char *pData){
  47284. u32 hash = 0;
  47285. int i;
  47286. for(i=0; i<nByte; i++){
  47287. hash = (hash*1039) + pData[i];
  47288. }
  47289. return hash;
  47290. }
  47291. static u32 pager_pagehash(PgHdr *pPage){
  47292. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  47293. }
  47294. static void pager_set_pagehash(PgHdr *pPage){
  47295. pPage->pageHash = pager_pagehash(pPage);
  47296. }
  47297. /*
  47298. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  47299. ** is defined, and NDEBUG is not defined, an assert() statement checks
  47300. ** that the page is either dirty or still matches the calculated page-hash.
  47301. */
  47302. #define CHECK_PAGE(x) checkPage(x)
  47303. static void checkPage(PgHdr *pPg){
  47304. Pager *pPager = pPg->pPager;
  47305. assert( pPager->eState!=PAGER_ERROR );
  47306. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  47307. }
  47308. #else
  47309. #define pager_datahash(X,Y) 0
  47310. #define pager_pagehash(X) 0
  47311. #define pager_set_pagehash(X)
  47312. #define CHECK_PAGE(x)
  47313. #endif /* SQLITE_CHECK_PAGES */
  47314. /*
  47315. ** When this is called the journal file for pager pPager must be open.
  47316. ** This function attempts to read a master journal file name from the
  47317. ** end of the file and, if successful, copies it into memory supplied
  47318. ** by the caller. See comments above writeMasterJournal() for the format
  47319. ** used to store a master journal file name at the end of a journal file.
  47320. **
  47321. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  47322. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  47323. ** enough space to write the master journal name). If the master journal
  47324. ** name in the journal is longer than nMaster bytes (including a
  47325. ** nul-terminator), then this is handled as if no master journal name
  47326. ** were present in the journal.
  47327. **
  47328. ** If a master journal file name is present at the end of the journal
  47329. ** file, then it is copied into the buffer pointed to by zMaster. A
  47330. ** nul-terminator byte is appended to the buffer following the master
  47331. ** journal file name.
  47332. **
  47333. ** If it is determined that no master journal file name is present
  47334. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  47335. **
  47336. ** If an error occurs while reading from the journal file, an SQLite
  47337. ** error code is returned.
  47338. */
  47339. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  47340. int rc; /* Return code */
  47341. u32 len; /* Length in bytes of master journal name */
  47342. i64 szJ; /* Total size in bytes of journal file pJrnl */
  47343. u32 cksum; /* MJ checksum value read from journal */
  47344. u32 u; /* Unsigned loop counter */
  47345. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  47346. zMaster[0] = '\0';
  47347. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  47348. || szJ<16
  47349. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  47350. || len>=nMaster
  47351. || len>szJ-16
  47352. || len==0
  47353. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  47354. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  47355. || memcmp(aMagic, aJournalMagic, 8)
  47356. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  47357. ){
  47358. return rc;
  47359. }
  47360. /* See if the checksum matches the master journal name */
  47361. for(u=0; u<len; u++){
  47362. cksum -= zMaster[u];
  47363. }
  47364. if( cksum ){
  47365. /* If the checksum doesn't add up, then one or more of the disk sectors
  47366. ** containing the master journal filename is corrupted. This means
  47367. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  47368. ** master-journal filename.
  47369. */
  47370. len = 0;
  47371. }
  47372. zMaster[len] = '\0';
  47373. return SQLITE_OK;
  47374. }
  47375. /*
  47376. ** Return the offset of the sector boundary at or immediately
  47377. ** following the value in pPager->journalOff, assuming a sector
  47378. ** size of pPager->sectorSize bytes.
  47379. **
  47380. ** i.e for a sector size of 512:
  47381. **
  47382. ** Pager.journalOff Return value
  47383. ** ---------------------------------------
  47384. ** 0 0
  47385. ** 512 512
  47386. ** 100 512
  47387. ** 2000 2048
  47388. **
  47389. */
  47390. static i64 journalHdrOffset(Pager *pPager){
  47391. i64 offset = 0;
  47392. i64 c = pPager->journalOff;
  47393. if( c ){
  47394. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  47395. }
  47396. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  47397. assert( offset>=c );
  47398. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  47399. return offset;
  47400. }
  47401. /*
  47402. ** The journal file must be open when this function is called.
  47403. **
  47404. ** This function is a no-op if the journal file has not been written to
  47405. ** within the current transaction (i.e. if Pager.journalOff==0).
  47406. **
  47407. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  47408. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  47409. ** zero the 28-byte header at the start of the journal file. In either case,
  47410. ** if the pager is not in no-sync mode, sync the journal file immediately
  47411. ** after writing or truncating it.
  47412. **
  47413. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  47414. ** following the truncation or zeroing described above the size of the
  47415. ** journal file in bytes is larger than this value, then truncate the
  47416. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  47417. ** not need to be synced following this operation.
  47418. **
  47419. ** If an IO error occurs, abandon processing and return the IO error code.
  47420. ** Otherwise, return SQLITE_OK.
  47421. */
  47422. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  47423. int rc = SQLITE_OK; /* Return code */
  47424. assert( isOpen(pPager->jfd) );
  47425. assert( !sqlite3JournalIsInMemory(pPager->jfd) );
  47426. if( pPager->journalOff ){
  47427. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  47428. IOTRACE(("JZEROHDR %p\n", pPager))
  47429. if( doTruncate || iLimit==0 ){
  47430. rc = sqlite3OsTruncate(pPager->jfd, 0);
  47431. }else{
  47432. static const char zeroHdr[28] = {0};
  47433. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  47434. }
  47435. if( rc==SQLITE_OK && !pPager->noSync ){
  47436. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  47437. }
  47438. /* At this point the transaction is committed but the write lock
  47439. ** is still held on the file. If there is a size limit configured for
  47440. ** the persistent journal and the journal file currently consumes more
  47441. ** space than that limit allows for, truncate it now. There is no need
  47442. ** to sync the file following this operation.
  47443. */
  47444. if( rc==SQLITE_OK && iLimit>0 ){
  47445. i64 sz;
  47446. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  47447. if( rc==SQLITE_OK && sz>iLimit ){
  47448. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  47449. }
  47450. }
  47451. }
  47452. return rc;
  47453. }
  47454. /*
  47455. ** The journal file must be open when this routine is called. A journal
  47456. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  47457. ** current location.
  47458. **
  47459. ** The format for the journal header is as follows:
  47460. ** - 8 bytes: Magic identifying journal format.
  47461. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  47462. ** - 4 bytes: Random number used for page hash.
  47463. ** - 4 bytes: Initial database page count.
  47464. ** - 4 bytes: Sector size used by the process that wrote this journal.
  47465. ** - 4 bytes: Database page size.
  47466. **
  47467. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  47468. */
  47469. static int writeJournalHdr(Pager *pPager){
  47470. int rc = SQLITE_OK; /* Return code */
  47471. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  47472. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  47473. u32 nWrite; /* Bytes of header sector written */
  47474. int ii; /* Loop counter */
  47475. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  47476. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  47477. nHeader = JOURNAL_HDR_SZ(pPager);
  47478. }
  47479. /* If there are active savepoints and any of them were created
  47480. ** since the most recent journal header was written, update the
  47481. ** PagerSavepoint.iHdrOffset fields now.
  47482. */
  47483. for(ii=0; ii<pPager->nSavepoint; ii++){
  47484. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  47485. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  47486. }
  47487. }
  47488. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  47489. /*
  47490. ** Write the nRec Field - the number of page records that follow this
  47491. ** journal header. Normally, zero is written to this value at this time.
  47492. ** After the records are added to the journal (and the journal synced,
  47493. ** if in full-sync mode), the zero is overwritten with the true number
  47494. ** of records (see syncJournal()).
  47495. **
  47496. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  47497. ** reading the journal this value tells SQLite to assume that the
  47498. ** rest of the journal file contains valid page records. This assumption
  47499. ** is dangerous, as if a failure occurred whilst writing to the journal
  47500. ** file it may contain some garbage data. There are two scenarios
  47501. ** where this risk can be ignored:
  47502. **
  47503. ** * When the pager is in no-sync mode. Corruption can follow a
  47504. ** power failure in this case anyway.
  47505. **
  47506. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  47507. ** that garbage data is never appended to the journal file.
  47508. */
  47509. assert( isOpen(pPager->fd) || pPager->noSync );
  47510. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  47511. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  47512. ){
  47513. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  47514. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  47515. }else{
  47516. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  47517. }
  47518. /* The random check-hash initializer */
  47519. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  47520. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  47521. /* The initial database size */
  47522. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  47523. /* The assumed sector size for this process */
  47524. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  47525. /* The page size */
  47526. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  47527. /* Initializing the tail of the buffer is not necessary. Everything
  47528. ** works find if the following memset() is omitted. But initializing
  47529. ** the memory prevents valgrind from complaining, so we are willing to
  47530. ** take the performance hit.
  47531. */
  47532. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  47533. nHeader-(sizeof(aJournalMagic)+20));
  47534. /* In theory, it is only necessary to write the 28 bytes that the
  47535. ** journal header consumes to the journal file here. Then increment the
  47536. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  47537. ** record is written to the following sector (leaving a gap in the file
  47538. ** that will be implicitly filled in by the OS).
  47539. **
  47540. ** However it has been discovered that on some systems this pattern can
  47541. ** be significantly slower than contiguously writing data to the file,
  47542. ** even if that means explicitly writing data to the block of
  47543. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  47544. ** is done.
  47545. **
  47546. ** The loop is required here in case the sector-size is larger than the
  47547. ** database page size. Since the zHeader buffer is only Pager.pageSize
  47548. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  47549. ** to populate the entire journal header sector.
  47550. */
  47551. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  47552. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  47553. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  47554. assert( pPager->journalHdr <= pPager->journalOff );
  47555. pPager->journalOff += nHeader;
  47556. }
  47557. return rc;
  47558. }
  47559. /*
  47560. ** The journal file must be open when this is called. A journal header file
  47561. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  47562. ** file. The current location in the journal file is given by
  47563. ** pPager->journalOff. See comments above function writeJournalHdr() for
  47564. ** a description of the journal header format.
  47565. **
  47566. ** If the header is read successfully, *pNRec is set to the number of
  47567. ** page records following this header and *pDbSize is set to the size of the
  47568. ** database before the transaction began, in pages. Also, pPager->cksumInit
  47569. ** is set to the value read from the journal header. SQLITE_OK is returned
  47570. ** in this case.
  47571. **
  47572. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  47573. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  47574. ** cannot be read from the journal file an error code is returned.
  47575. */
  47576. static int readJournalHdr(
  47577. Pager *pPager, /* Pager object */
  47578. int isHot,
  47579. i64 journalSize, /* Size of the open journal file in bytes */
  47580. u32 *pNRec, /* OUT: Value read from the nRec field */
  47581. u32 *pDbSize /* OUT: Value of original database size field */
  47582. ){
  47583. int rc; /* Return code */
  47584. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  47585. i64 iHdrOff; /* Offset of journal header being read */
  47586. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  47587. /* Advance Pager.journalOff to the start of the next sector. If the
  47588. ** journal file is too small for there to be a header stored at this
  47589. ** point, return SQLITE_DONE.
  47590. */
  47591. pPager->journalOff = journalHdrOffset(pPager);
  47592. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  47593. return SQLITE_DONE;
  47594. }
  47595. iHdrOff = pPager->journalOff;
  47596. /* Read in the first 8 bytes of the journal header. If they do not match
  47597. ** the magic string found at the start of each journal header, return
  47598. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  47599. ** proceed.
  47600. */
  47601. if( isHot || iHdrOff!=pPager->journalHdr ){
  47602. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  47603. if( rc ){
  47604. return rc;
  47605. }
  47606. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  47607. return SQLITE_DONE;
  47608. }
  47609. }
  47610. /* Read the first three 32-bit fields of the journal header: The nRec
  47611. ** field, the checksum-initializer and the database size at the start
  47612. ** of the transaction. Return an error code if anything goes wrong.
  47613. */
  47614. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  47615. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  47616. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  47617. ){
  47618. return rc;
  47619. }
  47620. if( pPager->journalOff==0 ){
  47621. u32 iPageSize; /* Page-size field of journal header */
  47622. u32 iSectorSize; /* Sector-size field of journal header */
  47623. /* Read the page-size and sector-size journal header fields. */
  47624. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  47625. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  47626. ){
  47627. return rc;
  47628. }
  47629. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  47630. ** journal header to zero. In this case, assume that the Pager.pageSize
  47631. ** variable is already set to the correct page size.
  47632. */
  47633. if( iPageSize==0 ){
  47634. iPageSize = pPager->pageSize;
  47635. }
  47636. /* Check that the values read from the page-size and sector-size fields
  47637. ** are within range. To be 'in range', both values need to be a power
  47638. ** of two greater than or equal to 512 or 32, and not greater than their
  47639. ** respective compile time maximum limits.
  47640. */
  47641. if( iPageSize<512 || iSectorSize<32
  47642. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  47643. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  47644. ){
  47645. /* If the either the page-size or sector-size in the journal-header is
  47646. ** invalid, then the process that wrote the journal-header must have
  47647. ** crashed before the header was synced. In this case stop reading
  47648. ** the journal file here.
  47649. */
  47650. return SQLITE_DONE;
  47651. }
  47652. /* Update the page-size to match the value read from the journal.
  47653. ** Use a testcase() macro to make sure that malloc failure within
  47654. ** PagerSetPagesize() is tested.
  47655. */
  47656. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  47657. testcase( rc!=SQLITE_OK );
  47658. /* Update the assumed sector-size to match the value used by
  47659. ** the process that created this journal. If this journal was
  47660. ** created by a process other than this one, then this routine
  47661. ** is being called from within pager_playback(). The local value
  47662. ** of Pager.sectorSize is restored at the end of that routine.
  47663. */
  47664. pPager->sectorSize = iSectorSize;
  47665. }
  47666. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  47667. return rc;
  47668. }
  47669. /*
  47670. ** Write the supplied master journal name into the journal file for pager
  47671. ** pPager at the current location. The master journal name must be the last
  47672. ** thing written to a journal file. If the pager is in full-sync mode, the
  47673. ** journal file descriptor is advanced to the next sector boundary before
  47674. ** anything is written. The format is:
  47675. **
  47676. ** + 4 bytes: PAGER_MJ_PGNO.
  47677. ** + N bytes: Master journal filename in utf-8.
  47678. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  47679. ** + 4 bytes: Master journal name checksum.
  47680. ** + 8 bytes: aJournalMagic[].
  47681. **
  47682. ** The master journal page checksum is the sum of the bytes in the master
  47683. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  47684. **
  47685. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  47686. ** this call is a no-op.
  47687. */
  47688. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  47689. int rc; /* Return code */
  47690. int nMaster; /* Length of string zMaster */
  47691. i64 iHdrOff; /* Offset of header in journal file */
  47692. i64 jrnlSize; /* Size of journal file on disk */
  47693. u32 cksum = 0; /* Checksum of string zMaster */
  47694. assert( pPager->setMaster==0 );
  47695. assert( !pagerUseWal(pPager) );
  47696. if( !zMaster
  47697. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  47698. || !isOpen(pPager->jfd)
  47699. ){
  47700. return SQLITE_OK;
  47701. }
  47702. pPager->setMaster = 1;
  47703. assert( pPager->journalHdr <= pPager->journalOff );
  47704. /* Calculate the length in bytes and the checksum of zMaster */
  47705. for(nMaster=0; zMaster[nMaster]; nMaster++){
  47706. cksum += zMaster[nMaster];
  47707. }
  47708. /* If in full-sync mode, advance to the next disk sector before writing
  47709. ** the master journal name. This is in case the previous page written to
  47710. ** the journal has already been synced.
  47711. */
  47712. if( pPager->fullSync ){
  47713. pPager->journalOff = journalHdrOffset(pPager);
  47714. }
  47715. iHdrOff = pPager->journalOff;
  47716. /* Write the master journal data to the end of the journal file. If
  47717. ** an error occurs, return the error code to the caller.
  47718. */
  47719. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  47720. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  47721. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  47722. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  47723. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  47724. iHdrOff+4+nMaster+8)))
  47725. ){
  47726. return rc;
  47727. }
  47728. pPager->journalOff += (nMaster+20);
  47729. /* If the pager is in peristent-journal mode, then the physical
  47730. ** journal-file may extend past the end of the master-journal name
  47731. ** and 8 bytes of magic data just written to the file. This is
  47732. ** dangerous because the code to rollback a hot-journal file
  47733. ** will not be able to find the master-journal name to determine
  47734. ** whether or not the journal is hot.
  47735. **
  47736. ** Easiest thing to do in this scenario is to truncate the journal
  47737. ** file to the required size.
  47738. */
  47739. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  47740. && jrnlSize>pPager->journalOff
  47741. ){
  47742. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  47743. }
  47744. return rc;
  47745. }
  47746. /*
  47747. ** Discard the entire contents of the in-memory page-cache.
  47748. */
  47749. static void pager_reset(Pager *pPager){
  47750. pPager->iDataVersion++;
  47751. sqlite3BackupRestart(pPager->pBackup);
  47752. sqlite3PcacheClear(pPager->pPCache);
  47753. }
  47754. /*
  47755. ** Return the pPager->iDataVersion value
  47756. */
  47757. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  47758. assert( pPager->eState>PAGER_OPEN );
  47759. return pPager->iDataVersion;
  47760. }
  47761. /*
  47762. ** Free all structures in the Pager.aSavepoint[] array and set both
  47763. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  47764. ** if it is open and the pager is not in exclusive mode.
  47765. */
  47766. static void releaseAllSavepoints(Pager *pPager){
  47767. int ii; /* Iterator for looping through Pager.aSavepoint */
  47768. for(ii=0; ii<pPager->nSavepoint; ii++){
  47769. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  47770. }
  47771. if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
  47772. sqlite3OsClose(pPager->sjfd);
  47773. }
  47774. sqlite3_free(pPager->aSavepoint);
  47775. pPager->aSavepoint = 0;
  47776. pPager->nSavepoint = 0;
  47777. pPager->nSubRec = 0;
  47778. }
  47779. /*
  47780. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  47781. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  47782. ** or SQLITE_NOMEM if a malloc failure occurs.
  47783. */
  47784. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  47785. int ii; /* Loop counter */
  47786. int rc = SQLITE_OK; /* Result code */
  47787. for(ii=0; ii<pPager->nSavepoint; ii++){
  47788. PagerSavepoint *p = &pPager->aSavepoint[ii];
  47789. if( pgno<=p->nOrig ){
  47790. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  47791. testcase( rc==SQLITE_NOMEM );
  47792. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  47793. }
  47794. }
  47795. return rc;
  47796. }
  47797. /*
  47798. ** This function is a no-op if the pager is in exclusive mode and not
  47799. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  47800. ** state.
  47801. **
  47802. ** If the pager is not in exclusive-access mode, the database file is
  47803. ** completely unlocked. If the file is unlocked and the file-system does
  47804. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  47805. ** closed (if it is open).
  47806. **
  47807. ** If the pager is in ERROR state when this function is called, the
  47808. ** contents of the pager cache are discarded before switching back to
  47809. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  47810. ** or not, any journal file left in the file-system will be treated
  47811. ** as a hot-journal and rolled back the next time a read-transaction
  47812. ** is opened (by this or by any other connection).
  47813. */
  47814. static void pager_unlock(Pager *pPager){
  47815. assert( pPager->eState==PAGER_READER
  47816. || pPager->eState==PAGER_OPEN
  47817. || pPager->eState==PAGER_ERROR
  47818. );
  47819. sqlite3BitvecDestroy(pPager->pInJournal);
  47820. pPager->pInJournal = 0;
  47821. releaseAllSavepoints(pPager);
  47822. if( pagerUseWal(pPager) ){
  47823. assert( !isOpen(pPager->jfd) );
  47824. sqlite3WalEndReadTransaction(pPager->pWal);
  47825. pPager->eState = PAGER_OPEN;
  47826. }else if( !pPager->exclusiveMode ){
  47827. int rc; /* Error code returned by pagerUnlockDb() */
  47828. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  47829. /* If the operating system support deletion of open files, then
  47830. ** close the journal file when dropping the database lock. Otherwise
  47831. ** another connection with journal_mode=delete might delete the file
  47832. ** out from under us.
  47833. */
  47834. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  47835. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  47836. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  47837. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  47838. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  47839. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  47840. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  47841. || 1!=(pPager->journalMode & 5)
  47842. ){
  47843. sqlite3OsClose(pPager->jfd);
  47844. }
  47845. /* If the pager is in the ERROR state and the call to unlock the database
  47846. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  47847. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  47848. ** is necessary.
  47849. */
  47850. rc = pagerUnlockDb(pPager, NO_LOCK);
  47851. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  47852. pPager->eLock = UNKNOWN_LOCK;
  47853. }
  47854. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  47855. ** without clearing the error code. This is intentional - the error
  47856. ** code is cleared and the cache reset in the block below.
  47857. */
  47858. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  47859. pPager->changeCountDone = 0;
  47860. pPager->eState = PAGER_OPEN;
  47861. }
  47862. /* If Pager.errCode is set, the contents of the pager cache cannot be
  47863. ** trusted. Now that there are no outstanding references to the pager,
  47864. ** it can safely move back to PAGER_OPEN state. This happens in both
  47865. ** normal and exclusive-locking mode.
  47866. */
  47867. assert( pPager->errCode==SQLITE_OK || !MEMDB );
  47868. if( pPager->errCode ){
  47869. if( pPager->tempFile==0 ){
  47870. pager_reset(pPager);
  47871. pPager->changeCountDone = 0;
  47872. pPager->eState = PAGER_OPEN;
  47873. }else{
  47874. pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
  47875. }
  47876. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  47877. pPager->errCode = SQLITE_OK;
  47878. setGetterMethod(pPager);
  47879. }
  47880. pPager->journalOff = 0;
  47881. pPager->journalHdr = 0;
  47882. pPager->setMaster = 0;
  47883. }
  47884. /*
  47885. ** This function is called whenever an IOERR or FULL error that requires
  47886. ** the pager to transition into the ERROR state may ahve occurred.
  47887. ** The first argument is a pointer to the pager structure, the second
  47888. ** the error-code about to be returned by a pager API function. The
  47889. ** value returned is a copy of the second argument to this function.
  47890. **
  47891. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  47892. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  47893. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  47894. ** all major API calls on the Pager will immediately return Pager.errCode.
  47895. **
  47896. ** The ERROR state indicates that the contents of the pager-cache
  47897. ** cannot be trusted. This state can be cleared by completely discarding
  47898. ** the contents of the pager-cache. If a transaction was active when
  47899. ** the persistent error occurred, then the rollback journal may need
  47900. ** to be replayed to restore the contents of the database file (as if
  47901. ** it were a hot-journal).
  47902. */
  47903. static int pager_error(Pager *pPager, int rc){
  47904. int rc2 = rc & 0xff;
  47905. assert( rc==SQLITE_OK || !MEMDB );
  47906. assert(
  47907. pPager->errCode==SQLITE_FULL ||
  47908. pPager->errCode==SQLITE_OK ||
  47909. (pPager->errCode & 0xff)==SQLITE_IOERR
  47910. );
  47911. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  47912. pPager->errCode = rc;
  47913. pPager->eState = PAGER_ERROR;
  47914. setGetterMethod(pPager);
  47915. }
  47916. return rc;
  47917. }
  47918. static int pager_truncate(Pager *pPager, Pgno nPage);
  47919. /*
  47920. ** The write transaction open on pPager is being committed (bCommit==1)
  47921. ** or rolled back (bCommit==0).
  47922. **
  47923. ** Return TRUE if and only if all dirty pages should be flushed to disk.
  47924. **
  47925. ** Rules:
  47926. **
  47927. ** * For non-TEMP databases, always sync to disk. This is necessary
  47928. ** for transactions to be durable.
  47929. **
  47930. ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
  47931. ** file has been created already (via a spill on pagerStress()) and
  47932. ** when the number of dirty pages in memory exceeds 25% of the total
  47933. ** cache size.
  47934. */
  47935. static int pagerFlushOnCommit(Pager *pPager, int bCommit){
  47936. if( pPager->tempFile==0 ) return 1;
  47937. if( !bCommit ) return 0;
  47938. if( !isOpen(pPager->fd) ) return 0;
  47939. return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
  47940. }
  47941. /*
  47942. ** This routine ends a transaction. A transaction is usually ended by
  47943. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  47944. ** after rollback of a hot-journal, or if an error occurs while opening
  47945. ** the journal file or writing the very first journal-header of a
  47946. ** database transaction.
  47947. **
  47948. ** This routine is never called in PAGER_ERROR state. If it is called
  47949. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  47950. ** exclusive than a RESERVED lock, it is a no-op.
  47951. **
  47952. ** Otherwise, any active savepoints are released.
  47953. **
  47954. ** If the journal file is open, then it is "finalized". Once a journal
  47955. ** file has been finalized it is not possible to use it to roll back a
  47956. ** transaction. Nor will it be considered to be a hot-journal by this
  47957. ** or any other database connection. Exactly how a journal is finalized
  47958. ** depends on whether or not the pager is running in exclusive mode and
  47959. ** the current journal-mode (Pager.journalMode value), as follows:
  47960. **
  47961. ** journalMode==MEMORY
  47962. ** Journal file descriptor is simply closed. This destroys an
  47963. ** in-memory journal.
  47964. **
  47965. ** journalMode==TRUNCATE
  47966. ** Journal file is truncated to zero bytes in size.
  47967. **
  47968. ** journalMode==PERSIST
  47969. ** The first 28 bytes of the journal file are zeroed. This invalidates
  47970. ** the first journal header in the file, and hence the entire journal
  47971. ** file. An invalid journal file cannot be rolled back.
  47972. **
  47973. ** journalMode==DELETE
  47974. ** The journal file is closed and deleted using sqlite3OsDelete().
  47975. **
  47976. ** If the pager is running in exclusive mode, this method of finalizing
  47977. ** the journal file is never used. Instead, if the journalMode is
  47978. ** DELETE and the pager is in exclusive mode, the method described under
  47979. ** journalMode==PERSIST is used instead.
  47980. **
  47981. ** After the journal is finalized, the pager moves to PAGER_READER state.
  47982. ** If running in non-exclusive rollback mode, the lock on the file is
  47983. ** downgraded to a SHARED_LOCK.
  47984. **
  47985. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  47986. ** any of the IO operations to finalize the journal file or unlock the
  47987. ** database then the IO error code is returned to the user. If the
  47988. ** operation to finalize the journal file fails, then the code still
  47989. ** tries to unlock the database file if not in exclusive mode. If the
  47990. ** unlock operation fails as well, then the first error code related
  47991. ** to the first error encountered (the journal finalization one) is
  47992. ** returned.
  47993. */
  47994. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  47995. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  47996. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  47997. /* Do nothing if the pager does not have an open write transaction
  47998. ** or at least a RESERVED lock. This function may be called when there
  47999. ** is no write-transaction active but a RESERVED or greater lock is
  48000. ** held under two circumstances:
  48001. **
  48002. ** 1. After a successful hot-journal rollback, it is called with
  48003. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  48004. **
  48005. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  48006. ** lock switches back to locking_mode=normal and then executes a
  48007. ** read-transaction, this function is called with eState==PAGER_READER
  48008. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  48009. */
  48010. assert( assert_pager_state(pPager) );
  48011. assert( pPager->eState!=PAGER_ERROR );
  48012. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  48013. return SQLITE_OK;
  48014. }
  48015. releaseAllSavepoints(pPager);
  48016. assert( isOpen(pPager->jfd) || pPager->pInJournal==0
  48017. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  48018. );
  48019. if( isOpen(pPager->jfd) ){
  48020. assert( !pagerUseWal(pPager) );
  48021. /* Finalize the journal file. */
  48022. if( sqlite3JournalIsInMemory(pPager->jfd) ){
  48023. /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
  48024. sqlite3OsClose(pPager->jfd);
  48025. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  48026. if( pPager->journalOff==0 ){
  48027. rc = SQLITE_OK;
  48028. }else{
  48029. rc = sqlite3OsTruncate(pPager->jfd, 0);
  48030. if( rc==SQLITE_OK && pPager->fullSync ){
  48031. /* Make sure the new file size is written into the inode right away.
  48032. ** Otherwise the journal might resurrect following a power loss and
  48033. ** cause the last transaction to roll back. See
  48034. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  48035. */
  48036. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  48037. }
  48038. }
  48039. pPager->journalOff = 0;
  48040. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  48041. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  48042. ){
  48043. rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
  48044. pPager->journalOff = 0;
  48045. }else{
  48046. /* This branch may be executed with Pager.journalMode==MEMORY if
  48047. ** a hot-journal was just rolled back. In this case the journal
  48048. ** file should be closed and deleted. If this connection writes to
  48049. ** the database file, it will do so using an in-memory journal.
  48050. */
  48051. int bDelete = !pPager->tempFile;
  48052. assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
  48053. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  48054. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  48055. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  48056. );
  48057. sqlite3OsClose(pPager->jfd);
  48058. if( bDelete ){
  48059. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
  48060. }
  48061. }
  48062. }
  48063. #ifdef SQLITE_CHECK_PAGES
  48064. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  48065. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  48066. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  48067. if( p ){
  48068. p->pageHash = 0;
  48069. sqlite3PagerUnrefNotNull(p);
  48070. }
  48071. }
  48072. #endif
  48073. sqlite3BitvecDestroy(pPager->pInJournal);
  48074. pPager->pInJournal = 0;
  48075. pPager->nRec = 0;
  48076. if( rc==SQLITE_OK ){
  48077. if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
  48078. sqlite3PcacheCleanAll(pPager->pPCache);
  48079. }else{
  48080. sqlite3PcacheClearWritable(pPager->pPCache);
  48081. }
  48082. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  48083. }
  48084. if( pagerUseWal(pPager) ){
  48085. /* Drop the WAL write-lock, if any. Also, if the connection was in
  48086. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  48087. ** lock held on the database file.
  48088. */
  48089. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  48090. assert( rc2==SQLITE_OK );
  48091. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  48092. /* This branch is taken when committing a transaction in rollback-journal
  48093. ** mode if the database file on disk is larger than the database image.
  48094. ** At this point the journal has been finalized and the transaction
  48095. ** successfully committed, but the EXCLUSIVE lock is still held on the
  48096. ** file. So it is safe to truncate the database file to its minimum
  48097. ** required size. */
  48098. assert( pPager->eLock==EXCLUSIVE_LOCK );
  48099. rc = pager_truncate(pPager, pPager->dbSize);
  48100. }
  48101. if( rc==SQLITE_OK && bCommit ){
  48102. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  48103. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  48104. }
  48105. if( !pPager->exclusiveMode
  48106. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  48107. ){
  48108. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  48109. pPager->changeCountDone = 0;
  48110. }
  48111. pPager->eState = PAGER_READER;
  48112. pPager->setMaster = 0;
  48113. return (rc==SQLITE_OK?rc2:rc);
  48114. }
  48115. /*
  48116. ** Execute a rollback if a transaction is active and unlock the
  48117. ** database file.
  48118. **
  48119. ** If the pager has already entered the ERROR state, do not attempt
  48120. ** the rollback at this time. Instead, pager_unlock() is called. The
  48121. ** call to pager_unlock() will discard all in-memory pages, unlock
  48122. ** the database file and move the pager back to OPEN state. If this
  48123. ** means that there is a hot-journal left in the file-system, the next
  48124. ** connection to obtain a shared lock on the pager (which may be this one)
  48125. ** will roll it back.
  48126. **
  48127. ** If the pager has not already entered the ERROR state, but an IO or
  48128. ** malloc error occurs during a rollback, then this will itself cause
  48129. ** the pager to enter the ERROR state. Which will be cleared by the
  48130. ** call to pager_unlock(), as described above.
  48131. */
  48132. static void pagerUnlockAndRollback(Pager *pPager){
  48133. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  48134. assert( assert_pager_state(pPager) );
  48135. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  48136. sqlite3BeginBenignMalloc();
  48137. sqlite3PagerRollback(pPager);
  48138. sqlite3EndBenignMalloc();
  48139. }else if( !pPager->exclusiveMode ){
  48140. assert( pPager->eState==PAGER_READER );
  48141. pager_end_transaction(pPager, 0, 0);
  48142. }
  48143. }
  48144. pager_unlock(pPager);
  48145. }
  48146. /*
  48147. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  48148. ** of data. Compute and return a checksum based ont the contents of the
  48149. ** page of data and the current value of pPager->cksumInit.
  48150. **
  48151. ** This is not a real checksum. It is really just the sum of the
  48152. ** random initial value (pPager->cksumInit) and every 200th byte
  48153. ** of the page data, starting with byte offset (pPager->pageSize%200).
  48154. ** Each byte is interpreted as an 8-bit unsigned integer.
  48155. **
  48156. ** Changing the formula used to compute this checksum results in an
  48157. ** incompatible journal file format.
  48158. **
  48159. ** If journal corruption occurs due to a power failure, the most likely
  48160. ** scenario is that one end or the other of the record will be changed.
  48161. ** It is much less likely that the two ends of the journal record will be
  48162. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  48163. ** though fast and simple, catches the mostly likely kind of corruption.
  48164. */
  48165. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  48166. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  48167. int i = pPager->pageSize-200; /* Loop counter */
  48168. while( i>0 ){
  48169. cksum += aData[i];
  48170. i -= 200;
  48171. }
  48172. return cksum;
  48173. }
  48174. /*
  48175. ** Report the current page size and number of reserved bytes back
  48176. ** to the codec.
  48177. */
  48178. #ifdef SQLITE_HAS_CODEC
  48179. static void pagerReportSize(Pager *pPager){
  48180. if( pPager->xCodecSizeChng ){
  48181. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  48182. (int)pPager->nReserve);
  48183. }
  48184. }
  48185. #else
  48186. # define pagerReportSize(X) /* No-op if we do not support a codec */
  48187. #endif
  48188. #ifdef SQLITE_HAS_CODEC
  48189. /*
  48190. ** Make sure the number of reserved bits is the same in the destination
  48191. ** pager as it is in the source. This comes up when a VACUUM changes the
  48192. ** number of reserved bits to the "optimal" amount.
  48193. */
  48194. SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
  48195. if( pDest->nReserve!=pSrc->nReserve ){
  48196. pDest->nReserve = pSrc->nReserve;
  48197. pagerReportSize(pDest);
  48198. }
  48199. }
  48200. #endif
  48201. /*
  48202. ** Read a single page from either the journal file (if isMainJrnl==1) or
  48203. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  48204. ** The page begins at offset *pOffset into the file. The *pOffset
  48205. ** value is increased to the start of the next page in the journal.
  48206. **
  48207. ** The main rollback journal uses checksums - the statement journal does
  48208. ** not.
  48209. **
  48210. ** If the page number of the page record read from the (sub-)journal file
  48211. ** is greater than the current value of Pager.dbSize, then playback is
  48212. ** skipped and SQLITE_OK is returned.
  48213. **
  48214. ** If pDone is not NULL, then it is a record of pages that have already
  48215. ** been played back. If the page at *pOffset has already been played back
  48216. ** (if the corresponding pDone bit is set) then skip the playback.
  48217. ** Make sure the pDone bit corresponding to the *pOffset page is set
  48218. ** prior to returning.
  48219. **
  48220. ** If the page record is successfully read from the (sub-)journal file
  48221. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  48222. ** while reading the record from the (sub-)journal file or while writing
  48223. ** to the database file, then the IO error code is returned. If data
  48224. ** is successfully read from the (sub-)journal file but appears to be
  48225. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  48226. ** two circumstances:
  48227. **
  48228. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  48229. ** * If the record is being rolled back from the main journal file
  48230. ** and the checksum field does not match the record content.
  48231. **
  48232. ** Neither of these two scenarios are possible during a savepoint rollback.
  48233. **
  48234. ** If this is a savepoint rollback, then memory may have to be dynamically
  48235. ** allocated by this function. If this is the case and an allocation fails,
  48236. ** SQLITE_NOMEM is returned.
  48237. */
  48238. static int pager_playback_one_page(
  48239. Pager *pPager, /* The pager being played back */
  48240. i64 *pOffset, /* Offset of record to playback */
  48241. Bitvec *pDone, /* Bitvec of pages already played back */
  48242. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  48243. int isSavepnt /* True for a savepoint rollback */
  48244. ){
  48245. int rc;
  48246. PgHdr *pPg; /* An existing page in the cache */
  48247. Pgno pgno; /* The page number of a page in journal */
  48248. u32 cksum; /* Checksum used for sanity checking */
  48249. char *aData; /* Temporary storage for the page */
  48250. sqlite3_file *jfd; /* The file descriptor for the journal file */
  48251. int isSynced; /* True if journal page is synced */
  48252. #ifdef SQLITE_HAS_CODEC
  48253. /* The jrnlEnc flag is true if Journal pages should be passed through
  48254. ** the codec. It is false for pure in-memory journals. */
  48255. const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
  48256. #endif
  48257. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  48258. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  48259. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  48260. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  48261. aData = pPager->pTmpSpace;
  48262. assert( aData ); /* Temp storage must have already been allocated */
  48263. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  48264. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  48265. ** or savepoint rollback done at the request of the caller) or this is
  48266. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  48267. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  48268. ** only reads from the main journal, not the sub-journal.
  48269. */
  48270. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  48271. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  48272. );
  48273. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  48274. /* Read the page number and page data from the journal or sub-journal
  48275. ** file. Return an error code to the caller if an IO error occurs.
  48276. */
  48277. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  48278. rc = read32bits(jfd, *pOffset, &pgno);
  48279. if( rc!=SQLITE_OK ) return rc;
  48280. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  48281. if( rc!=SQLITE_OK ) return rc;
  48282. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  48283. /* Sanity checking on the page. This is more important that I originally
  48284. ** thought. If a power failure occurs while the journal is being written,
  48285. ** it could cause invalid data to be written into the journal. We need to
  48286. ** detect this invalid data (with high probability) and ignore it.
  48287. */
  48288. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  48289. assert( !isSavepnt );
  48290. return SQLITE_DONE;
  48291. }
  48292. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  48293. return SQLITE_OK;
  48294. }
  48295. if( isMainJrnl ){
  48296. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  48297. if( rc ) return rc;
  48298. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  48299. return SQLITE_DONE;
  48300. }
  48301. }
  48302. /* If this page has already been played back before during the current
  48303. ** rollback, then don't bother to play it back again.
  48304. */
  48305. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  48306. return rc;
  48307. }
  48308. /* When playing back page 1, restore the nReserve setting
  48309. */
  48310. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  48311. pPager->nReserve = ((u8*)aData)[20];
  48312. pagerReportSize(pPager);
  48313. }
  48314. /* If the pager is in CACHEMOD state, then there must be a copy of this
  48315. ** page in the pager cache. In this case just update the pager cache,
  48316. ** not the database file. The page is left marked dirty in this case.
  48317. **
  48318. ** An exception to the above rule: If the database is in no-sync mode
  48319. ** and a page is moved during an incremental vacuum then the page may
  48320. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  48321. ** during a Movepage() call, then the page may not be in the cache
  48322. ** either. So the condition described in the above paragraph is not
  48323. ** assert()able.
  48324. **
  48325. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  48326. ** pager cache if it exists and the main file. The page is then marked
  48327. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  48328. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  48329. ** if the pager is in OPEN state.
  48330. **
  48331. ** Ticket #1171: The statement journal might contain page content that is
  48332. ** different from the page content at the start of the transaction.
  48333. ** This occurs when a page is changed prior to the start of a statement
  48334. ** then changed again within the statement. When rolling back such a
  48335. ** statement we must not write to the original database unless we know
  48336. ** for certain that original page contents are synced into the main rollback
  48337. ** journal. Otherwise, a power loss might leave modified data in the
  48338. ** database file without an entry in the rollback journal that can
  48339. ** restore the database to its original form. Two conditions must be
  48340. ** met before writing to the database files. (1) the database must be
  48341. ** locked. (2) we know that the original page content is fully synced
  48342. ** in the main journal either because the page is not in cache or else
  48343. ** the page is marked as needSync==0.
  48344. **
  48345. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  48346. ** is possible to fail a statement on a database that does not yet exist.
  48347. ** Do not attempt to write if database file has never been opened.
  48348. */
  48349. if( pagerUseWal(pPager) ){
  48350. pPg = 0;
  48351. }else{
  48352. pPg = sqlite3PagerLookup(pPager, pgno);
  48353. }
  48354. assert( pPg || !MEMDB );
  48355. assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
  48356. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  48357. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  48358. (isMainJrnl?"main-journal":"sub-journal")
  48359. ));
  48360. if( isMainJrnl ){
  48361. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  48362. }else{
  48363. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  48364. }
  48365. if( isOpen(pPager->fd)
  48366. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  48367. && isSynced
  48368. ){
  48369. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  48370. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  48371. assert( !pagerUseWal(pPager) );
  48372. /* Write the data read from the journal back into the database file.
  48373. ** This is usually safe even for an encrypted database - as the data
  48374. ** was encrypted before it was written to the journal file. The exception
  48375. ** is if the data was just read from an in-memory sub-journal. In that
  48376. ** case it must be encrypted here before it is copied into the database
  48377. ** file. */
  48378. #ifdef SQLITE_HAS_CODEC
  48379. if( !jrnlEnc ){
  48380. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
  48381. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  48382. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  48383. }else
  48384. #endif
  48385. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  48386. if( pgno>pPager->dbFileSize ){
  48387. pPager->dbFileSize = pgno;
  48388. }
  48389. if( pPager->pBackup ){
  48390. #ifdef SQLITE_HAS_CODEC
  48391. if( jrnlEnc ){
  48392. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
  48393. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  48394. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT,aData);
  48395. }else
  48396. #endif
  48397. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  48398. }
  48399. }else if( !isMainJrnl && pPg==0 ){
  48400. /* If this is a rollback of a savepoint and data was not written to
  48401. ** the database and the page is not in-memory, there is a potential
  48402. ** problem. When the page is next fetched by the b-tree layer, it
  48403. ** will be read from the database file, which may or may not be
  48404. ** current.
  48405. **
  48406. ** There are a couple of different ways this can happen. All are quite
  48407. ** obscure. When running in synchronous mode, this can only happen
  48408. ** if the page is on the free-list at the start of the transaction, then
  48409. ** populated, then moved using sqlite3PagerMovepage().
  48410. **
  48411. ** The solution is to add an in-memory page to the cache containing
  48412. ** the data just read from the sub-journal. Mark the page as dirty
  48413. ** and if the pager requires a journal-sync, then mark the page as
  48414. ** requiring a journal-sync before it is written.
  48415. */
  48416. assert( isSavepnt );
  48417. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  48418. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  48419. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  48420. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  48421. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  48422. if( rc!=SQLITE_OK ) return rc;
  48423. sqlite3PcacheMakeDirty(pPg);
  48424. }
  48425. if( pPg ){
  48426. /* No page should ever be explicitly rolled back that is in use, except
  48427. ** for page 1 which is held in use in order to keep the lock on the
  48428. ** database active. However such a page may be rolled back as a result
  48429. ** of an internal error resulting in an automatic call to
  48430. ** sqlite3PagerRollback().
  48431. */
  48432. void *pData;
  48433. pData = pPg->pData;
  48434. memcpy(pData, (u8*)aData, pPager->pageSize);
  48435. pPager->xReiniter(pPg);
  48436. /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
  48437. ** that call was dangerous and had no detectable benefit since the cache
  48438. ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
  48439. ** has been removed. */
  48440. pager_set_pagehash(pPg);
  48441. /* If this was page 1, then restore the value of Pager.dbFileVers.
  48442. ** Do this before any decoding. */
  48443. if( pgno==1 ){
  48444. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  48445. }
  48446. /* Decode the page just read from disk */
  48447. #if SQLITE_HAS_CODEC
  48448. if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
  48449. #endif
  48450. sqlite3PcacheRelease(pPg);
  48451. }
  48452. return rc;
  48453. }
  48454. /*
  48455. ** Parameter zMaster is the name of a master journal file. A single journal
  48456. ** file that referred to the master journal file has just been rolled back.
  48457. ** This routine checks if it is possible to delete the master journal file,
  48458. ** and does so if it is.
  48459. **
  48460. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  48461. ** available for use within this function.
  48462. **
  48463. ** When a master journal file is created, it is populated with the names
  48464. ** of all of its child journals, one after another, formatted as utf-8
  48465. ** encoded text. The end of each child journal file is marked with a
  48466. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  48467. ** file for a transaction involving two databases might be:
  48468. **
  48469. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  48470. **
  48471. ** A master journal file may only be deleted once all of its child
  48472. ** journals have been rolled back.
  48473. **
  48474. ** This function reads the contents of the master-journal file into
  48475. ** memory and loops through each of the child journal names. For
  48476. ** each child journal, it checks if:
  48477. **
  48478. ** * if the child journal exists, and if so
  48479. ** * if the child journal contains a reference to master journal
  48480. ** file zMaster
  48481. **
  48482. ** If a child journal can be found that matches both of the criteria
  48483. ** above, this function returns without doing anything. Otherwise, if
  48484. ** no such child journal can be found, file zMaster is deleted from
  48485. ** the file-system using sqlite3OsDelete().
  48486. **
  48487. ** If an IO error within this function, an error code is returned. This
  48488. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  48489. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  48490. ** occur, SQLITE_OK is returned.
  48491. **
  48492. ** TODO: This function allocates a single block of memory to load
  48493. ** the entire contents of the master journal file. This could be
  48494. ** a couple of kilobytes or so - potentially larger than the page
  48495. ** size.
  48496. */
  48497. static int pager_delmaster(Pager *pPager, const char *zMaster){
  48498. sqlite3_vfs *pVfs = pPager->pVfs;
  48499. int rc; /* Return code */
  48500. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  48501. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  48502. char *zMasterJournal = 0; /* Contents of master journal file */
  48503. i64 nMasterJournal; /* Size of master journal file */
  48504. char *zJournal; /* Pointer to one journal within MJ file */
  48505. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  48506. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  48507. /* Allocate space for both the pJournal and pMaster file descriptors.
  48508. ** If successful, open the master journal file for reading.
  48509. */
  48510. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  48511. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  48512. if( !pMaster ){
  48513. rc = SQLITE_NOMEM_BKPT;
  48514. }else{
  48515. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  48516. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  48517. }
  48518. if( rc!=SQLITE_OK ) goto delmaster_out;
  48519. /* Load the entire master journal file into space obtained from
  48520. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  48521. ** sufficient space (in zMasterPtr) to hold the names of master
  48522. ** journal files extracted from regular rollback-journals.
  48523. */
  48524. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  48525. if( rc!=SQLITE_OK ) goto delmaster_out;
  48526. nMasterPtr = pVfs->mxPathname+1;
  48527. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  48528. if( !zMasterJournal ){
  48529. rc = SQLITE_NOMEM_BKPT;
  48530. goto delmaster_out;
  48531. }
  48532. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  48533. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  48534. if( rc!=SQLITE_OK ) goto delmaster_out;
  48535. zMasterJournal[nMasterJournal] = 0;
  48536. zJournal = zMasterJournal;
  48537. while( (zJournal-zMasterJournal)<nMasterJournal ){
  48538. int exists;
  48539. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  48540. if( rc!=SQLITE_OK ){
  48541. goto delmaster_out;
  48542. }
  48543. if( exists ){
  48544. /* One of the journals pointed to by the master journal exists.
  48545. ** Open it and check if it points at the master journal. If
  48546. ** so, return without deleting the master journal file.
  48547. */
  48548. int c;
  48549. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  48550. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  48551. if( rc!=SQLITE_OK ){
  48552. goto delmaster_out;
  48553. }
  48554. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  48555. sqlite3OsClose(pJournal);
  48556. if( rc!=SQLITE_OK ){
  48557. goto delmaster_out;
  48558. }
  48559. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  48560. if( c ){
  48561. /* We have a match. Do not delete the master journal file. */
  48562. goto delmaster_out;
  48563. }
  48564. }
  48565. zJournal += (sqlite3Strlen30(zJournal)+1);
  48566. }
  48567. sqlite3OsClose(pMaster);
  48568. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  48569. delmaster_out:
  48570. sqlite3_free(zMasterJournal);
  48571. if( pMaster ){
  48572. sqlite3OsClose(pMaster);
  48573. assert( !isOpen(pJournal) );
  48574. sqlite3_free(pMaster);
  48575. }
  48576. return rc;
  48577. }
  48578. /*
  48579. ** This function is used to change the actual size of the database
  48580. ** file in the file-system. This only happens when committing a transaction,
  48581. ** or rolling back a transaction (including rolling back a hot-journal).
  48582. **
  48583. ** If the main database file is not open, or the pager is not in either
  48584. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  48585. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  48586. ** If the file on disk is currently larger than nPage pages, then use the VFS
  48587. ** xTruncate() method to truncate it.
  48588. **
  48589. ** Or, it might be the case that the file on disk is smaller than
  48590. ** nPage pages. Some operating system implementations can get confused if
  48591. ** you try to truncate a file to some size that is larger than it
  48592. ** currently is, so detect this case and write a single zero byte to
  48593. ** the end of the new file instead.
  48594. **
  48595. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  48596. ** the database file, return the error code to the caller.
  48597. */
  48598. static int pager_truncate(Pager *pPager, Pgno nPage){
  48599. int rc = SQLITE_OK;
  48600. assert( pPager->eState!=PAGER_ERROR );
  48601. assert( pPager->eState!=PAGER_READER );
  48602. if( isOpen(pPager->fd)
  48603. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  48604. ){
  48605. i64 currentSize, newSize;
  48606. int szPage = pPager->pageSize;
  48607. assert( pPager->eLock==EXCLUSIVE_LOCK );
  48608. /* TODO: Is it safe to use Pager.dbFileSize here? */
  48609. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  48610. newSize = szPage*(i64)nPage;
  48611. if( rc==SQLITE_OK && currentSize!=newSize ){
  48612. if( currentSize>newSize ){
  48613. rc = sqlite3OsTruncate(pPager->fd, newSize);
  48614. }else if( (currentSize+szPage)<=newSize ){
  48615. char *pTmp = pPager->pTmpSpace;
  48616. memset(pTmp, 0, szPage);
  48617. testcase( (newSize-szPage) == currentSize );
  48618. testcase( (newSize-szPage) > currentSize );
  48619. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  48620. }
  48621. if( rc==SQLITE_OK ){
  48622. pPager->dbFileSize = nPage;
  48623. }
  48624. }
  48625. }
  48626. return rc;
  48627. }
  48628. /*
  48629. ** Return a sanitized version of the sector-size of OS file pFile. The
  48630. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  48631. */
  48632. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  48633. int iRet = sqlite3OsSectorSize(pFile);
  48634. if( iRet<32 ){
  48635. iRet = 512;
  48636. }else if( iRet>MAX_SECTOR_SIZE ){
  48637. assert( MAX_SECTOR_SIZE>=512 );
  48638. iRet = MAX_SECTOR_SIZE;
  48639. }
  48640. return iRet;
  48641. }
  48642. /*
  48643. ** Set the value of the Pager.sectorSize variable for the given
  48644. ** pager based on the value returned by the xSectorSize method
  48645. ** of the open database file. The sector size will be used
  48646. ** to determine the size and alignment of journal header and
  48647. ** master journal pointers within created journal files.
  48648. **
  48649. ** For temporary files the effective sector size is always 512 bytes.
  48650. **
  48651. ** Otherwise, for non-temporary files, the effective sector size is
  48652. ** the value returned by the xSectorSize() method rounded up to 32 if
  48653. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  48654. ** is greater than MAX_SECTOR_SIZE.
  48655. **
  48656. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  48657. ** the effective sector size to its minimum value (512). The purpose of
  48658. ** pPager->sectorSize is to define the "blast radius" of bytes that
  48659. ** might change if a crash occurs while writing to a single byte in
  48660. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  48661. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  48662. ** size. For backwards compatibility of the rollback journal file format,
  48663. ** we cannot reduce the effective sector size below 512.
  48664. */
  48665. static void setSectorSize(Pager *pPager){
  48666. assert( isOpen(pPager->fd) || pPager->tempFile );
  48667. if( pPager->tempFile
  48668. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  48669. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  48670. ){
  48671. /* Sector size doesn't matter for temporary files. Also, the file
  48672. ** may not have been opened yet, in which case the OsSectorSize()
  48673. ** call will segfault. */
  48674. pPager->sectorSize = 512;
  48675. }else{
  48676. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  48677. }
  48678. }
  48679. /*
  48680. ** Playback the journal and thus restore the database file to
  48681. ** the state it was in before we started making changes.
  48682. **
  48683. ** The journal file format is as follows:
  48684. **
  48685. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  48686. ** (2) 4 byte big-endian integer which is the number of valid page records
  48687. ** in the journal. If this value is 0xffffffff, then compute the
  48688. ** number of page records from the journal size.
  48689. ** (3) 4 byte big-endian integer which is the initial value for the
  48690. ** sanity checksum.
  48691. ** (4) 4 byte integer which is the number of pages to truncate the
  48692. ** database to during a rollback.
  48693. ** (5) 4 byte big-endian integer which is the sector size. The header
  48694. ** is this many bytes in size.
  48695. ** (6) 4 byte big-endian integer which is the page size.
  48696. ** (7) zero padding out to the next sector size.
  48697. ** (8) Zero or more pages instances, each as follows:
  48698. ** + 4 byte page number.
  48699. ** + pPager->pageSize bytes of data.
  48700. ** + 4 byte checksum
  48701. **
  48702. ** When we speak of the journal header, we mean the first 7 items above.
  48703. ** Each entry in the journal is an instance of the 8th item.
  48704. **
  48705. ** Call the value from the second bullet "nRec". nRec is the number of
  48706. ** valid page entries in the journal. In most cases, you can compute the
  48707. ** value of nRec from the size of the journal file. But if a power
  48708. ** failure occurred while the journal was being written, it could be the
  48709. ** case that the size of the journal file had already been increased but
  48710. ** the extra entries had not yet made it safely to disk. In such a case,
  48711. ** the value of nRec computed from the file size would be too large. For
  48712. ** that reason, we always use the nRec value in the header.
  48713. **
  48714. ** If the nRec value is 0xffffffff it means that nRec should be computed
  48715. ** from the file size. This value is used when the user selects the
  48716. ** no-sync option for the journal. A power failure could lead to corruption
  48717. ** in this case. But for things like temporary table (which will be
  48718. ** deleted when the power is restored) we don't care.
  48719. **
  48720. ** If the file opened as the journal file is not a well-formed
  48721. ** journal file then all pages up to the first corrupted page are rolled
  48722. ** back (or no pages if the journal header is corrupted). The journal file
  48723. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  48724. ** been encountered.
  48725. **
  48726. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  48727. ** and an error code is returned.
  48728. **
  48729. ** The isHot parameter indicates that we are trying to rollback a journal
  48730. ** that might be a hot journal. Or, it could be that the journal is
  48731. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  48732. ** If the journal really is hot, reset the pager cache prior rolling
  48733. ** back any content. If the journal is merely persistent, no reset is
  48734. ** needed.
  48735. */
  48736. static int pager_playback(Pager *pPager, int isHot){
  48737. sqlite3_vfs *pVfs = pPager->pVfs;
  48738. i64 szJ; /* Size of the journal file in bytes */
  48739. u32 nRec; /* Number of Records in the journal */
  48740. u32 u; /* Unsigned loop counter */
  48741. Pgno mxPg = 0; /* Size of the original file in pages */
  48742. int rc; /* Result code of a subroutine */
  48743. int res = 1; /* Value returned by sqlite3OsAccess() */
  48744. char *zMaster = 0; /* Name of master journal file if any */
  48745. int needPagerReset; /* True to reset page prior to first page rollback */
  48746. int nPlayback = 0; /* Total number of pages restored from journal */
  48747. u32 savedPageSize = pPager->pageSize;
  48748. /* Figure out how many records are in the journal. Abort early if
  48749. ** the journal is empty.
  48750. */
  48751. assert( isOpen(pPager->jfd) );
  48752. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  48753. if( rc!=SQLITE_OK ){
  48754. goto end_playback;
  48755. }
  48756. /* Read the master journal name from the journal, if it is present.
  48757. ** If a master journal file name is specified, but the file is not
  48758. ** present on disk, then the journal is not hot and does not need to be
  48759. ** played back.
  48760. **
  48761. ** TODO: Technically the following is an error because it assumes that
  48762. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  48763. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  48764. ** mxPathname is 512, which is the same as the minimum allowable value
  48765. ** for pageSize.
  48766. */
  48767. zMaster = pPager->pTmpSpace;
  48768. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  48769. if( rc==SQLITE_OK && zMaster[0] ){
  48770. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  48771. }
  48772. zMaster = 0;
  48773. if( rc!=SQLITE_OK || !res ){
  48774. goto end_playback;
  48775. }
  48776. pPager->journalOff = 0;
  48777. needPagerReset = isHot;
  48778. /* This loop terminates either when a readJournalHdr() or
  48779. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  48780. ** occurs.
  48781. */
  48782. while( 1 ){
  48783. /* Read the next journal header from the journal file. If there are
  48784. ** not enough bytes left in the journal file for a complete header, or
  48785. ** it is corrupted, then a process must have failed while writing it.
  48786. ** This indicates nothing more needs to be rolled back.
  48787. */
  48788. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  48789. if( rc!=SQLITE_OK ){
  48790. if( rc==SQLITE_DONE ){
  48791. rc = SQLITE_OK;
  48792. }
  48793. goto end_playback;
  48794. }
  48795. /* If nRec is 0xffffffff, then this journal was created by a process
  48796. ** working in no-sync mode. This means that the rest of the journal
  48797. ** file consists of pages, there are no more journal headers. Compute
  48798. ** the value of nRec based on this assumption.
  48799. */
  48800. if( nRec==0xffffffff ){
  48801. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  48802. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  48803. }
  48804. /* If nRec is 0 and this rollback is of a transaction created by this
  48805. ** process and if this is the final header in the journal, then it means
  48806. ** that this part of the journal was being filled but has not yet been
  48807. ** synced to disk. Compute the number of pages based on the remaining
  48808. ** size of the file.
  48809. **
  48810. ** The third term of the test was added to fix ticket #2565.
  48811. ** When rolling back a hot journal, nRec==0 always means that the next
  48812. ** chunk of the journal contains zero pages to be rolled back. But
  48813. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  48814. ** the journal, it means that the journal might contain additional
  48815. ** pages that need to be rolled back and that the number of pages
  48816. ** should be computed based on the journal file size.
  48817. */
  48818. if( nRec==0 && !isHot &&
  48819. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  48820. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  48821. }
  48822. /* If this is the first header read from the journal, truncate the
  48823. ** database file back to its original size.
  48824. */
  48825. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  48826. rc = pager_truncate(pPager, mxPg);
  48827. if( rc!=SQLITE_OK ){
  48828. goto end_playback;
  48829. }
  48830. pPager->dbSize = mxPg;
  48831. }
  48832. /* Copy original pages out of the journal and back into the
  48833. ** database file and/or page cache.
  48834. */
  48835. for(u=0; u<nRec; u++){
  48836. if( needPagerReset ){
  48837. pager_reset(pPager);
  48838. needPagerReset = 0;
  48839. }
  48840. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  48841. if( rc==SQLITE_OK ){
  48842. nPlayback++;
  48843. }else{
  48844. if( rc==SQLITE_DONE ){
  48845. pPager->journalOff = szJ;
  48846. break;
  48847. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  48848. /* If the journal has been truncated, simply stop reading and
  48849. ** processing the journal. This might happen if the journal was
  48850. ** not completely written and synced prior to a crash. In that
  48851. ** case, the database should have never been written in the
  48852. ** first place so it is OK to simply abandon the rollback. */
  48853. rc = SQLITE_OK;
  48854. goto end_playback;
  48855. }else{
  48856. /* If we are unable to rollback, quit and return the error
  48857. ** code. This will cause the pager to enter the error state
  48858. ** so that no further harm will be done. Perhaps the next
  48859. ** process to come along will be able to rollback the database.
  48860. */
  48861. goto end_playback;
  48862. }
  48863. }
  48864. }
  48865. }
  48866. /*NOTREACHED*/
  48867. assert( 0 );
  48868. end_playback:
  48869. if( rc==SQLITE_OK ){
  48870. rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
  48871. }
  48872. /* Following a rollback, the database file should be back in its original
  48873. ** state prior to the start of the transaction, so invoke the
  48874. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  48875. ** assertion that the transaction counter was modified.
  48876. */
  48877. #ifdef SQLITE_DEBUG
  48878. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  48879. #endif
  48880. /* If this playback is happening automatically as a result of an IO or
  48881. ** malloc error that occurred after the change-counter was updated but
  48882. ** before the transaction was committed, then the change-counter
  48883. ** modification may just have been reverted. If this happens in exclusive
  48884. ** mode, then subsequent transactions performed by the connection will not
  48885. ** update the change-counter at all. This may lead to cache inconsistency
  48886. ** problems for other processes at some point in the future. So, just
  48887. ** in case this has happened, clear the changeCountDone flag now.
  48888. */
  48889. pPager->changeCountDone = pPager->tempFile;
  48890. if( rc==SQLITE_OK ){
  48891. zMaster = pPager->pTmpSpace;
  48892. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  48893. testcase( rc!=SQLITE_OK );
  48894. }
  48895. if( rc==SQLITE_OK
  48896. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  48897. ){
  48898. rc = sqlite3PagerSync(pPager, 0);
  48899. }
  48900. if( rc==SQLITE_OK ){
  48901. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  48902. testcase( rc!=SQLITE_OK );
  48903. }
  48904. if( rc==SQLITE_OK && zMaster[0] && res ){
  48905. /* If there was a master journal and this routine will return success,
  48906. ** see if it is possible to delete the master journal.
  48907. */
  48908. rc = pager_delmaster(pPager, zMaster);
  48909. testcase( rc!=SQLITE_OK );
  48910. }
  48911. if( isHot && nPlayback ){
  48912. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  48913. nPlayback, pPager->zJournal);
  48914. }
  48915. /* The Pager.sectorSize variable may have been updated while rolling
  48916. ** back a journal created by a process with a different sector size
  48917. ** value. Reset it to the correct value for this process.
  48918. */
  48919. setSectorSize(pPager);
  48920. return rc;
  48921. }
  48922. /*
  48923. ** Read the content for page pPg out of the database file (or out of
  48924. ** the WAL if that is where the most recent copy if found) into
  48925. ** pPg->pData. A shared lock or greater must be held on the database
  48926. ** file before this function is called.
  48927. **
  48928. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  48929. ** the value read from the database file.
  48930. **
  48931. ** If an IO error occurs, then the IO error is returned to the caller.
  48932. ** Otherwise, SQLITE_OK is returned.
  48933. */
  48934. static int readDbPage(PgHdr *pPg){
  48935. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  48936. int rc = SQLITE_OK; /* Return code */
  48937. #ifndef SQLITE_OMIT_WAL
  48938. u32 iFrame = 0; /* Frame of WAL containing pgno */
  48939. assert( pPager->eState>=PAGER_READER && !MEMDB );
  48940. assert( isOpen(pPager->fd) );
  48941. if( pagerUseWal(pPager) ){
  48942. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  48943. if( rc ) return rc;
  48944. }
  48945. if( iFrame ){
  48946. rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
  48947. }else
  48948. #endif
  48949. {
  48950. i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
  48951. rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
  48952. if( rc==SQLITE_IOERR_SHORT_READ ){
  48953. rc = SQLITE_OK;
  48954. }
  48955. }
  48956. if( pPg->pgno==1 ){
  48957. if( rc ){
  48958. /* If the read is unsuccessful, set the dbFileVers[] to something
  48959. ** that will never be a valid file version. dbFileVers[] is a copy
  48960. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  48961. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  48962. ** should be page numbers which are never 0xffffffff. So filling
  48963. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  48964. **
  48965. ** For an encrypted database, the situation is more complex: bytes
  48966. ** 24..39 of the database are white noise. But the probability of
  48967. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  48968. ** we should still be ok.
  48969. */
  48970. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  48971. }else{
  48972. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  48973. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  48974. }
  48975. }
  48976. CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
  48977. PAGER_INCR(sqlite3_pager_readdb_count);
  48978. PAGER_INCR(pPager->nRead);
  48979. IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
  48980. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  48981. PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
  48982. return rc;
  48983. }
  48984. /*
  48985. ** Update the value of the change-counter at offsets 24 and 92 in
  48986. ** the header and the sqlite version number at offset 96.
  48987. **
  48988. ** This is an unconditional update. See also the pager_incr_changecounter()
  48989. ** routine which only updates the change-counter if the update is actually
  48990. ** needed, as determined by the pPager->changeCountDone state variable.
  48991. */
  48992. static void pager_write_changecounter(PgHdr *pPg){
  48993. u32 change_counter;
  48994. /* Increment the value just read and write it back to byte 24. */
  48995. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  48996. put32bits(((char*)pPg->pData)+24, change_counter);
  48997. /* Also store the SQLite version number in bytes 96..99 and in
  48998. ** bytes 92..95 store the change counter for which the version number
  48999. ** is valid. */
  49000. put32bits(((char*)pPg->pData)+92, change_counter);
  49001. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  49002. }
  49003. #ifndef SQLITE_OMIT_WAL
  49004. /*
  49005. ** This function is invoked once for each page that has already been
  49006. ** written into the log file when a WAL transaction is rolled back.
  49007. ** Parameter iPg is the page number of said page. The pCtx argument
  49008. ** is actually a pointer to the Pager structure.
  49009. **
  49010. ** If page iPg is present in the cache, and has no outstanding references,
  49011. ** it is discarded. Otherwise, if there are one or more outstanding
  49012. ** references, the page content is reloaded from the database. If the
  49013. ** attempt to reload content from the database is required and fails,
  49014. ** return an SQLite error code. Otherwise, SQLITE_OK.
  49015. */
  49016. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  49017. int rc = SQLITE_OK;
  49018. Pager *pPager = (Pager *)pCtx;
  49019. PgHdr *pPg;
  49020. assert( pagerUseWal(pPager) );
  49021. pPg = sqlite3PagerLookup(pPager, iPg);
  49022. if( pPg ){
  49023. if( sqlite3PcachePageRefcount(pPg)==1 ){
  49024. sqlite3PcacheDrop(pPg);
  49025. }else{
  49026. rc = readDbPage(pPg);
  49027. if( rc==SQLITE_OK ){
  49028. pPager->xReiniter(pPg);
  49029. }
  49030. sqlite3PagerUnrefNotNull(pPg);
  49031. }
  49032. }
  49033. /* Normally, if a transaction is rolled back, any backup processes are
  49034. ** updated as data is copied out of the rollback journal and into the
  49035. ** database. This is not generally possible with a WAL database, as
  49036. ** rollback involves simply truncating the log file. Therefore, if one
  49037. ** or more frames have already been written to the log (and therefore
  49038. ** also copied into the backup databases) as part of this transaction,
  49039. ** the backups must be restarted.
  49040. */
  49041. sqlite3BackupRestart(pPager->pBackup);
  49042. return rc;
  49043. }
  49044. /*
  49045. ** This function is called to rollback a transaction on a WAL database.
  49046. */
  49047. static int pagerRollbackWal(Pager *pPager){
  49048. int rc; /* Return Code */
  49049. PgHdr *pList; /* List of dirty pages to revert */
  49050. /* For all pages in the cache that are currently dirty or have already
  49051. ** been written (but not committed) to the log file, do one of the
  49052. ** following:
  49053. **
  49054. ** + Discard the cached page (if refcount==0), or
  49055. ** + Reload page content from the database (if refcount>0).
  49056. */
  49057. pPager->dbSize = pPager->dbOrigSize;
  49058. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  49059. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  49060. while( pList && rc==SQLITE_OK ){
  49061. PgHdr *pNext = pList->pDirty;
  49062. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  49063. pList = pNext;
  49064. }
  49065. return rc;
  49066. }
  49067. /*
  49068. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  49069. ** the contents of the list of pages headed by pList (connected by pDirty),
  49070. ** this function notifies any active backup processes that the pages have
  49071. ** changed.
  49072. **
  49073. ** The list of pages passed into this routine is always sorted by page number.
  49074. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  49075. */
  49076. static int pagerWalFrames(
  49077. Pager *pPager, /* Pager object */
  49078. PgHdr *pList, /* List of frames to log */
  49079. Pgno nTruncate, /* Database size after this commit */
  49080. int isCommit /* True if this is a commit */
  49081. ){
  49082. int rc; /* Return code */
  49083. int nList; /* Number of pages in pList */
  49084. PgHdr *p; /* For looping over pages */
  49085. assert( pPager->pWal );
  49086. assert( pList );
  49087. #ifdef SQLITE_DEBUG
  49088. /* Verify that the page list is in accending order */
  49089. for(p=pList; p && p->pDirty; p=p->pDirty){
  49090. assert( p->pgno < p->pDirty->pgno );
  49091. }
  49092. #endif
  49093. assert( pList->pDirty==0 || isCommit );
  49094. if( isCommit ){
  49095. /* If a WAL transaction is being committed, there is no point in writing
  49096. ** any pages with page numbers greater than nTruncate into the WAL file.
  49097. ** They will never be read by any client. So remove them from the pDirty
  49098. ** list here. */
  49099. PgHdr **ppNext = &pList;
  49100. nList = 0;
  49101. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  49102. if( p->pgno<=nTruncate ){
  49103. ppNext = &p->pDirty;
  49104. nList++;
  49105. }
  49106. }
  49107. assert( pList );
  49108. }else{
  49109. nList = 1;
  49110. }
  49111. pPager->aStat[PAGER_STAT_WRITE] += nList;
  49112. if( pList->pgno==1 ) pager_write_changecounter(pList);
  49113. rc = sqlite3WalFrames(pPager->pWal,
  49114. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  49115. );
  49116. if( rc==SQLITE_OK && pPager->pBackup ){
  49117. for(p=pList; p; p=p->pDirty){
  49118. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  49119. }
  49120. }
  49121. #ifdef SQLITE_CHECK_PAGES
  49122. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  49123. for(p=pList; p; p=p->pDirty){
  49124. pager_set_pagehash(p);
  49125. }
  49126. #endif
  49127. return rc;
  49128. }
  49129. /*
  49130. ** Begin a read transaction on the WAL.
  49131. **
  49132. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  49133. ** makes a snapshot of the database at the current point in time and preserves
  49134. ** that snapshot for use by the reader in spite of concurrently changes by
  49135. ** other writers or checkpointers.
  49136. */
  49137. static int pagerBeginReadTransaction(Pager *pPager){
  49138. int rc; /* Return code */
  49139. int changed = 0; /* True if cache must be reset */
  49140. assert( pagerUseWal(pPager) );
  49141. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  49142. /* sqlite3WalEndReadTransaction() was not called for the previous
  49143. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  49144. ** are in locking_mode=NORMAL and EndRead() was previously called,
  49145. ** the duplicate call is harmless.
  49146. */
  49147. sqlite3WalEndReadTransaction(pPager->pWal);
  49148. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  49149. if( rc!=SQLITE_OK || changed ){
  49150. pager_reset(pPager);
  49151. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  49152. }
  49153. return rc;
  49154. }
  49155. #endif
  49156. /*
  49157. ** This function is called as part of the transition from PAGER_OPEN
  49158. ** to PAGER_READER state to determine the size of the database file
  49159. ** in pages (assuming the page size currently stored in Pager.pageSize).
  49160. **
  49161. ** If no error occurs, SQLITE_OK is returned and the size of the database
  49162. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  49163. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  49164. */
  49165. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  49166. Pgno nPage; /* Value to return via *pnPage */
  49167. /* Query the WAL sub-system for the database size. The WalDbsize()
  49168. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  49169. ** if the database size is not available. The database size is not
  49170. ** available from the WAL sub-system if the log file is empty or
  49171. ** contains no valid committed transactions.
  49172. */
  49173. assert( pPager->eState==PAGER_OPEN );
  49174. assert( pPager->eLock>=SHARED_LOCK );
  49175. assert( isOpen(pPager->fd) );
  49176. assert( pPager->tempFile==0 );
  49177. nPage = sqlite3WalDbsize(pPager->pWal);
  49178. /* If the number of pages in the database is not available from the
  49179. ** WAL sub-system, determine the page count based on the size of
  49180. ** the database file. If the size of the database file is not an
  49181. ** integer multiple of the page-size, round up the result.
  49182. */
  49183. if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
  49184. i64 n = 0; /* Size of db file in bytes */
  49185. int rc = sqlite3OsFileSize(pPager->fd, &n);
  49186. if( rc!=SQLITE_OK ){
  49187. return rc;
  49188. }
  49189. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  49190. }
  49191. /* If the current number of pages in the file is greater than the
  49192. ** configured maximum pager number, increase the allowed limit so
  49193. ** that the file can be read.
  49194. */
  49195. if( nPage>pPager->mxPgno ){
  49196. pPager->mxPgno = (Pgno)nPage;
  49197. }
  49198. *pnPage = nPage;
  49199. return SQLITE_OK;
  49200. }
  49201. #ifndef SQLITE_OMIT_WAL
  49202. /*
  49203. ** Check if the *-wal file that corresponds to the database opened by pPager
  49204. ** exists if the database is not empy, or verify that the *-wal file does
  49205. ** not exist (by deleting it) if the database file is empty.
  49206. **
  49207. ** If the database is not empty and the *-wal file exists, open the pager
  49208. ** in WAL mode. If the database is empty or if no *-wal file exists and
  49209. ** if no error occurs, make sure Pager.journalMode is not set to
  49210. ** PAGER_JOURNALMODE_WAL.
  49211. **
  49212. ** Return SQLITE_OK or an error code.
  49213. **
  49214. ** The caller must hold a SHARED lock on the database file to call this
  49215. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  49216. ** a WAL on a none-empty database, this ensures there is no race condition
  49217. ** between the xAccess() below and an xDelete() being executed by some
  49218. ** other connection.
  49219. */
  49220. static int pagerOpenWalIfPresent(Pager *pPager){
  49221. int rc = SQLITE_OK;
  49222. assert( pPager->eState==PAGER_OPEN );
  49223. assert( pPager->eLock>=SHARED_LOCK );
  49224. if( !pPager->tempFile ){
  49225. int isWal; /* True if WAL file exists */
  49226. rc = sqlite3OsAccess(
  49227. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  49228. );
  49229. if( rc==SQLITE_OK ){
  49230. if( isWal ){
  49231. Pgno nPage; /* Size of the database file */
  49232. rc = pagerPagecount(pPager, &nPage);
  49233. if( rc ) return rc;
  49234. if( nPage==0 ){
  49235. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  49236. }else{
  49237. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  49238. rc = sqlite3PagerOpenWal(pPager, 0);
  49239. }
  49240. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  49241. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  49242. }
  49243. }
  49244. }
  49245. return rc;
  49246. }
  49247. #endif
  49248. /*
  49249. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  49250. ** the entire master journal file. The case pSavepoint==NULL occurs when
  49251. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  49252. ** savepoint.
  49253. **
  49254. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  49255. ** being rolled back), then the rollback consists of up to three stages,
  49256. ** performed in the order specified:
  49257. **
  49258. ** * Pages are played back from the main journal starting at byte
  49259. ** offset PagerSavepoint.iOffset and continuing to
  49260. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  49261. ** file if PagerSavepoint.iHdrOffset is zero.
  49262. **
  49263. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  49264. ** back starting from the journal header immediately following
  49265. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  49266. **
  49267. ** * Pages are then played back from the sub-journal file, starting
  49268. ** with the PagerSavepoint.iSubRec and continuing to the end of
  49269. ** the journal file.
  49270. **
  49271. ** Throughout the rollback process, each time a page is rolled back, the
  49272. ** corresponding bit is set in a bitvec structure (variable pDone in the
  49273. ** implementation below). This is used to ensure that a page is only
  49274. ** rolled back the first time it is encountered in either journal.
  49275. **
  49276. ** If pSavepoint is NULL, then pages are only played back from the main
  49277. ** journal file. There is no need for a bitvec in this case.
  49278. **
  49279. ** In either case, before playback commences the Pager.dbSize variable
  49280. ** is reset to the value that it held at the start of the savepoint
  49281. ** (or transaction). No page with a page-number greater than this value
  49282. ** is played back. If one is encountered it is simply skipped.
  49283. */
  49284. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  49285. i64 szJ; /* Effective size of the main journal */
  49286. i64 iHdrOff; /* End of first segment of main-journal records */
  49287. int rc = SQLITE_OK; /* Return code */
  49288. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  49289. assert( pPager->eState!=PAGER_ERROR );
  49290. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  49291. /* Allocate a bitvec to use to store the set of pages rolled back */
  49292. if( pSavepoint ){
  49293. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  49294. if( !pDone ){
  49295. return SQLITE_NOMEM_BKPT;
  49296. }
  49297. }
  49298. /* Set the database size back to the value it was before the savepoint
  49299. ** being reverted was opened.
  49300. */
  49301. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  49302. pPager->changeCountDone = pPager->tempFile;
  49303. if( !pSavepoint && pagerUseWal(pPager) ){
  49304. return pagerRollbackWal(pPager);
  49305. }
  49306. /* Use pPager->journalOff as the effective size of the main rollback
  49307. ** journal. The actual file might be larger than this in
  49308. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  49309. ** past pPager->journalOff is off-limits to us.
  49310. */
  49311. szJ = pPager->journalOff;
  49312. assert( pagerUseWal(pPager)==0 || szJ==0 );
  49313. /* Begin by rolling back records from the main journal starting at
  49314. ** PagerSavepoint.iOffset and continuing to the next journal header.
  49315. ** There might be records in the main journal that have a page number
  49316. ** greater than the current database size (pPager->dbSize) but those
  49317. ** will be skipped automatically. Pages are added to pDone as they
  49318. ** are played back.
  49319. */
  49320. if( pSavepoint && !pagerUseWal(pPager) ){
  49321. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  49322. pPager->journalOff = pSavepoint->iOffset;
  49323. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  49324. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  49325. }
  49326. assert( rc!=SQLITE_DONE );
  49327. }else{
  49328. pPager->journalOff = 0;
  49329. }
  49330. /* Continue rolling back records out of the main journal starting at
  49331. ** the first journal header seen and continuing until the effective end
  49332. ** of the main journal file. Continue to skip out-of-range pages and
  49333. ** continue adding pages rolled back to pDone.
  49334. */
  49335. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  49336. u32 ii; /* Loop counter */
  49337. u32 nJRec = 0; /* Number of Journal Records */
  49338. u32 dummy;
  49339. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  49340. assert( rc!=SQLITE_DONE );
  49341. /*
  49342. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  49343. ** test is related to ticket #2565. See the discussion in the
  49344. ** pager_playback() function for additional information.
  49345. */
  49346. if( nJRec==0
  49347. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  49348. ){
  49349. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  49350. }
  49351. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  49352. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  49353. }
  49354. assert( rc!=SQLITE_DONE );
  49355. }
  49356. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  49357. /* Finally, rollback pages from the sub-journal. Page that were
  49358. ** previously rolled back out of the main journal (and are hence in pDone)
  49359. ** will be skipped. Out-of-range pages are also skipped.
  49360. */
  49361. if( pSavepoint ){
  49362. u32 ii; /* Loop counter */
  49363. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  49364. if( pagerUseWal(pPager) ){
  49365. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  49366. }
  49367. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  49368. assert( offset==(i64)ii*(4+pPager->pageSize) );
  49369. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  49370. }
  49371. assert( rc!=SQLITE_DONE );
  49372. }
  49373. sqlite3BitvecDestroy(pDone);
  49374. if( rc==SQLITE_OK ){
  49375. pPager->journalOff = szJ;
  49376. }
  49377. return rc;
  49378. }
  49379. /*
  49380. ** Change the maximum number of in-memory pages that are allowed
  49381. ** before attempting to recycle clean and unused pages.
  49382. */
  49383. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  49384. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  49385. }
  49386. /*
  49387. ** Change the maximum number of in-memory pages that are allowed
  49388. ** before attempting to spill pages to journal.
  49389. */
  49390. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  49391. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  49392. }
  49393. /*
  49394. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  49395. */
  49396. static void pagerFixMaplimit(Pager *pPager){
  49397. #if SQLITE_MAX_MMAP_SIZE>0
  49398. sqlite3_file *fd = pPager->fd;
  49399. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  49400. sqlite3_int64 sz;
  49401. sz = pPager->szMmap;
  49402. pPager->bUseFetch = (sz>0);
  49403. setGetterMethod(pPager);
  49404. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  49405. }
  49406. #endif
  49407. }
  49408. /*
  49409. ** Change the maximum size of any memory mapping made of the database file.
  49410. */
  49411. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  49412. pPager->szMmap = szMmap;
  49413. pagerFixMaplimit(pPager);
  49414. }
  49415. /*
  49416. ** Free as much memory as possible from the pager.
  49417. */
  49418. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  49419. sqlite3PcacheShrink(pPager->pPCache);
  49420. }
  49421. /*
  49422. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  49423. **
  49424. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  49425. ** of the database to damage due to OS crashes or power failures by
  49426. ** changing the number of syncs()s when writing the journals.
  49427. ** There are four levels:
  49428. **
  49429. ** OFF sqlite3OsSync() is never called. This is the default
  49430. ** for temporary and transient files.
  49431. **
  49432. ** NORMAL The journal is synced once before writes begin on the
  49433. ** database. This is normally adequate protection, but
  49434. ** it is theoretically possible, though very unlikely,
  49435. ** that an inopertune power failure could leave the journal
  49436. ** in a state which would cause damage to the database
  49437. ** when it is rolled back.
  49438. **
  49439. ** FULL The journal is synced twice before writes begin on the
  49440. ** database (with some additional information - the nRec field
  49441. ** of the journal header - being written in between the two
  49442. ** syncs). If we assume that writing a
  49443. ** single disk sector is atomic, then this mode provides
  49444. ** assurance that the journal will not be corrupted to the
  49445. ** point of causing damage to the database during rollback.
  49446. **
  49447. ** EXTRA This is like FULL except that is also syncs the directory
  49448. ** that contains the rollback journal after the rollback
  49449. ** journal is unlinked.
  49450. **
  49451. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  49452. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  49453. ** prior to the start of checkpoint and that the database file is synced
  49454. ** at the conclusion of the checkpoint if the entire content of the WAL
  49455. ** was written back into the database. But no sync operations occur for
  49456. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  49457. ** file is synced following each commit operation, in addition to the
  49458. ** syncs associated with NORMAL. There is no difference between FULL
  49459. ** and EXTRA for WAL mode.
  49460. **
  49461. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  49462. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  49463. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  49464. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  49465. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  49466. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  49467. ** the xSync primitive is called and is relevant to all platforms.
  49468. **
  49469. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  49470. ** and FULL=3.
  49471. */
  49472. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  49473. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  49474. Pager *pPager, /* The pager to set safety level for */
  49475. unsigned pgFlags /* Various flags */
  49476. ){
  49477. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  49478. if( pPager->tempFile ){
  49479. pPager->noSync = 1;
  49480. pPager->fullSync = 0;
  49481. pPager->extraSync = 0;
  49482. }else{
  49483. pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
  49484. pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
  49485. pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
  49486. }
  49487. if( pPager->noSync ){
  49488. pPager->syncFlags = 0;
  49489. }else if( pgFlags & PAGER_FULLFSYNC ){
  49490. pPager->syncFlags = SQLITE_SYNC_FULL;
  49491. }else{
  49492. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  49493. }
  49494. pPager->walSyncFlags = (pPager->syncFlags<<2);
  49495. if( pPager->fullSync ){
  49496. pPager->walSyncFlags |= pPager->syncFlags;
  49497. }
  49498. if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
  49499. pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
  49500. }
  49501. if( pgFlags & PAGER_CACHESPILL ){
  49502. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  49503. }else{
  49504. pPager->doNotSpill |= SPILLFLAG_OFF;
  49505. }
  49506. }
  49507. #endif
  49508. /*
  49509. ** The following global variable is incremented whenever the library
  49510. ** attempts to open a temporary file. This information is used for
  49511. ** testing and analysis only.
  49512. */
  49513. #ifdef SQLITE_TEST
  49514. SQLITE_API int sqlite3_opentemp_count = 0;
  49515. #endif
  49516. /*
  49517. ** Open a temporary file.
  49518. **
  49519. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  49520. ** or some other error code if we fail. The OS will automatically
  49521. ** delete the temporary file when it is closed.
  49522. **
  49523. ** The flags passed to the VFS layer xOpen() call are those specified
  49524. ** by parameter vfsFlags ORed with the following:
  49525. **
  49526. ** SQLITE_OPEN_READWRITE
  49527. ** SQLITE_OPEN_CREATE
  49528. ** SQLITE_OPEN_EXCLUSIVE
  49529. ** SQLITE_OPEN_DELETEONCLOSE
  49530. */
  49531. static int pagerOpentemp(
  49532. Pager *pPager, /* The pager object */
  49533. sqlite3_file *pFile, /* Write the file descriptor here */
  49534. int vfsFlags /* Flags passed through to the VFS */
  49535. ){
  49536. int rc; /* Return code */
  49537. #ifdef SQLITE_TEST
  49538. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  49539. #endif
  49540. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  49541. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  49542. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  49543. assert( rc!=SQLITE_OK || isOpen(pFile) );
  49544. return rc;
  49545. }
  49546. /*
  49547. ** Set the busy handler function.
  49548. **
  49549. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  49550. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  49551. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  49552. ** lock. It does *not* invoke the busy handler when upgrading from
  49553. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  49554. ** (which occurs during hot-journal rollback). Summary:
  49555. **
  49556. ** Transition | Invokes xBusyHandler
  49557. ** --------------------------------------------------------
  49558. ** NO_LOCK -> SHARED_LOCK | Yes
  49559. ** SHARED_LOCK -> RESERVED_LOCK | No
  49560. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  49561. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  49562. **
  49563. ** If the busy-handler callback returns non-zero, the lock is
  49564. ** retried. If it returns zero, then the SQLITE_BUSY error is
  49565. ** returned to the caller of the pager API function.
  49566. */
  49567. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
  49568. Pager *pPager, /* Pager object */
  49569. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  49570. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  49571. ){
  49572. void **ap;
  49573. pPager->xBusyHandler = xBusyHandler;
  49574. pPager->pBusyHandlerArg = pBusyHandlerArg;
  49575. ap = (void **)&pPager->xBusyHandler;
  49576. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  49577. assert( ap[1]==pBusyHandlerArg );
  49578. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  49579. }
  49580. /*
  49581. ** Change the page size used by the Pager object. The new page size
  49582. ** is passed in *pPageSize.
  49583. **
  49584. ** If the pager is in the error state when this function is called, it
  49585. ** is a no-op. The value returned is the error state error code (i.e.
  49586. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  49587. **
  49588. ** Otherwise, if all of the following are true:
  49589. **
  49590. ** * the new page size (value of *pPageSize) is valid (a power
  49591. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  49592. **
  49593. ** * there are no outstanding page references, and
  49594. **
  49595. ** * the database is either not an in-memory database or it is
  49596. ** an in-memory database that currently consists of zero pages.
  49597. **
  49598. ** then the pager object page size is set to *pPageSize.
  49599. **
  49600. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  49601. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  49602. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  49603. ** In all other cases, SQLITE_OK is returned.
  49604. **
  49605. ** If the page size is not changed, either because one of the enumerated
  49606. ** conditions above is not true, the pager was in error state when this
  49607. ** function was called, or because the memory allocation attempt failed,
  49608. ** then *pPageSize is set to the old, retained page size before returning.
  49609. */
  49610. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  49611. int rc = SQLITE_OK;
  49612. /* It is not possible to do a full assert_pager_state() here, as this
  49613. ** function may be called from within PagerOpen(), before the state
  49614. ** of the Pager object is internally consistent.
  49615. **
  49616. ** At one point this function returned an error if the pager was in
  49617. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  49618. ** there is at least one outstanding page reference, this function
  49619. ** is a no-op for that case anyhow.
  49620. */
  49621. u32 pageSize = *pPageSize;
  49622. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  49623. if( (pPager->memDb==0 || pPager->dbSize==0)
  49624. && sqlite3PcacheRefCount(pPager->pPCache)==0
  49625. && pageSize && pageSize!=(u32)pPager->pageSize
  49626. ){
  49627. char *pNew = NULL; /* New temp space */
  49628. i64 nByte = 0;
  49629. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  49630. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  49631. }
  49632. if( rc==SQLITE_OK ){
  49633. pNew = (char *)sqlite3PageMalloc(pageSize);
  49634. if( !pNew ) rc = SQLITE_NOMEM_BKPT;
  49635. }
  49636. if( rc==SQLITE_OK ){
  49637. pager_reset(pPager);
  49638. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  49639. }
  49640. if( rc==SQLITE_OK ){
  49641. sqlite3PageFree(pPager->pTmpSpace);
  49642. pPager->pTmpSpace = pNew;
  49643. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  49644. pPager->pageSize = pageSize;
  49645. }else{
  49646. sqlite3PageFree(pNew);
  49647. }
  49648. }
  49649. *pPageSize = pPager->pageSize;
  49650. if( rc==SQLITE_OK ){
  49651. if( nReserve<0 ) nReserve = pPager->nReserve;
  49652. assert( nReserve>=0 && nReserve<1000 );
  49653. pPager->nReserve = (i16)nReserve;
  49654. pagerReportSize(pPager);
  49655. pagerFixMaplimit(pPager);
  49656. }
  49657. return rc;
  49658. }
  49659. /*
  49660. ** Return a pointer to the "temporary page" buffer held internally
  49661. ** by the pager. This is a buffer that is big enough to hold the
  49662. ** entire content of a database page. This buffer is used internally
  49663. ** during rollback and will be overwritten whenever a rollback
  49664. ** occurs. But other modules are free to use it too, as long as
  49665. ** no rollbacks are happening.
  49666. */
  49667. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  49668. return pPager->pTmpSpace;
  49669. }
  49670. /*
  49671. ** Attempt to set the maximum database page count if mxPage is positive.
  49672. ** Make no changes if mxPage is zero or negative. And never reduce the
  49673. ** maximum page count below the current size of the database.
  49674. **
  49675. ** Regardless of mxPage, return the current maximum page count.
  49676. */
  49677. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  49678. if( mxPage>0 ){
  49679. pPager->mxPgno = mxPage;
  49680. }
  49681. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  49682. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  49683. return pPager->mxPgno;
  49684. }
  49685. /*
  49686. ** The following set of routines are used to disable the simulated
  49687. ** I/O error mechanism. These routines are used to avoid simulated
  49688. ** errors in places where we do not care about errors.
  49689. **
  49690. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  49691. ** and generate no code.
  49692. */
  49693. #ifdef SQLITE_TEST
  49694. SQLITE_API extern int sqlite3_io_error_pending;
  49695. SQLITE_API extern int sqlite3_io_error_hit;
  49696. static int saved_cnt;
  49697. void disable_simulated_io_errors(void){
  49698. saved_cnt = sqlite3_io_error_pending;
  49699. sqlite3_io_error_pending = -1;
  49700. }
  49701. void enable_simulated_io_errors(void){
  49702. sqlite3_io_error_pending = saved_cnt;
  49703. }
  49704. #else
  49705. # define disable_simulated_io_errors()
  49706. # define enable_simulated_io_errors()
  49707. #endif
  49708. /*
  49709. ** Read the first N bytes from the beginning of the file into memory
  49710. ** that pDest points to.
  49711. **
  49712. ** If the pager was opened on a transient file (zFilename==""), or
  49713. ** opened on a file less than N bytes in size, the output buffer is
  49714. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  49715. ** function is used to read database headers, and a new transient or
  49716. ** zero sized database has a header than consists entirely of zeroes.
  49717. **
  49718. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  49719. ** the error code is returned to the caller and the contents of the
  49720. ** output buffer undefined.
  49721. */
  49722. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  49723. int rc = SQLITE_OK;
  49724. memset(pDest, 0, N);
  49725. assert( isOpen(pPager->fd) || pPager->tempFile );
  49726. /* This routine is only called by btree immediately after creating
  49727. ** the Pager object. There has not been an opportunity to transition
  49728. ** to WAL mode yet.
  49729. */
  49730. assert( !pagerUseWal(pPager) );
  49731. if( isOpen(pPager->fd) ){
  49732. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  49733. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  49734. if( rc==SQLITE_IOERR_SHORT_READ ){
  49735. rc = SQLITE_OK;
  49736. }
  49737. }
  49738. return rc;
  49739. }
  49740. /*
  49741. ** This function may only be called when a read-transaction is open on
  49742. ** the pager. It returns the total number of pages in the database.
  49743. **
  49744. ** However, if the file is between 1 and <page-size> bytes in size, then
  49745. ** this is considered a 1 page file.
  49746. */
  49747. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  49748. assert( pPager->eState>=PAGER_READER );
  49749. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  49750. *pnPage = (int)pPager->dbSize;
  49751. }
  49752. /*
  49753. ** Try to obtain a lock of type locktype on the database file. If
  49754. ** a similar or greater lock is already held, this function is a no-op
  49755. ** (returning SQLITE_OK immediately).
  49756. **
  49757. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  49758. ** the busy callback if the lock is currently not available. Repeat
  49759. ** until the busy callback returns false or until the attempt to
  49760. ** obtain the lock succeeds.
  49761. **
  49762. ** Return SQLITE_OK on success and an error code if we cannot obtain
  49763. ** the lock. If the lock is obtained successfully, set the Pager.state
  49764. ** variable to locktype before returning.
  49765. */
  49766. static int pager_wait_on_lock(Pager *pPager, int locktype){
  49767. int rc; /* Return code */
  49768. /* Check that this is either a no-op (because the requested lock is
  49769. ** already held), or one of the transitions that the busy-handler
  49770. ** may be invoked during, according to the comment above
  49771. ** sqlite3PagerSetBusyhandler().
  49772. */
  49773. assert( (pPager->eLock>=locktype)
  49774. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  49775. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  49776. );
  49777. do {
  49778. rc = pagerLockDb(pPager, locktype);
  49779. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  49780. return rc;
  49781. }
  49782. /*
  49783. ** Function assertTruncateConstraint(pPager) checks that one of the
  49784. ** following is true for all dirty pages currently in the page-cache:
  49785. **
  49786. ** a) The page number is less than or equal to the size of the
  49787. ** current database image, in pages, OR
  49788. **
  49789. ** b) if the page content were written at this time, it would not
  49790. ** be necessary to write the current content out to the sub-journal
  49791. ** (as determined by function subjRequiresPage()).
  49792. **
  49793. ** If the condition asserted by this function were not true, and the
  49794. ** dirty page were to be discarded from the cache via the pagerStress()
  49795. ** routine, pagerStress() would not write the current page content to
  49796. ** the database file. If a savepoint transaction were rolled back after
  49797. ** this happened, the correct behavior would be to restore the current
  49798. ** content of the page. However, since this content is not present in either
  49799. ** the database file or the portion of the rollback journal and
  49800. ** sub-journal rolled back the content could not be restored and the
  49801. ** database image would become corrupt. It is therefore fortunate that
  49802. ** this circumstance cannot arise.
  49803. */
  49804. #if defined(SQLITE_DEBUG)
  49805. static void assertTruncateConstraintCb(PgHdr *pPg){
  49806. assert( pPg->flags&PGHDR_DIRTY );
  49807. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  49808. }
  49809. static void assertTruncateConstraint(Pager *pPager){
  49810. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  49811. }
  49812. #else
  49813. # define assertTruncateConstraint(pPager)
  49814. #endif
  49815. /*
  49816. ** Truncate the in-memory database file image to nPage pages. This
  49817. ** function does not actually modify the database file on disk. It
  49818. ** just sets the internal state of the pager object so that the
  49819. ** truncation will be done when the current transaction is committed.
  49820. **
  49821. ** This function is only called right before committing a transaction.
  49822. ** Once this function has been called, the transaction must either be
  49823. ** rolled back or committed. It is not safe to call this function and
  49824. ** then continue writing to the database.
  49825. */
  49826. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  49827. assert( pPager->dbSize>=nPage );
  49828. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  49829. pPager->dbSize = nPage;
  49830. /* At one point the code here called assertTruncateConstraint() to
  49831. ** ensure that all pages being truncated away by this operation are,
  49832. ** if one or more savepoints are open, present in the savepoint
  49833. ** journal so that they can be restored if the savepoint is rolled
  49834. ** back. This is no longer necessary as this function is now only
  49835. ** called right before committing a transaction. So although the
  49836. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  49837. ** they cannot be rolled back. So the assertTruncateConstraint() call
  49838. ** is no longer correct. */
  49839. }
  49840. /*
  49841. ** This function is called before attempting a hot-journal rollback. It
  49842. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  49843. ** size of the journal file so that the pager_playback() routine knows
  49844. ** that the entire journal file has been synced.
  49845. **
  49846. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  49847. ** that if a power-failure occurs during the rollback, the process that
  49848. ** attempts rollback following system recovery sees the same journal
  49849. ** content as this process.
  49850. **
  49851. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  49852. ** an SQLite error code.
  49853. */
  49854. static int pagerSyncHotJournal(Pager *pPager){
  49855. int rc = SQLITE_OK;
  49856. if( !pPager->noSync ){
  49857. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  49858. }
  49859. if( rc==SQLITE_OK ){
  49860. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  49861. }
  49862. return rc;
  49863. }
  49864. #if SQLITE_MAX_MMAP_SIZE>0
  49865. /*
  49866. ** Obtain a reference to a memory mapped page object for page number pgno.
  49867. ** The new object will use the pointer pData, obtained from xFetch().
  49868. ** If successful, set *ppPage to point to the new page reference
  49869. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  49870. ** *ppPage to zero.
  49871. **
  49872. ** Page references obtained by calling this function should be released
  49873. ** by calling pagerReleaseMapPage().
  49874. */
  49875. static int pagerAcquireMapPage(
  49876. Pager *pPager, /* Pager object */
  49877. Pgno pgno, /* Page number */
  49878. void *pData, /* xFetch()'d data for this page */
  49879. PgHdr **ppPage /* OUT: Acquired page object */
  49880. ){
  49881. PgHdr *p; /* Memory mapped page to return */
  49882. if( pPager->pMmapFreelist ){
  49883. *ppPage = p = pPager->pMmapFreelist;
  49884. pPager->pMmapFreelist = p->pDirty;
  49885. p->pDirty = 0;
  49886. assert( pPager->nExtra>=8 );
  49887. memset(p->pExtra, 0, 8);
  49888. }else{
  49889. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  49890. if( p==0 ){
  49891. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  49892. return SQLITE_NOMEM_BKPT;
  49893. }
  49894. p->pExtra = (void *)&p[1];
  49895. p->flags = PGHDR_MMAP;
  49896. p->nRef = 1;
  49897. p->pPager = pPager;
  49898. }
  49899. assert( p->pExtra==(void *)&p[1] );
  49900. assert( p->pPage==0 );
  49901. assert( p->flags==PGHDR_MMAP );
  49902. assert( p->pPager==pPager );
  49903. assert( p->nRef==1 );
  49904. p->pgno = pgno;
  49905. p->pData = pData;
  49906. pPager->nMmapOut++;
  49907. return SQLITE_OK;
  49908. }
  49909. #endif
  49910. /*
  49911. ** Release a reference to page pPg. pPg must have been returned by an
  49912. ** earlier call to pagerAcquireMapPage().
  49913. */
  49914. static void pagerReleaseMapPage(PgHdr *pPg){
  49915. Pager *pPager = pPg->pPager;
  49916. pPager->nMmapOut--;
  49917. pPg->pDirty = pPager->pMmapFreelist;
  49918. pPager->pMmapFreelist = pPg;
  49919. assert( pPager->fd->pMethods->iVersion>=3 );
  49920. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  49921. }
  49922. /*
  49923. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  49924. */
  49925. static void pagerFreeMapHdrs(Pager *pPager){
  49926. PgHdr *p;
  49927. PgHdr *pNext;
  49928. for(p=pPager->pMmapFreelist; p; p=pNext){
  49929. pNext = p->pDirty;
  49930. sqlite3_free(p);
  49931. }
  49932. }
  49933. /* Verify that the database file has not be deleted or renamed out from
  49934. ** under the pager. Return SQLITE_OK if the database is still where it ought
  49935. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  49936. ** code from sqlite3OsAccess()) if the database has gone missing.
  49937. */
  49938. static int databaseIsUnmoved(Pager *pPager){
  49939. int bHasMoved = 0;
  49940. int rc;
  49941. if( pPager->tempFile ) return SQLITE_OK;
  49942. if( pPager->dbSize==0 ) return SQLITE_OK;
  49943. assert( pPager->zFilename && pPager->zFilename[0] );
  49944. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  49945. if( rc==SQLITE_NOTFOUND ){
  49946. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  49947. ** has not been moved. That is the historical behavior of SQLite: prior to
  49948. ** version 3.8.3, it never checked */
  49949. rc = SQLITE_OK;
  49950. }else if( rc==SQLITE_OK && bHasMoved ){
  49951. rc = SQLITE_READONLY_DBMOVED;
  49952. }
  49953. return rc;
  49954. }
  49955. /*
  49956. ** Shutdown the page cache. Free all memory and close all files.
  49957. **
  49958. ** If a transaction was in progress when this routine is called, that
  49959. ** transaction is rolled back. All outstanding pages are invalidated
  49960. ** and their memory is freed. Any attempt to use a page associated
  49961. ** with this page cache after this function returns will likely
  49962. ** result in a coredump.
  49963. **
  49964. ** This function always succeeds. If a transaction is active an attempt
  49965. ** is made to roll it back. If an error occurs during the rollback
  49966. ** a hot journal may be left in the filesystem but no error is returned
  49967. ** to the caller.
  49968. */
  49969. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
  49970. u8 *pTmp = (u8*)pPager->pTmpSpace;
  49971. assert( db || pagerUseWal(pPager)==0 );
  49972. assert( assert_pager_state(pPager) );
  49973. disable_simulated_io_errors();
  49974. sqlite3BeginBenignMalloc();
  49975. pagerFreeMapHdrs(pPager);
  49976. /* pPager->errCode = 0; */
  49977. pPager->exclusiveMode = 0;
  49978. #ifndef SQLITE_OMIT_WAL
  49979. {
  49980. u8 *a = 0;
  49981. assert( db || pPager->pWal==0 );
  49982. if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
  49983. && SQLITE_OK==databaseIsUnmoved(pPager)
  49984. ){
  49985. a = pTmp;
  49986. }
  49987. sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
  49988. pPager->pWal = 0;
  49989. }
  49990. #endif
  49991. pager_reset(pPager);
  49992. if( MEMDB ){
  49993. pager_unlock(pPager);
  49994. }else{
  49995. /* If it is open, sync the journal file before calling UnlockAndRollback.
  49996. ** If this is not done, then an unsynced portion of the open journal
  49997. ** file may be played back into the database. If a power failure occurs
  49998. ** while this is happening, the database could become corrupt.
  49999. **
  50000. ** If an error occurs while trying to sync the journal, shift the pager
  50001. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  50002. ** database and close the journal file without attempting to roll it
  50003. ** back or finalize it. The next database user will have to do hot-journal
  50004. ** rollback before accessing the database file.
  50005. */
  50006. if( isOpen(pPager->jfd) ){
  50007. pager_error(pPager, pagerSyncHotJournal(pPager));
  50008. }
  50009. pagerUnlockAndRollback(pPager);
  50010. }
  50011. sqlite3EndBenignMalloc();
  50012. enable_simulated_io_errors();
  50013. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  50014. IOTRACE(("CLOSE %p\n", pPager))
  50015. sqlite3OsClose(pPager->jfd);
  50016. sqlite3OsClose(pPager->fd);
  50017. sqlite3PageFree(pTmp);
  50018. sqlite3PcacheClose(pPager->pPCache);
  50019. #ifdef SQLITE_HAS_CODEC
  50020. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  50021. #endif
  50022. assert( !pPager->aSavepoint && !pPager->pInJournal );
  50023. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  50024. sqlite3_free(pPager);
  50025. return SQLITE_OK;
  50026. }
  50027. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  50028. /*
  50029. ** Return the page number for page pPg.
  50030. */
  50031. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  50032. return pPg->pgno;
  50033. }
  50034. #endif
  50035. /*
  50036. ** Increment the reference count for page pPg.
  50037. */
  50038. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  50039. sqlite3PcacheRef(pPg);
  50040. }
  50041. /*
  50042. ** Sync the journal. In other words, make sure all the pages that have
  50043. ** been written to the journal have actually reached the surface of the
  50044. ** disk and can be restored in the event of a hot-journal rollback.
  50045. **
  50046. ** If the Pager.noSync flag is set, then this function is a no-op.
  50047. ** Otherwise, the actions required depend on the journal-mode and the
  50048. ** device characteristics of the file-system, as follows:
  50049. **
  50050. ** * If the journal file is an in-memory journal file, no action need
  50051. ** be taken.
  50052. **
  50053. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  50054. ** then the nRec field of the most recently written journal header
  50055. ** is updated to contain the number of journal records that have
  50056. ** been written following it. If the pager is operating in full-sync
  50057. ** mode, then the journal file is synced before this field is updated.
  50058. **
  50059. ** * If the device does not support the SEQUENTIAL property, then
  50060. ** journal file is synced.
  50061. **
  50062. ** Or, in pseudo-code:
  50063. **
  50064. ** if( NOT <in-memory journal> ){
  50065. ** if( NOT SAFE_APPEND ){
  50066. ** if( <full-sync mode> ) xSync(<journal file>);
  50067. ** <update nRec field>
  50068. ** }
  50069. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  50070. ** }
  50071. **
  50072. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  50073. ** page currently held in memory before returning SQLITE_OK. If an IO
  50074. ** error is encountered, then the IO error code is returned to the caller.
  50075. */
  50076. static int syncJournal(Pager *pPager, int newHdr){
  50077. int rc; /* Return code */
  50078. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  50079. || pPager->eState==PAGER_WRITER_DBMOD
  50080. );
  50081. assert( assert_pager_state(pPager) );
  50082. assert( !pagerUseWal(pPager) );
  50083. rc = sqlite3PagerExclusiveLock(pPager);
  50084. if( rc!=SQLITE_OK ) return rc;
  50085. if( !pPager->noSync ){
  50086. assert( !pPager->tempFile );
  50087. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  50088. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  50089. assert( isOpen(pPager->jfd) );
  50090. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  50091. /* This block deals with an obscure problem. If the last connection
  50092. ** that wrote to this database was operating in persistent-journal
  50093. ** mode, then the journal file may at this point actually be larger
  50094. ** than Pager.journalOff bytes. If the next thing in the journal
  50095. ** file happens to be a journal-header (written as part of the
  50096. ** previous connection's transaction), and a crash or power-failure
  50097. ** occurs after nRec is updated but before this connection writes
  50098. ** anything else to the journal file (or commits/rolls back its
  50099. ** transaction), then SQLite may become confused when doing the
  50100. ** hot-journal rollback following recovery. It may roll back all
  50101. ** of this connections data, then proceed to rolling back the old,
  50102. ** out-of-date data that follows it. Database corruption.
  50103. **
  50104. ** To work around this, if the journal file does appear to contain
  50105. ** a valid header following Pager.journalOff, then write a 0x00
  50106. ** byte to the start of it to prevent it from being recognized.
  50107. **
  50108. ** Variable iNextHdrOffset is set to the offset at which this
  50109. ** problematic header will occur, if it exists. aMagic is used
  50110. ** as a temporary buffer to inspect the first couple of bytes of
  50111. ** the potential journal header.
  50112. */
  50113. i64 iNextHdrOffset;
  50114. u8 aMagic[8];
  50115. u8 zHeader[sizeof(aJournalMagic)+4];
  50116. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  50117. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  50118. iNextHdrOffset = journalHdrOffset(pPager);
  50119. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  50120. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  50121. static const u8 zerobyte = 0;
  50122. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  50123. }
  50124. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  50125. return rc;
  50126. }
  50127. /* Write the nRec value into the journal file header. If in
  50128. ** full-synchronous mode, sync the journal first. This ensures that
  50129. ** all data has really hit the disk before nRec is updated to mark
  50130. ** it as a candidate for rollback.
  50131. **
  50132. ** This is not required if the persistent media supports the
  50133. ** SAFE_APPEND property. Because in this case it is not possible
  50134. ** for garbage data to be appended to the file, the nRec field
  50135. ** is populated with 0xFFFFFFFF when the journal header is written
  50136. ** and never needs to be updated.
  50137. */
  50138. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  50139. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  50140. IOTRACE(("JSYNC %p\n", pPager))
  50141. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  50142. if( rc!=SQLITE_OK ) return rc;
  50143. }
  50144. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  50145. rc = sqlite3OsWrite(
  50146. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  50147. );
  50148. if( rc!=SQLITE_OK ) return rc;
  50149. }
  50150. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  50151. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  50152. IOTRACE(("JSYNC %p\n", pPager))
  50153. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  50154. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  50155. );
  50156. if( rc!=SQLITE_OK ) return rc;
  50157. }
  50158. pPager->journalHdr = pPager->journalOff;
  50159. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  50160. pPager->nRec = 0;
  50161. rc = writeJournalHdr(pPager);
  50162. if( rc!=SQLITE_OK ) return rc;
  50163. }
  50164. }else{
  50165. pPager->journalHdr = pPager->journalOff;
  50166. }
  50167. }
  50168. /* Unless the pager is in noSync mode, the journal file was just
  50169. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  50170. ** all pages.
  50171. */
  50172. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  50173. pPager->eState = PAGER_WRITER_DBMOD;
  50174. assert( assert_pager_state(pPager) );
  50175. return SQLITE_OK;
  50176. }
  50177. /*
  50178. ** The argument is the first in a linked list of dirty pages connected
  50179. ** by the PgHdr.pDirty pointer. This function writes each one of the
  50180. ** in-memory pages in the list to the database file. The argument may
  50181. ** be NULL, representing an empty list. In this case this function is
  50182. ** a no-op.
  50183. **
  50184. ** The pager must hold at least a RESERVED lock when this function
  50185. ** is called. Before writing anything to the database file, this lock
  50186. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  50187. ** SQLITE_BUSY is returned and no data is written to the database file.
  50188. **
  50189. ** If the pager is a temp-file pager and the actual file-system file
  50190. ** is not yet open, it is created and opened before any data is
  50191. ** written out.
  50192. **
  50193. ** Once the lock has been upgraded and, if necessary, the file opened,
  50194. ** the pages are written out to the database file in list order. Writing
  50195. ** a page is skipped if it meets either of the following criteria:
  50196. **
  50197. ** * The page number is greater than Pager.dbSize, or
  50198. ** * The PGHDR_DONT_WRITE flag is set on the page.
  50199. **
  50200. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  50201. ** is updated accordingly. If page 1 is written out, then the value cached
  50202. ** in Pager.dbFileVers[] is updated to match the new value stored in
  50203. ** the database file.
  50204. **
  50205. ** If everything is successful, SQLITE_OK is returned. If an IO error
  50206. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  50207. ** be obtained, SQLITE_BUSY is returned.
  50208. */
  50209. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  50210. int rc = SQLITE_OK; /* Return code */
  50211. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  50212. assert( !pagerUseWal(pPager) );
  50213. assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
  50214. assert( pPager->eLock==EXCLUSIVE_LOCK );
  50215. assert( isOpen(pPager->fd) || pList->pDirty==0 );
  50216. /* If the file is a temp-file has not yet been opened, open it now. It
  50217. ** is not possible for rc to be other than SQLITE_OK if this branch
  50218. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  50219. */
  50220. if( !isOpen(pPager->fd) ){
  50221. assert( pPager->tempFile && rc==SQLITE_OK );
  50222. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  50223. }
  50224. /* Before the first write, give the VFS a hint of what the final
  50225. ** file size will be.
  50226. */
  50227. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  50228. if( rc==SQLITE_OK
  50229. && pPager->dbHintSize<pPager->dbSize
  50230. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  50231. ){
  50232. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  50233. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  50234. pPager->dbHintSize = pPager->dbSize;
  50235. }
  50236. while( rc==SQLITE_OK && pList ){
  50237. Pgno pgno = pList->pgno;
  50238. /* If there are dirty pages in the page cache with page numbers greater
  50239. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  50240. ** make the file smaller (presumably by auto-vacuum code). Do not write
  50241. ** any such pages to the file.
  50242. **
  50243. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  50244. ** set (set by sqlite3PagerDontWrite()).
  50245. */
  50246. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  50247. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  50248. char *pData; /* Data to write */
  50249. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  50250. if( pList->pgno==1 ) pager_write_changecounter(pList);
  50251. /* Encode the database */
  50252. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
  50253. /* Write out the page data. */
  50254. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  50255. /* If page 1 was just written, update Pager.dbFileVers to match
  50256. ** the value now stored in the database file. If writing this
  50257. ** page caused the database file to grow, update dbFileSize.
  50258. */
  50259. if( pgno==1 ){
  50260. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  50261. }
  50262. if( pgno>pPager->dbFileSize ){
  50263. pPager->dbFileSize = pgno;
  50264. }
  50265. pPager->aStat[PAGER_STAT_WRITE]++;
  50266. /* Update any backup objects copying the contents of this pager. */
  50267. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  50268. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  50269. PAGERID(pPager), pgno, pager_pagehash(pList)));
  50270. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  50271. PAGER_INCR(sqlite3_pager_writedb_count);
  50272. }else{
  50273. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  50274. }
  50275. pager_set_pagehash(pList);
  50276. pList = pList->pDirty;
  50277. }
  50278. return rc;
  50279. }
  50280. /*
  50281. ** Ensure that the sub-journal file is open. If it is already open, this
  50282. ** function is a no-op.
  50283. **
  50284. ** SQLITE_OK is returned if everything goes according to plan. An
  50285. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  50286. ** fails.
  50287. */
  50288. static int openSubJournal(Pager *pPager){
  50289. int rc = SQLITE_OK;
  50290. if( !isOpen(pPager->sjfd) ){
  50291. const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
  50292. | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
  50293. | SQLITE_OPEN_DELETEONCLOSE;
  50294. int nStmtSpill = sqlite3Config.nStmtSpill;
  50295. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  50296. nStmtSpill = -1;
  50297. }
  50298. rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
  50299. }
  50300. return rc;
  50301. }
  50302. /*
  50303. ** Append a record of the current state of page pPg to the sub-journal.
  50304. **
  50305. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  50306. ** for all open savepoints before returning.
  50307. **
  50308. ** This function returns SQLITE_OK if everything is successful, an IO
  50309. ** error code if the attempt to write to the sub-journal fails, or
  50310. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  50311. ** bitvec.
  50312. */
  50313. static int subjournalPage(PgHdr *pPg){
  50314. int rc = SQLITE_OK;
  50315. Pager *pPager = pPg->pPager;
  50316. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  50317. /* Open the sub-journal, if it has not already been opened */
  50318. assert( pPager->useJournal );
  50319. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  50320. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  50321. assert( pagerUseWal(pPager)
  50322. || pageInJournal(pPager, pPg)
  50323. || pPg->pgno>pPager->dbOrigSize
  50324. );
  50325. rc = openSubJournal(pPager);
  50326. /* If the sub-journal was opened successfully (or was already open),
  50327. ** write the journal record into the file. */
  50328. if( rc==SQLITE_OK ){
  50329. void *pData = pPg->pData;
  50330. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  50331. char *pData2;
  50332. #if SQLITE_HAS_CODEC
  50333. if( !pPager->subjInMemory ){
  50334. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  50335. }else
  50336. #endif
  50337. pData2 = pData;
  50338. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  50339. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  50340. if( rc==SQLITE_OK ){
  50341. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  50342. }
  50343. }
  50344. }
  50345. if( rc==SQLITE_OK ){
  50346. pPager->nSubRec++;
  50347. assert( pPager->nSavepoint>0 );
  50348. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  50349. }
  50350. return rc;
  50351. }
  50352. static int subjournalPageIfRequired(PgHdr *pPg){
  50353. if( subjRequiresPage(pPg) ){
  50354. return subjournalPage(pPg);
  50355. }else{
  50356. return SQLITE_OK;
  50357. }
  50358. }
  50359. /*
  50360. ** This function is called by the pcache layer when it has reached some
  50361. ** soft memory limit. The first argument is a pointer to a Pager object
  50362. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  50363. ** database). The second argument is a reference to a page that is
  50364. ** currently dirty but has no outstanding references. The page
  50365. ** is always associated with the Pager object passed as the first
  50366. ** argument.
  50367. **
  50368. ** The job of this function is to make pPg clean by writing its contents
  50369. ** out to the database file, if possible. This may involve syncing the
  50370. ** journal file.
  50371. **
  50372. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  50373. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  50374. ** page clean, the IO error code is returned. If the page cannot be
  50375. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  50376. ** is returned by sqlite3PcacheMakeClean() is not called.
  50377. */
  50378. static int pagerStress(void *p, PgHdr *pPg){
  50379. Pager *pPager = (Pager *)p;
  50380. int rc = SQLITE_OK;
  50381. assert( pPg->pPager==pPager );
  50382. assert( pPg->flags&PGHDR_DIRTY );
  50383. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  50384. ** journal (and adding a new header) is not allowed. This occurs
  50385. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  50386. ** pages belonging to the same sector.
  50387. **
  50388. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  50389. ** regardless of whether or not a sync is required. This is set during
  50390. ** a rollback or by user request, respectively.
  50391. **
  50392. ** Spilling is also prohibited when in an error state since that could
  50393. ** lead to database corruption. In the current implementation it
  50394. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  50395. ** while in the error state, hence it is impossible for this routine to
  50396. ** be called in the error state. Nevertheless, we include a NEVER()
  50397. ** test for the error state as a safeguard against future changes.
  50398. */
  50399. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  50400. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  50401. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  50402. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  50403. if( pPager->doNotSpill
  50404. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  50405. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  50406. ){
  50407. return SQLITE_OK;
  50408. }
  50409. pPager->aStat[PAGER_STAT_SPILL]++;
  50410. pPg->pDirty = 0;
  50411. if( pagerUseWal(pPager) ){
  50412. /* Write a single frame for this page to the log. */
  50413. rc = subjournalPageIfRequired(pPg);
  50414. if( rc==SQLITE_OK ){
  50415. rc = pagerWalFrames(pPager, pPg, 0, 0);
  50416. }
  50417. }else{
  50418. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  50419. if( pPager->tempFile==0 ){
  50420. rc = sqlite3JournalCreate(pPager->jfd);
  50421. if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
  50422. }
  50423. #endif
  50424. /* Sync the journal file if required. */
  50425. if( pPg->flags&PGHDR_NEED_SYNC
  50426. || pPager->eState==PAGER_WRITER_CACHEMOD
  50427. ){
  50428. rc = syncJournal(pPager, 1);
  50429. }
  50430. /* Write the contents of the page out to the database file. */
  50431. if( rc==SQLITE_OK ){
  50432. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  50433. rc = pager_write_pagelist(pPager, pPg);
  50434. }
  50435. }
  50436. /* Mark the page as clean. */
  50437. if( rc==SQLITE_OK ){
  50438. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  50439. sqlite3PcacheMakeClean(pPg);
  50440. }
  50441. return pager_error(pPager, rc);
  50442. }
  50443. /*
  50444. ** Flush all unreferenced dirty pages to disk.
  50445. */
  50446. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  50447. int rc = pPager->errCode;
  50448. if( !MEMDB ){
  50449. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  50450. assert( assert_pager_state(pPager) );
  50451. while( rc==SQLITE_OK && pList ){
  50452. PgHdr *pNext = pList->pDirty;
  50453. if( pList->nRef==0 ){
  50454. rc = pagerStress((void*)pPager, pList);
  50455. }
  50456. pList = pNext;
  50457. }
  50458. }
  50459. return rc;
  50460. }
  50461. /*
  50462. ** Allocate and initialize a new Pager object and put a pointer to it
  50463. ** in *ppPager. The pager should eventually be freed by passing it
  50464. ** to sqlite3PagerClose().
  50465. **
  50466. ** The zFilename argument is the path to the database file to open.
  50467. ** If zFilename is NULL then a randomly-named temporary file is created
  50468. ** and used as the file to be cached. Temporary files are be deleted
  50469. ** automatically when they are closed. If zFilename is ":memory:" then
  50470. ** all information is held in cache. It is never written to disk.
  50471. ** This can be used to implement an in-memory database.
  50472. **
  50473. ** The nExtra parameter specifies the number of bytes of space allocated
  50474. ** along with each page reference. This space is available to the user
  50475. ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
  50476. ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
  50477. ** (The extra space is used by btree as the MemPage object.)
  50478. **
  50479. ** The flags argument is used to specify properties that affect the
  50480. ** operation of the pager. It should be passed some bitwise combination
  50481. ** of the PAGER_* flags.
  50482. **
  50483. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  50484. ** of the xOpen() method of the supplied VFS when opening files.
  50485. **
  50486. ** If the pager object is allocated and the specified file opened
  50487. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  50488. ** the new pager object. If an error occurs, *ppPager is set to NULL
  50489. ** and error code returned. This function may return SQLITE_NOMEM
  50490. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  50491. ** various SQLITE_IO_XXX errors.
  50492. */
  50493. SQLITE_PRIVATE int sqlite3PagerOpen(
  50494. sqlite3_vfs *pVfs, /* The virtual file system to use */
  50495. Pager **ppPager, /* OUT: Return the Pager structure here */
  50496. const char *zFilename, /* Name of the database file to open */
  50497. int nExtra, /* Extra bytes append to each in-memory page */
  50498. int flags, /* flags controlling this file */
  50499. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  50500. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  50501. ){
  50502. u8 *pPtr;
  50503. Pager *pPager = 0; /* Pager object to allocate and return */
  50504. int rc = SQLITE_OK; /* Return code */
  50505. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  50506. int memDb = 0; /* True if this is an in-memory file */
  50507. #ifdef SQLITE_ENABLE_DESERIALIZE
  50508. int memJM = 0; /* Memory journal mode */
  50509. #else
  50510. # define memJM 0
  50511. #endif
  50512. int readOnly = 0; /* True if this is a read-only file */
  50513. int journalFileSize; /* Bytes to allocate for each journal fd */
  50514. char *zPathname = 0; /* Full path to database file */
  50515. int nPathname = 0; /* Number of bytes in zPathname */
  50516. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  50517. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  50518. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  50519. const char *zUri = 0; /* URI args to copy */
  50520. int nUri = 0; /* Number of bytes of URI args at *zUri */
  50521. /* Figure out how much space is required for each journal file-handle
  50522. ** (there are two of them, the main journal and the sub-journal). */
  50523. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  50524. /* Set the output variable to NULL in case an error occurs. */
  50525. *ppPager = 0;
  50526. #ifndef SQLITE_OMIT_MEMORYDB
  50527. if( flags & PAGER_MEMORY ){
  50528. memDb = 1;
  50529. if( zFilename && zFilename[0] ){
  50530. zPathname = sqlite3DbStrDup(0, zFilename);
  50531. if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
  50532. nPathname = sqlite3Strlen30(zPathname);
  50533. zFilename = 0;
  50534. }
  50535. }
  50536. #endif
  50537. /* Compute and store the full pathname in an allocated buffer pointed
  50538. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  50539. ** leave both nPathname and zPathname set to 0.
  50540. */
  50541. if( zFilename && zFilename[0] ){
  50542. const char *z;
  50543. nPathname = pVfs->mxPathname+1;
  50544. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  50545. if( zPathname==0 ){
  50546. return SQLITE_NOMEM_BKPT;
  50547. }
  50548. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  50549. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  50550. nPathname = sqlite3Strlen30(zPathname);
  50551. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  50552. while( *z ){
  50553. z += sqlite3Strlen30(z)+1;
  50554. z += sqlite3Strlen30(z)+1;
  50555. }
  50556. nUri = (int)(&z[1] - zUri);
  50557. assert( nUri>=0 );
  50558. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  50559. /* This branch is taken when the journal path required by
  50560. ** the database being opened will be more than pVfs->mxPathname
  50561. ** bytes in length. This means the database cannot be opened,
  50562. ** as it will not be possible to open the journal file or even
  50563. ** check for a hot-journal before reading.
  50564. */
  50565. rc = SQLITE_CANTOPEN_BKPT;
  50566. }
  50567. if( rc!=SQLITE_OK ){
  50568. sqlite3DbFree(0, zPathname);
  50569. return rc;
  50570. }
  50571. }
  50572. /* Allocate memory for the Pager structure, PCache object, the
  50573. ** three file descriptors, the database file name and the journal
  50574. ** file name. The layout in memory is as follows:
  50575. **
  50576. ** Pager object (sizeof(Pager) bytes)
  50577. ** PCache object (sqlite3PcacheSize() bytes)
  50578. ** Database file handle (pVfs->szOsFile bytes)
  50579. ** Sub-journal file handle (journalFileSize bytes)
  50580. ** Main journal file handle (journalFileSize bytes)
  50581. ** Database file name (nPathname+1 bytes)
  50582. ** Journal file name (nPathname+8+1 bytes)
  50583. */
  50584. pPtr = (u8 *)sqlite3MallocZero(
  50585. ROUND8(sizeof(*pPager)) + /* Pager structure */
  50586. ROUND8(pcacheSize) + /* PCache object */
  50587. ROUND8(pVfs->szOsFile) + /* The main db file */
  50588. journalFileSize * 2 + /* The two journal files */
  50589. nPathname + 1 + nUri + /* zFilename */
  50590. nPathname + 8 + 2 /* zJournal */
  50591. #ifndef SQLITE_OMIT_WAL
  50592. + nPathname + 4 + 2 /* zWal */
  50593. #endif
  50594. );
  50595. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  50596. if( !pPtr ){
  50597. sqlite3DbFree(0, zPathname);
  50598. return SQLITE_NOMEM_BKPT;
  50599. }
  50600. pPager = (Pager*)(pPtr);
  50601. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  50602. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  50603. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  50604. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  50605. pPager->zFilename = (char*)(pPtr += journalFileSize);
  50606. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  50607. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  50608. if( zPathname ){
  50609. assert( nPathname>0 );
  50610. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  50611. memcpy(pPager->zFilename, zPathname, nPathname);
  50612. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  50613. memcpy(pPager->zJournal, zPathname, nPathname);
  50614. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  50615. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  50616. #ifndef SQLITE_OMIT_WAL
  50617. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  50618. memcpy(pPager->zWal, zPathname, nPathname);
  50619. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  50620. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  50621. #endif
  50622. sqlite3DbFree(0, zPathname);
  50623. }
  50624. pPager->pVfs = pVfs;
  50625. pPager->vfsFlags = vfsFlags;
  50626. /* Open the pager file.
  50627. */
  50628. if( zFilename && zFilename[0] ){
  50629. int fout = 0; /* VFS flags returned by xOpen() */
  50630. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  50631. assert( !memDb );
  50632. #ifdef SQLITE_ENABLE_DESERIALIZE
  50633. memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
  50634. #endif
  50635. readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
  50636. /* If the file was successfully opened for read/write access,
  50637. ** choose a default page size in case we have to create the
  50638. ** database file. The default page size is the maximum of:
  50639. **
  50640. ** + SQLITE_DEFAULT_PAGE_SIZE,
  50641. ** + The value returned by sqlite3OsSectorSize()
  50642. ** + The largest page size that can be written atomically.
  50643. */
  50644. if( rc==SQLITE_OK ){
  50645. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  50646. if( !readOnly ){
  50647. setSectorSize(pPager);
  50648. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  50649. if( szPageDflt<pPager->sectorSize ){
  50650. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  50651. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  50652. }else{
  50653. szPageDflt = (u32)pPager->sectorSize;
  50654. }
  50655. }
  50656. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  50657. {
  50658. int ii;
  50659. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  50660. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  50661. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  50662. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  50663. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  50664. szPageDflt = ii;
  50665. }
  50666. }
  50667. }
  50668. #endif
  50669. }
  50670. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  50671. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  50672. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  50673. vfsFlags |= SQLITE_OPEN_READONLY;
  50674. goto act_like_temp_file;
  50675. }
  50676. }
  50677. }else{
  50678. /* If a temporary file is requested, it is not opened immediately.
  50679. ** In this case we accept the default page size and delay actually
  50680. ** opening the file until the first call to OsWrite().
  50681. **
  50682. ** This branch is also run for an in-memory database. An in-memory
  50683. ** database is the same as a temp-file that is never written out to
  50684. ** disk and uses an in-memory rollback journal.
  50685. **
  50686. ** This branch also runs for files marked as immutable.
  50687. */
  50688. act_like_temp_file:
  50689. tempFile = 1;
  50690. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  50691. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  50692. pPager->noLock = 1; /* Do no locking */
  50693. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  50694. }
  50695. /* The following call to PagerSetPagesize() serves to set the value of
  50696. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  50697. */
  50698. if( rc==SQLITE_OK ){
  50699. assert( pPager->memDb==0 );
  50700. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  50701. testcase( rc!=SQLITE_OK );
  50702. }
  50703. /* Initialize the PCache object. */
  50704. if( rc==SQLITE_OK ){
  50705. nExtra = ROUND8(nExtra);
  50706. assert( nExtra>=8 && nExtra<1000 );
  50707. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  50708. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  50709. }
  50710. /* If an error occurred above, free the Pager structure and close the file.
  50711. */
  50712. if( rc!=SQLITE_OK ){
  50713. sqlite3OsClose(pPager->fd);
  50714. sqlite3PageFree(pPager->pTmpSpace);
  50715. sqlite3_free(pPager);
  50716. return rc;
  50717. }
  50718. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  50719. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  50720. pPager->useJournal = (u8)useJournal;
  50721. /* pPager->stmtOpen = 0; */
  50722. /* pPager->stmtInUse = 0; */
  50723. /* pPager->nRef = 0; */
  50724. /* pPager->stmtSize = 0; */
  50725. /* pPager->stmtJSize = 0; */
  50726. /* pPager->nPage = 0; */
  50727. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  50728. /* pPager->state = PAGER_UNLOCK; */
  50729. /* pPager->errMask = 0; */
  50730. pPager->tempFile = (u8)tempFile;
  50731. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  50732. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  50733. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  50734. pPager->exclusiveMode = (u8)tempFile;
  50735. pPager->changeCountDone = pPager->tempFile;
  50736. pPager->memDb = (u8)memDb;
  50737. pPager->readOnly = (u8)readOnly;
  50738. assert( useJournal || pPager->tempFile );
  50739. pPager->noSync = pPager->tempFile;
  50740. if( pPager->noSync ){
  50741. assert( pPager->fullSync==0 );
  50742. assert( pPager->extraSync==0 );
  50743. assert( pPager->syncFlags==0 );
  50744. assert( pPager->walSyncFlags==0 );
  50745. }else{
  50746. pPager->fullSync = 1;
  50747. pPager->extraSync = 0;
  50748. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  50749. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
  50750. }
  50751. /* pPager->pFirst = 0; */
  50752. /* pPager->pFirstSynced = 0; */
  50753. /* pPager->pLast = 0; */
  50754. pPager->nExtra = (u16)nExtra;
  50755. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  50756. assert( isOpen(pPager->fd) || tempFile );
  50757. setSectorSize(pPager);
  50758. if( !useJournal ){
  50759. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  50760. }else if( memDb || memJM ){
  50761. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  50762. }
  50763. /* pPager->xBusyHandler = 0; */
  50764. /* pPager->pBusyHandlerArg = 0; */
  50765. pPager->xReiniter = xReinit;
  50766. setGetterMethod(pPager);
  50767. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  50768. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  50769. *ppPager = pPager;
  50770. return SQLITE_OK;
  50771. }
  50772. /*
  50773. ** This function is called after transitioning from PAGER_UNLOCK to
  50774. ** PAGER_SHARED state. It tests if there is a hot journal present in
  50775. ** the file-system for the given pager. A hot journal is one that
  50776. ** needs to be played back. According to this function, a hot-journal
  50777. ** file exists if the following criteria are met:
  50778. **
  50779. ** * The journal file exists in the file system, and
  50780. ** * No process holds a RESERVED or greater lock on the database file, and
  50781. ** * The database file itself is greater than 0 bytes in size, and
  50782. ** * The first byte of the journal file exists and is not 0x00.
  50783. **
  50784. ** If the current size of the database file is 0 but a journal file
  50785. ** exists, that is probably an old journal left over from a prior
  50786. ** database with the same name. In this case the journal file is
  50787. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  50788. ** is returned.
  50789. **
  50790. ** This routine does not check if there is a master journal filename
  50791. ** at the end of the file. If there is, and that master journal file
  50792. ** does not exist, then the journal file is not really hot. In this
  50793. ** case this routine will return a false-positive. The pager_playback()
  50794. ** routine will discover that the journal file is not really hot and
  50795. ** will not roll it back.
  50796. **
  50797. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  50798. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  50799. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  50800. ** to determine whether or not a hot-journal file exists, the IO error
  50801. ** code is returned and the value of *pExists is undefined.
  50802. */
  50803. static int hasHotJournal(Pager *pPager, int *pExists){
  50804. sqlite3_vfs * const pVfs = pPager->pVfs;
  50805. int rc = SQLITE_OK; /* Return code */
  50806. int exists = 1; /* True if a journal file is present */
  50807. int jrnlOpen = !!isOpen(pPager->jfd);
  50808. assert( pPager->useJournal );
  50809. assert( isOpen(pPager->fd) );
  50810. assert( pPager->eState==PAGER_OPEN );
  50811. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  50812. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  50813. ));
  50814. *pExists = 0;
  50815. if( !jrnlOpen ){
  50816. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  50817. }
  50818. if( rc==SQLITE_OK && exists ){
  50819. int locked = 0; /* True if some process holds a RESERVED lock */
  50820. /* Race condition here: Another process might have been holding the
  50821. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  50822. ** call above, but then delete the journal and drop the lock before
  50823. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  50824. ** is the case, this routine might think there is a hot journal when
  50825. ** in fact there is none. This results in a false-positive which will
  50826. ** be dealt with by the playback routine. Ticket #3883.
  50827. */
  50828. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  50829. if( rc==SQLITE_OK && !locked ){
  50830. Pgno nPage; /* Number of pages in database file */
  50831. assert( pPager->tempFile==0 );
  50832. rc = pagerPagecount(pPager, &nPage);
  50833. if( rc==SQLITE_OK ){
  50834. /* If the database is zero pages in size, that means that either (1) the
  50835. ** journal is a remnant from a prior database with the same name where
  50836. ** the database file but not the journal was deleted, or (2) the initial
  50837. ** transaction that populates a new database is being rolled back.
  50838. ** In either case, the journal file can be deleted. However, take care
  50839. ** not to delete the journal file if it is already open due to
  50840. ** journal_mode=PERSIST.
  50841. */
  50842. if( nPage==0 && !jrnlOpen ){
  50843. sqlite3BeginBenignMalloc();
  50844. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  50845. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  50846. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  50847. }
  50848. sqlite3EndBenignMalloc();
  50849. }else{
  50850. /* The journal file exists and no other connection has a reserved
  50851. ** or greater lock on the database file. Now check that there is
  50852. ** at least one non-zero bytes at the start of the journal file.
  50853. ** If there is, then we consider this journal to be hot. If not,
  50854. ** it can be ignored.
  50855. */
  50856. if( !jrnlOpen ){
  50857. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  50858. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  50859. }
  50860. if( rc==SQLITE_OK ){
  50861. u8 first = 0;
  50862. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  50863. if( rc==SQLITE_IOERR_SHORT_READ ){
  50864. rc = SQLITE_OK;
  50865. }
  50866. if( !jrnlOpen ){
  50867. sqlite3OsClose(pPager->jfd);
  50868. }
  50869. *pExists = (first!=0);
  50870. }else if( rc==SQLITE_CANTOPEN ){
  50871. /* If we cannot open the rollback journal file in order to see if
  50872. ** it has a zero header, that might be due to an I/O error, or
  50873. ** it might be due to the race condition described above and in
  50874. ** ticket #3883. Either way, assume that the journal is hot.
  50875. ** This might be a false positive. But if it is, then the
  50876. ** automatic journal playback and recovery mechanism will deal
  50877. ** with it under an EXCLUSIVE lock where we do not need to
  50878. ** worry so much with race conditions.
  50879. */
  50880. *pExists = 1;
  50881. rc = SQLITE_OK;
  50882. }
  50883. }
  50884. }
  50885. }
  50886. }
  50887. return rc;
  50888. }
  50889. /*
  50890. ** This function is called to obtain a shared lock on the database file.
  50891. ** It is illegal to call sqlite3PagerGet() until after this function
  50892. ** has been successfully called. If a shared-lock is already held when
  50893. ** this function is called, it is a no-op.
  50894. **
  50895. ** The following operations are also performed by this function.
  50896. **
  50897. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  50898. ** on the database file), then an attempt is made to obtain a
  50899. ** SHARED lock on the database file. Immediately after obtaining
  50900. ** the SHARED lock, the file-system is checked for a hot-journal,
  50901. ** which is played back if present. Following any hot-journal
  50902. ** rollback, the contents of the cache are validated by checking
  50903. ** the 'change-counter' field of the database file header and
  50904. ** discarded if they are found to be invalid.
  50905. **
  50906. ** 2) If the pager is running in exclusive-mode, and there are currently
  50907. ** no outstanding references to any pages, and is in the error state,
  50908. ** then an attempt is made to clear the error state by discarding
  50909. ** the contents of the page cache and rolling back any open journal
  50910. ** file.
  50911. **
  50912. ** If everything is successful, SQLITE_OK is returned. If an IO error
  50913. ** occurs while locking the database, checking for a hot-journal file or
  50914. ** rolling back a journal file, the IO error code is returned.
  50915. */
  50916. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  50917. int rc = SQLITE_OK; /* Return code */
  50918. /* This routine is only called from b-tree and only when there are no
  50919. ** outstanding pages. This implies that the pager state should either
  50920. ** be OPEN or READER. READER is only possible if the pager is or was in
  50921. ** exclusive access mode. */
  50922. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  50923. assert( assert_pager_state(pPager) );
  50924. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  50925. assert( pPager->errCode==SQLITE_OK );
  50926. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  50927. int bHotJournal = 1; /* True if there exists a hot journal-file */
  50928. assert( !MEMDB );
  50929. assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
  50930. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  50931. if( rc!=SQLITE_OK ){
  50932. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  50933. goto failed;
  50934. }
  50935. /* If a journal file exists, and there is no RESERVED lock on the
  50936. ** database file, then it either needs to be played back or deleted.
  50937. */
  50938. if( pPager->eLock<=SHARED_LOCK ){
  50939. rc = hasHotJournal(pPager, &bHotJournal);
  50940. }
  50941. if( rc!=SQLITE_OK ){
  50942. goto failed;
  50943. }
  50944. if( bHotJournal ){
  50945. if( pPager->readOnly ){
  50946. rc = SQLITE_READONLY_ROLLBACK;
  50947. goto failed;
  50948. }
  50949. /* Get an EXCLUSIVE lock on the database file. At this point it is
  50950. ** important that a RESERVED lock is not obtained on the way to the
  50951. ** EXCLUSIVE lock. If it were, another process might open the
  50952. ** database file, detect the RESERVED lock, and conclude that the
  50953. ** database is safe to read while this process is still rolling the
  50954. ** hot-journal back.
  50955. **
  50956. ** Because the intermediate RESERVED lock is not requested, any
  50957. ** other process attempting to access the database file will get to
  50958. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  50959. ** on the database file.
  50960. **
  50961. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  50962. ** downgraded to SHARED_LOCK before this function returns.
  50963. */
  50964. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  50965. if( rc!=SQLITE_OK ){
  50966. goto failed;
  50967. }
  50968. /* If it is not already open and the file exists on disk, open the
  50969. ** journal for read/write access. Write access is required because
  50970. ** in exclusive-access mode the file descriptor will be kept open
  50971. ** and possibly used for a transaction later on. Also, write-access
  50972. ** is usually required to finalize the journal in journal_mode=persist
  50973. ** mode (and also for journal_mode=truncate on some systems).
  50974. **
  50975. ** If the journal does not exist, it usually means that some
  50976. ** other connection managed to get in and roll it back before
  50977. ** this connection obtained the exclusive lock above. Or, it
  50978. ** may mean that the pager was in the error-state when this
  50979. ** function was called and the journal file does not exist.
  50980. */
  50981. if( !isOpen(pPager->jfd) ){
  50982. sqlite3_vfs * const pVfs = pPager->pVfs;
  50983. int bExists; /* True if journal file exists */
  50984. rc = sqlite3OsAccess(
  50985. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  50986. if( rc==SQLITE_OK && bExists ){
  50987. int fout = 0;
  50988. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  50989. assert( !pPager->tempFile );
  50990. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  50991. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  50992. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  50993. rc = SQLITE_CANTOPEN_BKPT;
  50994. sqlite3OsClose(pPager->jfd);
  50995. }
  50996. }
  50997. }
  50998. /* Playback and delete the journal. Drop the database write
  50999. ** lock and reacquire the read lock. Purge the cache before
  51000. ** playing back the hot-journal so that we don't end up with
  51001. ** an inconsistent cache. Sync the hot journal before playing
  51002. ** it back since the process that crashed and left the hot journal
  51003. ** probably did not sync it and we are required to always sync
  51004. ** the journal before playing it back.
  51005. */
  51006. if( isOpen(pPager->jfd) ){
  51007. assert( rc==SQLITE_OK );
  51008. rc = pagerSyncHotJournal(pPager);
  51009. if( rc==SQLITE_OK ){
  51010. rc = pager_playback(pPager, !pPager->tempFile);
  51011. pPager->eState = PAGER_OPEN;
  51012. }
  51013. }else if( !pPager->exclusiveMode ){
  51014. pagerUnlockDb(pPager, SHARED_LOCK);
  51015. }
  51016. if( rc!=SQLITE_OK ){
  51017. /* This branch is taken if an error occurs while trying to open
  51018. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  51019. ** pager_unlock() routine will be called before returning to unlock
  51020. ** the file. If the unlock attempt fails, then Pager.eLock must be
  51021. ** set to UNKNOWN_LOCK (see the comment above the #define for
  51022. ** UNKNOWN_LOCK above for an explanation).
  51023. **
  51024. ** In order to get pager_unlock() to do this, set Pager.eState to
  51025. ** PAGER_ERROR now. This is not actually counted as a transition
  51026. ** to ERROR state in the state diagram at the top of this file,
  51027. ** since we know that the same call to pager_unlock() will very
  51028. ** shortly transition the pager object to the OPEN state. Calling
  51029. ** assert_pager_state() would fail now, as it should not be possible
  51030. ** to be in ERROR state when there are zero outstanding page
  51031. ** references.
  51032. */
  51033. pager_error(pPager, rc);
  51034. goto failed;
  51035. }
  51036. assert( pPager->eState==PAGER_OPEN );
  51037. assert( (pPager->eLock==SHARED_LOCK)
  51038. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  51039. );
  51040. }
  51041. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  51042. /* The shared-lock has just been acquired then check to
  51043. ** see if the database has been modified. If the database has changed,
  51044. ** flush the cache. The hasHeldSharedLock flag prevents this from
  51045. ** occurring on the very first access to a file, in order to save a
  51046. ** single unnecessary sqlite3OsRead() call at the start-up.
  51047. **
  51048. ** Database changes are detected by looking at 15 bytes beginning
  51049. ** at offset 24 into the file. The first 4 of these 16 bytes are
  51050. ** a 32-bit counter that is incremented with each change. The
  51051. ** other bytes change randomly with each file change when
  51052. ** a codec is in use.
  51053. **
  51054. ** There is a vanishingly small chance that a change will not be
  51055. ** detected. The chance of an undetected change is so small that
  51056. ** it can be neglected.
  51057. */
  51058. char dbFileVers[sizeof(pPager->dbFileVers)];
  51059. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  51060. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  51061. if( rc!=SQLITE_OK ){
  51062. if( rc!=SQLITE_IOERR_SHORT_READ ){
  51063. goto failed;
  51064. }
  51065. memset(dbFileVers, 0, sizeof(dbFileVers));
  51066. }
  51067. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  51068. pager_reset(pPager);
  51069. /* Unmap the database file. It is possible that external processes
  51070. ** may have truncated the database file and then extended it back
  51071. ** to its original size while this process was not holding a lock.
  51072. ** In this case there may exist a Pager.pMap mapping that appears
  51073. ** to be the right size but is not actually valid. Avoid this
  51074. ** possibility by unmapping the db here. */
  51075. if( USEFETCH(pPager) ){
  51076. sqlite3OsUnfetch(pPager->fd, 0, 0);
  51077. }
  51078. }
  51079. }
  51080. /* If there is a WAL file in the file-system, open this database in WAL
  51081. ** mode. Otherwise, the following function call is a no-op.
  51082. */
  51083. rc = pagerOpenWalIfPresent(pPager);
  51084. #ifndef SQLITE_OMIT_WAL
  51085. assert( pPager->pWal==0 || rc==SQLITE_OK );
  51086. #endif
  51087. }
  51088. if( pagerUseWal(pPager) ){
  51089. assert( rc==SQLITE_OK );
  51090. rc = pagerBeginReadTransaction(pPager);
  51091. }
  51092. if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  51093. rc = pagerPagecount(pPager, &pPager->dbSize);
  51094. }
  51095. failed:
  51096. if( rc!=SQLITE_OK ){
  51097. assert( !MEMDB );
  51098. pager_unlock(pPager);
  51099. assert( pPager->eState==PAGER_OPEN );
  51100. }else{
  51101. pPager->eState = PAGER_READER;
  51102. pPager->hasHeldSharedLock = 1;
  51103. }
  51104. return rc;
  51105. }
  51106. /*
  51107. ** If the reference count has reached zero, rollback any active
  51108. ** transaction and unlock the pager.
  51109. **
  51110. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  51111. ** the rollback journal, the unlock is not performed and there is
  51112. ** nothing to rollback, so this routine is a no-op.
  51113. */
  51114. static void pagerUnlockIfUnused(Pager *pPager){
  51115. if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
  51116. assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
  51117. pagerUnlockAndRollback(pPager);
  51118. }
  51119. }
  51120. /*
  51121. ** The page getter methods each try to acquire a reference to a
  51122. ** page with page number pgno. If the requested reference is
  51123. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  51124. **
  51125. ** There are different implementations of the getter method depending
  51126. ** on the current state of the pager.
  51127. **
  51128. ** getPageNormal() -- The normal getter
  51129. ** getPageError() -- Used if the pager is in an error state
  51130. ** getPageMmap() -- Used if memory-mapped I/O is enabled
  51131. **
  51132. ** If the requested page is already in the cache, it is returned.
  51133. ** Otherwise, a new page object is allocated and populated with data
  51134. ** read from the database file. In some cases, the pcache module may
  51135. ** choose not to allocate a new page object and may reuse an existing
  51136. ** object with no outstanding references.
  51137. **
  51138. ** The extra data appended to a page is always initialized to zeros the
  51139. ** first time a page is loaded into memory. If the page requested is
  51140. ** already in the cache when this function is called, then the extra
  51141. ** data is left as it was when the page object was last used.
  51142. **
  51143. ** If the database image is smaller than the requested page or if
  51144. ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
  51145. ** requested page is not already stored in the cache, then no
  51146. ** actual disk read occurs. In this case the memory image of the
  51147. ** page is initialized to all zeros.
  51148. **
  51149. ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
  51150. ** the contents of the page. This occurs in two scenarios:
  51151. **
  51152. ** a) When reading a free-list leaf page from the database, and
  51153. **
  51154. ** b) When a savepoint is being rolled back and we need to load
  51155. ** a new page into the cache to be filled with the data read
  51156. ** from the savepoint journal.
  51157. **
  51158. ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
  51159. ** of being read from the database. Additionally, the bits corresponding
  51160. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  51161. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  51162. ** savepoints are set. This means if the page is made writable at any
  51163. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  51164. ** will not be journaled. This saves IO.
  51165. **
  51166. ** The acquisition might fail for several reasons. In all cases,
  51167. ** an appropriate error code is returned and *ppPage is set to NULL.
  51168. **
  51169. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  51170. ** to find a page in the in-memory cache first. If the page is not already
  51171. ** in memory, this routine goes to disk to read it in whereas Lookup()
  51172. ** just returns 0. This routine acquires a read-lock the first time it
  51173. ** has to go to disk, and could also playback an old journal if necessary.
  51174. ** Since Lookup() never goes to disk, it never has to deal with locks
  51175. ** or journal files.
  51176. */
  51177. static int getPageNormal(
  51178. Pager *pPager, /* The pager open on the database file */
  51179. Pgno pgno, /* Page number to fetch */
  51180. DbPage **ppPage, /* Write a pointer to the page here */
  51181. int flags /* PAGER_GET_XXX flags */
  51182. ){
  51183. int rc = SQLITE_OK;
  51184. PgHdr *pPg;
  51185. u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
  51186. sqlite3_pcache_page *pBase;
  51187. assert( pPager->errCode==SQLITE_OK );
  51188. assert( pPager->eState>=PAGER_READER );
  51189. assert( assert_pager_state(pPager) );
  51190. assert( pPager->hasHeldSharedLock==1 );
  51191. if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
  51192. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  51193. if( pBase==0 ){
  51194. pPg = 0;
  51195. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  51196. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  51197. if( pBase==0 ){
  51198. rc = SQLITE_NOMEM_BKPT;
  51199. goto pager_acquire_err;
  51200. }
  51201. }
  51202. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  51203. assert( pPg==(*ppPage) );
  51204. assert( pPg->pgno==pgno );
  51205. assert( pPg->pPager==pPager || pPg->pPager==0 );
  51206. noContent = (flags & PAGER_GET_NOCONTENT)!=0;
  51207. if( pPg->pPager && !noContent ){
  51208. /* In this case the pcache already contains an initialized copy of
  51209. ** the page. Return without further ado. */
  51210. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  51211. pPager->aStat[PAGER_STAT_HIT]++;
  51212. return SQLITE_OK;
  51213. }else{
  51214. /* The pager cache has created a new page. Its content needs to
  51215. ** be initialized. But first some error checks:
  51216. **
  51217. ** (1) The maximum page number is 2^31
  51218. ** (2) Never try to fetch the locking page
  51219. */
  51220. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  51221. rc = SQLITE_CORRUPT_BKPT;
  51222. goto pager_acquire_err;
  51223. }
  51224. pPg->pPager = pPager;
  51225. assert( !isOpen(pPager->fd) || !MEMDB );
  51226. if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
  51227. if( pgno>pPager->mxPgno ){
  51228. rc = SQLITE_FULL;
  51229. goto pager_acquire_err;
  51230. }
  51231. if( noContent ){
  51232. /* Failure to set the bits in the InJournal bit-vectors is benign.
  51233. ** It merely means that we might do some extra work to journal a
  51234. ** page that does not need to be journaled. Nevertheless, be sure
  51235. ** to test the case where a malloc error occurs while trying to set
  51236. ** a bit in a bit vector.
  51237. */
  51238. sqlite3BeginBenignMalloc();
  51239. if( pgno<=pPager->dbOrigSize ){
  51240. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  51241. testcase( rc==SQLITE_NOMEM );
  51242. }
  51243. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  51244. testcase( rc==SQLITE_NOMEM );
  51245. sqlite3EndBenignMalloc();
  51246. }
  51247. memset(pPg->pData, 0, pPager->pageSize);
  51248. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  51249. }else{
  51250. assert( pPg->pPager==pPager );
  51251. pPager->aStat[PAGER_STAT_MISS]++;
  51252. rc = readDbPage(pPg);
  51253. if( rc!=SQLITE_OK ){
  51254. goto pager_acquire_err;
  51255. }
  51256. }
  51257. pager_set_pagehash(pPg);
  51258. }
  51259. return SQLITE_OK;
  51260. pager_acquire_err:
  51261. assert( rc!=SQLITE_OK );
  51262. if( pPg ){
  51263. sqlite3PcacheDrop(pPg);
  51264. }
  51265. pagerUnlockIfUnused(pPager);
  51266. *ppPage = 0;
  51267. return rc;
  51268. }
  51269. #if SQLITE_MAX_MMAP_SIZE>0
  51270. /* The page getter for when memory-mapped I/O is enabled */
  51271. static int getPageMMap(
  51272. Pager *pPager, /* The pager open on the database file */
  51273. Pgno pgno, /* Page number to fetch */
  51274. DbPage **ppPage, /* Write a pointer to the page here */
  51275. int flags /* PAGER_GET_XXX flags */
  51276. ){
  51277. int rc = SQLITE_OK;
  51278. PgHdr *pPg = 0;
  51279. u32 iFrame = 0; /* Frame to read from WAL file */
  51280. /* It is acceptable to use a read-only (mmap) page for any page except
  51281. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  51282. ** flag was specified by the caller. And so long as the db is not a
  51283. ** temporary or in-memory database. */
  51284. const int bMmapOk = (pgno>1
  51285. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  51286. );
  51287. assert( USEFETCH(pPager) );
  51288. #ifdef SQLITE_HAS_CODEC
  51289. assert( pPager->xCodec==0 );
  51290. #endif
  51291. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  51292. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  51293. ** test in the previous statement, and avoid testing pgno==0 in the
  51294. ** common case where pgno is large. */
  51295. if( pgno<=1 && pgno==0 ){
  51296. return SQLITE_CORRUPT_BKPT;
  51297. }
  51298. assert( pPager->eState>=PAGER_READER );
  51299. assert( assert_pager_state(pPager) );
  51300. assert( pPager->hasHeldSharedLock==1 );
  51301. assert( pPager->errCode==SQLITE_OK );
  51302. if( bMmapOk && pagerUseWal(pPager) ){
  51303. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  51304. if( rc!=SQLITE_OK ){
  51305. *ppPage = 0;
  51306. return rc;
  51307. }
  51308. }
  51309. if( bMmapOk && iFrame==0 ){
  51310. void *pData = 0;
  51311. rc = sqlite3OsFetch(pPager->fd,
  51312. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  51313. );
  51314. if( rc==SQLITE_OK && pData ){
  51315. if( pPager->eState>PAGER_READER || pPager->tempFile ){
  51316. pPg = sqlite3PagerLookup(pPager, pgno);
  51317. }
  51318. if( pPg==0 ){
  51319. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  51320. }else{
  51321. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  51322. }
  51323. if( pPg ){
  51324. assert( rc==SQLITE_OK );
  51325. *ppPage = pPg;
  51326. return SQLITE_OK;
  51327. }
  51328. }
  51329. if( rc!=SQLITE_OK ){
  51330. *ppPage = 0;
  51331. return rc;
  51332. }
  51333. }
  51334. return getPageNormal(pPager, pgno, ppPage, flags);
  51335. }
  51336. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  51337. /* The page getter method for when the pager is an error state */
  51338. static int getPageError(
  51339. Pager *pPager, /* The pager open on the database file */
  51340. Pgno pgno, /* Page number to fetch */
  51341. DbPage **ppPage, /* Write a pointer to the page here */
  51342. int flags /* PAGER_GET_XXX flags */
  51343. ){
  51344. UNUSED_PARAMETER(pgno);
  51345. UNUSED_PARAMETER(flags);
  51346. assert( pPager->errCode!=SQLITE_OK );
  51347. *ppPage = 0;
  51348. return pPager->errCode;
  51349. }
  51350. /* Dispatch all page fetch requests to the appropriate getter method.
  51351. */
  51352. SQLITE_PRIVATE int sqlite3PagerGet(
  51353. Pager *pPager, /* The pager open on the database file */
  51354. Pgno pgno, /* Page number to fetch */
  51355. DbPage **ppPage, /* Write a pointer to the page here */
  51356. int flags /* PAGER_GET_XXX flags */
  51357. ){
  51358. return pPager->xGet(pPager, pgno, ppPage, flags);
  51359. }
  51360. /*
  51361. ** Acquire a page if it is already in the in-memory cache. Do
  51362. ** not read the page from disk. Return a pointer to the page,
  51363. ** or 0 if the page is not in cache.
  51364. **
  51365. ** See also sqlite3PagerGet(). The difference between this routine
  51366. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  51367. ** in the page if the page is not already in cache. This routine
  51368. ** returns NULL if the page is not in cache or if a disk I/O error
  51369. ** has ever happened.
  51370. */
  51371. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  51372. sqlite3_pcache_page *pPage;
  51373. assert( pPager!=0 );
  51374. assert( pgno!=0 );
  51375. assert( pPager->pPCache!=0 );
  51376. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  51377. assert( pPage==0 || pPager->hasHeldSharedLock );
  51378. if( pPage==0 ) return 0;
  51379. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  51380. }
  51381. /*
  51382. ** Release a page reference.
  51383. **
  51384. ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
  51385. ** used if we know that the page being released is not the last page.
  51386. ** The btree layer always holds page1 open until the end, so these first
  51387. ** to routines can be used to release any page other than BtShared.pPage1.
  51388. **
  51389. ** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine
  51390. ** checks the total number of outstanding pages and if the number of
  51391. ** pages reaches zero it drops the database lock.
  51392. */
  51393. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  51394. TESTONLY( Pager *pPager = pPg->pPager; )
  51395. assert( pPg!=0 );
  51396. if( pPg->flags & PGHDR_MMAP ){
  51397. assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
  51398. pagerReleaseMapPage(pPg);
  51399. }else{
  51400. sqlite3PcacheRelease(pPg);
  51401. }
  51402. /* Do not use this routine to release the last reference to page1 */
  51403. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  51404. }
  51405. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  51406. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  51407. }
  51408. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
  51409. Pager *pPager;
  51410. assert( pPg!=0 );
  51411. assert( pPg->pgno==1 );
  51412. assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
  51413. pPager = pPg->pPager;
  51414. sqlite3PagerResetLockTimeout(pPager);
  51415. sqlite3PcacheRelease(pPg);
  51416. pagerUnlockIfUnused(pPager);
  51417. }
  51418. /*
  51419. ** This function is called at the start of every write transaction.
  51420. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  51421. ** file when this routine is called.
  51422. **
  51423. ** Open the journal file for pager pPager and write a journal header
  51424. ** to the start of it. If there are active savepoints, open the sub-journal
  51425. ** as well. This function is only used when the journal file is being
  51426. ** opened to write a rollback log for a transaction. It is not used
  51427. ** when opening a hot journal file to roll it back.
  51428. **
  51429. ** If the journal file is already open (as it may be in exclusive mode),
  51430. ** then this function just writes a journal header to the start of the
  51431. ** already open file.
  51432. **
  51433. ** Whether or not the journal file is opened by this function, the
  51434. ** Pager.pInJournal bitvec structure is allocated.
  51435. **
  51436. ** Return SQLITE_OK if everything is successful. Otherwise, return
  51437. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  51438. ** an IO error code if opening or writing the journal file fails.
  51439. */
  51440. static int pager_open_journal(Pager *pPager){
  51441. int rc = SQLITE_OK; /* Return code */
  51442. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  51443. assert( pPager->eState==PAGER_WRITER_LOCKED );
  51444. assert( assert_pager_state(pPager) );
  51445. assert( pPager->pInJournal==0 );
  51446. /* If already in the error state, this function is a no-op. But on
  51447. ** the other hand, this routine is never called if we are already in
  51448. ** an error state. */
  51449. if( NEVER(pPager->errCode) ) return pPager->errCode;
  51450. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  51451. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  51452. if( pPager->pInJournal==0 ){
  51453. return SQLITE_NOMEM_BKPT;
  51454. }
  51455. /* Open the journal file if it is not already open. */
  51456. if( !isOpen(pPager->jfd) ){
  51457. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  51458. sqlite3MemJournalOpen(pPager->jfd);
  51459. }else{
  51460. int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  51461. int nSpill;
  51462. if( pPager->tempFile ){
  51463. flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
  51464. nSpill = sqlite3Config.nStmtSpill;
  51465. }else{
  51466. flags |= SQLITE_OPEN_MAIN_JOURNAL;
  51467. nSpill = jrnlBufferSize(pPager);
  51468. }
  51469. /* Verify that the database still has the same name as it did when
  51470. ** it was originally opened. */
  51471. rc = databaseIsUnmoved(pPager);
  51472. if( rc==SQLITE_OK ){
  51473. rc = sqlite3JournalOpen (
  51474. pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
  51475. );
  51476. }
  51477. }
  51478. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  51479. }
  51480. /* Write the first journal header to the journal file and open
  51481. ** the sub-journal if necessary.
  51482. */
  51483. if( rc==SQLITE_OK ){
  51484. /* TODO: Check if all of these are really required. */
  51485. pPager->nRec = 0;
  51486. pPager->journalOff = 0;
  51487. pPager->setMaster = 0;
  51488. pPager->journalHdr = 0;
  51489. rc = writeJournalHdr(pPager);
  51490. }
  51491. }
  51492. if( rc!=SQLITE_OK ){
  51493. sqlite3BitvecDestroy(pPager->pInJournal);
  51494. pPager->pInJournal = 0;
  51495. }else{
  51496. assert( pPager->eState==PAGER_WRITER_LOCKED );
  51497. pPager->eState = PAGER_WRITER_CACHEMOD;
  51498. }
  51499. return rc;
  51500. }
  51501. /*
  51502. ** Begin a write-transaction on the specified pager object. If a
  51503. ** write-transaction has already been opened, this function is a no-op.
  51504. **
  51505. ** If the exFlag argument is false, then acquire at least a RESERVED
  51506. ** lock on the database file. If exFlag is true, then acquire at least
  51507. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  51508. ** functions need be called.
  51509. **
  51510. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  51511. ** within this transaction will be opened as an in-memory file. This
  51512. ** has no effect if the sub-journal is already opened (as it may be when
  51513. ** running in exclusive mode) or if the transaction does not require a
  51514. ** sub-journal. If the subjInMemory argument is zero, then any required
  51515. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  51516. ** or using a temporary file otherwise.
  51517. */
  51518. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  51519. int rc = SQLITE_OK;
  51520. if( pPager->errCode ) return pPager->errCode;
  51521. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  51522. pPager->subjInMemory = (u8)subjInMemory;
  51523. if( ALWAYS(pPager->eState==PAGER_READER) ){
  51524. assert( pPager->pInJournal==0 );
  51525. if( pagerUseWal(pPager) ){
  51526. /* If the pager is configured to use locking_mode=exclusive, and an
  51527. ** exclusive lock on the database is not already held, obtain it now.
  51528. */
  51529. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  51530. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  51531. if( rc!=SQLITE_OK ){
  51532. return rc;
  51533. }
  51534. (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
  51535. }
  51536. /* Grab the write lock on the log file. If successful, upgrade to
  51537. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  51538. ** The busy-handler is not invoked if another connection already
  51539. ** holds the write-lock. If possible, the upper layer will call it.
  51540. */
  51541. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  51542. }else{
  51543. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  51544. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  51545. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  51546. ** lock, but not when obtaining the RESERVED lock.
  51547. */
  51548. rc = pagerLockDb(pPager, RESERVED_LOCK);
  51549. if( rc==SQLITE_OK && exFlag ){
  51550. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  51551. }
  51552. }
  51553. if( rc==SQLITE_OK ){
  51554. /* Change to WRITER_LOCKED state.
  51555. **
  51556. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  51557. ** when it has an open transaction, but never to DBMOD or FINISHED.
  51558. ** This is because in those states the code to roll back savepoint
  51559. ** transactions may copy data from the sub-journal into the database
  51560. ** file as well as into the page cache. Which would be incorrect in
  51561. ** WAL mode.
  51562. */
  51563. pPager->eState = PAGER_WRITER_LOCKED;
  51564. pPager->dbHintSize = pPager->dbSize;
  51565. pPager->dbFileSize = pPager->dbSize;
  51566. pPager->dbOrigSize = pPager->dbSize;
  51567. pPager->journalOff = 0;
  51568. }
  51569. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  51570. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  51571. assert( assert_pager_state(pPager) );
  51572. }
  51573. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  51574. return rc;
  51575. }
  51576. /*
  51577. ** Write page pPg onto the end of the rollback journal.
  51578. */
  51579. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  51580. Pager *pPager = pPg->pPager;
  51581. int rc;
  51582. u32 cksum;
  51583. char *pData2;
  51584. i64 iOff = pPager->journalOff;
  51585. /* We should never write to the journal file the page that
  51586. ** contains the database locks. The following assert verifies
  51587. ** that we do not. */
  51588. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  51589. assert( pPager->journalHdr<=pPager->journalOff );
  51590. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
  51591. cksum = pager_cksum(pPager, (u8*)pData2);
  51592. /* Even if an IO or diskfull error occurs while journalling the
  51593. ** page in the block above, set the need-sync flag for the page.
  51594. ** Otherwise, when the transaction is rolled back, the logic in
  51595. ** playback_one_page() will think that the page needs to be restored
  51596. ** in the database file. And if an IO error occurs while doing so,
  51597. ** then corruption may follow.
  51598. */
  51599. pPg->flags |= PGHDR_NEED_SYNC;
  51600. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  51601. if( rc!=SQLITE_OK ) return rc;
  51602. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  51603. if( rc!=SQLITE_OK ) return rc;
  51604. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  51605. if( rc!=SQLITE_OK ) return rc;
  51606. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  51607. pPager->journalOff, pPager->pageSize));
  51608. PAGER_INCR(sqlite3_pager_writej_count);
  51609. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  51610. PAGERID(pPager), pPg->pgno,
  51611. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  51612. pPager->journalOff += 8 + pPager->pageSize;
  51613. pPager->nRec++;
  51614. assert( pPager->pInJournal!=0 );
  51615. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  51616. testcase( rc==SQLITE_NOMEM );
  51617. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  51618. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  51619. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  51620. return rc;
  51621. }
  51622. /*
  51623. ** Mark a single data page as writeable. The page is written into the
  51624. ** main journal or sub-journal as required. If the page is written into
  51625. ** one of the journals, the corresponding bit is set in the
  51626. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  51627. ** of any open savepoints as appropriate.
  51628. */
  51629. static int pager_write(PgHdr *pPg){
  51630. Pager *pPager = pPg->pPager;
  51631. int rc = SQLITE_OK;
  51632. /* This routine is not called unless a write-transaction has already
  51633. ** been started. The journal file may or may not be open at this point.
  51634. ** It is never called in the ERROR state.
  51635. */
  51636. assert( pPager->eState==PAGER_WRITER_LOCKED
  51637. || pPager->eState==PAGER_WRITER_CACHEMOD
  51638. || pPager->eState==PAGER_WRITER_DBMOD
  51639. );
  51640. assert( assert_pager_state(pPager) );
  51641. assert( pPager->errCode==0 );
  51642. assert( pPager->readOnly==0 );
  51643. CHECK_PAGE(pPg);
  51644. /* The journal file needs to be opened. Higher level routines have already
  51645. ** obtained the necessary locks to begin the write-transaction, but the
  51646. ** rollback journal might not yet be open. Open it now if this is the case.
  51647. **
  51648. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  51649. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  51650. ** an error might occur and the pager would end up in WRITER_LOCKED state
  51651. ** with pages marked as dirty in the cache.
  51652. */
  51653. if( pPager->eState==PAGER_WRITER_LOCKED ){
  51654. rc = pager_open_journal(pPager);
  51655. if( rc!=SQLITE_OK ) return rc;
  51656. }
  51657. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  51658. assert( assert_pager_state(pPager) );
  51659. /* Mark the page that is about to be modified as dirty. */
  51660. sqlite3PcacheMakeDirty(pPg);
  51661. /* If a rollback journal is in use, them make sure the page that is about
  51662. ** to change is in the rollback journal, or if the page is a new page off
  51663. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  51664. */
  51665. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  51666. if( pPager->pInJournal!=0
  51667. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  51668. ){
  51669. assert( pagerUseWal(pPager)==0 );
  51670. if( pPg->pgno<=pPager->dbOrigSize ){
  51671. rc = pagerAddPageToRollbackJournal(pPg);
  51672. if( rc!=SQLITE_OK ){
  51673. return rc;
  51674. }
  51675. }else{
  51676. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  51677. pPg->flags |= PGHDR_NEED_SYNC;
  51678. }
  51679. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  51680. PAGERID(pPager), pPg->pgno,
  51681. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  51682. }
  51683. }
  51684. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  51685. ** and before writing the page into the rollback journal. Wait until now,
  51686. ** after the page has been successfully journalled, before setting the
  51687. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  51688. */
  51689. pPg->flags |= PGHDR_WRITEABLE;
  51690. /* If the statement journal is open and the page is not in it,
  51691. ** then write the page into the statement journal.
  51692. */
  51693. if( pPager->nSavepoint>0 ){
  51694. rc = subjournalPageIfRequired(pPg);
  51695. }
  51696. /* Update the database size and return. */
  51697. if( pPager->dbSize<pPg->pgno ){
  51698. pPager->dbSize = pPg->pgno;
  51699. }
  51700. return rc;
  51701. }
  51702. /*
  51703. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  51704. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  51705. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  51706. ** a sector need to be journalled in case of a power loss in the middle of
  51707. ** a write.
  51708. **
  51709. ** Usually, the sector size is less than or equal to the page size, in which
  51710. ** case pages can be individually written. This routine only runs in the
  51711. ** exceptional case where the page size is smaller than the sector size.
  51712. */
  51713. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  51714. int rc = SQLITE_OK; /* Return code */
  51715. Pgno nPageCount; /* Total number of pages in database file */
  51716. Pgno pg1; /* First page of the sector pPg is located on. */
  51717. int nPage = 0; /* Number of pages starting at pg1 to journal */
  51718. int ii; /* Loop counter */
  51719. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  51720. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  51721. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  51722. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  51723. ** a journal header to be written between the pages journaled by
  51724. ** this function.
  51725. */
  51726. assert( !MEMDB );
  51727. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  51728. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  51729. /* This trick assumes that both the page-size and sector-size are
  51730. ** an integer power of 2. It sets variable pg1 to the identifier
  51731. ** of the first page of the sector pPg is located on.
  51732. */
  51733. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  51734. nPageCount = pPager->dbSize;
  51735. if( pPg->pgno>nPageCount ){
  51736. nPage = (pPg->pgno - pg1)+1;
  51737. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  51738. nPage = nPageCount+1-pg1;
  51739. }else{
  51740. nPage = nPagePerSector;
  51741. }
  51742. assert(nPage>0);
  51743. assert(pg1<=pPg->pgno);
  51744. assert((pg1+nPage)>pPg->pgno);
  51745. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  51746. Pgno pg = pg1+ii;
  51747. PgHdr *pPage;
  51748. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  51749. if( pg!=PAGER_MJ_PGNO(pPager) ){
  51750. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  51751. if( rc==SQLITE_OK ){
  51752. rc = pager_write(pPage);
  51753. if( pPage->flags&PGHDR_NEED_SYNC ){
  51754. needSync = 1;
  51755. }
  51756. sqlite3PagerUnrefNotNull(pPage);
  51757. }
  51758. }
  51759. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  51760. if( pPage->flags&PGHDR_NEED_SYNC ){
  51761. needSync = 1;
  51762. }
  51763. sqlite3PagerUnrefNotNull(pPage);
  51764. }
  51765. }
  51766. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  51767. ** starting at pg1, then it needs to be set for all of them. Because
  51768. ** writing to any of these nPage pages may damage the others, the
  51769. ** journal file must contain sync()ed copies of all of them
  51770. ** before any of them can be written out to the database file.
  51771. */
  51772. if( rc==SQLITE_OK && needSync ){
  51773. assert( !MEMDB );
  51774. for(ii=0; ii<nPage; ii++){
  51775. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  51776. if( pPage ){
  51777. pPage->flags |= PGHDR_NEED_SYNC;
  51778. sqlite3PagerUnrefNotNull(pPage);
  51779. }
  51780. }
  51781. }
  51782. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  51783. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  51784. return rc;
  51785. }
  51786. /*
  51787. ** Mark a data page as writeable. This routine must be called before
  51788. ** making changes to a page. The caller must check the return value
  51789. ** of this function and be careful not to change any page data unless
  51790. ** this routine returns SQLITE_OK.
  51791. **
  51792. ** The difference between this function and pager_write() is that this
  51793. ** function also deals with the special case where 2 or more pages
  51794. ** fit on a single disk sector. In this case all co-resident pages
  51795. ** must have been written to the journal file before returning.
  51796. **
  51797. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  51798. ** as appropriate. Otherwise, SQLITE_OK.
  51799. */
  51800. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  51801. Pager *pPager = pPg->pPager;
  51802. assert( (pPg->flags & PGHDR_MMAP)==0 );
  51803. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  51804. assert( assert_pager_state(pPager) );
  51805. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  51806. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  51807. return SQLITE_OK;
  51808. }else if( pPager->errCode ){
  51809. return pPager->errCode;
  51810. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  51811. assert( pPager->tempFile==0 );
  51812. return pagerWriteLargeSector(pPg);
  51813. }else{
  51814. return pager_write(pPg);
  51815. }
  51816. }
  51817. /*
  51818. ** Return TRUE if the page given in the argument was previously passed
  51819. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  51820. ** to change the content of the page.
  51821. */
  51822. #ifndef NDEBUG
  51823. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  51824. return pPg->flags & PGHDR_WRITEABLE;
  51825. }
  51826. #endif
  51827. /*
  51828. ** A call to this routine tells the pager that it is not necessary to
  51829. ** write the information on page pPg back to the disk, even though
  51830. ** that page might be marked as dirty. This happens, for example, when
  51831. ** the page has been added as a leaf of the freelist and so its
  51832. ** content no longer matters.
  51833. **
  51834. ** The overlying software layer calls this routine when all of the data
  51835. ** on the given page is unused. The pager marks the page as clean so
  51836. ** that it does not get written to disk.
  51837. **
  51838. ** Tests show that this optimization can quadruple the speed of large
  51839. ** DELETE operations.
  51840. **
  51841. ** This optimization cannot be used with a temp-file, as the page may
  51842. ** have been dirty at the start of the transaction. In that case, if
  51843. ** memory pressure forces page pPg out of the cache, the data does need
  51844. ** to be written out to disk so that it may be read back in if the
  51845. ** current transaction is rolled back.
  51846. */
  51847. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  51848. Pager *pPager = pPg->pPager;
  51849. if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  51850. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  51851. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  51852. pPg->flags |= PGHDR_DONT_WRITE;
  51853. pPg->flags &= ~PGHDR_WRITEABLE;
  51854. testcase( pPg->flags & PGHDR_NEED_SYNC );
  51855. pager_set_pagehash(pPg);
  51856. }
  51857. }
  51858. /*
  51859. ** This routine is called to increment the value of the database file
  51860. ** change-counter, stored as a 4-byte big-endian integer starting at
  51861. ** byte offset 24 of the pager file. The secondary change counter at
  51862. ** 92 is also updated, as is the SQLite version number at offset 96.
  51863. **
  51864. ** But this only happens if the pPager->changeCountDone flag is false.
  51865. ** To avoid excess churning of page 1, the update only happens once.
  51866. ** See also the pager_write_changecounter() routine that does an
  51867. ** unconditional update of the change counters.
  51868. **
  51869. ** If the isDirectMode flag is zero, then this is done by calling
  51870. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  51871. ** page data. In this case the file will be updated when the current
  51872. ** transaction is committed.
  51873. **
  51874. ** The isDirectMode flag may only be non-zero if the library was compiled
  51875. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  51876. ** if isDirect is non-zero, then the database file is updated directly
  51877. ** by writing an updated version of page 1 using a call to the
  51878. ** sqlite3OsWrite() function.
  51879. */
  51880. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  51881. int rc = SQLITE_OK;
  51882. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  51883. || pPager->eState==PAGER_WRITER_DBMOD
  51884. );
  51885. assert( assert_pager_state(pPager) );
  51886. /* Declare and initialize constant integer 'isDirect'. If the
  51887. ** atomic-write optimization is enabled in this build, then isDirect
  51888. ** is initialized to the value passed as the isDirectMode parameter
  51889. ** to this function. Otherwise, it is always set to zero.
  51890. **
  51891. ** The idea is that if the atomic-write optimization is not
  51892. ** enabled at compile time, the compiler can omit the tests of
  51893. ** 'isDirect' below, as well as the block enclosed in the
  51894. ** "if( isDirect )" condition.
  51895. */
  51896. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  51897. # define DIRECT_MODE 0
  51898. assert( isDirectMode==0 );
  51899. UNUSED_PARAMETER(isDirectMode);
  51900. #else
  51901. # define DIRECT_MODE isDirectMode
  51902. #endif
  51903. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  51904. PgHdr *pPgHdr; /* Reference to page 1 */
  51905. assert( !pPager->tempFile && isOpen(pPager->fd) );
  51906. /* Open page 1 of the file for writing. */
  51907. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  51908. assert( pPgHdr==0 || rc==SQLITE_OK );
  51909. /* If page one was fetched successfully, and this function is not
  51910. ** operating in direct-mode, make page 1 writable. When not in
  51911. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  51912. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  51913. */
  51914. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  51915. rc = sqlite3PagerWrite(pPgHdr);
  51916. }
  51917. if( rc==SQLITE_OK ){
  51918. /* Actually do the update of the change counter */
  51919. pager_write_changecounter(pPgHdr);
  51920. /* If running in direct mode, write the contents of page 1 to the file. */
  51921. if( DIRECT_MODE ){
  51922. const void *zBuf;
  51923. assert( pPager->dbFileSize>0 );
  51924. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
  51925. if( rc==SQLITE_OK ){
  51926. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  51927. pPager->aStat[PAGER_STAT_WRITE]++;
  51928. }
  51929. if( rc==SQLITE_OK ){
  51930. /* Update the pager's copy of the change-counter. Otherwise, the
  51931. ** next time a read transaction is opened the cache will be
  51932. ** flushed (as the change-counter values will not match). */
  51933. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  51934. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  51935. pPager->changeCountDone = 1;
  51936. }
  51937. }else{
  51938. pPager->changeCountDone = 1;
  51939. }
  51940. }
  51941. /* Release the page reference. */
  51942. sqlite3PagerUnref(pPgHdr);
  51943. }
  51944. return rc;
  51945. }
  51946. /*
  51947. ** Sync the database file to disk. This is a no-op for in-memory databases
  51948. ** or pages with the Pager.noSync flag set.
  51949. **
  51950. ** If successful, or if called on a pager for which it is a no-op, this
  51951. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  51952. */
  51953. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  51954. int rc = SQLITE_OK;
  51955. void *pArg = (void*)zMaster;
  51956. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  51957. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  51958. if( rc==SQLITE_OK && !pPager->noSync ){
  51959. assert( !MEMDB );
  51960. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  51961. }
  51962. return rc;
  51963. }
  51964. /*
  51965. ** This function may only be called while a write-transaction is active in
  51966. ** rollback. If the connection is in WAL mode, this call is a no-op.
  51967. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  51968. ** the database file, an attempt is made to obtain one.
  51969. **
  51970. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  51971. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  51972. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  51973. ** returned.
  51974. */
  51975. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  51976. int rc = pPager->errCode;
  51977. assert( assert_pager_state(pPager) );
  51978. if( rc==SQLITE_OK ){
  51979. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  51980. || pPager->eState==PAGER_WRITER_DBMOD
  51981. || pPager->eState==PAGER_WRITER_LOCKED
  51982. );
  51983. assert( assert_pager_state(pPager) );
  51984. if( 0==pagerUseWal(pPager) ){
  51985. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  51986. }
  51987. }
  51988. return rc;
  51989. }
  51990. /*
  51991. ** Sync the database file for the pager pPager. zMaster points to the name
  51992. ** of a master journal file that should be written into the individual
  51993. ** journal file. zMaster may be NULL, which is interpreted as no master
  51994. ** journal (a single database transaction).
  51995. **
  51996. ** This routine ensures that:
  51997. **
  51998. ** * The database file change-counter is updated,
  51999. ** * the journal is synced (unless the atomic-write optimization is used),
  52000. ** * all dirty pages are written to the database file,
  52001. ** * the database file is truncated (if required), and
  52002. ** * the database file synced.
  52003. **
  52004. ** The only thing that remains to commit the transaction is to finalize
  52005. ** (delete, truncate or zero the first part of) the journal file (or
  52006. ** delete the master journal file if specified).
  52007. **
  52008. ** Note that if zMaster==NULL, this does not overwrite a previous value
  52009. ** passed to an sqlite3PagerCommitPhaseOne() call.
  52010. **
  52011. ** If the final parameter - noSync - is true, then the database file itself
  52012. ** is not synced. The caller must call sqlite3PagerSync() directly to
  52013. ** sync the database file before calling CommitPhaseTwo() to delete the
  52014. ** journal file in this case.
  52015. */
  52016. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  52017. Pager *pPager, /* Pager object */
  52018. const char *zMaster, /* If not NULL, the master journal name */
  52019. int noSync /* True to omit the xSync on the db file */
  52020. ){
  52021. int rc = SQLITE_OK; /* Return code */
  52022. assert( pPager->eState==PAGER_WRITER_LOCKED
  52023. || pPager->eState==PAGER_WRITER_CACHEMOD
  52024. || pPager->eState==PAGER_WRITER_DBMOD
  52025. || pPager->eState==PAGER_ERROR
  52026. );
  52027. assert( assert_pager_state(pPager) );
  52028. /* If a prior error occurred, report that error again. */
  52029. if( NEVER(pPager->errCode) ) return pPager->errCode;
  52030. /* Provide the ability to easily simulate an I/O error during testing */
  52031. if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
  52032. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  52033. pPager->zFilename, zMaster, pPager->dbSize));
  52034. /* If no database changes have been made, return early. */
  52035. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  52036. assert( MEMDB==0 || pPager->tempFile );
  52037. assert( isOpen(pPager->fd) || pPager->tempFile );
  52038. if( 0==pagerFlushOnCommit(pPager, 1) ){
  52039. /* If this is an in-memory db, or no pages have been written to, or this
  52040. ** function has already been called, it is mostly a no-op. However, any
  52041. ** backup in progress needs to be restarted. */
  52042. sqlite3BackupRestart(pPager->pBackup);
  52043. }else{
  52044. if( pagerUseWal(pPager) ){
  52045. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  52046. PgHdr *pPageOne = 0;
  52047. if( pList==0 ){
  52048. /* Must have at least one page for the WAL commit flag.
  52049. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  52050. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  52051. pList = pPageOne;
  52052. pList->pDirty = 0;
  52053. }
  52054. assert( rc==SQLITE_OK );
  52055. if( ALWAYS(pList) ){
  52056. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  52057. }
  52058. sqlite3PagerUnref(pPageOne);
  52059. if( rc==SQLITE_OK ){
  52060. sqlite3PcacheCleanAll(pPager->pPCache);
  52061. }
  52062. }else{
  52063. /* The bBatch boolean is true if the batch-atomic-write commit method
  52064. ** should be used. No rollback journal is created if batch-atomic-write
  52065. ** is enabled.
  52066. */
  52067. sqlite3_file *fd = pPager->fd;
  52068. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  52069. const int bBatch = zMaster==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
  52070. && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
  52071. && !pPager->noSync
  52072. && sqlite3JournalIsInMemory(pPager->jfd);
  52073. #else
  52074. # define bBatch 0
  52075. #endif
  52076. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  52077. /* The following block updates the change-counter. Exactly how it
  52078. ** does this depends on whether or not the atomic-update optimization
  52079. ** was enabled at compile time, and if this transaction meets the
  52080. ** runtime criteria to use the operation:
  52081. **
  52082. ** * The file-system supports the atomic-write property for
  52083. ** blocks of size page-size, and
  52084. ** * This commit is not part of a multi-file transaction, and
  52085. ** * Exactly one page has been modified and store in the journal file.
  52086. **
  52087. ** If the optimization was not enabled at compile time, then the
  52088. ** pager_incr_changecounter() function is called to update the change
  52089. ** counter in 'indirect-mode'. If the optimization is compiled in but
  52090. ** is not applicable to this transaction, call sqlite3JournalCreate()
  52091. ** to make sure the journal file has actually been created, then call
  52092. ** pager_incr_changecounter() to update the change-counter in indirect
  52093. ** mode.
  52094. **
  52095. ** Otherwise, if the optimization is both enabled and applicable,
  52096. ** then call pager_incr_changecounter() to update the change-counter
  52097. ** in 'direct' mode. In this case the journal file will never be
  52098. ** created for this transaction.
  52099. */
  52100. if( bBatch==0 ){
  52101. PgHdr *pPg;
  52102. assert( isOpen(pPager->jfd)
  52103. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  52104. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  52105. );
  52106. if( !zMaster && isOpen(pPager->jfd)
  52107. && pPager->journalOff==jrnlBufferSize(pPager)
  52108. && pPager->dbSize>=pPager->dbOrigSize
  52109. && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  52110. ){
  52111. /* Update the db file change counter via the direct-write method. The
  52112. ** following call will modify the in-memory representation of page 1
  52113. ** to include the updated change counter and then write page 1
  52114. ** directly to the database file. Because of the atomic-write
  52115. ** property of the host file-system, this is safe.
  52116. */
  52117. rc = pager_incr_changecounter(pPager, 1);
  52118. }else{
  52119. rc = sqlite3JournalCreate(pPager->jfd);
  52120. if( rc==SQLITE_OK ){
  52121. rc = pager_incr_changecounter(pPager, 0);
  52122. }
  52123. }
  52124. }
  52125. #else
  52126. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  52127. if( zMaster ){
  52128. rc = sqlite3JournalCreate(pPager->jfd);
  52129. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52130. }
  52131. #endif
  52132. rc = pager_incr_changecounter(pPager, 0);
  52133. #endif
  52134. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52135. /* Write the master journal name into the journal file. If a master
  52136. ** journal file name has already been written to the journal file,
  52137. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  52138. */
  52139. rc = writeMasterJournal(pPager, zMaster);
  52140. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52141. /* Sync the journal file and write all dirty pages to the database.
  52142. ** If the atomic-update optimization is being used, this sync will not
  52143. ** create the journal file or perform any real IO.
  52144. **
  52145. ** Because the change-counter page was just modified, unless the
  52146. ** atomic-update optimization is used it is almost certain that the
  52147. ** journal requires a sync here. However, in locking_mode=exclusive
  52148. ** on a system under memory pressure it is just possible that this is
  52149. ** not the case. In this case it is likely enough that the redundant
  52150. ** xSync() call will be changed to a no-op by the OS anyhow.
  52151. */
  52152. rc = syncJournal(pPager, 0);
  52153. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52154. if( bBatch ){
  52155. /* The pager is now in DBMOD state. But regardless of what happens
  52156. ** next, attempting to play the journal back into the database would
  52157. ** be unsafe. Close it now to make sure that does not happen. */
  52158. sqlite3OsClose(pPager->jfd);
  52159. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
  52160. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52161. }
  52162. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  52163. if( bBatch ){
  52164. if( rc==SQLITE_OK ){
  52165. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
  52166. }
  52167. if( rc!=SQLITE_OK ){
  52168. sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
  52169. }
  52170. }
  52171. if( rc!=SQLITE_OK ){
  52172. assert( rc!=SQLITE_IOERR_BLOCKED );
  52173. goto commit_phase_one_exit;
  52174. }
  52175. sqlite3PcacheCleanAll(pPager->pPCache);
  52176. /* If the file on disk is smaller than the database image, use
  52177. ** pager_truncate to grow the file here. This can happen if the database
  52178. ** image was extended as part of the current transaction and then the
  52179. ** last page in the db image moved to the free-list. In this case the
  52180. ** last page is never written out to disk, leaving the database file
  52181. ** undersized. Fix this now if it is the case. */
  52182. if( pPager->dbSize>pPager->dbFileSize ){
  52183. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  52184. assert( pPager->eState==PAGER_WRITER_DBMOD );
  52185. rc = pager_truncate(pPager, nNew);
  52186. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  52187. }
  52188. /* Finally, sync the database file. */
  52189. if( !noSync ){
  52190. rc = sqlite3PagerSync(pPager, zMaster);
  52191. }
  52192. IOTRACE(("DBSYNC %p\n", pPager))
  52193. }
  52194. }
  52195. commit_phase_one_exit:
  52196. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  52197. pPager->eState = PAGER_WRITER_FINISHED;
  52198. }
  52199. return rc;
  52200. }
  52201. /*
  52202. ** When this function is called, the database file has been completely
  52203. ** updated to reflect the changes made by the current transaction and
  52204. ** synced to disk. The journal file still exists in the file-system
  52205. ** though, and if a failure occurs at this point it will eventually
  52206. ** be used as a hot-journal and the current transaction rolled back.
  52207. **
  52208. ** This function finalizes the journal file, either by deleting,
  52209. ** truncating or partially zeroing it, so that it cannot be used
  52210. ** for hot-journal rollback. Once this is done the transaction is
  52211. ** irrevocably committed.
  52212. **
  52213. ** If an error occurs, an IO error code is returned and the pager
  52214. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  52215. */
  52216. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  52217. int rc = SQLITE_OK; /* Return code */
  52218. /* This routine should not be called if a prior error has occurred.
  52219. ** But if (due to a coding error elsewhere in the system) it does get
  52220. ** called, just return the same error code without doing anything. */
  52221. if( NEVER(pPager->errCode) ) return pPager->errCode;
  52222. assert( pPager->eState==PAGER_WRITER_LOCKED
  52223. || pPager->eState==PAGER_WRITER_FINISHED
  52224. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  52225. );
  52226. assert( assert_pager_state(pPager) );
  52227. /* An optimization. If the database was not actually modified during
  52228. ** this transaction, the pager is running in exclusive-mode and is
  52229. ** using persistent journals, then this function is a no-op.
  52230. **
  52231. ** The start of the journal file currently contains a single journal
  52232. ** header with the nRec field set to 0. If such a journal is used as
  52233. ** a hot-journal during hot-journal rollback, 0 changes will be made
  52234. ** to the database file. So there is no need to zero the journal
  52235. ** header. Since the pager is in exclusive mode, there is no need
  52236. ** to drop any locks either.
  52237. */
  52238. if( pPager->eState==PAGER_WRITER_LOCKED
  52239. && pPager->exclusiveMode
  52240. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  52241. ){
  52242. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  52243. pPager->eState = PAGER_READER;
  52244. return SQLITE_OK;
  52245. }
  52246. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  52247. pPager->iDataVersion++;
  52248. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  52249. return pager_error(pPager, rc);
  52250. }
  52251. /*
  52252. ** If a write transaction is open, then all changes made within the
  52253. ** transaction are reverted and the current write-transaction is closed.
  52254. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  52255. ** state if an error occurs.
  52256. **
  52257. ** If the pager is already in PAGER_ERROR state when this function is called,
  52258. ** it returns Pager.errCode immediately. No work is performed in this case.
  52259. **
  52260. ** Otherwise, in rollback mode, this function performs two functions:
  52261. **
  52262. ** 1) It rolls back the journal file, restoring all database file and
  52263. ** in-memory cache pages to the state they were in when the transaction
  52264. ** was opened, and
  52265. **
  52266. ** 2) It finalizes the journal file, so that it is not used for hot
  52267. ** rollback at any point in the future.
  52268. **
  52269. ** Finalization of the journal file (task 2) is only performed if the
  52270. ** rollback is successful.
  52271. **
  52272. ** In WAL mode, all cache-entries containing data modified within the
  52273. ** current transaction are either expelled from the cache or reverted to
  52274. ** their pre-transaction state by re-reading data from the database or
  52275. ** WAL files. The WAL transaction is then closed.
  52276. */
  52277. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  52278. int rc = SQLITE_OK; /* Return code */
  52279. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  52280. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  52281. ** the pager is already in the ERROR state, the rollback is not
  52282. ** attempted here. Instead, the error code is returned to the caller.
  52283. */
  52284. assert( assert_pager_state(pPager) );
  52285. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  52286. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  52287. if( pagerUseWal(pPager) ){
  52288. int rc2;
  52289. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  52290. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  52291. if( rc==SQLITE_OK ) rc = rc2;
  52292. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  52293. int eState = pPager->eState;
  52294. rc = pager_end_transaction(pPager, 0, 0);
  52295. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  52296. /* This can happen using journal_mode=off. Move the pager to the error
  52297. ** state to indicate that the contents of the cache may not be trusted.
  52298. ** Any active readers will get SQLITE_ABORT.
  52299. */
  52300. pPager->errCode = SQLITE_ABORT;
  52301. pPager->eState = PAGER_ERROR;
  52302. setGetterMethod(pPager);
  52303. return rc;
  52304. }
  52305. }else{
  52306. rc = pager_playback(pPager, 0);
  52307. }
  52308. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  52309. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  52310. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  52311. || rc==SQLITE_CANTOPEN
  52312. );
  52313. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  52314. ** cache. So call pager_error() on the way out to make any error persistent.
  52315. */
  52316. return pager_error(pPager, rc);
  52317. }
  52318. /*
  52319. ** Return TRUE if the database file is opened read-only. Return FALSE
  52320. ** if the database is (in theory) writable.
  52321. */
  52322. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  52323. return pPager->readOnly;
  52324. }
  52325. #ifdef SQLITE_DEBUG
  52326. /*
  52327. ** Return the sum of the reference counts for all pages held by pPager.
  52328. */
  52329. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  52330. return sqlite3PcacheRefCount(pPager->pPCache);
  52331. }
  52332. #endif
  52333. /*
  52334. ** Return the approximate number of bytes of memory currently
  52335. ** used by the pager and its associated cache.
  52336. */
  52337. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  52338. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  52339. + 5*sizeof(void*);
  52340. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  52341. + sqlite3MallocSize(pPager)
  52342. + pPager->pageSize;
  52343. }
  52344. /*
  52345. ** Return the number of references to the specified page.
  52346. */
  52347. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  52348. return sqlite3PcachePageRefcount(pPage);
  52349. }
  52350. #ifdef SQLITE_TEST
  52351. /*
  52352. ** This routine is used for testing and analysis only.
  52353. */
  52354. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  52355. static int a[11];
  52356. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  52357. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  52358. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  52359. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  52360. a[4] = pPager->eState;
  52361. a[5] = pPager->errCode;
  52362. a[6] = pPager->aStat[PAGER_STAT_HIT];
  52363. a[7] = pPager->aStat[PAGER_STAT_MISS];
  52364. a[8] = 0; /* Used to be pPager->nOvfl */
  52365. a[9] = pPager->nRead;
  52366. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  52367. return a;
  52368. }
  52369. #endif
  52370. /*
  52371. ** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,
  52372. ** or _WRITE+1. The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation
  52373. ** of SQLITE_DBSTATUS_CACHE_SPILL. The _SPILL case is not contiguous because
  52374. ** it was added later.
  52375. **
  52376. ** Before returning, *pnVal is incremented by the
  52377. ** current cache hit or miss count, according to the value of eStat. If the
  52378. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  52379. ** returning.
  52380. */
  52381. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  52382. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  52383. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  52384. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  52385. || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
  52386. );
  52387. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  52388. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  52389. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1
  52390. && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );
  52391. eStat -= SQLITE_DBSTATUS_CACHE_HIT;
  52392. *pnVal += pPager->aStat[eStat];
  52393. if( reset ){
  52394. pPager->aStat[eStat] = 0;
  52395. }
  52396. }
  52397. /*
  52398. ** Return true if this is an in-memory or temp-file backed pager.
  52399. */
  52400. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  52401. return pPager->tempFile;
  52402. }
  52403. /*
  52404. ** Check that there are at least nSavepoint savepoints open. If there are
  52405. ** currently less than nSavepoints open, then open one or more savepoints
  52406. ** to make up the difference. If the number of savepoints is already
  52407. ** equal to nSavepoint, then this function is a no-op.
  52408. **
  52409. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  52410. ** occurs while opening the sub-journal file, then an IO error code is
  52411. ** returned. Otherwise, SQLITE_OK.
  52412. */
  52413. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  52414. int rc = SQLITE_OK; /* Return code */
  52415. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  52416. int ii; /* Iterator variable */
  52417. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  52418. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  52419. assert( assert_pager_state(pPager) );
  52420. assert( nSavepoint>nCurrent && pPager->useJournal );
  52421. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  52422. ** if the allocation fails. Otherwise, zero the new portion in case a
  52423. ** malloc failure occurs while populating it in the for(...) loop below.
  52424. */
  52425. aNew = (PagerSavepoint *)sqlite3Realloc(
  52426. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  52427. );
  52428. if( !aNew ){
  52429. return SQLITE_NOMEM_BKPT;
  52430. }
  52431. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  52432. pPager->aSavepoint = aNew;
  52433. /* Populate the PagerSavepoint structures just allocated. */
  52434. for(ii=nCurrent; ii<nSavepoint; ii++){
  52435. aNew[ii].nOrig = pPager->dbSize;
  52436. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  52437. aNew[ii].iOffset = pPager->journalOff;
  52438. }else{
  52439. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  52440. }
  52441. aNew[ii].iSubRec = pPager->nSubRec;
  52442. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  52443. if( !aNew[ii].pInSavepoint ){
  52444. return SQLITE_NOMEM_BKPT;
  52445. }
  52446. if( pagerUseWal(pPager) ){
  52447. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  52448. }
  52449. pPager->nSavepoint = ii+1;
  52450. }
  52451. assert( pPager->nSavepoint==nSavepoint );
  52452. assertTruncateConstraint(pPager);
  52453. return rc;
  52454. }
  52455. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  52456. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  52457. assert( assert_pager_state(pPager) );
  52458. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  52459. return pagerOpenSavepoint(pPager, nSavepoint);
  52460. }else{
  52461. return SQLITE_OK;
  52462. }
  52463. }
  52464. /*
  52465. ** This function is called to rollback or release (commit) a savepoint.
  52466. ** The savepoint to release or rollback need not be the most recently
  52467. ** created savepoint.
  52468. **
  52469. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  52470. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  52471. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  52472. ** that have occurred since the specified savepoint was created.
  52473. **
  52474. ** The savepoint to rollback or release is identified by parameter
  52475. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  52476. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  52477. ** on the most recently created savepoint. If iSavepoint is greater than
  52478. ** (Pager.nSavepoint-1), then this function is a no-op.
  52479. **
  52480. ** If a negative value is passed to this function, then the current
  52481. ** transaction is rolled back. This is different to calling
  52482. ** sqlite3PagerRollback() because this function does not terminate
  52483. ** the transaction or unlock the database, it just restores the
  52484. ** contents of the database to its original state.
  52485. **
  52486. ** In any case, all savepoints with an index greater than iSavepoint
  52487. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  52488. ** then savepoint iSavepoint is also destroyed.
  52489. **
  52490. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  52491. ** or an IO error code if an IO error occurs while rolling back a
  52492. ** savepoint. If no errors occur, SQLITE_OK is returned.
  52493. */
  52494. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  52495. int rc = pPager->errCode;
  52496. #ifdef SQLITE_ENABLE_ZIPVFS
  52497. if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
  52498. #endif
  52499. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  52500. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  52501. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  52502. int ii; /* Iterator variable */
  52503. int nNew; /* Number of remaining savepoints after this op. */
  52504. /* Figure out how many savepoints will still be active after this
  52505. ** operation. Store this value in nNew. Then free resources associated
  52506. ** with any savepoints that are destroyed by this operation.
  52507. */
  52508. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  52509. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  52510. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  52511. }
  52512. pPager->nSavepoint = nNew;
  52513. /* If this is a release of the outermost savepoint, truncate
  52514. ** the sub-journal to zero bytes in size. */
  52515. if( op==SAVEPOINT_RELEASE ){
  52516. if( nNew==0 && isOpen(pPager->sjfd) ){
  52517. /* Only truncate if it is an in-memory sub-journal. */
  52518. if( sqlite3JournalIsInMemory(pPager->sjfd) ){
  52519. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  52520. assert( rc==SQLITE_OK );
  52521. }
  52522. pPager->nSubRec = 0;
  52523. }
  52524. }
  52525. /* Else this is a rollback operation, playback the specified savepoint.
  52526. ** If this is a temp-file, it is possible that the journal file has
  52527. ** not yet been opened. In this case there have been no changes to
  52528. ** the database file, so the playback operation can be skipped.
  52529. */
  52530. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  52531. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  52532. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  52533. assert(rc!=SQLITE_DONE);
  52534. }
  52535. #ifdef SQLITE_ENABLE_ZIPVFS
  52536. /* If the cache has been modified but the savepoint cannot be rolled
  52537. ** back journal_mode=off, put the pager in the error state. This way,
  52538. ** if the VFS used by this pager includes ZipVFS, the entire transaction
  52539. ** can be rolled back at the ZipVFS level. */
  52540. else if(
  52541. pPager->journalMode==PAGER_JOURNALMODE_OFF
  52542. && pPager->eState>=PAGER_WRITER_CACHEMOD
  52543. ){
  52544. pPager->errCode = SQLITE_ABORT;
  52545. pPager->eState = PAGER_ERROR;
  52546. setGetterMethod(pPager);
  52547. }
  52548. #endif
  52549. }
  52550. return rc;
  52551. }
  52552. /*
  52553. ** Return the full pathname of the database file.
  52554. **
  52555. ** Except, if the pager is in-memory only, then return an empty string if
  52556. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  52557. ** used to report the filename to the user, for compatibility with legacy
  52558. ** behavior. But when the Btree needs to know the filename for matching to
  52559. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  52560. ** participate in shared-cache.
  52561. */
  52562. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  52563. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  52564. }
  52565. /*
  52566. ** Return the VFS structure for the pager.
  52567. */
  52568. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  52569. return pPager->pVfs;
  52570. }
  52571. /*
  52572. ** Return the file handle for the database file associated
  52573. ** with the pager. This might return NULL if the file has
  52574. ** not yet been opened.
  52575. */
  52576. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  52577. return pPager->fd;
  52578. }
  52579. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  52580. /*
  52581. ** Reset the lock timeout for pager.
  52582. */
  52583. SQLITE_PRIVATE void sqlite3PagerResetLockTimeout(Pager *pPager){
  52584. int x = 0;
  52585. sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_LOCK_TIMEOUT, &x);
  52586. }
  52587. #endif
  52588. /*
  52589. ** Return the file handle for the journal file (if it exists).
  52590. ** This will be either the rollback journal or the WAL file.
  52591. */
  52592. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  52593. #if SQLITE_OMIT_WAL
  52594. return pPager->jfd;
  52595. #else
  52596. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  52597. #endif
  52598. }
  52599. /*
  52600. ** Return the full pathname of the journal file.
  52601. */
  52602. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  52603. return pPager->zJournal;
  52604. }
  52605. #ifdef SQLITE_HAS_CODEC
  52606. /*
  52607. ** Set or retrieve the codec for this pager
  52608. */
  52609. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  52610. Pager *pPager,
  52611. void *(*xCodec)(void*,void*,Pgno,int),
  52612. void (*xCodecSizeChng)(void*,int,int),
  52613. void (*xCodecFree)(void*),
  52614. void *pCodec
  52615. ){
  52616. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  52617. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  52618. pPager->xCodecSizeChng = xCodecSizeChng;
  52619. pPager->xCodecFree = xCodecFree;
  52620. pPager->pCodec = pCodec;
  52621. setGetterMethod(pPager);
  52622. pagerReportSize(pPager);
  52623. }
  52624. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  52625. return pPager->pCodec;
  52626. }
  52627. /*
  52628. ** This function is called by the wal module when writing page content
  52629. ** into the log file.
  52630. **
  52631. ** This function returns a pointer to a buffer containing the encrypted
  52632. ** page content. If a malloc fails, this function may return NULL.
  52633. */
  52634. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  52635. void *aData = 0;
  52636. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  52637. return aData;
  52638. }
  52639. /*
  52640. ** Return the current pager state
  52641. */
  52642. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  52643. return pPager->eState;
  52644. }
  52645. #endif /* SQLITE_HAS_CODEC */
  52646. #ifndef SQLITE_OMIT_AUTOVACUUM
  52647. /*
  52648. ** Move the page pPg to location pgno in the file.
  52649. **
  52650. ** There must be no references to the page previously located at
  52651. ** pgno (which we call pPgOld) though that page is allowed to be
  52652. ** in cache. If the page previously located at pgno is not already
  52653. ** in the rollback journal, it is not put there by by this routine.
  52654. **
  52655. ** References to the page pPg remain valid. Updating any
  52656. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  52657. ** allocated along with the page) is the responsibility of the caller.
  52658. **
  52659. ** A transaction must be active when this routine is called. It used to be
  52660. ** required that a statement transaction was not active, but this restriction
  52661. ** has been removed (CREATE INDEX needs to move a page when a statement
  52662. ** transaction is active).
  52663. **
  52664. ** If the fourth argument, isCommit, is non-zero, then this page is being
  52665. ** moved as part of a database reorganization just before the transaction
  52666. ** is being committed. In this case, it is guaranteed that the database page
  52667. ** pPg refers to will not be written to again within this transaction.
  52668. **
  52669. ** This function may return SQLITE_NOMEM or an IO error code if an error
  52670. ** occurs. Otherwise, it returns SQLITE_OK.
  52671. */
  52672. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  52673. PgHdr *pPgOld; /* The page being overwritten. */
  52674. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  52675. int rc; /* Return code */
  52676. Pgno origPgno; /* The original page number */
  52677. assert( pPg->nRef>0 );
  52678. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  52679. || pPager->eState==PAGER_WRITER_DBMOD
  52680. );
  52681. assert( assert_pager_state(pPager) );
  52682. /* In order to be able to rollback, an in-memory database must journal
  52683. ** the page we are moving from.
  52684. */
  52685. assert( pPager->tempFile || !MEMDB );
  52686. if( pPager->tempFile ){
  52687. rc = sqlite3PagerWrite(pPg);
  52688. if( rc ) return rc;
  52689. }
  52690. /* If the page being moved is dirty and has not been saved by the latest
  52691. ** savepoint, then save the current contents of the page into the
  52692. ** sub-journal now. This is required to handle the following scenario:
  52693. **
  52694. ** BEGIN;
  52695. ** <journal page X, then modify it in memory>
  52696. ** SAVEPOINT one;
  52697. ** <Move page X to location Y>
  52698. ** ROLLBACK TO one;
  52699. **
  52700. ** If page X were not written to the sub-journal here, it would not
  52701. ** be possible to restore its contents when the "ROLLBACK TO one"
  52702. ** statement were is processed.
  52703. **
  52704. ** subjournalPage() may need to allocate space to store pPg->pgno into
  52705. ** one or more savepoint bitvecs. This is the reason this function
  52706. ** may return SQLITE_NOMEM.
  52707. */
  52708. if( (pPg->flags & PGHDR_DIRTY)!=0
  52709. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  52710. ){
  52711. return rc;
  52712. }
  52713. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  52714. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  52715. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  52716. /* If the journal needs to be sync()ed before page pPg->pgno can
  52717. ** be written to, store pPg->pgno in local variable needSyncPgno.
  52718. **
  52719. ** If the isCommit flag is set, there is no need to remember that
  52720. ** the journal needs to be sync()ed before database page pPg->pgno
  52721. ** can be written to. The caller has already promised not to write to it.
  52722. */
  52723. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  52724. needSyncPgno = pPg->pgno;
  52725. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  52726. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  52727. assert( pPg->flags&PGHDR_DIRTY );
  52728. }
  52729. /* If the cache contains a page with page-number pgno, remove it
  52730. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  52731. ** page pgno before the 'move' operation, it needs to be retained
  52732. ** for the page moved there.
  52733. */
  52734. pPg->flags &= ~PGHDR_NEED_SYNC;
  52735. pPgOld = sqlite3PagerLookup(pPager, pgno);
  52736. assert( !pPgOld || pPgOld->nRef==1 );
  52737. if( pPgOld ){
  52738. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  52739. if( pPager->tempFile ){
  52740. /* Do not discard pages from an in-memory database since we might
  52741. ** need to rollback later. Just move the page out of the way. */
  52742. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  52743. }else{
  52744. sqlite3PcacheDrop(pPgOld);
  52745. }
  52746. }
  52747. origPgno = pPg->pgno;
  52748. sqlite3PcacheMove(pPg, pgno);
  52749. sqlite3PcacheMakeDirty(pPg);
  52750. /* For an in-memory database, make sure the original page continues
  52751. ** to exist, in case the transaction needs to roll back. Use pPgOld
  52752. ** as the original page since it has already been allocated.
  52753. */
  52754. if( pPager->tempFile && pPgOld ){
  52755. sqlite3PcacheMove(pPgOld, origPgno);
  52756. sqlite3PagerUnrefNotNull(pPgOld);
  52757. }
  52758. if( needSyncPgno ){
  52759. /* If needSyncPgno is non-zero, then the journal file needs to be
  52760. ** sync()ed before any data is written to database file page needSyncPgno.
  52761. ** Currently, no such page exists in the page-cache and the
  52762. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  52763. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  52764. ** flag.
  52765. **
  52766. ** If the attempt to load the page into the page-cache fails, (due
  52767. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  52768. ** array. Otherwise, if the page is loaded and written again in
  52769. ** this transaction, it may be written to the database file before
  52770. ** it is synced into the journal file. This way, it may end up in
  52771. ** the journal file twice, but that is not a problem.
  52772. */
  52773. PgHdr *pPgHdr;
  52774. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  52775. if( rc!=SQLITE_OK ){
  52776. if( needSyncPgno<=pPager->dbOrigSize ){
  52777. assert( pPager->pTmpSpace!=0 );
  52778. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  52779. }
  52780. return rc;
  52781. }
  52782. pPgHdr->flags |= PGHDR_NEED_SYNC;
  52783. sqlite3PcacheMakeDirty(pPgHdr);
  52784. sqlite3PagerUnrefNotNull(pPgHdr);
  52785. }
  52786. return SQLITE_OK;
  52787. }
  52788. #endif
  52789. /*
  52790. ** The page handle passed as the first argument refers to a dirty page
  52791. ** with a page number other than iNew. This function changes the page's
  52792. ** page number to iNew and sets the value of the PgHdr.flags field to
  52793. ** the value passed as the third parameter.
  52794. */
  52795. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  52796. assert( pPg->pgno!=iNew );
  52797. pPg->flags = flags;
  52798. sqlite3PcacheMove(pPg, iNew);
  52799. }
  52800. /*
  52801. ** Return a pointer to the data for the specified page.
  52802. */
  52803. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  52804. assert( pPg->nRef>0 || pPg->pPager->memDb );
  52805. return pPg->pData;
  52806. }
  52807. /*
  52808. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  52809. ** allocated along with the specified page.
  52810. */
  52811. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  52812. return pPg->pExtra;
  52813. }
  52814. /*
  52815. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  52816. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  52817. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  52818. ** the locking-mode is set to the value specified.
  52819. **
  52820. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  52821. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  52822. ** locking-mode.
  52823. */
  52824. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  52825. assert( eMode==PAGER_LOCKINGMODE_QUERY
  52826. || eMode==PAGER_LOCKINGMODE_NORMAL
  52827. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  52828. assert( PAGER_LOCKINGMODE_QUERY<0 );
  52829. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  52830. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  52831. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  52832. pPager->exclusiveMode = (u8)eMode;
  52833. }
  52834. return (int)pPager->exclusiveMode;
  52835. }
  52836. /*
  52837. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  52838. **
  52839. ** PAGER_JOURNALMODE_DELETE
  52840. ** PAGER_JOURNALMODE_TRUNCATE
  52841. ** PAGER_JOURNALMODE_PERSIST
  52842. ** PAGER_JOURNALMODE_OFF
  52843. ** PAGER_JOURNALMODE_MEMORY
  52844. ** PAGER_JOURNALMODE_WAL
  52845. **
  52846. ** The journalmode is set to the value specified if the change is allowed.
  52847. ** The change may be disallowed for the following reasons:
  52848. **
  52849. ** * An in-memory database can only have its journal_mode set to _OFF
  52850. ** or _MEMORY.
  52851. **
  52852. ** * Temporary databases cannot have _WAL journalmode.
  52853. **
  52854. ** The returned indicate the current (possibly updated) journal-mode.
  52855. */
  52856. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  52857. u8 eOld = pPager->journalMode; /* Prior journalmode */
  52858. #ifdef SQLITE_DEBUG
  52859. /* The print_pager_state() routine is intended to be used by the debugger
  52860. ** only. We invoke it once here to suppress a compiler warning. */
  52861. print_pager_state(pPager);
  52862. #endif
  52863. /* The eMode parameter is always valid */
  52864. assert( eMode==PAGER_JOURNALMODE_DELETE
  52865. || eMode==PAGER_JOURNALMODE_TRUNCATE
  52866. || eMode==PAGER_JOURNALMODE_PERSIST
  52867. || eMode==PAGER_JOURNALMODE_OFF
  52868. || eMode==PAGER_JOURNALMODE_WAL
  52869. || eMode==PAGER_JOURNALMODE_MEMORY );
  52870. /* This routine is only called from the OP_JournalMode opcode, and
  52871. ** the logic there will never allow a temporary file to be changed
  52872. ** to WAL mode.
  52873. */
  52874. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  52875. /* Do allow the journalmode of an in-memory database to be set to
  52876. ** anything other than MEMORY or OFF
  52877. */
  52878. if( MEMDB ){
  52879. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  52880. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  52881. eMode = eOld;
  52882. }
  52883. }
  52884. if( eMode!=eOld ){
  52885. /* Change the journal mode. */
  52886. assert( pPager->eState!=PAGER_ERROR );
  52887. pPager->journalMode = (u8)eMode;
  52888. /* When transistioning from TRUNCATE or PERSIST to any other journal
  52889. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  52890. ** delete the journal file.
  52891. */
  52892. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  52893. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  52894. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  52895. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  52896. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  52897. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  52898. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  52899. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  52900. /* In this case we would like to delete the journal file. If it is
  52901. ** not possible, then that is not a problem. Deleting the journal file
  52902. ** here is an optimization only.
  52903. **
  52904. ** Before deleting the journal file, obtain a RESERVED lock on the
  52905. ** database file. This ensures that the journal file is not deleted
  52906. ** while it is in use by some other client.
  52907. */
  52908. sqlite3OsClose(pPager->jfd);
  52909. if( pPager->eLock>=RESERVED_LOCK ){
  52910. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  52911. }else{
  52912. int rc = SQLITE_OK;
  52913. int state = pPager->eState;
  52914. assert( state==PAGER_OPEN || state==PAGER_READER );
  52915. if( state==PAGER_OPEN ){
  52916. rc = sqlite3PagerSharedLock(pPager);
  52917. }
  52918. if( pPager->eState==PAGER_READER ){
  52919. assert( rc==SQLITE_OK );
  52920. rc = pagerLockDb(pPager, RESERVED_LOCK);
  52921. }
  52922. if( rc==SQLITE_OK ){
  52923. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  52924. }
  52925. if( rc==SQLITE_OK && state==PAGER_READER ){
  52926. pagerUnlockDb(pPager, SHARED_LOCK);
  52927. }else if( state==PAGER_OPEN ){
  52928. pager_unlock(pPager);
  52929. }
  52930. assert( state==pPager->eState );
  52931. }
  52932. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  52933. sqlite3OsClose(pPager->jfd);
  52934. }
  52935. }
  52936. /* Return the new journal mode */
  52937. return (int)pPager->journalMode;
  52938. }
  52939. /*
  52940. ** Return the current journal mode.
  52941. */
  52942. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  52943. return (int)pPager->journalMode;
  52944. }
  52945. /*
  52946. ** Return TRUE if the pager is in a state where it is OK to change the
  52947. ** journalmode. Journalmode changes can only happen when the database
  52948. ** is unmodified.
  52949. */
  52950. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  52951. assert( assert_pager_state(pPager) );
  52952. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  52953. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  52954. return 1;
  52955. }
  52956. /*
  52957. ** Get/set the size-limit used for persistent journal files.
  52958. **
  52959. ** Setting the size limit to -1 means no limit is enforced.
  52960. ** An attempt to set a limit smaller than -1 is a no-op.
  52961. */
  52962. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  52963. if( iLimit>=-1 ){
  52964. pPager->journalSizeLimit = iLimit;
  52965. sqlite3WalLimit(pPager->pWal, iLimit);
  52966. }
  52967. return pPager->journalSizeLimit;
  52968. }
  52969. /*
  52970. ** Return a pointer to the pPager->pBackup variable. The backup module
  52971. ** in backup.c maintains the content of this variable. This module
  52972. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  52973. ** sqlite3BackupUpdate() only.
  52974. */
  52975. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  52976. return &pPager->pBackup;
  52977. }
  52978. #ifndef SQLITE_OMIT_VACUUM
  52979. /*
  52980. ** Unless this is an in-memory or temporary database, clear the pager cache.
  52981. */
  52982. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  52983. assert( MEMDB==0 || pPager->tempFile );
  52984. if( pPager->tempFile==0 ) pager_reset(pPager);
  52985. }
  52986. #endif
  52987. #ifndef SQLITE_OMIT_WAL
  52988. /*
  52989. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  52990. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  52991. ** or wal_blocking_checkpoint() API functions.
  52992. **
  52993. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  52994. */
  52995. SQLITE_PRIVATE int sqlite3PagerCheckpoint(
  52996. Pager *pPager, /* Checkpoint on this pager */
  52997. sqlite3 *db, /* Db handle used to check for interrupts */
  52998. int eMode, /* Type of checkpoint */
  52999. int *pnLog, /* OUT: Final number of frames in log */
  53000. int *pnCkpt /* OUT: Final number of checkpointed frames */
  53001. ){
  53002. int rc = SQLITE_OK;
  53003. if( pPager->pWal ){
  53004. rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
  53005. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  53006. pPager->pBusyHandlerArg,
  53007. pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  53008. pnLog, pnCkpt
  53009. );
  53010. sqlite3PagerResetLockTimeout(pPager);
  53011. }
  53012. return rc;
  53013. }
  53014. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  53015. return sqlite3WalCallback(pPager->pWal);
  53016. }
  53017. /*
  53018. ** Return true if the underlying VFS for the given pager supports the
  53019. ** primitives necessary for write-ahead logging.
  53020. */
  53021. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  53022. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  53023. if( pPager->noLock ) return 0;
  53024. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  53025. }
  53026. /*
  53027. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  53028. ** is obtained instead, immediately release it.
  53029. */
  53030. static int pagerExclusiveLock(Pager *pPager){
  53031. int rc; /* Return code */
  53032. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  53033. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  53034. if( rc!=SQLITE_OK ){
  53035. /* If the attempt to grab the exclusive lock failed, release the
  53036. ** pending lock that may have been obtained instead. */
  53037. pagerUnlockDb(pPager, SHARED_LOCK);
  53038. }
  53039. return rc;
  53040. }
  53041. /*
  53042. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  53043. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  53044. ** lock on the database file and use heap-memory to store the wal-index
  53045. ** in. Otherwise, use the normal shared-memory.
  53046. */
  53047. static int pagerOpenWal(Pager *pPager){
  53048. int rc = SQLITE_OK;
  53049. assert( pPager->pWal==0 && pPager->tempFile==0 );
  53050. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  53051. /* If the pager is already in exclusive-mode, the WAL module will use
  53052. ** heap-memory for the wal-index instead of the VFS shared-memory
  53053. ** implementation. Take the exclusive lock now, before opening the WAL
  53054. ** file, to make sure this is safe.
  53055. */
  53056. if( pPager->exclusiveMode ){
  53057. rc = pagerExclusiveLock(pPager);
  53058. }
  53059. /* Open the connection to the log file. If this operation fails,
  53060. ** (e.g. due to malloc() failure), return an error code.
  53061. */
  53062. if( rc==SQLITE_OK ){
  53063. rc = sqlite3WalOpen(pPager->pVfs,
  53064. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  53065. pPager->journalSizeLimit, &pPager->pWal
  53066. );
  53067. }
  53068. pagerFixMaplimit(pPager);
  53069. return rc;
  53070. }
  53071. /*
  53072. ** The caller must be holding a SHARED lock on the database file to call
  53073. ** this function.
  53074. **
  53075. ** If the pager passed as the first argument is open on a real database
  53076. ** file (not a temp file or an in-memory database), and the WAL file
  53077. ** is not already open, make an attempt to open it now. If successful,
  53078. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  53079. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  53080. ** not modified in either case.
  53081. **
  53082. ** If the pager is open on a temp-file (or in-memory database), or if
  53083. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  53084. ** without doing anything.
  53085. */
  53086. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  53087. Pager *pPager, /* Pager object */
  53088. int *pbOpen /* OUT: Set to true if call is a no-op */
  53089. ){
  53090. int rc = SQLITE_OK; /* Return code */
  53091. assert( assert_pager_state(pPager) );
  53092. assert( pPager->eState==PAGER_OPEN || pbOpen );
  53093. assert( pPager->eState==PAGER_READER || !pbOpen );
  53094. assert( pbOpen==0 || *pbOpen==0 );
  53095. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  53096. if( !pPager->tempFile && !pPager->pWal ){
  53097. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  53098. /* Close any rollback journal previously open */
  53099. sqlite3OsClose(pPager->jfd);
  53100. rc = pagerOpenWal(pPager);
  53101. if( rc==SQLITE_OK ){
  53102. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  53103. pPager->eState = PAGER_OPEN;
  53104. }
  53105. }else{
  53106. *pbOpen = 1;
  53107. }
  53108. return rc;
  53109. }
  53110. /*
  53111. ** This function is called to close the connection to the log file prior
  53112. ** to switching from WAL to rollback mode.
  53113. **
  53114. ** Before closing the log file, this function attempts to take an
  53115. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  53116. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  53117. ** If successful, the EXCLUSIVE lock is not released before returning.
  53118. */
  53119. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
  53120. int rc = SQLITE_OK;
  53121. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  53122. /* If the log file is not already open, but does exist in the file-system,
  53123. ** it may need to be checkpointed before the connection can switch to
  53124. ** rollback mode. Open it now so this can happen.
  53125. */
  53126. if( !pPager->pWal ){
  53127. int logexists = 0;
  53128. rc = pagerLockDb(pPager, SHARED_LOCK);
  53129. if( rc==SQLITE_OK ){
  53130. rc = sqlite3OsAccess(
  53131. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  53132. );
  53133. }
  53134. if( rc==SQLITE_OK && logexists ){
  53135. rc = pagerOpenWal(pPager);
  53136. }
  53137. }
  53138. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  53139. ** the database file, the log and log-summary files will be deleted.
  53140. */
  53141. if( rc==SQLITE_OK && pPager->pWal ){
  53142. rc = pagerExclusiveLock(pPager);
  53143. if( rc==SQLITE_OK ){
  53144. rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
  53145. pPager->pageSize, (u8*)pPager->pTmpSpace);
  53146. pPager->pWal = 0;
  53147. pagerFixMaplimit(pPager);
  53148. if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  53149. }
  53150. }
  53151. return rc;
  53152. }
  53153. #ifdef SQLITE_ENABLE_SNAPSHOT
  53154. /*
  53155. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  53156. ** currently open. Otherwise, return an error.
  53157. */
  53158. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  53159. int rc = SQLITE_ERROR;
  53160. if( pPager->pWal ){
  53161. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  53162. }
  53163. return rc;
  53164. }
  53165. /*
  53166. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  53167. ** read transaction is opened, attempt to read from the snapshot it
  53168. ** identifies. If this is not a WAL database, return an error.
  53169. */
  53170. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
  53171. int rc = SQLITE_OK;
  53172. if( pPager->pWal ){
  53173. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  53174. }else{
  53175. rc = SQLITE_ERROR;
  53176. }
  53177. return rc;
  53178. }
  53179. /*
  53180. ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
  53181. ** is not a WAL database, return an error.
  53182. */
  53183. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
  53184. int rc;
  53185. if( pPager->pWal ){
  53186. rc = sqlite3WalSnapshotRecover(pPager->pWal);
  53187. }else{
  53188. rc = SQLITE_ERROR;
  53189. }
  53190. return rc;
  53191. }
  53192. #endif /* SQLITE_ENABLE_SNAPSHOT */
  53193. #endif /* !SQLITE_OMIT_WAL */
  53194. #ifdef SQLITE_ENABLE_ZIPVFS
  53195. /*
  53196. ** A read-lock must be held on the pager when this function is called. If
  53197. ** the pager is in WAL mode and the WAL file currently contains one or more
  53198. ** frames, return the size in bytes of the page images stored within the
  53199. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  53200. ** is empty, return 0.
  53201. */
  53202. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  53203. assert( pPager->eState>=PAGER_READER );
  53204. return sqlite3WalFramesize(pPager->pWal);
  53205. }
  53206. #endif
  53207. #endif /* SQLITE_OMIT_DISKIO */
  53208. /************** End of pager.c ***********************************************/
  53209. /************** Begin file wal.c *********************************************/
  53210. /*
  53211. ** 2010 February 1
  53212. **
  53213. ** The author disclaims copyright to this source code. In place of
  53214. ** a legal notice, here is a blessing:
  53215. **
  53216. ** May you do good and not evil.
  53217. ** May you find forgiveness for yourself and forgive others.
  53218. ** May you share freely, never taking more than you give.
  53219. **
  53220. *************************************************************************
  53221. **
  53222. ** This file contains the implementation of a write-ahead log (WAL) used in
  53223. ** "journal_mode=WAL" mode.
  53224. **
  53225. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  53226. **
  53227. ** A WAL file consists of a header followed by zero or more "frames".
  53228. ** Each frame records the revised content of a single page from the
  53229. ** database file. All changes to the database are recorded by writing
  53230. ** frames into the WAL. Transactions commit when a frame is written that
  53231. ** contains a commit marker. A single WAL can and usually does record
  53232. ** multiple transactions. Periodically, the content of the WAL is
  53233. ** transferred back into the database file in an operation called a
  53234. ** "checkpoint".
  53235. **
  53236. ** A single WAL file can be used multiple times. In other words, the
  53237. ** WAL can fill up with frames and then be checkpointed and then new
  53238. ** frames can overwrite the old ones. A WAL always grows from beginning
  53239. ** toward the end. Checksums and counters attached to each frame are
  53240. ** used to determine which frames within the WAL are valid and which
  53241. ** are leftovers from prior checkpoints.
  53242. **
  53243. ** The WAL header is 32 bytes in size and consists of the following eight
  53244. ** big-endian 32-bit unsigned integer values:
  53245. **
  53246. ** 0: Magic number. 0x377f0682 or 0x377f0683
  53247. ** 4: File format version. Currently 3007000
  53248. ** 8: Database page size. Example: 1024
  53249. ** 12: Checkpoint sequence number
  53250. ** 16: Salt-1, random integer incremented with each checkpoint
  53251. ** 20: Salt-2, a different random integer changing with each ckpt
  53252. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  53253. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  53254. **
  53255. ** Immediately following the wal-header are zero or more frames. Each
  53256. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  53257. ** of page data. The frame-header is six big-endian 32-bit unsigned
  53258. ** integer values, as follows:
  53259. **
  53260. ** 0: Page number.
  53261. ** 4: For commit records, the size of the database image in pages
  53262. ** after the commit. For all other records, zero.
  53263. ** 8: Salt-1 (copied from the header)
  53264. ** 12: Salt-2 (copied from the header)
  53265. ** 16: Checksum-1.
  53266. ** 20: Checksum-2.
  53267. **
  53268. ** A frame is considered valid if and only if the following conditions are
  53269. ** true:
  53270. **
  53271. ** (1) The salt-1 and salt-2 values in the frame-header match
  53272. ** salt values in the wal-header
  53273. **
  53274. ** (2) The checksum values in the final 8 bytes of the frame-header
  53275. ** exactly match the checksum computed consecutively on the
  53276. ** WAL header and the first 8 bytes and the content of all frames
  53277. ** up to and including the current frame.
  53278. **
  53279. ** The checksum is computed using 32-bit big-endian integers if the
  53280. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  53281. ** is computed using little-endian if the magic number is 0x377f0682.
  53282. ** The checksum values are always stored in the frame header in a
  53283. ** big-endian format regardless of which byte order is used to compute
  53284. ** the checksum. The checksum is computed by interpreting the input as
  53285. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  53286. ** algorithm used for the checksum is as follows:
  53287. **
  53288. ** for i from 0 to n-1 step 2:
  53289. ** s0 += x[i] + s1;
  53290. ** s1 += x[i+1] + s0;
  53291. ** endfor
  53292. **
  53293. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  53294. ** in reverse order (the largest fibonacci weight occurs on the first element
  53295. ** of the sequence being summed.) The s1 value spans all 32-bit
  53296. ** terms of the sequence whereas s0 omits the final term.
  53297. **
  53298. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  53299. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  53300. ** The VFS.xSync operations serve as write barriers - all writes launched
  53301. ** before the xSync must complete before any write that launches after the
  53302. ** xSync begins.
  53303. **
  53304. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  53305. ** value is randomized. This prevents old and new frames in the WAL from
  53306. ** being considered valid at the same time and being checkpointing together
  53307. ** following a crash.
  53308. **
  53309. ** READER ALGORITHM
  53310. **
  53311. ** To read a page from the database (call it page number P), a reader
  53312. ** first checks the WAL to see if it contains page P. If so, then the
  53313. ** last valid instance of page P that is a followed by a commit frame
  53314. ** or is a commit frame itself becomes the value read. If the WAL
  53315. ** contains no copies of page P that are valid and which are a commit
  53316. ** frame or are followed by a commit frame, then page P is read from
  53317. ** the database file.
  53318. **
  53319. ** To start a read transaction, the reader records the index of the last
  53320. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  53321. ** for all subsequent read operations. New transactions can be appended
  53322. ** to the WAL, but as long as the reader uses its original mxFrame value
  53323. ** and ignores the newly appended content, it will see a consistent snapshot
  53324. ** of the database from a single point in time. This technique allows
  53325. ** multiple concurrent readers to view different versions of the database
  53326. ** content simultaneously.
  53327. **
  53328. ** The reader algorithm in the previous paragraphs works correctly, but
  53329. ** because frames for page P can appear anywhere within the WAL, the
  53330. ** reader has to scan the entire WAL looking for page P frames. If the
  53331. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  53332. ** and read performance suffers. To overcome this problem, a separate
  53333. ** data structure called the wal-index is maintained to expedite the
  53334. ** search for frames of a particular page.
  53335. **
  53336. ** WAL-INDEX FORMAT
  53337. **
  53338. ** Conceptually, the wal-index is shared memory, though VFS implementations
  53339. ** might choose to implement the wal-index using a mmapped file. Because
  53340. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  53341. ** on a network filesystem. All users of the database must be able to
  53342. ** share memory.
  53343. **
  53344. ** In the default unix and windows implementation, the wal-index is a mmapped
  53345. ** file whose name is the database name with a "-shm" suffix added. For that
  53346. ** reason, the wal-index is sometimes called the "shm" file.
  53347. **
  53348. ** The wal-index is transient. After a crash, the wal-index can (and should
  53349. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  53350. ** to either truncate or zero the header of the wal-index when the last
  53351. ** connection to it closes. Because the wal-index is transient, it can
  53352. ** use an architecture-specific format; it does not have to be cross-platform.
  53353. ** Hence, unlike the database and WAL file formats which store all values
  53354. ** as big endian, the wal-index can store multi-byte values in the native
  53355. ** byte order of the host computer.
  53356. **
  53357. ** The purpose of the wal-index is to answer this question quickly: Given
  53358. ** a page number P and a maximum frame index M, return the index of the
  53359. ** last frame in the wal before frame M for page P in the WAL, or return
  53360. ** NULL if there are no frames for page P in the WAL prior to M.
  53361. **
  53362. ** The wal-index consists of a header region, followed by an one or
  53363. ** more index blocks.
  53364. **
  53365. ** The wal-index header contains the total number of frames within the WAL
  53366. ** in the mxFrame field.
  53367. **
  53368. ** Each index block except for the first contains information on
  53369. ** HASHTABLE_NPAGE frames. The first index block contains information on
  53370. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  53371. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  53372. ** first index block are the same size as all other index blocks in the
  53373. ** wal-index.
  53374. **
  53375. ** Each index block contains two sections, a page-mapping that contains the
  53376. ** database page number associated with each wal frame, and a hash-table
  53377. ** that allows readers to query an index block for a specific page number.
  53378. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  53379. ** for the first index block) 32-bit page numbers. The first entry in the
  53380. ** first index-block contains the database page number corresponding to the
  53381. ** first frame in the WAL file. The first entry in the second index block
  53382. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  53383. ** the log, and so on.
  53384. **
  53385. ** The last index block in a wal-index usually contains less than the full
  53386. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  53387. ** depending on the contents of the WAL file. This does not change the
  53388. ** allocated size of the page-mapping array - the page-mapping array merely
  53389. ** contains unused entries.
  53390. **
  53391. ** Even without using the hash table, the last frame for page P
  53392. ** can be found by scanning the page-mapping sections of each index block
  53393. ** starting with the last index block and moving toward the first, and
  53394. ** within each index block, starting at the end and moving toward the
  53395. ** beginning. The first entry that equals P corresponds to the frame
  53396. ** holding the content for that page.
  53397. **
  53398. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  53399. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  53400. ** hash table for each page number in the mapping section, so the hash
  53401. ** table is never more than half full. The expected number of collisions
  53402. ** prior to finding a match is 1. Each entry of the hash table is an
  53403. ** 1-based index of an entry in the mapping section of the same
  53404. ** index block. Let K be the 1-based index of the largest entry in
  53405. ** the mapping section. (For index blocks other than the last, K will
  53406. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  53407. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  53408. ** contain a value of 0.
  53409. **
  53410. ** To look for page P in the hash table, first compute a hash iKey on
  53411. ** P as follows:
  53412. **
  53413. ** iKey = (P * 383) % HASHTABLE_NSLOT
  53414. **
  53415. ** Then start scanning entries of the hash table, starting with iKey
  53416. ** (wrapping around to the beginning when the end of the hash table is
  53417. ** reached) until an unused hash slot is found. Let the first unused slot
  53418. ** be at index iUnused. (iUnused might be less than iKey if there was
  53419. ** wrap-around.) Because the hash table is never more than half full,
  53420. ** the search is guaranteed to eventually hit an unused entry. Let
  53421. ** iMax be the value between iKey and iUnused, closest to iUnused,
  53422. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  53423. ** no hash slot such that aHash[i]==p) then page P is not in the
  53424. ** current index block. Otherwise the iMax-th mapping entry of the
  53425. ** current index block corresponds to the last entry that references
  53426. ** page P.
  53427. **
  53428. ** A hash search begins with the last index block and moves toward the
  53429. ** first index block, looking for entries corresponding to page P. On
  53430. ** average, only two or three slots in each index block need to be
  53431. ** examined in order to either find the last entry for page P, or to
  53432. ** establish that no such entry exists in the block. Each index block
  53433. ** holds over 4000 entries. So two or three index blocks are sufficient
  53434. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  53435. ** comparisons (on average) suffice to either locate a frame in the
  53436. ** WAL or to establish that the frame does not exist in the WAL. This
  53437. ** is much faster than scanning the entire 10MB WAL.
  53438. **
  53439. ** Note that entries are added in order of increasing K. Hence, one
  53440. ** reader might be using some value K0 and a second reader that started
  53441. ** at a later time (after additional transactions were added to the WAL
  53442. ** and to the wal-index) might be using a different value K1, where K1>K0.
  53443. ** Both readers can use the same hash table and mapping section to get
  53444. ** the correct result. There may be entries in the hash table with
  53445. ** K>K0 but to the first reader, those entries will appear to be unused
  53446. ** slots in the hash table and so the first reader will get an answer as
  53447. ** if no values greater than K0 had ever been inserted into the hash table
  53448. ** in the first place - which is what reader one wants. Meanwhile, the
  53449. ** second reader using K1 will see additional values that were inserted
  53450. ** later, which is exactly what reader two wants.
  53451. **
  53452. ** When a rollback occurs, the value of K is decreased. Hash table entries
  53453. ** that correspond to frames greater than the new K value are removed
  53454. ** from the hash table at this point.
  53455. */
  53456. #ifndef SQLITE_OMIT_WAL
  53457. /* #include "wal.h" */
  53458. /*
  53459. ** Trace output macros
  53460. */
  53461. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  53462. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  53463. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  53464. #else
  53465. # define WALTRACE(X)
  53466. #endif
  53467. /*
  53468. ** The maximum (and only) versions of the wal and wal-index formats
  53469. ** that may be interpreted by this version of SQLite.
  53470. **
  53471. ** If a client begins recovering a WAL file and finds that (a) the checksum
  53472. ** values in the wal-header are correct and (b) the version field is not
  53473. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  53474. **
  53475. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  53476. ** checksum test is successful) and finds that the version field is not
  53477. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  53478. ** returns SQLITE_CANTOPEN.
  53479. */
  53480. #define WAL_MAX_VERSION 3007000
  53481. #define WALINDEX_MAX_VERSION 3007000
  53482. /*
  53483. ** Index numbers for various locking bytes. WAL_NREADER is the number
  53484. ** of available reader locks and should be at least 3. The default
  53485. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  53486. **
  53487. ** Technically, the various VFSes are free to implement these locks however
  53488. ** they see fit. However, compatibility is encouraged so that VFSes can
  53489. ** interoperate. The standard implemention used on both unix and windows
  53490. ** is for the index number to indicate a byte offset into the
  53491. ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
  53492. ** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which
  53493. ** should be 120) is the location in the shm file for the first locking
  53494. ** byte.
  53495. */
  53496. #define WAL_WRITE_LOCK 0
  53497. #define WAL_ALL_BUT_WRITE 1
  53498. #define WAL_CKPT_LOCK 1
  53499. #define WAL_RECOVER_LOCK 2
  53500. #define WAL_READ_LOCK(I) (3+(I))
  53501. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  53502. /* Object declarations */
  53503. typedef struct WalIndexHdr WalIndexHdr;
  53504. typedef struct WalIterator WalIterator;
  53505. typedef struct WalCkptInfo WalCkptInfo;
  53506. /*
  53507. ** The following object holds a copy of the wal-index header content.
  53508. **
  53509. ** The actual header in the wal-index consists of two copies of this
  53510. ** object followed by one instance of the WalCkptInfo object.
  53511. ** For all versions of SQLite through 3.10.0 and probably beyond,
  53512. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  53513. ** the total header size is 136 bytes.
  53514. **
  53515. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  53516. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  53517. ** added in 3.7.1 when support for 64K pages was added.
  53518. */
  53519. struct WalIndexHdr {
  53520. u32 iVersion; /* Wal-index version */
  53521. u32 unused; /* Unused (padding) field */
  53522. u32 iChange; /* Counter incremented each transaction */
  53523. u8 isInit; /* 1 when initialized */
  53524. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  53525. u16 szPage; /* Database page size in bytes. 1==64K */
  53526. u32 mxFrame; /* Index of last valid frame in the WAL */
  53527. u32 nPage; /* Size of database in pages */
  53528. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  53529. u32 aSalt[2]; /* Two salt values copied from WAL header */
  53530. u32 aCksum[2]; /* Checksum over all prior fields */
  53531. };
  53532. /*
  53533. ** A copy of the following object occurs in the wal-index immediately
  53534. ** following the second copy of the WalIndexHdr. This object stores
  53535. ** information used by checkpoint.
  53536. **
  53537. ** nBackfill is the number of frames in the WAL that have been written
  53538. ** back into the database. (We call the act of moving content from WAL to
  53539. ** database "backfilling".) The nBackfill number is never greater than
  53540. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  53541. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  53542. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  53543. ** mxFrame back to zero when the WAL is reset.
  53544. **
  53545. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  53546. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  53547. ** the nBackfillAttempted is set before any backfilling is done and the
  53548. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  53549. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  53550. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  53551. **
  53552. ** The aLock[] field is a set of bytes used for locking. These bytes should
  53553. ** never be read or written.
  53554. **
  53555. ** There is one entry in aReadMark[] for each reader lock. If a reader
  53556. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  53557. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  53558. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  53559. ** a special case; its value is never used and it exists as a place-holder
  53560. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  53561. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  53562. ** directly from the database.
  53563. **
  53564. ** The value of aReadMark[K] may only be changed by a thread that
  53565. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  53566. ** aReadMark[K] cannot changed while there is a reader is using that mark
  53567. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  53568. **
  53569. ** The checkpointer may only transfer frames from WAL to database where
  53570. ** the frame numbers are less than or equal to every aReadMark[] that is
  53571. ** in use (that is, every aReadMark[j] for which there is a corresponding
  53572. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  53573. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  53574. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  53575. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  53576. ** in the WAL has been backfilled into the database) then new readers
  53577. ** will choose aReadMark[0] which has value 0 and hence such reader will
  53578. ** get all their all content directly from the database file and ignore
  53579. ** the WAL.
  53580. **
  53581. ** Writers normally append new frames to the end of the WAL. However,
  53582. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  53583. ** written back into the database) and if no readers are using the WAL
  53584. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  53585. ** the writer will first "reset" the WAL back to the beginning and start
  53586. ** writing new content beginning at frame 1.
  53587. **
  53588. ** We assume that 32-bit loads are atomic and so no locks are needed in
  53589. ** order to read from any aReadMark[] entries.
  53590. */
  53591. struct WalCkptInfo {
  53592. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  53593. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  53594. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  53595. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  53596. u32 notUsed0; /* Available for future enhancements */
  53597. };
  53598. #define READMARK_NOT_USED 0xffffffff
  53599. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  53600. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  53601. ** only support mandatory file-locks, we do not read or write data
  53602. ** from the region of the file on which locks are applied.
  53603. */
  53604. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  53605. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  53606. /* Size of header before each frame in wal */
  53607. #define WAL_FRAME_HDRSIZE 24
  53608. /* Size of write ahead log header, including checksum. */
  53609. #define WAL_HDRSIZE 32
  53610. /* WAL magic value. Either this value, or the same value with the least
  53611. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  53612. ** big-endian format in the first 4 bytes of a WAL file.
  53613. **
  53614. ** If the LSB is set, then the checksums for each frame within the WAL
  53615. ** file are calculated by treating all data as an array of 32-bit
  53616. ** big-endian words. Otherwise, they are calculated by interpreting
  53617. ** all data as 32-bit little-endian words.
  53618. */
  53619. #define WAL_MAGIC 0x377f0682
  53620. /*
  53621. ** Return the offset of frame iFrame in the write-ahead log file,
  53622. ** assuming a database page size of szPage bytes. The offset returned
  53623. ** is to the start of the write-ahead log frame-header.
  53624. */
  53625. #define walFrameOffset(iFrame, szPage) ( \
  53626. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  53627. )
  53628. /*
  53629. ** An open write-ahead log file is represented by an instance of the
  53630. ** following object.
  53631. */
  53632. struct Wal {
  53633. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  53634. sqlite3_file *pDbFd; /* File handle for the database file */
  53635. sqlite3_file *pWalFd; /* File handle for WAL file */
  53636. u32 iCallback; /* Value to pass to log callback (or 0) */
  53637. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  53638. int nWiData; /* Size of array apWiData */
  53639. int szFirstBlock; /* Size of first block written to WAL file */
  53640. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  53641. u32 szPage; /* Database page size */
  53642. i16 readLock; /* Which read lock is being held. -1 for none */
  53643. u8 syncFlags; /* Flags to use to sync header writes */
  53644. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  53645. u8 writeLock; /* True if in a write transaction */
  53646. u8 ckptLock; /* True if holding a checkpoint lock */
  53647. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  53648. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  53649. u8 syncHeader; /* Fsync the WAL header if true */
  53650. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  53651. u8 bShmUnreliable; /* SHM content is read-only and unreliable */
  53652. WalIndexHdr hdr; /* Wal-index header for current transaction */
  53653. u32 minFrame; /* Ignore wal frames before this one */
  53654. u32 iReCksum; /* On commit, recalculate checksums from here */
  53655. const char *zWalName; /* Name of WAL file */
  53656. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  53657. #ifdef SQLITE_DEBUG
  53658. u8 lockError; /* True if a locking error has occurred */
  53659. #endif
  53660. #ifdef SQLITE_ENABLE_SNAPSHOT
  53661. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  53662. #endif
  53663. };
  53664. /*
  53665. ** Candidate values for Wal.exclusiveMode.
  53666. */
  53667. #define WAL_NORMAL_MODE 0
  53668. #define WAL_EXCLUSIVE_MODE 1
  53669. #define WAL_HEAPMEMORY_MODE 2
  53670. /*
  53671. ** Possible values for WAL.readOnly
  53672. */
  53673. #define WAL_RDWR 0 /* Normal read/write connection */
  53674. #define WAL_RDONLY 1 /* The WAL file is readonly */
  53675. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  53676. /*
  53677. ** Each page of the wal-index mapping contains a hash-table made up of
  53678. ** an array of HASHTABLE_NSLOT elements of the following type.
  53679. */
  53680. typedef u16 ht_slot;
  53681. /*
  53682. ** This structure is used to implement an iterator that loops through
  53683. ** all frames in the WAL in database page order. Where two or more frames
  53684. ** correspond to the same database page, the iterator visits only the
  53685. ** frame most recently written to the WAL (in other words, the frame with
  53686. ** the largest index).
  53687. **
  53688. ** The internals of this structure are only accessed by:
  53689. **
  53690. ** walIteratorInit() - Create a new iterator,
  53691. ** walIteratorNext() - Step an iterator,
  53692. ** walIteratorFree() - Free an iterator.
  53693. **
  53694. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  53695. */
  53696. struct WalIterator {
  53697. int iPrior; /* Last result returned from the iterator */
  53698. int nSegment; /* Number of entries in aSegment[] */
  53699. struct WalSegment {
  53700. int iNext; /* Next slot in aIndex[] not yet returned */
  53701. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  53702. u32 *aPgno; /* Array of page numbers. */
  53703. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  53704. int iZero; /* Frame number associated with aPgno[0] */
  53705. } aSegment[1]; /* One for every 32KB page in the wal-index */
  53706. };
  53707. /*
  53708. ** Define the parameters of the hash tables in the wal-index file. There
  53709. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  53710. ** wal-index.
  53711. **
  53712. ** Changing any of these constants will alter the wal-index format and
  53713. ** create incompatibilities.
  53714. */
  53715. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  53716. #define HASHTABLE_HASH_1 383 /* Should be prime */
  53717. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  53718. /*
  53719. ** The block of page numbers associated with the first hash-table in a
  53720. ** wal-index is smaller than usual. This is so that there is a complete
  53721. ** hash-table on each aligned 32KB page of the wal-index.
  53722. */
  53723. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  53724. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  53725. #define WALINDEX_PGSZ ( \
  53726. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  53727. )
  53728. /*
  53729. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  53730. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  53731. ** numbered from zero.
  53732. **
  53733. ** If the wal-index is currently smaller the iPage pages then the size
  53734. ** of the wal-index might be increased, but only if it is safe to do
  53735. ** so. It is safe to enlarge the wal-index if pWal->writeLock is true
  53736. ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
  53737. **
  53738. ** If this call is successful, *ppPage is set to point to the wal-index
  53739. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  53740. ** then an SQLite error code is returned and *ppPage is set to 0.
  53741. */
  53742. static SQLITE_NOINLINE int walIndexPageRealloc(
  53743. Wal *pWal, /* The WAL context */
  53744. int iPage, /* The page we seek */
  53745. volatile u32 **ppPage /* Write the page pointer here */
  53746. ){
  53747. int rc = SQLITE_OK;
  53748. /* Enlarge the pWal->apWiData[] array if required */
  53749. if( pWal->nWiData<=iPage ){
  53750. int nByte = sizeof(u32*)*(iPage+1);
  53751. volatile u32 **apNew;
  53752. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  53753. if( !apNew ){
  53754. *ppPage = 0;
  53755. return SQLITE_NOMEM_BKPT;
  53756. }
  53757. memset((void*)&apNew[pWal->nWiData], 0,
  53758. sizeof(u32*)*(iPage+1-pWal->nWiData));
  53759. pWal->apWiData = apNew;
  53760. pWal->nWiData = iPage+1;
  53761. }
  53762. /* Request a pointer to the required page from the VFS */
  53763. assert( pWal->apWiData[iPage]==0 );
  53764. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  53765. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  53766. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
  53767. }else{
  53768. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  53769. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  53770. );
  53771. assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
  53772. testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
  53773. if( (rc&0xff)==SQLITE_READONLY ){
  53774. pWal->readOnly |= WAL_SHM_RDONLY;
  53775. if( rc==SQLITE_READONLY ){
  53776. rc = SQLITE_OK;
  53777. }
  53778. }
  53779. }
  53780. *ppPage = pWal->apWiData[iPage];
  53781. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  53782. return rc;
  53783. }
  53784. static int walIndexPage(
  53785. Wal *pWal, /* The WAL context */
  53786. int iPage, /* The page we seek */
  53787. volatile u32 **ppPage /* Write the page pointer here */
  53788. ){
  53789. if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
  53790. return walIndexPageRealloc(pWal, iPage, ppPage);
  53791. }
  53792. return SQLITE_OK;
  53793. }
  53794. /*
  53795. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  53796. */
  53797. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  53798. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  53799. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  53800. }
  53801. /*
  53802. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  53803. */
  53804. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  53805. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  53806. return (volatile WalIndexHdr*)pWal->apWiData[0];
  53807. }
  53808. /*
  53809. ** The argument to this macro must be of type u32. On a little-endian
  53810. ** architecture, it returns the u32 value that results from interpreting
  53811. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  53812. ** returns the value that would be produced by interpreting the 4 bytes
  53813. ** of the input value as a little-endian integer.
  53814. */
  53815. #define BYTESWAP32(x) ( \
  53816. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  53817. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  53818. )
  53819. /*
  53820. ** Generate or extend an 8 byte checksum based on the data in
  53821. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  53822. ** initial values of 0 and 0 if aIn==NULL).
  53823. **
  53824. ** The checksum is written back into aOut[] before returning.
  53825. **
  53826. ** nByte must be a positive multiple of 8.
  53827. */
  53828. static void walChecksumBytes(
  53829. int nativeCksum, /* True for native byte-order, false for non-native */
  53830. u8 *a, /* Content to be checksummed */
  53831. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  53832. const u32 *aIn, /* Initial checksum value input */
  53833. u32 *aOut /* OUT: Final checksum value output */
  53834. ){
  53835. u32 s1, s2;
  53836. u32 *aData = (u32 *)a;
  53837. u32 *aEnd = (u32 *)&a[nByte];
  53838. if( aIn ){
  53839. s1 = aIn[0];
  53840. s2 = aIn[1];
  53841. }else{
  53842. s1 = s2 = 0;
  53843. }
  53844. assert( nByte>=8 );
  53845. assert( (nByte&0x00000007)==0 );
  53846. if( nativeCksum ){
  53847. do {
  53848. s1 += *aData++ + s2;
  53849. s2 += *aData++ + s1;
  53850. }while( aData<aEnd );
  53851. }else{
  53852. do {
  53853. s1 += BYTESWAP32(aData[0]) + s2;
  53854. s2 += BYTESWAP32(aData[1]) + s1;
  53855. aData += 2;
  53856. }while( aData<aEnd );
  53857. }
  53858. aOut[0] = s1;
  53859. aOut[1] = s2;
  53860. }
  53861. static void walShmBarrier(Wal *pWal){
  53862. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  53863. sqlite3OsShmBarrier(pWal->pDbFd);
  53864. }
  53865. }
  53866. /*
  53867. ** Write the header information in pWal->hdr into the wal-index.
  53868. **
  53869. ** The checksum on pWal->hdr is updated before it is written.
  53870. */
  53871. static void walIndexWriteHdr(Wal *pWal){
  53872. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  53873. const int nCksum = offsetof(WalIndexHdr, aCksum);
  53874. assert( pWal->writeLock );
  53875. pWal->hdr.isInit = 1;
  53876. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  53877. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  53878. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  53879. walShmBarrier(pWal);
  53880. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  53881. }
  53882. /*
  53883. ** This function encodes a single frame header and writes it to a buffer
  53884. ** supplied by the caller. A frame-header is made up of a series of
  53885. ** 4-byte big-endian integers, as follows:
  53886. **
  53887. ** 0: Page number.
  53888. ** 4: For commit records, the size of the database image in pages
  53889. ** after the commit. For all other records, zero.
  53890. ** 8: Salt-1 (copied from the wal-header)
  53891. ** 12: Salt-2 (copied from the wal-header)
  53892. ** 16: Checksum-1.
  53893. ** 20: Checksum-2.
  53894. */
  53895. static void walEncodeFrame(
  53896. Wal *pWal, /* The write-ahead log */
  53897. u32 iPage, /* Database page number for frame */
  53898. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  53899. u8 *aData, /* Pointer to page data */
  53900. u8 *aFrame /* OUT: Write encoded frame here */
  53901. ){
  53902. int nativeCksum; /* True for native byte-order checksums */
  53903. u32 *aCksum = pWal->hdr.aFrameCksum;
  53904. assert( WAL_FRAME_HDRSIZE==24 );
  53905. sqlite3Put4byte(&aFrame[0], iPage);
  53906. sqlite3Put4byte(&aFrame[4], nTruncate);
  53907. if( pWal->iReCksum==0 ){
  53908. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  53909. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  53910. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  53911. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  53912. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  53913. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  53914. }else{
  53915. memset(&aFrame[8], 0, 16);
  53916. }
  53917. }
  53918. /*
  53919. ** Check to see if the frame with header in aFrame[] and content
  53920. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  53921. ** *pnTruncate and return true. Return if the frame is not valid.
  53922. */
  53923. static int walDecodeFrame(
  53924. Wal *pWal, /* The write-ahead log */
  53925. u32 *piPage, /* OUT: Database page number for frame */
  53926. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  53927. u8 *aData, /* Pointer to page data (for checksum) */
  53928. u8 *aFrame /* Frame data */
  53929. ){
  53930. int nativeCksum; /* True for native byte-order checksums */
  53931. u32 *aCksum = pWal->hdr.aFrameCksum;
  53932. u32 pgno; /* Page number of the frame */
  53933. assert( WAL_FRAME_HDRSIZE==24 );
  53934. /* A frame is only valid if the salt values in the frame-header
  53935. ** match the salt values in the wal-header.
  53936. */
  53937. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  53938. return 0;
  53939. }
  53940. /* A frame is only valid if the page number is creater than zero.
  53941. */
  53942. pgno = sqlite3Get4byte(&aFrame[0]);
  53943. if( pgno==0 ){
  53944. return 0;
  53945. }
  53946. /* A frame is only valid if a checksum of the WAL header,
  53947. ** all prior frams, the first 16 bytes of this frame-header,
  53948. ** and the frame-data matches the checksum in the last 8
  53949. ** bytes of this frame-header.
  53950. */
  53951. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  53952. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  53953. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  53954. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  53955. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  53956. ){
  53957. /* Checksum failed. */
  53958. return 0;
  53959. }
  53960. /* If we reach this point, the frame is valid. Return the page number
  53961. ** and the new database size.
  53962. */
  53963. *piPage = pgno;
  53964. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  53965. return 1;
  53966. }
  53967. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  53968. /*
  53969. ** Names of locks. This routine is used to provide debugging output and is not
  53970. ** a part of an ordinary build.
  53971. */
  53972. static const char *walLockName(int lockIdx){
  53973. if( lockIdx==WAL_WRITE_LOCK ){
  53974. return "WRITE-LOCK";
  53975. }else if( lockIdx==WAL_CKPT_LOCK ){
  53976. return "CKPT-LOCK";
  53977. }else if( lockIdx==WAL_RECOVER_LOCK ){
  53978. return "RECOVER-LOCK";
  53979. }else{
  53980. static char zName[15];
  53981. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  53982. lockIdx-WAL_READ_LOCK(0));
  53983. return zName;
  53984. }
  53985. }
  53986. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  53987. /*
  53988. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  53989. ** A lock cannot be moved directly between shared and exclusive - it must go
  53990. ** through the unlocked state first.
  53991. **
  53992. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  53993. */
  53994. static int walLockShared(Wal *pWal, int lockIdx){
  53995. int rc;
  53996. if( pWal->exclusiveMode ) return SQLITE_OK;
  53997. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  53998. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  53999. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  54000. walLockName(lockIdx), rc ? "failed" : "ok"));
  54001. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  54002. return rc;
  54003. }
  54004. static void walUnlockShared(Wal *pWal, int lockIdx){
  54005. if( pWal->exclusiveMode ) return;
  54006. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  54007. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  54008. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  54009. }
  54010. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  54011. int rc;
  54012. if( pWal->exclusiveMode ) return SQLITE_OK;
  54013. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  54014. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  54015. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  54016. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  54017. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  54018. return rc;
  54019. }
  54020. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  54021. if( pWal->exclusiveMode ) return;
  54022. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  54023. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  54024. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  54025. walLockName(lockIdx), n));
  54026. }
  54027. /*
  54028. ** Compute a hash on a page number. The resulting hash value must land
  54029. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  54030. ** the hash to the next value in the event of a collision.
  54031. */
  54032. static int walHash(u32 iPage){
  54033. assert( iPage>0 );
  54034. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  54035. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  54036. }
  54037. static int walNextHash(int iPriorHash){
  54038. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  54039. }
  54040. /*
  54041. ** Return pointers to the hash table and page number array stored on
  54042. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  54043. ** numbered starting from 0.
  54044. **
  54045. ** Set output variable *paHash to point to the start of the hash table
  54046. ** in the wal-index file. Set *piZero to one less than the frame
  54047. ** number of the first frame indexed by this hash table. If a
  54048. ** slot in the hash table is set to N, it refers to frame number
  54049. ** (*piZero+N) in the log.
  54050. **
  54051. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  54052. ** first frame indexed by the hash table, frame (*piZero+1).
  54053. */
  54054. static int walHashGet(
  54055. Wal *pWal, /* WAL handle */
  54056. int iHash, /* Find the iHash'th table */
  54057. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  54058. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  54059. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  54060. ){
  54061. int rc; /* Return code */
  54062. volatile u32 *aPgno;
  54063. rc = walIndexPage(pWal, iHash, &aPgno);
  54064. assert( rc==SQLITE_OK || iHash>0 );
  54065. if( rc==SQLITE_OK ){
  54066. u32 iZero;
  54067. volatile ht_slot *aHash;
  54068. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  54069. if( iHash==0 ){
  54070. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  54071. iZero = 0;
  54072. }else{
  54073. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  54074. }
  54075. *paPgno = &aPgno[-1];
  54076. *paHash = aHash;
  54077. *piZero = iZero;
  54078. }
  54079. return rc;
  54080. }
  54081. /*
  54082. ** Return the number of the wal-index page that contains the hash-table
  54083. ** and page-number array that contain entries corresponding to WAL frame
  54084. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  54085. ** are numbered starting from 0.
  54086. */
  54087. static int walFramePage(u32 iFrame){
  54088. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  54089. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  54090. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  54091. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  54092. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  54093. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  54094. );
  54095. return iHash;
  54096. }
  54097. /*
  54098. ** Return the page number associated with frame iFrame in this WAL.
  54099. */
  54100. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  54101. int iHash = walFramePage(iFrame);
  54102. if( iHash==0 ){
  54103. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  54104. }
  54105. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  54106. }
  54107. /*
  54108. ** Remove entries from the hash table that point to WAL slots greater
  54109. ** than pWal->hdr.mxFrame.
  54110. **
  54111. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  54112. ** to a rollback or savepoint.
  54113. **
  54114. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  54115. ** updated. Any later hash tables will be automatically cleared when
  54116. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  54117. ** actually needed.
  54118. */
  54119. static void walCleanupHash(Wal *pWal){
  54120. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  54121. volatile u32 *aPgno = 0; /* Page number array for hash table */
  54122. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  54123. int iLimit = 0; /* Zero values greater than this */
  54124. int nByte; /* Number of bytes to zero in aPgno[] */
  54125. int i; /* Used to iterate through aHash[] */
  54126. assert( pWal->writeLock );
  54127. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  54128. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  54129. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  54130. if( pWal->hdr.mxFrame==0 ) return;
  54131. /* Obtain pointers to the hash-table and page-number array containing
  54132. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  54133. ** that the page said hash-table and array reside on is already mapped.
  54134. */
  54135. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  54136. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  54137. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  54138. /* Zero all hash-table entries that correspond to frame numbers greater
  54139. ** than pWal->hdr.mxFrame.
  54140. */
  54141. iLimit = pWal->hdr.mxFrame - iZero;
  54142. assert( iLimit>0 );
  54143. for(i=0; i<HASHTABLE_NSLOT; i++){
  54144. if( aHash[i]>iLimit ){
  54145. aHash[i] = 0;
  54146. }
  54147. }
  54148. /* Zero the entries in the aPgno array that correspond to frames with
  54149. ** frame numbers greater than pWal->hdr.mxFrame.
  54150. */
  54151. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  54152. memset((void *)&aPgno[iLimit+1], 0, nByte);
  54153. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  54154. /* Verify that the every entry in the mapping region is still reachable
  54155. ** via the hash table even after the cleanup.
  54156. */
  54157. if( iLimit ){
  54158. int j; /* Loop counter */
  54159. int iKey; /* Hash key */
  54160. for(j=1; j<=iLimit; j++){
  54161. for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
  54162. if( aHash[iKey]==j ) break;
  54163. }
  54164. assert( aHash[iKey]==j );
  54165. }
  54166. }
  54167. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  54168. }
  54169. /*
  54170. ** Set an entry in the wal-index that will map database page number
  54171. ** pPage into WAL frame iFrame.
  54172. */
  54173. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  54174. int rc; /* Return code */
  54175. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  54176. volatile u32 *aPgno = 0; /* Page number array */
  54177. volatile ht_slot *aHash = 0; /* Hash table */
  54178. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  54179. /* Assuming the wal-index file was successfully mapped, populate the
  54180. ** page number array and hash table entry.
  54181. */
  54182. if( rc==SQLITE_OK ){
  54183. int iKey; /* Hash table key */
  54184. int idx; /* Value to write to hash-table slot */
  54185. int nCollide; /* Number of hash collisions */
  54186. idx = iFrame - iZero;
  54187. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  54188. /* If this is the first entry to be added to this hash-table, zero the
  54189. ** entire hash table and aPgno[] array before proceeding.
  54190. */
  54191. if( idx==1 ){
  54192. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  54193. memset((void*)&aPgno[1], 0, nByte);
  54194. }
  54195. /* If the entry in aPgno[] is already set, then the previous writer
  54196. ** must have exited unexpectedly in the middle of a transaction (after
  54197. ** writing one or more dirty pages to the WAL to free up memory).
  54198. ** Remove the remnants of that writers uncommitted transaction from
  54199. ** the hash-table before writing any new entries.
  54200. */
  54201. if( aPgno[idx] ){
  54202. walCleanupHash(pWal);
  54203. assert( !aPgno[idx] );
  54204. }
  54205. /* Write the aPgno[] array entry and the hash-table slot. */
  54206. nCollide = idx;
  54207. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  54208. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  54209. }
  54210. aPgno[idx] = iPage;
  54211. aHash[iKey] = (ht_slot)idx;
  54212. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  54213. /* Verify that the number of entries in the hash table exactly equals
  54214. ** the number of entries in the mapping region.
  54215. */
  54216. {
  54217. int i; /* Loop counter */
  54218. int nEntry = 0; /* Number of entries in the hash table */
  54219. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  54220. assert( nEntry==idx );
  54221. }
  54222. /* Verify that the every entry in the mapping region is reachable
  54223. ** via the hash table. This turns out to be a really, really expensive
  54224. ** thing to check, so only do this occasionally - not on every
  54225. ** iteration.
  54226. */
  54227. if( (idx&0x3ff)==0 ){
  54228. int i; /* Loop counter */
  54229. for(i=1; i<=idx; i++){
  54230. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  54231. if( aHash[iKey]==i ) break;
  54232. }
  54233. assert( aHash[iKey]==i );
  54234. }
  54235. }
  54236. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  54237. }
  54238. return rc;
  54239. }
  54240. /*
  54241. ** Recover the wal-index by reading the write-ahead log file.
  54242. **
  54243. ** This routine first tries to establish an exclusive lock on the
  54244. ** wal-index to prevent other threads/processes from doing anything
  54245. ** with the WAL or wal-index while recovery is running. The
  54246. ** WAL_RECOVER_LOCK is also held so that other threads will know
  54247. ** that this thread is running recovery. If unable to establish
  54248. ** the necessary locks, this routine returns SQLITE_BUSY.
  54249. */
  54250. static int walIndexRecover(Wal *pWal){
  54251. int rc; /* Return Code */
  54252. i64 nSize; /* Size of log file */
  54253. u32 aFrameCksum[2] = {0, 0};
  54254. int iLock; /* Lock offset to lock for checkpoint */
  54255. /* Obtain an exclusive lock on all byte in the locking range not already
  54256. ** locked by the caller. The caller is guaranteed to have locked the
  54257. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  54258. ** If successful, the same bytes that are locked here are unlocked before
  54259. ** this function returns.
  54260. */
  54261. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  54262. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  54263. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  54264. assert( pWal->writeLock );
  54265. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  54266. rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  54267. if( rc==SQLITE_OK ){
  54268. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  54269. if( rc!=SQLITE_OK ){
  54270. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  54271. }
  54272. }
  54273. if( rc ){
  54274. return rc;
  54275. }
  54276. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  54277. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  54278. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  54279. if( rc!=SQLITE_OK ){
  54280. goto recovery_error;
  54281. }
  54282. if( nSize>WAL_HDRSIZE ){
  54283. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  54284. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  54285. int szFrame; /* Number of bytes in buffer aFrame[] */
  54286. u8 *aData; /* Pointer to data part of aFrame buffer */
  54287. int iFrame; /* Index of last frame read */
  54288. i64 iOffset; /* Next offset to read from log file */
  54289. int szPage; /* Page size according to the log */
  54290. u32 magic; /* Magic value read from WAL header */
  54291. u32 version; /* Magic value read from WAL header */
  54292. int isValid; /* True if this frame is valid */
  54293. /* Read in the WAL header. */
  54294. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  54295. if( rc!=SQLITE_OK ){
  54296. goto recovery_error;
  54297. }
  54298. /* If the database page size is not a power of two, or is greater than
  54299. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  54300. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  54301. ** WAL file.
  54302. */
  54303. magic = sqlite3Get4byte(&aBuf[0]);
  54304. szPage = sqlite3Get4byte(&aBuf[8]);
  54305. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  54306. || szPage&(szPage-1)
  54307. || szPage>SQLITE_MAX_PAGE_SIZE
  54308. || szPage<512
  54309. ){
  54310. goto finished;
  54311. }
  54312. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  54313. pWal->szPage = szPage;
  54314. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  54315. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  54316. /* Verify that the WAL header checksum is correct */
  54317. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  54318. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  54319. );
  54320. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  54321. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  54322. ){
  54323. goto finished;
  54324. }
  54325. /* Verify that the version number on the WAL format is one that
  54326. ** are able to understand */
  54327. version = sqlite3Get4byte(&aBuf[4]);
  54328. if( version!=WAL_MAX_VERSION ){
  54329. rc = SQLITE_CANTOPEN_BKPT;
  54330. goto finished;
  54331. }
  54332. /* Malloc a buffer to read frames into. */
  54333. szFrame = szPage + WAL_FRAME_HDRSIZE;
  54334. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  54335. if( !aFrame ){
  54336. rc = SQLITE_NOMEM_BKPT;
  54337. goto recovery_error;
  54338. }
  54339. aData = &aFrame[WAL_FRAME_HDRSIZE];
  54340. /* Read all frames from the log file. */
  54341. iFrame = 0;
  54342. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  54343. u32 pgno; /* Database page number for frame */
  54344. u32 nTruncate; /* dbsize field from frame header */
  54345. /* Read and decode the next log frame. */
  54346. iFrame++;
  54347. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  54348. if( rc!=SQLITE_OK ) break;
  54349. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  54350. if( !isValid ) break;
  54351. rc = walIndexAppend(pWal, iFrame, pgno);
  54352. if( rc!=SQLITE_OK ) break;
  54353. /* If nTruncate is non-zero, this is a commit record. */
  54354. if( nTruncate ){
  54355. pWal->hdr.mxFrame = iFrame;
  54356. pWal->hdr.nPage = nTruncate;
  54357. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  54358. testcase( szPage<=32768 );
  54359. testcase( szPage>=65536 );
  54360. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  54361. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  54362. }
  54363. }
  54364. sqlite3_free(aFrame);
  54365. }
  54366. finished:
  54367. if( rc==SQLITE_OK ){
  54368. volatile WalCkptInfo *pInfo;
  54369. int i;
  54370. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  54371. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  54372. walIndexWriteHdr(pWal);
  54373. /* Reset the checkpoint-header. This is safe because this thread is
  54374. ** currently holding locks that exclude all other readers, writers and
  54375. ** checkpointers.
  54376. */
  54377. pInfo = walCkptInfo(pWal);
  54378. pInfo->nBackfill = 0;
  54379. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  54380. pInfo->aReadMark[0] = 0;
  54381. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  54382. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  54383. /* If more than one frame was recovered from the log file, report an
  54384. ** event via sqlite3_log(). This is to help with identifying performance
  54385. ** problems caused by applications routinely shutting down without
  54386. ** checkpointing the log file.
  54387. */
  54388. if( pWal->hdr.nPage ){
  54389. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  54390. "recovered %d frames from WAL file %s",
  54391. pWal->hdr.mxFrame, pWal->zWalName
  54392. );
  54393. }
  54394. }
  54395. recovery_error:
  54396. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  54397. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  54398. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  54399. return rc;
  54400. }
  54401. /*
  54402. ** Close an open wal-index.
  54403. */
  54404. static void walIndexClose(Wal *pWal, int isDelete){
  54405. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
  54406. int i;
  54407. for(i=0; i<pWal->nWiData; i++){
  54408. sqlite3_free((void *)pWal->apWiData[i]);
  54409. pWal->apWiData[i] = 0;
  54410. }
  54411. }
  54412. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  54413. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  54414. }
  54415. }
  54416. /*
  54417. ** Open a connection to the WAL file zWalName. The database file must
  54418. ** already be opened on connection pDbFd. The buffer that zWalName points
  54419. ** to must remain valid for the lifetime of the returned Wal* handle.
  54420. **
  54421. ** A SHARED lock should be held on the database file when this function
  54422. ** is called. The purpose of this SHARED lock is to prevent any other
  54423. ** client from unlinking the WAL or wal-index file. If another process
  54424. ** were to do this just after this client opened one of these files, the
  54425. ** system would be badly broken.
  54426. **
  54427. ** If the log file is successfully opened, SQLITE_OK is returned and
  54428. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  54429. ** an SQLite error code is returned and *ppWal is left unmodified.
  54430. */
  54431. SQLITE_PRIVATE int sqlite3WalOpen(
  54432. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  54433. sqlite3_file *pDbFd, /* The open database file */
  54434. const char *zWalName, /* Name of the WAL file */
  54435. int bNoShm, /* True to run in heap-memory mode */
  54436. i64 mxWalSize, /* Truncate WAL to this size on reset */
  54437. Wal **ppWal /* OUT: Allocated Wal handle */
  54438. ){
  54439. int rc; /* Return Code */
  54440. Wal *pRet; /* Object to allocate and return */
  54441. int flags; /* Flags passed to OsOpen() */
  54442. assert( zWalName && zWalName[0] );
  54443. assert( pDbFd );
  54444. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  54445. ** this source file. Verify that the #defines of the locking byte offsets
  54446. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  54447. ** For that matter, if the lock offset ever changes from its initial design
  54448. ** value of 120, we need to know that so there is an assert() to check it.
  54449. */
  54450. assert( 120==WALINDEX_LOCK_OFFSET );
  54451. assert( 136==WALINDEX_HDR_SIZE );
  54452. #ifdef WIN_SHM_BASE
  54453. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  54454. #endif
  54455. #ifdef UNIX_SHM_BASE
  54456. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  54457. #endif
  54458. /* Allocate an instance of struct Wal to return. */
  54459. *ppWal = 0;
  54460. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  54461. if( !pRet ){
  54462. return SQLITE_NOMEM_BKPT;
  54463. }
  54464. pRet->pVfs = pVfs;
  54465. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  54466. pRet->pDbFd = pDbFd;
  54467. pRet->readLock = -1;
  54468. pRet->mxWalSize = mxWalSize;
  54469. pRet->zWalName = zWalName;
  54470. pRet->syncHeader = 1;
  54471. pRet->padToSectorBoundary = 1;
  54472. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  54473. /* Open file handle on the write-ahead log file. */
  54474. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  54475. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  54476. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  54477. pRet->readOnly = WAL_RDONLY;
  54478. }
  54479. if( rc!=SQLITE_OK ){
  54480. walIndexClose(pRet, 0);
  54481. sqlite3OsClose(pRet->pWalFd);
  54482. sqlite3_free(pRet);
  54483. }else{
  54484. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  54485. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  54486. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  54487. pRet->padToSectorBoundary = 0;
  54488. }
  54489. *ppWal = pRet;
  54490. WALTRACE(("WAL%d: opened\n", pRet));
  54491. }
  54492. return rc;
  54493. }
  54494. /*
  54495. ** Change the size to which the WAL file is trucated on each reset.
  54496. */
  54497. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  54498. if( pWal ) pWal->mxWalSize = iLimit;
  54499. }
  54500. /*
  54501. ** Find the smallest page number out of all pages held in the WAL that
  54502. ** has not been returned by any prior invocation of this method on the
  54503. ** same WalIterator object. Write into *piFrame the frame index where
  54504. ** that page was last written into the WAL. Write into *piPage the page
  54505. ** number.
  54506. **
  54507. ** Return 0 on success. If there are no pages in the WAL with a page
  54508. ** number larger than *piPage, then return 1.
  54509. */
  54510. static int walIteratorNext(
  54511. WalIterator *p, /* Iterator */
  54512. u32 *piPage, /* OUT: The page number of the next page */
  54513. u32 *piFrame /* OUT: Wal frame index of next page */
  54514. ){
  54515. u32 iMin; /* Result pgno must be greater than iMin */
  54516. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  54517. int i; /* For looping through segments */
  54518. iMin = p->iPrior;
  54519. assert( iMin<0xffffffff );
  54520. for(i=p->nSegment-1; i>=0; i--){
  54521. struct WalSegment *pSegment = &p->aSegment[i];
  54522. while( pSegment->iNext<pSegment->nEntry ){
  54523. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  54524. if( iPg>iMin ){
  54525. if( iPg<iRet ){
  54526. iRet = iPg;
  54527. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  54528. }
  54529. break;
  54530. }
  54531. pSegment->iNext++;
  54532. }
  54533. }
  54534. *piPage = p->iPrior = iRet;
  54535. return (iRet==0xFFFFFFFF);
  54536. }
  54537. /*
  54538. ** This function merges two sorted lists into a single sorted list.
  54539. **
  54540. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  54541. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  54542. ** is guaranteed for all J<K:
  54543. **
  54544. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  54545. ** aContent[aRight[J]] < aContent[aRight[K]]
  54546. **
  54547. ** This routine overwrites aRight[] with a new (probably longer) sequence
  54548. ** of indices such that the aRight[] contains every index that appears in
  54549. ** either aLeft[] or the old aRight[] and such that the second condition
  54550. ** above is still met.
  54551. **
  54552. ** The aContent[aLeft[X]] values will be unique for all X. And the
  54553. ** aContent[aRight[X]] values will be unique too. But there might be
  54554. ** one or more combinations of X and Y such that
  54555. **
  54556. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  54557. **
  54558. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  54559. */
  54560. static void walMerge(
  54561. const u32 *aContent, /* Pages in wal - keys for the sort */
  54562. ht_slot *aLeft, /* IN: Left hand input list */
  54563. int nLeft, /* IN: Elements in array *paLeft */
  54564. ht_slot **paRight, /* IN/OUT: Right hand input list */
  54565. int *pnRight, /* IN/OUT: Elements in *paRight */
  54566. ht_slot *aTmp /* Temporary buffer */
  54567. ){
  54568. int iLeft = 0; /* Current index in aLeft */
  54569. int iRight = 0; /* Current index in aRight */
  54570. int iOut = 0; /* Current index in output buffer */
  54571. int nRight = *pnRight;
  54572. ht_slot *aRight = *paRight;
  54573. assert( nLeft>0 && nRight>0 );
  54574. while( iRight<nRight || iLeft<nLeft ){
  54575. ht_slot logpage;
  54576. Pgno dbpage;
  54577. if( (iLeft<nLeft)
  54578. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  54579. ){
  54580. logpage = aLeft[iLeft++];
  54581. }else{
  54582. logpage = aRight[iRight++];
  54583. }
  54584. dbpage = aContent[logpage];
  54585. aTmp[iOut++] = logpage;
  54586. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  54587. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  54588. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  54589. }
  54590. *paRight = aLeft;
  54591. *pnRight = iOut;
  54592. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  54593. }
  54594. /*
  54595. ** Sort the elements in list aList using aContent[] as the sort key.
  54596. ** Remove elements with duplicate keys, preferring to keep the
  54597. ** larger aList[] values.
  54598. **
  54599. ** The aList[] entries are indices into aContent[]. The values in
  54600. ** aList[] are to be sorted so that for all J<K:
  54601. **
  54602. ** aContent[aList[J]] < aContent[aList[K]]
  54603. **
  54604. ** For any X and Y such that
  54605. **
  54606. ** aContent[aList[X]] == aContent[aList[Y]]
  54607. **
  54608. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  54609. ** the smaller.
  54610. */
  54611. static void walMergesort(
  54612. const u32 *aContent, /* Pages in wal */
  54613. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  54614. ht_slot *aList, /* IN/OUT: List to sort */
  54615. int *pnList /* IN/OUT: Number of elements in aList[] */
  54616. ){
  54617. struct Sublist {
  54618. int nList; /* Number of elements in aList */
  54619. ht_slot *aList; /* Pointer to sub-list content */
  54620. };
  54621. const int nList = *pnList; /* Size of input list */
  54622. int nMerge = 0; /* Number of elements in list aMerge */
  54623. ht_slot *aMerge = 0; /* List to be merged */
  54624. int iList; /* Index into input list */
  54625. u32 iSub = 0; /* Index into aSub array */
  54626. struct Sublist aSub[13]; /* Array of sub-lists */
  54627. memset(aSub, 0, sizeof(aSub));
  54628. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  54629. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  54630. for(iList=0; iList<nList; iList++){
  54631. nMerge = 1;
  54632. aMerge = &aList[iList];
  54633. for(iSub=0; iList & (1<<iSub); iSub++){
  54634. struct Sublist *p;
  54635. assert( iSub<ArraySize(aSub) );
  54636. p = &aSub[iSub];
  54637. assert( p->aList && p->nList<=(1<<iSub) );
  54638. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  54639. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  54640. }
  54641. aSub[iSub].aList = aMerge;
  54642. aSub[iSub].nList = nMerge;
  54643. }
  54644. for(iSub++; iSub<ArraySize(aSub); iSub++){
  54645. if( nList & (1<<iSub) ){
  54646. struct Sublist *p;
  54647. assert( iSub<ArraySize(aSub) );
  54648. p = &aSub[iSub];
  54649. assert( p->nList<=(1<<iSub) );
  54650. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  54651. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  54652. }
  54653. }
  54654. assert( aMerge==aList );
  54655. *pnList = nMerge;
  54656. #ifdef SQLITE_DEBUG
  54657. {
  54658. int i;
  54659. for(i=1; i<*pnList; i++){
  54660. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  54661. }
  54662. }
  54663. #endif
  54664. }
  54665. /*
  54666. ** Free an iterator allocated by walIteratorInit().
  54667. */
  54668. static void walIteratorFree(WalIterator *p){
  54669. sqlite3_free(p);
  54670. }
  54671. /*
  54672. ** Construct a WalInterator object that can be used to loop over all
  54673. ** pages in the WAL following frame nBackfill in ascending order. Frames
  54674. ** nBackfill or earlier may be included - excluding them is an optimization
  54675. ** only. The caller must hold the checkpoint lock.
  54676. **
  54677. ** On success, make *pp point to the newly allocated WalInterator object
  54678. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  54679. ** returns an error, the value of *pp is undefined.
  54680. **
  54681. ** The calling routine should invoke walIteratorFree() to destroy the
  54682. ** WalIterator object when it has finished with it.
  54683. */
  54684. static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
  54685. WalIterator *p; /* Return value */
  54686. int nSegment; /* Number of segments to merge */
  54687. u32 iLast; /* Last frame in log */
  54688. int nByte; /* Number of bytes to allocate */
  54689. int i; /* Iterator variable */
  54690. ht_slot *aTmp; /* Temp space used by merge-sort */
  54691. int rc = SQLITE_OK; /* Return Code */
  54692. /* This routine only runs while holding the checkpoint lock. And
  54693. ** it only runs if there is actually content in the log (mxFrame>0).
  54694. */
  54695. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  54696. iLast = pWal->hdr.mxFrame;
  54697. /* Allocate space for the WalIterator object. */
  54698. nSegment = walFramePage(iLast) + 1;
  54699. nByte = sizeof(WalIterator)
  54700. + (nSegment-1)*sizeof(struct WalSegment)
  54701. + iLast*sizeof(ht_slot);
  54702. p = (WalIterator *)sqlite3_malloc64(nByte);
  54703. if( !p ){
  54704. return SQLITE_NOMEM_BKPT;
  54705. }
  54706. memset(p, 0, nByte);
  54707. p->nSegment = nSegment;
  54708. /* Allocate temporary space used by the merge-sort routine. This block
  54709. ** of memory will be freed before this function returns.
  54710. */
  54711. aTmp = (ht_slot *)sqlite3_malloc64(
  54712. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  54713. );
  54714. if( !aTmp ){
  54715. rc = SQLITE_NOMEM_BKPT;
  54716. }
  54717. for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
  54718. volatile ht_slot *aHash;
  54719. u32 iZero;
  54720. volatile u32 *aPgno;
  54721. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  54722. if( rc==SQLITE_OK ){
  54723. int j; /* Counter variable */
  54724. int nEntry; /* Number of entries in this segment */
  54725. ht_slot *aIndex; /* Sorted index for this segment */
  54726. aPgno++;
  54727. if( (i+1)==nSegment ){
  54728. nEntry = (int)(iLast - iZero);
  54729. }else{
  54730. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  54731. }
  54732. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  54733. iZero++;
  54734. for(j=0; j<nEntry; j++){
  54735. aIndex[j] = (ht_slot)j;
  54736. }
  54737. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  54738. p->aSegment[i].iZero = iZero;
  54739. p->aSegment[i].nEntry = nEntry;
  54740. p->aSegment[i].aIndex = aIndex;
  54741. p->aSegment[i].aPgno = (u32 *)aPgno;
  54742. }
  54743. }
  54744. sqlite3_free(aTmp);
  54745. if( rc!=SQLITE_OK ){
  54746. walIteratorFree(p);
  54747. p = 0;
  54748. }
  54749. *pp = p;
  54750. return rc;
  54751. }
  54752. /*
  54753. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  54754. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  54755. ** busy-handler function. Invoke it and retry the lock until either the
  54756. ** lock is successfully obtained or the busy-handler returns 0.
  54757. */
  54758. static int walBusyLock(
  54759. Wal *pWal, /* WAL connection */
  54760. int (*xBusy)(void*), /* Function to call when busy */
  54761. void *pBusyArg, /* Context argument for xBusyHandler */
  54762. int lockIdx, /* Offset of first byte to lock */
  54763. int n /* Number of bytes to lock */
  54764. ){
  54765. int rc;
  54766. do {
  54767. rc = walLockExclusive(pWal, lockIdx, n);
  54768. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  54769. return rc;
  54770. }
  54771. /*
  54772. ** The cache of the wal-index header must be valid to call this function.
  54773. ** Return the page-size in bytes used by the database.
  54774. */
  54775. static int walPagesize(Wal *pWal){
  54776. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  54777. }
  54778. /*
  54779. ** The following is guaranteed when this function is called:
  54780. **
  54781. ** a) the WRITER lock is held,
  54782. ** b) the entire log file has been checkpointed, and
  54783. ** c) any existing readers are reading exclusively from the database
  54784. ** file - there are no readers that may attempt to read a frame from
  54785. ** the log file.
  54786. **
  54787. ** This function updates the shared-memory structures so that the next
  54788. ** client to write to the database (which may be this one) does so by
  54789. ** writing frames into the start of the log file.
  54790. **
  54791. ** The value of parameter salt1 is used as the aSalt[1] value in the
  54792. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  54793. ** one obtained from sqlite3_randomness()).
  54794. */
  54795. static void walRestartHdr(Wal *pWal, u32 salt1){
  54796. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  54797. int i; /* Loop counter */
  54798. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  54799. pWal->nCkpt++;
  54800. pWal->hdr.mxFrame = 0;
  54801. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  54802. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  54803. walIndexWriteHdr(pWal);
  54804. pInfo->nBackfill = 0;
  54805. pInfo->nBackfillAttempted = 0;
  54806. pInfo->aReadMark[1] = 0;
  54807. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  54808. assert( pInfo->aReadMark[0]==0 );
  54809. }
  54810. /*
  54811. ** Copy as much content as we can from the WAL back into the database file
  54812. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  54813. **
  54814. ** The amount of information copies from WAL to database might be limited
  54815. ** by active readers. This routine will never overwrite a database page
  54816. ** that a concurrent reader might be using.
  54817. **
  54818. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  54819. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  54820. ** checkpoints are always run by a background thread or background
  54821. ** process, foreground threads will never block on a lengthy fsync call.
  54822. **
  54823. ** Fsync is called on the WAL before writing content out of the WAL and
  54824. ** into the database. This ensures that if the new content is persistent
  54825. ** in the WAL and can be recovered following a power-loss or hard reset.
  54826. **
  54827. ** Fsync is also called on the database file if (and only if) the entire
  54828. ** WAL content is copied into the database file. This second fsync makes
  54829. ** it safe to delete the WAL since the new content will persist in the
  54830. ** database file.
  54831. **
  54832. ** This routine uses and updates the nBackfill field of the wal-index header.
  54833. ** This is the only routine that will increase the value of nBackfill.
  54834. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  54835. ** its value.)
  54836. **
  54837. ** The caller must be holding sufficient locks to ensure that no other
  54838. ** checkpoint is running (in any other thread or process) at the same
  54839. ** time.
  54840. */
  54841. static int walCheckpoint(
  54842. Wal *pWal, /* Wal connection */
  54843. sqlite3 *db, /* Check for interrupts on this handle */
  54844. int eMode, /* One of PASSIVE, FULL or RESTART */
  54845. int (*xBusy)(void*), /* Function to call when busy */
  54846. void *pBusyArg, /* Context argument for xBusyHandler */
  54847. int sync_flags, /* Flags for OsSync() (or 0) */
  54848. u8 *zBuf /* Temporary buffer to use */
  54849. ){
  54850. int rc = SQLITE_OK; /* Return code */
  54851. int szPage; /* Database page-size */
  54852. WalIterator *pIter = 0; /* Wal iterator context */
  54853. u32 iDbpage = 0; /* Next database page to write */
  54854. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  54855. u32 mxSafeFrame; /* Max frame that can be backfilled */
  54856. u32 mxPage; /* Max database page to write */
  54857. int i; /* Loop counter */
  54858. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  54859. szPage = walPagesize(pWal);
  54860. testcase( szPage<=32768 );
  54861. testcase( szPage>=65536 );
  54862. pInfo = walCkptInfo(pWal);
  54863. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  54864. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  54865. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  54866. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  54867. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  54868. ** safe to write into the database. Frames beyond mxSafeFrame might
  54869. ** overwrite database pages that are in use by active readers and thus
  54870. ** cannot be backfilled from the WAL.
  54871. */
  54872. mxSafeFrame = pWal->hdr.mxFrame;
  54873. mxPage = pWal->hdr.nPage;
  54874. for(i=1; i<WAL_NREADER; i++){
  54875. /* Thread-sanitizer reports that the following is an unsafe read,
  54876. ** as some other thread may be in the process of updating the value
  54877. ** of the aReadMark[] slot. The assumption here is that if that is
  54878. ** happening, the other client may only be increasing the value,
  54879. ** not decreasing it. So assuming either that either the "old" or
  54880. ** "new" version of the value is read, and not some arbitrary value
  54881. ** that would never be written by a real client, things are still
  54882. ** safe. */
  54883. u32 y = pInfo->aReadMark[i];
  54884. if( mxSafeFrame>y ){
  54885. assert( y<=pWal->hdr.mxFrame );
  54886. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  54887. if( rc==SQLITE_OK ){
  54888. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  54889. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  54890. }else if( rc==SQLITE_BUSY ){
  54891. mxSafeFrame = y;
  54892. xBusy = 0;
  54893. }else{
  54894. goto walcheckpoint_out;
  54895. }
  54896. }
  54897. }
  54898. /* Allocate the iterator */
  54899. if( pInfo->nBackfill<mxSafeFrame ){
  54900. rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
  54901. assert( rc==SQLITE_OK || pIter==0 );
  54902. }
  54903. if( pIter
  54904. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  54905. ){
  54906. i64 nSize; /* Current size of database file */
  54907. u32 nBackfill = pInfo->nBackfill;
  54908. pInfo->nBackfillAttempted = mxSafeFrame;
  54909. /* Sync the WAL to disk */
  54910. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  54911. /* If the database may grow as a result of this checkpoint, hint
  54912. ** about the eventual size of the db file to the VFS layer.
  54913. */
  54914. if( rc==SQLITE_OK ){
  54915. i64 nReq = ((i64)mxPage * szPage);
  54916. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  54917. if( rc==SQLITE_OK && nSize<nReq ){
  54918. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  54919. }
  54920. }
  54921. /* Iterate through the contents of the WAL, copying data to the db file */
  54922. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  54923. i64 iOffset;
  54924. assert( walFramePgno(pWal, iFrame)==iDbpage );
  54925. if( db->u1.isInterrupted ){
  54926. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  54927. break;
  54928. }
  54929. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  54930. continue;
  54931. }
  54932. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  54933. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  54934. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  54935. if( rc!=SQLITE_OK ) break;
  54936. iOffset = (iDbpage-1)*(i64)szPage;
  54937. testcase( IS_BIG_INT(iOffset) );
  54938. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  54939. if( rc!=SQLITE_OK ) break;
  54940. }
  54941. /* If work was actually accomplished... */
  54942. if( rc==SQLITE_OK ){
  54943. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  54944. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  54945. testcase( IS_BIG_INT(szDb) );
  54946. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  54947. if( rc==SQLITE_OK ){
  54948. rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
  54949. }
  54950. }
  54951. if( rc==SQLITE_OK ){
  54952. pInfo->nBackfill = mxSafeFrame;
  54953. }
  54954. }
  54955. /* Release the reader lock held while backfilling */
  54956. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  54957. }
  54958. if( rc==SQLITE_BUSY ){
  54959. /* Reset the return code so as not to report a checkpoint failure
  54960. ** just because there are active readers. */
  54961. rc = SQLITE_OK;
  54962. }
  54963. }
  54964. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  54965. ** entire wal file has been copied into the database file, then block
  54966. ** until all readers have finished using the wal file. This ensures that
  54967. ** the next process to write to the database restarts the wal file.
  54968. */
  54969. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  54970. assert( pWal->writeLock );
  54971. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  54972. rc = SQLITE_BUSY;
  54973. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  54974. u32 salt1;
  54975. sqlite3_randomness(4, &salt1);
  54976. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  54977. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  54978. if( rc==SQLITE_OK ){
  54979. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  54980. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  54981. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  54982. ** truncates the log file to zero bytes just prior to a
  54983. ** successful return.
  54984. **
  54985. ** In theory, it might be safe to do this without updating the
  54986. ** wal-index header in shared memory, as all subsequent reader or
  54987. ** writer clients should see that the entire log file has been
  54988. ** checkpointed and behave accordingly. This seems unsafe though,
  54989. ** as it would leave the system in a state where the contents of
  54990. ** the wal-index header do not match the contents of the
  54991. ** file-system. To avoid this, update the wal-index header to
  54992. ** indicate that the log file contains zero valid frames. */
  54993. walRestartHdr(pWal, salt1);
  54994. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  54995. }
  54996. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  54997. }
  54998. }
  54999. }
  55000. walcheckpoint_out:
  55001. walIteratorFree(pIter);
  55002. return rc;
  55003. }
  55004. /*
  55005. ** If the WAL file is currently larger than nMax bytes in size, truncate
  55006. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  55007. */
  55008. static void walLimitSize(Wal *pWal, i64 nMax){
  55009. i64 sz;
  55010. int rx;
  55011. sqlite3BeginBenignMalloc();
  55012. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  55013. if( rx==SQLITE_OK && (sz > nMax ) ){
  55014. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  55015. }
  55016. sqlite3EndBenignMalloc();
  55017. if( rx ){
  55018. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  55019. }
  55020. }
  55021. /*
  55022. ** Close a connection to a log file.
  55023. */
  55024. SQLITE_PRIVATE int sqlite3WalClose(
  55025. Wal *pWal, /* Wal to close */
  55026. sqlite3 *db, /* For interrupt flag */
  55027. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  55028. int nBuf,
  55029. u8 *zBuf /* Buffer of at least nBuf bytes */
  55030. ){
  55031. int rc = SQLITE_OK;
  55032. if( pWal ){
  55033. int isDelete = 0; /* True to unlink wal and wal-index files */
  55034. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  55035. ** ordinary, rollback-mode locking methods, this guarantees that the
  55036. ** connection associated with this log file is the only connection to
  55037. ** the database. In this case checkpoint the database and unlink both
  55038. ** the wal and wal-index files.
  55039. **
  55040. ** The EXCLUSIVE lock is not released before returning.
  55041. */
  55042. if( zBuf!=0
  55043. && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
  55044. ){
  55045. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  55046. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  55047. }
  55048. rc = sqlite3WalCheckpoint(pWal, db,
  55049. SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  55050. );
  55051. if( rc==SQLITE_OK ){
  55052. int bPersist = -1;
  55053. sqlite3OsFileControlHint(
  55054. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  55055. );
  55056. if( bPersist!=1 ){
  55057. /* Try to delete the WAL file if the checkpoint completed and
  55058. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  55059. ** mode (!bPersist) */
  55060. isDelete = 1;
  55061. }else if( pWal->mxWalSize>=0 ){
  55062. /* Try to truncate the WAL file to zero bytes if the checkpoint
  55063. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  55064. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  55065. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  55066. ** to zero bytes as truncating to the journal_size_limit might
  55067. ** leave a corrupt WAL file on disk. */
  55068. walLimitSize(pWal, 0);
  55069. }
  55070. }
  55071. }
  55072. walIndexClose(pWal, isDelete);
  55073. sqlite3OsClose(pWal->pWalFd);
  55074. if( isDelete ){
  55075. sqlite3BeginBenignMalloc();
  55076. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  55077. sqlite3EndBenignMalloc();
  55078. }
  55079. WALTRACE(("WAL%p: closed\n", pWal));
  55080. sqlite3_free((void *)pWal->apWiData);
  55081. sqlite3_free(pWal);
  55082. }
  55083. return rc;
  55084. }
  55085. /*
  55086. ** Try to read the wal-index header. Return 0 on success and 1 if
  55087. ** there is a problem.
  55088. **
  55089. ** The wal-index is in shared memory. Another thread or process might
  55090. ** be writing the header at the same time this procedure is trying to
  55091. ** read it, which might result in inconsistency. A dirty read is detected
  55092. ** by verifying that both copies of the header are the same and also by
  55093. ** a checksum on the header.
  55094. **
  55095. ** If and only if the read is consistent and the header is different from
  55096. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  55097. ** and *pChanged is set to 1.
  55098. **
  55099. ** If the checksum cannot be verified return non-zero. If the header
  55100. ** is read successfully and the checksum verified, return zero.
  55101. */
  55102. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  55103. u32 aCksum[2]; /* Checksum on the header content */
  55104. WalIndexHdr h1, h2; /* Two copies of the header content */
  55105. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  55106. /* The first page of the wal-index must be mapped at this point. */
  55107. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  55108. /* Read the header. This might happen concurrently with a write to the
  55109. ** same area of shared memory on a different CPU in a SMP,
  55110. ** meaning it is possible that an inconsistent snapshot is read
  55111. ** from the file. If this happens, return non-zero.
  55112. **
  55113. ** There are two copies of the header at the beginning of the wal-index.
  55114. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  55115. ** Memory barriers are used to prevent the compiler or the hardware from
  55116. ** reordering the reads and writes.
  55117. */
  55118. aHdr = walIndexHdr(pWal);
  55119. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  55120. walShmBarrier(pWal);
  55121. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  55122. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  55123. return 1; /* Dirty read */
  55124. }
  55125. if( h1.isInit==0 ){
  55126. return 1; /* Malformed header - probably all zeros */
  55127. }
  55128. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  55129. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  55130. return 1; /* Checksum does not match */
  55131. }
  55132. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  55133. *pChanged = 1;
  55134. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  55135. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  55136. testcase( pWal->szPage<=32768 );
  55137. testcase( pWal->szPage>=65536 );
  55138. }
  55139. /* The header was successfully read. Return zero. */
  55140. return 0;
  55141. }
  55142. /*
  55143. ** This is the value that walTryBeginRead returns when it needs to
  55144. ** be retried.
  55145. */
  55146. #define WAL_RETRY (-1)
  55147. /*
  55148. ** Read the wal-index header from the wal-index and into pWal->hdr.
  55149. ** If the wal-header appears to be corrupt, try to reconstruct the
  55150. ** wal-index from the WAL before returning.
  55151. **
  55152. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  55153. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  55154. ** to 0.
  55155. **
  55156. ** If the wal-index header is successfully read, return SQLITE_OK.
  55157. ** Otherwise an SQLite error code.
  55158. */
  55159. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  55160. int rc; /* Return code */
  55161. int badHdr; /* True if a header read failed */
  55162. volatile u32 *page0; /* Chunk of wal-index containing header */
  55163. /* Ensure that page 0 of the wal-index (the page that contains the
  55164. ** wal-index header) is mapped. Return early if an error occurs here.
  55165. */
  55166. assert( pChanged );
  55167. rc = walIndexPage(pWal, 0, &page0);
  55168. if( rc!=SQLITE_OK ){
  55169. assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
  55170. if( rc==SQLITE_READONLY_CANTINIT ){
  55171. /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
  55172. ** was openable but is not writable, and this thread is unable to
  55173. ** confirm that another write-capable connection has the shared-memory
  55174. ** open, and hence the content of the shared-memory is unreliable,
  55175. ** since the shared-memory might be inconsistent with the WAL file
  55176. ** and there is no writer on hand to fix it. */
  55177. assert( page0==0 );
  55178. assert( pWal->writeLock==0 );
  55179. assert( pWal->readOnly & WAL_SHM_RDONLY );
  55180. pWal->bShmUnreliable = 1;
  55181. pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
  55182. *pChanged = 1;
  55183. }else{
  55184. return rc; /* Any other non-OK return is just an error */
  55185. }
  55186. }else{
  55187. /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
  55188. ** is zero, which prevents the SHM from growing */
  55189. testcase( page0!=0 );
  55190. }
  55191. assert( page0!=0 || pWal->writeLock==0 );
  55192. /* If the first page of the wal-index has been mapped, try to read the
  55193. ** wal-index header immediately, without holding any lock. This usually
  55194. ** works, but may fail if the wal-index header is corrupt or currently
  55195. ** being modified by another thread or process.
  55196. */
  55197. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  55198. /* If the first attempt failed, it might have been due to a race
  55199. ** with a writer. So get a WRITE lock and try again.
  55200. */
  55201. assert( badHdr==0 || pWal->writeLock==0 );
  55202. if( badHdr ){
  55203. if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
  55204. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  55205. walUnlockShared(pWal, WAL_WRITE_LOCK);
  55206. rc = SQLITE_READONLY_RECOVERY;
  55207. }
  55208. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  55209. pWal->writeLock = 1;
  55210. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  55211. badHdr = walIndexTryHdr(pWal, pChanged);
  55212. if( badHdr ){
  55213. /* If the wal-index header is still malformed even while holding
  55214. ** a WRITE lock, it can only mean that the header is corrupted and
  55215. ** needs to be reconstructed. So run recovery to do exactly that.
  55216. */
  55217. rc = walIndexRecover(pWal);
  55218. *pChanged = 1;
  55219. }
  55220. }
  55221. pWal->writeLock = 0;
  55222. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  55223. }
  55224. }
  55225. /* If the header is read successfully, check the version number to make
  55226. ** sure the wal-index was not constructed with some future format that
  55227. ** this version of SQLite cannot understand.
  55228. */
  55229. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  55230. rc = SQLITE_CANTOPEN_BKPT;
  55231. }
  55232. if( pWal->bShmUnreliable ){
  55233. if( rc!=SQLITE_OK ){
  55234. walIndexClose(pWal, 0);
  55235. pWal->bShmUnreliable = 0;
  55236. assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
  55237. /* walIndexRecover() might have returned SHORT_READ if a concurrent
  55238. ** writer truncated the WAL out from under it. If that happens, it
  55239. ** indicates that a writer has fixed the SHM file for us, so retry */
  55240. if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
  55241. }
  55242. pWal->exclusiveMode = WAL_NORMAL_MODE;
  55243. }
  55244. return rc;
  55245. }
  55246. /*
  55247. ** Open a transaction in a connection where the shared-memory is read-only
  55248. ** and where we cannot verify that there is a separate write-capable connection
  55249. ** on hand to keep the shared-memory up-to-date with the WAL file.
  55250. **
  55251. ** This can happen, for example, when the shared-memory is implemented by
  55252. ** memory-mapping a *-shm file, where a prior writer has shut down and
  55253. ** left the *-shm file on disk, and now the present connection is trying
  55254. ** to use that database but lacks write permission on the *-shm file.
  55255. ** Other scenarios are also possible, depending on the VFS implementation.
  55256. **
  55257. ** Precondition:
  55258. **
  55259. ** The *-wal file has been read and an appropriate wal-index has been
  55260. ** constructed in pWal->apWiData[] using heap memory instead of shared
  55261. ** memory.
  55262. **
  55263. ** If this function returns SQLITE_OK, then the read transaction has
  55264. ** been successfully opened. In this case output variable (*pChanged)
  55265. ** is set to true before returning if the caller should discard the
  55266. ** contents of the page cache before proceeding. Or, if it returns
  55267. ** WAL_RETRY, then the heap memory wal-index has been discarded and
  55268. ** the caller should retry opening the read transaction from the
  55269. ** beginning (including attempting to map the *-shm file).
  55270. **
  55271. ** If an error occurs, an SQLite error code is returned.
  55272. */
  55273. static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
  55274. i64 szWal; /* Size of wal file on disk in bytes */
  55275. i64 iOffset; /* Current offset when reading wal file */
  55276. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  55277. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  55278. int szFrame; /* Number of bytes in buffer aFrame[] */
  55279. u8 *aData; /* Pointer to data part of aFrame buffer */
  55280. volatile void *pDummy; /* Dummy argument for xShmMap */
  55281. int rc; /* Return code */
  55282. u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
  55283. assert( pWal->bShmUnreliable );
  55284. assert( pWal->readOnly & WAL_SHM_RDONLY );
  55285. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  55286. /* Take WAL_READ_LOCK(0). This has the effect of preventing any
  55287. ** writers from running a checkpoint, but does not stop them
  55288. ** from running recovery. */
  55289. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  55290. if( rc!=SQLITE_OK ){
  55291. if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
  55292. goto begin_unreliable_shm_out;
  55293. }
  55294. pWal->readLock = 0;
  55295. /* Check to see if a separate writer has attached to the shared-memory area,
  55296. ** thus making the shared-memory "reliable" again. Do this by invoking
  55297. ** the xShmMap() routine of the VFS and looking to see if the return
  55298. ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
  55299. **
  55300. ** If the shared-memory is now "reliable" return WAL_RETRY, which will
  55301. ** cause the heap-memory WAL-index to be discarded and the actual
  55302. ** shared memory to be used in its place.
  55303. **
  55304. ** This step is important because, even though this connection is holding
  55305. ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
  55306. ** have already checkpointed the WAL file and, while the current
  55307. ** is active, wrap the WAL and start overwriting frames that this
  55308. ** process wants to use.
  55309. **
  55310. ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
  55311. ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
  55312. ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
  55313. ** even if some external agent does a "chmod" to make the shared-memory
  55314. ** writable by us, until sqlite3OsShmUnmap() has been called.
  55315. ** This is a requirement on the VFS implementation.
  55316. */
  55317. rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
  55318. assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
  55319. if( rc!=SQLITE_READONLY_CANTINIT ){
  55320. rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
  55321. goto begin_unreliable_shm_out;
  55322. }
  55323. /* We reach this point only if the real shared-memory is still unreliable.
  55324. ** Assume the in-memory WAL-index substitute is correct and load it
  55325. ** into pWal->hdr.
  55326. */
  55327. memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
  55328. /* Make sure some writer hasn't come in and changed the WAL file out
  55329. ** from under us, then disconnected, while we were not looking.
  55330. */
  55331. rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
  55332. if( rc!=SQLITE_OK ){
  55333. goto begin_unreliable_shm_out;
  55334. }
  55335. if( szWal<WAL_HDRSIZE ){
  55336. /* If the wal file is too small to contain a wal-header and the
  55337. ** wal-index header has mxFrame==0, then it must be safe to proceed
  55338. ** reading the database file only. However, the page cache cannot
  55339. ** be trusted, as a read/write connection may have connected, written
  55340. ** the db, run a checkpoint, truncated the wal file and disconnected
  55341. ** since this client's last read transaction. */
  55342. *pChanged = 1;
  55343. rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
  55344. goto begin_unreliable_shm_out;
  55345. }
  55346. /* Check the salt keys at the start of the wal file still match. */
  55347. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  55348. if( rc!=SQLITE_OK ){
  55349. goto begin_unreliable_shm_out;
  55350. }
  55351. if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
  55352. /* Some writer has wrapped the WAL file while we were not looking.
  55353. ** Return WAL_RETRY which will cause the in-memory WAL-index to be
  55354. ** rebuilt. */
  55355. rc = WAL_RETRY;
  55356. goto begin_unreliable_shm_out;
  55357. }
  55358. /* Allocate a buffer to read frames into */
  55359. szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;
  55360. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  55361. if( aFrame==0 ){
  55362. rc = SQLITE_NOMEM_BKPT;
  55363. goto begin_unreliable_shm_out;
  55364. }
  55365. aData = &aFrame[WAL_FRAME_HDRSIZE];
  55366. /* Check to see if a complete transaction has been appended to the
  55367. ** wal file since the heap-memory wal-index was created. If so, the
  55368. ** heap-memory wal-index is discarded and WAL_RETRY returned to
  55369. ** the caller. */
  55370. aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
  55371. aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
  55372. for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage);
  55373. iOffset+szFrame<=szWal;
  55374. iOffset+=szFrame
  55375. ){
  55376. u32 pgno; /* Database page number for frame */
  55377. u32 nTruncate; /* dbsize field from frame header */
  55378. /* Read and decode the next log frame. */
  55379. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  55380. if( rc!=SQLITE_OK ) break;
  55381. if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
  55382. /* If nTruncate is non-zero, then a complete transaction has been
  55383. ** appended to this wal file. Set rc to WAL_RETRY and break out of
  55384. ** the loop. */
  55385. if( nTruncate ){
  55386. rc = WAL_RETRY;
  55387. break;
  55388. }
  55389. }
  55390. pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
  55391. pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
  55392. begin_unreliable_shm_out:
  55393. sqlite3_free(aFrame);
  55394. if( rc!=SQLITE_OK ){
  55395. int i;
  55396. for(i=0; i<pWal->nWiData; i++){
  55397. sqlite3_free((void*)pWal->apWiData[i]);
  55398. pWal->apWiData[i] = 0;
  55399. }
  55400. pWal->bShmUnreliable = 0;
  55401. sqlite3WalEndReadTransaction(pWal);
  55402. *pChanged = 1;
  55403. }
  55404. return rc;
  55405. }
  55406. /*
  55407. ** Attempt to start a read transaction. This might fail due to a race or
  55408. ** other transient condition. When that happens, it returns WAL_RETRY to
  55409. ** indicate to the caller that it is safe to retry immediately.
  55410. **
  55411. ** On success return SQLITE_OK. On a permanent failure (such an
  55412. ** I/O error or an SQLITE_BUSY because another process is running
  55413. ** recovery) return a positive error code.
  55414. **
  55415. ** The useWal parameter is true to force the use of the WAL and disable
  55416. ** the case where the WAL is bypassed because it has been completely
  55417. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  55418. ** to make a copy of the wal-index header into pWal->hdr. If the
  55419. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  55420. ** to the caller that the local page cache is obsolete and needs to be
  55421. ** flushed.) When useWal==1, the wal-index header is assumed to already
  55422. ** be loaded and the pChanged parameter is unused.
  55423. **
  55424. ** The caller must set the cnt parameter to the number of prior calls to
  55425. ** this routine during the current read attempt that returned WAL_RETRY.
  55426. ** This routine will start taking more aggressive measures to clear the
  55427. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  55428. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  55429. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  55430. ** and is not honoring the locking protocol. There is a vanishingly small
  55431. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  55432. ** bad luck when there is lots of contention for the wal-index, but that
  55433. ** possibility is so small that it can be safely neglected, we believe.
  55434. **
  55435. ** On success, this routine obtains a read lock on
  55436. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  55437. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  55438. ** that means the Wal does not hold any read lock. The reader must not
  55439. ** access any database page that is modified by a WAL frame up to and
  55440. ** including frame number aReadMark[pWal->readLock]. The reader will
  55441. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  55442. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  55443. ** completely and get all content directly from the database file.
  55444. ** If the useWal parameter is 1 then the WAL will never be ignored and
  55445. ** this routine will always set pWal->readLock>0 on success.
  55446. ** When the read transaction is completed, the caller must release the
  55447. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  55448. **
  55449. ** This routine uses the nBackfill and aReadMark[] fields of the header
  55450. ** to select a particular WAL_READ_LOCK() that strives to let the
  55451. ** checkpoint process do as much work as possible. This routine might
  55452. ** update values of the aReadMark[] array in the header, but if it does
  55453. ** so it takes care to hold an exclusive lock on the corresponding
  55454. ** WAL_READ_LOCK() while changing values.
  55455. */
  55456. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  55457. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  55458. u32 mxReadMark; /* Largest aReadMark[] value */
  55459. int mxI; /* Index of largest aReadMark[] value */
  55460. int i; /* Loop counter */
  55461. int rc = SQLITE_OK; /* Return code */
  55462. u32 mxFrame; /* Wal frame to lock to */
  55463. assert( pWal->readLock<0 ); /* Not currently locked */
  55464. /* useWal may only be set for read/write connections */
  55465. assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
  55466. /* Take steps to avoid spinning forever if there is a protocol error.
  55467. **
  55468. ** Circumstances that cause a RETRY should only last for the briefest
  55469. ** instances of time. No I/O or other system calls are done while the
  55470. ** locks are held, so the locks should not be held for very long. But
  55471. ** if we are unlucky, another process that is holding a lock might get
  55472. ** paged out or take a page-fault that is time-consuming to resolve,
  55473. ** during the few nanoseconds that it is holding the lock. In that case,
  55474. ** it might take longer than normal for the lock to free.
  55475. **
  55476. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  55477. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  55478. ** is more of a scheduler yield than an actual delay. But on the 10th
  55479. ** an subsequent retries, the delays start becoming longer and longer,
  55480. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  55481. ** The total delay time before giving up is less than 10 seconds.
  55482. */
  55483. if( cnt>5 ){
  55484. int nDelay = 1; /* Pause time in microseconds */
  55485. if( cnt>100 ){
  55486. VVA_ONLY( pWal->lockError = 1; )
  55487. return SQLITE_PROTOCOL;
  55488. }
  55489. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  55490. sqlite3OsSleep(pWal->pVfs, nDelay);
  55491. }
  55492. if( !useWal ){
  55493. assert( rc==SQLITE_OK );
  55494. if( pWal->bShmUnreliable==0 ){
  55495. rc = walIndexReadHdr(pWal, pChanged);
  55496. }
  55497. if( rc==SQLITE_BUSY ){
  55498. /* If there is not a recovery running in another thread or process
  55499. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  55500. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  55501. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  55502. ** would be technically correct. But the race is benign since with
  55503. ** WAL_RETRY this routine will be called again and will probably be
  55504. ** right on the second iteration.
  55505. */
  55506. if( pWal->apWiData[0]==0 ){
  55507. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  55508. ** We assume this is a transient condition, so return WAL_RETRY. The
  55509. ** xShmMap() implementation used by the default unix and win32 VFS
  55510. ** modules may return SQLITE_BUSY due to a race condition in the
  55511. ** code that determines whether or not the shared-memory region
  55512. ** must be zeroed before the requested page is returned.
  55513. */
  55514. rc = WAL_RETRY;
  55515. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  55516. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  55517. rc = WAL_RETRY;
  55518. }else if( rc==SQLITE_BUSY ){
  55519. rc = SQLITE_BUSY_RECOVERY;
  55520. }
  55521. }
  55522. if( rc!=SQLITE_OK ){
  55523. return rc;
  55524. }
  55525. else if( pWal->bShmUnreliable ){
  55526. return walBeginShmUnreliable(pWal, pChanged);
  55527. }
  55528. }
  55529. assert( pWal->nWiData>0 );
  55530. assert( pWal->apWiData[0]!=0 );
  55531. pInfo = walCkptInfo(pWal);
  55532. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
  55533. #ifdef SQLITE_ENABLE_SNAPSHOT
  55534. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
  55535. #endif
  55536. ){
  55537. /* The WAL has been completely backfilled (or it is empty).
  55538. ** and can be safely ignored.
  55539. */
  55540. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  55541. walShmBarrier(pWal);
  55542. if( rc==SQLITE_OK ){
  55543. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  55544. /* It is not safe to allow the reader to continue here if frames
  55545. ** may have been appended to the log before READ_LOCK(0) was obtained.
  55546. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  55547. ** which implies that the database file contains a trustworthy
  55548. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  55549. ** happening, this is usually correct.
  55550. **
  55551. ** However, if frames have been appended to the log (or if the log
  55552. ** is wrapped and written for that matter) before the READ_LOCK(0)
  55553. ** is obtained, that is not necessarily true. A checkpointer may
  55554. ** have started to backfill the appended frames but crashed before
  55555. ** it finished. Leaving a corrupt image in the database file.
  55556. */
  55557. walUnlockShared(pWal, WAL_READ_LOCK(0));
  55558. return WAL_RETRY;
  55559. }
  55560. pWal->readLock = 0;
  55561. return SQLITE_OK;
  55562. }else if( rc!=SQLITE_BUSY ){
  55563. return rc;
  55564. }
  55565. }
  55566. /* If we get this far, it means that the reader will want to use
  55567. ** the WAL to get at content from recent commits. The job now is
  55568. ** to select one of the aReadMark[] entries that is closest to
  55569. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  55570. */
  55571. mxReadMark = 0;
  55572. mxI = 0;
  55573. mxFrame = pWal->hdr.mxFrame;
  55574. #ifdef SQLITE_ENABLE_SNAPSHOT
  55575. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  55576. mxFrame = pWal->pSnapshot->mxFrame;
  55577. }
  55578. #endif
  55579. for(i=1; i<WAL_NREADER; i++){
  55580. u32 thisMark = pInfo->aReadMark[i];
  55581. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  55582. assert( thisMark!=READMARK_NOT_USED );
  55583. mxReadMark = thisMark;
  55584. mxI = i;
  55585. }
  55586. }
  55587. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  55588. && (mxReadMark<mxFrame || mxI==0)
  55589. ){
  55590. for(i=1; i<WAL_NREADER; i++){
  55591. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  55592. if( rc==SQLITE_OK ){
  55593. mxReadMark = pInfo->aReadMark[i] = mxFrame;
  55594. mxI = i;
  55595. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  55596. break;
  55597. }else if( rc!=SQLITE_BUSY ){
  55598. return rc;
  55599. }
  55600. }
  55601. }
  55602. if( mxI==0 ){
  55603. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  55604. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
  55605. }
  55606. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  55607. if( rc ){
  55608. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  55609. }
  55610. /* Now that the read-lock has been obtained, check that neither the
  55611. ** value in the aReadMark[] array or the contents of the wal-index
  55612. ** header have changed.
  55613. **
  55614. ** It is necessary to check that the wal-index header did not change
  55615. ** between the time it was read and when the shared-lock was obtained
  55616. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  55617. ** that the log file may have been wrapped by a writer, or that frames
  55618. ** that occur later in the log than pWal->hdr.mxFrame may have been
  55619. ** copied into the database by a checkpointer. If either of these things
  55620. ** happened, then reading the database with the current value of
  55621. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  55622. ** instead.
  55623. **
  55624. ** Before checking that the live wal-index header has not changed
  55625. ** since it was read, set Wal.minFrame to the first frame in the wal
  55626. ** file that has not yet been checkpointed. This client will not need
  55627. ** to read any frames earlier than minFrame from the wal file - they
  55628. ** can be safely read directly from the database file.
  55629. **
  55630. ** Because a ShmBarrier() call is made between taking the copy of
  55631. ** nBackfill and checking that the wal-header in shared-memory still
  55632. ** matches the one cached in pWal->hdr, it is guaranteed that the
  55633. ** checkpointer that set nBackfill was not working with a wal-index
  55634. ** header newer than that cached in pWal->hdr. If it were, that could
  55635. ** cause a problem. The checkpointer could omit to checkpoint
  55636. ** a version of page X that lies before pWal->minFrame (call that version
  55637. ** A) on the basis that there is a newer version (version B) of the same
  55638. ** page later in the wal file. But if version B happens to like past
  55639. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  55640. ** that it can read version A from the database file. However, since
  55641. ** we can guarantee that the checkpointer that set nBackfill could not
  55642. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  55643. */
  55644. pWal->minFrame = pInfo->nBackfill+1;
  55645. walShmBarrier(pWal);
  55646. if( pInfo->aReadMark[mxI]!=mxReadMark
  55647. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  55648. ){
  55649. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  55650. return WAL_RETRY;
  55651. }else{
  55652. assert( mxReadMark<=pWal->hdr.mxFrame );
  55653. pWal->readLock = (i16)mxI;
  55654. }
  55655. return rc;
  55656. }
  55657. #ifdef SQLITE_ENABLE_SNAPSHOT
  55658. /*
  55659. ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
  55660. ** variable so that older snapshots can be accessed. To do this, loop
  55661. ** through all wal frames from nBackfillAttempted to (nBackfill+1),
  55662. ** comparing their content to the corresponding page with the database
  55663. ** file, if any. Set nBackfillAttempted to the frame number of the
  55664. ** first frame for which the wal file content matches the db file.
  55665. **
  55666. ** This is only really safe if the file-system is such that any page
  55667. ** writes made by earlier checkpointers were atomic operations, which
  55668. ** is not always true. It is also possible that nBackfillAttempted
  55669. ** may be left set to a value larger than expected, if a wal frame
  55670. ** contains content that duplicate of an earlier version of the same
  55671. ** page.
  55672. **
  55673. ** SQLITE_OK is returned if successful, or an SQLite error code if an
  55674. ** error occurs. It is not an error if nBackfillAttempted cannot be
  55675. ** decreased at all.
  55676. */
  55677. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
  55678. int rc;
  55679. assert( pWal->readLock>=0 );
  55680. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  55681. if( rc==SQLITE_OK ){
  55682. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  55683. int szPage = (int)pWal->szPage;
  55684. i64 szDb; /* Size of db file in bytes */
  55685. rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
  55686. if( rc==SQLITE_OK ){
  55687. void *pBuf1 = sqlite3_malloc(szPage);
  55688. void *pBuf2 = sqlite3_malloc(szPage);
  55689. if( pBuf1==0 || pBuf2==0 ){
  55690. rc = SQLITE_NOMEM;
  55691. }else{
  55692. u32 i = pInfo->nBackfillAttempted;
  55693. for(i=pInfo->nBackfillAttempted; i>pInfo->nBackfill; i--){
  55694. volatile ht_slot *dummy;
  55695. volatile u32 *aPgno; /* Array of page numbers */
  55696. u32 iZero; /* Frame corresponding to aPgno[0] */
  55697. u32 pgno; /* Page number in db file */
  55698. i64 iDbOff; /* Offset of db file entry */
  55699. i64 iWalOff; /* Offset of wal file entry */
  55700. rc = walHashGet(pWal, walFramePage(i), &dummy, &aPgno, &iZero);
  55701. if( rc!=SQLITE_OK ) break;
  55702. pgno = aPgno[i-iZero];
  55703. iDbOff = (i64)(pgno-1) * szPage;
  55704. if( iDbOff+szPage<=szDb ){
  55705. iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
  55706. rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
  55707. if( rc==SQLITE_OK ){
  55708. rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
  55709. }
  55710. if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
  55711. break;
  55712. }
  55713. }
  55714. pInfo->nBackfillAttempted = i-1;
  55715. }
  55716. }
  55717. sqlite3_free(pBuf1);
  55718. sqlite3_free(pBuf2);
  55719. }
  55720. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  55721. }
  55722. return rc;
  55723. }
  55724. #endif /* SQLITE_ENABLE_SNAPSHOT */
  55725. /*
  55726. ** Begin a read transaction on the database.
  55727. **
  55728. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  55729. ** it takes a snapshot of the state of the WAL and wal-index for the current
  55730. ** instant in time. The current thread will continue to use this snapshot.
  55731. ** Other threads might append new content to the WAL and wal-index but
  55732. ** that extra content is ignored by the current thread.
  55733. **
  55734. ** If the database contents have changes since the previous read
  55735. ** transaction, then *pChanged is set to 1 before returning. The
  55736. ** Pager layer will use this to know that is cache is stale and
  55737. ** needs to be flushed.
  55738. */
  55739. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  55740. int rc; /* Return code */
  55741. int cnt = 0; /* Number of TryBeginRead attempts */
  55742. #ifdef SQLITE_ENABLE_SNAPSHOT
  55743. int bChanged = 0;
  55744. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  55745. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  55746. bChanged = 1;
  55747. }
  55748. #endif
  55749. do{
  55750. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  55751. }while( rc==WAL_RETRY );
  55752. testcase( (rc&0xff)==SQLITE_BUSY );
  55753. testcase( (rc&0xff)==SQLITE_IOERR );
  55754. testcase( rc==SQLITE_PROTOCOL );
  55755. testcase( rc==SQLITE_OK );
  55756. #ifdef SQLITE_ENABLE_SNAPSHOT
  55757. if( rc==SQLITE_OK ){
  55758. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  55759. /* At this point the client has a lock on an aReadMark[] slot holding
  55760. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  55761. ** is populated with the wal-index header corresponding to the head
  55762. ** of the wal file. Verify that pSnapshot is still valid before
  55763. ** continuing. Reasons why pSnapshot might no longer be valid:
  55764. **
  55765. ** (1) The WAL file has been reset since the snapshot was taken.
  55766. ** In this case, the salt will have changed.
  55767. **
  55768. ** (2) A checkpoint as been attempted that wrote frames past
  55769. ** pSnapshot->mxFrame into the database file. Note that the
  55770. ** checkpoint need not have completed for this to cause problems.
  55771. */
  55772. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  55773. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  55774. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  55775. /* It is possible that there is a checkpointer thread running
  55776. ** concurrent with this code. If this is the case, it may be that the
  55777. ** checkpointer has already determined that it will checkpoint
  55778. ** snapshot X, where X is later in the wal file than pSnapshot, but
  55779. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  55780. ** its intent. To avoid the race condition this leads to, ensure that
  55781. ** there is no checkpointer process by taking a shared CKPT lock
  55782. ** before checking pInfo->nBackfillAttempted.
  55783. **
  55784. ** TODO: Does the aReadMark[] lock prevent a checkpointer from doing
  55785. ** this already?
  55786. */
  55787. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  55788. if( rc==SQLITE_OK ){
  55789. /* Check that the wal file has not been wrapped. Assuming that it has
  55790. ** not, also check that no checkpointer has attempted to checkpoint any
  55791. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  55792. ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
  55793. ** with *pSnapshot and set *pChanged as appropriate for opening the
  55794. ** snapshot. */
  55795. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  55796. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  55797. ){
  55798. assert( pWal->readLock>0 );
  55799. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  55800. *pChanged = bChanged;
  55801. }else{
  55802. rc = SQLITE_BUSY_SNAPSHOT;
  55803. }
  55804. /* Release the shared CKPT lock obtained above. */
  55805. walUnlockShared(pWal, WAL_CKPT_LOCK);
  55806. }
  55807. if( rc!=SQLITE_OK ){
  55808. sqlite3WalEndReadTransaction(pWal);
  55809. }
  55810. }
  55811. }
  55812. #endif
  55813. return rc;
  55814. }
  55815. /*
  55816. ** Finish with a read transaction. All this does is release the
  55817. ** read-lock.
  55818. */
  55819. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  55820. sqlite3WalEndWriteTransaction(pWal);
  55821. if( pWal->readLock>=0 ){
  55822. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  55823. pWal->readLock = -1;
  55824. }
  55825. }
  55826. /*
  55827. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  55828. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  55829. ** to zero.
  55830. **
  55831. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  55832. ** error does occur, the final value of *piRead is undefined.
  55833. */
  55834. SQLITE_PRIVATE int sqlite3WalFindFrame(
  55835. Wal *pWal, /* WAL handle */
  55836. Pgno pgno, /* Database page number to read data for */
  55837. u32 *piRead /* OUT: Frame number (or zero) */
  55838. ){
  55839. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  55840. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  55841. int iHash; /* Used to loop through N hash tables */
  55842. int iMinHash;
  55843. /* This routine is only be called from within a read transaction. */
  55844. assert( pWal->readLock>=0 || pWal->lockError );
  55845. /* If the "last page" field of the wal-index header snapshot is 0, then
  55846. ** no data will be read from the wal under any circumstances. Return early
  55847. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  55848. ** then the WAL is ignored by the reader so return early, as if the
  55849. ** WAL were empty.
  55850. */
  55851. if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
  55852. *piRead = 0;
  55853. return SQLITE_OK;
  55854. }
  55855. /* Search the hash table or tables for an entry matching page number
  55856. ** pgno. Each iteration of the following for() loop searches one
  55857. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  55858. **
  55859. ** This code might run concurrently to the code in walIndexAppend()
  55860. ** that adds entries to the wal-index (and possibly to this hash
  55861. ** table). This means the value just read from the hash
  55862. ** slot (aHash[iKey]) may have been added before or after the
  55863. ** current read transaction was opened. Values added after the
  55864. ** read transaction was opened may have been written incorrectly -
  55865. ** i.e. these slots may contain garbage data. However, we assume
  55866. ** that any slots written before the current read transaction was
  55867. ** opened remain unmodified.
  55868. **
  55869. ** For the reasons above, the if(...) condition featured in the inner
  55870. ** loop of the following block is more stringent that would be required
  55871. ** if we had exclusive access to the hash-table:
  55872. **
  55873. ** (aPgno[iFrame]==pgno):
  55874. ** This condition filters out normal hash-table collisions.
  55875. **
  55876. ** (iFrame<=iLast):
  55877. ** This condition filters out entries that were added to the hash
  55878. ** table after the current read-transaction had started.
  55879. */
  55880. iMinHash = walFramePage(pWal->minFrame);
  55881. for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
  55882. volatile ht_slot *aHash; /* Pointer to hash table */
  55883. volatile u32 *aPgno; /* Pointer to array of page numbers */
  55884. u32 iZero; /* Frame number corresponding to aPgno[0] */
  55885. int iKey; /* Hash slot index */
  55886. int nCollide; /* Number of hash collisions remaining */
  55887. int rc; /* Error code */
  55888. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  55889. if( rc!=SQLITE_OK ){
  55890. return rc;
  55891. }
  55892. nCollide = HASHTABLE_NSLOT;
  55893. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  55894. u32 iFrame = aHash[iKey] + iZero;
  55895. if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
  55896. assert( iFrame>iRead || CORRUPT_DB );
  55897. iRead = iFrame;
  55898. }
  55899. if( (nCollide--)==0 ){
  55900. return SQLITE_CORRUPT_BKPT;
  55901. }
  55902. }
  55903. if( iRead ) break;
  55904. }
  55905. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  55906. /* If expensive assert() statements are available, do a linear search
  55907. ** of the wal-index file content. Make sure the results agree with the
  55908. ** result obtained using the hash indexes above. */
  55909. {
  55910. u32 iRead2 = 0;
  55911. u32 iTest;
  55912. assert( pWal->bShmUnreliable || pWal->minFrame>0 );
  55913. for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
  55914. if( walFramePgno(pWal, iTest)==pgno ){
  55915. iRead2 = iTest;
  55916. break;
  55917. }
  55918. }
  55919. assert( iRead==iRead2 );
  55920. }
  55921. #endif
  55922. *piRead = iRead;
  55923. return SQLITE_OK;
  55924. }
  55925. /*
  55926. ** Read the contents of frame iRead from the wal file into buffer pOut
  55927. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  55928. ** error code otherwise.
  55929. */
  55930. SQLITE_PRIVATE int sqlite3WalReadFrame(
  55931. Wal *pWal, /* WAL handle */
  55932. u32 iRead, /* Frame to read */
  55933. int nOut, /* Size of buffer pOut in bytes */
  55934. u8 *pOut /* Buffer to write page data to */
  55935. ){
  55936. int sz;
  55937. i64 iOffset;
  55938. sz = pWal->hdr.szPage;
  55939. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  55940. testcase( sz<=32768 );
  55941. testcase( sz>=65536 );
  55942. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  55943. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  55944. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  55945. }
  55946. /*
  55947. ** Return the size of the database in pages (or zero, if unknown).
  55948. */
  55949. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  55950. if( pWal && ALWAYS(pWal->readLock>=0) ){
  55951. return pWal->hdr.nPage;
  55952. }
  55953. return 0;
  55954. }
  55955. /*
  55956. ** This function starts a write transaction on the WAL.
  55957. **
  55958. ** A read transaction must have already been started by a prior call
  55959. ** to sqlite3WalBeginReadTransaction().
  55960. **
  55961. ** If another thread or process has written into the database since
  55962. ** the read transaction was started, then it is not possible for this
  55963. ** thread to write as doing so would cause a fork. So this routine
  55964. ** returns SQLITE_BUSY in that case and no write transaction is started.
  55965. **
  55966. ** There can only be a single writer active at a time.
  55967. */
  55968. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  55969. int rc;
  55970. /* Cannot start a write transaction without first holding a read
  55971. ** transaction. */
  55972. assert( pWal->readLock>=0 );
  55973. assert( pWal->writeLock==0 && pWal->iReCksum==0 );
  55974. if( pWal->readOnly ){
  55975. return SQLITE_READONLY;
  55976. }
  55977. /* Only one writer allowed at a time. Get the write lock. Return
  55978. ** SQLITE_BUSY if unable.
  55979. */
  55980. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  55981. if( rc ){
  55982. return rc;
  55983. }
  55984. pWal->writeLock = 1;
  55985. /* If another connection has written to the database file since the
  55986. ** time the read transaction on this connection was started, then
  55987. ** the write is disallowed.
  55988. */
  55989. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  55990. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  55991. pWal->writeLock = 0;
  55992. rc = SQLITE_BUSY_SNAPSHOT;
  55993. }
  55994. return rc;
  55995. }
  55996. /*
  55997. ** End a write transaction. The commit has already been done. This
  55998. ** routine merely releases the lock.
  55999. */
  56000. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  56001. if( pWal->writeLock ){
  56002. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  56003. pWal->writeLock = 0;
  56004. pWal->iReCksum = 0;
  56005. pWal->truncateOnCommit = 0;
  56006. }
  56007. return SQLITE_OK;
  56008. }
  56009. /*
  56010. ** If any data has been written (but not committed) to the log file, this
  56011. ** function moves the write-pointer back to the start of the transaction.
  56012. **
  56013. ** Additionally, the callback function is invoked for each frame written
  56014. ** to the WAL since the start of the transaction. If the callback returns
  56015. ** other than SQLITE_OK, it is not invoked again and the error code is
  56016. ** returned to the caller.
  56017. **
  56018. ** Otherwise, if the callback function does not return an error, this
  56019. ** function returns SQLITE_OK.
  56020. */
  56021. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  56022. int rc = SQLITE_OK;
  56023. if( ALWAYS(pWal->writeLock) ){
  56024. Pgno iMax = pWal->hdr.mxFrame;
  56025. Pgno iFrame;
  56026. /* Restore the clients cache of the wal-index header to the state it
  56027. ** was in before the client began writing to the database.
  56028. */
  56029. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  56030. for(iFrame=pWal->hdr.mxFrame+1;
  56031. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  56032. iFrame++
  56033. ){
  56034. /* This call cannot fail. Unless the page for which the page number
  56035. ** is passed as the second argument is (a) in the cache and
  56036. ** (b) has an outstanding reference, then xUndo is either a no-op
  56037. ** (if (a) is false) or simply expels the page from the cache (if (b)
  56038. ** is false).
  56039. **
  56040. ** If the upper layer is doing a rollback, it is guaranteed that there
  56041. ** are no outstanding references to any page other than page 1. And
  56042. ** page 1 is never written to the log until the transaction is
  56043. ** committed. As a result, the call to xUndo may not fail.
  56044. */
  56045. assert( walFramePgno(pWal, iFrame)!=1 );
  56046. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  56047. }
  56048. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  56049. }
  56050. return rc;
  56051. }
  56052. /*
  56053. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  56054. ** values. This function populates the array with values required to
  56055. ** "rollback" the write position of the WAL handle back to the current
  56056. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  56057. */
  56058. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  56059. assert( pWal->writeLock );
  56060. aWalData[0] = pWal->hdr.mxFrame;
  56061. aWalData[1] = pWal->hdr.aFrameCksum[0];
  56062. aWalData[2] = pWal->hdr.aFrameCksum[1];
  56063. aWalData[3] = pWal->nCkpt;
  56064. }
  56065. /*
  56066. ** Move the write position of the WAL back to the point identified by
  56067. ** the values in the aWalData[] array. aWalData must point to an array
  56068. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  56069. ** by a call to WalSavepoint().
  56070. */
  56071. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  56072. int rc = SQLITE_OK;
  56073. assert( pWal->writeLock );
  56074. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  56075. if( aWalData[3]!=pWal->nCkpt ){
  56076. /* This savepoint was opened immediately after the write-transaction
  56077. ** was started. Right after that, the writer decided to wrap around
  56078. ** to the start of the log. Update the savepoint values to match.
  56079. */
  56080. aWalData[0] = 0;
  56081. aWalData[3] = pWal->nCkpt;
  56082. }
  56083. if( aWalData[0]<pWal->hdr.mxFrame ){
  56084. pWal->hdr.mxFrame = aWalData[0];
  56085. pWal->hdr.aFrameCksum[0] = aWalData[1];
  56086. pWal->hdr.aFrameCksum[1] = aWalData[2];
  56087. walCleanupHash(pWal);
  56088. }
  56089. return rc;
  56090. }
  56091. /*
  56092. ** This function is called just before writing a set of frames to the log
  56093. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  56094. ** to the current log file, it is possible to overwrite the start of the
  56095. ** existing log file with the new frames (i.e. "reset" the log). If so,
  56096. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  56097. ** unchanged.
  56098. **
  56099. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  56100. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  56101. ** if an error occurs.
  56102. */
  56103. static int walRestartLog(Wal *pWal){
  56104. int rc = SQLITE_OK;
  56105. int cnt;
  56106. if( pWal->readLock==0 ){
  56107. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  56108. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  56109. if( pInfo->nBackfill>0 ){
  56110. u32 salt1;
  56111. sqlite3_randomness(4, &salt1);
  56112. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  56113. if( rc==SQLITE_OK ){
  56114. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  56115. ** readers are currently using the WAL), then the transactions
  56116. ** frames will overwrite the start of the existing log. Update the
  56117. ** wal-index header to reflect this.
  56118. **
  56119. ** In theory it would be Ok to update the cache of the header only
  56120. ** at this point. But updating the actual wal-index header is also
  56121. ** safe and means there is no special case for sqlite3WalUndo()
  56122. ** to handle if this transaction is rolled back. */
  56123. walRestartHdr(pWal, salt1);
  56124. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  56125. }else if( rc!=SQLITE_BUSY ){
  56126. return rc;
  56127. }
  56128. }
  56129. walUnlockShared(pWal, WAL_READ_LOCK(0));
  56130. pWal->readLock = -1;
  56131. cnt = 0;
  56132. do{
  56133. int notUsed;
  56134. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  56135. }while( rc==WAL_RETRY );
  56136. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  56137. testcase( (rc&0xff)==SQLITE_IOERR );
  56138. testcase( rc==SQLITE_PROTOCOL );
  56139. testcase( rc==SQLITE_OK );
  56140. }
  56141. return rc;
  56142. }
  56143. /*
  56144. ** Information about the current state of the WAL file and where
  56145. ** the next fsync should occur - passed from sqlite3WalFrames() into
  56146. ** walWriteToLog().
  56147. */
  56148. typedef struct WalWriter {
  56149. Wal *pWal; /* The complete WAL information */
  56150. sqlite3_file *pFd; /* The WAL file to which we write */
  56151. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  56152. int syncFlags; /* Flags for the fsync */
  56153. int szPage; /* Size of one page */
  56154. } WalWriter;
  56155. /*
  56156. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  56157. ** Do a sync when crossing the p->iSyncPoint boundary.
  56158. **
  56159. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  56160. ** first write the part before iSyncPoint, then sync, then write the
  56161. ** rest.
  56162. */
  56163. static int walWriteToLog(
  56164. WalWriter *p, /* WAL to write to */
  56165. void *pContent, /* Content to be written */
  56166. int iAmt, /* Number of bytes to write */
  56167. sqlite3_int64 iOffset /* Start writing at this offset */
  56168. ){
  56169. int rc;
  56170. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  56171. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  56172. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  56173. if( rc ) return rc;
  56174. iOffset += iFirstAmt;
  56175. iAmt -= iFirstAmt;
  56176. pContent = (void*)(iFirstAmt + (char*)pContent);
  56177. assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
  56178. rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
  56179. if( iAmt==0 || rc ) return rc;
  56180. }
  56181. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  56182. return rc;
  56183. }
  56184. /*
  56185. ** Write out a single frame of the WAL
  56186. */
  56187. static int walWriteOneFrame(
  56188. WalWriter *p, /* Where to write the frame */
  56189. PgHdr *pPage, /* The page of the frame to be written */
  56190. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  56191. sqlite3_int64 iOffset /* Byte offset at which to write */
  56192. ){
  56193. int rc; /* Result code from subfunctions */
  56194. void *pData; /* Data actually written */
  56195. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  56196. #if defined(SQLITE_HAS_CODEC)
  56197. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
  56198. #else
  56199. pData = pPage->pData;
  56200. #endif
  56201. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  56202. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  56203. if( rc ) return rc;
  56204. /* Write the page data */
  56205. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  56206. return rc;
  56207. }
  56208. /*
  56209. ** This function is called as part of committing a transaction within which
  56210. ** one or more frames have been overwritten. It updates the checksums for
  56211. ** all frames written to the wal file by the current transaction starting
  56212. ** with the earliest to have been overwritten.
  56213. **
  56214. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  56215. */
  56216. static int walRewriteChecksums(Wal *pWal, u32 iLast){
  56217. const int szPage = pWal->szPage;/* Database page size */
  56218. int rc = SQLITE_OK; /* Return code */
  56219. u8 *aBuf; /* Buffer to load data from wal file into */
  56220. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
  56221. u32 iRead; /* Next frame to read from wal file */
  56222. i64 iCksumOff;
  56223. aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  56224. if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
  56225. /* Find the checksum values to use as input for the recalculating the
  56226. ** first checksum. If the first frame is frame 1 (implying that the current
  56227. ** transaction restarted the wal file), these values must be read from the
  56228. ** wal-file header. Otherwise, read them from the frame header of the
  56229. ** previous frame. */
  56230. assert( pWal->iReCksum>0 );
  56231. if( pWal->iReCksum==1 ){
  56232. iCksumOff = 24;
  56233. }else{
  56234. iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  56235. }
  56236. rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  56237. pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  56238. pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
  56239. iRead = pWal->iReCksum;
  56240. pWal->iReCksum = 0;
  56241. for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
  56242. i64 iOff = walFrameOffset(iRead, szPage);
  56243. rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
  56244. if( rc==SQLITE_OK ){
  56245. u32 iPgno, nDbSize;
  56246. iPgno = sqlite3Get4byte(aBuf);
  56247. nDbSize = sqlite3Get4byte(&aBuf[4]);
  56248. walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
  56249. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
  56250. }
  56251. }
  56252. sqlite3_free(aBuf);
  56253. return rc;
  56254. }
  56255. /*
  56256. ** Write a set of frames to the log. The caller must hold the write-lock
  56257. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  56258. */
  56259. SQLITE_PRIVATE int sqlite3WalFrames(
  56260. Wal *pWal, /* Wal handle to write to */
  56261. int szPage, /* Database page-size in bytes */
  56262. PgHdr *pList, /* List of dirty pages to write */
  56263. Pgno nTruncate, /* Database size after this commit */
  56264. int isCommit, /* True if this is a commit */
  56265. int sync_flags /* Flags to pass to OsSync() (or 0) */
  56266. ){
  56267. int rc; /* Used to catch return codes */
  56268. u32 iFrame; /* Next frame address */
  56269. PgHdr *p; /* Iterator to run through pList with. */
  56270. PgHdr *pLast = 0; /* Last frame in list */
  56271. int nExtra = 0; /* Number of extra copies of last page */
  56272. int szFrame; /* The size of a single frame */
  56273. i64 iOffset; /* Next byte to write in WAL file */
  56274. WalWriter w; /* The writer */
  56275. u32 iFirst = 0; /* First frame that may be overwritten */
  56276. WalIndexHdr *pLive; /* Pointer to shared header */
  56277. assert( pList );
  56278. assert( pWal->writeLock );
  56279. /* If this frame set completes a transaction, then nTruncate>0. If
  56280. ** nTruncate==0 then this frame set does not complete the transaction. */
  56281. assert( (isCommit!=0)==(nTruncate!=0) );
  56282. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  56283. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  56284. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  56285. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  56286. }
  56287. #endif
  56288. pLive = (WalIndexHdr*)walIndexHdr(pWal);
  56289. if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
  56290. iFirst = pLive->mxFrame+1;
  56291. }
  56292. /* See if it is possible to write these frames into the start of the
  56293. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  56294. */
  56295. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  56296. return rc;
  56297. }
  56298. /* If this is the first frame written into the log, write the WAL
  56299. ** header to the start of the WAL file. See comments at the top of
  56300. ** this source file for a description of the WAL header format.
  56301. */
  56302. iFrame = pWal->hdr.mxFrame;
  56303. if( iFrame==0 ){
  56304. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  56305. u32 aCksum[2]; /* Checksum for wal-header */
  56306. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  56307. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  56308. sqlite3Put4byte(&aWalHdr[8], szPage);
  56309. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  56310. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  56311. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  56312. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  56313. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  56314. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  56315. pWal->szPage = szPage;
  56316. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  56317. pWal->hdr.aFrameCksum[0] = aCksum[0];
  56318. pWal->hdr.aFrameCksum[1] = aCksum[1];
  56319. pWal->truncateOnCommit = 1;
  56320. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  56321. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  56322. if( rc!=SQLITE_OK ){
  56323. return rc;
  56324. }
  56325. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  56326. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  56327. ** an out-of-order write following a WAL restart could result in
  56328. ** database corruption. See the ticket:
  56329. **
  56330. ** https://sqlite.org/src/info/ff5be73dee
  56331. */
  56332. if( pWal->syncHeader ){
  56333. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  56334. if( rc ) return rc;
  56335. }
  56336. }
  56337. assert( (int)pWal->szPage==szPage );
  56338. /* Setup information needed to write frames into the WAL */
  56339. w.pWal = pWal;
  56340. w.pFd = pWal->pWalFd;
  56341. w.iSyncPoint = 0;
  56342. w.syncFlags = sync_flags;
  56343. w.szPage = szPage;
  56344. iOffset = walFrameOffset(iFrame+1, szPage);
  56345. szFrame = szPage + WAL_FRAME_HDRSIZE;
  56346. /* Write all frames into the log file exactly once */
  56347. for(p=pList; p; p=p->pDirty){
  56348. int nDbSize; /* 0 normally. Positive == commit flag */
  56349. /* Check if this page has already been written into the wal file by
  56350. ** the current transaction. If so, overwrite the existing frame and
  56351. ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
  56352. ** checksums must be recomputed when the transaction is committed. */
  56353. if( iFirst && (p->pDirty || isCommit==0) ){
  56354. u32 iWrite = 0;
  56355. VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
  56356. assert( rc==SQLITE_OK || iWrite==0 );
  56357. if( iWrite>=iFirst ){
  56358. i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
  56359. void *pData;
  56360. if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
  56361. pWal->iReCksum = iWrite;
  56362. }
  56363. #if defined(SQLITE_HAS_CODEC)
  56364. if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
  56365. #else
  56366. pData = p->pData;
  56367. #endif
  56368. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
  56369. if( rc ) return rc;
  56370. p->flags &= ~PGHDR_WAL_APPEND;
  56371. continue;
  56372. }
  56373. }
  56374. iFrame++;
  56375. assert( iOffset==walFrameOffset(iFrame, szPage) );
  56376. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  56377. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  56378. if( rc ) return rc;
  56379. pLast = p;
  56380. iOffset += szFrame;
  56381. p->flags |= PGHDR_WAL_APPEND;
  56382. }
  56383. /* Recalculate checksums within the wal file if required. */
  56384. if( isCommit && pWal->iReCksum ){
  56385. rc = walRewriteChecksums(pWal, iFrame);
  56386. if( rc ) return rc;
  56387. }
  56388. /* If this is the end of a transaction, then we might need to pad
  56389. ** the transaction and/or sync the WAL file.
  56390. **
  56391. ** Padding and syncing only occur if this set of frames complete a
  56392. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  56393. ** or synchronous==OFF, then no padding or syncing are needed.
  56394. **
  56395. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  56396. ** needed and only the sync is done. If padding is needed, then the
  56397. ** final frame is repeated (with its commit mark) until the next sector
  56398. ** boundary is crossed. Only the part of the WAL prior to the last
  56399. ** sector boundary is synced; the part of the last frame that extends
  56400. ** past the sector boundary is written after the sync.
  56401. */
  56402. if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
  56403. int bSync = 1;
  56404. if( pWal->padToSectorBoundary ){
  56405. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  56406. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  56407. bSync = (w.iSyncPoint==iOffset);
  56408. testcase( bSync );
  56409. while( iOffset<w.iSyncPoint ){
  56410. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  56411. if( rc ) return rc;
  56412. iOffset += szFrame;
  56413. nExtra++;
  56414. }
  56415. }
  56416. if( bSync ){
  56417. assert( rc==SQLITE_OK );
  56418. rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
  56419. }
  56420. }
  56421. /* If this frame set completes the first transaction in the WAL and
  56422. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  56423. ** journal size limit, if possible.
  56424. */
  56425. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  56426. i64 sz = pWal->mxWalSize;
  56427. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  56428. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  56429. }
  56430. walLimitSize(pWal, sz);
  56431. pWal->truncateOnCommit = 0;
  56432. }
  56433. /* Append data to the wal-index. It is not necessary to lock the
  56434. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  56435. ** guarantees that there are no other writers, and no data that may
  56436. ** be in use by existing readers is being overwritten.
  56437. */
  56438. iFrame = pWal->hdr.mxFrame;
  56439. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  56440. if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
  56441. iFrame++;
  56442. rc = walIndexAppend(pWal, iFrame, p->pgno);
  56443. }
  56444. while( rc==SQLITE_OK && nExtra>0 ){
  56445. iFrame++;
  56446. nExtra--;
  56447. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  56448. }
  56449. if( rc==SQLITE_OK ){
  56450. /* Update the private copy of the header. */
  56451. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  56452. testcase( szPage<=32768 );
  56453. testcase( szPage>=65536 );
  56454. pWal->hdr.mxFrame = iFrame;
  56455. if( isCommit ){
  56456. pWal->hdr.iChange++;
  56457. pWal->hdr.nPage = nTruncate;
  56458. }
  56459. /* If this is a commit, update the wal-index header too. */
  56460. if( isCommit ){
  56461. walIndexWriteHdr(pWal);
  56462. pWal->iCallback = iFrame;
  56463. }
  56464. }
  56465. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  56466. return rc;
  56467. }
  56468. /*
  56469. ** This routine is called to implement sqlite3_wal_checkpoint() and
  56470. ** related interfaces.
  56471. **
  56472. ** Obtain a CHECKPOINT lock and then backfill as much information as
  56473. ** we can from WAL into the database.
  56474. **
  56475. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  56476. ** callback. In this case this function runs a blocking checkpoint.
  56477. */
  56478. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  56479. Wal *pWal, /* Wal connection */
  56480. sqlite3 *db, /* Check this handle's interrupt flag */
  56481. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  56482. int (*xBusy)(void*), /* Function to call when busy */
  56483. void *pBusyArg, /* Context argument for xBusyHandler */
  56484. int sync_flags, /* Flags to sync db file with (or 0) */
  56485. int nBuf, /* Size of temporary buffer */
  56486. u8 *zBuf, /* Temporary buffer to use */
  56487. int *pnLog, /* OUT: Number of frames in WAL */
  56488. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  56489. ){
  56490. int rc; /* Return code */
  56491. int isChanged = 0; /* True if a new wal-index header is loaded */
  56492. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  56493. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  56494. assert( pWal->ckptLock==0 );
  56495. assert( pWal->writeLock==0 );
  56496. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  56497. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  56498. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  56499. if( pWal->readOnly ) return SQLITE_READONLY;
  56500. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  56501. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  56502. ** "checkpoint" lock on the database file. */
  56503. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  56504. if( rc ){
  56505. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  56506. ** checkpoint operation at the same time, the lock cannot be obtained and
  56507. ** SQLITE_BUSY is returned.
  56508. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  56509. ** it will not be invoked in this case.
  56510. */
  56511. testcase( rc==SQLITE_BUSY );
  56512. testcase( xBusy!=0 );
  56513. return rc;
  56514. }
  56515. pWal->ckptLock = 1;
  56516. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  56517. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  56518. ** file.
  56519. **
  56520. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  56521. ** immediately, and a busy-handler is configured, it is invoked and the
  56522. ** writer lock retried until either the busy-handler returns 0 or the
  56523. ** lock is successfully obtained.
  56524. */
  56525. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  56526. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  56527. if( rc==SQLITE_OK ){
  56528. pWal->writeLock = 1;
  56529. }else if( rc==SQLITE_BUSY ){
  56530. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  56531. xBusy2 = 0;
  56532. rc = SQLITE_OK;
  56533. }
  56534. }
  56535. /* Read the wal-index header. */
  56536. if( rc==SQLITE_OK ){
  56537. rc = walIndexReadHdr(pWal, &isChanged);
  56538. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  56539. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  56540. }
  56541. }
  56542. /* Copy data from the log to the database file. */
  56543. if( rc==SQLITE_OK ){
  56544. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  56545. rc = SQLITE_CORRUPT_BKPT;
  56546. }else{
  56547. rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  56548. }
  56549. /* If no error occurred, set the output variables. */
  56550. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  56551. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  56552. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  56553. }
  56554. }
  56555. if( isChanged ){
  56556. /* If a new wal-index header was loaded before the checkpoint was
  56557. ** performed, then the pager-cache associated with pWal is now
  56558. ** out of date. So zero the cached wal-index header to ensure that
  56559. ** next time the pager opens a snapshot on this database it knows that
  56560. ** the cache needs to be reset.
  56561. */
  56562. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  56563. }
  56564. /* Release the locks. */
  56565. sqlite3WalEndWriteTransaction(pWal);
  56566. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  56567. pWal->ckptLock = 0;
  56568. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  56569. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  56570. }
  56571. /* Return the value to pass to a sqlite3_wal_hook callback, the
  56572. ** number of frames in the WAL at the point of the last commit since
  56573. ** sqlite3WalCallback() was called. If no commits have occurred since
  56574. ** the last call, then return 0.
  56575. */
  56576. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  56577. u32 ret = 0;
  56578. if( pWal ){
  56579. ret = pWal->iCallback;
  56580. pWal->iCallback = 0;
  56581. }
  56582. return (int)ret;
  56583. }
  56584. /*
  56585. ** This function is called to change the WAL subsystem into or out
  56586. ** of locking_mode=EXCLUSIVE.
  56587. **
  56588. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  56589. ** into locking_mode=NORMAL. This means that we must acquire a lock
  56590. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  56591. ** or if the acquisition of the lock fails, then return 0. If the
  56592. ** transition out of exclusive-mode is successful, return 1. This
  56593. ** operation must occur while the pager is still holding the exclusive
  56594. ** lock on the main database file.
  56595. **
  56596. ** If op is one, then change from locking_mode=NORMAL into
  56597. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  56598. ** be released. Return 1 if the transition is made and 0 if the
  56599. ** WAL is already in exclusive-locking mode - meaning that this
  56600. ** routine is a no-op. The pager must already hold the exclusive lock
  56601. ** on the main database file before invoking this operation.
  56602. **
  56603. ** If op is negative, then do a dry-run of the op==1 case but do
  56604. ** not actually change anything. The pager uses this to see if it
  56605. ** should acquire the database exclusive lock prior to invoking
  56606. ** the op==1 case.
  56607. */
  56608. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  56609. int rc;
  56610. assert( pWal->writeLock==0 );
  56611. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  56612. /* pWal->readLock is usually set, but might be -1 if there was a
  56613. ** prior error while attempting to acquire are read-lock. This cannot
  56614. ** happen if the connection is actually in exclusive mode (as no xShmLock
  56615. ** locks are taken in this case). Nor should the pager attempt to
  56616. ** upgrade to exclusive-mode following such an error.
  56617. */
  56618. assert( pWal->readLock>=0 || pWal->lockError );
  56619. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  56620. if( op==0 ){
  56621. if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
  56622. pWal->exclusiveMode = WAL_NORMAL_MODE;
  56623. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  56624. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  56625. }
  56626. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  56627. }else{
  56628. /* Already in locking_mode=NORMAL */
  56629. rc = 0;
  56630. }
  56631. }else if( op>0 ){
  56632. assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
  56633. assert( pWal->readLock>=0 );
  56634. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  56635. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  56636. rc = 1;
  56637. }else{
  56638. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  56639. }
  56640. return rc;
  56641. }
  56642. /*
  56643. ** Return true if the argument is non-NULL and the WAL module is using
  56644. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  56645. ** WAL module is using shared-memory, return false.
  56646. */
  56647. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  56648. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  56649. }
  56650. #ifdef SQLITE_ENABLE_SNAPSHOT
  56651. /* Create a snapshot object. The content of a snapshot is opaque to
  56652. ** every other subsystem, so the WAL module can put whatever it needs
  56653. ** in the object.
  56654. */
  56655. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  56656. int rc = SQLITE_OK;
  56657. WalIndexHdr *pRet;
  56658. static const u32 aZero[4] = { 0, 0, 0, 0 };
  56659. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  56660. if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
  56661. *ppSnapshot = 0;
  56662. return SQLITE_ERROR;
  56663. }
  56664. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  56665. if( pRet==0 ){
  56666. rc = SQLITE_NOMEM_BKPT;
  56667. }else{
  56668. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  56669. *ppSnapshot = (sqlite3_snapshot*)pRet;
  56670. }
  56671. return rc;
  56672. }
  56673. /* Try to open on pSnapshot when the next read-transaction starts
  56674. */
  56675. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
  56676. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  56677. }
  56678. /*
  56679. ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
  56680. ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
  56681. */
  56682. SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
  56683. WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
  56684. WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
  56685. /* aSalt[0] is a copy of the value stored in the wal file header. It
  56686. ** is incremented each time the wal file is restarted. */
  56687. if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
  56688. if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
  56689. if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
  56690. if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
  56691. return 0;
  56692. }
  56693. #endif /* SQLITE_ENABLE_SNAPSHOT */
  56694. #ifdef SQLITE_ENABLE_ZIPVFS
  56695. /*
  56696. ** If the argument is not NULL, it points to a Wal object that holds a
  56697. ** read-lock. This function returns the database page-size if it is known,
  56698. ** or zero if it is not (or if pWal is NULL).
  56699. */
  56700. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  56701. assert( pWal==0 || pWal->readLock>=0 );
  56702. return (pWal ? pWal->szPage : 0);
  56703. }
  56704. #endif
  56705. /* Return the sqlite3_file object for the WAL file
  56706. */
  56707. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  56708. return pWal->pWalFd;
  56709. }
  56710. #endif /* #ifndef SQLITE_OMIT_WAL */
  56711. /************** End of wal.c *************************************************/
  56712. /************** Begin file btmutex.c *****************************************/
  56713. /*
  56714. ** 2007 August 27
  56715. **
  56716. ** The author disclaims copyright to this source code. In place of
  56717. ** a legal notice, here is a blessing:
  56718. **
  56719. ** May you do good and not evil.
  56720. ** May you find forgiveness for yourself and forgive others.
  56721. ** May you share freely, never taking more than you give.
  56722. **
  56723. *************************************************************************
  56724. **
  56725. ** This file contains code used to implement mutexes on Btree objects.
  56726. ** This code really belongs in btree.c. But btree.c is getting too
  56727. ** big and we want to break it down some. This packaged seemed like
  56728. ** a good breakout.
  56729. */
  56730. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  56731. /************** Begin file btreeInt.h ****************************************/
  56732. /*
  56733. ** 2004 April 6
  56734. **
  56735. ** The author disclaims copyright to this source code. In place of
  56736. ** a legal notice, here is a blessing:
  56737. **
  56738. ** May you do good and not evil.
  56739. ** May you find forgiveness for yourself and forgive others.
  56740. ** May you share freely, never taking more than you give.
  56741. **
  56742. *************************************************************************
  56743. ** This file implements an external (disk-based) database using BTrees.
  56744. ** For a detailed discussion of BTrees, refer to
  56745. **
  56746. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  56747. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  56748. ** Publishing Company, Reading, Massachusetts.
  56749. **
  56750. ** The basic idea is that each page of the file contains N database
  56751. ** entries and N+1 pointers to subpages.
  56752. **
  56753. ** ----------------------------------------------------------------
  56754. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  56755. ** ----------------------------------------------------------------
  56756. **
  56757. ** All of the keys on the page that Ptr(0) points to have values less
  56758. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  56759. ** values greater than Key(0) and less than Key(1). All of the keys
  56760. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  56761. ** so forth.
  56762. **
  56763. ** Finding a particular key requires reading O(log(M)) pages from the
  56764. ** disk where M is the number of entries in the tree.
  56765. **
  56766. ** In this implementation, a single file can hold one or more separate
  56767. ** BTrees. Each BTree is identified by the index of its root page. The
  56768. ** key and data for any entry are combined to form the "payload". A
  56769. ** fixed amount of payload can be carried directly on the database
  56770. ** page. If the payload is larger than the preset amount then surplus
  56771. ** bytes are stored on overflow pages. The payload for an entry
  56772. ** and the preceding pointer are combined to form a "Cell". Each
  56773. ** page has a small header which contains the Ptr(N) pointer and other
  56774. ** information such as the size of key and data.
  56775. **
  56776. ** FORMAT DETAILS
  56777. **
  56778. ** The file is divided into pages. The first page is called page 1,
  56779. ** the second is page 2, and so forth. A page number of zero indicates
  56780. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  56781. ** Each page can be either a btree page, a freelist page, an overflow
  56782. ** page, or a pointer-map page.
  56783. **
  56784. ** The first page is always a btree page. The first 100 bytes of the first
  56785. ** page contain a special header (the "file header") that describes the file.
  56786. ** The format of the file header is as follows:
  56787. **
  56788. ** OFFSET SIZE DESCRIPTION
  56789. ** 0 16 Header string: "SQLite format 3\000"
  56790. ** 16 2 Page size in bytes. (1 means 65536)
  56791. ** 18 1 File format write version
  56792. ** 19 1 File format read version
  56793. ** 20 1 Bytes of unused space at the end of each page
  56794. ** 21 1 Max embedded payload fraction (must be 64)
  56795. ** 22 1 Min embedded payload fraction (must be 32)
  56796. ** 23 1 Min leaf payload fraction (must be 32)
  56797. ** 24 4 File change counter
  56798. ** 28 4 Reserved for future use
  56799. ** 32 4 First freelist page
  56800. ** 36 4 Number of freelist pages in the file
  56801. ** 40 60 15 4-byte meta values passed to higher layers
  56802. **
  56803. ** 40 4 Schema cookie
  56804. ** 44 4 File format of schema layer
  56805. ** 48 4 Size of page cache
  56806. ** 52 4 Largest root-page (auto/incr_vacuum)
  56807. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  56808. ** 60 4 User version
  56809. ** 64 4 Incremental vacuum mode
  56810. ** 68 4 Application-ID
  56811. ** 72 20 unused
  56812. ** 92 4 The version-valid-for number
  56813. ** 96 4 SQLITE_VERSION_NUMBER
  56814. **
  56815. ** All of the integer values are big-endian (most significant byte first).
  56816. **
  56817. ** The file change counter is incremented when the database is changed
  56818. ** This counter allows other processes to know when the file has changed
  56819. ** and thus when they need to flush their cache.
  56820. **
  56821. ** The max embedded payload fraction is the amount of the total usable
  56822. ** space in a page that can be consumed by a single cell for standard
  56823. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  56824. ** is to limit the maximum cell size so that at least 4 cells will fit
  56825. ** on one page. Thus the default max embedded payload fraction is 64.
  56826. **
  56827. ** If the payload for a cell is larger than the max payload, then extra
  56828. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  56829. ** as many bytes as possible are moved into the overflow pages without letting
  56830. ** the cell size drop below the min embedded payload fraction.
  56831. **
  56832. ** The min leaf payload fraction is like the min embedded payload fraction
  56833. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  56834. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  56835. ** not specified in the header.
  56836. **
  56837. ** Each btree pages is divided into three sections: The header, the
  56838. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  56839. ** file header that occurs before the page header.
  56840. **
  56841. ** |----------------|
  56842. ** | file header | 100 bytes. Page 1 only.
  56843. ** |----------------|
  56844. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  56845. ** |----------------|
  56846. ** | cell pointer | | 2 bytes per cell. Sorted order.
  56847. ** | array | | Grows downward
  56848. ** | | v
  56849. ** |----------------|
  56850. ** | unallocated |
  56851. ** | space |
  56852. ** |----------------| ^ Grows upwards
  56853. ** | cell content | | Arbitrary order interspersed with freeblocks.
  56854. ** | area | | and free space fragments.
  56855. ** |----------------|
  56856. **
  56857. ** The page headers looks like this:
  56858. **
  56859. ** OFFSET SIZE DESCRIPTION
  56860. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  56861. ** 1 2 byte offset to the first freeblock
  56862. ** 3 2 number of cells on this page
  56863. ** 5 2 first byte of the cell content area
  56864. ** 7 1 number of fragmented free bytes
  56865. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  56866. **
  56867. ** The flags define the format of this btree page. The leaf flag means that
  56868. ** this page has no children. The zerodata flag means that this page carries
  56869. ** only keys and no data. The intkey flag means that the key is an integer
  56870. ** which is stored in the key size entry of the cell header rather than in
  56871. ** the payload area.
  56872. **
  56873. ** The cell pointer array begins on the first byte after the page header.
  56874. ** The cell pointer array contains zero or more 2-byte numbers which are
  56875. ** offsets from the beginning of the page to the cell content in the cell
  56876. ** content area. The cell pointers occur in sorted order. The system strives
  56877. ** to keep free space after the last cell pointer so that new cells can
  56878. ** be easily added without having to defragment the page.
  56879. **
  56880. ** Cell content is stored at the very end of the page and grows toward the
  56881. ** beginning of the page.
  56882. **
  56883. ** Unused space within the cell content area is collected into a linked list of
  56884. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  56885. ** to the first freeblock is given in the header. Freeblocks occur in
  56886. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  56887. ** any group of 3 or fewer unused bytes in the cell content area cannot
  56888. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  56889. ** a fragment. The total number of bytes in all fragments is recorded.
  56890. ** in the page header at offset 7.
  56891. **
  56892. ** SIZE DESCRIPTION
  56893. ** 2 Byte offset of the next freeblock
  56894. ** 2 Bytes in this freeblock
  56895. **
  56896. ** Cells are of variable length. Cells are stored in the cell content area at
  56897. ** the end of the page. Pointers to the cells are in the cell pointer array
  56898. ** that immediately follows the page header. Cells is not necessarily
  56899. ** contiguous or in order, but cell pointers are contiguous and in order.
  56900. **
  56901. ** Cell content makes use of variable length integers. A variable
  56902. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  56903. ** byte are used. The integer consists of all bytes that have bit 8 set and
  56904. ** the first byte with bit 8 clear. The most significant byte of the integer
  56905. ** appears first. A variable-length integer may not be more than 9 bytes long.
  56906. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  56907. ** allows a 64-bit integer to be encoded in 9 bytes.
  56908. **
  56909. ** 0x00 becomes 0x00000000
  56910. ** 0x7f becomes 0x0000007f
  56911. ** 0x81 0x00 becomes 0x00000080
  56912. ** 0x82 0x00 becomes 0x00000100
  56913. ** 0x80 0x7f becomes 0x0000007f
  56914. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  56915. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  56916. **
  56917. ** Variable length integers are used for rowids and to hold the number of
  56918. ** bytes of key and data in a btree cell.
  56919. **
  56920. ** The content of a cell looks like this:
  56921. **
  56922. ** SIZE DESCRIPTION
  56923. ** 4 Page number of the left child. Omitted if leaf flag is set.
  56924. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  56925. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  56926. ** * Payload
  56927. ** 4 First page of the overflow chain. Omitted if no overflow
  56928. **
  56929. ** Overflow pages form a linked list. Each page except the last is completely
  56930. ** filled with data (pagesize - 4 bytes). The last page can have as little
  56931. ** as 1 byte of data.
  56932. **
  56933. ** SIZE DESCRIPTION
  56934. ** 4 Page number of next overflow page
  56935. ** * Data
  56936. **
  56937. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  56938. ** file header points to the first in a linked list of trunk page. Each trunk
  56939. ** page points to multiple leaf pages. The content of a leaf page is
  56940. ** unspecified. A trunk page looks like this:
  56941. **
  56942. ** SIZE DESCRIPTION
  56943. ** 4 Page number of next trunk page
  56944. ** 4 Number of leaf pointers on this page
  56945. ** * zero or more pages numbers of leaves
  56946. */
  56947. /* #include "sqliteInt.h" */
  56948. /* The following value is the maximum cell size assuming a maximum page
  56949. ** size give above.
  56950. */
  56951. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  56952. /* The maximum number of cells on a single page of the database. This
  56953. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  56954. ** plus 2 bytes for the index to the cell in the page header). Such
  56955. ** small cells will be rare, but they are possible.
  56956. */
  56957. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  56958. /* Forward declarations */
  56959. typedef struct MemPage MemPage;
  56960. typedef struct BtLock BtLock;
  56961. typedef struct CellInfo CellInfo;
  56962. /*
  56963. ** This is a magic string that appears at the beginning of every
  56964. ** SQLite database in order to identify the file as a real database.
  56965. **
  56966. ** You can change this value at compile-time by specifying a
  56967. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  56968. ** header must be exactly 16 bytes including the zero-terminator so
  56969. ** the string itself should be 15 characters long. If you change
  56970. ** the header, then your custom library will not be able to read
  56971. ** databases generated by the standard tools and the standard tools
  56972. ** will not be able to read databases created by your custom library.
  56973. */
  56974. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  56975. # define SQLITE_FILE_HEADER "SQLite format 3"
  56976. #endif
  56977. /*
  56978. ** Page type flags. An ORed combination of these flags appear as the
  56979. ** first byte of on-disk image of every BTree page.
  56980. */
  56981. #define PTF_INTKEY 0x01
  56982. #define PTF_ZERODATA 0x02
  56983. #define PTF_LEAFDATA 0x04
  56984. #define PTF_LEAF 0x08
  56985. /*
  56986. ** An instance of this object stores information about each a single database
  56987. ** page that has been loaded into memory. The information in this object
  56988. ** is derived from the raw on-disk page content.
  56989. **
  56990. ** As each database page is loaded into memory, the pager allocats an
  56991. ** instance of this object and zeros the first 8 bytes. (This is the
  56992. ** "extra" information associated with each page of the pager.)
  56993. **
  56994. ** Access to all fields of this structure is controlled by the mutex
  56995. ** stored in MemPage.pBt->mutex.
  56996. */
  56997. struct MemPage {
  56998. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  56999. u8 bBusy; /* Prevent endless loops on corrupt database files */
  57000. u8 intKey; /* True if table b-trees. False for index b-trees */
  57001. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  57002. Pgno pgno; /* Page number for this page */
  57003. /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
  57004. ** is allocated. All fields that follow must be initialized before use */
  57005. u8 leaf; /* True if a leaf page */
  57006. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  57007. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  57008. u8 max1bytePayload; /* min(maxLocal,127) */
  57009. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  57010. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  57011. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  57012. u16 cellOffset; /* Index in aData of first cell pointer */
  57013. u16 nFree; /* Number of free bytes on the page */
  57014. u16 nCell; /* Number of cells on this page, local and ovfl */
  57015. u16 maskPage; /* Mask for page offset */
  57016. u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
  57017. ** non-overflow cell */
  57018. u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
  57019. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  57020. u8 *aData; /* Pointer to disk image of the page data */
  57021. u8 *aDataEnd; /* One byte past the end of usable data */
  57022. u8 *aCellIdx; /* The cell index area */
  57023. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  57024. DbPage *pDbPage; /* Pager page handle */
  57025. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  57026. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  57027. };
  57028. /*
  57029. ** A linked list of the following structures is stored at BtShared.pLock.
  57030. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  57031. ** is opened on the table with root page BtShared.iTable. Locks are removed
  57032. ** from this list when a transaction is committed or rolled back, or when
  57033. ** a btree handle is closed.
  57034. */
  57035. struct BtLock {
  57036. Btree *pBtree; /* Btree handle holding this lock */
  57037. Pgno iTable; /* Root page of table */
  57038. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  57039. BtLock *pNext; /* Next in BtShared.pLock list */
  57040. };
  57041. /* Candidate values for BtLock.eLock */
  57042. #define READ_LOCK 1
  57043. #define WRITE_LOCK 2
  57044. /* A Btree handle
  57045. **
  57046. ** A database connection contains a pointer to an instance of
  57047. ** this object for every database file that it has open. This structure
  57048. ** is opaque to the database connection. The database connection cannot
  57049. ** see the internals of this structure and only deals with pointers to
  57050. ** this structure.
  57051. **
  57052. ** For some database files, the same underlying database cache might be
  57053. ** shared between multiple connections. In that case, each connection
  57054. ** has it own instance of this object. But each instance of this object
  57055. ** points to the same BtShared object. The database cache and the
  57056. ** schema associated with the database file are all contained within
  57057. ** the BtShared object.
  57058. **
  57059. ** All fields in this structure are accessed under sqlite3.mutex.
  57060. ** The pBt pointer itself may not be changed while there exists cursors
  57061. ** in the referenced BtShared that point back to this Btree since those
  57062. ** cursors have to go through this Btree to find their BtShared and
  57063. ** they often do so without holding sqlite3.mutex.
  57064. */
  57065. struct Btree {
  57066. sqlite3 *db; /* The database connection holding this btree */
  57067. BtShared *pBt; /* Sharable content of this btree */
  57068. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  57069. u8 sharable; /* True if we can share pBt with another db */
  57070. u8 locked; /* True if db currently has pBt locked */
  57071. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  57072. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  57073. int nBackup; /* Number of backup operations reading this btree */
  57074. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  57075. Btree *pNext; /* List of other sharable Btrees from the same db */
  57076. Btree *pPrev; /* Back pointer of the same list */
  57077. #ifndef SQLITE_OMIT_SHARED_CACHE
  57078. BtLock lock; /* Object used to lock page 1 */
  57079. #endif
  57080. };
  57081. /*
  57082. ** Btree.inTrans may take one of the following values.
  57083. **
  57084. ** If the shared-data extension is enabled, there may be multiple users
  57085. ** of the Btree structure. At most one of these may open a write transaction,
  57086. ** but any number may have active read transactions.
  57087. */
  57088. #define TRANS_NONE 0
  57089. #define TRANS_READ 1
  57090. #define TRANS_WRITE 2
  57091. /*
  57092. ** An instance of this object represents a single database file.
  57093. **
  57094. ** A single database file can be in use at the same time by two
  57095. ** or more database connections. When two or more connections are
  57096. ** sharing the same database file, each connection has it own
  57097. ** private Btree object for the file and each of those Btrees points
  57098. ** to this one BtShared object. BtShared.nRef is the number of
  57099. ** connections currently sharing this database file.
  57100. **
  57101. ** Fields in this structure are accessed under the BtShared.mutex
  57102. ** mutex, except for nRef and pNext which are accessed under the
  57103. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  57104. ** may not be modified once it is initially set as long as nRef>0.
  57105. ** The pSchema field may be set once under BtShared.mutex and
  57106. ** thereafter is unchanged as long as nRef>0.
  57107. **
  57108. ** isPending:
  57109. **
  57110. ** If a BtShared client fails to obtain a write-lock on a database
  57111. ** table (because there exists one or more read-locks on the table),
  57112. ** the shared-cache enters 'pending-lock' state and isPending is
  57113. ** set to true.
  57114. **
  57115. ** The shared-cache leaves the 'pending lock' state when either of
  57116. ** the following occur:
  57117. **
  57118. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  57119. ** 2) The number of locks held by other connections drops to zero.
  57120. **
  57121. ** while in the 'pending-lock' state, no connection may start a new
  57122. ** transaction.
  57123. **
  57124. ** This feature is included to help prevent writer-starvation.
  57125. */
  57126. struct BtShared {
  57127. Pager *pPager; /* The page cache */
  57128. sqlite3 *db; /* Database connection currently using this Btree */
  57129. BtCursor *pCursor; /* A list of all open cursors */
  57130. MemPage *pPage1; /* First page of the database */
  57131. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  57132. #ifndef SQLITE_OMIT_AUTOVACUUM
  57133. u8 autoVacuum; /* True if auto-vacuum is enabled */
  57134. u8 incrVacuum; /* True if incr-vacuum is enabled */
  57135. u8 bDoTruncate; /* True to truncate db on commit */
  57136. #endif
  57137. u8 inTransaction; /* Transaction state */
  57138. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  57139. #ifdef SQLITE_HAS_CODEC
  57140. u8 optimalReserve; /* Desired amount of reserved space per page */
  57141. #endif
  57142. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  57143. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  57144. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  57145. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  57146. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  57147. u32 pageSize; /* Total number of bytes on a page */
  57148. u32 usableSize; /* Number of usable bytes on each page */
  57149. int nTransaction; /* Number of open transactions (read + write) */
  57150. u32 nPage; /* Number of pages in the database */
  57151. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  57152. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  57153. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  57154. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  57155. #ifndef SQLITE_OMIT_SHARED_CACHE
  57156. int nRef; /* Number of references to this structure */
  57157. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  57158. BtLock *pLock; /* List of locks held on this shared-btree struct */
  57159. Btree *pWriter; /* Btree with currently open write transaction */
  57160. #endif
  57161. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  57162. };
  57163. /*
  57164. ** Allowed values for BtShared.btsFlags
  57165. */
  57166. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  57167. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  57168. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  57169. #define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */
  57170. #define BTS_FAST_SECURE 0x000c /* Combination of the previous two */
  57171. #define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */
  57172. #define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
  57173. #define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
  57174. #define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
  57175. /*
  57176. ** An instance of the following structure is used to hold information
  57177. ** about a cell. The parseCellPtr() function fills in this structure
  57178. ** based on information extract from the raw disk page.
  57179. */
  57180. struct CellInfo {
  57181. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  57182. u8 *pPayload; /* Pointer to the start of payload */
  57183. u32 nPayload; /* Bytes of payload */
  57184. u16 nLocal; /* Amount of payload held locally, not on overflow */
  57185. u16 nSize; /* Size of the cell content on the main b-tree page */
  57186. };
  57187. /*
  57188. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  57189. ** this will be declared corrupt. This value is calculated based on a
  57190. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  57191. ** root-node and 3 for all other internal nodes.
  57192. **
  57193. ** If a tree that appears to be taller than this is encountered, it is
  57194. ** assumed that the database is corrupt.
  57195. */
  57196. #define BTCURSOR_MAX_DEPTH 20
  57197. /*
  57198. ** A cursor is a pointer to a particular entry within a particular
  57199. ** b-tree within a database file.
  57200. **
  57201. ** The entry is identified by its MemPage and the index in
  57202. ** MemPage.aCell[] of the entry.
  57203. **
  57204. ** A single database file can be shared by two more database connections,
  57205. ** but cursors cannot be shared. Each cursor is associated with a
  57206. ** particular database connection identified BtCursor.pBtree.db.
  57207. **
  57208. ** Fields in this structure are accessed under the BtShared.mutex
  57209. ** found at self->pBt->mutex.
  57210. **
  57211. ** skipNext meaning:
  57212. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  57213. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  57214. ** eState==FAULT: Cursor fault with skipNext as error code.
  57215. */
  57216. struct BtCursor {
  57217. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  57218. u8 curFlags; /* zero or more BTCF_* flags defined below */
  57219. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  57220. u8 hints; /* As configured by CursorSetHints() */
  57221. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  57222. ** Error code if eState==CURSOR_FAULT */
  57223. Btree *pBtree; /* The Btree to which this cursor belongs */
  57224. Pgno *aOverflow; /* Cache of overflow page locations */
  57225. void *pKey; /* Saved key that was cursor last known position */
  57226. /* All fields above are zeroed when the cursor is allocated. See
  57227. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  57228. ** initialized. */
  57229. #define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
  57230. BtShared *pBt; /* The BtShared this cursor points to */
  57231. BtCursor *pNext; /* Forms a linked list of all cursors */
  57232. CellInfo info; /* A parse of the cell we are pointing at */
  57233. i64 nKey; /* Size of pKey, or last integer key */
  57234. Pgno pgnoRoot; /* The root page of this tree */
  57235. i8 iPage; /* Index of current page in apPage */
  57236. u8 curIntKey; /* Value of apPage[0]->intKey */
  57237. u16 ix; /* Current index for apPage[iPage] */
  57238. u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
  57239. struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
  57240. MemPage *pPage; /* Current page */
  57241. MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
  57242. };
  57243. /*
  57244. ** Legal values for BtCursor.curFlags
  57245. */
  57246. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  57247. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  57248. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  57249. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  57250. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  57251. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  57252. /*
  57253. ** Potential values for BtCursor.eState.
  57254. **
  57255. ** CURSOR_INVALID:
  57256. ** Cursor does not point to a valid entry. This can happen (for example)
  57257. ** because the table is empty or because BtreeCursorFirst() has not been
  57258. ** called.
  57259. **
  57260. ** CURSOR_VALID:
  57261. ** Cursor points to a valid entry. getPayload() etc. may be called.
  57262. **
  57263. ** CURSOR_SKIPNEXT:
  57264. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  57265. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  57266. ** operation should be a no-op.
  57267. **
  57268. ** CURSOR_REQUIRESEEK:
  57269. ** The table that this cursor was opened on still exists, but has been
  57270. ** modified since the cursor was last used. The cursor position is saved
  57271. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  57272. ** this state, restoreCursorPosition() can be called to attempt to
  57273. ** seek the cursor to the saved position.
  57274. **
  57275. ** CURSOR_FAULT:
  57276. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  57277. ** on a different connection that shares the BtShared cache with this
  57278. ** cursor. The error has left the cache in an inconsistent state.
  57279. ** Do nothing else with this cursor. Any attempt to use the cursor
  57280. ** should return the error code stored in BtCursor.skipNext
  57281. */
  57282. #define CURSOR_VALID 0
  57283. #define CURSOR_INVALID 1
  57284. #define CURSOR_SKIPNEXT 2
  57285. #define CURSOR_REQUIRESEEK 3
  57286. #define CURSOR_FAULT 4
  57287. /*
  57288. ** The database page the PENDING_BYTE occupies. This page is never used.
  57289. */
  57290. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  57291. /*
  57292. ** These macros define the location of the pointer-map entry for a
  57293. ** database page. The first argument to each is the number of usable
  57294. ** bytes on each page of the database (often 1024). The second is the
  57295. ** page number to look up in the pointer map.
  57296. **
  57297. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  57298. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  57299. ** the offset of the requested map entry.
  57300. **
  57301. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  57302. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  57303. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  57304. ** this test.
  57305. */
  57306. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  57307. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  57308. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  57309. /*
  57310. ** The pointer map is a lookup table that identifies the parent page for
  57311. ** each child page in the database file. The parent page is the page that
  57312. ** contains a pointer to the child. Every page in the database contains
  57313. ** 0 or 1 parent pages. (In this context 'database page' refers
  57314. ** to any page that is not part of the pointer map itself.) Each pointer map
  57315. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  57316. ** The PTRMAP_XXX identifiers below are the valid types.
  57317. **
  57318. ** The purpose of the pointer map is to facility moving pages from one
  57319. ** position in the file to another as part of autovacuum. When a page
  57320. ** is moved, the pointer in its parent must be updated to point to the
  57321. ** new location. The pointer map is used to locate the parent page quickly.
  57322. **
  57323. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  57324. ** used in this case.
  57325. **
  57326. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  57327. ** is not used in this case.
  57328. **
  57329. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  57330. ** overflow pages. The page number identifies the page that
  57331. ** contains the cell with a pointer to this overflow page.
  57332. **
  57333. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  57334. ** overflow pages. The page-number identifies the previous
  57335. ** page in the overflow page list.
  57336. **
  57337. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  57338. ** identifies the parent page in the btree.
  57339. */
  57340. #define PTRMAP_ROOTPAGE 1
  57341. #define PTRMAP_FREEPAGE 2
  57342. #define PTRMAP_OVERFLOW1 3
  57343. #define PTRMAP_OVERFLOW2 4
  57344. #define PTRMAP_BTREE 5
  57345. /* A bunch of assert() statements to check the transaction state variables
  57346. ** of handle p (type Btree*) are internally consistent.
  57347. */
  57348. #define btreeIntegrity(p) \
  57349. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  57350. assert( p->pBt->inTransaction>=p->inTrans );
  57351. /*
  57352. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  57353. ** if the database supports auto-vacuum or not. Because it is used
  57354. ** within an expression that is an argument to another macro
  57355. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  57356. ** So, this macro is defined instead.
  57357. */
  57358. #ifndef SQLITE_OMIT_AUTOVACUUM
  57359. #define ISAUTOVACUUM (pBt->autoVacuum)
  57360. #else
  57361. #define ISAUTOVACUUM 0
  57362. #endif
  57363. /*
  57364. ** This structure is passed around through all the sanity checking routines
  57365. ** in order to keep track of some global state information.
  57366. **
  57367. ** The aRef[] array is allocated so that there is 1 bit for each page in
  57368. ** the database. As the integrity-check proceeds, for each page used in
  57369. ** the database the corresponding bit is set. This allows integrity-check to
  57370. ** detect pages that are used twice and orphaned pages (both of which
  57371. ** indicate corruption).
  57372. */
  57373. typedef struct IntegrityCk IntegrityCk;
  57374. struct IntegrityCk {
  57375. BtShared *pBt; /* The tree being checked out */
  57376. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  57377. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  57378. Pgno nPage; /* Number of pages in the database */
  57379. int mxErr; /* Stop accumulating errors when this reaches zero */
  57380. int nErr; /* Number of messages written to zErrMsg so far */
  57381. int mallocFailed; /* A memory allocation error has occurred */
  57382. const char *zPfx; /* Error message prefix */
  57383. int v1, v2; /* Values for up to two %d fields in zPfx */
  57384. StrAccum errMsg; /* Accumulate the error message text here */
  57385. u32 *heap; /* Min-heap used for analyzing cell coverage */
  57386. };
  57387. /*
  57388. ** Routines to read or write a two- and four-byte big-endian integer values.
  57389. */
  57390. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  57391. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  57392. #define get4byte sqlite3Get4byte
  57393. #define put4byte sqlite3Put4byte
  57394. /*
  57395. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  57396. ** two-byte aligned address. get2bytea() is only used for accessing the
  57397. ** cell addresses in a btree header.
  57398. */
  57399. #if SQLITE_BYTEORDER==4321
  57400. # define get2byteAligned(x) (*(u16*)(x))
  57401. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
  57402. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  57403. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  57404. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  57405. #else
  57406. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  57407. #endif
  57408. /************** End of btreeInt.h ********************************************/
  57409. /************** Continuing where we left off in btmutex.c ********************/
  57410. #ifndef SQLITE_OMIT_SHARED_CACHE
  57411. #if SQLITE_THREADSAFE
  57412. /*
  57413. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  57414. ** set BtShared.db to the database handle associated with p and the
  57415. ** p->locked boolean to true.
  57416. */
  57417. static void lockBtreeMutex(Btree *p){
  57418. assert( p->locked==0 );
  57419. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  57420. assert( sqlite3_mutex_held(p->db->mutex) );
  57421. sqlite3_mutex_enter(p->pBt->mutex);
  57422. p->pBt->db = p->db;
  57423. p->locked = 1;
  57424. }
  57425. /*
  57426. ** Release the BtShared mutex associated with B-Tree handle p and
  57427. ** clear the p->locked boolean.
  57428. */
  57429. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  57430. BtShared *pBt = p->pBt;
  57431. assert( p->locked==1 );
  57432. assert( sqlite3_mutex_held(pBt->mutex) );
  57433. assert( sqlite3_mutex_held(p->db->mutex) );
  57434. assert( p->db==pBt->db );
  57435. sqlite3_mutex_leave(pBt->mutex);
  57436. p->locked = 0;
  57437. }
  57438. /* Forward reference */
  57439. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  57440. /*
  57441. ** Enter a mutex on the given BTree object.
  57442. **
  57443. ** If the object is not sharable, then no mutex is ever required
  57444. ** and this routine is a no-op. The underlying mutex is non-recursive.
  57445. ** But we keep a reference count in Btree.wantToLock so the behavior
  57446. ** of this interface is recursive.
  57447. **
  57448. ** To avoid deadlocks, multiple Btrees are locked in the same order
  57449. ** by all database connections. The p->pNext is a list of other
  57450. ** Btrees belonging to the same database connection as the p Btree
  57451. ** which need to be locked after p. If we cannot get a lock on
  57452. ** p, then first unlock all of the others on p->pNext, then wait
  57453. ** for the lock to become available on p, then relock all of the
  57454. ** subsequent Btrees that desire a lock.
  57455. */
  57456. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  57457. /* Some basic sanity checking on the Btree. The list of Btrees
  57458. ** connected by pNext and pPrev should be in sorted order by
  57459. ** Btree.pBt value. All elements of the list should belong to
  57460. ** the same connection. Only shared Btrees are on the list. */
  57461. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  57462. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  57463. assert( p->pNext==0 || p->pNext->db==p->db );
  57464. assert( p->pPrev==0 || p->pPrev->db==p->db );
  57465. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  57466. /* Check for locking consistency */
  57467. assert( !p->locked || p->wantToLock>0 );
  57468. assert( p->sharable || p->wantToLock==0 );
  57469. /* We should already hold a lock on the database connection */
  57470. assert( sqlite3_mutex_held(p->db->mutex) );
  57471. /* Unless the database is sharable and unlocked, then BtShared.db
  57472. ** should already be set correctly. */
  57473. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  57474. if( !p->sharable ) return;
  57475. p->wantToLock++;
  57476. if( p->locked ) return;
  57477. btreeLockCarefully(p);
  57478. }
  57479. /* This is a helper function for sqlite3BtreeLock(). By moving
  57480. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  57481. ** into this routine, we avoid unnecessary stack pointer changes
  57482. ** and thus help the sqlite3BtreeLock() routine to run much faster
  57483. ** in the common case.
  57484. */
  57485. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  57486. Btree *pLater;
  57487. /* In most cases, we should be able to acquire the lock we
  57488. ** want without having to go through the ascending lock
  57489. ** procedure that follows. Just be sure not to block.
  57490. */
  57491. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  57492. p->pBt->db = p->db;
  57493. p->locked = 1;
  57494. return;
  57495. }
  57496. /* To avoid deadlock, first release all locks with a larger
  57497. ** BtShared address. Then acquire our lock. Then reacquire
  57498. ** the other BtShared locks that we used to hold in ascending
  57499. ** order.
  57500. */
  57501. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  57502. assert( pLater->sharable );
  57503. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  57504. assert( !pLater->locked || pLater->wantToLock>0 );
  57505. if( pLater->locked ){
  57506. unlockBtreeMutex(pLater);
  57507. }
  57508. }
  57509. lockBtreeMutex(p);
  57510. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  57511. if( pLater->wantToLock ){
  57512. lockBtreeMutex(pLater);
  57513. }
  57514. }
  57515. }
  57516. /*
  57517. ** Exit the recursive mutex on a Btree.
  57518. */
  57519. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  57520. assert( sqlite3_mutex_held(p->db->mutex) );
  57521. if( p->sharable ){
  57522. assert( p->wantToLock>0 );
  57523. p->wantToLock--;
  57524. if( p->wantToLock==0 ){
  57525. unlockBtreeMutex(p);
  57526. }
  57527. }
  57528. }
  57529. #ifndef NDEBUG
  57530. /*
  57531. ** Return true if the BtShared mutex is held on the btree, or if the
  57532. ** B-Tree is not marked as sharable.
  57533. **
  57534. ** This routine is used only from within assert() statements.
  57535. */
  57536. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  57537. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  57538. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  57539. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  57540. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  57541. return (p->sharable==0 || p->locked);
  57542. }
  57543. #endif
  57544. /*
  57545. ** Enter the mutex on every Btree associated with a database
  57546. ** connection. This is needed (for example) prior to parsing
  57547. ** a statement since we will be comparing table and column names
  57548. ** against all schemas and we do not want those schemas being
  57549. ** reset out from under us.
  57550. **
  57551. ** There is a corresponding leave-all procedures.
  57552. **
  57553. ** Enter the mutexes in accending order by BtShared pointer address
  57554. ** to avoid the possibility of deadlock when two threads with
  57555. ** two or more btrees in common both try to lock all their btrees
  57556. ** at the same instant.
  57557. */
  57558. static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
  57559. int i;
  57560. int skipOk = 1;
  57561. Btree *p;
  57562. assert( sqlite3_mutex_held(db->mutex) );
  57563. for(i=0; i<db->nDb; i++){
  57564. p = db->aDb[i].pBt;
  57565. if( p && p->sharable ){
  57566. sqlite3BtreeEnter(p);
  57567. skipOk = 0;
  57568. }
  57569. }
  57570. db->skipBtreeMutex = skipOk;
  57571. }
  57572. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  57573. if( db->skipBtreeMutex==0 ) btreeEnterAll(db);
  57574. }
  57575. static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
  57576. int i;
  57577. Btree *p;
  57578. assert( sqlite3_mutex_held(db->mutex) );
  57579. for(i=0; i<db->nDb; i++){
  57580. p = db->aDb[i].pBt;
  57581. if( p ) sqlite3BtreeLeave(p);
  57582. }
  57583. }
  57584. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  57585. if( db->skipBtreeMutex==0 ) btreeLeaveAll(db);
  57586. }
  57587. #ifndef NDEBUG
  57588. /*
  57589. ** Return true if the current thread holds the database connection
  57590. ** mutex and all required BtShared mutexes.
  57591. **
  57592. ** This routine is used inside assert() statements only.
  57593. */
  57594. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  57595. int i;
  57596. if( !sqlite3_mutex_held(db->mutex) ){
  57597. return 0;
  57598. }
  57599. for(i=0; i<db->nDb; i++){
  57600. Btree *p;
  57601. p = db->aDb[i].pBt;
  57602. if( p && p->sharable &&
  57603. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  57604. return 0;
  57605. }
  57606. }
  57607. return 1;
  57608. }
  57609. #endif /* NDEBUG */
  57610. #ifndef NDEBUG
  57611. /*
  57612. ** Return true if the correct mutexes are held for accessing the
  57613. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  57614. ** access are:
  57615. **
  57616. ** (1) The mutex on db
  57617. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  57618. **
  57619. ** If pSchema is not NULL, then iDb is computed from pSchema and
  57620. ** db using sqlite3SchemaToIndex().
  57621. */
  57622. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  57623. Btree *p;
  57624. assert( db!=0 );
  57625. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  57626. assert( iDb>=0 && iDb<db->nDb );
  57627. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  57628. if( iDb==1 ) return 1;
  57629. p = db->aDb[iDb].pBt;
  57630. assert( p!=0 );
  57631. return p->sharable==0 || p->locked==1;
  57632. }
  57633. #endif /* NDEBUG */
  57634. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  57635. /*
  57636. ** The following are special cases for mutex enter routines for use
  57637. ** in single threaded applications that use shared cache. Except for
  57638. ** these two routines, all mutex operations are no-ops in that case and
  57639. ** are null #defines in btree.h.
  57640. **
  57641. ** If shared cache is disabled, then all btree mutex routines, including
  57642. ** the ones below, are no-ops and are null #defines in btree.h.
  57643. */
  57644. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  57645. p->pBt->db = p->db;
  57646. }
  57647. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  57648. int i;
  57649. for(i=0; i<db->nDb; i++){
  57650. Btree *p = db->aDb[i].pBt;
  57651. if( p ){
  57652. p->pBt->db = p->db;
  57653. }
  57654. }
  57655. }
  57656. #endif /* if SQLITE_THREADSAFE */
  57657. #ifndef SQLITE_OMIT_INCRBLOB
  57658. /*
  57659. ** Enter a mutex on a Btree given a cursor owned by that Btree.
  57660. **
  57661. ** These entry points are used by incremental I/O only. Enter() is required
  57662. ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
  57663. ** the build is threadsafe. Leave() is only required by threadsafe builds.
  57664. */
  57665. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  57666. sqlite3BtreeEnter(pCur->pBtree);
  57667. }
  57668. # if SQLITE_THREADSAFE
  57669. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  57670. sqlite3BtreeLeave(pCur->pBtree);
  57671. }
  57672. # endif
  57673. #endif /* ifndef SQLITE_OMIT_INCRBLOB */
  57674. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  57675. /************** End of btmutex.c *********************************************/
  57676. /************** Begin file btree.c *******************************************/
  57677. /*
  57678. ** 2004 April 6
  57679. **
  57680. ** The author disclaims copyright to this source code. In place of
  57681. ** a legal notice, here is a blessing:
  57682. **
  57683. ** May you do good and not evil.
  57684. ** May you find forgiveness for yourself and forgive others.
  57685. ** May you share freely, never taking more than you give.
  57686. **
  57687. *************************************************************************
  57688. ** This file implements an external (disk-based) database using BTrees.
  57689. ** See the header comment on "btreeInt.h" for additional information.
  57690. ** Including a description of file format and an overview of operation.
  57691. */
  57692. /* #include "btreeInt.h" */
  57693. /*
  57694. ** The header string that appears at the beginning of every
  57695. ** SQLite database.
  57696. */
  57697. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  57698. /*
  57699. ** Set this global variable to 1 to enable tracing using the TRACE
  57700. ** macro.
  57701. */
  57702. #if 0
  57703. int sqlite3BtreeTrace=1; /* True to enable tracing */
  57704. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  57705. #else
  57706. # define TRACE(X)
  57707. #endif
  57708. /*
  57709. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  57710. ** But if the value is zero, make it 65536.
  57711. **
  57712. ** This routine is used to extract the "offset to cell content area" value
  57713. ** from the header of a btree page. If the page size is 65536 and the page
  57714. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  57715. ** This routine makes the necessary adjustment to 65536.
  57716. */
  57717. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  57718. /*
  57719. ** Values passed as the 5th argument to allocateBtreePage()
  57720. */
  57721. #define BTALLOC_ANY 0 /* Allocate any page */
  57722. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  57723. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  57724. /*
  57725. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  57726. ** defined, or 0 if it is. For example:
  57727. **
  57728. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  57729. */
  57730. #ifndef SQLITE_OMIT_AUTOVACUUM
  57731. #define IfNotOmitAV(expr) (expr)
  57732. #else
  57733. #define IfNotOmitAV(expr) 0
  57734. #endif
  57735. #ifndef SQLITE_OMIT_SHARED_CACHE
  57736. /*
  57737. ** A list of BtShared objects that are eligible for participation
  57738. ** in shared cache. This variable has file scope during normal builds,
  57739. ** but the test harness needs to access it so we make it global for
  57740. ** test builds.
  57741. **
  57742. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  57743. */
  57744. #ifdef SQLITE_TEST
  57745. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  57746. #else
  57747. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  57748. #endif
  57749. #endif /* SQLITE_OMIT_SHARED_CACHE */
  57750. #ifndef SQLITE_OMIT_SHARED_CACHE
  57751. /*
  57752. ** Enable or disable the shared pager and schema features.
  57753. **
  57754. ** This routine has no effect on existing database connections.
  57755. ** The shared cache setting effects only future calls to
  57756. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  57757. */
  57758. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  57759. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  57760. return SQLITE_OK;
  57761. }
  57762. #endif
  57763. #ifdef SQLITE_OMIT_SHARED_CACHE
  57764. /*
  57765. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  57766. ** and clearAllSharedCacheTableLocks()
  57767. ** manipulate entries in the BtShared.pLock linked list used to store
  57768. ** shared-cache table level locks. If the library is compiled with the
  57769. ** shared-cache feature disabled, then there is only ever one user
  57770. ** of each BtShared structure and so this locking is not necessary.
  57771. ** So define the lock related functions as no-ops.
  57772. */
  57773. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  57774. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  57775. #define clearAllSharedCacheTableLocks(a)
  57776. #define downgradeAllSharedCacheTableLocks(a)
  57777. #define hasSharedCacheTableLock(a,b,c,d) 1
  57778. #define hasReadConflicts(a, b) 0
  57779. #endif
  57780. /*
  57781. ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
  57782. ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
  57783. **
  57784. ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
  57785. ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
  57786. ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
  57787. ** with the page number and filename associated with the (MemPage*).
  57788. */
  57789. #ifdef SQLITE_DEBUG
  57790. int corruptPageError(int lineno, MemPage *p){
  57791. char *zMsg;
  57792. sqlite3BeginBenignMalloc();
  57793. zMsg = sqlite3_mprintf("database corruption page %d of %s",
  57794. (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
  57795. );
  57796. sqlite3EndBenignMalloc();
  57797. if( zMsg ){
  57798. sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  57799. }
  57800. sqlite3_free(zMsg);
  57801. return SQLITE_CORRUPT_BKPT;
  57802. }
  57803. # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
  57804. #else
  57805. # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
  57806. #endif
  57807. #ifndef SQLITE_OMIT_SHARED_CACHE
  57808. #ifdef SQLITE_DEBUG
  57809. /*
  57810. **** This function is only used as part of an assert() statement. ***
  57811. **
  57812. ** Check to see if pBtree holds the required locks to read or write to the
  57813. ** table with root page iRoot. Return 1 if it does and 0 if not.
  57814. **
  57815. ** For example, when writing to a table with root-page iRoot via
  57816. ** Btree connection pBtree:
  57817. **
  57818. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  57819. **
  57820. ** When writing to an index that resides in a sharable database, the
  57821. ** caller should have first obtained a lock specifying the root page of
  57822. ** the corresponding table. This makes things a bit more complicated,
  57823. ** as this module treats each table as a separate structure. To determine
  57824. ** the table corresponding to the index being written, this
  57825. ** function has to search through the database schema.
  57826. **
  57827. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  57828. ** hold a write-lock on the schema table (root page 1). This is also
  57829. ** acceptable.
  57830. */
  57831. static int hasSharedCacheTableLock(
  57832. Btree *pBtree, /* Handle that must hold lock */
  57833. Pgno iRoot, /* Root page of b-tree */
  57834. int isIndex, /* True if iRoot is the root of an index b-tree */
  57835. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  57836. ){
  57837. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  57838. Pgno iTab = 0;
  57839. BtLock *pLock;
  57840. /* If this database is not shareable, or if the client is reading
  57841. ** and has the read-uncommitted flag set, then no lock is required.
  57842. ** Return true immediately.
  57843. */
  57844. if( (pBtree->sharable==0)
  57845. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
  57846. ){
  57847. return 1;
  57848. }
  57849. /* If the client is reading or writing an index and the schema is
  57850. ** not loaded, then it is too difficult to actually check to see if
  57851. ** the correct locks are held. So do not bother - just return true.
  57852. ** This case does not come up very often anyhow.
  57853. */
  57854. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  57855. return 1;
  57856. }
  57857. /* Figure out the root-page that the lock should be held on. For table
  57858. ** b-trees, this is just the root page of the b-tree being read or
  57859. ** written. For index b-trees, it is the root page of the associated
  57860. ** table. */
  57861. if( isIndex ){
  57862. HashElem *p;
  57863. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  57864. Index *pIdx = (Index *)sqliteHashData(p);
  57865. if( pIdx->tnum==(int)iRoot ){
  57866. if( iTab ){
  57867. /* Two or more indexes share the same root page. There must
  57868. ** be imposter tables. So just return true. The assert is not
  57869. ** useful in that case. */
  57870. return 1;
  57871. }
  57872. iTab = pIdx->pTable->tnum;
  57873. }
  57874. }
  57875. }else{
  57876. iTab = iRoot;
  57877. }
  57878. /* Search for the required lock. Either a write-lock on root-page iTab, a
  57879. ** write-lock on the schema table, or (if the client is reading) a
  57880. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  57881. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  57882. if( pLock->pBtree==pBtree
  57883. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  57884. && pLock->eLock>=eLockType
  57885. ){
  57886. return 1;
  57887. }
  57888. }
  57889. /* Failed to find the required lock. */
  57890. return 0;
  57891. }
  57892. #endif /* SQLITE_DEBUG */
  57893. #ifdef SQLITE_DEBUG
  57894. /*
  57895. **** This function may be used as part of assert() statements only. ****
  57896. **
  57897. ** Return true if it would be illegal for pBtree to write into the
  57898. ** table or index rooted at iRoot because other shared connections are
  57899. ** simultaneously reading that same table or index.
  57900. **
  57901. ** It is illegal for pBtree to write if some other Btree object that
  57902. ** shares the same BtShared object is currently reading or writing
  57903. ** the iRoot table. Except, if the other Btree object has the
  57904. ** read-uncommitted flag set, then it is OK for the other object to
  57905. ** have a read cursor.
  57906. **
  57907. ** For example, before writing to any part of the table or index
  57908. ** rooted at page iRoot, one should call:
  57909. **
  57910. ** assert( !hasReadConflicts(pBtree, iRoot) );
  57911. */
  57912. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  57913. BtCursor *p;
  57914. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  57915. if( p->pgnoRoot==iRoot
  57916. && p->pBtree!=pBtree
  57917. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
  57918. ){
  57919. return 1;
  57920. }
  57921. }
  57922. return 0;
  57923. }
  57924. #endif /* #ifdef SQLITE_DEBUG */
  57925. /*
  57926. ** Query to see if Btree handle p may obtain a lock of type eLock
  57927. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  57928. ** SQLITE_OK if the lock may be obtained (by calling
  57929. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  57930. */
  57931. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  57932. BtShared *pBt = p->pBt;
  57933. BtLock *pIter;
  57934. assert( sqlite3BtreeHoldsMutex(p) );
  57935. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  57936. assert( p->db!=0 );
  57937. assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
  57938. /* If requesting a write-lock, then the Btree must have an open write
  57939. ** transaction on this file. And, obviously, for this to be so there
  57940. ** must be an open write transaction on the file itself.
  57941. */
  57942. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  57943. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  57944. /* This routine is a no-op if the shared-cache is not enabled */
  57945. if( !p->sharable ){
  57946. return SQLITE_OK;
  57947. }
  57948. /* If some other connection is holding an exclusive lock, the
  57949. ** requested lock may not be obtained.
  57950. */
  57951. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  57952. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  57953. return SQLITE_LOCKED_SHAREDCACHE;
  57954. }
  57955. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  57956. /* The condition (pIter->eLock!=eLock) in the following if(...)
  57957. ** statement is a simplification of:
  57958. **
  57959. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  57960. **
  57961. ** since we know that if eLock==WRITE_LOCK, then no other connection
  57962. ** may hold a WRITE_LOCK on any table in this file (since there can
  57963. ** only be a single writer).
  57964. */
  57965. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  57966. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  57967. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  57968. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  57969. if( eLock==WRITE_LOCK ){
  57970. assert( p==pBt->pWriter );
  57971. pBt->btsFlags |= BTS_PENDING;
  57972. }
  57973. return SQLITE_LOCKED_SHAREDCACHE;
  57974. }
  57975. }
  57976. return SQLITE_OK;
  57977. }
  57978. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  57979. #ifndef SQLITE_OMIT_SHARED_CACHE
  57980. /*
  57981. ** Add a lock on the table with root-page iTable to the shared-btree used
  57982. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  57983. ** WRITE_LOCK.
  57984. **
  57985. ** This function assumes the following:
  57986. **
  57987. ** (a) The specified Btree object p is connected to a sharable
  57988. ** database (one with the BtShared.sharable flag set), and
  57989. **
  57990. ** (b) No other Btree objects hold a lock that conflicts
  57991. ** with the requested lock (i.e. querySharedCacheTableLock() has
  57992. ** already been called and returned SQLITE_OK).
  57993. **
  57994. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  57995. ** is returned if a malloc attempt fails.
  57996. */
  57997. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  57998. BtShared *pBt = p->pBt;
  57999. BtLock *pLock = 0;
  58000. BtLock *pIter;
  58001. assert( sqlite3BtreeHoldsMutex(p) );
  58002. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  58003. assert( p->db!=0 );
  58004. /* A connection with the read-uncommitted flag set will never try to
  58005. ** obtain a read-lock using this function. The only read-lock obtained
  58006. ** by a connection in read-uncommitted mode is on the sqlite_master
  58007. ** table, and that lock is obtained in BtreeBeginTrans(). */
  58008. assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
  58009. /* This function should only be called on a sharable b-tree after it
  58010. ** has been determined that no other b-tree holds a conflicting lock. */
  58011. assert( p->sharable );
  58012. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  58013. /* First search the list for an existing lock on this table. */
  58014. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  58015. if( pIter->iTable==iTable && pIter->pBtree==p ){
  58016. pLock = pIter;
  58017. break;
  58018. }
  58019. }
  58020. /* If the above search did not find a BtLock struct associating Btree p
  58021. ** with table iTable, allocate one and link it into the list.
  58022. */
  58023. if( !pLock ){
  58024. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  58025. if( !pLock ){
  58026. return SQLITE_NOMEM_BKPT;
  58027. }
  58028. pLock->iTable = iTable;
  58029. pLock->pBtree = p;
  58030. pLock->pNext = pBt->pLock;
  58031. pBt->pLock = pLock;
  58032. }
  58033. /* Set the BtLock.eLock variable to the maximum of the current lock
  58034. ** and the requested lock. This means if a write-lock was already held
  58035. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  58036. */
  58037. assert( WRITE_LOCK>READ_LOCK );
  58038. if( eLock>pLock->eLock ){
  58039. pLock->eLock = eLock;
  58040. }
  58041. return SQLITE_OK;
  58042. }
  58043. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  58044. #ifndef SQLITE_OMIT_SHARED_CACHE
  58045. /*
  58046. ** Release all the table locks (locks obtained via calls to
  58047. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  58048. **
  58049. ** This function assumes that Btree p has an open read or write
  58050. ** transaction. If it does not, then the BTS_PENDING flag
  58051. ** may be incorrectly cleared.
  58052. */
  58053. static void clearAllSharedCacheTableLocks(Btree *p){
  58054. BtShared *pBt = p->pBt;
  58055. BtLock **ppIter = &pBt->pLock;
  58056. assert( sqlite3BtreeHoldsMutex(p) );
  58057. assert( p->sharable || 0==*ppIter );
  58058. assert( p->inTrans>0 );
  58059. while( *ppIter ){
  58060. BtLock *pLock = *ppIter;
  58061. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  58062. assert( pLock->pBtree->inTrans>=pLock->eLock );
  58063. if( pLock->pBtree==p ){
  58064. *ppIter = pLock->pNext;
  58065. assert( pLock->iTable!=1 || pLock==&p->lock );
  58066. if( pLock->iTable!=1 ){
  58067. sqlite3_free(pLock);
  58068. }
  58069. }else{
  58070. ppIter = &pLock->pNext;
  58071. }
  58072. }
  58073. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  58074. if( pBt->pWriter==p ){
  58075. pBt->pWriter = 0;
  58076. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  58077. }else if( pBt->nTransaction==2 ){
  58078. /* This function is called when Btree p is concluding its
  58079. ** transaction. If there currently exists a writer, and p is not
  58080. ** that writer, then the number of locks held by connections other
  58081. ** than the writer must be about to drop to zero. In this case
  58082. ** set the BTS_PENDING flag to 0.
  58083. **
  58084. ** If there is not currently a writer, then BTS_PENDING must
  58085. ** be zero already. So this next line is harmless in that case.
  58086. */
  58087. pBt->btsFlags &= ~BTS_PENDING;
  58088. }
  58089. }
  58090. /*
  58091. ** This function changes all write-locks held by Btree p into read-locks.
  58092. */
  58093. static void downgradeAllSharedCacheTableLocks(Btree *p){
  58094. BtShared *pBt = p->pBt;
  58095. if( pBt->pWriter==p ){
  58096. BtLock *pLock;
  58097. pBt->pWriter = 0;
  58098. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  58099. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  58100. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  58101. pLock->eLock = READ_LOCK;
  58102. }
  58103. }
  58104. }
  58105. #endif /* SQLITE_OMIT_SHARED_CACHE */
  58106. static void releasePage(MemPage *pPage); /* Forward reference */
  58107. static void releasePageOne(MemPage *pPage); /* Forward reference */
  58108. static void releasePageNotNull(MemPage *pPage); /* Forward reference */
  58109. /*
  58110. ***** This routine is used inside of assert() only ****
  58111. **
  58112. ** Verify that the cursor holds the mutex on its BtShared
  58113. */
  58114. #ifdef SQLITE_DEBUG
  58115. static int cursorHoldsMutex(BtCursor *p){
  58116. return sqlite3_mutex_held(p->pBt->mutex);
  58117. }
  58118. /* Verify that the cursor and the BtShared agree about what is the current
  58119. ** database connetion. This is important in shared-cache mode. If the database
  58120. ** connection pointers get out-of-sync, it is possible for routines like
  58121. ** btreeInitPage() to reference an stale connection pointer that references a
  58122. ** a connection that has already closed. This routine is used inside assert()
  58123. ** statements only and for the purpose of double-checking that the btree code
  58124. ** does keep the database connection pointers up-to-date.
  58125. */
  58126. static int cursorOwnsBtShared(BtCursor *p){
  58127. assert( cursorHoldsMutex(p) );
  58128. return (p->pBtree->db==p->pBt->db);
  58129. }
  58130. #endif
  58131. /*
  58132. ** Invalidate the overflow cache of the cursor passed as the first argument.
  58133. ** on the shared btree structure pBt.
  58134. */
  58135. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  58136. /*
  58137. ** Invalidate the overflow page-list cache for all cursors opened
  58138. ** on the shared btree structure pBt.
  58139. */
  58140. static void invalidateAllOverflowCache(BtShared *pBt){
  58141. BtCursor *p;
  58142. assert( sqlite3_mutex_held(pBt->mutex) );
  58143. for(p=pBt->pCursor; p; p=p->pNext){
  58144. invalidateOverflowCache(p);
  58145. }
  58146. }
  58147. #ifndef SQLITE_OMIT_INCRBLOB
  58148. /*
  58149. ** This function is called before modifying the contents of a table
  58150. ** to invalidate any incrblob cursors that are open on the
  58151. ** row or one of the rows being modified.
  58152. **
  58153. ** If argument isClearTable is true, then the entire contents of the
  58154. ** table is about to be deleted. In this case invalidate all incrblob
  58155. ** cursors open on any row within the table with root-page pgnoRoot.
  58156. **
  58157. ** Otherwise, if argument isClearTable is false, then the row with
  58158. ** rowid iRow is being replaced or deleted. In this case invalidate
  58159. ** only those incrblob cursors open on that specific row.
  58160. */
  58161. static void invalidateIncrblobCursors(
  58162. Btree *pBtree, /* The database file to check */
  58163. Pgno pgnoRoot, /* The table that might be changing */
  58164. i64 iRow, /* The rowid that might be changing */
  58165. int isClearTable /* True if all rows are being deleted */
  58166. ){
  58167. BtCursor *p;
  58168. if( pBtree->hasIncrblobCur==0 ) return;
  58169. assert( sqlite3BtreeHoldsMutex(pBtree) );
  58170. pBtree->hasIncrblobCur = 0;
  58171. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  58172. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  58173. pBtree->hasIncrblobCur = 1;
  58174. if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
  58175. p->eState = CURSOR_INVALID;
  58176. }
  58177. }
  58178. }
  58179. }
  58180. #else
  58181. /* Stub function when INCRBLOB is omitted */
  58182. #define invalidateIncrblobCursors(w,x,y,z)
  58183. #endif /* SQLITE_OMIT_INCRBLOB */
  58184. /*
  58185. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  58186. ** when a page that previously contained data becomes a free-list leaf
  58187. ** page.
  58188. **
  58189. ** The BtShared.pHasContent bitvec exists to work around an obscure
  58190. ** bug caused by the interaction of two useful IO optimizations surrounding
  58191. ** free-list leaf pages:
  58192. **
  58193. ** 1) When all data is deleted from a page and the page becomes
  58194. ** a free-list leaf page, the page is not written to the database
  58195. ** (as free-list leaf pages contain no meaningful data). Sometimes
  58196. ** such a page is not even journalled (as it will not be modified,
  58197. ** why bother journalling it?).
  58198. **
  58199. ** 2) When a free-list leaf page is reused, its content is not read
  58200. ** from the database or written to the journal file (why should it
  58201. ** be, if it is not at all meaningful?).
  58202. **
  58203. ** By themselves, these optimizations work fine and provide a handy
  58204. ** performance boost to bulk delete or insert operations. However, if
  58205. ** a page is moved to the free-list and then reused within the same
  58206. ** transaction, a problem comes up. If the page is not journalled when
  58207. ** it is moved to the free-list and it is also not journalled when it
  58208. ** is extracted from the free-list and reused, then the original data
  58209. ** may be lost. In the event of a rollback, it may not be possible
  58210. ** to restore the database to its original configuration.
  58211. **
  58212. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  58213. ** moved to become a free-list leaf page, the corresponding bit is
  58214. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  58215. ** optimization 2 above is omitted if the corresponding bit is already
  58216. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  58217. ** at the end of every transaction.
  58218. */
  58219. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  58220. int rc = SQLITE_OK;
  58221. if( !pBt->pHasContent ){
  58222. assert( pgno<=pBt->nPage );
  58223. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  58224. if( !pBt->pHasContent ){
  58225. rc = SQLITE_NOMEM_BKPT;
  58226. }
  58227. }
  58228. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  58229. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  58230. }
  58231. return rc;
  58232. }
  58233. /*
  58234. ** Query the BtShared.pHasContent vector.
  58235. **
  58236. ** This function is called when a free-list leaf page is removed from the
  58237. ** free-list for reuse. It returns false if it is safe to retrieve the
  58238. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  58239. */
  58240. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  58241. Bitvec *p = pBt->pHasContent;
  58242. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  58243. }
  58244. /*
  58245. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  58246. ** invoked at the conclusion of each write-transaction.
  58247. */
  58248. static void btreeClearHasContent(BtShared *pBt){
  58249. sqlite3BitvecDestroy(pBt->pHasContent);
  58250. pBt->pHasContent = 0;
  58251. }
  58252. /*
  58253. ** Release all of the apPage[] pages for a cursor.
  58254. */
  58255. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  58256. int i;
  58257. if( pCur->iPage>=0 ){
  58258. for(i=0; i<pCur->iPage; i++){
  58259. releasePageNotNull(pCur->apPage[i]);
  58260. }
  58261. releasePageNotNull(pCur->pPage);
  58262. pCur->iPage = -1;
  58263. }
  58264. }
  58265. /*
  58266. ** The cursor passed as the only argument must point to a valid entry
  58267. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  58268. ** function saves the current cursor key in variables pCur->nKey and
  58269. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  58270. ** code otherwise.
  58271. **
  58272. ** If the cursor is open on an intkey table, then the integer key
  58273. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  58274. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  58275. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  58276. ** the key.
  58277. */
  58278. static int saveCursorKey(BtCursor *pCur){
  58279. int rc = SQLITE_OK;
  58280. assert( CURSOR_VALID==pCur->eState );
  58281. assert( 0==pCur->pKey );
  58282. assert( cursorHoldsMutex(pCur) );
  58283. if( pCur->curIntKey ){
  58284. /* Only the rowid is required for a table btree */
  58285. pCur->nKey = sqlite3BtreeIntegerKey(pCur);
  58286. }else{
  58287. /* For an index btree, save the complete key content */
  58288. void *pKey;
  58289. pCur->nKey = sqlite3BtreePayloadSize(pCur);
  58290. pKey = sqlite3Malloc( pCur->nKey );
  58291. if( pKey ){
  58292. rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
  58293. if( rc==SQLITE_OK ){
  58294. pCur->pKey = pKey;
  58295. }else{
  58296. sqlite3_free(pKey);
  58297. }
  58298. }else{
  58299. rc = SQLITE_NOMEM_BKPT;
  58300. }
  58301. }
  58302. assert( !pCur->curIntKey || !pCur->pKey );
  58303. return rc;
  58304. }
  58305. /*
  58306. ** Save the current cursor position in the variables BtCursor.nKey
  58307. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  58308. **
  58309. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  58310. ** prior to calling this routine.
  58311. */
  58312. static int saveCursorPosition(BtCursor *pCur){
  58313. int rc;
  58314. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  58315. assert( 0==pCur->pKey );
  58316. assert( cursorHoldsMutex(pCur) );
  58317. if( pCur->eState==CURSOR_SKIPNEXT ){
  58318. pCur->eState = CURSOR_VALID;
  58319. }else{
  58320. pCur->skipNext = 0;
  58321. }
  58322. rc = saveCursorKey(pCur);
  58323. if( rc==SQLITE_OK ){
  58324. btreeReleaseAllCursorPages(pCur);
  58325. pCur->eState = CURSOR_REQUIRESEEK;
  58326. }
  58327. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  58328. return rc;
  58329. }
  58330. /* Forward reference */
  58331. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  58332. /*
  58333. ** Save the positions of all cursors (except pExcept) that are open on
  58334. ** the table with root-page iRoot. "Saving the cursor position" means that
  58335. ** the location in the btree is remembered in such a way that it can be
  58336. ** moved back to the same spot after the btree has been modified. This
  58337. ** routine is called just before cursor pExcept is used to modify the
  58338. ** table, for example in BtreeDelete() or BtreeInsert().
  58339. **
  58340. ** If there are two or more cursors on the same btree, then all such
  58341. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  58342. ** routine enforces that rule. This routine only needs to be called in
  58343. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  58344. **
  58345. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  58346. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  58347. ** pointless call to this routine.
  58348. **
  58349. ** Implementation note: This routine merely checks to see if any cursors
  58350. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  58351. ** event that cursors are in need to being saved.
  58352. */
  58353. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  58354. BtCursor *p;
  58355. assert( sqlite3_mutex_held(pBt->mutex) );
  58356. assert( pExcept==0 || pExcept->pBt==pBt );
  58357. for(p=pBt->pCursor; p; p=p->pNext){
  58358. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  58359. }
  58360. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  58361. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  58362. return SQLITE_OK;
  58363. }
  58364. /* This helper routine to saveAllCursors does the actual work of saving
  58365. ** the cursors if and when a cursor is found that actually requires saving.
  58366. ** The common case is that no cursors need to be saved, so this routine is
  58367. ** broken out from its caller to avoid unnecessary stack pointer movement.
  58368. */
  58369. static int SQLITE_NOINLINE saveCursorsOnList(
  58370. BtCursor *p, /* The first cursor that needs saving */
  58371. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  58372. BtCursor *pExcept /* Do not save this cursor */
  58373. ){
  58374. do{
  58375. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  58376. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  58377. int rc = saveCursorPosition(p);
  58378. if( SQLITE_OK!=rc ){
  58379. return rc;
  58380. }
  58381. }else{
  58382. testcase( p->iPage>=0 );
  58383. btreeReleaseAllCursorPages(p);
  58384. }
  58385. }
  58386. p = p->pNext;
  58387. }while( p );
  58388. return SQLITE_OK;
  58389. }
  58390. /*
  58391. ** Clear the current cursor position.
  58392. */
  58393. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  58394. assert( cursorHoldsMutex(pCur) );
  58395. sqlite3_free(pCur->pKey);
  58396. pCur->pKey = 0;
  58397. pCur->eState = CURSOR_INVALID;
  58398. }
  58399. /*
  58400. ** In this version of BtreeMoveto, pKey is a packed index record
  58401. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  58402. ** record and then call BtreeMovetoUnpacked() to do the work.
  58403. */
  58404. static int btreeMoveto(
  58405. BtCursor *pCur, /* Cursor open on the btree to be searched */
  58406. const void *pKey, /* Packed key if the btree is an index */
  58407. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  58408. int bias, /* Bias search to the high end */
  58409. int *pRes /* Write search results here */
  58410. ){
  58411. int rc; /* Status code */
  58412. UnpackedRecord *pIdxKey; /* Unpacked index key */
  58413. if( pKey ){
  58414. assert( nKey==(i64)(int)nKey );
  58415. pIdxKey = sqlite3VdbeAllocUnpackedRecord(pCur->pKeyInfo);
  58416. if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
  58417. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  58418. if( pIdxKey->nField==0 ){
  58419. rc = SQLITE_CORRUPT_BKPT;
  58420. goto moveto_done;
  58421. }
  58422. }else{
  58423. pIdxKey = 0;
  58424. }
  58425. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  58426. moveto_done:
  58427. if( pIdxKey ){
  58428. sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
  58429. }
  58430. return rc;
  58431. }
  58432. /*
  58433. ** Restore the cursor to the position it was in (or as close to as possible)
  58434. ** when saveCursorPosition() was called. Note that this call deletes the
  58435. ** saved position info stored by saveCursorPosition(), so there can be
  58436. ** at most one effective restoreCursorPosition() call after each
  58437. ** saveCursorPosition().
  58438. */
  58439. static int btreeRestoreCursorPosition(BtCursor *pCur){
  58440. int rc;
  58441. int skipNext;
  58442. assert( cursorOwnsBtShared(pCur) );
  58443. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  58444. if( pCur->eState==CURSOR_FAULT ){
  58445. return pCur->skipNext;
  58446. }
  58447. pCur->eState = CURSOR_INVALID;
  58448. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  58449. if( rc==SQLITE_OK ){
  58450. sqlite3_free(pCur->pKey);
  58451. pCur->pKey = 0;
  58452. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  58453. pCur->skipNext |= skipNext;
  58454. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  58455. pCur->eState = CURSOR_SKIPNEXT;
  58456. }
  58457. }
  58458. return rc;
  58459. }
  58460. #define restoreCursorPosition(p) \
  58461. (p->eState>=CURSOR_REQUIRESEEK ? \
  58462. btreeRestoreCursorPosition(p) : \
  58463. SQLITE_OK)
  58464. /*
  58465. ** Determine whether or not a cursor has moved from the position where
  58466. ** it was last placed, or has been invalidated for any other reason.
  58467. ** Cursors can move when the row they are pointing at is deleted out
  58468. ** from under them, for example. Cursor might also move if a btree
  58469. ** is rebalanced.
  58470. **
  58471. ** Calling this routine with a NULL cursor pointer returns false.
  58472. **
  58473. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  58474. ** back to where it ought to be if this routine returns true.
  58475. */
  58476. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  58477. return pCur->eState!=CURSOR_VALID;
  58478. }
  58479. /*
  58480. ** Return a pointer to a fake BtCursor object that will always answer
  58481. ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
  58482. ** cursor returned must not be used with any other Btree interface.
  58483. */
  58484. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
  58485. static u8 fakeCursor = CURSOR_VALID;
  58486. assert( offsetof(BtCursor, eState)==0 );
  58487. return (BtCursor*)&fakeCursor;
  58488. }
  58489. /*
  58490. ** This routine restores a cursor back to its original position after it
  58491. ** has been moved by some outside activity (such as a btree rebalance or
  58492. ** a row having been deleted out from under the cursor).
  58493. **
  58494. ** On success, the *pDifferentRow parameter is false if the cursor is left
  58495. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  58496. ** was pointing to has been deleted, forcing the cursor to point to some
  58497. ** nearby row.
  58498. **
  58499. ** This routine should only be called for a cursor that just returned
  58500. ** TRUE from sqlite3BtreeCursorHasMoved().
  58501. */
  58502. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  58503. int rc;
  58504. assert( pCur!=0 );
  58505. assert( pCur->eState!=CURSOR_VALID );
  58506. rc = restoreCursorPosition(pCur);
  58507. if( rc ){
  58508. *pDifferentRow = 1;
  58509. return rc;
  58510. }
  58511. if( pCur->eState!=CURSOR_VALID ){
  58512. *pDifferentRow = 1;
  58513. }else{
  58514. assert( pCur->skipNext==0 );
  58515. *pDifferentRow = 0;
  58516. }
  58517. return SQLITE_OK;
  58518. }
  58519. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  58520. /*
  58521. ** Provide hints to the cursor. The particular hint given (and the type
  58522. ** and number of the varargs parameters) is determined by the eHintType
  58523. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  58524. */
  58525. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  58526. /* Used only by system that substitute their own storage engine */
  58527. }
  58528. #endif
  58529. /*
  58530. ** Provide flag hints to the cursor.
  58531. */
  58532. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  58533. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  58534. pCur->hints = x;
  58535. }
  58536. #ifndef SQLITE_OMIT_AUTOVACUUM
  58537. /*
  58538. ** Given a page number of a regular database page, return the page
  58539. ** number for the pointer-map page that contains the entry for the
  58540. ** input page number.
  58541. **
  58542. ** Return 0 (not a valid page) for pgno==1 since there is
  58543. ** no pointer map associated with page 1. The integrity_check logic
  58544. ** requires that ptrmapPageno(*,1)!=1.
  58545. */
  58546. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  58547. int nPagesPerMapPage;
  58548. Pgno iPtrMap, ret;
  58549. assert( sqlite3_mutex_held(pBt->mutex) );
  58550. if( pgno<2 ) return 0;
  58551. nPagesPerMapPage = (pBt->usableSize/5)+1;
  58552. iPtrMap = (pgno-2)/nPagesPerMapPage;
  58553. ret = (iPtrMap*nPagesPerMapPage) + 2;
  58554. if( ret==PENDING_BYTE_PAGE(pBt) ){
  58555. ret++;
  58556. }
  58557. return ret;
  58558. }
  58559. /*
  58560. ** Write an entry into the pointer map.
  58561. **
  58562. ** This routine updates the pointer map entry for page number 'key'
  58563. ** so that it maps to type 'eType' and parent page number 'pgno'.
  58564. **
  58565. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  58566. ** a no-op. If an error occurs, the appropriate error code is written
  58567. ** into *pRC.
  58568. */
  58569. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  58570. DbPage *pDbPage; /* The pointer map page */
  58571. u8 *pPtrmap; /* The pointer map data */
  58572. Pgno iPtrmap; /* The pointer map page number */
  58573. int offset; /* Offset in pointer map page */
  58574. int rc; /* Return code from subfunctions */
  58575. if( *pRC ) return;
  58576. assert( sqlite3_mutex_held(pBt->mutex) );
  58577. /* The master-journal page number must never be used as a pointer map page */
  58578. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  58579. assert( pBt->autoVacuum );
  58580. if( key==0 ){
  58581. *pRC = SQLITE_CORRUPT_BKPT;
  58582. return;
  58583. }
  58584. iPtrmap = PTRMAP_PAGENO(pBt, key);
  58585. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  58586. if( rc!=SQLITE_OK ){
  58587. *pRC = rc;
  58588. return;
  58589. }
  58590. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  58591. if( offset<0 ){
  58592. *pRC = SQLITE_CORRUPT_BKPT;
  58593. goto ptrmap_exit;
  58594. }
  58595. assert( offset <= (int)pBt->usableSize-5 );
  58596. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  58597. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  58598. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  58599. *pRC= rc = sqlite3PagerWrite(pDbPage);
  58600. if( rc==SQLITE_OK ){
  58601. pPtrmap[offset] = eType;
  58602. put4byte(&pPtrmap[offset+1], parent);
  58603. }
  58604. }
  58605. ptrmap_exit:
  58606. sqlite3PagerUnref(pDbPage);
  58607. }
  58608. /*
  58609. ** Read an entry from the pointer map.
  58610. **
  58611. ** This routine retrieves the pointer map entry for page 'key', writing
  58612. ** the type and parent page number to *pEType and *pPgno respectively.
  58613. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  58614. */
  58615. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  58616. DbPage *pDbPage; /* The pointer map page */
  58617. int iPtrmap; /* Pointer map page index */
  58618. u8 *pPtrmap; /* Pointer map page data */
  58619. int offset; /* Offset of entry in pointer map */
  58620. int rc;
  58621. assert( sqlite3_mutex_held(pBt->mutex) );
  58622. iPtrmap = PTRMAP_PAGENO(pBt, key);
  58623. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  58624. if( rc!=0 ){
  58625. return rc;
  58626. }
  58627. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  58628. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  58629. if( offset<0 ){
  58630. sqlite3PagerUnref(pDbPage);
  58631. return SQLITE_CORRUPT_BKPT;
  58632. }
  58633. assert( offset <= (int)pBt->usableSize-5 );
  58634. assert( pEType!=0 );
  58635. *pEType = pPtrmap[offset];
  58636. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  58637. sqlite3PagerUnref(pDbPage);
  58638. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
  58639. return SQLITE_OK;
  58640. }
  58641. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  58642. #define ptrmapPut(w,x,y,z,rc)
  58643. #define ptrmapGet(w,x,y,z) SQLITE_OK
  58644. #define ptrmapPutOvflPtr(x, y, rc)
  58645. #endif
  58646. /*
  58647. ** Given a btree page and a cell index (0 means the first cell on
  58648. ** the page, 1 means the second cell, and so forth) return a pointer
  58649. ** to the cell content.
  58650. **
  58651. ** findCellPastPtr() does the same except it skips past the initial
  58652. ** 4-byte child pointer found on interior pages, if there is one.
  58653. **
  58654. ** This routine works only for pages that do not contain overflow cells.
  58655. */
  58656. #define findCell(P,I) \
  58657. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  58658. #define findCellPastPtr(P,I) \
  58659. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  58660. /*
  58661. ** This is common tail processing for btreeParseCellPtr() and
  58662. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  58663. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  58664. ** structure.
  58665. */
  58666. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  58667. MemPage *pPage, /* Page containing the cell */
  58668. u8 *pCell, /* Pointer to the cell text. */
  58669. CellInfo *pInfo /* Fill in this structure */
  58670. ){
  58671. /* If the payload will not fit completely on the local page, we have
  58672. ** to decide how much to store locally and how much to spill onto
  58673. ** overflow pages. The strategy is to minimize the amount of unused
  58674. ** space on overflow pages while keeping the amount of local storage
  58675. ** in between minLocal and maxLocal.
  58676. **
  58677. ** Warning: changing the way overflow payload is distributed in any
  58678. ** way will result in an incompatible file format.
  58679. */
  58680. int minLocal; /* Minimum amount of payload held locally */
  58681. int maxLocal; /* Maximum amount of payload held locally */
  58682. int surplus; /* Overflow payload available for local storage */
  58683. minLocal = pPage->minLocal;
  58684. maxLocal = pPage->maxLocal;
  58685. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  58686. testcase( surplus==maxLocal );
  58687. testcase( surplus==maxLocal+1 );
  58688. if( surplus <= maxLocal ){
  58689. pInfo->nLocal = (u16)surplus;
  58690. }else{
  58691. pInfo->nLocal = (u16)minLocal;
  58692. }
  58693. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  58694. }
  58695. /*
  58696. ** The following routines are implementations of the MemPage.xParseCell()
  58697. ** method.
  58698. **
  58699. ** Parse a cell content block and fill in the CellInfo structure.
  58700. **
  58701. ** btreeParseCellPtr() => table btree leaf nodes
  58702. ** btreeParseCellNoPayload() => table btree internal nodes
  58703. ** btreeParseCellPtrIndex() => index btree nodes
  58704. **
  58705. ** There is also a wrapper function btreeParseCell() that works for
  58706. ** all MemPage types and that references the cell by index rather than
  58707. ** by pointer.
  58708. */
  58709. static void btreeParseCellPtrNoPayload(
  58710. MemPage *pPage, /* Page containing the cell */
  58711. u8 *pCell, /* Pointer to the cell text. */
  58712. CellInfo *pInfo /* Fill in this structure */
  58713. ){
  58714. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  58715. assert( pPage->leaf==0 );
  58716. assert( pPage->childPtrSize==4 );
  58717. #ifndef SQLITE_DEBUG
  58718. UNUSED_PARAMETER(pPage);
  58719. #endif
  58720. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  58721. pInfo->nPayload = 0;
  58722. pInfo->nLocal = 0;
  58723. pInfo->pPayload = 0;
  58724. return;
  58725. }
  58726. static void btreeParseCellPtr(
  58727. MemPage *pPage, /* Page containing the cell */
  58728. u8 *pCell, /* Pointer to the cell text. */
  58729. CellInfo *pInfo /* Fill in this structure */
  58730. ){
  58731. u8 *pIter; /* For scanning through pCell */
  58732. u32 nPayload; /* Number of bytes of cell payload */
  58733. u64 iKey; /* Extracted Key value */
  58734. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  58735. assert( pPage->leaf==0 || pPage->leaf==1 );
  58736. assert( pPage->intKeyLeaf );
  58737. assert( pPage->childPtrSize==0 );
  58738. pIter = pCell;
  58739. /* The next block of code is equivalent to:
  58740. **
  58741. ** pIter += getVarint32(pIter, nPayload);
  58742. **
  58743. ** The code is inlined to avoid a function call.
  58744. */
  58745. nPayload = *pIter;
  58746. if( nPayload>=0x80 ){
  58747. u8 *pEnd = &pIter[8];
  58748. nPayload &= 0x7f;
  58749. do{
  58750. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  58751. }while( (*pIter)>=0x80 && pIter<pEnd );
  58752. }
  58753. pIter++;
  58754. /* The next block of code is equivalent to:
  58755. **
  58756. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  58757. **
  58758. ** The code is inlined to avoid a function call.
  58759. */
  58760. iKey = *pIter;
  58761. if( iKey>=0x80 ){
  58762. u8 *pEnd = &pIter[7];
  58763. iKey &= 0x7f;
  58764. while(1){
  58765. iKey = (iKey<<7) | (*++pIter & 0x7f);
  58766. if( (*pIter)<0x80 ) break;
  58767. if( pIter>=pEnd ){
  58768. iKey = (iKey<<8) | *++pIter;
  58769. break;
  58770. }
  58771. }
  58772. }
  58773. pIter++;
  58774. pInfo->nKey = *(i64*)&iKey;
  58775. pInfo->nPayload = nPayload;
  58776. pInfo->pPayload = pIter;
  58777. testcase( nPayload==pPage->maxLocal );
  58778. testcase( nPayload==pPage->maxLocal+1 );
  58779. if( nPayload<=pPage->maxLocal ){
  58780. /* This is the (easy) common case where the entire payload fits
  58781. ** on the local page. No overflow is required.
  58782. */
  58783. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  58784. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  58785. pInfo->nLocal = (u16)nPayload;
  58786. }else{
  58787. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  58788. }
  58789. }
  58790. static void btreeParseCellPtrIndex(
  58791. MemPage *pPage, /* Page containing the cell */
  58792. u8 *pCell, /* Pointer to the cell text. */
  58793. CellInfo *pInfo /* Fill in this structure */
  58794. ){
  58795. u8 *pIter; /* For scanning through pCell */
  58796. u32 nPayload; /* Number of bytes of cell payload */
  58797. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  58798. assert( pPage->leaf==0 || pPage->leaf==1 );
  58799. assert( pPage->intKeyLeaf==0 );
  58800. pIter = pCell + pPage->childPtrSize;
  58801. nPayload = *pIter;
  58802. if( nPayload>=0x80 ){
  58803. u8 *pEnd = &pIter[8];
  58804. nPayload &= 0x7f;
  58805. do{
  58806. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  58807. }while( *(pIter)>=0x80 && pIter<pEnd );
  58808. }
  58809. pIter++;
  58810. pInfo->nKey = nPayload;
  58811. pInfo->nPayload = nPayload;
  58812. pInfo->pPayload = pIter;
  58813. testcase( nPayload==pPage->maxLocal );
  58814. testcase( nPayload==pPage->maxLocal+1 );
  58815. if( nPayload<=pPage->maxLocal ){
  58816. /* This is the (easy) common case where the entire payload fits
  58817. ** on the local page. No overflow is required.
  58818. */
  58819. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  58820. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  58821. pInfo->nLocal = (u16)nPayload;
  58822. }else{
  58823. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  58824. }
  58825. }
  58826. static void btreeParseCell(
  58827. MemPage *pPage, /* Page containing the cell */
  58828. int iCell, /* The cell index. First cell is 0 */
  58829. CellInfo *pInfo /* Fill in this structure */
  58830. ){
  58831. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  58832. }
  58833. /*
  58834. ** The following routines are implementations of the MemPage.xCellSize
  58835. ** method.
  58836. **
  58837. ** Compute the total number of bytes that a Cell needs in the cell
  58838. ** data area of the btree-page. The return number includes the cell
  58839. ** data header and the local payload, but not any overflow page or
  58840. ** the space used by the cell pointer.
  58841. **
  58842. ** cellSizePtrNoPayload() => table internal nodes
  58843. ** cellSizePtr() => all index nodes & table leaf nodes
  58844. */
  58845. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  58846. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  58847. u8 *pEnd; /* End mark for a varint */
  58848. u32 nSize; /* Size value to return */
  58849. #ifdef SQLITE_DEBUG
  58850. /* The value returned by this function should always be the same as
  58851. ** the (CellInfo.nSize) value found by doing a full parse of the
  58852. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  58853. ** this function verifies that this invariant is not violated. */
  58854. CellInfo debuginfo;
  58855. pPage->xParseCell(pPage, pCell, &debuginfo);
  58856. #endif
  58857. nSize = *pIter;
  58858. if( nSize>=0x80 ){
  58859. pEnd = &pIter[8];
  58860. nSize &= 0x7f;
  58861. do{
  58862. nSize = (nSize<<7) | (*++pIter & 0x7f);
  58863. }while( *(pIter)>=0x80 && pIter<pEnd );
  58864. }
  58865. pIter++;
  58866. if( pPage->intKey ){
  58867. /* pIter now points at the 64-bit integer key value, a variable length
  58868. ** integer. The following block moves pIter to point at the first byte
  58869. ** past the end of the key value. */
  58870. pEnd = &pIter[9];
  58871. while( (*pIter++)&0x80 && pIter<pEnd );
  58872. }
  58873. testcase( nSize==pPage->maxLocal );
  58874. testcase( nSize==pPage->maxLocal+1 );
  58875. if( nSize<=pPage->maxLocal ){
  58876. nSize += (u32)(pIter - pCell);
  58877. if( nSize<4 ) nSize = 4;
  58878. }else{
  58879. int minLocal = pPage->minLocal;
  58880. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  58881. testcase( nSize==pPage->maxLocal );
  58882. testcase( nSize==pPage->maxLocal+1 );
  58883. if( nSize>pPage->maxLocal ){
  58884. nSize = minLocal;
  58885. }
  58886. nSize += 4 + (u16)(pIter - pCell);
  58887. }
  58888. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  58889. return (u16)nSize;
  58890. }
  58891. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  58892. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  58893. u8 *pEnd; /* End mark for a varint */
  58894. #ifdef SQLITE_DEBUG
  58895. /* The value returned by this function should always be the same as
  58896. ** the (CellInfo.nSize) value found by doing a full parse of the
  58897. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  58898. ** this function verifies that this invariant is not violated. */
  58899. CellInfo debuginfo;
  58900. pPage->xParseCell(pPage, pCell, &debuginfo);
  58901. #else
  58902. UNUSED_PARAMETER(pPage);
  58903. #endif
  58904. assert( pPage->childPtrSize==4 );
  58905. pEnd = pIter + 9;
  58906. while( (*pIter++)&0x80 && pIter<pEnd );
  58907. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  58908. return (u16)(pIter - pCell);
  58909. }
  58910. #ifdef SQLITE_DEBUG
  58911. /* This variation on cellSizePtr() is used inside of assert() statements
  58912. ** only. */
  58913. static u16 cellSize(MemPage *pPage, int iCell){
  58914. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  58915. }
  58916. #endif
  58917. #ifndef SQLITE_OMIT_AUTOVACUUM
  58918. /*
  58919. ** If the cell pCell, part of page pPage contains a pointer
  58920. ** to an overflow page, insert an entry into the pointer-map
  58921. ** for the overflow page.
  58922. */
  58923. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  58924. CellInfo info;
  58925. if( *pRC ) return;
  58926. assert( pCell!=0 );
  58927. pPage->xParseCell(pPage, pCell, &info);
  58928. if( info.nLocal<info.nPayload ){
  58929. Pgno ovfl = get4byte(&pCell[info.nSize-4]);
  58930. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  58931. }
  58932. }
  58933. #endif
  58934. /*
  58935. ** Defragment the page given. This routine reorganizes cells within the
  58936. ** page so that there are no free-blocks on the free-block list.
  58937. **
  58938. ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
  58939. ** present in the page after this routine returns.
  58940. **
  58941. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  58942. ** b-tree page so that there are no freeblocks or fragment bytes, all
  58943. ** unused bytes are contained in the unallocated space region, and all
  58944. ** cells are packed tightly at the end of the page.
  58945. */
  58946. static int defragmentPage(MemPage *pPage, int nMaxFrag){
  58947. int i; /* Loop counter */
  58948. int pc; /* Address of the i-th cell */
  58949. int hdr; /* Offset to the page header */
  58950. int size; /* Size of a cell */
  58951. int usableSize; /* Number of usable bytes on a page */
  58952. int cellOffset; /* Offset to the cell pointer array */
  58953. int cbrk; /* Offset to the cell content area */
  58954. int nCell; /* Number of cells on the page */
  58955. unsigned char *data; /* The page data */
  58956. unsigned char *temp; /* Temp area for cell content */
  58957. unsigned char *src; /* Source of content */
  58958. int iCellFirst; /* First allowable cell index */
  58959. int iCellLast; /* Last possible cell index */
  58960. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  58961. assert( pPage->pBt!=0 );
  58962. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  58963. assert( pPage->nOverflow==0 );
  58964. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  58965. temp = 0;
  58966. src = data = pPage->aData;
  58967. hdr = pPage->hdrOffset;
  58968. cellOffset = pPage->cellOffset;
  58969. nCell = pPage->nCell;
  58970. assert( nCell==get2byte(&data[hdr+3]) );
  58971. iCellFirst = cellOffset + 2*nCell;
  58972. usableSize = pPage->pBt->usableSize;
  58973. /* This block handles pages with two or fewer free blocks and nMaxFrag
  58974. ** or fewer fragmented bytes. In this case it is faster to move the
  58975. ** two (or one) blocks of cells using memmove() and add the required
  58976. ** offsets to each pointer in the cell-pointer array than it is to
  58977. ** reconstruct the entire page. */
  58978. if( (int)data[hdr+7]<=nMaxFrag ){
  58979. int iFree = get2byte(&data[hdr+1]);
  58980. if( iFree ){
  58981. int iFree2 = get2byte(&data[iFree]);
  58982. /* pageFindSlot() has already verified that free blocks are sorted
  58983. ** in order of offset within the page, and that no block extends
  58984. ** past the end of the page. Provided the two free slots do not
  58985. ** overlap, this guarantees that the memmove() calls below will not
  58986. ** overwrite the usableSize byte buffer, even if the database page
  58987. ** is corrupt. */
  58988. assert( iFree2==0 || iFree2>iFree );
  58989. assert( iFree+get2byte(&data[iFree+2]) <= usableSize );
  58990. assert( iFree2==0 || iFree2+get2byte(&data[iFree2+2]) <= usableSize );
  58991. if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
  58992. u8 *pEnd = &data[cellOffset + nCell*2];
  58993. u8 *pAddr;
  58994. int sz2 = 0;
  58995. int sz = get2byte(&data[iFree+2]);
  58996. int top = get2byte(&data[hdr+5]);
  58997. if( top>=iFree ){
  58998. return SQLITE_CORRUPT_PAGE(pPage);
  58999. }
  59000. if( iFree2 ){
  59001. assert( iFree+sz<=iFree2 ); /* Verified by pageFindSlot() */
  59002. sz2 = get2byte(&data[iFree2+2]);
  59003. assert( iFree+sz+sz2+iFree2-(iFree+sz) <= usableSize );
  59004. memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
  59005. sz += sz2;
  59006. }
  59007. cbrk = top+sz;
  59008. assert( cbrk+(iFree-top) <= usableSize );
  59009. memmove(&data[cbrk], &data[top], iFree-top);
  59010. for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
  59011. pc = get2byte(pAddr);
  59012. if( pc<iFree ){ put2byte(pAddr, pc+sz); }
  59013. else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
  59014. }
  59015. goto defragment_out;
  59016. }
  59017. }
  59018. }
  59019. cbrk = usableSize;
  59020. iCellLast = usableSize - 4;
  59021. for(i=0; i<nCell; i++){
  59022. u8 *pAddr; /* The i-th cell pointer */
  59023. pAddr = &data[cellOffset + i*2];
  59024. pc = get2byte(pAddr);
  59025. testcase( pc==iCellFirst );
  59026. testcase( pc==iCellLast );
  59027. /* These conditions have already been verified in btreeInitPage()
  59028. ** if PRAGMA cell_size_check=ON.
  59029. */
  59030. if( pc<iCellFirst || pc>iCellLast ){
  59031. return SQLITE_CORRUPT_PAGE(pPage);
  59032. }
  59033. assert( pc>=iCellFirst && pc<=iCellLast );
  59034. size = pPage->xCellSize(pPage, &src[pc]);
  59035. cbrk -= size;
  59036. if( cbrk<iCellFirst || pc+size>usableSize ){
  59037. return SQLITE_CORRUPT_PAGE(pPage);
  59038. }
  59039. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  59040. testcase( cbrk+size==usableSize );
  59041. testcase( pc+size==usableSize );
  59042. put2byte(pAddr, cbrk);
  59043. if( temp==0 ){
  59044. int x;
  59045. if( cbrk==pc ) continue;
  59046. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  59047. x = get2byte(&data[hdr+5]);
  59048. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  59049. src = temp;
  59050. }
  59051. memcpy(&data[cbrk], &src[pc], size);
  59052. }
  59053. data[hdr+7] = 0;
  59054. defragment_out:
  59055. if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
  59056. return SQLITE_CORRUPT_PAGE(pPage);
  59057. }
  59058. assert( cbrk>=iCellFirst );
  59059. put2byte(&data[hdr+5], cbrk);
  59060. data[hdr+1] = 0;
  59061. data[hdr+2] = 0;
  59062. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  59063. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  59064. return SQLITE_OK;
  59065. }
  59066. /*
  59067. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  59068. ** size. If one can be found, return a pointer to the space and remove it
  59069. ** from the free-list.
  59070. **
  59071. ** If no suitable space can be found on the free-list, return NULL.
  59072. **
  59073. ** This function may detect corruption within pPg. If corruption is
  59074. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  59075. **
  59076. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  59077. ** will be ignored if adding the extra space to the fragmentation count
  59078. ** causes the fragmentation count to exceed 60.
  59079. */
  59080. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  59081. const int hdr = pPg->hdrOffset;
  59082. u8 * const aData = pPg->aData;
  59083. int iAddr = hdr + 1;
  59084. int pc = get2byte(&aData[iAddr]);
  59085. int x;
  59086. int usableSize = pPg->pBt->usableSize;
  59087. int size; /* Size of the free slot */
  59088. assert( pc>0 );
  59089. while( pc<=usableSize-4 ){
  59090. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  59091. ** freeblock form a big-endian integer which is the size of the freeblock
  59092. ** in bytes, including the 4-byte header. */
  59093. size = get2byte(&aData[pc+2]);
  59094. if( (x = size - nByte)>=0 ){
  59095. testcase( x==4 );
  59096. testcase( x==3 );
  59097. if( size+pc > usableSize ){
  59098. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  59099. return 0;
  59100. }else if( x<4 ){
  59101. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  59102. ** number of bytes in fragments may not exceed 60. */
  59103. if( aData[hdr+7]>57 ) return 0;
  59104. /* Remove the slot from the free-list. Update the number of
  59105. ** fragmented bytes within the page. */
  59106. memcpy(&aData[iAddr], &aData[pc], 2);
  59107. aData[hdr+7] += (u8)x;
  59108. }else{
  59109. /* The slot remains on the free-list. Reduce its size to account
  59110. ** for the portion used by the new allocation. */
  59111. put2byte(&aData[pc+2], x);
  59112. }
  59113. return &aData[pc + x];
  59114. }
  59115. iAddr = pc;
  59116. pc = get2byte(&aData[pc]);
  59117. if( pc<iAddr+size ) break;
  59118. }
  59119. if( pc ){
  59120. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  59121. }
  59122. return 0;
  59123. }
  59124. /*
  59125. ** Allocate nByte bytes of space from within the B-Tree page passed
  59126. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  59127. ** of the first byte of allocated space. Return either SQLITE_OK or
  59128. ** an error code (usually SQLITE_CORRUPT).
  59129. **
  59130. ** The caller guarantees that there is sufficient space to make the
  59131. ** allocation. This routine might need to defragment in order to bring
  59132. ** all the space together, however. This routine will avoid using
  59133. ** the first two bytes past the cell pointer area since presumably this
  59134. ** allocation is being made in order to insert a new cell, so we will
  59135. ** also end up needing a new cell pointer.
  59136. */
  59137. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  59138. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  59139. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  59140. int top; /* First byte of cell content area */
  59141. int rc = SQLITE_OK; /* Integer return code */
  59142. int gap; /* First byte of gap between cell pointers and cell content */
  59143. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  59144. assert( pPage->pBt );
  59145. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59146. assert( nByte>=0 ); /* Minimum cell size is 4 */
  59147. assert( pPage->nFree>=nByte );
  59148. assert( pPage->nOverflow==0 );
  59149. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  59150. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  59151. gap = pPage->cellOffset + 2*pPage->nCell;
  59152. assert( gap<=65536 );
  59153. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  59154. ** and the reserved space is zero (the usual value for reserved space)
  59155. ** then the cell content offset of an empty page wants to be 65536.
  59156. ** However, that integer is too large to be stored in a 2-byte unsigned
  59157. ** integer, so a value of 0 is used in its place. */
  59158. top = get2byte(&data[hdr+5]);
  59159. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  59160. if( gap>top ){
  59161. if( top==0 && pPage->pBt->usableSize==65536 ){
  59162. top = 65536;
  59163. }else{
  59164. return SQLITE_CORRUPT_PAGE(pPage);
  59165. }
  59166. }
  59167. /* If there is enough space between gap and top for one more cell pointer
  59168. ** array entry offset, and if the freelist is not empty, then search the
  59169. ** freelist looking for a free slot big enough to satisfy the request.
  59170. */
  59171. testcase( gap+2==top );
  59172. testcase( gap+1==top );
  59173. testcase( gap==top );
  59174. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  59175. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  59176. if( pSpace ){
  59177. assert( pSpace>=data && (pSpace - data)<65536 );
  59178. *pIdx = (int)(pSpace - data);
  59179. return SQLITE_OK;
  59180. }else if( rc ){
  59181. return rc;
  59182. }
  59183. }
  59184. /* The request could not be fulfilled using a freelist slot. Check
  59185. ** to see if defragmentation is necessary.
  59186. */
  59187. testcase( gap+2+nByte==top );
  59188. if( gap+2+nByte>top ){
  59189. assert( pPage->nCell>0 || CORRUPT_DB );
  59190. rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
  59191. if( rc ) return rc;
  59192. top = get2byteNotZero(&data[hdr+5]);
  59193. assert( gap+2+nByte<=top );
  59194. }
  59195. /* Allocate memory from the gap in between the cell pointer array
  59196. ** and the cell content area. The btreeInitPage() call has already
  59197. ** validated the freelist. Given that the freelist is valid, there
  59198. ** is no way that the allocation can extend off the end of the page.
  59199. ** The assert() below verifies the previous sentence.
  59200. */
  59201. top -= nByte;
  59202. put2byte(&data[hdr+5], top);
  59203. assert( top+nByte <= (int)pPage->pBt->usableSize );
  59204. *pIdx = top;
  59205. return SQLITE_OK;
  59206. }
  59207. /*
  59208. ** Return a section of the pPage->aData to the freelist.
  59209. ** The first byte of the new free block is pPage->aData[iStart]
  59210. ** and the size of the block is iSize bytes.
  59211. **
  59212. ** Adjacent freeblocks are coalesced.
  59213. **
  59214. ** Note that even though the freeblock list was checked by btreeInitPage(),
  59215. ** that routine will not detect overlap between cells or freeblocks. Nor
  59216. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  59217. ** at the end of the page. So do additional corruption checks inside this
  59218. ** routine and return SQLITE_CORRUPT if any problems are found.
  59219. */
  59220. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  59221. u16 iPtr; /* Address of ptr to next freeblock */
  59222. u16 iFreeBlk; /* Address of the next freeblock */
  59223. u8 hdr; /* Page header size. 0 or 100 */
  59224. u8 nFrag = 0; /* Reduction in fragmentation */
  59225. u16 iOrigSize = iSize; /* Original value of iSize */
  59226. u16 x; /* Offset to cell content area */
  59227. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  59228. unsigned char *data = pPage->aData; /* Page content */
  59229. assert( pPage->pBt!=0 );
  59230. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  59231. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  59232. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  59233. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59234. assert( iSize>=4 ); /* Minimum cell size is 4 */
  59235. assert( iStart<=pPage->pBt->usableSize-4 );
  59236. /* The list of freeblocks must be in ascending order. Find the
  59237. ** spot on the list where iStart should be inserted.
  59238. */
  59239. hdr = pPage->hdrOffset;
  59240. iPtr = hdr + 1;
  59241. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  59242. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  59243. }else{
  59244. while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
  59245. if( iFreeBlk<iPtr+4 ){
  59246. if( iFreeBlk==0 ) break;
  59247. return SQLITE_CORRUPT_PAGE(pPage);
  59248. }
  59249. iPtr = iFreeBlk;
  59250. }
  59251. if( iFreeBlk>pPage->pBt->usableSize-4 ){
  59252. return SQLITE_CORRUPT_PAGE(pPage);
  59253. }
  59254. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  59255. /* At this point:
  59256. ** iFreeBlk: First freeblock after iStart, or zero if none
  59257. ** iPtr: The address of a pointer to iFreeBlk
  59258. **
  59259. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  59260. */
  59261. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  59262. nFrag = iFreeBlk - iEnd;
  59263. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
  59264. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  59265. if( iEnd > pPage->pBt->usableSize ){
  59266. return SQLITE_CORRUPT_PAGE(pPage);
  59267. }
  59268. iSize = iEnd - iStart;
  59269. iFreeBlk = get2byte(&data[iFreeBlk]);
  59270. }
  59271. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  59272. ** pointer in the page header) then check to see if iStart should be
  59273. ** coalesced onto the end of iPtr.
  59274. */
  59275. if( iPtr>hdr+1 ){
  59276. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  59277. if( iPtrEnd+3>=iStart ){
  59278. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
  59279. nFrag += iStart - iPtrEnd;
  59280. iSize = iEnd - iPtr;
  59281. iStart = iPtr;
  59282. }
  59283. }
  59284. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
  59285. data[hdr+7] -= nFrag;
  59286. }
  59287. x = get2byte(&data[hdr+5]);
  59288. if( iStart<=x ){
  59289. /* The new freeblock is at the beginning of the cell content area,
  59290. ** so just extend the cell content area rather than create another
  59291. ** freelist entry */
  59292. if( iStart<x || iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
  59293. put2byte(&data[hdr+1], iFreeBlk);
  59294. put2byte(&data[hdr+5], iEnd);
  59295. }else{
  59296. /* Insert the new freeblock into the freelist */
  59297. put2byte(&data[iPtr], iStart);
  59298. }
  59299. if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
  59300. /* Overwrite deleted information with zeros when the secure_delete
  59301. ** option is enabled */
  59302. memset(&data[iStart], 0, iSize);
  59303. }
  59304. put2byte(&data[iStart], iFreeBlk);
  59305. put2byte(&data[iStart+2], iSize);
  59306. pPage->nFree += iOrigSize;
  59307. return SQLITE_OK;
  59308. }
  59309. /*
  59310. ** Decode the flags byte (the first byte of the header) for a page
  59311. ** and initialize fields of the MemPage structure accordingly.
  59312. **
  59313. ** Only the following combinations are supported. Anything different
  59314. ** indicates a corrupt database files:
  59315. **
  59316. ** PTF_ZERODATA
  59317. ** PTF_ZERODATA | PTF_LEAF
  59318. ** PTF_LEAFDATA | PTF_INTKEY
  59319. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  59320. */
  59321. static int decodeFlags(MemPage *pPage, int flagByte){
  59322. BtShared *pBt; /* A copy of pPage->pBt */
  59323. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  59324. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59325. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  59326. flagByte &= ~PTF_LEAF;
  59327. pPage->childPtrSize = 4-4*pPage->leaf;
  59328. pPage->xCellSize = cellSizePtr;
  59329. pBt = pPage->pBt;
  59330. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  59331. /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
  59332. ** interior table b-tree page. */
  59333. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  59334. /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
  59335. ** leaf table b-tree page. */
  59336. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  59337. pPage->intKey = 1;
  59338. if( pPage->leaf ){
  59339. pPage->intKeyLeaf = 1;
  59340. pPage->xParseCell = btreeParseCellPtr;
  59341. }else{
  59342. pPage->intKeyLeaf = 0;
  59343. pPage->xCellSize = cellSizePtrNoPayload;
  59344. pPage->xParseCell = btreeParseCellPtrNoPayload;
  59345. }
  59346. pPage->maxLocal = pBt->maxLeaf;
  59347. pPage->minLocal = pBt->minLeaf;
  59348. }else if( flagByte==PTF_ZERODATA ){
  59349. /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
  59350. ** interior index b-tree page. */
  59351. assert( (PTF_ZERODATA)==2 );
  59352. /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
  59353. ** leaf index b-tree page. */
  59354. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  59355. pPage->intKey = 0;
  59356. pPage->intKeyLeaf = 0;
  59357. pPage->xParseCell = btreeParseCellPtrIndex;
  59358. pPage->maxLocal = pBt->maxLocal;
  59359. pPage->minLocal = pBt->minLocal;
  59360. }else{
  59361. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  59362. ** an error. */
  59363. return SQLITE_CORRUPT_PAGE(pPage);
  59364. }
  59365. pPage->max1bytePayload = pBt->max1bytePayload;
  59366. return SQLITE_OK;
  59367. }
  59368. /*
  59369. ** Initialize the auxiliary information for a disk block.
  59370. **
  59371. ** Return SQLITE_OK on success. If we see that the page does
  59372. ** not contain a well-formed database page, then return
  59373. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  59374. ** guarantee that the page is well-formed. It only shows that
  59375. ** we failed to detect any corruption.
  59376. */
  59377. static int btreeInitPage(MemPage *pPage){
  59378. int pc; /* Address of a freeblock within pPage->aData[] */
  59379. u8 hdr; /* Offset to beginning of page header */
  59380. u8 *data; /* Equal to pPage->aData */
  59381. BtShared *pBt; /* The main btree structure */
  59382. int usableSize; /* Amount of usable space on each page */
  59383. u16 cellOffset; /* Offset from start of page to first cell pointer */
  59384. int nFree; /* Number of unused bytes on the page */
  59385. int top; /* First byte of the cell content area */
  59386. int iCellFirst; /* First allowable cell or freeblock offset */
  59387. int iCellLast; /* Last possible cell or freeblock offset */
  59388. assert( pPage->pBt!=0 );
  59389. assert( pPage->pBt->db!=0 );
  59390. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59391. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  59392. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  59393. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  59394. assert( pPage->isInit==0 );
  59395. pBt = pPage->pBt;
  59396. hdr = pPage->hdrOffset;
  59397. data = pPage->aData;
  59398. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  59399. ** the b-tree page type. */
  59400. if( decodeFlags(pPage, data[hdr]) ){
  59401. return SQLITE_CORRUPT_PAGE(pPage);
  59402. }
  59403. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  59404. pPage->maskPage = (u16)(pBt->pageSize - 1);
  59405. pPage->nOverflow = 0;
  59406. usableSize = pBt->usableSize;
  59407. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  59408. pPage->aDataEnd = &data[usableSize];
  59409. pPage->aCellIdx = &data[cellOffset];
  59410. pPage->aDataOfst = &data[pPage->childPtrSize];
  59411. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  59412. ** the start of the cell content area. A zero value for this integer is
  59413. ** interpreted as 65536. */
  59414. top = get2byteNotZero(&data[hdr+5]);
  59415. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  59416. ** number of cells on the page. */
  59417. pPage->nCell = get2byte(&data[hdr+3]);
  59418. if( pPage->nCell>MX_CELL(pBt) ){
  59419. /* To many cells for a single page. The page must be corrupt */
  59420. return SQLITE_CORRUPT_PAGE(pPage);
  59421. }
  59422. testcase( pPage->nCell==MX_CELL(pBt) );
  59423. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  59424. ** possible for a root page of a table that contains no rows) then the
  59425. ** offset to the cell content area will equal the page size minus the
  59426. ** bytes of reserved space. */
  59427. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  59428. /* A malformed database page might cause us to read past the end
  59429. ** of page when parsing a cell.
  59430. **
  59431. ** The following block of code checks early to see if a cell extends
  59432. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  59433. ** returned if it does.
  59434. */
  59435. iCellFirst = cellOffset + 2*pPage->nCell;
  59436. iCellLast = usableSize - 4;
  59437. if( pBt->db->flags & SQLITE_CellSizeCk ){
  59438. int i; /* Index into the cell pointer array */
  59439. int sz; /* Size of a cell */
  59440. if( !pPage->leaf ) iCellLast--;
  59441. for(i=0; i<pPage->nCell; i++){
  59442. pc = get2byteAligned(&data[cellOffset+i*2]);
  59443. testcase( pc==iCellFirst );
  59444. testcase( pc==iCellLast );
  59445. if( pc<iCellFirst || pc>iCellLast ){
  59446. return SQLITE_CORRUPT_PAGE(pPage);
  59447. }
  59448. sz = pPage->xCellSize(pPage, &data[pc]);
  59449. testcase( pc+sz==usableSize );
  59450. if( pc+sz>usableSize ){
  59451. return SQLITE_CORRUPT_PAGE(pPage);
  59452. }
  59453. }
  59454. if( !pPage->leaf ) iCellLast++;
  59455. }
  59456. /* Compute the total free space on the page
  59457. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  59458. ** start of the first freeblock on the page, or is zero if there are no
  59459. ** freeblocks. */
  59460. pc = get2byte(&data[hdr+1]);
  59461. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  59462. if( pc>0 ){
  59463. u32 next, size;
  59464. if( pc<iCellFirst ){
  59465. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  59466. ** always be at least one cell before the first freeblock.
  59467. */
  59468. return SQLITE_CORRUPT_PAGE(pPage);
  59469. }
  59470. while( 1 ){
  59471. if( pc>iCellLast ){
  59472. /* Freeblock off the end of the page */
  59473. return SQLITE_CORRUPT_PAGE(pPage);
  59474. }
  59475. next = get2byte(&data[pc]);
  59476. size = get2byte(&data[pc+2]);
  59477. nFree = nFree + size;
  59478. if( next<=pc+size+3 ) break;
  59479. pc = next;
  59480. }
  59481. if( next>0 ){
  59482. /* Freeblock not in ascending order */
  59483. return SQLITE_CORRUPT_PAGE(pPage);
  59484. }
  59485. if( pc+size>(unsigned int)usableSize ){
  59486. /* Last freeblock extends past page end */
  59487. return SQLITE_CORRUPT_PAGE(pPage);
  59488. }
  59489. }
  59490. /* At this point, nFree contains the sum of the offset to the start
  59491. ** of the cell-content area plus the number of free bytes within
  59492. ** the cell-content area. If this is greater than the usable-size
  59493. ** of the page, then the page must be corrupted. This check also
  59494. ** serves to verify that the offset to the start of the cell-content
  59495. ** area, according to the page header, lies within the page.
  59496. */
  59497. if( nFree>usableSize ){
  59498. return SQLITE_CORRUPT_PAGE(pPage);
  59499. }
  59500. pPage->nFree = (u16)(nFree - iCellFirst);
  59501. pPage->isInit = 1;
  59502. return SQLITE_OK;
  59503. }
  59504. /*
  59505. ** Set up a raw page so that it looks like a database page holding
  59506. ** no entries.
  59507. */
  59508. static void zeroPage(MemPage *pPage, int flags){
  59509. unsigned char *data = pPage->aData;
  59510. BtShared *pBt = pPage->pBt;
  59511. u8 hdr = pPage->hdrOffset;
  59512. u16 first;
  59513. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  59514. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  59515. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  59516. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  59517. assert( sqlite3_mutex_held(pBt->mutex) );
  59518. if( pBt->btsFlags & BTS_FAST_SECURE ){
  59519. memset(&data[hdr], 0, pBt->usableSize - hdr);
  59520. }
  59521. data[hdr] = (char)flags;
  59522. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  59523. memset(&data[hdr+1], 0, 4);
  59524. data[hdr+7] = 0;
  59525. put2byte(&data[hdr+5], pBt->usableSize);
  59526. pPage->nFree = (u16)(pBt->usableSize - first);
  59527. decodeFlags(pPage, flags);
  59528. pPage->cellOffset = first;
  59529. pPage->aDataEnd = &data[pBt->usableSize];
  59530. pPage->aCellIdx = &data[first];
  59531. pPage->aDataOfst = &data[pPage->childPtrSize];
  59532. pPage->nOverflow = 0;
  59533. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  59534. pPage->maskPage = (u16)(pBt->pageSize - 1);
  59535. pPage->nCell = 0;
  59536. pPage->isInit = 1;
  59537. }
  59538. /*
  59539. ** Convert a DbPage obtained from the pager into a MemPage used by
  59540. ** the btree layer.
  59541. */
  59542. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  59543. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  59544. if( pgno!=pPage->pgno ){
  59545. pPage->aData = sqlite3PagerGetData(pDbPage);
  59546. pPage->pDbPage = pDbPage;
  59547. pPage->pBt = pBt;
  59548. pPage->pgno = pgno;
  59549. pPage->hdrOffset = pgno==1 ? 100 : 0;
  59550. }
  59551. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  59552. return pPage;
  59553. }
  59554. /*
  59555. ** Get a page from the pager. Initialize the MemPage.pBt and
  59556. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  59557. **
  59558. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  59559. ** about the content of the page at this time. So do not go to the disk
  59560. ** to fetch the content. Just fill in the content with zeros for now.
  59561. ** If in the future we call sqlite3PagerWrite() on this page, that
  59562. ** means we have started to be concerned about content and the disk
  59563. ** read should occur at that point.
  59564. */
  59565. static int btreeGetPage(
  59566. BtShared *pBt, /* The btree */
  59567. Pgno pgno, /* Number of the page to fetch */
  59568. MemPage **ppPage, /* Return the page in this parameter */
  59569. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  59570. ){
  59571. int rc;
  59572. DbPage *pDbPage;
  59573. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  59574. assert( sqlite3_mutex_held(pBt->mutex) );
  59575. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  59576. if( rc ) return rc;
  59577. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  59578. return SQLITE_OK;
  59579. }
  59580. /*
  59581. ** Retrieve a page from the pager cache. If the requested page is not
  59582. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  59583. ** MemPage.aData elements if needed.
  59584. */
  59585. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  59586. DbPage *pDbPage;
  59587. assert( sqlite3_mutex_held(pBt->mutex) );
  59588. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  59589. if( pDbPage ){
  59590. return btreePageFromDbPage(pDbPage, pgno, pBt);
  59591. }
  59592. return 0;
  59593. }
  59594. /*
  59595. ** Return the size of the database file in pages. If there is any kind of
  59596. ** error, return ((unsigned int)-1).
  59597. */
  59598. static Pgno btreePagecount(BtShared *pBt){
  59599. return pBt->nPage;
  59600. }
  59601. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  59602. assert( sqlite3BtreeHoldsMutex(p) );
  59603. assert( ((p->pBt->nPage)&0x80000000)==0 );
  59604. return btreePagecount(p->pBt);
  59605. }
  59606. /*
  59607. ** Get a page from the pager and initialize it.
  59608. **
  59609. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  59610. ** call. Do additional sanity checking on the page in this case.
  59611. ** And if the fetch fails, this routine must decrement pCur->iPage.
  59612. **
  59613. ** The page is fetched as read-write unless pCur is not NULL and is
  59614. ** a read-only cursor.
  59615. **
  59616. ** If an error occurs, then *ppPage is undefined. It
  59617. ** may remain unchanged, or it may be set to an invalid value.
  59618. */
  59619. static int getAndInitPage(
  59620. BtShared *pBt, /* The database file */
  59621. Pgno pgno, /* Number of the page to get */
  59622. MemPage **ppPage, /* Write the page pointer here */
  59623. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  59624. int bReadOnly /* True for a read-only page */
  59625. ){
  59626. int rc;
  59627. DbPage *pDbPage;
  59628. assert( sqlite3_mutex_held(pBt->mutex) );
  59629. assert( pCur==0 || ppPage==&pCur->pPage );
  59630. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  59631. assert( pCur==0 || pCur->iPage>0 );
  59632. if( pgno>btreePagecount(pBt) ){
  59633. rc = SQLITE_CORRUPT_BKPT;
  59634. goto getAndInitPage_error;
  59635. }
  59636. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  59637. if( rc ){
  59638. goto getAndInitPage_error;
  59639. }
  59640. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  59641. if( (*ppPage)->isInit==0 ){
  59642. btreePageFromDbPage(pDbPage, pgno, pBt);
  59643. rc = btreeInitPage(*ppPage);
  59644. if( rc!=SQLITE_OK ){
  59645. releasePage(*ppPage);
  59646. goto getAndInitPage_error;
  59647. }
  59648. }
  59649. assert( (*ppPage)->pgno==pgno );
  59650. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  59651. /* If obtaining a child page for a cursor, we must verify that the page is
  59652. ** compatible with the root page. */
  59653. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  59654. rc = SQLITE_CORRUPT_PGNO(pgno);
  59655. releasePage(*ppPage);
  59656. goto getAndInitPage_error;
  59657. }
  59658. return SQLITE_OK;
  59659. getAndInitPage_error:
  59660. if( pCur ){
  59661. pCur->iPage--;
  59662. pCur->pPage = pCur->apPage[pCur->iPage];
  59663. }
  59664. testcase( pgno==0 );
  59665. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  59666. return rc;
  59667. }
  59668. /*
  59669. ** Release a MemPage. This should be called once for each prior
  59670. ** call to btreeGetPage.
  59671. **
  59672. ** Page1 is a special case and must be released using releasePageOne().
  59673. */
  59674. static void releasePageNotNull(MemPage *pPage){
  59675. assert( pPage->aData );
  59676. assert( pPage->pBt );
  59677. assert( pPage->pDbPage!=0 );
  59678. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  59679. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  59680. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59681. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  59682. }
  59683. static void releasePage(MemPage *pPage){
  59684. if( pPage ) releasePageNotNull(pPage);
  59685. }
  59686. static void releasePageOne(MemPage *pPage){
  59687. assert( pPage!=0 );
  59688. assert( pPage->aData );
  59689. assert( pPage->pBt );
  59690. assert( pPage->pDbPage!=0 );
  59691. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  59692. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  59693. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59694. sqlite3PagerUnrefPageOne(pPage->pDbPage);
  59695. }
  59696. /*
  59697. ** Get an unused page.
  59698. **
  59699. ** This works just like btreeGetPage() with the addition:
  59700. **
  59701. ** * If the page is already in use for some other purpose, immediately
  59702. ** release it and return an SQLITE_CURRUPT error.
  59703. ** * Make sure the isInit flag is clear
  59704. */
  59705. static int btreeGetUnusedPage(
  59706. BtShared *pBt, /* The btree */
  59707. Pgno pgno, /* Number of the page to fetch */
  59708. MemPage **ppPage, /* Return the page in this parameter */
  59709. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  59710. ){
  59711. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  59712. if( rc==SQLITE_OK ){
  59713. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  59714. releasePage(*ppPage);
  59715. *ppPage = 0;
  59716. return SQLITE_CORRUPT_BKPT;
  59717. }
  59718. (*ppPage)->isInit = 0;
  59719. }else{
  59720. *ppPage = 0;
  59721. }
  59722. return rc;
  59723. }
  59724. /*
  59725. ** During a rollback, when the pager reloads information into the cache
  59726. ** so that the cache is restored to its original state at the start of
  59727. ** the transaction, for each page restored this routine is called.
  59728. **
  59729. ** This routine needs to reset the extra data section at the end of the
  59730. ** page to agree with the restored data.
  59731. */
  59732. static void pageReinit(DbPage *pData){
  59733. MemPage *pPage;
  59734. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  59735. assert( sqlite3PagerPageRefcount(pData)>0 );
  59736. if( pPage->isInit ){
  59737. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  59738. pPage->isInit = 0;
  59739. if( sqlite3PagerPageRefcount(pData)>1 ){
  59740. /* pPage might not be a btree page; it might be an overflow page
  59741. ** or ptrmap page or a free page. In those cases, the following
  59742. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  59743. ** But no harm is done by this. And it is very important that
  59744. ** btreeInitPage() be called on every btree page so we make
  59745. ** the call for every page that comes in for re-initing. */
  59746. btreeInitPage(pPage);
  59747. }
  59748. }
  59749. }
  59750. /*
  59751. ** Invoke the busy handler for a btree.
  59752. */
  59753. static int btreeInvokeBusyHandler(void *pArg){
  59754. BtShared *pBt = (BtShared*)pArg;
  59755. assert( pBt->db );
  59756. assert( sqlite3_mutex_held(pBt->db->mutex) );
  59757. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler,
  59758. sqlite3PagerFile(pBt->pPager));
  59759. }
  59760. /*
  59761. ** Open a database file.
  59762. **
  59763. ** zFilename is the name of the database file. If zFilename is NULL
  59764. ** then an ephemeral database is created. The ephemeral database might
  59765. ** be exclusively in memory, or it might use a disk-based memory cache.
  59766. ** Either way, the ephemeral database will be automatically deleted
  59767. ** when sqlite3BtreeClose() is called.
  59768. **
  59769. ** If zFilename is ":memory:" then an in-memory database is created
  59770. ** that is automatically destroyed when it is closed.
  59771. **
  59772. ** The "flags" parameter is a bitmask that might contain bits like
  59773. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  59774. **
  59775. ** If the database is already opened in the same database connection
  59776. ** and we are in shared cache mode, then the open will fail with an
  59777. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  59778. ** objects in the same database connection since doing so will lead
  59779. ** to problems with locking.
  59780. */
  59781. SQLITE_PRIVATE int sqlite3BtreeOpen(
  59782. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  59783. const char *zFilename, /* Name of the file containing the BTree database */
  59784. sqlite3 *db, /* Associated database handle */
  59785. Btree **ppBtree, /* Pointer to new Btree object written here */
  59786. int flags, /* Options */
  59787. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  59788. ){
  59789. BtShared *pBt = 0; /* Shared part of btree structure */
  59790. Btree *p; /* Handle to return */
  59791. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  59792. int rc = SQLITE_OK; /* Result code from this function */
  59793. u8 nReserve; /* Byte of unused space on each page */
  59794. unsigned char zDbHeader[100]; /* Database header content */
  59795. /* True if opening an ephemeral, temporary database */
  59796. const int isTempDb = zFilename==0 || zFilename[0]==0;
  59797. /* Set the variable isMemdb to true for an in-memory database, or
  59798. ** false for a file-based database.
  59799. */
  59800. #ifdef SQLITE_OMIT_MEMORYDB
  59801. const int isMemdb = 0;
  59802. #else
  59803. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  59804. || (isTempDb && sqlite3TempInMemory(db))
  59805. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  59806. #endif
  59807. assert( db!=0 );
  59808. assert( pVfs!=0 );
  59809. assert( sqlite3_mutex_held(db->mutex) );
  59810. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  59811. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  59812. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  59813. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  59814. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  59815. if( isMemdb ){
  59816. flags |= BTREE_MEMORY;
  59817. }
  59818. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  59819. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  59820. }
  59821. p = sqlite3MallocZero(sizeof(Btree));
  59822. if( !p ){
  59823. return SQLITE_NOMEM_BKPT;
  59824. }
  59825. p->inTrans = TRANS_NONE;
  59826. p->db = db;
  59827. #ifndef SQLITE_OMIT_SHARED_CACHE
  59828. p->lock.pBtree = p;
  59829. p->lock.iTable = 1;
  59830. #endif
  59831. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  59832. /*
  59833. ** If this Btree is a candidate for shared cache, try to find an
  59834. ** existing BtShared object that we can share with
  59835. */
  59836. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  59837. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  59838. int nFilename = sqlite3Strlen30(zFilename)+1;
  59839. int nFullPathname = pVfs->mxPathname+1;
  59840. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  59841. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  59842. p->sharable = 1;
  59843. if( !zFullPathname ){
  59844. sqlite3_free(p);
  59845. return SQLITE_NOMEM_BKPT;
  59846. }
  59847. if( isMemdb ){
  59848. memcpy(zFullPathname, zFilename, nFilename);
  59849. }else{
  59850. rc = sqlite3OsFullPathname(pVfs, zFilename,
  59851. nFullPathname, zFullPathname);
  59852. if( rc ){
  59853. sqlite3_free(zFullPathname);
  59854. sqlite3_free(p);
  59855. return rc;
  59856. }
  59857. }
  59858. #if SQLITE_THREADSAFE
  59859. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  59860. sqlite3_mutex_enter(mutexOpen);
  59861. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  59862. sqlite3_mutex_enter(mutexShared);
  59863. #endif
  59864. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  59865. assert( pBt->nRef>0 );
  59866. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  59867. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  59868. int iDb;
  59869. for(iDb=db->nDb-1; iDb>=0; iDb--){
  59870. Btree *pExisting = db->aDb[iDb].pBt;
  59871. if( pExisting && pExisting->pBt==pBt ){
  59872. sqlite3_mutex_leave(mutexShared);
  59873. sqlite3_mutex_leave(mutexOpen);
  59874. sqlite3_free(zFullPathname);
  59875. sqlite3_free(p);
  59876. return SQLITE_CONSTRAINT;
  59877. }
  59878. }
  59879. p->pBt = pBt;
  59880. pBt->nRef++;
  59881. break;
  59882. }
  59883. }
  59884. sqlite3_mutex_leave(mutexShared);
  59885. sqlite3_free(zFullPathname);
  59886. }
  59887. #ifdef SQLITE_DEBUG
  59888. else{
  59889. /* In debug mode, we mark all persistent databases as sharable
  59890. ** even when they are not. This exercises the locking code and
  59891. ** gives more opportunity for asserts(sqlite3_mutex_held())
  59892. ** statements to find locking problems.
  59893. */
  59894. p->sharable = 1;
  59895. }
  59896. #endif
  59897. }
  59898. #endif
  59899. if( pBt==0 ){
  59900. /*
  59901. ** The following asserts make sure that structures used by the btree are
  59902. ** the right size. This is to guard against size changes that result
  59903. ** when compiling on a different architecture.
  59904. */
  59905. assert( sizeof(i64)==8 );
  59906. assert( sizeof(u64)==8 );
  59907. assert( sizeof(u32)==4 );
  59908. assert( sizeof(u16)==2 );
  59909. assert( sizeof(Pgno)==4 );
  59910. pBt = sqlite3MallocZero( sizeof(*pBt) );
  59911. if( pBt==0 ){
  59912. rc = SQLITE_NOMEM_BKPT;
  59913. goto btree_open_out;
  59914. }
  59915. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  59916. sizeof(MemPage), flags, vfsFlags, pageReinit);
  59917. if( rc==SQLITE_OK ){
  59918. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  59919. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  59920. }
  59921. if( rc!=SQLITE_OK ){
  59922. goto btree_open_out;
  59923. }
  59924. pBt->openFlags = (u8)flags;
  59925. pBt->db = db;
  59926. sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  59927. p->pBt = pBt;
  59928. pBt->pCursor = 0;
  59929. pBt->pPage1 = 0;
  59930. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  59931. #if defined(SQLITE_SECURE_DELETE)
  59932. pBt->btsFlags |= BTS_SECURE_DELETE;
  59933. #elif defined(SQLITE_FAST_SECURE_DELETE)
  59934. pBt->btsFlags |= BTS_OVERWRITE;
  59935. #endif
  59936. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  59937. ** determined by the 2-byte integer located at an offset of 16 bytes from
  59938. ** the beginning of the database file. */
  59939. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  59940. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  59941. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  59942. pBt->pageSize = 0;
  59943. #ifndef SQLITE_OMIT_AUTOVACUUM
  59944. /* If the magic name ":memory:" will create an in-memory database, then
  59945. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  59946. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  59947. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  59948. ** regular file-name. In this case the auto-vacuum applies as per normal.
  59949. */
  59950. if( zFilename && !isMemdb ){
  59951. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  59952. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  59953. }
  59954. #endif
  59955. nReserve = 0;
  59956. }else{
  59957. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  59958. ** determined by the one-byte unsigned integer found at an offset of 20
  59959. ** into the database file header. */
  59960. nReserve = zDbHeader[20];
  59961. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  59962. #ifndef SQLITE_OMIT_AUTOVACUUM
  59963. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  59964. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  59965. #endif
  59966. }
  59967. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  59968. if( rc ) goto btree_open_out;
  59969. pBt->usableSize = pBt->pageSize - nReserve;
  59970. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  59971. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  59972. /* Add the new BtShared object to the linked list sharable BtShareds.
  59973. */
  59974. pBt->nRef = 1;
  59975. if( p->sharable ){
  59976. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  59977. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  59978. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  59979. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  59980. if( pBt->mutex==0 ){
  59981. rc = SQLITE_NOMEM_BKPT;
  59982. goto btree_open_out;
  59983. }
  59984. }
  59985. sqlite3_mutex_enter(mutexShared);
  59986. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  59987. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  59988. sqlite3_mutex_leave(mutexShared);
  59989. }
  59990. #endif
  59991. }
  59992. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  59993. /* If the new Btree uses a sharable pBtShared, then link the new
  59994. ** Btree into the list of all sharable Btrees for the same connection.
  59995. ** The list is kept in ascending order by pBt address.
  59996. */
  59997. if( p->sharable ){
  59998. int i;
  59999. Btree *pSib;
  60000. for(i=0; i<db->nDb; i++){
  60001. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  60002. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  60003. if( (uptr)p->pBt<(uptr)pSib->pBt ){
  60004. p->pNext = pSib;
  60005. p->pPrev = 0;
  60006. pSib->pPrev = p;
  60007. }else{
  60008. while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
  60009. pSib = pSib->pNext;
  60010. }
  60011. p->pNext = pSib->pNext;
  60012. p->pPrev = pSib;
  60013. if( p->pNext ){
  60014. p->pNext->pPrev = p;
  60015. }
  60016. pSib->pNext = p;
  60017. }
  60018. break;
  60019. }
  60020. }
  60021. }
  60022. #endif
  60023. *ppBtree = p;
  60024. btree_open_out:
  60025. if( rc!=SQLITE_OK ){
  60026. if( pBt && pBt->pPager ){
  60027. sqlite3PagerClose(pBt->pPager, 0);
  60028. }
  60029. sqlite3_free(pBt);
  60030. sqlite3_free(p);
  60031. *ppBtree = 0;
  60032. }else{
  60033. sqlite3_file *pFile;
  60034. /* If the B-Tree was successfully opened, set the pager-cache size to the
  60035. ** default value. Except, when opening on an existing shared pager-cache,
  60036. ** do not change the pager-cache size.
  60037. */
  60038. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  60039. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  60040. }
  60041. pFile = sqlite3PagerFile(pBt->pPager);
  60042. if( pFile->pMethods ){
  60043. sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
  60044. }
  60045. }
  60046. if( mutexOpen ){
  60047. assert( sqlite3_mutex_held(mutexOpen) );
  60048. sqlite3_mutex_leave(mutexOpen);
  60049. }
  60050. assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
  60051. return rc;
  60052. }
  60053. /*
  60054. ** Decrement the BtShared.nRef counter. When it reaches zero,
  60055. ** remove the BtShared structure from the sharing list. Return
  60056. ** true if the BtShared.nRef counter reaches zero and return
  60057. ** false if it is still positive.
  60058. */
  60059. static int removeFromSharingList(BtShared *pBt){
  60060. #ifndef SQLITE_OMIT_SHARED_CACHE
  60061. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  60062. BtShared *pList;
  60063. int removed = 0;
  60064. assert( sqlite3_mutex_notheld(pBt->mutex) );
  60065. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  60066. sqlite3_mutex_enter(pMaster);
  60067. pBt->nRef--;
  60068. if( pBt->nRef<=0 ){
  60069. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  60070. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  60071. }else{
  60072. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  60073. while( ALWAYS(pList) && pList->pNext!=pBt ){
  60074. pList=pList->pNext;
  60075. }
  60076. if( ALWAYS(pList) ){
  60077. pList->pNext = pBt->pNext;
  60078. }
  60079. }
  60080. if( SQLITE_THREADSAFE ){
  60081. sqlite3_mutex_free(pBt->mutex);
  60082. }
  60083. removed = 1;
  60084. }
  60085. sqlite3_mutex_leave(pMaster);
  60086. return removed;
  60087. #else
  60088. return 1;
  60089. #endif
  60090. }
  60091. /*
  60092. ** Make sure pBt->pTmpSpace points to an allocation of
  60093. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  60094. ** pointer.
  60095. */
  60096. static void allocateTempSpace(BtShared *pBt){
  60097. if( !pBt->pTmpSpace ){
  60098. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  60099. /* One of the uses of pBt->pTmpSpace is to format cells before
  60100. ** inserting them into a leaf page (function fillInCell()). If
  60101. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  60102. ** by the various routines that manipulate binary cells. Which
  60103. ** can mean that fillInCell() only initializes the first 2 or 3
  60104. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  60105. ** it into a database page. This is not actually a problem, but it
  60106. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  60107. ** data is passed to system call write(). So to avoid this error,
  60108. ** zero the first 4 bytes of temp space here.
  60109. **
  60110. ** Also: Provide four bytes of initialized space before the
  60111. ** beginning of pTmpSpace as an area available to prepend the
  60112. ** left-child pointer to the beginning of a cell.
  60113. */
  60114. if( pBt->pTmpSpace ){
  60115. memset(pBt->pTmpSpace, 0, 8);
  60116. pBt->pTmpSpace += 4;
  60117. }
  60118. }
  60119. }
  60120. /*
  60121. ** Free the pBt->pTmpSpace allocation
  60122. */
  60123. static void freeTempSpace(BtShared *pBt){
  60124. if( pBt->pTmpSpace ){
  60125. pBt->pTmpSpace -= 4;
  60126. sqlite3PageFree(pBt->pTmpSpace);
  60127. pBt->pTmpSpace = 0;
  60128. }
  60129. }
  60130. /*
  60131. ** Close an open database and invalidate all cursors.
  60132. */
  60133. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  60134. BtShared *pBt = p->pBt;
  60135. BtCursor *pCur;
  60136. /* Close all cursors opened via this handle. */
  60137. assert( sqlite3_mutex_held(p->db->mutex) );
  60138. sqlite3BtreeEnter(p);
  60139. pCur = pBt->pCursor;
  60140. while( pCur ){
  60141. BtCursor *pTmp = pCur;
  60142. pCur = pCur->pNext;
  60143. if( pTmp->pBtree==p ){
  60144. sqlite3BtreeCloseCursor(pTmp);
  60145. }
  60146. }
  60147. /* Rollback any active transaction and free the handle structure.
  60148. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  60149. ** this handle.
  60150. */
  60151. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  60152. sqlite3BtreeLeave(p);
  60153. /* If there are still other outstanding references to the shared-btree
  60154. ** structure, return now. The remainder of this procedure cleans
  60155. ** up the shared-btree.
  60156. */
  60157. assert( p->wantToLock==0 && p->locked==0 );
  60158. if( !p->sharable || removeFromSharingList(pBt) ){
  60159. /* The pBt is no longer on the sharing list, so we can access
  60160. ** it without having to hold the mutex.
  60161. **
  60162. ** Clean out and delete the BtShared object.
  60163. */
  60164. assert( !pBt->pCursor );
  60165. sqlite3PagerClose(pBt->pPager, p->db);
  60166. if( pBt->xFreeSchema && pBt->pSchema ){
  60167. pBt->xFreeSchema(pBt->pSchema);
  60168. }
  60169. sqlite3DbFree(0, pBt->pSchema);
  60170. freeTempSpace(pBt);
  60171. sqlite3_free(pBt);
  60172. }
  60173. #ifndef SQLITE_OMIT_SHARED_CACHE
  60174. assert( p->wantToLock==0 );
  60175. assert( p->locked==0 );
  60176. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  60177. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  60178. #endif
  60179. sqlite3_free(p);
  60180. return SQLITE_OK;
  60181. }
  60182. /*
  60183. ** Change the "soft" limit on the number of pages in the cache.
  60184. ** Unused and unmodified pages will be recycled when the number of
  60185. ** pages in the cache exceeds this soft limit. But the size of the
  60186. ** cache is allowed to grow larger than this limit if it contains
  60187. ** dirty pages or pages still in active use.
  60188. */
  60189. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  60190. BtShared *pBt = p->pBt;
  60191. assert( sqlite3_mutex_held(p->db->mutex) );
  60192. sqlite3BtreeEnter(p);
  60193. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  60194. sqlite3BtreeLeave(p);
  60195. return SQLITE_OK;
  60196. }
  60197. /*
  60198. ** Change the "spill" limit on the number of pages in the cache.
  60199. ** If the number of pages exceeds this limit during a write transaction,
  60200. ** the pager might attempt to "spill" pages to the journal early in
  60201. ** order to free up memory.
  60202. **
  60203. ** The value returned is the current spill size. If zero is passed
  60204. ** as an argument, no changes are made to the spill size setting, so
  60205. ** using mxPage of 0 is a way to query the current spill size.
  60206. */
  60207. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  60208. BtShared *pBt = p->pBt;
  60209. int res;
  60210. assert( sqlite3_mutex_held(p->db->mutex) );
  60211. sqlite3BtreeEnter(p);
  60212. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  60213. sqlite3BtreeLeave(p);
  60214. return res;
  60215. }
  60216. #if SQLITE_MAX_MMAP_SIZE>0
  60217. /*
  60218. ** Change the limit on the amount of the database file that may be
  60219. ** memory mapped.
  60220. */
  60221. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  60222. BtShared *pBt = p->pBt;
  60223. assert( sqlite3_mutex_held(p->db->mutex) );
  60224. sqlite3BtreeEnter(p);
  60225. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  60226. sqlite3BtreeLeave(p);
  60227. return SQLITE_OK;
  60228. }
  60229. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  60230. /*
  60231. ** Change the way data is synced to disk in order to increase or decrease
  60232. ** how well the database resists damage due to OS crashes and power
  60233. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  60234. ** there is a high probability of damage) Level 2 is the default. There
  60235. ** is a very low but non-zero probability of damage. Level 3 reduces the
  60236. ** probability of damage to near zero but with a write performance reduction.
  60237. */
  60238. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  60239. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  60240. Btree *p, /* The btree to set the safety level on */
  60241. unsigned pgFlags /* Various PAGER_* flags */
  60242. ){
  60243. BtShared *pBt = p->pBt;
  60244. assert( sqlite3_mutex_held(p->db->mutex) );
  60245. sqlite3BtreeEnter(p);
  60246. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  60247. sqlite3BtreeLeave(p);
  60248. return SQLITE_OK;
  60249. }
  60250. #endif
  60251. /*
  60252. ** Change the default pages size and the number of reserved bytes per page.
  60253. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  60254. ** without changing anything.
  60255. **
  60256. ** The page size must be a power of 2 between 512 and 65536. If the page
  60257. ** size supplied does not meet this constraint then the page size is not
  60258. ** changed.
  60259. **
  60260. ** Page sizes are constrained to be a power of two so that the region
  60261. ** of the database file used for locking (beginning at PENDING_BYTE,
  60262. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  60263. ** at the beginning of a page.
  60264. **
  60265. ** If parameter nReserve is less than zero, then the number of reserved
  60266. ** bytes per page is left unchanged.
  60267. **
  60268. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  60269. ** and autovacuum mode can no longer be changed.
  60270. */
  60271. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  60272. int rc = SQLITE_OK;
  60273. BtShared *pBt = p->pBt;
  60274. assert( nReserve>=-1 && nReserve<=255 );
  60275. sqlite3BtreeEnter(p);
  60276. #if SQLITE_HAS_CODEC
  60277. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  60278. #endif
  60279. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  60280. sqlite3BtreeLeave(p);
  60281. return SQLITE_READONLY;
  60282. }
  60283. if( nReserve<0 ){
  60284. nReserve = pBt->pageSize - pBt->usableSize;
  60285. }
  60286. assert( nReserve>=0 && nReserve<=255 );
  60287. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  60288. ((pageSize-1)&pageSize)==0 ){
  60289. assert( (pageSize & 7)==0 );
  60290. assert( !pBt->pCursor );
  60291. pBt->pageSize = (u32)pageSize;
  60292. freeTempSpace(pBt);
  60293. }
  60294. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  60295. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  60296. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  60297. sqlite3BtreeLeave(p);
  60298. return rc;
  60299. }
  60300. /*
  60301. ** Return the currently defined page size
  60302. */
  60303. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  60304. return p->pBt->pageSize;
  60305. }
  60306. /*
  60307. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  60308. ** may only be called if it is guaranteed that the b-tree mutex is already
  60309. ** held.
  60310. **
  60311. ** This is useful in one special case in the backup API code where it is
  60312. ** known that the shared b-tree mutex is held, but the mutex on the
  60313. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  60314. ** were to be called, it might collide with some other operation on the
  60315. ** database handle that owns *p, causing undefined behavior.
  60316. */
  60317. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  60318. int n;
  60319. assert( sqlite3_mutex_held(p->pBt->mutex) );
  60320. n = p->pBt->pageSize - p->pBt->usableSize;
  60321. return n;
  60322. }
  60323. /*
  60324. ** Return the number of bytes of space at the end of every page that
  60325. ** are intentually left unused. This is the "reserved" space that is
  60326. ** sometimes used by extensions.
  60327. **
  60328. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  60329. ** greater of the current reserved space and the maximum requested
  60330. ** reserve space.
  60331. */
  60332. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  60333. int n;
  60334. sqlite3BtreeEnter(p);
  60335. n = sqlite3BtreeGetReserveNoMutex(p);
  60336. #ifdef SQLITE_HAS_CODEC
  60337. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  60338. #endif
  60339. sqlite3BtreeLeave(p);
  60340. return n;
  60341. }
  60342. /*
  60343. ** Set the maximum page count for a database if mxPage is positive.
  60344. ** No changes are made if mxPage is 0 or negative.
  60345. ** Regardless of the value of mxPage, return the maximum page count.
  60346. */
  60347. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  60348. int n;
  60349. sqlite3BtreeEnter(p);
  60350. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  60351. sqlite3BtreeLeave(p);
  60352. return n;
  60353. }
  60354. /*
  60355. ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
  60356. **
  60357. ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
  60358. ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
  60359. ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
  60360. ** newFlag==(-1) No changes
  60361. **
  60362. ** This routine acts as a query if newFlag is less than zero
  60363. **
  60364. ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
  60365. ** freelist leaf pages are not written back to the database. Thus in-page
  60366. ** deleted content is cleared, but freelist deleted content is not.
  60367. **
  60368. ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
  60369. ** that freelist leaf pages are written back into the database, increasing
  60370. ** the amount of disk I/O.
  60371. */
  60372. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  60373. int b;
  60374. if( p==0 ) return 0;
  60375. sqlite3BtreeEnter(p);
  60376. assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
  60377. assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
  60378. if( newFlag>=0 ){
  60379. p->pBt->btsFlags &= ~BTS_FAST_SECURE;
  60380. p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
  60381. }
  60382. b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
  60383. sqlite3BtreeLeave(p);
  60384. return b;
  60385. }
  60386. /*
  60387. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  60388. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  60389. ** is disabled. The default value for the auto-vacuum property is
  60390. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  60391. */
  60392. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  60393. #ifdef SQLITE_OMIT_AUTOVACUUM
  60394. return SQLITE_READONLY;
  60395. #else
  60396. BtShared *pBt = p->pBt;
  60397. int rc = SQLITE_OK;
  60398. u8 av = (u8)autoVacuum;
  60399. sqlite3BtreeEnter(p);
  60400. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  60401. rc = SQLITE_READONLY;
  60402. }else{
  60403. pBt->autoVacuum = av ?1:0;
  60404. pBt->incrVacuum = av==2 ?1:0;
  60405. }
  60406. sqlite3BtreeLeave(p);
  60407. return rc;
  60408. #endif
  60409. }
  60410. /*
  60411. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  60412. ** enabled 1 is returned. Otherwise 0.
  60413. */
  60414. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  60415. #ifdef SQLITE_OMIT_AUTOVACUUM
  60416. return BTREE_AUTOVACUUM_NONE;
  60417. #else
  60418. int rc;
  60419. sqlite3BtreeEnter(p);
  60420. rc = (
  60421. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  60422. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  60423. BTREE_AUTOVACUUM_INCR
  60424. );
  60425. sqlite3BtreeLeave(p);
  60426. return rc;
  60427. #endif
  60428. }
  60429. /*
  60430. ** If the user has not set the safety-level for this database connection
  60431. ** using "PRAGMA synchronous", and if the safety-level is not already
  60432. ** set to the value passed to this function as the second parameter,
  60433. ** set it so.
  60434. */
  60435. #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
  60436. && !defined(SQLITE_OMIT_WAL)
  60437. static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
  60438. sqlite3 *db;
  60439. Db *pDb;
  60440. if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
  60441. while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
  60442. if( pDb->bSyncSet==0
  60443. && pDb->safety_level!=safety_level
  60444. && pDb!=&db->aDb[1]
  60445. ){
  60446. pDb->safety_level = safety_level;
  60447. sqlite3PagerSetFlags(pBt->pPager,
  60448. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
  60449. }
  60450. }
  60451. }
  60452. #else
  60453. # define setDefaultSyncFlag(pBt,safety_level)
  60454. #endif
  60455. /*
  60456. ** Get a reference to pPage1 of the database file. This will
  60457. ** also acquire a readlock on that file.
  60458. **
  60459. ** SQLITE_OK is returned on success. If the file is not a
  60460. ** well-formed database file, then SQLITE_CORRUPT is returned.
  60461. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  60462. ** is returned if we run out of memory.
  60463. */
  60464. static int lockBtree(BtShared *pBt){
  60465. int rc; /* Result code from subfunctions */
  60466. MemPage *pPage1; /* Page 1 of the database file */
  60467. int nPage; /* Number of pages in the database */
  60468. int nPageFile = 0; /* Number of pages in the database file */
  60469. int nPageHeader; /* Number of pages in the database according to hdr */
  60470. assert( sqlite3_mutex_held(pBt->mutex) );
  60471. assert( pBt->pPage1==0 );
  60472. rc = sqlite3PagerSharedLock(pBt->pPager);
  60473. if( rc!=SQLITE_OK ) return rc;
  60474. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  60475. if( rc!=SQLITE_OK ) return rc;
  60476. /* Do some checking to help insure the file we opened really is
  60477. ** a valid database file.
  60478. */
  60479. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  60480. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  60481. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  60482. nPage = nPageFile;
  60483. }
  60484. if( nPage>0 ){
  60485. u32 pageSize;
  60486. u32 usableSize;
  60487. u8 *page1 = pPage1->aData;
  60488. rc = SQLITE_NOTADB;
  60489. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  60490. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  60491. ** 61 74 20 33 00. */
  60492. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  60493. goto page1_init_failed;
  60494. }
  60495. #ifdef SQLITE_OMIT_WAL
  60496. if( page1[18]>1 ){
  60497. pBt->btsFlags |= BTS_READ_ONLY;
  60498. }
  60499. if( page1[19]>1 ){
  60500. goto page1_init_failed;
  60501. }
  60502. #else
  60503. if( page1[18]>2 ){
  60504. pBt->btsFlags |= BTS_READ_ONLY;
  60505. }
  60506. if( page1[19]>2 ){
  60507. goto page1_init_failed;
  60508. }
  60509. /* If the write version is set to 2, this database should be accessed
  60510. ** in WAL mode. If the log is not already open, open it now. Then
  60511. ** return SQLITE_OK and return without populating BtShared.pPage1.
  60512. ** The caller detects this and calls this function again. This is
  60513. ** required as the version of page 1 currently in the page1 buffer
  60514. ** may not be the latest version - there may be a newer one in the log
  60515. ** file.
  60516. */
  60517. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  60518. int isOpen = 0;
  60519. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  60520. if( rc!=SQLITE_OK ){
  60521. goto page1_init_failed;
  60522. }else{
  60523. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
  60524. if( isOpen==0 ){
  60525. releasePageOne(pPage1);
  60526. return SQLITE_OK;
  60527. }
  60528. }
  60529. rc = SQLITE_NOTADB;
  60530. }else{
  60531. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
  60532. }
  60533. #endif
  60534. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  60535. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  60536. **
  60537. ** The original design allowed these amounts to vary, but as of
  60538. ** version 3.6.0, we require them to be fixed.
  60539. */
  60540. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  60541. goto page1_init_failed;
  60542. }
  60543. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  60544. ** determined by the 2-byte integer located at an offset of 16 bytes from
  60545. ** the beginning of the database file. */
  60546. pageSize = (page1[16]<<8) | (page1[17]<<16);
  60547. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  60548. ** between 512 and 65536 inclusive. */
  60549. if( ((pageSize-1)&pageSize)!=0
  60550. || pageSize>SQLITE_MAX_PAGE_SIZE
  60551. || pageSize<=256
  60552. ){
  60553. goto page1_init_failed;
  60554. }
  60555. assert( (pageSize & 7)==0 );
  60556. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  60557. ** integer at offset 20 is the number of bytes of space at the end of
  60558. ** each page to reserve for extensions.
  60559. **
  60560. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  60561. ** determined by the one-byte unsigned integer found at an offset of 20
  60562. ** into the database file header. */
  60563. usableSize = pageSize - page1[20];
  60564. if( (u32)pageSize!=pBt->pageSize ){
  60565. /* After reading the first page of the database assuming a page size
  60566. ** of BtShared.pageSize, we have discovered that the page-size is
  60567. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  60568. ** zero and return SQLITE_OK. The caller will call this function
  60569. ** again with the correct page-size.
  60570. */
  60571. releasePageOne(pPage1);
  60572. pBt->usableSize = usableSize;
  60573. pBt->pageSize = pageSize;
  60574. freeTempSpace(pBt);
  60575. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  60576. pageSize-usableSize);
  60577. return rc;
  60578. }
  60579. if( (pBt->db->flags & SQLITE_WriteSchema)==0 && nPage>nPageFile ){
  60580. rc = SQLITE_CORRUPT_BKPT;
  60581. goto page1_init_failed;
  60582. }
  60583. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  60584. ** be less than 480. In other words, if the page size is 512, then the
  60585. ** reserved space size cannot exceed 32. */
  60586. if( usableSize<480 ){
  60587. goto page1_init_failed;
  60588. }
  60589. pBt->pageSize = pageSize;
  60590. pBt->usableSize = usableSize;
  60591. #ifndef SQLITE_OMIT_AUTOVACUUM
  60592. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  60593. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  60594. #endif
  60595. }
  60596. /* maxLocal is the maximum amount of payload to store locally for
  60597. ** a cell. Make sure it is small enough so that at least minFanout
  60598. ** cells can will fit on one page. We assume a 10-byte page header.
  60599. ** Besides the payload, the cell must store:
  60600. ** 2-byte pointer to the cell
  60601. ** 4-byte child pointer
  60602. ** 9-byte nKey value
  60603. ** 4-byte nData value
  60604. ** 4-byte overflow page pointer
  60605. ** So a cell consists of a 2-byte pointer, a header which is as much as
  60606. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  60607. ** page pointer.
  60608. */
  60609. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  60610. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  60611. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  60612. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  60613. if( pBt->maxLocal>127 ){
  60614. pBt->max1bytePayload = 127;
  60615. }else{
  60616. pBt->max1bytePayload = (u8)pBt->maxLocal;
  60617. }
  60618. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  60619. pBt->pPage1 = pPage1;
  60620. pBt->nPage = nPage;
  60621. return SQLITE_OK;
  60622. page1_init_failed:
  60623. releasePageOne(pPage1);
  60624. pBt->pPage1 = 0;
  60625. return rc;
  60626. }
  60627. #ifndef NDEBUG
  60628. /*
  60629. ** Return the number of cursors open on pBt. This is for use
  60630. ** in assert() expressions, so it is only compiled if NDEBUG is not
  60631. ** defined.
  60632. **
  60633. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  60634. ** false then all cursors are counted.
  60635. **
  60636. ** For the purposes of this routine, a cursor is any cursor that
  60637. ** is capable of reading or writing to the database. Cursors that
  60638. ** have been tripped into the CURSOR_FAULT state are not counted.
  60639. */
  60640. static int countValidCursors(BtShared *pBt, int wrOnly){
  60641. BtCursor *pCur;
  60642. int r = 0;
  60643. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  60644. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  60645. && pCur->eState!=CURSOR_FAULT ) r++;
  60646. }
  60647. return r;
  60648. }
  60649. #endif
  60650. /*
  60651. ** If there are no outstanding cursors and we are not in the middle
  60652. ** of a transaction but there is a read lock on the database, then
  60653. ** this routine unrefs the first page of the database file which
  60654. ** has the effect of releasing the read lock.
  60655. **
  60656. ** If there is a transaction in progress, this routine is a no-op.
  60657. */
  60658. static void unlockBtreeIfUnused(BtShared *pBt){
  60659. assert( sqlite3_mutex_held(pBt->mutex) );
  60660. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  60661. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  60662. MemPage *pPage1 = pBt->pPage1;
  60663. assert( pPage1->aData );
  60664. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  60665. pBt->pPage1 = 0;
  60666. releasePageOne(pPage1);
  60667. }
  60668. }
  60669. /*
  60670. ** If pBt points to an empty file then convert that empty file
  60671. ** into a new empty database by initializing the first page of
  60672. ** the database.
  60673. */
  60674. static int newDatabase(BtShared *pBt){
  60675. MemPage *pP1;
  60676. unsigned char *data;
  60677. int rc;
  60678. assert( sqlite3_mutex_held(pBt->mutex) );
  60679. if( pBt->nPage>0 ){
  60680. return SQLITE_OK;
  60681. }
  60682. pP1 = pBt->pPage1;
  60683. assert( pP1!=0 );
  60684. data = pP1->aData;
  60685. rc = sqlite3PagerWrite(pP1->pDbPage);
  60686. if( rc ) return rc;
  60687. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  60688. assert( sizeof(zMagicHeader)==16 );
  60689. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  60690. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  60691. data[18] = 1;
  60692. data[19] = 1;
  60693. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  60694. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  60695. data[21] = 64;
  60696. data[22] = 32;
  60697. data[23] = 32;
  60698. memset(&data[24], 0, 100-24);
  60699. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  60700. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  60701. #ifndef SQLITE_OMIT_AUTOVACUUM
  60702. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  60703. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  60704. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  60705. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  60706. #endif
  60707. pBt->nPage = 1;
  60708. data[31] = 1;
  60709. return SQLITE_OK;
  60710. }
  60711. /*
  60712. ** Initialize the first page of the database file (creating a database
  60713. ** consisting of a single page and no schema objects). Return SQLITE_OK
  60714. ** if successful, or an SQLite error code otherwise.
  60715. */
  60716. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  60717. int rc;
  60718. sqlite3BtreeEnter(p);
  60719. p->pBt->nPage = 0;
  60720. rc = newDatabase(p->pBt);
  60721. sqlite3BtreeLeave(p);
  60722. return rc;
  60723. }
  60724. /*
  60725. ** Attempt to start a new transaction. A write-transaction
  60726. ** is started if the second argument is nonzero, otherwise a read-
  60727. ** transaction. If the second argument is 2 or more and exclusive
  60728. ** transaction is started, meaning that no other process is allowed
  60729. ** to access the database. A preexisting transaction may not be
  60730. ** upgraded to exclusive by calling this routine a second time - the
  60731. ** exclusivity flag only works for a new transaction.
  60732. **
  60733. ** A write-transaction must be started before attempting any
  60734. ** changes to the database. None of the following routines
  60735. ** will work unless a transaction is started first:
  60736. **
  60737. ** sqlite3BtreeCreateTable()
  60738. ** sqlite3BtreeCreateIndex()
  60739. ** sqlite3BtreeClearTable()
  60740. ** sqlite3BtreeDropTable()
  60741. ** sqlite3BtreeInsert()
  60742. ** sqlite3BtreeDelete()
  60743. ** sqlite3BtreeUpdateMeta()
  60744. **
  60745. ** If an initial attempt to acquire the lock fails because of lock contention
  60746. ** and the database was previously unlocked, then invoke the busy handler
  60747. ** if there is one. But if there was previously a read-lock, do not
  60748. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  60749. ** returned when there is already a read-lock in order to avoid a deadlock.
  60750. **
  60751. ** Suppose there are two processes A and B. A has a read lock and B has
  60752. ** a reserved lock. B tries to promote to exclusive but is blocked because
  60753. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  60754. ** One or the other of the two processes must give way or there can be
  60755. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  60756. ** when A already has a read lock, we encourage A to give up and let B
  60757. ** proceed.
  60758. */
  60759. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  60760. BtShared *pBt = p->pBt;
  60761. int rc = SQLITE_OK;
  60762. sqlite3BtreeEnter(p);
  60763. btreeIntegrity(p);
  60764. /* If the btree is already in a write-transaction, or it
  60765. ** is already in a read-transaction and a read-transaction
  60766. ** is requested, this is a no-op.
  60767. */
  60768. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  60769. goto trans_begun;
  60770. }
  60771. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  60772. /* Write transactions are not possible on a read-only database */
  60773. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  60774. rc = SQLITE_READONLY;
  60775. goto trans_begun;
  60776. }
  60777. #ifndef SQLITE_OMIT_SHARED_CACHE
  60778. {
  60779. sqlite3 *pBlock = 0;
  60780. /* If another database handle has already opened a write transaction
  60781. ** on this shared-btree structure and a second write transaction is
  60782. ** requested, return SQLITE_LOCKED.
  60783. */
  60784. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  60785. || (pBt->btsFlags & BTS_PENDING)!=0
  60786. ){
  60787. pBlock = pBt->pWriter->db;
  60788. }else if( wrflag>1 ){
  60789. BtLock *pIter;
  60790. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  60791. if( pIter->pBtree!=p ){
  60792. pBlock = pIter->pBtree->db;
  60793. break;
  60794. }
  60795. }
  60796. }
  60797. if( pBlock ){
  60798. sqlite3ConnectionBlocked(p->db, pBlock);
  60799. rc = SQLITE_LOCKED_SHAREDCACHE;
  60800. goto trans_begun;
  60801. }
  60802. }
  60803. #endif
  60804. /* Any read-only or read-write transaction implies a read-lock on
  60805. ** page 1. So if some other shared-cache client already has a write-lock
  60806. ** on page 1, the transaction cannot be opened. */
  60807. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  60808. if( SQLITE_OK!=rc ) goto trans_begun;
  60809. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  60810. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  60811. do {
  60812. /* Call lockBtree() until either pBt->pPage1 is populated or
  60813. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  60814. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  60815. ** reading page 1 it discovers that the page-size of the database
  60816. ** file is not pBt->pageSize. In this case lockBtree() will update
  60817. ** pBt->pageSize to the page-size of the file on disk.
  60818. */
  60819. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  60820. if( rc==SQLITE_OK && wrflag ){
  60821. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  60822. rc = SQLITE_READONLY;
  60823. }else{
  60824. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  60825. if( rc==SQLITE_OK ){
  60826. rc = newDatabase(pBt);
  60827. }
  60828. }
  60829. }
  60830. if( rc!=SQLITE_OK ){
  60831. unlockBtreeIfUnused(pBt);
  60832. }
  60833. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  60834. btreeInvokeBusyHandler(pBt) );
  60835. sqlite3PagerResetLockTimeout(pBt->pPager);
  60836. if( rc==SQLITE_OK ){
  60837. if( p->inTrans==TRANS_NONE ){
  60838. pBt->nTransaction++;
  60839. #ifndef SQLITE_OMIT_SHARED_CACHE
  60840. if( p->sharable ){
  60841. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  60842. p->lock.eLock = READ_LOCK;
  60843. p->lock.pNext = pBt->pLock;
  60844. pBt->pLock = &p->lock;
  60845. }
  60846. #endif
  60847. }
  60848. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  60849. if( p->inTrans>pBt->inTransaction ){
  60850. pBt->inTransaction = p->inTrans;
  60851. }
  60852. if( wrflag ){
  60853. MemPage *pPage1 = pBt->pPage1;
  60854. #ifndef SQLITE_OMIT_SHARED_CACHE
  60855. assert( !pBt->pWriter );
  60856. pBt->pWriter = p;
  60857. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  60858. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  60859. #endif
  60860. /* If the db-size header field is incorrect (as it may be if an old
  60861. ** client has been writing the database file), update it now. Doing
  60862. ** this sooner rather than later means the database size can safely
  60863. ** re-read the database size from page 1 if a savepoint or transaction
  60864. ** rollback occurs within the transaction.
  60865. */
  60866. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  60867. rc = sqlite3PagerWrite(pPage1->pDbPage);
  60868. if( rc==SQLITE_OK ){
  60869. put4byte(&pPage1->aData[28], pBt->nPage);
  60870. }
  60871. }
  60872. }
  60873. }
  60874. trans_begun:
  60875. if( rc==SQLITE_OK && wrflag ){
  60876. /* This call makes sure that the pager has the correct number of
  60877. ** open savepoints. If the second parameter is greater than 0 and
  60878. ** the sub-journal is not already open, then it will be opened here.
  60879. */
  60880. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  60881. }
  60882. btreeIntegrity(p);
  60883. sqlite3BtreeLeave(p);
  60884. return rc;
  60885. }
  60886. #ifndef SQLITE_OMIT_AUTOVACUUM
  60887. /*
  60888. ** Set the pointer-map entries for all children of page pPage. Also, if
  60889. ** pPage contains cells that point to overflow pages, set the pointer
  60890. ** map entries for the overflow pages as well.
  60891. */
  60892. static int setChildPtrmaps(MemPage *pPage){
  60893. int i; /* Counter variable */
  60894. int nCell; /* Number of cells in page pPage */
  60895. int rc; /* Return code */
  60896. BtShared *pBt = pPage->pBt;
  60897. Pgno pgno = pPage->pgno;
  60898. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60899. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  60900. if( rc!=SQLITE_OK ) return rc;
  60901. nCell = pPage->nCell;
  60902. for(i=0; i<nCell; i++){
  60903. u8 *pCell = findCell(pPage, i);
  60904. ptrmapPutOvflPtr(pPage, pCell, &rc);
  60905. if( !pPage->leaf ){
  60906. Pgno childPgno = get4byte(pCell);
  60907. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  60908. }
  60909. }
  60910. if( !pPage->leaf ){
  60911. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  60912. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  60913. }
  60914. return rc;
  60915. }
  60916. /*
  60917. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  60918. ** that it points to iTo. Parameter eType describes the type of pointer to
  60919. ** be modified, as follows:
  60920. **
  60921. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  60922. ** page of pPage.
  60923. **
  60924. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  60925. ** page pointed to by one of the cells on pPage.
  60926. **
  60927. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  60928. ** overflow page in the list.
  60929. */
  60930. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  60931. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  60932. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  60933. if( eType==PTRMAP_OVERFLOW2 ){
  60934. /* The pointer is always the first 4 bytes of the page in this case. */
  60935. if( get4byte(pPage->aData)!=iFrom ){
  60936. return SQLITE_CORRUPT_PAGE(pPage);
  60937. }
  60938. put4byte(pPage->aData, iTo);
  60939. }else{
  60940. int i;
  60941. int nCell;
  60942. int rc;
  60943. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  60944. if( rc ) return rc;
  60945. nCell = pPage->nCell;
  60946. for(i=0; i<nCell; i++){
  60947. u8 *pCell = findCell(pPage, i);
  60948. if( eType==PTRMAP_OVERFLOW1 ){
  60949. CellInfo info;
  60950. pPage->xParseCell(pPage, pCell, &info);
  60951. if( info.nLocal<info.nPayload ){
  60952. if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
  60953. return SQLITE_CORRUPT_PAGE(pPage);
  60954. }
  60955. if( iFrom==get4byte(pCell+info.nSize-4) ){
  60956. put4byte(pCell+info.nSize-4, iTo);
  60957. break;
  60958. }
  60959. }
  60960. }else{
  60961. if( get4byte(pCell)==iFrom ){
  60962. put4byte(pCell, iTo);
  60963. break;
  60964. }
  60965. }
  60966. }
  60967. if( i==nCell ){
  60968. if( eType!=PTRMAP_BTREE ||
  60969. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  60970. return SQLITE_CORRUPT_PAGE(pPage);
  60971. }
  60972. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  60973. }
  60974. }
  60975. return SQLITE_OK;
  60976. }
  60977. /*
  60978. ** Move the open database page pDbPage to location iFreePage in the
  60979. ** database. The pDbPage reference remains valid.
  60980. **
  60981. ** The isCommit flag indicates that there is no need to remember that
  60982. ** the journal needs to be sync()ed before database page pDbPage->pgno
  60983. ** can be written to. The caller has already promised not to write to that
  60984. ** page.
  60985. */
  60986. static int relocatePage(
  60987. BtShared *pBt, /* Btree */
  60988. MemPage *pDbPage, /* Open page to move */
  60989. u8 eType, /* Pointer map 'type' entry for pDbPage */
  60990. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  60991. Pgno iFreePage, /* The location to move pDbPage to */
  60992. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  60993. ){
  60994. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  60995. Pgno iDbPage = pDbPage->pgno;
  60996. Pager *pPager = pBt->pPager;
  60997. int rc;
  60998. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  60999. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  61000. assert( sqlite3_mutex_held(pBt->mutex) );
  61001. assert( pDbPage->pBt==pBt );
  61002. /* Move page iDbPage from its current location to page number iFreePage */
  61003. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  61004. iDbPage, iFreePage, iPtrPage, eType));
  61005. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  61006. if( rc!=SQLITE_OK ){
  61007. return rc;
  61008. }
  61009. pDbPage->pgno = iFreePage;
  61010. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  61011. ** that point to overflow pages. The pointer map entries for all these
  61012. ** pages need to be changed.
  61013. **
  61014. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  61015. ** pointer to a subsequent overflow page. If this is the case, then
  61016. ** the pointer map needs to be updated for the subsequent overflow page.
  61017. */
  61018. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  61019. rc = setChildPtrmaps(pDbPage);
  61020. if( rc!=SQLITE_OK ){
  61021. return rc;
  61022. }
  61023. }else{
  61024. Pgno nextOvfl = get4byte(pDbPage->aData);
  61025. if( nextOvfl!=0 ){
  61026. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  61027. if( rc!=SQLITE_OK ){
  61028. return rc;
  61029. }
  61030. }
  61031. }
  61032. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  61033. ** that it points at iFreePage. Also fix the pointer map entry for
  61034. ** iPtrPage.
  61035. */
  61036. if( eType!=PTRMAP_ROOTPAGE ){
  61037. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  61038. if( rc!=SQLITE_OK ){
  61039. return rc;
  61040. }
  61041. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  61042. if( rc!=SQLITE_OK ){
  61043. releasePage(pPtrPage);
  61044. return rc;
  61045. }
  61046. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  61047. releasePage(pPtrPage);
  61048. if( rc==SQLITE_OK ){
  61049. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  61050. }
  61051. }
  61052. return rc;
  61053. }
  61054. /* Forward declaration required by incrVacuumStep(). */
  61055. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  61056. /*
  61057. ** Perform a single step of an incremental-vacuum. If successful, return
  61058. ** SQLITE_OK. If there is no work to do (and therefore no point in
  61059. ** calling this function again), return SQLITE_DONE. Or, if an error
  61060. ** occurs, return some other error code.
  61061. **
  61062. ** More specifically, this function attempts to re-organize the database so
  61063. ** that the last page of the file currently in use is no longer in use.
  61064. **
  61065. ** Parameter nFin is the number of pages that this database would contain
  61066. ** were this function called until it returns SQLITE_DONE.
  61067. **
  61068. ** If the bCommit parameter is non-zero, this function assumes that the
  61069. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  61070. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  61071. ** operation, or false for an incremental vacuum.
  61072. */
  61073. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  61074. Pgno nFreeList; /* Number of pages still on the free-list */
  61075. int rc;
  61076. assert( sqlite3_mutex_held(pBt->mutex) );
  61077. assert( iLastPg>nFin );
  61078. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  61079. u8 eType;
  61080. Pgno iPtrPage;
  61081. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  61082. if( nFreeList==0 ){
  61083. return SQLITE_DONE;
  61084. }
  61085. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  61086. if( rc!=SQLITE_OK ){
  61087. return rc;
  61088. }
  61089. if( eType==PTRMAP_ROOTPAGE ){
  61090. return SQLITE_CORRUPT_BKPT;
  61091. }
  61092. if( eType==PTRMAP_FREEPAGE ){
  61093. if( bCommit==0 ){
  61094. /* Remove the page from the files free-list. This is not required
  61095. ** if bCommit is non-zero. In that case, the free-list will be
  61096. ** truncated to zero after this function returns, so it doesn't
  61097. ** matter if it still contains some garbage entries.
  61098. */
  61099. Pgno iFreePg;
  61100. MemPage *pFreePg;
  61101. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  61102. if( rc!=SQLITE_OK ){
  61103. return rc;
  61104. }
  61105. assert( iFreePg==iLastPg );
  61106. releasePage(pFreePg);
  61107. }
  61108. } else {
  61109. Pgno iFreePg; /* Index of free page to move pLastPg to */
  61110. MemPage *pLastPg;
  61111. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  61112. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  61113. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  61114. if( rc!=SQLITE_OK ){
  61115. return rc;
  61116. }
  61117. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  61118. ** is swapped with the first free page pulled off the free list.
  61119. **
  61120. ** On the other hand, if bCommit is greater than zero, then keep
  61121. ** looping until a free-page located within the first nFin pages
  61122. ** of the file is found.
  61123. */
  61124. if( bCommit==0 ){
  61125. eMode = BTALLOC_LE;
  61126. iNear = nFin;
  61127. }
  61128. do {
  61129. MemPage *pFreePg;
  61130. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  61131. if( rc!=SQLITE_OK ){
  61132. releasePage(pLastPg);
  61133. return rc;
  61134. }
  61135. releasePage(pFreePg);
  61136. }while( bCommit && iFreePg>nFin );
  61137. assert( iFreePg<iLastPg );
  61138. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  61139. releasePage(pLastPg);
  61140. if( rc!=SQLITE_OK ){
  61141. return rc;
  61142. }
  61143. }
  61144. }
  61145. if( bCommit==0 ){
  61146. do {
  61147. iLastPg--;
  61148. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  61149. pBt->bDoTruncate = 1;
  61150. pBt->nPage = iLastPg;
  61151. }
  61152. return SQLITE_OK;
  61153. }
  61154. /*
  61155. ** The database opened by the first argument is an auto-vacuum database
  61156. ** nOrig pages in size containing nFree free pages. Return the expected
  61157. ** size of the database in pages following an auto-vacuum operation.
  61158. */
  61159. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  61160. int nEntry; /* Number of entries on one ptrmap page */
  61161. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  61162. Pgno nFin; /* Return value */
  61163. nEntry = pBt->usableSize/5;
  61164. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  61165. nFin = nOrig - nFree - nPtrmap;
  61166. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  61167. nFin--;
  61168. }
  61169. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  61170. nFin--;
  61171. }
  61172. return nFin;
  61173. }
  61174. /*
  61175. ** A write-transaction must be opened before calling this function.
  61176. ** It performs a single unit of work towards an incremental vacuum.
  61177. **
  61178. ** If the incremental vacuum is finished after this function has run,
  61179. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  61180. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  61181. */
  61182. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  61183. int rc;
  61184. BtShared *pBt = p->pBt;
  61185. sqlite3BtreeEnter(p);
  61186. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  61187. if( !pBt->autoVacuum ){
  61188. rc = SQLITE_DONE;
  61189. }else{
  61190. Pgno nOrig = btreePagecount(pBt);
  61191. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  61192. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  61193. if( nOrig<nFin ){
  61194. rc = SQLITE_CORRUPT_BKPT;
  61195. }else if( nFree>0 ){
  61196. rc = saveAllCursors(pBt, 0, 0);
  61197. if( rc==SQLITE_OK ){
  61198. invalidateAllOverflowCache(pBt);
  61199. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  61200. }
  61201. if( rc==SQLITE_OK ){
  61202. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  61203. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  61204. }
  61205. }else{
  61206. rc = SQLITE_DONE;
  61207. }
  61208. }
  61209. sqlite3BtreeLeave(p);
  61210. return rc;
  61211. }
  61212. /*
  61213. ** This routine is called prior to sqlite3PagerCommit when a transaction
  61214. ** is committed for an auto-vacuum database.
  61215. **
  61216. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  61217. ** the database file should be truncated to during the commit process.
  61218. ** i.e. the database has been reorganized so that only the first *pnTrunc
  61219. ** pages are in use.
  61220. */
  61221. static int autoVacuumCommit(BtShared *pBt){
  61222. int rc = SQLITE_OK;
  61223. Pager *pPager = pBt->pPager;
  61224. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  61225. assert( sqlite3_mutex_held(pBt->mutex) );
  61226. invalidateAllOverflowCache(pBt);
  61227. assert(pBt->autoVacuum);
  61228. if( !pBt->incrVacuum ){
  61229. Pgno nFin; /* Number of pages in database after autovacuuming */
  61230. Pgno nFree; /* Number of pages on the freelist initially */
  61231. Pgno iFree; /* The next page to be freed */
  61232. Pgno nOrig; /* Database size before freeing */
  61233. nOrig = btreePagecount(pBt);
  61234. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  61235. /* It is not possible to create a database for which the final page
  61236. ** is either a pointer-map page or the pending-byte page. If one
  61237. ** is encountered, this indicates corruption.
  61238. */
  61239. return SQLITE_CORRUPT_BKPT;
  61240. }
  61241. nFree = get4byte(&pBt->pPage1->aData[36]);
  61242. nFin = finalDbSize(pBt, nOrig, nFree);
  61243. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  61244. if( nFin<nOrig ){
  61245. rc = saveAllCursors(pBt, 0, 0);
  61246. }
  61247. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  61248. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  61249. }
  61250. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  61251. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  61252. put4byte(&pBt->pPage1->aData[32], 0);
  61253. put4byte(&pBt->pPage1->aData[36], 0);
  61254. put4byte(&pBt->pPage1->aData[28], nFin);
  61255. pBt->bDoTruncate = 1;
  61256. pBt->nPage = nFin;
  61257. }
  61258. if( rc!=SQLITE_OK ){
  61259. sqlite3PagerRollback(pPager);
  61260. }
  61261. }
  61262. assert( nRef>=sqlite3PagerRefcount(pPager) );
  61263. return rc;
  61264. }
  61265. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  61266. # define setChildPtrmaps(x) SQLITE_OK
  61267. #endif
  61268. /*
  61269. ** This routine does the first phase of a two-phase commit. This routine
  61270. ** causes a rollback journal to be created (if it does not already exist)
  61271. ** and populated with enough information so that if a power loss occurs
  61272. ** the database can be restored to its original state by playing back
  61273. ** the journal. Then the contents of the journal are flushed out to
  61274. ** the disk. After the journal is safely on oxide, the changes to the
  61275. ** database are written into the database file and flushed to oxide.
  61276. ** At the end of this call, the rollback journal still exists on the
  61277. ** disk and we are still holding all locks, so the transaction has not
  61278. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  61279. ** commit process.
  61280. **
  61281. ** This call is a no-op if no write-transaction is currently active on pBt.
  61282. **
  61283. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  61284. ** the name of a master journal file that should be written into the
  61285. ** individual journal file, or is NULL, indicating no master journal file
  61286. ** (single database transaction).
  61287. **
  61288. ** When this is called, the master journal should already have been
  61289. ** created, populated with this journal pointer and synced to disk.
  61290. **
  61291. ** Once this is routine has returned, the only thing required to commit
  61292. ** the write-transaction for this database file is to delete the journal.
  61293. */
  61294. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  61295. int rc = SQLITE_OK;
  61296. if( p->inTrans==TRANS_WRITE ){
  61297. BtShared *pBt = p->pBt;
  61298. sqlite3BtreeEnter(p);
  61299. #ifndef SQLITE_OMIT_AUTOVACUUM
  61300. if( pBt->autoVacuum ){
  61301. rc = autoVacuumCommit(pBt);
  61302. if( rc!=SQLITE_OK ){
  61303. sqlite3BtreeLeave(p);
  61304. return rc;
  61305. }
  61306. }
  61307. if( pBt->bDoTruncate ){
  61308. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  61309. }
  61310. #endif
  61311. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  61312. sqlite3BtreeLeave(p);
  61313. }
  61314. return rc;
  61315. }
  61316. /*
  61317. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  61318. ** at the conclusion of a transaction.
  61319. */
  61320. static void btreeEndTransaction(Btree *p){
  61321. BtShared *pBt = p->pBt;
  61322. sqlite3 *db = p->db;
  61323. assert( sqlite3BtreeHoldsMutex(p) );
  61324. #ifndef SQLITE_OMIT_AUTOVACUUM
  61325. pBt->bDoTruncate = 0;
  61326. #endif
  61327. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  61328. /* If there are other active statements that belong to this database
  61329. ** handle, downgrade to a read-only transaction. The other statements
  61330. ** may still be reading from the database. */
  61331. downgradeAllSharedCacheTableLocks(p);
  61332. p->inTrans = TRANS_READ;
  61333. }else{
  61334. /* If the handle had any kind of transaction open, decrement the
  61335. ** transaction count of the shared btree. If the transaction count
  61336. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  61337. ** call below will unlock the pager. */
  61338. if( p->inTrans!=TRANS_NONE ){
  61339. clearAllSharedCacheTableLocks(p);
  61340. pBt->nTransaction--;
  61341. if( 0==pBt->nTransaction ){
  61342. pBt->inTransaction = TRANS_NONE;
  61343. }
  61344. }
  61345. /* Set the current transaction state to TRANS_NONE and unlock the
  61346. ** pager if this call closed the only read or write transaction. */
  61347. p->inTrans = TRANS_NONE;
  61348. unlockBtreeIfUnused(pBt);
  61349. }
  61350. btreeIntegrity(p);
  61351. }
  61352. /*
  61353. ** Commit the transaction currently in progress.
  61354. **
  61355. ** This routine implements the second phase of a 2-phase commit. The
  61356. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  61357. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  61358. ** routine did all the work of writing information out to disk and flushing the
  61359. ** contents so that they are written onto the disk platter. All this
  61360. ** routine has to do is delete or truncate or zero the header in the
  61361. ** the rollback journal (which causes the transaction to commit) and
  61362. ** drop locks.
  61363. **
  61364. ** Normally, if an error occurs while the pager layer is attempting to
  61365. ** finalize the underlying journal file, this function returns an error and
  61366. ** the upper layer will attempt a rollback. However, if the second argument
  61367. ** is non-zero then this b-tree transaction is part of a multi-file
  61368. ** transaction. In this case, the transaction has already been committed
  61369. ** (by deleting a master journal file) and the caller will ignore this
  61370. ** functions return code. So, even if an error occurs in the pager layer,
  61371. ** reset the b-tree objects internal state to indicate that the write
  61372. ** transaction has been closed. This is quite safe, as the pager will have
  61373. ** transitioned to the error state.
  61374. **
  61375. ** This will release the write lock on the database file. If there
  61376. ** are no active cursors, it also releases the read lock.
  61377. */
  61378. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  61379. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  61380. sqlite3BtreeEnter(p);
  61381. btreeIntegrity(p);
  61382. /* If the handle has a write-transaction open, commit the shared-btrees
  61383. ** transaction and set the shared state to TRANS_READ.
  61384. */
  61385. if( p->inTrans==TRANS_WRITE ){
  61386. int rc;
  61387. BtShared *pBt = p->pBt;
  61388. assert( pBt->inTransaction==TRANS_WRITE );
  61389. assert( pBt->nTransaction>0 );
  61390. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  61391. if( rc!=SQLITE_OK && bCleanup==0 ){
  61392. sqlite3BtreeLeave(p);
  61393. return rc;
  61394. }
  61395. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  61396. pBt->inTransaction = TRANS_READ;
  61397. btreeClearHasContent(pBt);
  61398. }
  61399. btreeEndTransaction(p);
  61400. sqlite3BtreeLeave(p);
  61401. return SQLITE_OK;
  61402. }
  61403. /*
  61404. ** Do both phases of a commit.
  61405. */
  61406. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  61407. int rc;
  61408. sqlite3BtreeEnter(p);
  61409. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  61410. if( rc==SQLITE_OK ){
  61411. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  61412. }
  61413. sqlite3BtreeLeave(p);
  61414. return rc;
  61415. }
  61416. /*
  61417. ** This routine sets the state to CURSOR_FAULT and the error
  61418. ** code to errCode for every cursor on any BtShared that pBtree
  61419. ** references. Or if the writeOnly flag is set to 1, then only
  61420. ** trip write cursors and leave read cursors unchanged.
  61421. **
  61422. ** Every cursor is a candidate to be tripped, including cursors
  61423. ** that belong to other database connections that happen to be
  61424. ** sharing the cache with pBtree.
  61425. **
  61426. ** This routine gets called when a rollback occurs. If the writeOnly
  61427. ** flag is true, then only write-cursors need be tripped - read-only
  61428. ** cursors save their current positions so that they may continue
  61429. ** following the rollback. Or, if writeOnly is false, all cursors are
  61430. ** tripped. In general, writeOnly is false if the transaction being
  61431. ** rolled back modified the database schema. In this case b-tree root
  61432. ** pages may be moved or deleted from the database altogether, making
  61433. ** it unsafe for read cursors to continue.
  61434. **
  61435. ** If the writeOnly flag is true and an error is encountered while
  61436. ** saving the current position of a read-only cursor, all cursors,
  61437. ** including all read-cursors are tripped.
  61438. **
  61439. ** SQLITE_OK is returned if successful, or if an error occurs while
  61440. ** saving a cursor position, an SQLite error code.
  61441. */
  61442. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  61443. BtCursor *p;
  61444. int rc = SQLITE_OK;
  61445. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  61446. if( pBtree ){
  61447. sqlite3BtreeEnter(pBtree);
  61448. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  61449. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  61450. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  61451. rc = saveCursorPosition(p);
  61452. if( rc!=SQLITE_OK ){
  61453. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  61454. break;
  61455. }
  61456. }
  61457. }else{
  61458. sqlite3BtreeClearCursor(p);
  61459. p->eState = CURSOR_FAULT;
  61460. p->skipNext = errCode;
  61461. }
  61462. btreeReleaseAllCursorPages(p);
  61463. }
  61464. sqlite3BtreeLeave(pBtree);
  61465. }
  61466. return rc;
  61467. }
  61468. /*
  61469. ** Rollback the transaction in progress.
  61470. **
  61471. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  61472. ** Only write cursors are tripped if writeOnly is true but all cursors are
  61473. ** tripped if writeOnly is false. Any attempt to use
  61474. ** a tripped cursor will result in an error.
  61475. **
  61476. ** This will release the write lock on the database file. If there
  61477. ** are no active cursors, it also releases the read lock.
  61478. */
  61479. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  61480. int rc;
  61481. BtShared *pBt = p->pBt;
  61482. MemPage *pPage1;
  61483. assert( writeOnly==1 || writeOnly==0 );
  61484. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  61485. sqlite3BtreeEnter(p);
  61486. if( tripCode==SQLITE_OK ){
  61487. rc = tripCode = saveAllCursors(pBt, 0, 0);
  61488. if( rc ) writeOnly = 0;
  61489. }else{
  61490. rc = SQLITE_OK;
  61491. }
  61492. if( tripCode ){
  61493. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  61494. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  61495. if( rc2!=SQLITE_OK ) rc = rc2;
  61496. }
  61497. btreeIntegrity(p);
  61498. if( p->inTrans==TRANS_WRITE ){
  61499. int rc2;
  61500. assert( TRANS_WRITE==pBt->inTransaction );
  61501. rc2 = sqlite3PagerRollback(pBt->pPager);
  61502. if( rc2!=SQLITE_OK ){
  61503. rc = rc2;
  61504. }
  61505. /* The rollback may have destroyed the pPage1->aData value. So
  61506. ** call btreeGetPage() on page 1 again to make
  61507. ** sure pPage1->aData is set correctly. */
  61508. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  61509. int nPage = get4byte(28+(u8*)pPage1->aData);
  61510. testcase( nPage==0 );
  61511. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  61512. testcase( pBt->nPage!=nPage );
  61513. pBt->nPage = nPage;
  61514. releasePageOne(pPage1);
  61515. }
  61516. assert( countValidCursors(pBt, 1)==0 );
  61517. pBt->inTransaction = TRANS_READ;
  61518. btreeClearHasContent(pBt);
  61519. }
  61520. btreeEndTransaction(p);
  61521. sqlite3BtreeLeave(p);
  61522. return rc;
  61523. }
  61524. /*
  61525. ** Start a statement subtransaction. The subtransaction can be rolled
  61526. ** back independently of the main transaction. You must start a transaction
  61527. ** before starting a subtransaction. The subtransaction is ended automatically
  61528. ** if the main transaction commits or rolls back.
  61529. **
  61530. ** Statement subtransactions are used around individual SQL statements
  61531. ** that are contained within a BEGIN...COMMIT block. If a constraint
  61532. ** error occurs within the statement, the effect of that one statement
  61533. ** can be rolled back without having to rollback the entire transaction.
  61534. **
  61535. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  61536. ** value passed as the second parameter is the total number of savepoints,
  61537. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  61538. ** are no active savepoints and no other statement-transactions open,
  61539. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  61540. ** using the sqlite3BtreeSavepoint() function.
  61541. */
  61542. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  61543. int rc;
  61544. BtShared *pBt = p->pBt;
  61545. sqlite3BtreeEnter(p);
  61546. assert( p->inTrans==TRANS_WRITE );
  61547. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  61548. assert( iStatement>0 );
  61549. assert( iStatement>p->db->nSavepoint );
  61550. assert( pBt->inTransaction==TRANS_WRITE );
  61551. /* At the pager level, a statement transaction is a savepoint with
  61552. ** an index greater than all savepoints created explicitly using
  61553. ** SQL statements. It is illegal to open, release or rollback any
  61554. ** such savepoints while the statement transaction savepoint is active.
  61555. */
  61556. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  61557. sqlite3BtreeLeave(p);
  61558. return rc;
  61559. }
  61560. /*
  61561. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  61562. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  61563. ** savepoint identified by parameter iSavepoint, depending on the value
  61564. ** of op.
  61565. **
  61566. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  61567. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  61568. ** contents of the entire transaction are rolled back. This is different
  61569. ** from a normal transaction rollback, as no locks are released and the
  61570. ** transaction remains open.
  61571. */
  61572. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  61573. int rc = SQLITE_OK;
  61574. if( p && p->inTrans==TRANS_WRITE ){
  61575. BtShared *pBt = p->pBt;
  61576. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  61577. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  61578. sqlite3BtreeEnter(p);
  61579. if( op==SAVEPOINT_ROLLBACK ){
  61580. rc = saveAllCursors(pBt, 0, 0);
  61581. }
  61582. if( rc==SQLITE_OK ){
  61583. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  61584. }
  61585. if( rc==SQLITE_OK ){
  61586. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  61587. pBt->nPage = 0;
  61588. }
  61589. rc = newDatabase(pBt);
  61590. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  61591. /* The database size was written into the offset 28 of the header
  61592. ** when the transaction started, so we know that the value at offset
  61593. ** 28 is nonzero. */
  61594. assert( pBt->nPage>0 );
  61595. }
  61596. sqlite3BtreeLeave(p);
  61597. }
  61598. return rc;
  61599. }
  61600. /*
  61601. ** Create a new cursor for the BTree whose root is on the page
  61602. ** iTable. If a read-only cursor is requested, it is assumed that
  61603. ** the caller already has at least a read-only transaction open
  61604. ** on the database already. If a write-cursor is requested, then
  61605. ** the caller is assumed to have an open write transaction.
  61606. **
  61607. ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
  61608. ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
  61609. ** can be used for reading or for writing if other conditions for writing
  61610. ** are also met. These are the conditions that must be met in order
  61611. ** for writing to be allowed:
  61612. **
  61613. ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
  61614. **
  61615. ** 2: Other database connections that share the same pager cache
  61616. ** but which are not in the READ_UNCOMMITTED state may not have
  61617. ** cursors open with wrFlag==0 on the same table. Otherwise
  61618. ** the changes made by this write cursor would be visible to
  61619. ** the read cursors in the other database connection.
  61620. **
  61621. ** 3: The database must be writable (not on read-only media)
  61622. **
  61623. ** 4: There must be an active transaction.
  61624. **
  61625. ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
  61626. ** is set. If FORDELETE is set, that is a hint to the implementation that
  61627. ** this cursor will only be used to seek to and delete entries of an index
  61628. ** as part of a larger DELETE statement. The FORDELETE hint is not used by
  61629. ** this implementation. But in a hypothetical alternative storage engine
  61630. ** in which index entries are automatically deleted when corresponding table
  61631. ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
  61632. ** operations on this cursor can be no-ops and all READ operations can
  61633. ** return a null row (2-bytes: 0x01 0x00).
  61634. **
  61635. ** No checking is done to make sure that page iTable really is the
  61636. ** root page of a b-tree. If it is not, then the cursor acquired
  61637. ** will not work correctly.
  61638. **
  61639. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  61640. ** on pCur to initialize the memory space prior to invoking this routine.
  61641. */
  61642. static int btreeCursor(
  61643. Btree *p, /* The btree */
  61644. int iTable, /* Root page of table to open */
  61645. int wrFlag, /* 1 to write. 0 read-only */
  61646. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  61647. BtCursor *pCur /* Space for new cursor */
  61648. ){
  61649. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  61650. BtCursor *pX; /* Looping over other all cursors */
  61651. assert( sqlite3BtreeHoldsMutex(p) );
  61652. assert( wrFlag==0
  61653. || wrFlag==BTREE_WRCSR
  61654. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  61655. );
  61656. /* The following assert statements verify that if this is a sharable
  61657. ** b-tree database, the connection is holding the required table locks,
  61658. ** and that no other connection has any open cursor that conflicts with
  61659. ** this lock. */
  61660. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
  61661. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  61662. /* Assert that the caller has opened the required transaction. */
  61663. assert( p->inTrans>TRANS_NONE );
  61664. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  61665. assert( pBt->pPage1 && pBt->pPage1->aData );
  61666. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  61667. if( wrFlag ){
  61668. allocateTempSpace(pBt);
  61669. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
  61670. }
  61671. if( iTable==1 && btreePagecount(pBt)==0 ){
  61672. assert( wrFlag==0 );
  61673. iTable = 0;
  61674. }
  61675. /* Now that no other errors can occur, finish filling in the BtCursor
  61676. ** variables and link the cursor into the BtShared list. */
  61677. pCur->pgnoRoot = (Pgno)iTable;
  61678. pCur->iPage = -1;
  61679. pCur->pKeyInfo = pKeyInfo;
  61680. pCur->pBtree = p;
  61681. pCur->pBt = pBt;
  61682. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  61683. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  61684. /* If there are two or more cursors on the same btree, then all such
  61685. ** cursors *must* have the BTCF_Multiple flag set. */
  61686. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  61687. if( pX->pgnoRoot==(Pgno)iTable ){
  61688. pX->curFlags |= BTCF_Multiple;
  61689. pCur->curFlags |= BTCF_Multiple;
  61690. }
  61691. }
  61692. pCur->pNext = pBt->pCursor;
  61693. pBt->pCursor = pCur;
  61694. pCur->eState = CURSOR_INVALID;
  61695. return SQLITE_OK;
  61696. }
  61697. SQLITE_PRIVATE int sqlite3BtreeCursor(
  61698. Btree *p, /* The btree */
  61699. int iTable, /* Root page of table to open */
  61700. int wrFlag, /* 1 to write. 0 read-only */
  61701. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  61702. BtCursor *pCur /* Write new cursor here */
  61703. ){
  61704. int rc;
  61705. if( iTable<1 ){
  61706. rc = SQLITE_CORRUPT_BKPT;
  61707. }else{
  61708. sqlite3BtreeEnter(p);
  61709. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  61710. sqlite3BtreeLeave(p);
  61711. }
  61712. return rc;
  61713. }
  61714. /*
  61715. ** Return the size of a BtCursor object in bytes.
  61716. **
  61717. ** This interfaces is needed so that users of cursors can preallocate
  61718. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  61719. ** to users so they cannot do the sizeof() themselves - they must call
  61720. ** this routine.
  61721. */
  61722. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  61723. return ROUND8(sizeof(BtCursor));
  61724. }
  61725. /*
  61726. ** Initialize memory that will be converted into a BtCursor object.
  61727. **
  61728. ** The simple approach here would be to memset() the entire object
  61729. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  61730. ** do not need to be zeroed and they are large, so we can save a lot
  61731. ** of run-time by skipping the initialization of those elements.
  61732. */
  61733. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  61734. memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
  61735. }
  61736. /*
  61737. ** Close a cursor. The read lock on the database file is released
  61738. ** when the last cursor is closed.
  61739. */
  61740. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  61741. Btree *pBtree = pCur->pBtree;
  61742. if( pBtree ){
  61743. BtShared *pBt = pCur->pBt;
  61744. sqlite3BtreeEnter(pBtree);
  61745. assert( pBt->pCursor!=0 );
  61746. if( pBt->pCursor==pCur ){
  61747. pBt->pCursor = pCur->pNext;
  61748. }else{
  61749. BtCursor *pPrev = pBt->pCursor;
  61750. do{
  61751. if( pPrev->pNext==pCur ){
  61752. pPrev->pNext = pCur->pNext;
  61753. break;
  61754. }
  61755. pPrev = pPrev->pNext;
  61756. }while( ALWAYS(pPrev) );
  61757. }
  61758. btreeReleaseAllCursorPages(pCur);
  61759. unlockBtreeIfUnused(pBt);
  61760. sqlite3_free(pCur->aOverflow);
  61761. sqlite3_free(pCur->pKey);
  61762. sqlite3BtreeLeave(pBtree);
  61763. }
  61764. return SQLITE_OK;
  61765. }
  61766. /*
  61767. ** Make sure the BtCursor* given in the argument has a valid
  61768. ** BtCursor.info structure. If it is not already valid, call
  61769. ** btreeParseCell() to fill it in.
  61770. **
  61771. ** BtCursor.info is a cache of the information in the current cell.
  61772. ** Using this cache reduces the number of calls to btreeParseCell().
  61773. */
  61774. #ifndef NDEBUG
  61775. static int cellInfoEqual(CellInfo *a, CellInfo *b){
  61776. if( a->nKey!=b->nKey ) return 0;
  61777. if( a->pPayload!=b->pPayload ) return 0;
  61778. if( a->nPayload!=b->nPayload ) return 0;
  61779. if( a->nLocal!=b->nLocal ) return 0;
  61780. if( a->nSize!=b->nSize ) return 0;
  61781. return 1;
  61782. }
  61783. static void assertCellInfo(BtCursor *pCur){
  61784. CellInfo info;
  61785. memset(&info, 0, sizeof(info));
  61786. btreeParseCell(pCur->pPage, pCur->ix, &info);
  61787. assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
  61788. }
  61789. #else
  61790. #define assertCellInfo(x)
  61791. #endif
  61792. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  61793. if( pCur->info.nSize==0 ){
  61794. pCur->curFlags |= BTCF_ValidNKey;
  61795. btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
  61796. }else{
  61797. assertCellInfo(pCur);
  61798. }
  61799. }
  61800. #ifndef NDEBUG /* The next routine used only within assert() statements */
  61801. /*
  61802. ** Return true if the given BtCursor is valid. A valid cursor is one
  61803. ** that is currently pointing to a row in a (non-empty) table.
  61804. ** This is a verification routine is used only within assert() statements.
  61805. */
  61806. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  61807. return pCur && pCur->eState==CURSOR_VALID;
  61808. }
  61809. #endif /* NDEBUG */
  61810. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
  61811. assert( pCur!=0 );
  61812. return pCur->eState==CURSOR_VALID;
  61813. }
  61814. /*
  61815. ** Return the value of the integer key or "rowid" for a table btree.
  61816. ** This routine is only valid for a cursor that is pointing into a
  61817. ** ordinary table btree. If the cursor points to an index btree or
  61818. ** is invalid, the result of this routine is undefined.
  61819. */
  61820. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
  61821. assert( cursorHoldsMutex(pCur) );
  61822. assert( pCur->eState==CURSOR_VALID );
  61823. assert( pCur->curIntKey );
  61824. getCellInfo(pCur);
  61825. return pCur->info.nKey;
  61826. }
  61827. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  61828. /*
  61829. ** Return the offset into the database file for the start of the
  61830. ** payload to which the cursor is pointing.
  61831. */
  61832. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){
  61833. assert( cursorHoldsMutex(pCur) );
  61834. assert( pCur->eState==CURSOR_VALID );
  61835. getCellInfo(pCur);
  61836. return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
  61837. (i64)(pCur->info.pPayload - pCur->pPage->aData);
  61838. }
  61839. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  61840. /*
  61841. ** Return the number of bytes of payload for the entry that pCur is
  61842. ** currently pointing to. For table btrees, this will be the amount
  61843. ** of data. For index btrees, this will be the size of the key.
  61844. **
  61845. ** The caller must guarantee that the cursor is pointing to a non-NULL
  61846. ** valid entry. In other words, the calling procedure must guarantee
  61847. ** that the cursor has Cursor.eState==CURSOR_VALID.
  61848. */
  61849. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
  61850. assert( cursorHoldsMutex(pCur) );
  61851. assert( pCur->eState==CURSOR_VALID );
  61852. getCellInfo(pCur);
  61853. return pCur->info.nPayload;
  61854. }
  61855. /*
  61856. ** Given the page number of an overflow page in the database (parameter
  61857. ** ovfl), this function finds the page number of the next page in the
  61858. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  61859. ** pointer-map data instead of reading the content of page ovfl to do so.
  61860. **
  61861. ** If an error occurs an SQLite error code is returned. Otherwise:
  61862. **
  61863. ** The page number of the next overflow page in the linked list is
  61864. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  61865. ** list, *pPgnoNext is set to zero.
  61866. **
  61867. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  61868. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  61869. ** reference. It is the responsibility of the caller to call releasePage()
  61870. ** on *ppPage to free the reference. In no reference was obtained (because
  61871. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  61872. ** *ppPage is set to zero.
  61873. */
  61874. static int getOverflowPage(
  61875. BtShared *pBt, /* The database file */
  61876. Pgno ovfl, /* Current overflow page number */
  61877. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  61878. Pgno *pPgnoNext /* OUT: Next overflow page number */
  61879. ){
  61880. Pgno next = 0;
  61881. MemPage *pPage = 0;
  61882. int rc = SQLITE_OK;
  61883. assert( sqlite3_mutex_held(pBt->mutex) );
  61884. assert(pPgnoNext);
  61885. #ifndef SQLITE_OMIT_AUTOVACUUM
  61886. /* Try to find the next page in the overflow list using the
  61887. ** autovacuum pointer-map pages. Guess that the next page in
  61888. ** the overflow list is page number (ovfl+1). If that guess turns
  61889. ** out to be wrong, fall back to loading the data of page
  61890. ** number ovfl to determine the next page number.
  61891. */
  61892. if( pBt->autoVacuum ){
  61893. Pgno pgno;
  61894. Pgno iGuess = ovfl+1;
  61895. u8 eType;
  61896. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  61897. iGuess++;
  61898. }
  61899. if( iGuess<=btreePagecount(pBt) ){
  61900. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  61901. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  61902. next = iGuess;
  61903. rc = SQLITE_DONE;
  61904. }
  61905. }
  61906. }
  61907. #endif
  61908. assert( next==0 || rc==SQLITE_DONE );
  61909. if( rc==SQLITE_OK ){
  61910. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  61911. assert( rc==SQLITE_OK || pPage==0 );
  61912. if( rc==SQLITE_OK ){
  61913. next = get4byte(pPage->aData);
  61914. }
  61915. }
  61916. *pPgnoNext = next;
  61917. if( ppPage ){
  61918. *ppPage = pPage;
  61919. }else{
  61920. releasePage(pPage);
  61921. }
  61922. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  61923. }
  61924. /*
  61925. ** Copy data from a buffer to a page, or from a page to a buffer.
  61926. **
  61927. ** pPayload is a pointer to data stored on database page pDbPage.
  61928. ** If argument eOp is false, then nByte bytes of data are copied
  61929. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  61930. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  61931. ** of data are copied from the buffer pBuf to pPayload.
  61932. **
  61933. ** SQLITE_OK is returned on success, otherwise an error code.
  61934. */
  61935. static int copyPayload(
  61936. void *pPayload, /* Pointer to page data */
  61937. void *pBuf, /* Pointer to buffer */
  61938. int nByte, /* Number of bytes to copy */
  61939. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  61940. DbPage *pDbPage /* Page containing pPayload */
  61941. ){
  61942. if( eOp ){
  61943. /* Copy data from buffer to page (a write operation) */
  61944. int rc = sqlite3PagerWrite(pDbPage);
  61945. if( rc!=SQLITE_OK ){
  61946. return rc;
  61947. }
  61948. memcpy(pPayload, pBuf, nByte);
  61949. }else{
  61950. /* Copy data from page to buffer (a read operation) */
  61951. memcpy(pBuf, pPayload, nByte);
  61952. }
  61953. return SQLITE_OK;
  61954. }
  61955. /*
  61956. ** This function is used to read or overwrite payload information
  61957. ** for the entry that the pCur cursor is pointing to. The eOp
  61958. ** argument is interpreted as follows:
  61959. **
  61960. ** 0: The operation is a read. Populate the overflow cache.
  61961. ** 1: The operation is a write. Populate the overflow cache.
  61962. **
  61963. ** A total of "amt" bytes are read or written beginning at "offset".
  61964. ** Data is read to or from the buffer pBuf.
  61965. **
  61966. ** The content being read or written might appear on the main page
  61967. ** or be scattered out on multiple overflow pages.
  61968. **
  61969. ** If the current cursor entry uses one or more overflow pages
  61970. ** this function may allocate space for and lazily populate
  61971. ** the overflow page-list cache array (BtCursor.aOverflow).
  61972. ** Subsequent calls use this cache to make seeking to the supplied offset
  61973. ** more efficient.
  61974. **
  61975. ** Once an overflow page-list cache has been allocated, it must be
  61976. ** invalidated if some other cursor writes to the same table, or if
  61977. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  61978. ** mode, the following events may invalidate an overflow page-list cache.
  61979. **
  61980. ** * An incremental vacuum,
  61981. ** * A commit in auto_vacuum="full" mode,
  61982. ** * Creating a table (may require moving an overflow page).
  61983. */
  61984. static int accessPayload(
  61985. BtCursor *pCur, /* Cursor pointing to entry to read from */
  61986. u32 offset, /* Begin reading this far into payload */
  61987. u32 amt, /* Read this many bytes */
  61988. unsigned char *pBuf, /* Write the bytes into this buffer */
  61989. int eOp /* zero to read. non-zero to write. */
  61990. ){
  61991. unsigned char *aPayload;
  61992. int rc = SQLITE_OK;
  61993. int iIdx = 0;
  61994. MemPage *pPage = pCur->pPage; /* Btree page of current entry */
  61995. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  61996. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  61997. unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
  61998. #endif
  61999. assert( pPage );
  62000. assert( eOp==0 || eOp==1 );
  62001. assert( pCur->eState==CURSOR_VALID );
  62002. assert( pCur->ix<pPage->nCell );
  62003. assert( cursorHoldsMutex(pCur) );
  62004. getCellInfo(pCur);
  62005. aPayload = pCur->info.pPayload;
  62006. assert( offset+amt <= pCur->info.nPayload );
  62007. assert( aPayload > pPage->aData );
  62008. if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
  62009. /* Trying to read or write past the end of the data is an error. The
  62010. ** conditional above is really:
  62011. ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  62012. ** but is recast into its current form to avoid integer overflow problems
  62013. */
  62014. return SQLITE_CORRUPT_PAGE(pPage);
  62015. }
  62016. /* Check if data must be read/written to/from the btree page itself. */
  62017. if( offset<pCur->info.nLocal ){
  62018. int a = amt;
  62019. if( a+offset>pCur->info.nLocal ){
  62020. a = pCur->info.nLocal - offset;
  62021. }
  62022. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  62023. offset = 0;
  62024. pBuf += a;
  62025. amt -= a;
  62026. }else{
  62027. offset -= pCur->info.nLocal;
  62028. }
  62029. if( rc==SQLITE_OK && amt>0 ){
  62030. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  62031. Pgno nextPage;
  62032. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  62033. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  62034. **
  62035. ** The aOverflow[] array is sized at one entry for each overflow page
  62036. ** in the overflow chain. The page number of the first overflow page is
  62037. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  62038. ** means "not yet known" (the cache is lazily populated).
  62039. */
  62040. if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  62041. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  62042. if( pCur->aOverflow==0
  62043. || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
  62044. ){
  62045. Pgno *aNew = (Pgno*)sqlite3Realloc(
  62046. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  62047. );
  62048. if( aNew==0 ){
  62049. return SQLITE_NOMEM_BKPT;
  62050. }else{
  62051. pCur->aOverflow = aNew;
  62052. }
  62053. }
  62054. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  62055. pCur->curFlags |= BTCF_ValidOvfl;
  62056. }else{
  62057. /* If the overflow page-list cache has been allocated and the
  62058. ** entry for the first required overflow page is valid, skip
  62059. ** directly to it.
  62060. */
  62061. if( pCur->aOverflow[offset/ovflSize] ){
  62062. iIdx = (offset/ovflSize);
  62063. nextPage = pCur->aOverflow[iIdx];
  62064. offset = (offset%ovflSize);
  62065. }
  62066. }
  62067. assert( rc==SQLITE_OK && amt>0 );
  62068. while( nextPage ){
  62069. /* If required, populate the overflow page-list cache. */
  62070. assert( pCur->aOverflow[iIdx]==0
  62071. || pCur->aOverflow[iIdx]==nextPage
  62072. || CORRUPT_DB );
  62073. pCur->aOverflow[iIdx] = nextPage;
  62074. if( offset>=ovflSize ){
  62075. /* The only reason to read this page is to obtain the page
  62076. ** number for the next page in the overflow chain. The page
  62077. ** data is not required. So first try to lookup the overflow
  62078. ** page-list cache, if any, then fall back to the getOverflowPage()
  62079. ** function.
  62080. */
  62081. assert( pCur->curFlags & BTCF_ValidOvfl );
  62082. assert( pCur->pBtree->db==pBt->db );
  62083. if( pCur->aOverflow[iIdx+1] ){
  62084. nextPage = pCur->aOverflow[iIdx+1];
  62085. }else{
  62086. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  62087. }
  62088. offset -= ovflSize;
  62089. }else{
  62090. /* Need to read this page properly. It contains some of the
  62091. ** range of data that is being read (eOp==0) or written (eOp!=0).
  62092. */
  62093. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  62094. sqlite3_file *fd; /* File from which to do direct overflow read */
  62095. #endif
  62096. int a = amt;
  62097. if( a + offset > ovflSize ){
  62098. a = ovflSize - offset;
  62099. }
  62100. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  62101. /* If all the following are true:
  62102. **
  62103. ** 1) this is a read operation, and
  62104. ** 2) data is required from the start of this overflow page, and
  62105. ** 3) there is no open write-transaction, and
  62106. ** 4) the database is file-backed, and
  62107. ** 5) the page is not in the WAL file
  62108. ** 6) at least 4 bytes have already been read into the output buffer
  62109. **
  62110. ** then data can be read directly from the database file into the
  62111. ** output buffer, bypassing the page-cache altogether. This speeds
  62112. ** up loading large records that span many overflow pages.
  62113. */
  62114. if( eOp==0 /* (1) */
  62115. && offset==0 /* (2) */
  62116. && pBt->inTransaction==TRANS_READ /* (3) */
  62117. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (4) */
  62118. && 0==sqlite3PagerUseWal(pBt->pPager, nextPage) /* (5) */
  62119. && &pBuf[-4]>=pBufStart /* (6) */
  62120. ){
  62121. u8 aSave[4];
  62122. u8 *aWrite = &pBuf[-4];
  62123. assert( aWrite>=pBufStart ); /* due to (6) */
  62124. memcpy(aSave, aWrite, 4);
  62125. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  62126. nextPage = get4byte(aWrite);
  62127. memcpy(aWrite, aSave, 4);
  62128. }else
  62129. #endif
  62130. {
  62131. DbPage *pDbPage;
  62132. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  62133. (eOp==0 ? PAGER_GET_READONLY : 0)
  62134. );
  62135. if( rc==SQLITE_OK ){
  62136. aPayload = sqlite3PagerGetData(pDbPage);
  62137. nextPage = get4byte(aPayload);
  62138. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  62139. sqlite3PagerUnref(pDbPage);
  62140. offset = 0;
  62141. }
  62142. }
  62143. amt -= a;
  62144. if( amt==0 ) return rc;
  62145. pBuf += a;
  62146. }
  62147. if( rc ) break;
  62148. iIdx++;
  62149. }
  62150. }
  62151. if( rc==SQLITE_OK && amt>0 ){
  62152. /* Overflow chain ends prematurely */
  62153. return SQLITE_CORRUPT_PAGE(pPage);
  62154. }
  62155. return rc;
  62156. }
  62157. /*
  62158. ** Read part of the payload for the row at which that cursor pCur is currently
  62159. ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
  62160. ** begins at "offset".
  62161. **
  62162. ** pCur can be pointing to either a table or an index b-tree.
  62163. ** If pointing to a table btree, then the content section is read. If
  62164. ** pCur is pointing to an index b-tree then the key section is read.
  62165. **
  62166. ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
  62167. ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
  62168. ** cursor might be invalid or might need to be restored before being read.
  62169. **
  62170. ** Return SQLITE_OK on success or an error code if anything goes
  62171. ** wrong. An error is returned if "offset+amt" is larger than
  62172. ** the available payload.
  62173. */
  62174. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  62175. assert( cursorHoldsMutex(pCur) );
  62176. assert( pCur->eState==CURSOR_VALID );
  62177. assert( pCur->iPage>=0 && pCur->pPage );
  62178. assert( pCur->ix<pCur->pPage->nCell );
  62179. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  62180. }
  62181. /*
  62182. ** This variant of sqlite3BtreePayload() works even if the cursor has not
  62183. ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
  62184. ** interface.
  62185. */
  62186. #ifndef SQLITE_OMIT_INCRBLOB
  62187. static SQLITE_NOINLINE int accessPayloadChecked(
  62188. BtCursor *pCur,
  62189. u32 offset,
  62190. u32 amt,
  62191. void *pBuf
  62192. ){
  62193. int rc;
  62194. if ( pCur->eState==CURSOR_INVALID ){
  62195. return SQLITE_ABORT;
  62196. }
  62197. assert( cursorOwnsBtShared(pCur) );
  62198. rc = btreeRestoreCursorPosition(pCur);
  62199. return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
  62200. }
  62201. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  62202. if( pCur->eState==CURSOR_VALID ){
  62203. assert( cursorOwnsBtShared(pCur) );
  62204. return accessPayload(pCur, offset, amt, pBuf, 0);
  62205. }else{
  62206. return accessPayloadChecked(pCur, offset, amt, pBuf);
  62207. }
  62208. }
  62209. #endif /* SQLITE_OMIT_INCRBLOB */
  62210. /*
  62211. ** Return a pointer to payload information from the entry that the
  62212. ** pCur cursor is pointing to. The pointer is to the beginning of
  62213. ** the key if index btrees (pPage->intKey==0) and is the data for
  62214. ** table btrees (pPage->intKey==1). The number of bytes of available
  62215. ** key/data is written into *pAmt. If *pAmt==0, then the value
  62216. ** returned will not be a valid pointer.
  62217. **
  62218. ** This routine is an optimization. It is common for the entire key
  62219. ** and data to fit on the local page and for there to be no overflow
  62220. ** pages. When that is so, this routine can be used to access the
  62221. ** key and data without making a copy. If the key and/or data spills
  62222. ** onto overflow pages, then accessPayload() must be used to reassemble
  62223. ** the key/data and copy it into a preallocated buffer.
  62224. **
  62225. ** The pointer returned by this routine looks directly into the cached
  62226. ** page of the database. The data might change or move the next time
  62227. ** any btree routine is called.
  62228. */
  62229. static const void *fetchPayload(
  62230. BtCursor *pCur, /* Cursor pointing to entry to read from */
  62231. u32 *pAmt /* Write the number of available bytes here */
  62232. ){
  62233. int amt;
  62234. assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
  62235. assert( pCur->eState==CURSOR_VALID );
  62236. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  62237. assert( cursorOwnsBtShared(pCur) );
  62238. assert( pCur->ix<pCur->pPage->nCell );
  62239. assert( pCur->info.nSize>0 );
  62240. assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
  62241. assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
  62242. amt = pCur->info.nLocal;
  62243. if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
  62244. /* There is too little space on the page for the expected amount
  62245. ** of local content. Database must be corrupt. */
  62246. assert( CORRUPT_DB );
  62247. amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
  62248. }
  62249. *pAmt = (u32)amt;
  62250. return (void*)pCur->info.pPayload;
  62251. }
  62252. /*
  62253. ** For the entry that cursor pCur is point to, return as
  62254. ** many bytes of the key or data as are available on the local
  62255. ** b-tree page. Write the number of available bytes into *pAmt.
  62256. **
  62257. ** The pointer returned is ephemeral. The key/data may move
  62258. ** or be destroyed on the next call to any Btree routine,
  62259. ** including calls from other threads against the same cache.
  62260. ** Hence, a mutex on the BtShared should be held prior to calling
  62261. ** this routine.
  62262. **
  62263. ** These routines is used to get quick access to key and data
  62264. ** in the common case where no overflow pages are used.
  62265. */
  62266. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
  62267. return fetchPayload(pCur, pAmt);
  62268. }
  62269. /*
  62270. ** Move the cursor down to a new child page. The newPgno argument is the
  62271. ** page number of the child page to move to.
  62272. **
  62273. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  62274. ** the new child page does not match the flags field of the parent (i.e.
  62275. ** if an intkey page appears to be the parent of a non-intkey page, or
  62276. ** vice-versa).
  62277. */
  62278. static int moveToChild(BtCursor *pCur, u32 newPgno){
  62279. BtShared *pBt = pCur->pBt;
  62280. assert( cursorOwnsBtShared(pCur) );
  62281. assert( pCur->eState==CURSOR_VALID );
  62282. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  62283. assert( pCur->iPage>=0 );
  62284. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  62285. return SQLITE_CORRUPT_BKPT;
  62286. }
  62287. pCur->info.nSize = 0;
  62288. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  62289. pCur->aiIdx[pCur->iPage] = pCur->ix;
  62290. pCur->apPage[pCur->iPage] = pCur->pPage;
  62291. pCur->ix = 0;
  62292. pCur->iPage++;
  62293. return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
  62294. }
  62295. #ifdef SQLITE_DEBUG
  62296. /*
  62297. ** Page pParent is an internal (non-leaf) tree page. This function
  62298. ** asserts that page number iChild is the left-child if the iIdx'th
  62299. ** cell in page pParent. Or, if iIdx is equal to the total number of
  62300. ** cells in pParent, that page number iChild is the right-child of
  62301. ** the page.
  62302. */
  62303. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  62304. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  62305. ** in a corrupt database */
  62306. assert( iIdx<=pParent->nCell );
  62307. if( iIdx==pParent->nCell ){
  62308. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  62309. }else{
  62310. assert( get4byte(findCell(pParent, iIdx))==iChild );
  62311. }
  62312. }
  62313. #else
  62314. # define assertParentIndex(x,y,z)
  62315. #endif
  62316. /*
  62317. ** Move the cursor up to the parent page.
  62318. **
  62319. ** pCur->idx is set to the cell index that contains the pointer
  62320. ** to the page we are coming from. If we are coming from the
  62321. ** right-most child page then pCur->idx is set to one more than
  62322. ** the largest cell index.
  62323. */
  62324. static void moveToParent(BtCursor *pCur){
  62325. MemPage *pLeaf;
  62326. assert( cursorOwnsBtShared(pCur) );
  62327. assert( pCur->eState==CURSOR_VALID );
  62328. assert( pCur->iPage>0 );
  62329. assert( pCur->pPage );
  62330. assertParentIndex(
  62331. pCur->apPage[pCur->iPage-1],
  62332. pCur->aiIdx[pCur->iPage-1],
  62333. pCur->pPage->pgno
  62334. );
  62335. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  62336. pCur->info.nSize = 0;
  62337. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  62338. pCur->ix = pCur->aiIdx[pCur->iPage-1];
  62339. pLeaf = pCur->pPage;
  62340. pCur->pPage = pCur->apPage[--pCur->iPage];
  62341. releasePageNotNull(pLeaf);
  62342. }
  62343. /*
  62344. ** Move the cursor to point to the root page of its b-tree structure.
  62345. **
  62346. ** If the table has a virtual root page, then the cursor is moved to point
  62347. ** to the virtual root page instead of the actual root page. A table has a
  62348. ** virtual root page when the actual root page contains no cells and a
  62349. ** single child page. This can only happen with the table rooted at page 1.
  62350. **
  62351. ** If the b-tree structure is empty, the cursor state is set to
  62352. ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
  62353. ** the cursor is set to point to the first cell located on the root
  62354. ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
  62355. **
  62356. ** If this function returns successfully, it may be assumed that the
  62357. ** page-header flags indicate that the [virtual] root-page is the expected
  62358. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  62359. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  62360. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  62361. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  62362. ** b-tree).
  62363. */
  62364. static int moveToRoot(BtCursor *pCur){
  62365. MemPage *pRoot;
  62366. int rc = SQLITE_OK;
  62367. assert( cursorOwnsBtShared(pCur) );
  62368. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  62369. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  62370. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  62371. assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
  62372. assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
  62373. if( pCur->iPage>=0 ){
  62374. if( pCur->iPage ){
  62375. releasePageNotNull(pCur->pPage);
  62376. while( --pCur->iPage ){
  62377. releasePageNotNull(pCur->apPage[pCur->iPage]);
  62378. }
  62379. pCur->pPage = pCur->apPage[0];
  62380. goto skip_init;
  62381. }
  62382. }else if( pCur->pgnoRoot==0 ){
  62383. pCur->eState = CURSOR_INVALID;
  62384. return SQLITE_EMPTY;
  62385. }else{
  62386. assert( pCur->iPage==(-1) );
  62387. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  62388. if( pCur->eState==CURSOR_FAULT ){
  62389. assert( pCur->skipNext!=SQLITE_OK );
  62390. return pCur->skipNext;
  62391. }
  62392. sqlite3BtreeClearCursor(pCur);
  62393. }
  62394. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
  62395. 0, pCur->curPagerFlags);
  62396. if( rc!=SQLITE_OK ){
  62397. pCur->eState = CURSOR_INVALID;
  62398. return rc;
  62399. }
  62400. pCur->iPage = 0;
  62401. pCur->curIntKey = pCur->pPage->intKey;
  62402. }
  62403. pRoot = pCur->pPage;
  62404. assert( pRoot->pgno==pCur->pgnoRoot );
  62405. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  62406. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  62407. ** NULL, the caller expects a table b-tree. If this is not the case,
  62408. ** return an SQLITE_CORRUPT error.
  62409. **
  62410. ** Earlier versions of SQLite assumed that this test could not fail
  62411. ** if the root page was already loaded when this function was called (i.e.
  62412. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  62413. ** in such a way that page pRoot is linked into a second b-tree table
  62414. ** (or the freelist). */
  62415. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  62416. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  62417. return SQLITE_CORRUPT_PAGE(pCur->pPage);
  62418. }
  62419. skip_init:
  62420. pCur->ix = 0;
  62421. pCur->info.nSize = 0;
  62422. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  62423. pRoot = pCur->pPage;
  62424. if( pRoot->nCell>0 ){
  62425. pCur->eState = CURSOR_VALID;
  62426. }else if( !pRoot->leaf ){
  62427. Pgno subpage;
  62428. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  62429. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  62430. pCur->eState = CURSOR_VALID;
  62431. rc = moveToChild(pCur, subpage);
  62432. }else{
  62433. pCur->eState = CURSOR_INVALID;
  62434. rc = SQLITE_EMPTY;
  62435. }
  62436. return rc;
  62437. }
  62438. /*
  62439. ** Move the cursor down to the left-most leaf entry beneath the
  62440. ** entry to which it is currently pointing.
  62441. **
  62442. ** The left-most leaf is the one with the smallest key - the first
  62443. ** in ascending order.
  62444. */
  62445. static int moveToLeftmost(BtCursor *pCur){
  62446. Pgno pgno;
  62447. int rc = SQLITE_OK;
  62448. MemPage *pPage;
  62449. assert( cursorOwnsBtShared(pCur) );
  62450. assert( pCur->eState==CURSOR_VALID );
  62451. while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
  62452. assert( pCur->ix<pPage->nCell );
  62453. pgno = get4byte(findCell(pPage, pCur->ix));
  62454. rc = moveToChild(pCur, pgno);
  62455. }
  62456. return rc;
  62457. }
  62458. /*
  62459. ** Move the cursor down to the right-most leaf entry beneath the
  62460. ** page to which it is currently pointing. Notice the difference
  62461. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  62462. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  62463. ** finds the right-most entry beneath the *page*.
  62464. **
  62465. ** The right-most entry is the one with the largest key - the last
  62466. ** key in ascending order.
  62467. */
  62468. static int moveToRightmost(BtCursor *pCur){
  62469. Pgno pgno;
  62470. int rc = SQLITE_OK;
  62471. MemPage *pPage = 0;
  62472. assert( cursorOwnsBtShared(pCur) );
  62473. assert( pCur->eState==CURSOR_VALID );
  62474. while( !(pPage = pCur->pPage)->leaf ){
  62475. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  62476. pCur->ix = pPage->nCell;
  62477. rc = moveToChild(pCur, pgno);
  62478. if( rc ) return rc;
  62479. }
  62480. pCur->ix = pPage->nCell-1;
  62481. assert( pCur->info.nSize==0 );
  62482. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  62483. return SQLITE_OK;
  62484. }
  62485. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  62486. ** on success. Set *pRes to 0 if the cursor actually points to something
  62487. ** or set *pRes to 1 if the table is empty.
  62488. */
  62489. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  62490. int rc;
  62491. assert( cursorOwnsBtShared(pCur) );
  62492. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  62493. rc = moveToRoot(pCur);
  62494. if( rc==SQLITE_OK ){
  62495. assert( pCur->pPage->nCell>0 );
  62496. *pRes = 0;
  62497. rc = moveToLeftmost(pCur);
  62498. }else if( rc==SQLITE_EMPTY ){
  62499. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  62500. *pRes = 1;
  62501. rc = SQLITE_OK;
  62502. }
  62503. return rc;
  62504. }
  62505. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  62506. ** on success. Set *pRes to 0 if the cursor actually points to something
  62507. ** or set *pRes to 1 if the table is empty.
  62508. */
  62509. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  62510. int rc;
  62511. assert( cursorOwnsBtShared(pCur) );
  62512. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  62513. /* If the cursor already points to the last entry, this is a no-op. */
  62514. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  62515. #ifdef SQLITE_DEBUG
  62516. /* This block serves to assert() that the cursor really does point
  62517. ** to the last entry in the b-tree. */
  62518. int ii;
  62519. for(ii=0; ii<pCur->iPage; ii++){
  62520. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  62521. }
  62522. assert( pCur->ix==pCur->pPage->nCell-1 );
  62523. assert( pCur->pPage->leaf );
  62524. #endif
  62525. return SQLITE_OK;
  62526. }
  62527. rc = moveToRoot(pCur);
  62528. if( rc==SQLITE_OK ){
  62529. assert( pCur->eState==CURSOR_VALID );
  62530. *pRes = 0;
  62531. rc = moveToRightmost(pCur);
  62532. if( rc==SQLITE_OK ){
  62533. pCur->curFlags |= BTCF_AtLast;
  62534. }else{
  62535. pCur->curFlags &= ~BTCF_AtLast;
  62536. }
  62537. }else if( rc==SQLITE_EMPTY ){
  62538. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  62539. *pRes = 1;
  62540. rc = SQLITE_OK;
  62541. }
  62542. return rc;
  62543. }
  62544. /* Move the cursor so that it points to an entry near the key
  62545. ** specified by pIdxKey or intKey. Return a success code.
  62546. **
  62547. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  62548. ** must be NULL. For index tables, pIdxKey is used and intKey
  62549. ** is ignored.
  62550. **
  62551. ** If an exact match is not found, then the cursor is always
  62552. ** left pointing at a leaf page which would hold the entry if it
  62553. ** were present. The cursor might point to an entry that comes
  62554. ** before or after the key.
  62555. **
  62556. ** An integer is written into *pRes which is the result of
  62557. ** comparing the key with the entry to which the cursor is
  62558. ** pointing. The meaning of the integer written into
  62559. ** *pRes is as follows:
  62560. **
  62561. ** *pRes<0 The cursor is left pointing at an entry that
  62562. ** is smaller than intKey/pIdxKey or if the table is empty
  62563. ** and the cursor is therefore left point to nothing.
  62564. **
  62565. ** *pRes==0 The cursor is left pointing at an entry that
  62566. ** exactly matches intKey/pIdxKey.
  62567. **
  62568. ** *pRes>0 The cursor is left pointing at an entry that
  62569. ** is larger than intKey/pIdxKey.
  62570. **
  62571. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  62572. ** exists an entry in the table that exactly matches pIdxKey.
  62573. */
  62574. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  62575. BtCursor *pCur, /* The cursor to be moved */
  62576. UnpackedRecord *pIdxKey, /* Unpacked index key */
  62577. i64 intKey, /* The table key */
  62578. int biasRight, /* If true, bias the search to the high end */
  62579. int *pRes /* Write search results here */
  62580. ){
  62581. int rc;
  62582. RecordCompare xRecordCompare;
  62583. assert( cursorOwnsBtShared(pCur) );
  62584. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  62585. assert( pRes );
  62586. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  62587. assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
  62588. /* If the cursor is already positioned at the point we are trying
  62589. ** to move to, then just return without doing any work */
  62590. if( pIdxKey==0
  62591. && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  62592. ){
  62593. if( pCur->info.nKey==intKey ){
  62594. *pRes = 0;
  62595. return SQLITE_OK;
  62596. }
  62597. if( pCur->info.nKey<intKey ){
  62598. if( (pCur->curFlags & BTCF_AtLast)!=0 ){
  62599. *pRes = -1;
  62600. return SQLITE_OK;
  62601. }
  62602. /* If the requested key is one more than the previous key, then
  62603. ** try to get there using sqlite3BtreeNext() rather than a full
  62604. ** binary search. This is an optimization only. The correct answer
  62605. ** is still obtained without this case, only a little more slowely */
  62606. if( pCur->info.nKey+1==intKey && !pCur->skipNext ){
  62607. *pRes = 0;
  62608. rc = sqlite3BtreeNext(pCur, 0);
  62609. if( rc==SQLITE_OK ){
  62610. getCellInfo(pCur);
  62611. if( pCur->info.nKey==intKey ){
  62612. return SQLITE_OK;
  62613. }
  62614. }else if( rc==SQLITE_DONE ){
  62615. rc = SQLITE_OK;
  62616. }else{
  62617. return rc;
  62618. }
  62619. }
  62620. }
  62621. }
  62622. if( pIdxKey ){
  62623. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  62624. pIdxKey->errCode = 0;
  62625. assert( pIdxKey->default_rc==1
  62626. || pIdxKey->default_rc==0
  62627. || pIdxKey->default_rc==-1
  62628. );
  62629. }else{
  62630. xRecordCompare = 0; /* All keys are integers */
  62631. }
  62632. rc = moveToRoot(pCur);
  62633. if( rc ){
  62634. if( rc==SQLITE_EMPTY ){
  62635. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  62636. *pRes = -1;
  62637. return SQLITE_OK;
  62638. }
  62639. return rc;
  62640. }
  62641. assert( pCur->pPage );
  62642. assert( pCur->pPage->isInit );
  62643. assert( pCur->eState==CURSOR_VALID );
  62644. assert( pCur->pPage->nCell > 0 );
  62645. assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
  62646. assert( pCur->curIntKey || pIdxKey );
  62647. for(;;){
  62648. int lwr, upr, idx, c;
  62649. Pgno chldPg;
  62650. MemPage *pPage = pCur->pPage;
  62651. u8 *pCell; /* Pointer to current cell in pPage */
  62652. /* pPage->nCell must be greater than zero. If this is the root-page
  62653. ** the cursor would have been INVALID above and this for(;;) loop
  62654. ** not run. If this is not the root-page, then the moveToChild() routine
  62655. ** would have already detected db corruption. Similarly, pPage must
  62656. ** be the right kind (index or table) of b-tree page. Otherwise
  62657. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  62658. assert( pPage->nCell>0 );
  62659. assert( pPage->intKey==(pIdxKey==0) );
  62660. lwr = 0;
  62661. upr = pPage->nCell-1;
  62662. assert( biasRight==0 || biasRight==1 );
  62663. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  62664. pCur->ix = (u16)idx;
  62665. if( xRecordCompare==0 ){
  62666. for(;;){
  62667. i64 nCellKey;
  62668. pCell = findCellPastPtr(pPage, idx);
  62669. if( pPage->intKeyLeaf ){
  62670. while( 0x80 <= *(pCell++) ){
  62671. if( pCell>=pPage->aDataEnd ){
  62672. return SQLITE_CORRUPT_PAGE(pPage);
  62673. }
  62674. }
  62675. }
  62676. getVarint(pCell, (u64*)&nCellKey);
  62677. if( nCellKey<intKey ){
  62678. lwr = idx+1;
  62679. if( lwr>upr ){ c = -1; break; }
  62680. }else if( nCellKey>intKey ){
  62681. upr = idx-1;
  62682. if( lwr>upr ){ c = +1; break; }
  62683. }else{
  62684. assert( nCellKey==intKey );
  62685. pCur->ix = (u16)idx;
  62686. if( !pPage->leaf ){
  62687. lwr = idx;
  62688. goto moveto_next_layer;
  62689. }else{
  62690. pCur->curFlags |= BTCF_ValidNKey;
  62691. pCur->info.nKey = nCellKey;
  62692. pCur->info.nSize = 0;
  62693. *pRes = 0;
  62694. return SQLITE_OK;
  62695. }
  62696. }
  62697. assert( lwr+upr>=0 );
  62698. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  62699. }
  62700. }else{
  62701. for(;;){
  62702. int nCell; /* Size of the pCell cell in bytes */
  62703. pCell = findCellPastPtr(pPage, idx);
  62704. /* The maximum supported page-size is 65536 bytes. This means that
  62705. ** the maximum number of record bytes stored on an index B-Tree
  62706. ** page is less than 16384 bytes and may be stored as a 2-byte
  62707. ** varint. This information is used to attempt to avoid parsing
  62708. ** the entire cell by checking for the cases where the record is
  62709. ** stored entirely within the b-tree page by inspecting the first
  62710. ** 2 bytes of the cell.
  62711. */
  62712. nCell = pCell[0];
  62713. if( nCell<=pPage->max1bytePayload ){
  62714. /* This branch runs if the record-size field of the cell is a
  62715. ** single byte varint and the record fits entirely on the main
  62716. ** b-tree page. */
  62717. testcase( pCell+nCell+1==pPage->aDataEnd );
  62718. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  62719. }else if( !(pCell[1] & 0x80)
  62720. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  62721. ){
  62722. /* The record-size field is a 2 byte varint and the record
  62723. ** fits entirely on the main b-tree page. */
  62724. testcase( pCell+nCell+2==pPage->aDataEnd );
  62725. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  62726. }else{
  62727. /* The record flows over onto one or more overflow pages. In
  62728. ** this case the whole cell needs to be parsed, a buffer allocated
  62729. ** and accessPayload() used to retrieve the record into the
  62730. ** buffer before VdbeRecordCompare() can be called.
  62731. **
  62732. ** If the record is corrupt, the xRecordCompare routine may read
  62733. ** up to two varints past the end of the buffer. An extra 18
  62734. ** bytes of padding is allocated at the end of the buffer in
  62735. ** case this happens. */
  62736. void *pCellKey;
  62737. u8 * const pCellBody = pCell - pPage->childPtrSize;
  62738. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  62739. nCell = (int)pCur->info.nKey;
  62740. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  62741. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  62742. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  62743. testcase( nCell==2 ); /* Minimum legal index key size */
  62744. if( nCell<2 ){
  62745. rc = SQLITE_CORRUPT_PAGE(pPage);
  62746. goto moveto_finish;
  62747. }
  62748. pCellKey = sqlite3Malloc( nCell+18 );
  62749. if( pCellKey==0 ){
  62750. rc = SQLITE_NOMEM_BKPT;
  62751. goto moveto_finish;
  62752. }
  62753. pCur->ix = (u16)idx;
  62754. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  62755. pCur->curFlags &= ~BTCF_ValidOvfl;
  62756. if( rc ){
  62757. sqlite3_free(pCellKey);
  62758. goto moveto_finish;
  62759. }
  62760. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  62761. sqlite3_free(pCellKey);
  62762. }
  62763. assert(
  62764. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  62765. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  62766. );
  62767. if( c<0 ){
  62768. lwr = idx+1;
  62769. }else if( c>0 ){
  62770. upr = idx-1;
  62771. }else{
  62772. assert( c==0 );
  62773. *pRes = 0;
  62774. rc = SQLITE_OK;
  62775. pCur->ix = (u16)idx;
  62776. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
  62777. goto moveto_finish;
  62778. }
  62779. if( lwr>upr ) break;
  62780. assert( lwr+upr>=0 );
  62781. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  62782. }
  62783. }
  62784. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  62785. assert( pPage->isInit );
  62786. if( pPage->leaf ){
  62787. assert( pCur->ix<pCur->pPage->nCell );
  62788. pCur->ix = (u16)idx;
  62789. *pRes = c;
  62790. rc = SQLITE_OK;
  62791. goto moveto_finish;
  62792. }
  62793. moveto_next_layer:
  62794. if( lwr>=pPage->nCell ){
  62795. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  62796. }else{
  62797. chldPg = get4byte(findCell(pPage, lwr));
  62798. }
  62799. pCur->ix = (u16)lwr;
  62800. rc = moveToChild(pCur, chldPg);
  62801. if( rc ) break;
  62802. }
  62803. moveto_finish:
  62804. pCur->info.nSize = 0;
  62805. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  62806. return rc;
  62807. }
  62808. /*
  62809. ** Return TRUE if the cursor is not pointing at an entry of the table.
  62810. **
  62811. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  62812. ** past the last entry in the table or sqlite3BtreePrev() moves past
  62813. ** the first entry. TRUE is also returned if the table is empty.
  62814. */
  62815. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  62816. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  62817. ** have been deleted? This API will need to change to return an error code
  62818. ** as well as the boolean result value.
  62819. */
  62820. return (CURSOR_VALID!=pCur->eState);
  62821. }
  62822. /*
  62823. ** Return an estimate for the number of rows in the table that pCur is
  62824. ** pointing to. Return a negative number if no estimate is currently
  62825. ** available.
  62826. */
  62827. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
  62828. i64 n;
  62829. u8 i;
  62830. assert( cursorOwnsBtShared(pCur) );
  62831. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  62832. /* Currently this interface is only called by the OP_IfSmaller
  62833. ** opcode, and it that case the cursor will always be valid and
  62834. ** will always point to a leaf node. */
  62835. if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
  62836. if( NEVER(pCur->pPage->leaf==0) ) return -1;
  62837. n = pCur->pPage->nCell;
  62838. for(i=0; i<pCur->iPage; i++){
  62839. n *= pCur->apPage[i]->nCell;
  62840. }
  62841. return n;
  62842. }
  62843. /*
  62844. ** Advance the cursor to the next entry in the database.
  62845. ** Return value:
  62846. **
  62847. ** SQLITE_OK success
  62848. ** SQLITE_DONE cursor is already pointing at the last element
  62849. ** otherwise some kind of error occurred
  62850. **
  62851. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  62852. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  62853. ** to the next cell on the current page. The (slower) btreeNext() helper
  62854. ** routine is called when it is necessary to move to a different page or
  62855. ** to restore the cursor.
  62856. **
  62857. ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
  62858. ** cursor corresponds to an SQL index and this routine could have been
  62859. ** skipped if the SQL index had been a unique index. The F argument
  62860. ** is a hint to the implement. SQLite btree implementation does not use
  62861. ** this hint, but COMDB2 does.
  62862. */
  62863. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
  62864. int rc;
  62865. int idx;
  62866. MemPage *pPage;
  62867. assert( cursorOwnsBtShared(pCur) );
  62868. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  62869. if( pCur->eState!=CURSOR_VALID ){
  62870. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  62871. rc = restoreCursorPosition(pCur);
  62872. if( rc!=SQLITE_OK ){
  62873. return rc;
  62874. }
  62875. if( CURSOR_INVALID==pCur->eState ){
  62876. return SQLITE_DONE;
  62877. }
  62878. if( pCur->skipNext ){
  62879. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  62880. pCur->eState = CURSOR_VALID;
  62881. if( pCur->skipNext>0 ){
  62882. pCur->skipNext = 0;
  62883. return SQLITE_OK;
  62884. }
  62885. pCur->skipNext = 0;
  62886. }
  62887. }
  62888. pPage = pCur->pPage;
  62889. idx = ++pCur->ix;
  62890. assert( pPage->isInit );
  62891. /* If the database file is corrupt, it is possible for the value of idx
  62892. ** to be invalid here. This can only occur if a second cursor modifies
  62893. ** the page while cursor pCur is holding a reference to it. Which can
  62894. ** only happen if the database is corrupt in such a way as to link the
  62895. ** page into more than one b-tree structure. */
  62896. testcase( idx>pPage->nCell );
  62897. if( idx>=pPage->nCell ){
  62898. if( !pPage->leaf ){
  62899. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  62900. if( rc ) return rc;
  62901. return moveToLeftmost(pCur);
  62902. }
  62903. do{
  62904. if( pCur->iPage==0 ){
  62905. pCur->eState = CURSOR_INVALID;
  62906. return SQLITE_DONE;
  62907. }
  62908. moveToParent(pCur);
  62909. pPage = pCur->pPage;
  62910. }while( pCur->ix>=pPage->nCell );
  62911. if( pPage->intKey ){
  62912. return sqlite3BtreeNext(pCur, 0);
  62913. }else{
  62914. return SQLITE_OK;
  62915. }
  62916. }
  62917. if( pPage->leaf ){
  62918. return SQLITE_OK;
  62919. }else{
  62920. return moveToLeftmost(pCur);
  62921. }
  62922. }
  62923. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
  62924. MemPage *pPage;
  62925. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  62926. assert( cursorOwnsBtShared(pCur) );
  62927. assert( flags==0 || flags==1 );
  62928. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  62929. pCur->info.nSize = 0;
  62930. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  62931. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
  62932. pPage = pCur->pPage;
  62933. if( (++pCur->ix)>=pPage->nCell ){
  62934. pCur->ix--;
  62935. return btreeNext(pCur);
  62936. }
  62937. if( pPage->leaf ){
  62938. return SQLITE_OK;
  62939. }else{
  62940. return moveToLeftmost(pCur);
  62941. }
  62942. }
  62943. /*
  62944. ** Step the cursor to the back to the previous entry in the database.
  62945. ** Return values:
  62946. **
  62947. ** SQLITE_OK success
  62948. ** SQLITE_DONE the cursor is already on the first element of the table
  62949. ** otherwise some kind of error occurred
  62950. **
  62951. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  62952. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  62953. ** to the previous cell on the current page. The (slower) btreePrevious()
  62954. ** helper routine is called when it is necessary to move to a different page
  62955. ** or to restore the cursor.
  62956. **
  62957. ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
  62958. ** the cursor corresponds to an SQL index and this routine could have been
  62959. ** skipped if the SQL index had been a unique index. The F argument is a
  62960. ** hint to the implement. The native SQLite btree implementation does not
  62961. ** use this hint, but COMDB2 does.
  62962. */
  62963. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
  62964. int rc;
  62965. MemPage *pPage;
  62966. assert( cursorOwnsBtShared(pCur) );
  62967. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  62968. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  62969. assert( pCur->info.nSize==0 );
  62970. if( pCur->eState!=CURSOR_VALID ){
  62971. rc = restoreCursorPosition(pCur);
  62972. if( rc!=SQLITE_OK ){
  62973. return rc;
  62974. }
  62975. if( CURSOR_INVALID==pCur->eState ){
  62976. return SQLITE_DONE;
  62977. }
  62978. if( pCur->skipNext ){
  62979. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  62980. pCur->eState = CURSOR_VALID;
  62981. if( pCur->skipNext<0 ){
  62982. pCur->skipNext = 0;
  62983. return SQLITE_OK;
  62984. }
  62985. pCur->skipNext = 0;
  62986. }
  62987. }
  62988. pPage = pCur->pPage;
  62989. assert( pPage->isInit );
  62990. if( !pPage->leaf ){
  62991. int idx = pCur->ix;
  62992. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  62993. if( rc ) return rc;
  62994. rc = moveToRightmost(pCur);
  62995. }else{
  62996. while( pCur->ix==0 ){
  62997. if( pCur->iPage==0 ){
  62998. pCur->eState = CURSOR_INVALID;
  62999. return SQLITE_DONE;
  63000. }
  63001. moveToParent(pCur);
  63002. }
  63003. assert( pCur->info.nSize==0 );
  63004. assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
  63005. pCur->ix--;
  63006. pPage = pCur->pPage;
  63007. if( pPage->intKey && !pPage->leaf ){
  63008. rc = sqlite3BtreePrevious(pCur, 0);
  63009. }else{
  63010. rc = SQLITE_OK;
  63011. }
  63012. }
  63013. return rc;
  63014. }
  63015. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
  63016. assert( cursorOwnsBtShared(pCur) );
  63017. assert( flags==0 || flags==1 );
  63018. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  63019. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  63020. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  63021. pCur->info.nSize = 0;
  63022. if( pCur->eState!=CURSOR_VALID
  63023. || pCur->ix==0
  63024. || pCur->pPage->leaf==0
  63025. ){
  63026. return btreePrevious(pCur);
  63027. }
  63028. pCur->ix--;
  63029. return SQLITE_OK;
  63030. }
  63031. /*
  63032. ** Allocate a new page from the database file.
  63033. **
  63034. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  63035. ** has already been called on the new page.) The new page has also
  63036. ** been referenced and the calling routine is responsible for calling
  63037. ** sqlite3PagerUnref() on the new page when it is done.
  63038. **
  63039. ** SQLITE_OK is returned on success. Any other return value indicates
  63040. ** an error. *ppPage is set to NULL in the event of an error.
  63041. **
  63042. ** If the "nearby" parameter is not 0, then an effort is made to
  63043. ** locate a page close to the page number "nearby". This can be used in an
  63044. ** attempt to keep related pages close to each other in the database file,
  63045. ** which in turn can make database access faster.
  63046. **
  63047. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  63048. ** anywhere on the free-list, then it is guaranteed to be returned. If
  63049. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  63050. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  63051. ** are no restrictions on which page is returned.
  63052. */
  63053. static int allocateBtreePage(
  63054. BtShared *pBt, /* The btree */
  63055. MemPage **ppPage, /* Store pointer to the allocated page here */
  63056. Pgno *pPgno, /* Store the page number here */
  63057. Pgno nearby, /* Search for a page near this one */
  63058. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  63059. ){
  63060. MemPage *pPage1;
  63061. int rc;
  63062. u32 n; /* Number of pages on the freelist */
  63063. u32 k; /* Number of leaves on the trunk of the freelist */
  63064. MemPage *pTrunk = 0;
  63065. MemPage *pPrevTrunk = 0;
  63066. Pgno mxPage; /* Total size of the database file */
  63067. assert( sqlite3_mutex_held(pBt->mutex) );
  63068. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  63069. pPage1 = pBt->pPage1;
  63070. mxPage = btreePagecount(pBt);
  63071. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  63072. ** stores stores the total number of pages on the freelist. */
  63073. n = get4byte(&pPage1->aData[36]);
  63074. testcase( n==mxPage-1 );
  63075. if( n>=mxPage ){
  63076. return SQLITE_CORRUPT_BKPT;
  63077. }
  63078. if( n>0 ){
  63079. /* There are pages on the freelist. Reuse one of those pages. */
  63080. Pgno iTrunk;
  63081. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  63082. u32 nSearch = 0; /* Count of the number of search attempts */
  63083. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  63084. ** shows that the page 'nearby' is somewhere on the free-list, then
  63085. ** the entire-list will be searched for that page.
  63086. */
  63087. #ifndef SQLITE_OMIT_AUTOVACUUM
  63088. if( eMode==BTALLOC_EXACT ){
  63089. if( nearby<=mxPage ){
  63090. u8 eType;
  63091. assert( nearby>0 );
  63092. assert( pBt->autoVacuum );
  63093. rc = ptrmapGet(pBt, nearby, &eType, 0);
  63094. if( rc ) return rc;
  63095. if( eType==PTRMAP_FREEPAGE ){
  63096. searchList = 1;
  63097. }
  63098. }
  63099. }else if( eMode==BTALLOC_LE ){
  63100. searchList = 1;
  63101. }
  63102. #endif
  63103. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  63104. ** first free-list trunk page. iPrevTrunk is initially 1.
  63105. */
  63106. rc = sqlite3PagerWrite(pPage1->pDbPage);
  63107. if( rc ) return rc;
  63108. put4byte(&pPage1->aData[36], n-1);
  63109. /* The code within this loop is run only once if the 'searchList' variable
  63110. ** is not true. Otherwise, it runs once for each trunk-page on the
  63111. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  63112. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  63113. */
  63114. do {
  63115. pPrevTrunk = pTrunk;
  63116. if( pPrevTrunk ){
  63117. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  63118. ** is the page number of the next freelist trunk page in the list or
  63119. ** zero if this is the last freelist trunk page. */
  63120. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  63121. }else{
  63122. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  63123. ** stores the page number of the first page of the freelist, or zero if
  63124. ** the freelist is empty. */
  63125. iTrunk = get4byte(&pPage1->aData[32]);
  63126. }
  63127. testcase( iTrunk==mxPage );
  63128. if( iTrunk>mxPage || nSearch++ > n ){
  63129. rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
  63130. }else{
  63131. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  63132. }
  63133. if( rc ){
  63134. pTrunk = 0;
  63135. goto end_allocate_page;
  63136. }
  63137. assert( pTrunk!=0 );
  63138. assert( pTrunk->aData!=0 );
  63139. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  63140. ** is the number of leaf page pointers to follow. */
  63141. k = get4byte(&pTrunk->aData[4]);
  63142. if( k==0 && !searchList ){
  63143. /* The trunk has no leaves and the list is not being searched.
  63144. ** So extract the trunk page itself and use it as the newly
  63145. ** allocated page */
  63146. assert( pPrevTrunk==0 );
  63147. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  63148. if( rc ){
  63149. goto end_allocate_page;
  63150. }
  63151. *pPgno = iTrunk;
  63152. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  63153. *ppPage = pTrunk;
  63154. pTrunk = 0;
  63155. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  63156. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  63157. /* Value of k is out of range. Database corruption */
  63158. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  63159. goto end_allocate_page;
  63160. #ifndef SQLITE_OMIT_AUTOVACUUM
  63161. }else if( searchList
  63162. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  63163. ){
  63164. /* The list is being searched and this trunk page is the page
  63165. ** to allocate, regardless of whether it has leaves.
  63166. */
  63167. *pPgno = iTrunk;
  63168. *ppPage = pTrunk;
  63169. searchList = 0;
  63170. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  63171. if( rc ){
  63172. goto end_allocate_page;
  63173. }
  63174. if( k==0 ){
  63175. if( !pPrevTrunk ){
  63176. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  63177. }else{
  63178. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  63179. if( rc!=SQLITE_OK ){
  63180. goto end_allocate_page;
  63181. }
  63182. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  63183. }
  63184. }else{
  63185. /* The trunk page is required by the caller but it contains
  63186. ** pointers to free-list leaves. The first leaf becomes a trunk
  63187. ** page in this case.
  63188. */
  63189. MemPage *pNewTrunk;
  63190. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  63191. if( iNewTrunk>mxPage ){
  63192. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  63193. goto end_allocate_page;
  63194. }
  63195. testcase( iNewTrunk==mxPage );
  63196. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  63197. if( rc!=SQLITE_OK ){
  63198. goto end_allocate_page;
  63199. }
  63200. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  63201. if( rc!=SQLITE_OK ){
  63202. releasePage(pNewTrunk);
  63203. goto end_allocate_page;
  63204. }
  63205. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  63206. put4byte(&pNewTrunk->aData[4], k-1);
  63207. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  63208. releasePage(pNewTrunk);
  63209. if( !pPrevTrunk ){
  63210. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  63211. put4byte(&pPage1->aData[32], iNewTrunk);
  63212. }else{
  63213. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  63214. if( rc ){
  63215. goto end_allocate_page;
  63216. }
  63217. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  63218. }
  63219. }
  63220. pTrunk = 0;
  63221. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  63222. #endif
  63223. }else if( k>0 ){
  63224. /* Extract a leaf from the trunk */
  63225. u32 closest;
  63226. Pgno iPage;
  63227. unsigned char *aData = pTrunk->aData;
  63228. if( nearby>0 ){
  63229. u32 i;
  63230. closest = 0;
  63231. if( eMode==BTALLOC_LE ){
  63232. for(i=0; i<k; i++){
  63233. iPage = get4byte(&aData[8+i*4]);
  63234. if( iPage<=nearby ){
  63235. closest = i;
  63236. break;
  63237. }
  63238. }
  63239. }else{
  63240. int dist;
  63241. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  63242. for(i=1; i<k; i++){
  63243. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  63244. if( d2<dist ){
  63245. closest = i;
  63246. dist = d2;
  63247. }
  63248. }
  63249. }
  63250. }else{
  63251. closest = 0;
  63252. }
  63253. iPage = get4byte(&aData[8+closest*4]);
  63254. testcase( iPage==mxPage );
  63255. if( iPage>mxPage ){
  63256. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  63257. goto end_allocate_page;
  63258. }
  63259. testcase( iPage==mxPage );
  63260. if( !searchList
  63261. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  63262. ){
  63263. int noContent;
  63264. *pPgno = iPage;
  63265. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  63266. ": %d more free pages\n",
  63267. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  63268. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  63269. if( rc ) goto end_allocate_page;
  63270. if( closest<k-1 ){
  63271. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  63272. }
  63273. put4byte(&aData[4], k-1);
  63274. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  63275. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  63276. if( rc==SQLITE_OK ){
  63277. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  63278. if( rc!=SQLITE_OK ){
  63279. releasePage(*ppPage);
  63280. *ppPage = 0;
  63281. }
  63282. }
  63283. searchList = 0;
  63284. }
  63285. }
  63286. releasePage(pPrevTrunk);
  63287. pPrevTrunk = 0;
  63288. }while( searchList );
  63289. }else{
  63290. /* There are no pages on the freelist, so append a new page to the
  63291. ** database image.
  63292. **
  63293. ** Normally, new pages allocated by this block can be requested from the
  63294. ** pager layer with the 'no-content' flag set. This prevents the pager
  63295. ** from trying to read the pages content from disk. However, if the
  63296. ** current transaction has already run one or more incremental-vacuum
  63297. ** steps, then the page we are about to allocate may contain content
  63298. ** that is required in the event of a rollback. In this case, do
  63299. ** not set the no-content flag. This causes the pager to load and journal
  63300. ** the current page content before overwriting it.
  63301. **
  63302. ** Note that the pager will not actually attempt to load or journal
  63303. ** content for any page that really does lie past the end of the database
  63304. ** file on disk. So the effects of disabling the no-content optimization
  63305. ** here are confined to those pages that lie between the end of the
  63306. ** database image and the end of the database file.
  63307. */
  63308. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  63309. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  63310. if( rc ) return rc;
  63311. pBt->nPage++;
  63312. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  63313. #ifndef SQLITE_OMIT_AUTOVACUUM
  63314. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  63315. /* If *pPgno refers to a pointer-map page, allocate two new pages
  63316. ** at the end of the file instead of one. The first allocated page
  63317. ** becomes a new pointer-map page, the second is used by the caller.
  63318. */
  63319. MemPage *pPg = 0;
  63320. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  63321. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  63322. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  63323. if( rc==SQLITE_OK ){
  63324. rc = sqlite3PagerWrite(pPg->pDbPage);
  63325. releasePage(pPg);
  63326. }
  63327. if( rc ) return rc;
  63328. pBt->nPage++;
  63329. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  63330. }
  63331. #endif
  63332. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  63333. *pPgno = pBt->nPage;
  63334. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  63335. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  63336. if( rc ) return rc;
  63337. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  63338. if( rc!=SQLITE_OK ){
  63339. releasePage(*ppPage);
  63340. *ppPage = 0;
  63341. }
  63342. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  63343. }
  63344. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  63345. end_allocate_page:
  63346. releasePage(pTrunk);
  63347. releasePage(pPrevTrunk);
  63348. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  63349. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  63350. return rc;
  63351. }
  63352. /*
  63353. ** This function is used to add page iPage to the database file free-list.
  63354. ** It is assumed that the page is not already a part of the free-list.
  63355. **
  63356. ** The value passed as the second argument to this function is optional.
  63357. ** If the caller happens to have a pointer to the MemPage object
  63358. ** corresponding to page iPage handy, it may pass it as the second value.
  63359. ** Otherwise, it may pass NULL.
  63360. **
  63361. ** If a pointer to a MemPage object is passed as the second argument,
  63362. ** its reference count is not altered by this function.
  63363. */
  63364. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  63365. MemPage *pTrunk = 0; /* Free-list trunk page */
  63366. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  63367. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  63368. MemPage *pPage; /* Page being freed. May be NULL. */
  63369. int rc; /* Return Code */
  63370. int nFree; /* Initial number of pages on free-list */
  63371. assert( sqlite3_mutex_held(pBt->mutex) );
  63372. assert( CORRUPT_DB || iPage>1 );
  63373. assert( !pMemPage || pMemPage->pgno==iPage );
  63374. if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
  63375. if( pMemPage ){
  63376. pPage = pMemPage;
  63377. sqlite3PagerRef(pPage->pDbPage);
  63378. }else{
  63379. pPage = btreePageLookup(pBt, iPage);
  63380. }
  63381. /* Increment the free page count on pPage1 */
  63382. rc = sqlite3PagerWrite(pPage1->pDbPage);
  63383. if( rc ) goto freepage_out;
  63384. nFree = get4byte(&pPage1->aData[36]);
  63385. put4byte(&pPage1->aData[36], nFree+1);
  63386. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  63387. /* If the secure_delete option is enabled, then
  63388. ** always fully overwrite deleted information with zeros.
  63389. */
  63390. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  63391. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  63392. ){
  63393. goto freepage_out;
  63394. }
  63395. memset(pPage->aData, 0, pPage->pBt->pageSize);
  63396. }
  63397. /* If the database supports auto-vacuum, write an entry in the pointer-map
  63398. ** to indicate that the page is free.
  63399. */
  63400. if( ISAUTOVACUUM ){
  63401. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  63402. if( rc ) goto freepage_out;
  63403. }
  63404. /* Now manipulate the actual database free-list structure. There are two
  63405. ** possibilities. If the free-list is currently empty, or if the first
  63406. ** trunk page in the free-list is full, then this page will become a
  63407. ** new free-list trunk page. Otherwise, it will become a leaf of the
  63408. ** first trunk page in the current free-list. This block tests if it
  63409. ** is possible to add the page as a new free-list leaf.
  63410. */
  63411. if( nFree!=0 ){
  63412. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  63413. iTrunk = get4byte(&pPage1->aData[32]);
  63414. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  63415. if( rc!=SQLITE_OK ){
  63416. goto freepage_out;
  63417. }
  63418. nLeaf = get4byte(&pTrunk->aData[4]);
  63419. assert( pBt->usableSize>32 );
  63420. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  63421. rc = SQLITE_CORRUPT_BKPT;
  63422. goto freepage_out;
  63423. }
  63424. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  63425. /* In this case there is room on the trunk page to insert the page
  63426. ** being freed as a new leaf.
  63427. **
  63428. ** Note that the trunk page is not really full until it contains
  63429. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  63430. ** coded. But due to a coding error in versions of SQLite prior to
  63431. ** 3.6.0, databases with freelist trunk pages holding more than
  63432. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  63433. ** to maintain backwards compatibility with older versions of SQLite,
  63434. ** we will continue to restrict the number of entries to usableSize/4 - 8
  63435. ** for now. At some point in the future (once everyone has upgraded
  63436. ** to 3.6.0 or later) we should consider fixing the conditional above
  63437. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  63438. **
  63439. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  63440. ** avoid using the last six entries in the freelist trunk page array in
  63441. ** order that database files created by newer versions of SQLite can be
  63442. ** read by older versions of SQLite.
  63443. */
  63444. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  63445. if( rc==SQLITE_OK ){
  63446. put4byte(&pTrunk->aData[4], nLeaf+1);
  63447. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  63448. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  63449. sqlite3PagerDontWrite(pPage->pDbPage);
  63450. }
  63451. rc = btreeSetHasContent(pBt, iPage);
  63452. }
  63453. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  63454. goto freepage_out;
  63455. }
  63456. }
  63457. /* If control flows to this point, then it was not possible to add the
  63458. ** the page being freed as a leaf page of the first trunk in the free-list.
  63459. ** Possibly because the free-list is empty, or possibly because the
  63460. ** first trunk in the free-list is full. Either way, the page being freed
  63461. ** will become the new first trunk page in the free-list.
  63462. */
  63463. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  63464. goto freepage_out;
  63465. }
  63466. rc = sqlite3PagerWrite(pPage->pDbPage);
  63467. if( rc!=SQLITE_OK ){
  63468. goto freepage_out;
  63469. }
  63470. put4byte(pPage->aData, iTrunk);
  63471. put4byte(&pPage->aData[4], 0);
  63472. put4byte(&pPage1->aData[32], iPage);
  63473. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  63474. freepage_out:
  63475. if( pPage ){
  63476. pPage->isInit = 0;
  63477. }
  63478. releasePage(pPage);
  63479. releasePage(pTrunk);
  63480. return rc;
  63481. }
  63482. static void freePage(MemPage *pPage, int *pRC){
  63483. if( (*pRC)==SQLITE_OK ){
  63484. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  63485. }
  63486. }
  63487. /*
  63488. ** Free any overflow pages associated with the given Cell. Store
  63489. ** size information about the cell in pInfo.
  63490. */
  63491. static int clearCell(
  63492. MemPage *pPage, /* The page that contains the Cell */
  63493. unsigned char *pCell, /* First byte of the Cell */
  63494. CellInfo *pInfo /* Size information about the cell */
  63495. ){
  63496. BtShared *pBt;
  63497. Pgno ovflPgno;
  63498. int rc;
  63499. int nOvfl;
  63500. u32 ovflPageSize;
  63501. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  63502. pPage->xParseCell(pPage, pCell, pInfo);
  63503. if( pInfo->nLocal==pInfo->nPayload ){
  63504. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  63505. }
  63506. if( pCell+pInfo->nSize-1 > pPage->aData+pPage->maskPage ){
  63507. /* Cell extends past end of page */
  63508. return SQLITE_CORRUPT_PAGE(pPage);
  63509. }
  63510. ovflPgno = get4byte(pCell + pInfo->nSize - 4);
  63511. pBt = pPage->pBt;
  63512. assert( pBt->usableSize > 4 );
  63513. ovflPageSize = pBt->usableSize - 4;
  63514. nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
  63515. assert( nOvfl>0 ||
  63516. (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
  63517. );
  63518. while( nOvfl-- ){
  63519. Pgno iNext = 0;
  63520. MemPage *pOvfl = 0;
  63521. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  63522. /* 0 is not a legal page number and page 1 cannot be an
  63523. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  63524. ** file the database must be corrupt. */
  63525. return SQLITE_CORRUPT_BKPT;
  63526. }
  63527. if( nOvfl ){
  63528. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  63529. if( rc ) return rc;
  63530. }
  63531. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  63532. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  63533. ){
  63534. /* There is no reason any cursor should have an outstanding reference
  63535. ** to an overflow page belonging to a cell that is being deleted/updated.
  63536. ** So if there exists more than one reference to this page, then it
  63537. ** must not really be an overflow page and the database must be corrupt.
  63538. ** It is helpful to detect this before calling freePage2(), as
  63539. ** freePage2() may zero the page contents if secure-delete mode is
  63540. ** enabled. If this 'overflow' page happens to be a page that the
  63541. ** caller is iterating through or using in some other way, this
  63542. ** can be problematic.
  63543. */
  63544. rc = SQLITE_CORRUPT_BKPT;
  63545. }else{
  63546. rc = freePage2(pBt, pOvfl, ovflPgno);
  63547. }
  63548. if( pOvfl ){
  63549. sqlite3PagerUnref(pOvfl->pDbPage);
  63550. }
  63551. if( rc ) return rc;
  63552. ovflPgno = iNext;
  63553. }
  63554. return SQLITE_OK;
  63555. }
  63556. /*
  63557. ** Create the byte sequence used to represent a cell on page pPage
  63558. ** and write that byte sequence into pCell[]. Overflow pages are
  63559. ** allocated and filled in as necessary. The calling procedure
  63560. ** is responsible for making sure sufficient space has been allocated
  63561. ** for pCell[].
  63562. **
  63563. ** Note that pCell does not necessary need to point to the pPage->aData
  63564. ** area. pCell might point to some temporary storage. The cell will
  63565. ** be constructed in this temporary area then copied into pPage->aData
  63566. ** later.
  63567. */
  63568. static int fillInCell(
  63569. MemPage *pPage, /* The page that contains the cell */
  63570. unsigned char *pCell, /* Complete text of the cell */
  63571. const BtreePayload *pX, /* Payload with which to construct the cell */
  63572. int *pnSize /* Write cell size here */
  63573. ){
  63574. int nPayload;
  63575. const u8 *pSrc;
  63576. int nSrc, n, rc, mn;
  63577. int spaceLeft;
  63578. MemPage *pToRelease;
  63579. unsigned char *pPrior;
  63580. unsigned char *pPayload;
  63581. BtShared *pBt;
  63582. Pgno pgnoOvfl;
  63583. int nHeader;
  63584. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  63585. /* pPage is not necessarily writeable since pCell might be auxiliary
  63586. ** buffer space that is separate from the pPage buffer area */
  63587. assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
  63588. || sqlite3PagerIswriteable(pPage->pDbPage) );
  63589. /* Fill in the header. */
  63590. nHeader = pPage->childPtrSize;
  63591. if( pPage->intKey ){
  63592. nPayload = pX->nData + pX->nZero;
  63593. pSrc = pX->pData;
  63594. nSrc = pX->nData;
  63595. assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
  63596. nHeader += putVarint32(&pCell[nHeader], nPayload);
  63597. nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
  63598. }else{
  63599. assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
  63600. nSrc = nPayload = (int)pX->nKey;
  63601. pSrc = pX->pKey;
  63602. nHeader += putVarint32(&pCell[nHeader], nPayload);
  63603. }
  63604. /* Fill in the payload */
  63605. pPayload = &pCell[nHeader];
  63606. if( nPayload<=pPage->maxLocal ){
  63607. /* This is the common case where everything fits on the btree page
  63608. ** and no overflow pages are required. */
  63609. n = nHeader + nPayload;
  63610. testcase( n==3 );
  63611. testcase( n==4 );
  63612. if( n<4 ) n = 4;
  63613. *pnSize = n;
  63614. assert( nSrc<=nPayload );
  63615. testcase( nSrc<nPayload );
  63616. memcpy(pPayload, pSrc, nSrc);
  63617. memset(pPayload+nSrc, 0, nPayload-nSrc);
  63618. return SQLITE_OK;
  63619. }
  63620. /* If we reach this point, it means that some of the content will need
  63621. ** to spill onto overflow pages.
  63622. */
  63623. mn = pPage->minLocal;
  63624. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  63625. testcase( n==pPage->maxLocal );
  63626. testcase( n==pPage->maxLocal+1 );
  63627. if( n > pPage->maxLocal ) n = mn;
  63628. spaceLeft = n;
  63629. *pnSize = n + nHeader + 4;
  63630. pPrior = &pCell[nHeader+n];
  63631. pToRelease = 0;
  63632. pgnoOvfl = 0;
  63633. pBt = pPage->pBt;
  63634. /* At this point variables should be set as follows:
  63635. **
  63636. ** nPayload Total payload size in bytes
  63637. ** pPayload Begin writing payload here
  63638. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  63639. ** that means content must spill into overflow pages.
  63640. ** *pnSize Size of the local cell (not counting overflow pages)
  63641. ** pPrior Where to write the pgno of the first overflow page
  63642. **
  63643. ** Use a call to btreeParseCellPtr() to verify that the values above
  63644. ** were computed correctly.
  63645. */
  63646. #ifdef SQLITE_DEBUG
  63647. {
  63648. CellInfo info;
  63649. pPage->xParseCell(pPage, pCell, &info);
  63650. assert( nHeader==(int)(info.pPayload - pCell) );
  63651. assert( info.nKey==pX->nKey );
  63652. assert( *pnSize == info.nSize );
  63653. assert( spaceLeft == info.nLocal );
  63654. }
  63655. #endif
  63656. /* Write the payload into the local Cell and any extra into overflow pages */
  63657. while( 1 ){
  63658. n = nPayload;
  63659. if( n>spaceLeft ) n = spaceLeft;
  63660. /* If pToRelease is not zero than pPayload points into the data area
  63661. ** of pToRelease. Make sure pToRelease is still writeable. */
  63662. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  63663. /* If pPayload is part of the data area of pPage, then make sure pPage
  63664. ** is still writeable */
  63665. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  63666. || sqlite3PagerIswriteable(pPage->pDbPage) );
  63667. if( nSrc>=n ){
  63668. memcpy(pPayload, pSrc, n);
  63669. }else if( nSrc>0 ){
  63670. n = nSrc;
  63671. memcpy(pPayload, pSrc, n);
  63672. }else{
  63673. memset(pPayload, 0, n);
  63674. }
  63675. nPayload -= n;
  63676. if( nPayload<=0 ) break;
  63677. pPayload += n;
  63678. pSrc += n;
  63679. nSrc -= n;
  63680. spaceLeft -= n;
  63681. if( spaceLeft==0 ){
  63682. MemPage *pOvfl = 0;
  63683. #ifndef SQLITE_OMIT_AUTOVACUUM
  63684. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  63685. if( pBt->autoVacuum ){
  63686. do{
  63687. pgnoOvfl++;
  63688. } while(
  63689. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  63690. );
  63691. }
  63692. #endif
  63693. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  63694. #ifndef SQLITE_OMIT_AUTOVACUUM
  63695. /* If the database supports auto-vacuum, and the second or subsequent
  63696. ** overflow page is being allocated, add an entry to the pointer-map
  63697. ** for that page now.
  63698. **
  63699. ** If this is the first overflow page, then write a partial entry
  63700. ** to the pointer-map. If we write nothing to this pointer-map slot,
  63701. ** then the optimistic overflow chain processing in clearCell()
  63702. ** may misinterpret the uninitialized values and delete the
  63703. ** wrong pages from the database.
  63704. */
  63705. if( pBt->autoVacuum && rc==SQLITE_OK ){
  63706. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  63707. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  63708. if( rc ){
  63709. releasePage(pOvfl);
  63710. }
  63711. }
  63712. #endif
  63713. if( rc ){
  63714. releasePage(pToRelease);
  63715. return rc;
  63716. }
  63717. /* If pToRelease is not zero than pPrior points into the data area
  63718. ** of pToRelease. Make sure pToRelease is still writeable. */
  63719. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  63720. /* If pPrior is part of the data area of pPage, then make sure pPage
  63721. ** is still writeable */
  63722. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  63723. || sqlite3PagerIswriteable(pPage->pDbPage) );
  63724. put4byte(pPrior, pgnoOvfl);
  63725. releasePage(pToRelease);
  63726. pToRelease = pOvfl;
  63727. pPrior = pOvfl->aData;
  63728. put4byte(pPrior, 0);
  63729. pPayload = &pOvfl->aData[4];
  63730. spaceLeft = pBt->usableSize - 4;
  63731. }
  63732. }
  63733. releasePage(pToRelease);
  63734. return SQLITE_OK;
  63735. }
  63736. /*
  63737. ** Remove the i-th cell from pPage. This routine effects pPage only.
  63738. ** The cell content is not freed or deallocated. It is assumed that
  63739. ** the cell content has been copied someplace else. This routine just
  63740. ** removes the reference to the cell from pPage.
  63741. **
  63742. ** "sz" must be the number of bytes in the cell.
  63743. */
  63744. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  63745. u32 pc; /* Offset to cell content of cell being deleted */
  63746. u8 *data; /* pPage->aData */
  63747. u8 *ptr; /* Used to move bytes around within data[] */
  63748. int rc; /* The return code */
  63749. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  63750. if( *pRC ) return;
  63751. assert( idx>=0 && idx<pPage->nCell );
  63752. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  63753. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  63754. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  63755. data = pPage->aData;
  63756. ptr = &pPage->aCellIdx[2*idx];
  63757. pc = get2byte(ptr);
  63758. hdr = pPage->hdrOffset;
  63759. testcase( pc==get2byte(&data[hdr+5]) );
  63760. testcase( pc+sz==pPage->pBt->usableSize );
  63761. if( pc+sz > pPage->pBt->usableSize ){
  63762. *pRC = SQLITE_CORRUPT_BKPT;
  63763. return;
  63764. }
  63765. rc = freeSpace(pPage, pc, sz);
  63766. if( rc ){
  63767. *pRC = rc;
  63768. return;
  63769. }
  63770. pPage->nCell--;
  63771. if( pPage->nCell==0 ){
  63772. memset(&data[hdr+1], 0, 4);
  63773. data[hdr+7] = 0;
  63774. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  63775. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  63776. - pPage->childPtrSize - 8;
  63777. }else{
  63778. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  63779. put2byte(&data[hdr+3], pPage->nCell);
  63780. pPage->nFree += 2;
  63781. }
  63782. }
  63783. /*
  63784. ** Insert a new cell on pPage at cell index "i". pCell points to the
  63785. ** content of the cell.
  63786. **
  63787. ** If the cell content will fit on the page, then put it there. If it
  63788. ** will not fit, then make a copy of the cell content into pTemp if
  63789. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  63790. ** in pPage->apOvfl[] and make it point to the cell content (either
  63791. ** in pTemp or the original pCell) and also record its index.
  63792. ** Allocating a new entry in pPage->aCell[] implies that
  63793. ** pPage->nOverflow is incremented.
  63794. **
  63795. ** *pRC must be SQLITE_OK when this routine is called.
  63796. */
  63797. static void insertCell(
  63798. MemPage *pPage, /* Page into which we are copying */
  63799. int i, /* New cell becomes the i-th cell of the page */
  63800. u8 *pCell, /* Content of the new cell */
  63801. int sz, /* Bytes of content in pCell */
  63802. u8 *pTemp, /* Temp storage space for pCell, if needed */
  63803. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  63804. int *pRC /* Read and write return code from here */
  63805. ){
  63806. int idx = 0; /* Where to write new cell content in data[] */
  63807. int j; /* Loop counter */
  63808. u8 *data; /* The content of the whole page */
  63809. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  63810. assert( *pRC==SQLITE_OK );
  63811. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  63812. assert( MX_CELL(pPage->pBt)<=10921 );
  63813. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  63814. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  63815. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  63816. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  63817. /* The cell should normally be sized correctly. However, when moving a
  63818. ** malformed cell from a leaf page to an interior page, if the cell size
  63819. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  63820. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  63821. ** the term after the || in the following assert(). */
  63822. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  63823. if( pPage->nOverflow || sz+2>pPage->nFree ){
  63824. if( pTemp ){
  63825. memcpy(pTemp, pCell, sz);
  63826. pCell = pTemp;
  63827. }
  63828. if( iChild ){
  63829. put4byte(pCell, iChild);
  63830. }
  63831. j = pPage->nOverflow++;
  63832. /* Comparison against ArraySize-1 since we hold back one extra slot
  63833. ** as a contingency. In other words, never need more than 3 overflow
  63834. ** slots but 4 are allocated, just to be safe. */
  63835. assert( j < ArraySize(pPage->apOvfl)-1 );
  63836. pPage->apOvfl[j] = pCell;
  63837. pPage->aiOvfl[j] = (u16)i;
  63838. /* When multiple overflows occur, they are always sequential and in
  63839. ** sorted order. This invariants arise because multiple overflows can
  63840. ** only occur when inserting divider cells into the parent page during
  63841. ** balancing, and the dividers are adjacent and sorted.
  63842. */
  63843. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  63844. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  63845. }else{
  63846. int rc = sqlite3PagerWrite(pPage->pDbPage);
  63847. if( rc!=SQLITE_OK ){
  63848. *pRC = rc;
  63849. return;
  63850. }
  63851. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  63852. data = pPage->aData;
  63853. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  63854. rc = allocateSpace(pPage, sz, &idx);
  63855. if( rc ){ *pRC = rc; return; }
  63856. /* The allocateSpace() routine guarantees the following properties
  63857. ** if it returns successfully */
  63858. assert( idx >= 0 );
  63859. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  63860. assert( idx+sz <= (int)pPage->pBt->usableSize );
  63861. pPage->nFree -= (u16)(2 + sz);
  63862. memcpy(&data[idx], pCell, sz);
  63863. if( iChild ){
  63864. put4byte(&data[idx], iChild);
  63865. }
  63866. pIns = pPage->aCellIdx + i*2;
  63867. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  63868. put2byte(pIns, idx);
  63869. pPage->nCell++;
  63870. /* increment the cell count */
  63871. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  63872. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
  63873. #ifndef SQLITE_OMIT_AUTOVACUUM
  63874. if( pPage->pBt->autoVacuum ){
  63875. /* The cell may contain a pointer to an overflow page. If so, write
  63876. ** the entry for the overflow page into the pointer map.
  63877. */
  63878. ptrmapPutOvflPtr(pPage, pCell, pRC);
  63879. }
  63880. #endif
  63881. }
  63882. }
  63883. /*
  63884. ** A CellArray object contains a cache of pointers and sizes for a
  63885. ** consecutive sequence of cells that might be held on multiple pages.
  63886. */
  63887. typedef struct CellArray CellArray;
  63888. struct CellArray {
  63889. int nCell; /* Number of cells in apCell[] */
  63890. MemPage *pRef; /* Reference page */
  63891. u8 **apCell; /* All cells begin balanced */
  63892. u16 *szCell; /* Local size of all cells in apCell[] */
  63893. };
  63894. /*
  63895. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  63896. ** computed.
  63897. */
  63898. static void populateCellCache(CellArray *p, int idx, int N){
  63899. assert( idx>=0 && idx+N<=p->nCell );
  63900. while( N>0 ){
  63901. assert( p->apCell[idx]!=0 );
  63902. if( p->szCell[idx]==0 ){
  63903. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  63904. }else{
  63905. assert( CORRUPT_DB ||
  63906. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  63907. }
  63908. idx++;
  63909. N--;
  63910. }
  63911. }
  63912. /*
  63913. ** Return the size of the Nth element of the cell array
  63914. */
  63915. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  63916. assert( N>=0 && N<p->nCell );
  63917. assert( p->szCell[N]==0 );
  63918. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  63919. return p->szCell[N];
  63920. }
  63921. static u16 cachedCellSize(CellArray *p, int N){
  63922. assert( N>=0 && N<p->nCell );
  63923. if( p->szCell[N] ) return p->szCell[N];
  63924. return computeCellSize(p, N);
  63925. }
  63926. /*
  63927. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  63928. ** szCell[] array contains the size in bytes of each cell. This function
  63929. ** replaces the current contents of page pPg with the contents of the cell
  63930. ** array.
  63931. **
  63932. ** Some of the cells in apCell[] may currently be stored in pPg. This
  63933. ** function works around problems caused by this by making a copy of any
  63934. ** such cells before overwriting the page data.
  63935. **
  63936. ** The MemPage.nFree field is invalidated by this function. It is the
  63937. ** responsibility of the caller to set it correctly.
  63938. */
  63939. static int rebuildPage(
  63940. MemPage *pPg, /* Edit this page */
  63941. int nCell, /* Final number of cells on page */
  63942. u8 **apCell, /* Array of cells */
  63943. u16 *szCell /* Array of cell sizes */
  63944. ){
  63945. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  63946. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  63947. const int usableSize = pPg->pBt->usableSize;
  63948. u8 * const pEnd = &aData[usableSize];
  63949. int i;
  63950. u8 *pCellptr = pPg->aCellIdx;
  63951. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  63952. u8 *pData;
  63953. i = get2byte(&aData[hdr+5]);
  63954. memcpy(&pTmp[i], &aData[i], usableSize - i);
  63955. pData = pEnd;
  63956. for(i=0; i<nCell; i++){
  63957. u8 *pCell = apCell[i];
  63958. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  63959. pCell = &pTmp[pCell - aData];
  63960. }
  63961. pData -= szCell[i];
  63962. put2byte(pCellptr, (pData - aData));
  63963. pCellptr += 2;
  63964. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  63965. memcpy(pData, pCell, szCell[i]);
  63966. assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  63967. testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
  63968. }
  63969. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  63970. pPg->nCell = nCell;
  63971. pPg->nOverflow = 0;
  63972. put2byte(&aData[hdr+1], 0);
  63973. put2byte(&aData[hdr+3], pPg->nCell);
  63974. put2byte(&aData[hdr+5], pData - aData);
  63975. aData[hdr+7] = 0x00;
  63976. return SQLITE_OK;
  63977. }
  63978. /*
  63979. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  63980. ** contains the size in bytes of each such cell. This function attempts to
  63981. ** add the cells stored in the array to page pPg. If it cannot (because
  63982. ** the page needs to be defragmented before the cells will fit), non-zero
  63983. ** is returned. Otherwise, if the cells are added successfully, zero is
  63984. ** returned.
  63985. **
  63986. ** Argument pCellptr points to the first entry in the cell-pointer array
  63987. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  63988. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  63989. ** cell in the array. It is the responsibility of the caller to ensure
  63990. ** that it is safe to overwrite this part of the cell-pointer array.
  63991. **
  63992. ** When this function is called, *ppData points to the start of the
  63993. ** content area on page pPg. If the size of the content area is extended,
  63994. ** *ppData is updated to point to the new start of the content area
  63995. ** before returning.
  63996. **
  63997. ** Finally, argument pBegin points to the byte immediately following the
  63998. ** end of the space required by this page for the cell-pointer area (for
  63999. ** all cells - not just those inserted by the current call). If the content
  64000. ** area must be extended to before this point in order to accomodate all
  64001. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  64002. */
  64003. static int pageInsertArray(
  64004. MemPage *pPg, /* Page to add cells to */
  64005. u8 *pBegin, /* End of cell-pointer array */
  64006. u8 **ppData, /* IN/OUT: Page content -area pointer */
  64007. u8 *pCellptr, /* Pointer to cell-pointer area */
  64008. int iFirst, /* Index of first cell to add */
  64009. int nCell, /* Number of cells to add to pPg */
  64010. CellArray *pCArray /* Array of cells */
  64011. ){
  64012. int i;
  64013. u8 *aData = pPg->aData;
  64014. u8 *pData = *ppData;
  64015. int iEnd = iFirst + nCell;
  64016. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  64017. for(i=iFirst; i<iEnd; i++){
  64018. int sz, rc;
  64019. u8 *pSlot;
  64020. sz = cachedCellSize(pCArray, i);
  64021. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  64022. if( (pData - pBegin)<sz ) return 1;
  64023. pData -= sz;
  64024. pSlot = pData;
  64025. }
  64026. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  64027. ** database. But they might for a corrupt database. Hence use memmove()
  64028. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  64029. assert( (pSlot+sz)<=pCArray->apCell[i]
  64030. || pSlot>=(pCArray->apCell[i]+sz)
  64031. || CORRUPT_DB );
  64032. memmove(pSlot, pCArray->apCell[i], sz);
  64033. put2byte(pCellptr, (pSlot - aData));
  64034. pCellptr += 2;
  64035. }
  64036. *ppData = pData;
  64037. return 0;
  64038. }
  64039. /*
  64040. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  64041. ** contains the size in bytes of each such cell. This function adds the
  64042. ** space associated with each cell in the array that is currently stored
  64043. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  64044. ** fields of the page are not updated.
  64045. **
  64046. ** This function returns the total number of cells added to the free-list.
  64047. */
  64048. static int pageFreeArray(
  64049. MemPage *pPg, /* Page to edit */
  64050. int iFirst, /* First cell to delete */
  64051. int nCell, /* Cells to delete */
  64052. CellArray *pCArray /* Array of cells */
  64053. ){
  64054. u8 * const aData = pPg->aData;
  64055. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  64056. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  64057. int nRet = 0;
  64058. int i;
  64059. int iEnd = iFirst + nCell;
  64060. u8 *pFree = 0;
  64061. int szFree = 0;
  64062. for(i=iFirst; i<iEnd; i++){
  64063. u8 *pCell = pCArray->apCell[i];
  64064. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  64065. int sz;
  64066. /* No need to use cachedCellSize() here. The sizes of all cells that
  64067. ** are to be freed have already been computing while deciding which
  64068. ** cells need freeing */
  64069. sz = pCArray->szCell[i]; assert( sz>0 );
  64070. if( pFree!=(pCell + sz) ){
  64071. if( pFree ){
  64072. assert( pFree>aData && (pFree - aData)<65536 );
  64073. freeSpace(pPg, (u16)(pFree - aData), szFree);
  64074. }
  64075. pFree = pCell;
  64076. szFree = sz;
  64077. if( pFree+sz>pEnd ) return 0;
  64078. }else{
  64079. pFree = pCell;
  64080. szFree += sz;
  64081. }
  64082. nRet++;
  64083. }
  64084. }
  64085. if( pFree ){
  64086. assert( pFree>aData && (pFree - aData)<65536 );
  64087. freeSpace(pPg, (u16)(pFree - aData), szFree);
  64088. }
  64089. return nRet;
  64090. }
  64091. /*
  64092. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  64093. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  64094. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  64095. ** starting at apCell[iNew].
  64096. **
  64097. ** This routine makes the necessary adjustments to pPg so that it contains
  64098. ** the correct cells after being balanced.
  64099. **
  64100. ** The pPg->nFree field is invalid when this function returns. It is the
  64101. ** responsibility of the caller to set it correctly.
  64102. */
  64103. static int editPage(
  64104. MemPage *pPg, /* Edit this page */
  64105. int iOld, /* Index of first cell currently on page */
  64106. int iNew, /* Index of new first cell on page */
  64107. int nNew, /* Final number of cells on page */
  64108. CellArray *pCArray /* Array of cells and sizes */
  64109. ){
  64110. u8 * const aData = pPg->aData;
  64111. const int hdr = pPg->hdrOffset;
  64112. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  64113. int nCell = pPg->nCell; /* Cells stored on pPg */
  64114. u8 *pData;
  64115. u8 *pCellptr;
  64116. int i;
  64117. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  64118. int iNewEnd = iNew + nNew;
  64119. #ifdef SQLITE_DEBUG
  64120. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  64121. memcpy(pTmp, aData, pPg->pBt->usableSize);
  64122. #endif
  64123. /* Remove cells from the start and end of the page */
  64124. if( iOld<iNew ){
  64125. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  64126. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  64127. nCell -= nShift;
  64128. }
  64129. if( iNewEnd < iOldEnd ){
  64130. nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  64131. }
  64132. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  64133. if( pData<pBegin ) goto editpage_fail;
  64134. /* Add cells to the start of the page */
  64135. if( iNew<iOld ){
  64136. int nAdd = MIN(nNew,iOld-iNew);
  64137. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  64138. pCellptr = pPg->aCellIdx;
  64139. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  64140. if( pageInsertArray(
  64141. pPg, pBegin, &pData, pCellptr,
  64142. iNew, nAdd, pCArray
  64143. ) ) goto editpage_fail;
  64144. nCell += nAdd;
  64145. }
  64146. /* Add any overflow cells */
  64147. for(i=0; i<pPg->nOverflow; i++){
  64148. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  64149. if( iCell>=0 && iCell<nNew ){
  64150. pCellptr = &pPg->aCellIdx[iCell * 2];
  64151. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  64152. nCell++;
  64153. if( pageInsertArray(
  64154. pPg, pBegin, &pData, pCellptr,
  64155. iCell+iNew, 1, pCArray
  64156. ) ) goto editpage_fail;
  64157. }
  64158. }
  64159. /* Append cells to the end of the page */
  64160. pCellptr = &pPg->aCellIdx[nCell*2];
  64161. if( pageInsertArray(
  64162. pPg, pBegin, &pData, pCellptr,
  64163. iNew+nCell, nNew-nCell, pCArray
  64164. ) ) goto editpage_fail;
  64165. pPg->nCell = nNew;
  64166. pPg->nOverflow = 0;
  64167. put2byte(&aData[hdr+3], pPg->nCell);
  64168. put2byte(&aData[hdr+5], pData - aData);
  64169. #ifdef SQLITE_DEBUG
  64170. for(i=0; i<nNew && !CORRUPT_DB; i++){
  64171. u8 *pCell = pCArray->apCell[i+iNew];
  64172. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  64173. if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
  64174. pCell = &pTmp[pCell - aData];
  64175. }
  64176. assert( 0==memcmp(pCell, &aData[iOff],
  64177. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  64178. }
  64179. #endif
  64180. return SQLITE_OK;
  64181. editpage_fail:
  64182. /* Unable to edit this page. Rebuild it from scratch instead. */
  64183. populateCellCache(pCArray, iNew, nNew);
  64184. return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
  64185. }
  64186. /*
  64187. ** The following parameters determine how many adjacent pages get involved
  64188. ** in a balancing operation. NN is the number of neighbors on either side
  64189. ** of the page that participate in the balancing operation. NB is the
  64190. ** total number of pages that participate, including the target page and
  64191. ** NN neighbors on either side.
  64192. **
  64193. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  64194. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  64195. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  64196. ** The value of NN appears to give the best results overall.
  64197. */
  64198. #define NN 1 /* Number of neighbors on either side of pPage */
  64199. #define NB (NN*2+1) /* Total pages involved in the balance */
  64200. #ifndef SQLITE_OMIT_QUICKBALANCE
  64201. /*
  64202. ** This version of balance() handles the common special case where
  64203. ** a new entry is being inserted on the extreme right-end of the
  64204. ** tree, in other words, when the new entry will become the largest
  64205. ** entry in the tree.
  64206. **
  64207. ** Instead of trying to balance the 3 right-most leaf pages, just add
  64208. ** a new page to the right-hand side and put the one new entry in
  64209. ** that page. This leaves the right side of the tree somewhat
  64210. ** unbalanced. But odds are that we will be inserting new entries
  64211. ** at the end soon afterwards so the nearly empty page will quickly
  64212. ** fill up. On average.
  64213. **
  64214. ** pPage is the leaf page which is the right-most page in the tree.
  64215. ** pParent is its parent. pPage must have a single overflow entry
  64216. ** which is also the right-most entry on the page.
  64217. **
  64218. ** The pSpace buffer is used to store a temporary copy of the divider
  64219. ** cell that will be inserted into pParent. Such a cell consists of a 4
  64220. ** byte page number followed by a variable length integer. In other
  64221. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  64222. ** least 13 bytes in size.
  64223. */
  64224. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  64225. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  64226. MemPage *pNew; /* Newly allocated page */
  64227. int rc; /* Return Code */
  64228. Pgno pgnoNew; /* Page number of pNew */
  64229. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  64230. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  64231. assert( pPage->nOverflow==1 );
  64232. /* This error condition is now caught prior to reaching this function */
  64233. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  64234. /* Allocate a new page. This page will become the right-sibling of
  64235. ** pPage. Make the parent page writable, so that the new divider cell
  64236. ** may be inserted. If both these operations are successful, proceed.
  64237. */
  64238. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  64239. if( rc==SQLITE_OK ){
  64240. u8 *pOut = &pSpace[4];
  64241. u8 *pCell = pPage->apOvfl[0];
  64242. u16 szCell = pPage->xCellSize(pPage, pCell);
  64243. u8 *pStop;
  64244. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  64245. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  64246. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  64247. rc = rebuildPage(pNew, 1, &pCell, &szCell);
  64248. if( NEVER(rc) ) return rc;
  64249. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  64250. /* If this is an auto-vacuum database, update the pointer map
  64251. ** with entries for the new page, and any pointer from the
  64252. ** cell on the page to an overflow page. If either of these
  64253. ** operations fails, the return code is set, but the contents
  64254. ** of the parent page are still manipulated by thh code below.
  64255. ** That is Ok, at this point the parent page is guaranteed to
  64256. ** be marked as dirty. Returning an error code will cause a
  64257. ** rollback, undoing any changes made to the parent page.
  64258. */
  64259. if( ISAUTOVACUUM ){
  64260. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  64261. if( szCell>pNew->minLocal ){
  64262. ptrmapPutOvflPtr(pNew, pCell, &rc);
  64263. }
  64264. }
  64265. /* Create a divider cell to insert into pParent. The divider cell
  64266. ** consists of a 4-byte page number (the page number of pPage) and
  64267. ** a variable length key value (which must be the same value as the
  64268. ** largest key on pPage).
  64269. **
  64270. ** To find the largest key value on pPage, first find the right-most
  64271. ** cell on pPage. The first two fields of this cell are the
  64272. ** record-length (a variable length integer at most 32-bits in size)
  64273. ** and the key value (a variable length integer, may have any value).
  64274. ** The first of the while(...) loops below skips over the record-length
  64275. ** field. The second while(...) loop copies the key value from the
  64276. ** cell on pPage into the pSpace buffer.
  64277. */
  64278. pCell = findCell(pPage, pPage->nCell-1);
  64279. pStop = &pCell[9];
  64280. while( (*(pCell++)&0x80) && pCell<pStop );
  64281. pStop = &pCell[9];
  64282. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  64283. /* Insert the new divider cell into pParent. */
  64284. if( rc==SQLITE_OK ){
  64285. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  64286. 0, pPage->pgno, &rc);
  64287. }
  64288. /* Set the right-child pointer of pParent to point to the new page. */
  64289. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  64290. /* Release the reference to the new page. */
  64291. releasePage(pNew);
  64292. }
  64293. return rc;
  64294. }
  64295. #endif /* SQLITE_OMIT_QUICKBALANCE */
  64296. #if 0
  64297. /*
  64298. ** This function does not contribute anything to the operation of SQLite.
  64299. ** it is sometimes activated temporarily while debugging code responsible
  64300. ** for setting pointer-map entries.
  64301. */
  64302. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  64303. int i, j;
  64304. for(i=0; i<nPage; i++){
  64305. Pgno n;
  64306. u8 e;
  64307. MemPage *pPage = apPage[i];
  64308. BtShared *pBt = pPage->pBt;
  64309. assert( pPage->isInit );
  64310. for(j=0; j<pPage->nCell; j++){
  64311. CellInfo info;
  64312. u8 *z;
  64313. z = findCell(pPage, j);
  64314. pPage->xParseCell(pPage, z, &info);
  64315. if( info.nLocal<info.nPayload ){
  64316. Pgno ovfl = get4byte(&z[info.nSize-4]);
  64317. ptrmapGet(pBt, ovfl, &e, &n);
  64318. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  64319. }
  64320. if( !pPage->leaf ){
  64321. Pgno child = get4byte(z);
  64322. ptrmapGet(pBt, child, &e, &n);
  64323. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  64324. }
  64325. }
  64326. if( !pPage->leaf ){
  64327. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  64328. ptrmapGet(pBt, child, &e, &n);
  64329. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  64330. }
  64331. }
  64332. return 1;
  64333. }
  64334. #endif
  64335. /*
  64336. ** This function is used to copy the contents of the b-tree node stored
  64337. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  64338. ** the pointer-map entries for each child page are updated so that the
  64339. ** parent page stored in the pointer map is page pTo. If pFrom contained
  64340. ** any cells with overflow page pointers, then the corresponding pointer
  64341. ** map entries are also updated so that the parent page is page pTo.
  64342. **
  64343. ** If pFrom is currently carrying any overflow cells (entries in the
  64344. ** MemPage.apOvfl[] array), they are not copied to pTo.
  64345. **
  64346. ** Before returning, page pTo is reinitialized using btreeInitPage().
  64347. **
  64348. ** The performance of this function is not critical. It is only used by
  64349. ** the balance_shallower() and balance_deeper() procedures, neither of
  64350. ** which are called often under normal circumstances.
  64351. */
  64352. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  64353. if( (*pRC)==SQLITE_OK ){
  64354. BtShared * const pBt = pFrom->pBt;
  64355. u8 * const aFrom = pFrom->aData;
  64356. u8 * const aTo = pTo->aData;
  64357. int const iFromHdr = pFrom->hdrOffset;
  64358. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  64359. int rc;
  64360. int iData;
  64361. assert( pFrom->isInit );
  64362. assert( pFrom->nFree>=iToHdr );
  64363. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  64364. /* Copy the b-tree node content from page pFrom to page pTo. */
  64365. iData = get2byte(&aFrom[iFromHdr+5]);
  64366. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  64367. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  64368. /* Reinitialize page pTo so that the contents of the MemPage structure
  64369. ** match the new data. The initialization of pTo can actually fail under
  64370. ** fairly obscure circumstances, even though it is a copy of initialized
  64371. ** page pFrom.
  64372. */
  64373. pTo->isInit = 0;
  64374. rc = btreeInitPage(pTo);
  64375. if( rc!=SQLITE_OK ){
  64376. *pRC = rc;
  64377. return;
  64378. }
  64379. /* If this is an auto-vacuum database, update the pointer-map entries
  64380. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  64381. */
  64382. if( ISAUTOVACUUM ){
  64383. *pRC = setChildPtrmaps(pTo);
  64384. }
  64385. }
  64386. }
  64387. /*
  64388. ** This routine redistributes cells on the iParentIdx'th child of pParent
  64389. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  64390. ** same amount of free space. Usually a single sibling on either side of the
  64391. ** page are used in the balancing, though both siblings might come from one
  64392. ** side if the page is the first or last child of its parent. If the page
  64393. ** has fewer than 2 siblings (something which can only happen if the page
  64394. ** is a root page or a child of a root page) then all available siblings
  64395. ** participate in the balancing.
  64396. **
  64397. ** The number of siblings of the page might be increased or decreased by
  64398. ** one or two in an effort to keep pages nearly full but not over full.
  64399. **
  64400. ** Note that when this routine is called, some of the cells on the page
  64401. ** might not actually be stored in MemPage.aData[]. This can happen
  64402. ** if the page is overfull. This routine ensures that all cells allocated
  64403. ** to the page and its siblings fit into MemPage.aData[] before returning.
  64404. **
  64405. ** In the course of balancing the page and its siblings, cells may be
  64406. ** inserted into or removed from the parent page (pParent). Doing so
  64407. ** may cause the parent page to become overfull or underfull. If this
  64408. ** happens, it is the responsibility of the caller to invoke the correct
  64409. ** balancing routine to fix this problem (see the balance() routine).
  64410. **
  64411. ** If this routine fails for any reason, it might leave the database
  64412. ** in a corrupted state. So if this routine fails, the database should
  64413. ** be rolled back.
  64414. **
  64415. ** The third argument to this function, aOvflSpace, is a pointer to a
  64416. ** buffer big enough to hold one page. If while inserting cells into the parent
  64417. ** page (pParent) the parent page becomes overfull, this buffer is
  64418. ** used to store the parent's overflow cells. Because this function inserts
  64419. ** a maximum of four divider cells into the parent page, and the maximum
  64420. ** size of a cell stored within an internal node is always less than 1/4
  64421. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  64422. ** enough for all overflow cells.
  64423. **
  64424. ** If aOvflSpace is set to a null pointer, this function returns
  64425. ** SQLITE_NOMEM.
  64426. */
  64427. static int balance_nonroot(
  64428. MemPage *pParent, /* Parent page of siblings being balanced */
  64429. int iParentIdx, /* Index of "the page" in pParent */
  64430. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  64431. int isRoot, /* True if pParent is a root-page */
  64432. int bBulk /* True if this call is part of a bulk load */
  64433. ){
  64434. BtShared *pBt; /* The whole database */
  64435. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  64436. int nNew = 0; /* Number of pages in apNew[] */
  64437. int nOld; /* Number of pages in apOld[] */
  64438. int i, j, k; /* Loop counters */
  64439. int nxDiv; /* Next divider slot in pParent->aCell[] */
  64440. int rc = SQLITE_OK; /* The return code */
  64441. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  64442. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  64443. int usableSpace; /* Bytes in pPage beyond the header */
  64444. int pageFlags; /* Value of pPage->aData[0] */
  64445. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  64446. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  64447. int szScratch; /* Size of scratch memory requested */
  64448. MemPage *apOld[NB]; /* pPage and up to two siblings */
  64449. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  64450. u8 *pRight; /* Location in parent of right-sibling pointer */
  64451. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  64452. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  64453. int cntOld[NB+2]; /* Old index in b.apCell[] */
  64454. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  64455. u8 *aSpace1; /* Space for copies of dividers cells */
  64456. Pgno pgno; /* Temp var to store a page number in */
  64457. u8 abDone[NB+2]; /* True after i'th new page is populated */
  64458. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  64459. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  64460. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  64461. CellArray b; /* Parsed information on cells being balanced */
  64462. memset(abDone, 0, sizeof(abDone));
  64463. b.nCell = 0;
  64464. b.apCell = 0;
  64465. pBt = pParent->pBt;
  64466. assert( sqlite3_mutex_held(pBt->mutex) );
  64467. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  64468. #if 0
  64469. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  64470. #endif
  64471. /* At this point pParent may have at most one overflow cell. And if
  64472. ** this overflow cell is present, it must be the cell with
  64473. ** index iParentIdx. This scenario comes about when this function
  64474. ** is called (indirectly) from sqlite3BtreeDelete().
  64475. */
  64476. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  64477. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  64478. if( !aOvflSpace ){
  64479. return SQLITE_NOMEM_BKPT;
  64480. }
  64481. /* Find the sibling pages to balance. Also locate the cells in pParent
  64482. ** that divide the siblings. An attempt is made to find NN siblings on
  64483. ** either side of pPage. More siblings are taken from one side, however,
  64484. ** if there are fewer than NN siblings on the other side. If pParent
  64485. ** has NB or fewer children then all children of pParent are taken.
  64486. **
  64487. ** This loop also drops the divider cells from the parent page. This
  64488. ** way, the remainder of the function does not have to deal with any
  64489. ** overflow cells in the parent page, since if any existed they will
  64490. ** have already been removed.
  64491. */
  64492. i = pParent->nOverflow + pParent->nCell;
  64493. if( i<2 ){
  64494. nxDiv = 0;
  64495. }else{
  64496. assert( bBulk==0 || bBulk==1 );
  64497. if( iParentIdx==0 ){
  64498. nxDiv = 0;
  64499. }else if( iParentIdx==i ){
  64500. nxDiv = i-2+bBulk;
  64501. }else{
  64502. nxDiv = iParentIdx-1;
  64503. }
  64504. i = 2-bBulk;
  64505. }
  64506. nOld = i+1;
  64507. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  64508. pRight = &pParent->aData[pParent->hdrOffset+8];
  64509. }else{
  64510. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  64511. }
  64512. pgno = get4byte(pRight);
  64513. while( 1 ){
  64514. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  64515. if( rc ){
  64516. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  64517. goto balance_cleanup;
  64518. }
  64519. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  64520. if( (i--)==0 ) break;
  64521. if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
  64522. apDiv[i] = pParent->apOvfl[0];
  64523. pgno = get4byte(apDiv[i]);
  64524. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  64525. pParent->nOverflow = 0;
  64526. }else{
  64527. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  64528. pgno = get4byte(apDiv[i]);
  64529. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  64530. /* Drop the cell from the parent page. apDiv[i] still points to
  64531. ** the cell within the parent, even though it has been dropped.
  64532. ** This is safe because dropping a cell only overwrites the first
  64533. ** four bytes of it, and this function does not need the first
  64534. ** four bytes of the divider cell. So the pointer is safe to use
  64535. ** later on.
  64536. **
  64537. ** But not if we are in secure-delete mode. In secure-delete mode,
  64538. ** the dropCell() routine will overwrite the entire cell with zeroes.
  64539. ** In this case, temporarily copy the cell into the aOvflSpace[]
  64540. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  64541. ** is allocated. */
  64542. if( pBt->btsFlags & BTS_FAST_SECURE ){
  64543. int iOff;
  64544. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  64545. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  64546. rc = SQLITE_CORRUPT_BKPT;
  64547. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  64548. goto balance_cleanup;
  64549. }else{
  64550. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  64551. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  64552. }
  64553. }
  64554. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  64555. }
  64556. }
  64557. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  64558. ** alignment */
  64559. nMaxCells = (nMaxCells + 3)&~3;
  64560. /*
  64561. ** Allocate space for memory structures
  64562. */
  64563. szScratch =
  64564. nMaxCells*sizeof(u8*) /* b.apCell */
  64565. + nMaxCells*sizeof(u16) /* b.szCell */
  64566. + pBt->pageSize; /* aSpace1 */
  64567. assert( szScratch<=6*(int)pBt->pageSize );
  64568. b.apCell = sqlite3StackAllocRaw(0, szScratch );
  64569. if( b.apCell==0 ){
  64570. rc = SQLITE_NOMEM_BKPT;
  64571. goto balance_cleanup;
  64572. }
  64573. b.szCell = (u16*)&b.apCell[nMaxCells];
  64574. aSpace1 = (u8*)&b.szCell[nMaxCells];
  64575. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  64576. /*
  64577. ** Load pointers to all cells on sibling pages and the divider cells
  64578. ** into the local b.apCell[] array. Make copies of the divider cells
  64579. ** into space obtained from aSpace1[]. The divider cells have already
  64580. ** been removed from pParent.
  64581. **
  64582. ** If the siblings are on leaf pages, then the child pointers of the
  64583. ** divider cells are stripped from the cells before they are copied
  64584. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  64585. ** child pointers. If siblings are not leaves, then all cell in
  64586. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  64587. ** are alike.
  64588. **
  64589. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  64590. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  64591. */
  64592. b.pRef = apOld[0];
  64593. leafCorrection = b.pRef->leaf*4;
  64594. leafData = b.pRef->intKeyLeaf;
  64595. for(i=0; i<nOld; i++){
  64596. MemPage *pOld = apOld[i];
  64597. int limit = pOld->nCell;
  64598. u8 *aData = pOld->aData;
  64599. u16 maskPage = pOld->maskPage;
  64600. u8 *piCell = aData + pOld->cellOffset;
  64601. u8 *piEnd;
  64602. /* Verify that all sibling pages are of the same "type" (table-leaf,
  64603. ** table-interior, index-leaf, or index-interior).
  64604. */
  64605. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  64606. rc = SQLITE_CORRUPT_BKPT;
  64607. goto balance_cleanup;
  64608. }
  64609. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  64610. ** contains overflow cells, include them in the b.apCell[] array
  64611. ** in the correct spot.
  64612. **
  64613. ** Note that when there are multiple overflow cells, it is always the
  64614. ** case that they are sequential and adjacent. This invariant arises
  64615. ** because multiple overflows can only occurs when inserting divider
  64616. ** cells into a parent on a prior balance, and divider cells are always
  64617. ** adjacent and are inserted in order. There is an assert() tagged
  64618. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  64619. ** invariant.
  64620. **
  64621. ** This must be done in advance. Once the balance starts, the cell
  64622. ** offset section of the btree page will be overwritten and we will no
  64623. ** long be able to find the cells if a pointer to each cell is not saved
  64624. ** first.
  64625. */
  64626. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
  64627. if( pOld->nOverflow>0 ){
  64628. limit = pOld->aiOvfl[0];
  64629. for(j=0; j<limit; j++){
  64630. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  64631. piCell += 2;
  64632. b.nCell++;
  64633. }
  64634. for(k=0; k<pOld->nOverflow; k++){
  64635. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  64636. b.apCell[b.nCell] = pOld->apOvfl[k];
  64637. b.nCell++;
  64638. }
  64639. }
  64640. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  64641. while( piCell<piEnd ){
  64642. assert( b.nCell<nMaxCells );
  64643. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  64644. piCell += 2;
  64645. b.nCell++;
  64646. }
  64647. cntOld[i] = b.nCell;
  64648. if( i<nOld-1 && !leafData){
  64649. u16 sz = (u16)szNew[i];
  64650. u8 *pTemp;
  64651. assert( b.nCell<nMaxCells );
  64652. b.szCell[b.nCell] = sz;
  64653. pTemp = &aSpace1[iSpace1];
  64654. iSpace1 += sz;
  64655. assert( sz<=pBt->maxLocal+23 );
  64656. assert( iSpace1 <= (int)pBt->pageSize );
  64657. memcpy(pTemp, apDiv[i], sz);
  64658. b.apCell[b.nCell] = pTemp+leafCorrection;
  64659. assert( leafCorrection==0 || leafCorrection==4 );
  64660. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  64661. if( !pOld->leaf ){
  64662. assert( leafCorrection==0 );
  64663. assert( pOld->hdrOffset==0 );
  64664. /* The right pointer of the child page pOld becomes the left
  64665. ** pointer of the divider cell */
  64666. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  64667. }else{
  64668. assert( leafCorrection==4 );
  64669. while( b.szCell[b.nCell]<4 ){
  64670. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  64671. ** does exist, pad it with 0x00 bytes. */
  64672. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  64673. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  64674. aSpace1[iSpace1++] = 0x00;
  64675. b.szCell[b.nCell]++;
  64676. }
  64677. }
  64678. b.nCell++;
  64679. }
  64680. }
  64681. /*
  64682. ** Figure out the number of pages needed to hold all b.nCell cells.
  64683. ** Store this number in "k". Also compute szNew[] which is the total
  64684. ** size of all cells on the i-th page and cntNew[] which is the index
  64685. ** in b.apCell[] of the cell that divides page i from page i+1.
  64686. ** cntNew[k] should equal b.nCell.
  64687. **
  64688. ** Values computed by this block:
  64689. **
  64690. ** k: The total number of sibling pages
  64691. ** szNew[i]: Spaced used on the i-th sibling page.
  64692. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  64693. ** the right of the i-th sibling page.
  64694. ** usableSpace: Number of bytes of space available on each sibling.
  64695. **
  64696. */
  64697. usableSpace = pBt->usableSize - 12 + leafCorrection;
  64698. for(i=0; i<nOld; i++){
  64699. MemPage *p = apOld[i];
  64700. szNew[i] = usableSpace - p->nFree;
  64701. for(j=0; j<p->nOverflow; j++){
  64702. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  64703. }
  64704. cntNew[i] = cntOld[i];
  64705. }
  64706. k = nOld;
  64707. for(i=0; i<k; i++){
  64708. int sz;
  64709. while( szNew[i]>usableSpace ){
  64710. if( i+1>=k ){
  64711. k = i+2;
  64712. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  64713. szNew[k-1] = 0;
  64714. cntNew[k-1] = b.nCell;
  64715. }
  64716. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  64717. szNew[i] -= sz;
  64718. if( !leafData ){
  64719. if( cntNew[i]<b.nCell ){
  64720. sz = 2 + cachedCellSize(&b, cntNew[i]);
  64721. }else{
  64722. sz = 0;
  64723. }
  64724. }
  64725. szNew[i+1] += sz;
  64726. cntNew[i]--;
  64727. }
  64728. while( cntNew[i]<b.nCell ){
  64729. sz = 2 + cachedCellSize(&b, cntNew[i]);
  64730. if( szNew[i]+sz>usableSpace ) break;
  64731. szNew[i] += sz;
  64732. cntNew[i]++;
  64733. if( !leafData ){
  64734. if( cntNew[i]<b.nCell ){
  64735. sz = 2 + cachedCellSize(&b, cntNew[i]);
  64736. }else{
  64737. sz = 0;
  64738. }
  64739. }
  64740. szNew[i+1] -= sz;
  64741. }
  64742. if( cntNew[i]>=b.nCell ){
  64743. k = i+1;
  64744. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  64745. rc = SQLITE_CORRUPT_BKPT;
  64746. goto balance_cleanup;
  64747. }
  64748. }
  64749. /*
  64750. ** The packing computed by the previous block is biased toward the siblings
  64751. ** on the left side (siblings with smaller keys). The left siblings are
  64752. ** always nearly full, while the right-most sibling might be nearly empty.
  64753. ** The next block of code attempts to adjust the packing of siblings to
  64754. ** get a better balance.
  64755. **
  64756. ** This adjustment is more than an optimization. The packing above might
  64757. ** be so out of balance as to be illegal. For example, the right-most
  64758. ** sibling might be completely empty. This adjustment is not optional.
  64759. */
  64760. for(i=k-1; i>0; i--){
  64761. int szRight = szNew[i]; /* Size of sibling on the right */
  64762. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  64763. int r; /* Index of right-most cell in left sibling */
  64764. int d; /* Index of first cell to the left of right sibling */
  64765. r = cntNew[i-1] - 1;
  64766. d = r + 1 - leafData;
  64767. (void)cachedCellSize(&b, d);
  64768. do{
  64769. assert( d<nMaxCells );
  64770. assert( r<nMaxCells );
  64771. (void)cachedCellSize(&b, r);
  64772. if( szRight!=0
  64773. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
  64774. break;
  64775. }
  64776. szRight += b.szCell[d] + 2;
  64777. szLeft -= b.szCell[r] + 2;
  64778. cntNew[i-1] = r;
  64779. r--;
  64780. d--;
  64781. }while( r>=0 );
  64782. szNew[i] = szRight;
  64783. szNew[i-1] = szLeft;
  64784. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  64785. rc = SQLITE_CORRUPT_BKPT;
  64786. goto balance_cleanup;
  64787. }
  64788. }
  64789. /* Sanity check: For a non-corrupt database file one of the follwing
  64790. ** must be true:
  64791. ** (1) We found one or more cells (cntNew[0])>0), or
  64792. ** (2) pPage is a virtual root page. A virtual root page is when
  64793. ** the real root page is page 1 and we are the only child of
  64794. ** that page.
  64795. */
  64796. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  64797. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  64798. apOld[0]->pgno, apOld[0]->nCell,
  64799. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  64800. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  64801. ));
  64802. /*
  64803. ** Allocate k new pages. Reuse old pages where possible.
  64804. */
  64805. pageFlags = apOld[0]->aData[0];
  64806. for(i=0; i<k; i++){
  64807. MemPage *pNew;
  64808. if( i<nOld ){
  64809. pNew = apNew[i] = apOld[i];
  64810. apOld[i] = 0;
  64811. rc = sqlite3PagerWrite(pNew->pDbPage);
  64812. nNew++;
  64813. if( rc ) goto balance_cleanup;
  64814. }else{
  64815. assert( i>0 );
  64816. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  64817. if( rc ) goto balance_cleanup;
  64818. zeroPage(pNew, pageFlags);
  64819. apNew[i] = pNew;
  64820. nNew++;
  64821. cntOld[i] = b.nCell;
  64822. /* Set the pointer-map entry for the new sibling page. */
  64823. if( ISAUTOVACUUM ){
  64824. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  64825. if( rc!=SQLITE_OK ){
  64826. goto balance_cleanup;
  64827. }
  64828. }
  64829. }
  64830. }
  64831. /*
  64832. ** Reassign page numbers so that the new pages are in ascending order.
  64833. ** This helps to keep entries in the disk file in order so that a scan
  64834. ** of the table is closer to a linear scan through the file. That in turn
  64835. ** helps the operating system to deliver pages from the disk more rapidly.
  64836. **
  64837. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  64838. ** than (NB+2) (a small constant), that should not be a problem.
  64839. **
  64840. ** When NB==3, this one optimization makes the database about 25% faster
  64841. ** for large insertions and deletions.
  64842. */
  64843. for(i=0; i<nNew; i++){
  64844. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  64845. aPgFlags[i] = apNew[i]->pDbPage->flags;
  64846. for(j=0; j<i; j++){
  64847. if( aPgno[j]==aPgno[i] ){
  64848. /* This branch is taken if the set of sibling pages somehow contains
  64849. ** duplicate entries. This can happen if the database is corrupt.
  64850. ** It would be simpler to detect this as part of the loop below, but
  64851. ** we do the detection here in order to avoid populating the pager
  64852. ** cache with two separate objects associated with the same
  64853. ** page number. */
  64854. assert( CORRUPT_DB );
  64855. rc = SQLITE_CORRUPT_BKPT;
  64856. goto balance_cleanup;
  64857. }
  64858. }
  64859. }
  64860. for(i=0; i<nNew; i++){
  64861. int iBest = 0; /* aPgno[] index of page number to use */
  64862. for(j=1; j<nNew; j++){
  64863. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  64864. }
  64865. pgno = aPgOrder[iBest];
  64866. aPgOrder[iBest] = 0xffffffff;
  64867. if( iBest!=i ){
  64868. if( iBest>i ){
  64869. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  64870. }
  64871. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  64872. apNew[i]->pgno = pgno;
  64873. }
  64874. }
  64875. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  64876. "%d(%d nc=%d) %d(%d nc=%d)\n",
  64877. apNew[0]->pgno, szNew[0], cntNew[0],
  64878. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  64879. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  64880. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  64881. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  64882. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  64883. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  64884. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  64885. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  64886. ));
  64887. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  64888. put4byte(pRight, apNew[nNew-1]->pgno);
  64889. /* If the sibling pages are not leaves, ensure that the right-child pointer
  64890. ** of the right-most new sibling page is set to the value that was
  64891. ** originally in the same field of the right-most old sibling page. */
  64892. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  64893. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  64894. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  64895. }
  64896. /* Make any required updates to pointer map entries associated with
  64897. ** cells stored on sibling pages following the balance operation. Pointer
  64898. ** map entries associated with divider cells are set by the insertCell()
  64899. ** routine. The associated pointer map entries are:
  64900. **
  64901. ** a) if the cell contains a reference to an overflow chain, the
  64902. ** entry associated with the first page in the overflow chain, and
  64903. **
  64904. ** b) if the sibling pages are not leaves, the child page associated
  64905. ** with the cell.
  64906. **
  64907. ** If the sibling pages are not leaves, then the pointer map entry
  64908. ** associated with the right-child of each sibling may also need to be
  64909. ** updated. This happens below, after the sibling pages have been
  64910. ** populated, not here.
  64911. */
  64912. if( ISAUTOVACUUM ){
  64913. MemPage *pNew = apNew[0];
  64914. u8 *aOld = pNew->aData;
  64915. int cntOldNext = pNew->nCell + pNew->nOverflow;
  64916. int usableSize = pBt->usableSize;
  64917. int iNew = 0;
  64918. int iOld = 0;
  64919. for(i=0; i<b.nCell; i++){
  64920. u8 *pCell = b.apCell[i];
  64921. if( i==cntOldNext ){
  64922. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  64923. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  64924. aOld = pOld->aData;
  64925. }
  64926. if( i==cntNew[iNew] ){
  64927. pNew = apNew[++iNew];
  64928. if( !leafData ) continue;
  64929. }
  64930. /* Cell pCell is destined for new sibling page pNew. Originally, it
  64931. ** was either part of sibling page iOld (possibly an overflow cell),
  64932. ** or else the divider cell to the left of sibling page iOld. So,
  64933. ** if sibling page iOld had the same page number as pNew, and if
  64934. ** pCell really was a part of sibling page iOld (not a divider or
  64935. ** overflow cell), we can skip updating the pointer map entries. */
  64936. if( iOld>=nNew
  64937. || pNew->pgno!=aPgno[iOld]
  64938. || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
  64939. ){
  64940. if( !leafCorrection ){
  64941. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  64942. }
  64943. if( cachedCellSize(&b,i)>pNew->minLocal ){
  64944. ptrmapPutOvflPtr(pNew, pCell, &rc);
  64945. }
  64946. if( rc ) goto balance_cleanup;
  64947. }
  64948. }
  64949. }
  64950. /* Insert new divider cells into pParent. */
  64951. for(i=0; i<nNew-1; i++){
  64952. u8 *pCell;
  64953. u8 *pTemp;
  64954. int sz;
  64955. MemPage *pNew = apNew[i];
  64956. j = cntNew[i];
  64957. assert( j<nMaxCells );
  64958. assert( b.apCell[j]!=0 );
  64959. pCell = b.apCell[j];
  64960. sz = b.szCell[j] + leafCorrection;
  64961. pTemp = &aOvflSpace[iOvflSpace];
  64962. if( !pNew->leaf ){
  64963. memcpy(&pNew->aData[8], pCell, 4);
  64964. }else if( leafData ){
  64965. /* If the tree is a leaf-data tree, and the siblings are leaves,
  64966. ** then there is no divider cell in b.apCell[]. Instead, the divider
  64967. ** cell consists of the integer key for the right-most cell of
  64968. ** the sibling-page assembled above only.
  64969. */
  64970. CellInfo info;
  64971. j--;
  64972. pNew->xParseCell(pNew, b.apCell[j], &info);
  64973. pCell = pTemp;
  64974. sz = 4 + putVarint(&pCell[4], info.nKey);
  64975. pTemp = 0;
  64976. }else{
  64977. pCell -= 4;
  64978. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  64979. ** previously stored on a leaf node, and its reported size was 4
  64980. ** bytes, then it may actually be smaller than this
  64981. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  64982. ** any cell). But it is important to pass the correct size to
  64983. ** insertCell(), so reparse the cell now.
  64984. **
  64985. ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
  64986. ** and WITHOUT ROWID tables with exactly one column which is the
  64987. ** primary key.
  64988. */
  64989. if( b.szCell[j]==4 ){
  64990. assert(leafCorrection==4);
  64991. sz = pParent->xCellSize(pParent, pCell);
  64992. }
  64993. }
  64994. iOvflSpace += sz;
  64995. assert( sz<=pBt->maxLocal+23 );
  64996. assert( iOvflSpace <= (int)pBt->pageSize );
  64997. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  64998. if( rc!=SQLITE_OK ) goto balance_cleanup;
  64999. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  65000. }
  65001. /* Now update the actual sibling pages. The order in which they are updated
  65002. ** is important, as this code needs to avoid disrupting any page from which
  65003. ** cells may still to be read. In practice, this means:
  65004. **
  65005. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  65006. ** then it is not safe to update page apNew[iPg] until after
  65007. ** the left-hand sibling apNew[iPg-1] has been updated.
  65008. **
  65009. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  65010. ** then it is not safe to update page apNew[iPg] until after
  65011. ** the right-hand sibling apNew[iPg+1] has been updated.
  65012. **
  65013. ** If neither of the above apply, the page is safe to update.
  65014. **
  65015. ** The iPg value in the following loop starts at nNew-1 goes down
  65016. ** to 0, then back up to nNew-1 again, thus making two passes over
  65017. ** the pages. On the initial downward pass, only condition (1) above
  65018. ** needs to be tested because (2) will always be true from the previous
  65019. ** step. On the upward pass, both conditions are always true, so the
  65020. ** upwards pass simply processes pages that were missed on the downward
  65021. ** pass.
  65022. */
  65023. for(i=1-nNew; i<nNew; i++){
  65024. int iPg = i<0 ? -i : i;
  65025. assert( iPg>=0 && iPg<nNew );
  65026. if( abDone[iPg] ) continue; /* Skip pages already processed */
  65027. if( i>=0 /* On the upwards pass, or... */
  65028. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  65029. ){
  65030. int iNew;
  65031. int iOld;
  65032. int nNewCell;
  65033. /* Verify condition (1): If cells are moving left, update iPg
  65034. ** only after iPg-1 has already been updated. */
  65035. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  65036. /* Verify condition (2): If cells are moving right, update iPg
  65037. ** only after iPg+1 has already been updated. */
  65038. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  65039. if( iPg==0 ){
  65040. iNew = iOld = 0;
  65041. nNewCell = cntNew[0];
  65042. }else{
  65043. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  65044. iNew = cntNew[iPg-1] + !leafData;
  65045. nNewCell = cntNew[iPg] - iNew;
  65046. }
  65047. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  65048. if( rc ) goto balance_cleanup;
  65049. abDone[iPg]++;
  65050. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  65051. assert( apNew[iPg]->nOverflow==0 );
  65052. assert( apNew[iPg]->nCell==nNewCell );
  65053. }
  65054. }
  65055. /* All pages have been processed exactly once */
  65056. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  65057. assert( nOld>0 );
  65058. assert( nNew>0 );
  65059. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  65060. /* The root page of the b-tree now contains no cells. The only sibling
  65061. ** page is the right-child of the parent. Copy the contents of the
  65062. ** child page into the parent, decreasing the overall height of the
  65063. ** b-tree structure by one. This is described as the "balance-shallower"
  65064. ** sub-algorithm in some documentation.
  65065. **
  65066. ** If this is an auto-vacuum database, the call to copyNodeContent()
  65067. ** sets all pointer-map entries corresponding to database image pages
  65068. ** for which the pointer is stored within the content being copied.
  65069. **
  65070. ** It is critical that the child page be defragmented before being
  65071. ** copied into the parent, because if the parent is page 1 then it will
  65072. ** by smaller than the child due to the database header, and so all the
  65073. ** free space needs to be up front.
  65074. */
  65075. assert( nNew==1 || CORRUPT_DB );
  65076. rc = defragmentPage(apNew[0], -1);
  65077. testcase( rc!=SQLITE_OK );
  65078. assert( apNew[0]->nFree ==
  65079. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  65080. || rc!=SQLITE_OK
  65081. );
  65082. copyNodeContent(apNew[0], pParent, &rc);
  65083. freePage(apNew[0], &rc);
  65084. }else if( ISAUTOVACUUM && !leafCorrection ){
  65085. /* Fix the pointer map entries associated with the right-child of each
  65086. ** sibling page. All other pointer map entries have already been taken
  65087. ** care of. */
  65088. for(i=0; i<nNew; i++){
  65089. u32 key = get4byte(&apNew[i]->aData[8]);
  65090. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  65091. }
  65092. }
  65093. assert( pParent->isInit );
  65094. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  65095. nOld, nNew, b.nCell));
  65096. /* Free any old pages that were not reused as new pages.
  65097. */
  65098. for(i=nNew; i<nOld; i++){
  65099. freePage(apOld[i], &rc);
  65100. }
  65101. #if 0
  65102. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  65103. /* The ptrmapCheckPages() contains assert() statements that verify that
  65104. ** all pointer map pages are set correctly. This is helpful while
  65105. ** debugging. This is usually disabled because a corrupt database may
  65106. ** cause an assert() statement to fail. */
  65107. ptrmapCheckPages(apNew, nNew);
  65108. ptrmapCheckPages(&pParent, 1);
  65109. }
  65110. #endif
  65111. /*
  65112. ** Cleanup before returning.
  65113. */
  65114. balance_cleanup:
  65115. sqlite3StackFree(0, b.apCell);
  65116. for(i=0; i<nOld; i++){
  65117. releasePage(apOld[i]);
  65118. }
  65119. for(i=0; i<nNew; i++){
  65120. releasePage(apNew[i]);
  65121. }
  65122. return rc;
  65123. }
  65124. /*
  65125. ** This function is called when the root page of a b-tree structure is
  65126. ** overfull (has one or more overflow pages).
  65127. **
  65128. ** A new child page is allocated and the contents of the current root
  65129. ** page, including overflow cells, are copied into the child. The root
  65130. ** page is then overwritten to make it an empty page with the right-child
  65131. ** pointer pointing to the new page.
  65132. **
  65133. ** Before returning, all pointer-map entries corresponding to pages
  65134. ** that the new child-page now contains pointers to are updated. The
  65135. ** entry corresponding to the new right-child pointer of the root
  65136. ** page is also updated.
  65137. **
  65138. ** If successful, *ppChild is set to contain a reference to the child
  65139. ** page and SQLITE_OK is returned. In this case the caller is required
  65140. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  65141. ** an error code is returned and *ppChild is set to 0.
  65142. */
  65143. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  65144. int rc; /* Return value from subprocedures */
  65145. MemPage *pChild = 0; /* Pointer to a new child page */
  65146. Pgno pgnoChild = 0; /* Page number of the new child page */
  65147. BtShared *pBt = pRoot->pBt; /* The BTree */
  65148. assert( pRoot->nOverflow>0 );
  65149. assert( sqlite3_mutex_held(pBt->mutex) );
  65150. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  65151. ** page that will become the new right-child of pPage. Copy the contents
  65152. ** of the node stored on pRoot into the new child page.
  65153. */
  65154. rc = sqlite3PagerWrite(pRoot->pDbPage);
  65155. if( rc==SQLITE_OK ){
  65156. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  65157. copyNodeContent(pRoot, pChild, &rc);
  65158. if( ISAUTOVACUUM ){
  65159. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  65160. }
  65161. }
  65162. if( rc ){
  65163. *ppChild = 0;
  65164. releasePage(pChild);
  65165. return rc;
  65166. }
  65167. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  65168. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  65169. assert( pChild->nCell==pRoot->nCell );
  65170. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  65171. /* Copy the overflow cells from pRoot to pChild */
  65172. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  65173. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  65174. memcpy(pChild->apOvfl, pRoot->apOvfl,
  65175. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  65176. pChild->nOverflow = pRoot->nOverflow;
  65177. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  65178. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  65179. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  65180. *ppChild = pChild;
  65181. return SQLITE_OK;
  65182. }
  65183. /*
  65184. ** The page that pCur currently points to has just been modified in
  65185. ** some way. This function figures out if this modification means the
  65186. ** tree needs to be balanced, and if so calls the appropriate balancing
  65187. ** routine. Balancing routines are:
  65188. **
  65189. ** balance_quick()
  65190. ** balance_deeper()
  65191. ** balance_nonroot()
  65192. */
  65193. static int balance(BtCursor *pCur){
  65194. int rc = SQLITE_OK;
  65195. const int nMin = pCur->pBt->usableSize * 2 / 3;
  65196. u8 aBalanceQuickSpace[13];
  65197. u8 *pFree = 0;
  65198. VVA_ONLY( int balance_quick_called = 0 );
  65199. VVA_ONLY( int balance_deeper_called = 0 );
  65200. do {
  65201. int iPage = pCur->iPage;
  65202. MemPage *pPage = pCur->pPage;
  65203. if( iPage==0 ){
  65204. if( pPage->nOverflow ){
  65205. /* The root page of the b-tree is overfull. In this case call the
  65206. ** balance_deeper() function to create a new child for the root-page
  65207. ** and copy the current contents of the root-page to it. The
  65208. ** next iteration of the do-loop will balance the child page.
  65209. */
  65210. assert( balance_deeper_called==0 );
  65211. VVA_ONLY( balance_deeper_called++ );
  65212. rc = balance_deeper(pPage, &pCur->apPage[1]);
  65213. if( rc==SQLITE_OK ){
  65214. pCur->iPage = 1;
  65215. pCur->ix = 0;
  65216. pCur->aiIdx[0] = 0;
  65217. pCur->apPage[0] = pPage;
  65218. pCur->pPage = pCur->apPage[1];
  65219. assert( pCur->pPage->nOverflow );
  65220. }
  65221. }else{
  65222. break;
  65223. }
  65224. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  65225. break;
  65226. }else{
  65227. MemPage * const pParent = pCur->apPage[iPage-1];
  65228. int const iIdx = pCur->aiIdx[iPage-1];
  65229. rc = sqlite3PagerWrite(pParent->pDbPage);
  65230. if( rc==SQLITE_OK ){
  65231. #ifndef SQLITE_OMIT_QUICKBALANCE
  65232. if( pPage->intKeyLeaf
  65233. && pPage->nOverflow==1
  65234. && pPage->aiOvfl[0]==pPage->nCell
  65235. && pParent->pgno!=1
  65236. && pParent->nCell==iIdx
  65237. ){
  65238. /* Call balance_quick() to create a new sibling of pPage on which
  65239. ** to store the overflow cell. balance_quick() inserts a new cell
  65240. ** into pParent, which may cause pParent overflow. If this
  65241. ** happens, the next iteration of the do-loop will balance pParent
  65242. ** use either balance_nonroot() or balance_deeper(). Until this
  65243. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  65244. ** buffer.
  65245. **
  65246. ** The purpose of the following assert() is to check that only a
  65247. ** single call to balance_quick() is made for each call to this
  65248. ** function. If this were not verified, a subtle bug involving reuse
  65249. ** of the aBalanceQuickSpace[] might sneak in.
  65250. */
  65251. assert( balance_quick_called==0 );
  65252. VVA_ONLY( balance_quick_called++ );
  65253. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  65254. }else
  65255. #endif
  65256. {
  65257. /* In this case, call balance_nonroot() to redistribute cells
  65258. ** between pPage and up to 2 of its sibling pages. This involves
  65259. ** modifying the contents of pParent, which may cause pParent to
  65260. ** become overfull or underfull. The next iteration of the do-loop
  65261. ** will balance the parent page to correct this.
  65262. **
  65263. ** If the parent page becomes overfull, the overflow cell or cells
  65264. ** are stored in the pSpace buffer allocated immediately below.
  65265. ** A subsequent iteration of the do-loop will deal with this by
  65266. ** calling balance_nonroot() (balance_deeper() may be called first,
  65267. ** but it doesn't deal with overflow cells - just moves them to a
  65268. ** different page). Once this subsequent call to balance_nonroot()
  65269. ** has completed, it is safe to release the pSpace buffer used by
  65270. ** the previous call, as the overflow cell data will have been
  65271. ** copied either into the body of a database page or into the new
  65272. ** pSpace buffer passed to the latter call to balance_nonroot().
  65273. */
  65274. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  65275. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  65276. pCur->hints&BTREE_BULKLOAD);
  65277. if( pFree ){
  65278. /* If pFree is not NULL, it points to the pSpace buffer used
  65279. ** by a previous call to balance_nonroot(). Its contents are
  65280. ** now stored either on real database pages or within the
  65281. ** new pSpace buffer, so it may be safely freed here. */
  65282. sqlite3PageFree(pFree);
  65283. }
  65284. /* The pSpace buffer will be freed after the next call to
  65285. ** balance_nonroot(), or just before this function returns, whichever
  65286. ** comes first. */
  65287. pFree = pSpace;
  65288. }
  65289. }
  65290. pPage->nOverflow = 0;
  65291. /* The next iteration of the do-loop balances the parent page. */
  65292. releasePage(pPage);
  65293. pCur->iPage--;
  65294. assert( pCur->iPage>=0 );
  65295. pCur->pPage = pCur->apPage[pCur->iPage];
  65296. }
  65297. }while( rc==SQLITE_OK );
  65298. if( pFree ){
  65299. sqlite3PageFree(pFree);
  65300. }
  65301. return rc;
  65302. }
  65303. /*
  65304. ** Insert a new record into the BTree. The content of the new record
  65305. ** is described by the pX object. The pCur cursor is used only to
  65306. ** define what table the record should be inserted into, and is left
  65307. ** pointing at a random location.
  65308. **
  65309. ** For a table btree (used for rowid tables), only the pX.nKey value of
  65310. ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
  65311. ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
  65312. ** hold the content of the row.
  65313. **
  65314. ** For an index btree (used for indexes and WITHOUT ROWID tables), the
  65315. ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
  65316. ** pX.pData,nData,nZero fields must be zero.
  65317. **
  65318. ** If the seekResult parameter is non-zero, then a successful call to
  65319. ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
  65320. ** been performed. In other words, if seekResult!=0 then the cursor
  65321. ** is currently pointing to a cell that will be adjacent to the cell
  65322. ** to be inserted. If seekResult<0 then pCur points to a cell that is
  65323. ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
  65324. ** that is larger than (pKey,nKey).
  65325. **
  65326. ** If seekResult==0, that means pCur is pointing at some unknown location.
  65327. ** In that case, this routine must seek the cursor to the correct insertion
  65328. ** point for (pKey,nKey) before doing the insertion. For index btrees,
  65329. ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
  65330. ** key values and pX->aMem can be used instead of pX->pKey to avoid having
  65331. ** to decode the key.
  65332. */
  65333. SQLITE_PRIVATE int sqlite3BtreeInsert(
  65334. BtCursor *pCur, /* Insert data into the table of this cursor */
  65335. const BtreePayload *pX, /* Content of the row to be inserted */
  65336. int flags, /* True if this is likely an append */
  65337. int seekResult /* Result of prior MovetoUnpacked() call */
  65338. ){
  65339. int rc;
  65340. int loc = seekResult; /* -1: before desired location +1: after */
  65341. int szNew = 0;
  65342. int idx;
  65343. MemPage *pPage;
  65344. Btree *p = pCur->pBtree;
  65345. BtShared *pBt = p->pBt;
  65346. unsigned char *oldCell;
  65347. unsigned char *newCell = 0;
  65348. assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
  65349. if( pCur->eState==CURSOR_FAULT ){
  65350. assert( pCur->skipNext!=SQLITE_OK );
  65351. return pCur->skipNext;
  65352. }
  65353. assert( cursorOwnsBtShared(pCur) );
  65354. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  65355. && pBt->inTransaction==TRANS_WRITE
  65356. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  65357. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  65358. /* Assert that the caller has been consistent. If this cursor was opened
  65359. ** expecting an index b-tree, then the caller should be inserting blob
  65360. ** keys with no associated data. If the cursor was opened expecting an
  65361. ** intkey table, the caller should be inserting integer keys with a
  65362. ** blob of associated data. */
  65363. assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
  65364. /* Save the positions of any other cursors open on this table.
  65365. **
  65366. ** In some cases, the call to btreeMoveto() below is a no-op. For
  65367. ** example, when inserting data into a table with auto-generated integer
  65368. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  65369. ** integer key to use. It then calls this function to actually insert the
  65370. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  65371. ** that the cursor is already where it needs to be and returns without
  65372. ** doing any work. To avoid thwarting these optimizations, it is important
  65373. ** not to clear the cursor here.
  65374. */
  65375. if( pCur->curFlags & BTCF_Multiple ){
  65376. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  65377. if( rc ) return rc;
  65378. }
  65379. if( pCur->pKeyInfo==0 ){
  65380. assert( pX->pKey==0 );
  65381. /* If this is an insert into a table b-tree, invalidate any incrblob
  65382. ** cursors open on the row being replaced */
  65383. invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
  65384. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  65385. ** to a row with the same key as the new entry being inserted. */
  65386. assert( (flags & BTREE_SAVEPOSITION)==0 ||
  65387. ((pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey) );
  65388. /* If the cursor is currently on the last row and we are appending a
  65389. ** new row onto the end, set the "loc" to avoid an unnecessary
  65390. ** btreeMoveto() call */
  65391. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
  65392. loc = 0;
  65393. }else if( loc==0 ){
  65394. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
  65395. if( rc ) return rc;
  65396. }
  65397. }else if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
  65398. if( pX->nMem ){
  65399. UnpackedRecord r;
  65400. r.pKeyInfo = pCur->pKeyInfo;
  65401. r.aMem = pX->aMem;
  65402. r.nField = pX->nMem;
  65403. r.default_rc = 0;
  65404. r.errCode = 0;
  65405. r.r1 = 0;
  65406. r.r2 = 0;
  65407. r.eqSeen = 0;
  65408. rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
  65409. }else{
  65410. rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
  65411. }
  65412. if( rc ) return rc;
  65413. }
  65414. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  65415. pPage = pCur->pPage;
  65416. assert( pPage->intKey || pX->nKey>=0 );
  65417. assert( pPage->leaf || !pPage->intKey );
  65418. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  65419. pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
  65420. loc==0 ? "overwrite" : "new entry"));
  65421. assert( pPage->isInit );
  65422. newCell = pBt->pTmpSpace;
  65423. assert( newCell!=0 );
  65424. rc = fillInCell(pPage, newCell, pX, &szNew);
  65425. if( rc ) goto end_insert;
  65426. assert( szNew==pPage->xCellSize(pPage, newCell) );
  65427. assert( szNew <= MX_CELL_SIZE(pBt) );
  65428. idx = pCur->ix;
  65429. if( loc==0 ){
  65430. CellInfo info;
  65431. assert( idx<pPage->nCell );
  65432. rc = sqlite3PagerWrite(pPage->pDbPage);
  65433. if( rc ){
  65434. goto end_insert;
  65435. }
  65436. oldCell = findCell(pPage, idx);
  65437. if( !pPage->leaf ){
  65438. memcpy(newCell, oldCell, 4);
  65439. }
  65440. rc = clearCell(pPage, oldCell, &info);
  65441. if( info.nSize==szNew && info.nLocal==info.nPayload
  65442. && (!ISAUTOVACUUM || szNew<pPage->minLocal)
  65443. ){
  65444. /* Overwrite the old cell with the new if they are the same size.
  65445. ** We could also try to do this if the old cell is smaller, then add
  65446. ** the leftover space to the free list. But experiments show that
  65447. ** doing that is no faster then skipping this optimization and just
  65448. ** calling dropCell() and insertCell().
  65449. **
  65450. ** This optimization cannot be used on an autovacuum database if the
  65451. ** new entry uses overflow pages, as the insertCell() call below is
  65452. ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
  65453. assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
  65454. if( oldCell+szNew > pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  65455. memcpy(oldCell, newCell, szNew);
  65456. return SQLITE_OK;
  65457. }
  65458. dropCell(pPage, idx, info.nSize, &rc);
  65459. if( rc ) goto end_insert;
  65460. }else if( loc<0 && pPage->nCell>0 ){
  65461. assert( pPage->leaf );
  65462. idx = ++pCur->ix;
  65463. pCur->curFlags &= ~BTCF_ValidNKey;
  65464. }else{
  65465. assert( pPage->leaf );
  65466. }
  65467. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  65468. assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  65469. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  65470. /* If no error has occurred and pPage has an overflow cell, call balance()
  65471. ** to redistribute the cells within the tree. Since balance() may move
  65472. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  65473. ** variables.
  65474. **
  65475. ** Previous versions of SQLite called moveToRoot() to move the cursor
  65476. ** back to the root page as balance() used to invalidate the contents
  65477. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  65478. ** set the cursor state to "invalid". This makes common insert operations
  65479. ** slightly faster.
  65480. **
  65481. ** There is a subtle but important optimization here too. When inserting
  65482. ** multiple records into an intkey b-tree using a single cursor (as can
  65483. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  65484. ** is advantageous to leave the cursor pointing to the last entry in
  65485. ** the b-tree if possible. If the cursor is left pointing to the last
  65486. ** entry in the table, and the next row inserted has an integer key
  65487. ** larger than the largest existing key, it is possible to insert the
  65488. ** row without seeking the cursor. This can be a big performance boost.
  65489. */
  65490. pCur->info.nSize = 0;
  65491. if( pPage->nOverflow ){
  65492. assert( rc==SQLITE_OK );
  65493. pCur->curFlags &= ~(BTCF_ValidNKey);
  65494. rc = balance(pCur);
  65495. /* Must make sure nOverflow is reset to zero even if the balance()
  65496. ** fails. Internal data structure corruption will result otherwise.
  65497. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  65498. ** from trying to save the current position of the cursor. */
  65499. pCur->pPage->nOverflow = 0;
  65500. pCur->eState = CURSOR_INVALID;
  65501. if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
  65502. btreeReleaseAllCursorPages(pCur);
  65503. if( pCur->pKeyInfo ){
  65504. assert( pCur->pKey==0 );
  65505. pCur->pKey = sqlite3Malloc( pX->nKey );
  65506. if( pCur->pKey==0 ){
  65507. rc = SQLITE_NOMEM;
  65508. }else{
  65509. memcpy(pCur->pKey, pX->pKey, pX->nKey);
  65510. }
  65511. }
  65512. pCur->eState = CURSOR_REQUIRESEEK;
  65513. pCur->nKey = pX->nKey;
  65514. }
  65515. }
  65516. assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
  65517. end_insert:
  65518. return rc;
  65519. }
  65520. /*
  65521. ** Delete the entry that the cursor is pointing to.
  65522. **
  65523. ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
  65524. ** the cursor is left pointing at an arbitrary location after the delete.
  65525. ** But if that bit is set, then the cursor is left in a state such that
  65526. ** the next call to BtreeNext() or BtreePrev() moves it to the same row
  65527. ** as it would have been on if the call to BtreeDelete() had been omitted.
  65528. **
  65529. ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
  65530. ** associated with a single table entry and its indexes. Only one of those
  65531. ** deletes is considered the "primary" delete. The primary delete occurs
  65532. ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
  65533. ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
  65534. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
  65535. ** but which might be used by alternative storage engines.
  65536. */
  65537. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
  65538. Btree *p = pCur->pBtree;
  65539. BtShared *pBt = p->pBt;
  65540. int rc; /* Return code */
  65541. MemPage *pPage; /* Page to delete cell from */
  65542. unsigned char *pCell; /* Pointer to cell to delete */
  65543. int iCellIdx; /* Index of cell to delete */
  65544. int iCellDepth; /* Depth of node containing pCell */
  65545. CellInfo info; /* Size of the cell being deleted */
  65546. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  65547. u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
  65548. assert( cursorOwnsBtShared(pCur) );
  65549. assert( pBt->inTransaction==TRANS_WRITE );
  65550. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  65551. assert( pCur->curFlags & BTCF_WriteFlag );
  65552. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  65553. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  65554. assert( pCur->ix<pCur->pPage->nCell );
  65555. assert( pCur->eState==CURSOR_VALID );
  65556. assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
  65557. iCellDepth = pCur->iPage;
  65558. iCellIdx = pCur->ix;
  65559. pPage = pCur->pPage;
  65560. pCell = findCell(pPage, iCellIdx);
  65561. /* If the bPreserve flag is set to true, then the cursor position must
  65562. ** be preserved following this delete operation. If the current delete
  65563. ** will cause a b-tree rebalance, then this is done by saving the cursor
  65564. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  65565. ** returning.
  65566. **
  65567. ** Or, if the current delete will not cause a rebalance, then the cursor
  65568. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  65569. ** before or after the deleted entry. In this case set bSkipnext to true. */
  65570. if( bPreserve ){
  65571. if( !pPage->leaf
  65572. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  65573. ){
  65574. /* A b-tree rebalance will be required after deleting this entry.
  65575. ** Save the cursor key. */
  65576. rc = saveCursorKey(pCur);
  65577. if( rc ) return rc;
  65578. }else{
  65579. bSkipnext = 1;
  65580. }
  65581. }
  65582. /* If the page containing the entry to delete is not a leaf page, move
  65583. ** the cursor to the largest entry in the tree that is smaller than
  65584. ** the entry being deleted. This cell will replace the cell being deleted
  65585. ** from the internal node. The 'previous' entry is used for this instead
  65586. ** of the 'next' entry, as the previous entry is always a part of the
  65587. ** sub-tree headed by the child page of the cell being deleted. This makes
  65588. ** balancing the tree following the delete operation easier. */
  65589. if( !pPage->leaf ){
  65590. rc = sqlite3BtreePrevious(pCur, 0);
  65591. assert( rc!=SQLITE_DONE );
  65592. if( rc ) return rc;
  65593. }
  65594. /* Save the positions of any other cursors open on this table before
  65595. ** making any modifications. */
  65596. if( pCur->curFlags & BTCF_Multiple ){
  65597. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  65598. if( rc ) return rc;
  65599. }
  65600. /* If this is a delete operation to remove a row from a table b-tree,
  65601. ** invalidate any incrblob cursors open on the row being deleted. */
  65602. if( pCur->pKeyInfo==0 ){
  65603. invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
  65604. }
  65605. /* Make the page containing the entry to be deleted writable. Then free any
  65606. ** overflow pages associated with the entry and finally remove the cell
  65607. ** itself from within the page. */
  65608. rc = sqlite3PagerWrite(pPage->pDbPage);
  65609. if( rc ) return rc;
  65610. rc = clearCell(pPage, pCell, &info);
  65611. dropCell(pPage, iCellIdx, info.nSize, &rc);
  65612. if( rc ) return rc;
  65613. /* If the cell deleted was not located on a leaf page, then the cursor
  65614. ** is currently pointing to the largest entry in the sub-tree headed
  65615. ** by the child-page of the cell that was just deleted from an internal
  65616. ** node. The cell from the leaf node needs to be moved to the internal
  65617. ** node to replace the deleted cell. */
  65618. if( !pPage->leaf ){
  65619. MemPage *pLeaf = pCur->pPage;
  65620. int nCell;
  65621. Pgno n;
  65622. unsigned char *pTmp;
  65623. if( iCellDepth<pCur->iPage-1 ){
  65624. n = pCur->apPage[iCellDepth+1]->pgno;
  65625. }else{
  65626. n = pCur->pPage->pgno;
  65627. }
  65628. pCell = findCell(pLeaf, pLeaf->nCell-1);
  65629. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  65630. nCell = pLeaf->xCellSize(pLeaf, pCell);
  65631. assert( MX_CELL_SIZE(pBt) >= nCell );
  65632. pTmp = pBt->pTmpSpace;
  65633. assert( pTmp!=0 );
  65634. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  65635. if( rc==SQLITE_OK ){
  65636. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  65637. }
  65638. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  65639. if( rc ) return rc;
  65640. }
  65641. /* Balance the tree. If the entry deleted was located on a leaf page,
  65642. ** then the cursor still points to that page. In this case the first
  65643. ** call to balance() repairs the tree, and the if(...) condition is
  65644. ** never true.
  65645. **
  65646. ** Otherwise, if the entry deleted was on an internal node page, then
  65647. ** pCur is pointing to the leaf page from which a cell was removed to
  65648. ** replace the cell deleted from the internal node. This is slightly
  65649. ** tricky as the leaf node may be underfull, and the internal node may
  65650. ** be either under or overfull. In this case run the balancing algorithm
  65651. ** on the leaf node first. If the balance proceeds far enough up the
  65652. ** tree that we can be sure that any problem in the internal node has
  65653. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  65654. ** walk the cursor up the tree to the internal node and balance it as
  65655. ** well. */
  65656. rc = balance(pCur);
  65657. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  65658. releasePageNotNull(pCur->pPage);
  65659. pCur->iPage--;
  65660. while( pCur->iPage>iCellDepth ){
  65661. releasePage(pCur->apPage[pCur->iPage--]);
  65662. }
  65663. pCur->pPage = pCur->apPage[pCur->iPage];
  65664. rc = balance(pCur);
  65665. }
  65666. if( rc==SQLITE_OK ){
  65667. if( bSkipnext ){
  65668. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  65669. assert( pPage==pCur->pPage || CORRUPT_DB );
  65670. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  65671. pCur->eState = CURSOR_SKIPNEXT;
  65672. if( iCellIdx>=pPage->nCell ){
  65673. pCur->skipNext = -1;
  65674. pCur->ix = pPage->nCell-1;
  65675. }else{
  65676. pCur->skipNext = 1;
  65677. }
  65678. }else{
  65679. rc = moveToRoot(pCur);
  65680. if( bPreserve ){
  65681. btreeReleaseAllCursorPages(pCur);
  65682. pCur->eState = CURSOR_REQUIRESEEK;
  65683. }
  65684. if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
  65685. }
  65686. }
  65687. return rc;
  65688. }
  65689. /*
  65690. ** Create a new BTree table. Write into *piTable the page
  65691. ** number for the root page of the new table.
  65692. **
  65693. ** The type of type is determined by the flags parameter. Only the
  65694. ** following values of flags are currently in use. Other values for
  65695. ** flags might not work:
  65696. **
  65697. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  65698. ** BTREE_ZERODATA Used for SQL indices
  65699. */
  65700. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  65701. BtShared *pBt = p->pBt;
  65702. MemPage *pRoot;
  65703. Pgno pgnoRoot;
  65704. int rc;
  65705. int ptfFlags; /* Page-type flage for the root page of new table */
  65706. assert( sqlite3BtreeHoldsMutex(p) );
  65707. assert( pBt->inTransaction==TRANS_WRITE );
  65708. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  65709. #ifdef SQLITE_OMIT_AUTOVACUUM
  65710. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  65711. if( rc ){
  65712. return rc;
  65713. }
  65714. #else
  65715. if( pBt->autoVacuum ){
  65716. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  65717. MemPage *pPageMove; /* The page to move to. */
  65718. /* Creating a new table may probably require moving an existing database
  65719. ** to make room for the new tables root page. In case this page turns
  65720. ** out to be an overflow page, delete all overflow page-map caches
  65721. ** held by open cursors.
  65722. */
  65723. invalidateAllOverflowCache(pBt);
  65724. /* Read the value of meta[3] from the database to determine where the
  65725. ** root page of the new table should go. meta[3] is the largest root-page
  65726. ** created so far, so the new root-page is (meta[3]+1).
  65727. */
  65728. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  65729. pgnoRoot++;
  65730. /* The new root-page may not be allocated on a pointer-map page, or the
  65731. ** PENDING_BYTE page.
  65732. */
  65733. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  65734. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  65735. pgnoRoot++;
  65736. }
  65737. assert( pgnoRoot>=3 || CORRUPT_DB );
  65738. testcase( pgnoRoot<3 );
  65739. /* Allocate a page. The page that currently resides at pgnoRoot will
  65740. ** be moved to the allocated page (unless the allocated page happens
  65741. ** to reside at pgnoRoot).
  65742. */
  65743. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  65744. if( rc!=SQLITE_OK ){
  65745. return rc;
  65746. }
  65747. if( pgnoMove!=pgnoRoot ){
  65748. /* pgnoRoot is the page that will be used for the root-page of
  65749. ** the new table (assuming an error did not occur). But we were
  65750. ** allocated pgnoMove. If required (i.e. if it was not allocated
  65751. ** by extending the file), the current page at position pgnoMove
  65752. ** is already journaled.
  65753. */
  65754. u8 eType = 0;
  65755. Pgno iPtrPage = 0;
  65756. /* Save the positions of any open cursors. This is required in
  65757. ** case they are holding a reference to an xFetch reference
  65758. ** corresponding to page pgnoRoot. */
  65759. rc = saveAllCursors(pBt, 0, 0);
  65760. releasePage(pPageMove);
  65761. if( rc!=SQLITE_OK ){
  65762. return rc;
  65763. }
  65764. /* Move the page currently at pgnoRoot to pgnoMove. */
  65765. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  65766. if( rc!=SQLITE_OK ){
  65767. return rc;
  65768. }
  65769. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  65770. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  65771. rc = SQLITE_CORRUPT_BKPT;
  65772. }
  65773. if( rc!=SQLITE_OK ){
  65774. releasePage(pRoot);
  65775. return rc;
  65776. }
  65777. assert( eType!=PTRMAP_ROOTPAGE );
  65778. assert( eType!=PTRMAP_FREEPAGE );
  65779. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  65780. releasePage(pRoot);
  65781. /* Obtain the page at pgnoRoot */
  65782. if( rc!=SQLITE_OK ){
  65783. return rc;
  65784. }
  65785. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  65786. if( rc!=SQLITE_OK ){
  65787. return rc;
  65788. }
  65789. rc = sqlite3PagerWrite(pRoot->pDbPage);
  65790. if( rc!=SQLITE_OK ){
  65791. releasePage(pRoot);
  65792. return rc;
  65793. }
  65794. }else{
  65795. pRoot = pPageMove;
  65796. }
  65797. /* Update the pointer-map and meta-data with the new root-page number. */
  65798. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  65799. if( rc ){
  65800. releasePage(pRoot);
  65801. return rc;
  65802. }
  65803. /* When the new root page was allocated, page 1 was made writable in
  65804. ** order either to increase the database filesize, or to decrement the
  65805. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  65806. */
  65807. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  65808. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  65809. if( NEVER(rc) ){
  65810. releasePage(pRoot);
  65811. return rc;
  65812. }
  65813. }else{
  65814. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  65815. if( rc ) return rc;
  65816. }
  65817. #endif
  65818. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  65819. if( createTabFlags & BTREE_INTKEY ){
  65820. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  65821. }else{
  65822. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  65823. }
  65824. zeroPage(pRoot, ptfFlags);
  65825. sqlite3PagerUnref(pRoot->pDbPage);
  65826. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  65827. *piTable = (int)pgnoRoot;
  65828. return SQLITE_OK;
  65829. }
  65830. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  65831. int rc;
  65832. sqlite3BtreeEnter(p);
  65833. rc = btreeCreateTable(p, piTable, flags);
  65834. sqlite3BtreeLeave(p);
  65835. return rc;
  65836. }
  65837. /*
  65838. ** Erase the given database page and all its children. Return
  65839. ** the page to the freelist.
  65840. */
  65841. static int clearDatabasePage(
  65842. BtShared *pBt, /* The BTree that contains the table */
  65843. Pgno pgno, /* Page number to clear */
  65844. int freePageFlag, /* Deallocate page if true */
  65845. int *pnChange /* Add number of Cells freed to this counter */
  65846. ){
  65847. MemPage *pPage;
  65848. int rc;
  65849. unsigned char *pCell;
  65850. int i;
  65851. int hdr;
  65852. CellInfo info;
  65853. assert( sqlite3_mutex_held(pBt->mutex) );
  65854. if( pgno>btreePagecount(pBt) ){
  65855. return SQLITE_CORRUPT_BKPT;
  65856. }
  65857. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  65858. if( rc ) return rc;
  65859. if( pPage->bBusy ){
  65860. rc = SQLITE_CORRUPT_BKPT;
  65861. goto cleardatabasepage_out;
  65862. }
  65863. pPage->bBusy = 1;
  65864. hdr = pPage->hdrOffset;
  65865. for(i=0; i<pPage->nCell; i++){
  65866. pCell = findCell(pPage, i);
  65867. if( !pPage->leaf ){
  65868. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  65869. if( rc ) goto cleardatabasepage_out;
  65870. }
  65871. rc = clearCell(pPage, pCell, &info);
  65872. if( rc ) goto cleardatabasepage_out;
  65873. }
  65874. if( !pPage->leaf ){
  65875. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  65876. if( rc ) goto cleardatabasepage_out;
  65877. }else if( pnChange ){
  65878. assert( pPage->intKey || CORRUPT_DB );
  65879. testcase( !pPage->intKey );
  65880. *pnChange += pPage->nCell;
  65881. }
  65882. if( freePageFlag ){
  65883. freePage(pPage, &rc);
  65884. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  65885. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  65886. }
  65887. cleardatabasepage_out:
  65888. pPage->bBusy = 0;
  65889. releasePage(pPage);
  65890. return rc;
  65891. }
  65892. /*
  65893. ** Delete all information from a single table in the database. iTable is
  65894. ** the page number of the root of the table. After this routine returns,
  65895. ** the root page is empty, but still exists.
  65896. **
  65897. ** This routine will fail with SQLITE_LOCKED if there are any open
  65898. ** read cursors on the table. Open write cursors are moved to the
  65899. ** root of the table.
  65900. **
  65901. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  65902. ** integer value pointed to by pnChange is incremented by the number of
  65903. ** entries in the table.
  65904. */
  65905. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  65906. int rc;
  65907. BtShared *pBt = p->pBt;
  65908. sqlite3BtreeEnter(p);
  65909. assert( p->inTrans==TRANS_WRITE );
  65910. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  65911. if( SQLITE_OK==rc ){
  65912. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  65913. ** is the root of a table b-tree - if it is not, the following call is
  65914. ** a no-op). */
  65915. invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
  65916. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  65917. }
  65918. sqlite3BtreeLeave(p);
  65919. return rc;
  65920. }
  65921. /*
  65922. ** Delete all information from the single table that pCur is open on.
  65923. **
  65924. ** This routine only work for pCur on an ephemeral table.
  65925. */
  65926. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  65927. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  65928. }
  65929. /*
  65930. ** Erase all information in a table and add the root of the table to
  65931. ** the freelist. Except, the root of the principle table (the one on
  65932. ** page 1) is never added to the freelist.
  65933. **
  65934. ** This routine will fail with SQLITE_LOCKED if there are any open
  65935. ** cursors on the table.
  65936. **
  65937. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  65938. ** root page in the database file, then the last root page
  65939. ** in the database file is moved into the slot formerly occupied by
  65940. ** iTable and that last slot formerly occupied by the last root page
  65941. ** is added to the freelist instead of iTable. In this say, all
  65942. ** root pages are kept at the beginning of the database file, which
  65943. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  65944. ** page number that used to be the last root page in the file before
  65945. ** the move. If no page gets moved, *piMoved is set to 0.
  65946. ** The last root page is recorded in meta[3] and the value of
  65947. ** meta[3] is updated by this procedure.
  65948. */
  65949. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  65950. int rc;
  65951. MemPage *pPage = 0;
  65952. BtShared *pBt = p->pBt;
  65953. assert( sqlite3BtreeHoldsMutex(p) );
  65954. assert( p->inTrans==TRANS_WRITE );
  65955. assert( iTable>=2 );
  65956. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  65957. if( rc ) return rc;
  65958. rc = sqlite3BtreeClearTable(p, iTable, 0);
  65959. if( rc ){
  65960. releasePage(pPage);
  65961. return rc;
  65962. }
  65963. *piMoved = 0;
  65964. #ifdef SQLITE_OMIT_AUTOVACUUM
  65965. freePage(pPage, &rc);
  65966. releasePage(pPage);
  65967. #else
  65968. if( pBt->autoVacuum ){
  65969. Pgno maxRootPgno;
  65970. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  65971. if( iTable==maxRootPgno ){
  65972. /* If the table being dropped is the table with the largest root-page
  65973. ** number in the database, put the root page on the free list.
  65974. */
  65975. freePage(pPage, &rc);
  65976. releasePage(pPage);
  65977. if( rc!=SQLITE_OK ){
  65978. return rc;
  65979. }
  65980. }else{
  65981. /* The table being dropped does not have the largest root-page
  65982. ** number in the database. So move the page that does into the
  65983. ** gap left by the deleted root-page.
  65984. */
  65985. MemPage *pMove;
  65986. releasePage(pPage);
  65987. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  65988. if( rc!=SQLITE_OK ){
  65989. return rc;
  65990. }
  65991. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  65992. releasePage(pMove);
  65993. if( rc!=SQLITE_OK ){
  65994. return rc;
  65995. }
  65996. pMove = 0;
  65997. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  65998. freePage(pMove, &rc);
  65999. releasePage(pMove);
  66000. if( rc!=SQLITE_OK ){
  66001. return rc;
  66002. }
  66003. *piMoved = maxRootPgno;
  66004. }
  66005. /* Set the new 'max-root-page' value in the database header. This
  66006. ** is the old value less one, less one more if that happens to
  66007. ** be a root-page number, less one again if that is the
  66008. ** PENDING_BYTE_PAGE.
  66009. */
  66010. maxRootPgno--;
  66011. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  66012. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  66013. maxRootPgno--;
  66014. }
  66015. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  66016. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  66017. }else{
  66018. freePage(pPage, &rc);
  66019. releasePage(pPage);
  66020. }
  66021. #endif
  66022. return rc;
  66023. }
  66024. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  66025. int rc;
  66026. sqlite3BtreeEnter(p);
  66027. rc = btreeDropTable(p, iTable, piMoved);
  66028. sqlite3BtreeLeave(p);
  66029. return rc;
  66030. }
  66031. /*
  66032. ** This function may only be called if the b-tree connection already
  66033. ** has a read or write transaction open on the database.
  66034. **
  66035. ** Read the meta-information out of a database file. Meta[0]
  66036. ** is the number of free pages currently in the database. Meta[1]
  66037. ** through meta[15] are available for use by higher layers. Meta[0]
  66038. ** is read-only, the others are read/write.
  66039. **
  66040. ** The schema layer numbers meta values differently. At the schema
  66041. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  66042. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  66043. **
  66044. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  66045. ** of reading the value out of the header, it instead loads the "DataVersion"
  66046. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  66047. ** database file. It is a number computed by the pager. But its access
  66048. ** pattern is the same as header meta values, and so it is convenient to
  66049. ** read it from this routine.
  66050. */
  66051. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  66052. BtShared *pBt = p->pBt;
  66053. sqlite3BtreeEnter(p);
  66054. assert( p->inTrans>TRANS_NONE );
  66055. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  66056. assert( pBt->pPage1 );
  66057. assert( idx>=0 && idx<=15 );
  66058. if( idx==BTREE_DATA_VERSION ){
  66059. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  66060. }else{
  66061. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  66062. }
  66063. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  66064. ** database, mark the database as read-only. */
  66065. #ifdef SQLITE_OMIT_AUTOVACUUM
  66066. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  66067. pBt->btsFlags |= BTS_READ_ONLY;
  66068. }
  66069. #endif
  66070. sqlite3BtreeLeave(p);
  66071. }
  66072. /*
  66073. ** Write meta-information back into the database. Meta[0] is
  66074. ** read-only and may not be written.
  66075. */
  66076. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  66077. BtShared *pBt = p->pBt;
  66078. unsigned char *pP1;
  66079. int rc;
  66080. assert( idx>=1 && idx<=15 );
  66081. sqlite3BtreeEnter(p);
  66082. assert( p->inTrans==TRANS_WRITE );
  66083. assert( pBt->pPage1!=0 );
  66084. pP1 = pBt->pPage1->aData;
  66085. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  66086. if( rc==SQLITE_OK ){
  66087. put4byte(&pP1[36 + idx*4], iMeta);
  66088. #ifndef SQLITE_OMIT_AUTOVACUUM
  66089. if( idx==BTREE_INCR_VACUUM ){
  66090. assert( pBt->autoVacuum || iMeta==0 );
  66091. assert( iMeta==0 || iMeta==1 );
  66092. pBt->incrVacuum = (u8)iMeta;
  66093. }
  66094. #endif
  66095. }
  66096. sqlite3BtreeLeave(p);
  66097. return rc;
  66098. }
  66099. #ifndef SQLITE_OMIT_BTREECOUNT
  66100. /*
  66101. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  66102. ** number of entries in the b-tree and write the result to *pnEntry.
  66103. **
  66104. ** SQLITE_OK is returned if the operation is successfully executed.
  66105. ** Otherwise, if an error is encountered (i.e. an IO error or database
  66106. ** corruption) an SQLite error code is returned.
  66107. */
  66108. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  66109. i64 nEntry = 0; /* Value to return in *pnEntry */
  66110. int rc; /* Return code */
  66111. rc = moveToRoot(pCur);
  66112. if( rc==SQLITE_EMPTY ){
  66113. *pnEntry = 0;
  66114. return SQLITE_OK;
  66115. }
  66116. /* Unless an error occurs, the following loop runs one iteration for each
  66117. ** page in the B-Tree structure (not including overflow pages).
  66118. */
  66119. while( rc==SQLITE_OK ){
  66120. int iIdx; /* Index of child node in parent */
  66121. MemPage *pPage; /* Current page of the b-tree */
  66122. /* If this is a leaf page or the tree is not an int-key tree, then
  66123. ** this page contains countable entries. Increment the entry counter
  66124. ** accordingly.
  66125. */
  66126. pPage = pCur->pPage;
  66127. if( pPage->leaf || !pPage->intKey ){
  66128. nEntry += pPage->nCell;
  66129. }
  66130. /* pPage is a leaf node. This loop navigates the cursor so that it
  66131. ** points to the first interior cell that it points to the parent of
  66132. ** the next page in the tree that has not yet been visited. The
  66133. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  66134. ** of the page, or to the number of cells in the page if the next page
  66135. ** to visit is the right-child of its parent.
  66136. **
  66137. ** If all pages in the tree have been visited, return SQLITE_OK to the
  66138. ** caller.
  66139. */
  66140. if( pPage->leaf ){
  66141. do {
  66142. if( pCur->iPage==0 ){
  66143. /* All pages of the b-tree have been visited. Return successfully. */
  66144. *pnEntry = nEntry;
  66145. return moveToRoot(pCur);
  66146. }
  66147. moveToParent(pCur);
  66148. }while ( pCur->ix>=pCur->pPage->nCell );
  66149. pCur->ix++;
  66150. pPage = pCur->pPage;
  66151. }
  66152. /* Descend to the child node of the cell that the cursor currently
  66153. ** points at. This is the right-child if (iIdx==pPage->nCell).
  66154. */
  66155. iIdx = pCur->ix;
  66156. if( iIdx==pPage->nCell ){
  66157. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  66158. }else{
  66159. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  66160. }
  66161. }
  66162. /* An error has occurred. Return an error code. */
  66163. return rc;
  66164. }
  66165. #endif
  66166. /*
  66167. ** Return the pager associated with a BTree. This routine is used for
  66168. ** testing and debugging only.
  66169. */
  66170. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  66171. return p->pBt->pPager;
  66172. }
  66173. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  66174. /*
  66175. ** Append a message to the error message string.
  66176. */
  66177. static void checkAppendMsg(
  66178. IntegrityCk *pCheck,
  66179. const char *zFormat,
  66180. ...
  66181. ){
  66182. va_list ap;
  66183. if( !pCheck->mxErr ) return;
  66184. pCheck->mxErr--;
  66185. pCheck->nErr++;
  66186. va_start(ap, zFormat);
  66187. if( pCheck->errMsg.nChar ){
  66188. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  66189. }
  66190. if( pCheck->zPfx ){
  66191. sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
  66192. }
  66193. sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
  66194. va_end(ap);
  66195. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  66196. pCheck->mallocFailed = 1;
  66197. }
  66198. }
  66199. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  66200. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  66201. /*
  66202. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  66203. ** corresponds to page iPg is already set.
  66204. */
  66205. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  66206. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  66207. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  66208. }
  66209. /*
  66210. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  66211. */
  66212. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  66213. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  66214. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  66215. }
  66216. /*
  66217. ** Add 1 to the reference count for page iPage. If this is the second
  66218. ** reference to the page, add an error message to pCheck->zErrMsg.
  66219. ** Return 1 if there are 2 or more references to the page and 0 if
  66220. ** if this is the first reference to the page.
  66221. **
  66222. ** Also check that the page number is in bounds.
  66223. */
  66224. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  66225. if( iPage==0 ) return 1;
  66226. if( iPage>pCheck->nPage ){
  66227. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  66228. return 1;
  66229. }
  66230. if( getPageReferenced(pCheck, iPage) ){
  66231. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  66232. return 1;
  66233. }
  66234. setPageReferenced(pCheck, iPage);
  66235. return 0;
  66236. }
  66237. #ifndef SQLITE_OMIT_AUTOVACUUM
  66238. /*
  66239. ** Check that the entry in the pointer-map for page iChild maps to
  66240. ** page iParent, pointer type ptrType. If not, append an error message
  66241. ** to pCheck.
  66242. */
  66243. static void checkPtrmap(
  66244. IntegrityCk *pCheck, /* Integrity check context */
  66245. Pgno iChild, /* Child page number */
  66246. u8 eType, /* Expected pointer map type */
  66247. Pgno iParent /* Expected pointer map parent page number */
  66248. ){
  66249. int rc;
  66250. u8 ePtrmapType;
  66251. Pgno iPtrmapParent;
  66252. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  66253. if( rc!=SQLITE_OK ){
  66254. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  66255. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  66256. return;
  66257. }
  66258. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  66259. checkAppendMsg(pCheck,
  66260. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  66261. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  66262. }
  66263. }
  66264. #endif
  66265. /*
  66266. ** Check the integrity of the freelist or of an overflow page list.
  66267. ** Verify that the number of pages on the list is N.
  66268. */
  66269. static void checkList(
  66270. IntegrityCk *pCheck, /* Integrity checking context */
  66271. int isFreeList, /* True for a freelist. False for overflow page list */
  66272. int iPage, /* Page number for first page in the list */
  66273. int N /* Expected number of pages in the list */
  66274. ){
  66275. int i;
  66276. int expected = N;
  66277. int iFirst = iPage;
  66278. while( N-- > 0 && pCheck->mxErr ){
  66279. DbPage *pOvflPage;
  66280. unsigned char *pOvflData;
  66281. if( iPage<1 ){
  66282. checkAppendMsg(pCheck,
  66283. "%d of %d pages missing from overflow list starting at %d",
  66284. N+1, expected, iFirst);
  66285. break;
  66286. }
  66287. if( checkRef(pCheck, iPage) ) break;
  66288. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  66289. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  66290. break;
  66291. }
  66292. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  66293. if( isFreeList ){
  66294. int n = get4byte(&pOvflData[4]);
  66295. #ifndef SQLITE_OMIT_AUTOVACUUM
  66296. if( pCheck->pBt->autoVacuum ){
  66297. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  66298. }
  66299. #endif
  66300. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  66301. checkAppendMsg(pCheck,
  66302. "freelist leaf count too big on page %d", iPage);
  66303. N--;
  66304. }else{
  66305. for(i=0; i<n; i++){
  66306. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  66307. #ifndef SQLITE_OMIT_AUTOVACUUM
  66308. if( pCheck->pBt->autoVacuum ){
  66309. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  66310. }
  66311. #endif
  66312. checkRef(pCheck, iFreePage);
  66313. }
  66314. N -= n;
  66315. }
  66316. }
  66317. #ifndef SQLITE_OMIT_AUTOVACUUM
  66318. else{
  66319. /* If this database supports auto-vacuum and iPage is not the last
  66320. ** page in this overflow list, check that the pointer-map entry for
  66321. ** the following page matches iPage.
  66322. */
  66323. if( pCheck->pBt->autoVacuum && N>0 ){
  66324. i = get4byte(pOvflData);
  66325. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  66326. }
  66327. }
  66328. #endif
  66329. iPage = get4byte(pOvflData);
  66330. sqlite3PagerUnref(pOvflPage);
  66331. if( isFreeList && N<(iPage!=0) ){
  66332. checkAppendMsg(pCheck, "free-page count in header is too small");
  66333. }
  66334. }
  66335. }
  66336. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  66337. /*
  66338. ** An implementation of a min-heap.
  66339. **
  66340. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  66341. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  66342. ** and aHeap[N*2+1].
  66343. **
  66344. ** The heap property is this: Every node is less than or equal to both
  66345. ** of its daughter nodes. A consequence of the heap property is that the
  66346. ** root node aHeap[1] is always the minimum value currently in the heap.
  66347. **
  66348. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  66349. ** the heap, preserving the heap property. The btreeHeapPull() routine
  66350. ** removes the root element from the heap (the minimum value in the heap)
  66351. ** and then moves other nodes around as necessary to preserve the heap
  66352. ** property.
  66353. **
  66354. ** This heap is used for cell overlap and coverage testing. Each u32
  66355. ** entry represents the span of a cell or freeblock on a btree page.
  66356. ** The upper 16 bits are the index of the first byte of a range and the
  66357. ** lower 16 bits are the index of the last byte of that range.
  66358. */
  66359. static void btreeHeapInsert(u32 *aHeap, u32 x){
  66360. u32 j, i = ++aHeap[0];
  66361. aHeap[i] = x;
  66362. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  66363. x = aHeap[j];
  66364. aHeap[j] = aHeap[i];
  66365. aHeap[i] = x;
  66366. i = j;
  66367. }
  66368. }
  66369. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  66370. u32 j, i, x;
  66371. if( (x = aHeap[0])==0 ) return 0;
  66372. *pOut = aHeap[1];
  66373. aHeap[1] = aHeap[x];
  66374. aHeap[x] = 0xffffffff;
  66375. aHeap[0]--;
  66376. i = 1;
  66377. while( (j = i*2)<=aHeap[0] ){
  66378. if( aHeap[j]>aHeap[j+1] ) j++;
  66379. if( aHeap[i]<aHeap[j] ) break;
  66380. x = aHeap[i];
  66381. aHeap[i] = aHeap[j];
  66382. aHeap[j] = x;
  66383. i = j;
  66384. }
  66385. return 1;
  66386. }
  66387. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  66388. /*
  66389. ** Do various sanity checks on a single page of a tree. Return
  66390. ** the tree depth. Root pages return 0. Parents of root pages
  66391. ** return 1, and so forth.
  66392. **
  66393. ** These checks are done:
  66394. **
  66395. ** 1. Make sure that cells and freeblocks do not overlap
  66396. ** but combine to completely cover the page.
  66397. ** 2. Make sure integer cell keys are in order.
  66398. ** 3. Check the integrity of overflow pages.
  66399. ** 4. Recursively call checkTreePage on all children.
  66400. ** 5. Verify that the depth of all children is the same.
  66401. */
  66402. static int checkTreePage(
  66403. IntegrityCk *pCheck, /* Context for the sanity check */
  66404. int iPage, /* Page number of the page to check */
  66405. i64 *piMinKey, /* Write minimum integer primary key here */
  66406. i64 maxKey /* Error if integer primary key greater than this */
  66407. ){
  66408. MemPage *pPage = 0; /* The page being analyzed */
  66409. int i; /* Loop counter */
  66410. int rc; /* Result code from subroutine call */
  66411. int depth = -1, d2; /* Depth of a subtree */
  66412. int pgno; /* Page number */
  66413. int nFrag; /* Number of fragmented bytes on the page */
  66414. int hdr; /* Offset to the page header */
  66415. int cellStart; /* Offset to the start of the cell pointer array */
  66416. int nCell; /* Number of cells */
  66417. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  66418. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  66419. ** False if IPK must be strictly less than maxKey */
  66420. u8 *data; /* Page content */
  66421. u8 *pCell; /* Cell content */
  66422. u8 *pCellIdx; /* Next element of the cell pointer array */
  66423. BtShared *pBt; /* The BtShared object that owns pPage */
  66424. u32 pc; /* Address of a cell */
  66425. u32 usableSize; /* Usable size of the page */
  66426. u32 contentOffset; /* Offset to the start of the cell content area */
  66427. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  66428. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  66429. const char *saved_zPfx = pCheck->zPfx;
  66430. int saved_v1 = pCheck->v1;
  66431. int saved_v2 = pCheck->v2;
  66432. u8 savedIsInit = 0;
  66433. /* Check that the page exists
  66434. */
  66435. pBt = pCheck->pBt;
  66436. usableSize = pBt->usableSize;
  66437. if( iPage==0 ) return 0;
  66438. if( checkRef(pCheck, iPage) ) return 0;
  66439. pCheck->zPfx = "Page %d: ";
  66440. pCheck->v1 = iPage;
  66441. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  66442. checkAppendMsg(pCheck,
  66443. "unable to get the page. error code=%d", rc);
  66444. goto end_of_check;
  66445. }
  66446. /* Clear MemPage.isInit to make sure the corruption detection code in
  66447. ** btreeInitPage() is executed. */
  66448. savedIsInit = pPage->isInit;
  66449. pPage->isInit = 0;
  66450. if( (rc = btreeInitPage(pPage))!=0 ){
  66451. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  66452. checkAppendMsg(pCheck,
  66453. "btreeInitPage() returns error code %d", rc);
  66454. goto end_of_check;
  66455. }
  66456. data = pPage->aData;
  66457. hdr = pPage->hdrOffset;
  66458. /* Set up for cell analysis */
  66459. pCheck->zPfx = "On tree page %d cell %d: ";
  66460. contentOffset = get2byteNotZero(&data[hdr+5]);
  66461. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  66462. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  66463. ** number of cells on the page. */
  66464. nCell = get2byte(&data[hdr+3]);
  66465. assert( pPage->nCell==nCell );
  66466. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  66467. ** immediately follows the b-tree page header. */
  66468. cellStart = hdr + 12 - 4*pPage->leaf;
  66469. assert( pPage->aCellIdx==&data[cellStart] );
  66470. pCellIdx = &data[cellStart + 2*(nCell-1)];
  66471. if( !pPage->leaf ){
  66472. /* Analyze the right-child page of internal pages */
  66473. pgno = get4byte(&data[hdr+8]);
  66474. #ifndef SQLITE_OMIT_AUTOVACUUM
  66475. if( pBt->autoVacuum ){
  66476. pCheck->zPfx = "On page %d at right child: ";
  66477. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  66478. }
  66479. #endif
  66480. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  66481. keyCanBeEqual = 0;
  66482. }else{
  66483. /* For leaf pages, the coverage check will occur in the same loop
  66484. ** as the other cell checks, so initialize the heap. */
  66485. heap = pCheck->heap;
  66486. heap[0] = 0;
  66487. }
  66488. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  66489. ** integer offsets to the cell contents. */
  66490. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  66491. CellInfo info;
  66492. /* Check cell size */
  66493. pCheck->v2 = i;
  66494. assert( pCellIdx==&data[cellStart + i*2] );
  66495. pc = get2byteAligned(pCellIdx);
  66496. pCellIdx -= 2;
  66497. if( pc<contentOffset || pc>usableSize-4 ){
  66498. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  66499. pc, contentOffset, usableSize-4);
  66500. doCoverageCheck = 0;
  66501. continue;
  66502. }
  66503. pCell = &data[pc];
  66504. pPage->xParseCell(pPage, pCell, &info);
  66505. if( pc+info.nSize>usableSize ){
  66506. checkAppendMsg(pCheck, "Extends off end of page");
  66507. doCoverageCheck = 0;
  66508. continue;
  66509. }
  66510. /* Check for integer primary key out of range */
  66511. if( pPage->intKey ){
  66512. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  66513. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  66514. }
  66515. maxKey = info.nKey;
  66516. keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
  66517. }
  66518. /* Check the content overflow list */
  66519. if( info.nPayload>info.nLocal ){
  66520. int nPage; /* Number of pages on the overflow chain */
  66521. Pgno pgnoOvfl; /* First page of the overflow chain */
  66522. assert( pc + info.nSize - 4 <= usableSize );
  66523. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  66524. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  66525. #ifndef SQLITE_OMIT_AUTOVACUUM
  66526. if( pBt->autoVacuum ){
  66527. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  66528. }
  66529. #endif
  66530. checkList(pCheck, 0, pgnoOvfl, nPage);
  66531. }
  66532. if( !pPage->leaf ){
  66533. /* Check sanity of left child page for internal pages */
  66534. pgno = get4byte(pCell);
  66535. #ifndef SQLITE_OMIT_AUTOVACUUM
  66536. if( pBt->autoVacuum ){
  66537. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  66538. }
  66539. #endif
  66540. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  66541. keyCanBeEqual = 0;
  66542. if( d2!=depth ){
  66543. checkAppendMsg(pCheck, "Child page depth differs");
  66544. depth = d2;
  66545. }
  66546. }else{
  66547. /* Populate the coverage-checking heap for leaf pages */
  66548. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  66549. }
  66550. }
  66551. *piMinKey = maxKey;
  66552. /* Check for complete coverage of the page
  66553. */
  66554. pCheck->zPfx = 0;
  66555. if( doCoverageCheck && pCheck->mxErr>0 ){
  66556. /* For leaf pages, the min-heap has already been initialized and the
  66557. ** cells have already been inserted. But for internal pages, that has
  66558. ** not yet been done, so do it now */
  66559. if( !pPage->leaf ){
  66560. heap = pCheck->heap;
  66561. heap[0] = 0;
  66562. for(i=nCell-1; i>=0; i--){
  66563. u32 size;
  66564. pc = get2byteAligned(&data[cellStart+i*2]);
  66565. size = pPage->xCellSize(pPage, &data[pc]);
  66566. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  66567. }
  66568. }
  66569. /* Add the freeblocks to the min-heap
  66570. **
  66571. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  66572. ** is the offset of the first freeblock, or zero if there are no
  66573. ** freeblocks on the page.
  66574. */
  66575. i = get2byte(&data[hdr+1]);
  66576. while( i>0 ){
  66577. int size, j;
  66578. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  66579. size = get2byte(&data[i+2]);
  66580. assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
  66581. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  66582. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  66583. ** big-endian integer which is the offset in the b-tree page of the next
  66584. ** freeblock in the chain, or zero if the freeblock is the last on the
  66585. ** chain. */
  66586. j = get2byte(&data[i]);
  66587. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  66588. ** increasing offset. */
  66589. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  66590. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  66591. i = j;
  66592. }
  66593. /* Analyze the min-heap looking for overlap between cells and/or
  66594. ** freeblocks, and counting the number of untracked bytes in nFrag.
  66595. **
  66596. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  66597. ** There is an implied first entry the covers the page header, the cell
  66598. ** pointer index, and the gap between the cell pointer index and the start
  66599. ** of cell content.
  66600. **
  66601. ** The loop below pulls entries from the min-heap in order and compares
  66602. ** the start_address against the previous end_address. If there is an
  66603. ** overlap, that means bytes are used multiple times. If there is a gap,
  66604. ** that gap is added to the fragmentation count.
  66605. */
  66606. nFrag = 0;
  66607. prev = contentOffset - 1; /* Implied first min-heap entry */
  66608. while( btreeHeapPull(heap,&x) ){
  66609. if( (prev&0xffff)>=(x>>16) ){
  66610. checkAppendMsg(pCheck,
  66611. "Multiple uses for byte %u of page %d", x>>16, iPage);
  66612. break;
  66613. }else{
  66614. nFrag += (x>>16) - (prev&0xffff) - 1;
  66615. prev = x;
  66616. }
  66617. }
  66618. nFrag += usableSize - (prev&0xffff) - 1;
  66619. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  66620. ** is stored in the fifth field of the b-tree page header.
  66621. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  66622. ** number of fragmented free bytes within the cell content area.
  66623. */
  66624. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  66625. checkAppendMsg(pCheck,
  66626. "Fragmentation of %d bytes reported as %d on page %d",
  66627. nFrag, data[hdr+7], iPage);
  66628. }
  66629. }
  66630. end_of_check:
  66631. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  66632. releasePage(pPage);
  66633. pCheck->zPfx = saved_zPfx;
  66634. pCheck->v1 = saved_v1;
  66635. pCheck->v2 = saved_v2;
  66636. return depth+1;
  66637. }
  66638. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  66639. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  66640. /*
  66641. ** This routine does a complete check of the given BTree file. aRoot[] is
  66642. ** an array of pages numbers were each page number is the root page of
  66643. ** a table. nRoot is the number of entries in aRoot.
  66644. **
  66645. ** A read-only or read-write transaction must be opened before calling
  66646. ** this function.
  66647. **
  66648. ** Write the number of error seen in *pnErr. Except for some memory
  66649. ** allocation errors, an error message held in memory obtained from
  66650. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  66651. ** returned. If a memory allocation error occurs, NULL is returned.
  66652. */
  66653. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  66654. Btree *p, /* The btree to be checked */
  66655. int *aRoot, /* An array of root pages numbers for individual trees */
  66656. int nRoot, /* Number of entries in aRoot[] */
  66657. int mxErr, /* Stop reporting errors after this many */
  66658. int *pnErr /* Write number of errors seen to this variable */
  66659. ){
  66660. Pgno i;
  66661. IntegrityCk sCheck;
  66662. BtShared *pBt = p->pBt;
  66663. int savedDbFlags = pBt->db->flags;
  66664. char zErr[100];
  66665. VVA_ONLY( int nRef );
  66666. sqlite3BtreeEnter(p);
  66667. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  66668. VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
  66669. assert( nRef>=0 );
  66670. sCheck.pBt = pBt;
  66671. sCheck.pPager = pBt->pPager;
  66672. sCheck.nPage = btreePagecount(sCheck.pBt);
  66673. sCheck.mxErr = mxErr;
  66674. sCheck.nErr = 0;
  66675. sCheck.mallocFailed = 0;
  66676. sCheck.zPfx = 0;
  66677. sCheck.v1 = 0;
  66678. sCheck.v2 = 0;
  66679. sCheck.aPgRef = 0;
  66680. sCheck.heap = 0;
  66681. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  66682. sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
  66683. if( sCheck.nPage==0 ){
  66684. goto integrity_ck_cleanup;
  66685. }
  66686. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  66687. if( !sCheck.aPgRef ){
  66688. sCheck.mallocFailed = 1;
  66689. goto integrity_ck_cleanup;
  66690. }
  66691. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  66692. if( sCheck.heap==0 ){
  66693. sCheck.mallocFailed = 1;
  66694. goto integrity_ck_cleanup;
  66695. }
  66696. i = PENDING_BYTE_PAGE(pBt);
  66697. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  66698. /* Check the integrity of the freelist
  66699. */
  66700. sCheck.zPfx = "Main freelist: ";
  66701. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  66702. get4byte(&pBt->pPage1->aData[36]));
  66703. sCheck.zPfx = 0;
  66704. /* Check all the tables.
  66705. */
  66706. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  66707. pBt->db->flags &= ~SQLITE_CellSizeCk;
  66708. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  66709. i64 notUsed;
  66710. if( aRoot[i]==0 ) continue;
  66711. #ifndef SQLITE_OMIT_AUTOVACUUM
  66712. if( pBt->autoVacuum && aRoot[i]>1 ){
  66713. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  66714. }
  66715. #endif
  66716. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  66717. }
  66718. pBt->db->flags = savedDbFlags;
  66719. /* Make sure every page in the file is referenced
  66720. */
  66721. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  66722. #ifdef SQLITE_OMIT_AUTOVACUUM
  66723. if( getPageReferenced(&sCheck, i)==0 ){
  66724. checkAppendMsg(&sCheck, "Page %d is never used", i);
  66725. }
  66726. #else
  66727. /* If the database supports auto-vacuum, make sure no tables contain
  66728. ** references to pointer-map pages.
  66729. */
  66730. if( getPageReferenced(&sCheck, i)==0 &&
  66731. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  66732. checkAppendMsg(&sCheck, "Page %d is never used", i);
  66733. }
  66734. if( getPageReferenced(&sCheck, i)!=0 &&
  66735. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  66736. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  66737. }
  66738. #endif
  66739. }
  66740. /* Clean up and report errors.
  66741. */
  66742. integrity_ck_cleanup:
  66743. sqlite3PageFree(sCheck.heap);
  66744. sqlite3_free(sCheck.aPgRef);
  66745. if( sCheck.mallocFailed ){
  66746. sqlite3StrAccumReset(&sCheck.errMsg);
  66747. sCheck.nErr++;
  66748. }
  66749. *pnErr = sCheck.nErr;
  66750. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  66751. /* Make sure this analysis did not leave any unref() pages. */
  66752. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  66753. sqlite3BtreeLeave(p);
  66754. return sqlite3StrAccumFinish(&sCheck.errMsg);
  66755. }
  66756. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  66757. /*
  66758. ** Return the full pathname of the underlying database file. Return
  66759. ** an empty string if the database is in-memory or a TEMP database.
  66760. **
  66761. ** The pager filename is invariant as long as the pager is
  66762. ** open so it is safe to access without the BtShared mutex.
  66763. */
  66764. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  66765. assert( p->pBt->pPager!=0 );
  66766. return sqlite3PagerFilename(p->pBt->pPager, 1);
  66767. }
  66768. /*
  66769. ** Return the pathname of the journal file for this database. The return
  66770. ** value of this routine is the same regardless of whether the journal file
  66771. ** has been created or not.
  66772. **
  66773. ** The pager journal filename is invariant as long as the pager is
  66774. ** open so it is safe to access without the BtShared mutex.
  66775. */
  66776. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  66777. assert( p->pBt->pPager!=0 );
  66778. return sqlite3PagerJournalname(p->pBt->pPager);
  66779. }
  66780. /*
  66781. ** Return non-zero if a transaction is active.
  66782. */
  66783. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  66784. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  66785. return (p && (p->inTrans==TRANS_WRITE));
  66786. }
  66787. #ifndef SQLITE_OMIT_WAL
  66788. /*
  66789. ** Run a checkpoint on the Btree passed as the first argument.
  66790. **
  66791. ** Return SQLITE_LOCKED if this or any other connection has an open
  66792. ** transaction on the shared-cache the argument Btree is connected to.
  66793. **
  66794. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  66795. */
  66796. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  66797. int rc = SQLITE_OK;
  66798. if( p ){
  66799. BtShared *pBt = p->pBt;
  66800. sqlite3BtreeEnter(p);
  66801. if( pBt->inTransaction!=TRANS_NONE ){
  66802. rc = SQLITE_LOCKED;
  66803. }else{
  66804. rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
  66805. }
  66806. sqlite3BtreeLeave(p);
  66807. }
  66808. return rc;
  66809. }
  66810. #endif
  66811. /*
  66812. ** Return non-zero if a read (or write) transaction is active.
  66813. */
  66814. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  66815. assert( p );
  66816. assert( sqlite3_mutex_held(p->db->mutex) );
  66817. return p->inTrans!=TRANS_NONE;
  66818. }
  66819. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  66820. assert( p );
  66821. assert( sqlite3_mutex_held(p->db->mutex) );
  66822. return p->nBackup!=0;
  66823. }
  66824. /*
  66825. ** This function returns a pointer to a blob of memory associated with
  66826. ** a single shared-btree. The memory is used by client code for its own
  66827. ** purposes (for example, to store a high-level schema associated with
  66828. ** the shared-btree). The btree layer manages reference counting issues.
  66829. **
  66830. ** The first time this is called on a shared-btree, nBytes bytes of memory
  66831. ** are allocated, zeroed, and returned to the caller. For each subsequent
  66832. ** call the nBytes parameter is ignored and a pointer to the same blob
  66833. ** of memory returned.
  66834. **
  66835. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  66836. ** allocated, a null pointer is returned. If the blob has already been
  66837. ** allocated, it is returned as normal.
  66838. **
  66839. ** Just before the shared-btree is closed, the function passed as the
  66840. ** xFree argument when the memory allocation was made is invoked on the
  66841. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  66842. ** on the memory, the btree layer does that.
  66843. */
  66844. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  66845. BtShared *pBt = p->pBt;
  66846. sqlite3BtreeEnter(p);
  66847. if( !pBt->pSchema && nBytes ){
  66848. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  66849. pBt->xFreeSchema = xFree;
  66850. }
  66851. sqlite3BtreeLeave(p);
  66852. return pBt->pSchema;
  66853. }
  66854. /*
  66855. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  66856. ** btree as the argument handle holds an exclusive lock on the
  66857. ** sqlite_master table. Otherwise SQLITE_OK.
  66858. */
  66859. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  66860. int rc;
  66861. assert( sqlite3_mutex_held(p->db->mutex) );
  66862. sqlite3BtreeEnter(p);
  66863. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  66864. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  66865. sqlite3BtreeLeave(p);
  66866. return rc;
  66867. }
  66868. #ifndef SQLITE_OMIT_SHARED_CACHE
  66869. /*
  66870. ** Obtain a lock on the table whose root page is iTab. The
  66871. ** lock is a write lock if isWritelock is true or a read lock
  66872. ** if it is false.
  66873. */
  66874. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  66875. int rc = SQLITE_OK;
  66876. assert( p->inTrans!=TRANS_NONE );
  66877. if( p->sharable ){
  66878. u8 lockType = READ_LOCK + isWriteLock;
  66879. assert( READ_LOCK+1==WRITE_LOCK );
  66880. assert( isWriteLock==0 || isWriteLock==1 );
  66881. sqlite3BtreeEnter(p);
  66882. rc = querySharedCacheTableLock(p, iTab, lockType);
  66883. if( rc==SQLITE_OK ){
  66884. rc = setSharedCacheTableLock(p, iTab, lockType);
  66885. }
  66886. sqlite3BtreeLeave(p);
  66887. }
  66888. return rc;
  66889. }
  66890. #endif
  66891. #ifndef SQLITE_OMIT_INCRBLOB
  66892. /*
  66893. ** Argument pCsr must be a cursor opened for writing on an
  66894. ** INTKEY table currently pointing at a valid table entry.
  66895. ** This function modifies the data stored as part of that entry.
  66896. **
  66897. ** Only the data content may only be modified, it is not possible to
  66898. ** change the length of the data stored. If this function is called with
  66899. ** parameters that attempt to write past the end of the existing data,
  66900. ** no modifications are made and SQLITE_CORRUPT is returned.
  66901. */
  66902. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  66903. int rc;
  66904. assert( cursorOwnsBtShared(pCsr) );
  66905. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  66906. assert( pCsr->curFlags & BTCF_Incrblob );
  66907. rc = restoreCursorPosition(pCsr);
  66908. if( rc!=SQLITE_OK ){
  66909. return rc;
  66910. }
  66911. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  66912. if( pCsr->eState!=CURSOR_VALID ){
  66913. return SQLITE_ABORT;
  66914. }
  66915. /* Save the positions of all other cursors open on this table. This is
  66916. ** required in case any of them are holding references to an xFetch
  66917. ** version of the b-tree page modified by the accessPayload call below.
  66918. **
  66919. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  66920. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  66921. ** saveAllCursors can only return SQLITE_OK.
  66922. */
  66923. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  66924. assert( rc==SQLITE_OK );
  66925. /* Check some assumptions:
  66926. ** (a) the cursor is open for writing,
  66927. ** (b) there is a read/write transaction open,
  66928. ** (c) the connection holds a write-lock on the table (if required),
  66929. ** (d) there are no conflicting read-locks, and
  66930. ** (e) the cursor points at a valid row of an intKey table.
  66931. */
  66932. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  66933. return SQLITE_READONLY;
  66934. }
  66935. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  66936. && pCsr->pBt->inTransaction==TRANS_WRITE );
  66937. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  66938. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  66939. assert( pCsr->pPage->intKey );
  66940. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  66941. }
  66942. /*
  66943. ** Mark this cursor as an incremental blob cursor.
  66944. */
  66945. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  66946. pCur->curFlags |= BTCF_Incrblob;
  66947. pCur->pBtree->hasIncrblobCur = 1;
  66948. }
  66949. #endif
  66950. /*
  66951. ** Set both the "read version" (single byte at byte offset 18) and
  66952. ** "write version" (single byte at byte offset 19) fields in the database
  66953. ** header to iVersion.
  66954. */
  66955. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  66956. BtShared *pBt = pBtree->pBt;
  66957. int rc; /* Return code */
  66958. assert( iVersion==1 || iVersion==2 );
  66959. /* If setting the version fields to 1, do not automatically open the
  66960. ** WAL connection, even if the version fields are currently set to 2.
  66961. */
  66962. pBt->btsFlags &= ~BTS_NO_WAL;
  66963. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  66964. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  66965. if( rc==SQLITE_OK ){
  66966. u8 *aData = pBt->pPage1->aData;
  66967. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  66968. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  66969. if( rc==SQLITE_OK ){
  66970. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  66971. if( rc==SQLITE_OK ){
  66972. aData[18] = (u8)iVersion;
  66973. aData[19] = (u8)iVersion;
  66974. }
  66975. }
  66976. }
  66977. }
  66978. pBt->btsFlags &= ~BTS_NO_WAL;
  66979. return rc;
  66980. }
  66981. /*
  66982. ** Return true if the cursor has a hint specified. This routine is
  66983. ** only used from within assert() statements
  66984. */
  66985. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  66986. return (pCsr->hints & mask)!=0;
  66987. }
  66988. /*
  66989. ** Return true if the given Btree is read-only.
  66990. */
  66991. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  66992. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  66993. }
  66994. /*
  66995. ** Return the size of the header added to each page by this module.
  66996. */
  66997. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  66998. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  66999. /*
  67000. ** Return true if the Btree passed as the only argument is sharable.
  67001. */
  67002. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  67003. return p->sharable;
  67004. }
  67005. /*
  67006. ** Return the number of connections to the BtShared object accessed by
  67007. ** the Btree handle passed as the only argument. For private caches
  67008. ** this is always 1. For shared caches it may be 1 or greater.
  67009. */
  67010. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
  67011. testcase( p->sharable );
  67012. return p->pBt->nRef;
  67013. }
  67014. #endif
  67015. /************** End of btree.c ***********************************************/
  67016. /************** Begin file backup.c ******************************************/
  67017. /*
  67018. ** 2009 January 28
  67019. **
  67020. ** The author disclaims copyright to this source code. In place of
  67021. ** a legal notice, here is a blessing:
  67022. **
  67023. ** May you do good and not evil.
  67024. ** May you find forgiveness for yourself and forgive others.
  67025. ** May you share freely, never taking more than you give.
  67026. **
  67027. *************************************************************************
  67028. ** This file contains the implementation of the sqlite3_backup_XXX()
  67029. ** API functions and the related features.
  67030. */
  67031. /* #include "sqliteInt.h" */
  67032. /* #include "btreeInt.h" */
  67033. /*
  67034. ** Structure allocated for each backup operation.
  67035. */
  67036. struct sqlite3_backup {
  67037. sqlite3* pDestDb; /* Destination database handle */
  67038. Btree *pDest; /* Destination b-tree file */
  67039. u32 iDestSchema; /* Original schema cookie in destination */
  67040. int bDestLocked; /* True once a write-transaction is open on pDest */
  67041. Pgno iNext; /* Page number of the next source page to copy */
  67042. sqlite3* pSrcDb; /* Source database handle */
  67043. Btree *pSrc; /* Source b-tree file */
  67044. int rc; /* Backup process error code */
  67045. /* These two variables are set by every call to backup_step(). They are
  67046. ** read by calls to backup_remaining() and backup_pagecount().
  67047. */
  67048. Pgno nRemaining; /* Number of pages left to copy */
  67049. Pgno nPagecount; /* Total number of pages to copy */
  67050. int isAttached; /* True once backup has been registered with pager */
  67051. sqlite3_backup *pNext; /* Next backup associated with source pager */
  67052. };
  67053. /*
  67054. ** THREAD SAFETY NOTES:
  67055. **
  67056. ** Once it has been created using backup_init(), a single sqlite3_backup
  67057. ** structure may be accessed via two groups of thread-safe entry points:
  67058. **
  67059. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  67060. ** backup_finish(). Both these functions obtain the source database
  67061. ** handle mutex and the mutex associated with the source BtShared
  67062. ** structure, in that order.
  67063. **
  67064. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  67065. ** invoked by the pager layer to report various state changes in
  67066. ** the page cache associated with the source database. The mutex
  67067. ** associated with the source database BtShared structure will always
  67068. ** be held when either of these functions are invoked.
  67069. **
  67070. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  67071. ** backup_pagecount() are not thread-safe functions. If they are called
  67072. ** while some other thread is calling backup_step() or backup_finish(),
  67073. ** the values returned may be invalid. There is no way for a call to
  67074. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  67075. ** or backup_pagecount().
  67076. **
  67077. ** Depending on the SQLite configuration, the database handles and/or
  67078. ** the Btree objects may have their own mutexes that require locking.
  67079. ** Non-sharable Btrees (in-memory databases for example), do not have
  67080. ** associated mutexes.
  67081. */
  67082. /*
  67083. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  67084. ** in connection handle pDb. If such a database cannot be found, return
  67085. ** a NULL pointer and write an error message to pErrorDb.
  67086. **
  67087. ** If the "temp" database is requested, it may need to be opened by this
  67088. ** function. If an error occurs while doing so, return 0 and write an
  67089. ** error message to pErrorDb.
  67090. */
  67091. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  67092. int i = sqlite3FindDbName(pDb, zDb);
  67093. if( i==1 ){
  67094. Parse sParse;
  67095. int rc = 0;
  67096. memset(&sParse, 0, sizeof(sParse));
  67097. sParse.db = pDb;
  67098. if( sqlite3OpenTempDatabase(&sParse) ){
  67099. sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
  67100. rc = SQLITE_ERROR;
  67101. }
  67102. sqlite3DbFree(pErrorDb, sParse.zErrMsg);
  67103. sqlite3ParserReset(&sParse);
  67104. if( rc ){
  67105. return 0;
  67106. }
  67107. }
  67108. if( i<0 ){
  67109. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  67110. return 0;
  67111. }
  67112. return pDb->aDb[i].pBt;
  67113. }
  67114. /*
  67115. ** Attempt to set the page size of the destination to match the page size
  67116. ** of the source.
  67117. */
  67118. static int setDestPgsz(sqlite3_backup *p){
  67119. int rc;
  67120. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  67121. return rc;
  67122. }
  67123. /*
  67124. ** Check that there is no open read-transaction on the b-tree passed as the
  67125. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  67126. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  67127. ** message in database handle db.
  67128. */
  67129. static int checkReadTransaction(sqlite3 *db, Btree *p){
  67130. if( sqlite3BtreeIsInReadTrans(p) ){
  67131. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  67132. return SQLITE_ERROR;
  67133. }
  67134. return SQLITE_OK;
  67135. }
  67136. /*
  67137. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  67138. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  67139. ** a pointer to the new sqlite3_backup object.
  67140. **
  67141. ** If an error occurs, NULL is returned and an error code and error message
  67142. ** stored in database handle pDestDb.
  67143. */
  67144. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  67145. sqlite3* pDestDb, /* Database to write to */
  67146. const char *zDestDb, /* Name of database within pDestDb */
  67147. sqlite3* pSrcDb, /* Database connection to read from */
  67148. const char *zSrcDb /* Name of database within pSrcDb */
  67149. ){
  67150. sqlite3_backup *p; /* Value to return */
  67151. #ifdef SQLITE_ENABLE_API_ARMOR
  67152. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  67153. (void)SQLITE_MISUSE_BKPT;
  67154. return 0;
  67155. }
  67156. #endif
  67157. /* Lock the source database handle. The destination database
  67158. ** handle is not locked in this routine, but it is locked in
  67159. ** sqlite3_backup_step(). The user is required to ensure that no
  67160. ** other thread accesses the destination handle for the duration
  67161. ** of the backup operation. Any attempt to use the destination
  67162. ** database connection while a backup is in progress may cause
  67163. ** a malfunction or a deadlock.
  67164. */
  67165. sqlite3_mutex_enter(pSrcDb->mutex);
  67166. sqlite3_mutex_enter(pDestDb->mutex);
  67167. if( pSrcDb==pDestDb ){
  67168. sqlite3ErrorWithMsg(
  67169. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  67170. );
  67171. p = 0;
  67172. }else {
  67173. /* Allocate space for a new sqlite3_backup object...
  67174. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  67175. ** call to sqlite3_backup_init() and is destroyed by a call to
  67176. ** sqlite3_backup_finish(). */
  67177. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  67178. if( !p ){
  67179. sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
  67180. }
  67181. }
  67182. /* If the allocation succeeded, populate the new object. */
  67183. if( p ){
  67184. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  67185. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  67186. p->pDestDb = pDestDb;
  67187. p->pSrcDb = pSrcDb;
  67188. p->iNext = 1;
  67189. p->isAttached = 0;
  67190. if( 0==p->pSrc || 0==p->pDest
  67191. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  67192. ){
  67193. /* One (or both) of the named databases did not exist or an OOM
  67194. ** error was hit. Or there is a transaction open on the destination
  67195. ** database. The error has already been written into the pDestDb
  67196. ** handle. All that is left to do here is free the sqlite3_backup
  67197. ** structure. */
  67198. sqlite3_free(p);
  67199. p = 0;
  67200. }
  67201. }
  67202. if( p ){
  67203. p->pSrc->nBackup++;
  67204. }
  67205. sqlite3_mutex_leave(pDestDb->mutex);
  67206. sqlite3_mutex_leave(pSrcDb->mutex);
  67207. return p;
  67208. }
  67209. /*
  67210. ** Argument rc is an SQLite error code. Return true if this error is
  67211. ** considered fatal if encountered during a backup operation. All errors
  67212. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  67213. */
  67214. static int isFatalError(int rc){
  67215. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  67216. }
  67217. /*
  67218. ** Parameter zSrcData points to a buffer containing the data for
  67219. ** page iSrcPg from the source database. Copy this data into the
  67220. ** destination database.
  67221. */
  67222. static int backupOnePage(
  67223. sqlite3_backup *p, /* Backup handle */
  67224. Pgno iSrcPg, /* Source database page to backup */
  67225. const u8 *zSrcData, /* Source database page data */
  67226. int bUpdate /* True for an update, false otherwise */
  67227. ){
  67228. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  67229. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  67230. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  67231. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  67232. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  67233. #ifdef SQLITE_HAS_CODEC
  67234. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  67235. ** guaranteed that the shared-mutex is held by this thread, handle
  67236. ** p->pSrc may not actually be the owner. */
  67237. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  67238. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  67239. #endif
  67240. int rc = SQLITE_OK;
  67241. i64 iOff;
  67242. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  67243. assert( p->bDestLocked );
  67244. assert( !isFatalError(p->rc) );
  67245. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  67246. assert( zSrcData );
  67247. /* Catch the case where the destination is an in-memory database and the
  67248. ** page sizes of the source and destination differ.
  67249. */
  67250. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  67251. rc = SQLITE_READONLY;
  67252. }
  67253. #ifdef SQLITE_HAS_CODEC
  67254. /* Backup is not possible if the page size of the destination is changing
  67255. ** and a codec is in use.
  67256. */
  67257. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  67258. rc = SQLITE_READONLY;
  67259. }
  67260. /* Backup is not possible if the number of bytes of reserve space differ
  67261. ** between source and destination. If there is a difference, try to
  67262. ** fix the destination to agree with the source. If that is not possible,
  67263. ** then the backup cannot proceed.
  67264. */
  67265. if( nSrcReserve!=nDestReserve ){
  67266. u32 newPgsz = nSrcPgsz;
  67267. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  67268. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  67269. }
  67270. #endif
  67271. /* This loop runs once for each destination page spanned by the source
  67272. ** page. For each iteration, variable iOff is set to the byte offset
  67273. ** of the destination page.
  67274. */
  67275. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  67276. DbPage *pDestPg = 0;
  67277. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  67278. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  67279. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  67280. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  67281. ){
  67282. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  67283. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  67284. u8 *zOut = &zDestData[iOff%nDestPgsz];
  67285. /* Copy the data from the source page into the destination page.
  67286. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  67287. ** and the pager code use this trick (clearing the first byte
  67288. ** of the page 'extra' space to invalidate the Btree layers
  67289. ** cached parse of the page). MemPage.isInit is marked
  67290. ** "MUST BE FIRST" for this purpose.
  67291. */
  67292. memcpy(zOut, zIn, nCopy);
  67293. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  67294. if( iOff==0 && bUpdate==0 ){
  67295. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  67296. }
  67297. }
  67298. sqlite3PagerUnref(pDestPg);
  67299. }
  67300. return rc;
  67301. }
  67302. /*
  67303. ** If pFile is currently larger than iSize bytes, then truncate it to
  67304. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  67305. ** this function is a no-op.
  67306. **
  67307. ** Return SQLITE_OK if everything is successful, or an SQLite error
  67308. ** code if an error occurs.
  67309. */
  67310. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  67311. i64 iCurrent;
  67312. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  67313. if( rc==SQLITE_OK && iCurrent>iSize ){
  67314. rc = sqlite3OsTruncate(pFile, iSize);
  67315. }
  67316. return rc;
  67317. }
  67318. /*
  67319. ** Register this backup object with the associated source pager for
  67320. ** callbacks when pages are changed or the cache invalidated.
  67321. */
  67322. static void attachBackupObject(sqlite3_backup *p){
  67323. sqlite3_backup **pp;
  67324. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  67325. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  67326. p->pNext = *pp;
  67327. *pp = p;
  67328. p->isAttached = 1;
  67329. }
  67330. /*
  67331. ** Copy nPage pages from the source b-tree to the destination.
  67332. */
  67333. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  67334. int rc;
  67335. int destMode; /* Destination journal mode */
  67336. int pgszSrc = 0; /* Source page size */
  67337. int pgszDest = 0; /* Destination page size */
  67338. #ifdef SQLITE_ENABLE_API_ARMOR
  67339. if( p==0 ) return SQLITE_MISUSE_BKPT;
  67340. #endif
  67341. sqlite3_mutex_enter(p->pSrcDb->mutex);
  67342. sqlite3BtreeEnter(p->pSrc);
  67343. if( p->pDestDb ){
  67344. sqlite3_mutex_enter(p->pDestDb->mutex);
  67345. }
  67346. rc = p->rc;
  67347. if( !isFatalError(rc) ){
  67348. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  67349. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  67350. int ii; /* Iterator variable */
  67351. int nSrcPage = -1; /* Size of source db in pages */
  67352. int bCloseTrans = 0; /* True if src db requires unlocking */
  67353. /* If the source pager is currently in a write-transaction, return
  67354. ** SQLITE_BUSY immediately.
  67355. */
  67356. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  67357. rc = SQLITE_BUSY;
  67358. }else{
  67359. rc = SQLITE_OK;
  67360. }
  67361. /* If there is no open read-transaction on the source database, open
  67362. ** one now. If a transaction is opened here, then it will be closed
  67363. ** before this function exits.
  67364. */
  67365. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  67366. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  67367. bCloseTrans = 1;
  67368. }
  67369. /* If the destination database has not yet been locked (i.e. if this
  67370. ** is the first call to backup_step() for the current backup operation),
  67371. ** try to set its page size to the same as the source database. This
  67372. ** is especially important on ZipVFS systems, as in that case it is
  67373. ** not possible to create a database file that uses one page size by
  67374. ** writing to it with another. */
  67375. if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
  67376. rc = SQLITE_NOMEM;
  67377. }
  67378. /* Lock the destination database, if it is not locked already. */
  67379. if( SQLITE_OK==rc && p->bDestLocked==0
  67380. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  67381. ){
  67382. p->bDestLocked = 1;
  67383. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  67384. }
  67385. /* Do not allow backup if the destination database is in WAL mode
  67386. ** and the page sizes are different between source and destination */
  67387. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  67388. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  67389. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  67390. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  67391. rc = SQLITE_READONLY;
  67392. }
  67393. /* Now that there is a read-lock on the source database, query the
  67394. ** source pager for the number of pages in the database.
  67395. */
  67396. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  67397. assert( nSrcPage>=0 );
  67398. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  67399. const Pgno iSrcPg = p->iNext; /* Source page number */
  67400. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  67401. DbPage *pSrcPg; /* Source page object */
  67402. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  67403. if( rc==SQLITE_OK ){
  67404. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  67405. sqlite3PagerUnref(pSrcPg);
  67406. }
  67407. }
  67408. p->iNext++;
  67409. }
  67410. if( rc==SQLITE_OK ){
  67411. p->nPagecount = nSrcPage;
  67412. p->nRemaining = nSrcPage+1-p->iNext;
  67413. if( p->iNext>(Pgno)nSrcPage ){
  67414. rc = SQLITE_DONE;
  67415. }else if( !p->isAttached ){
  67416. attachBackupObject(p);
  67417. }
  67418. }
  67419. /* Update the schema version field in the destination database. This
  67420. ** is to make sure that the schema-version really does change in
  67421. ** the case where the source and destination databases have the
  67422. ** same schema version.
  67423. */
  67424. if( rc==SQLITE_DONE ){
  67425. if( nSrcPage==0 ){
  67426. rc = sqlite3BtreeNewDb(p->pDest);
  67427. nSrcPage = 1;
  67428. }
  67429. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  67430. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  67431. }
  67432. if( rc==SQLITE_OK ){
  67433. if( p->pDestDb ){
  67434. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  67435. }
  67436. if( destMode==PAGER_JOURNALMODE_WAL ){
  67437. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  67438. }
  67439. }
  67440. if( rc==SQLITE_OK ){
  67441. int nDestTruncate;
  67442. /* Set nDestTruncate to the final number of pages in the destination
  67443. ** database. The complication here is that the destination page
  67444. ** size may be different to the source page size.
  67445. **
  67446. ** If the source page size is smaller than the destination page size,
  67447. ** round up. In this case the call to sqlite3OsTruncate() below will
  67448. ** fix the size of the file. However it is important to call
  67449. ** sqlite3PagerTruncateImage() here so that any pages in the
  67450. ** destination file that lie beyond the nDestTruncate page mark are
  67451. ** journalled by PagerCommitPhaseOne() before they are destroyed
  67452. ** by the file truncation.
  67453. */
  67454. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  67455. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  67456. if( pgszSrc<pgszDest ){
  67457. int ratio = pgszDest/pgszSrc;
  67458. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  67459. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  67460. nDestTruncate--;
  67461. }
  67462. }else{
  67463. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  67464. }
  67465. assert( nDestTruncate>0 );
  67466. if( pgszSrc<pgszDest ){
  67467. /* If the source page-size is smaller than the destination page-size,
  67468. ** two extra things may need to happen:
  67469. **
  67470. ** * The destination may need to be truncated, and
  67471. **
  67472. ** * Data stored on the pages immediately following the
  67473. ** pending-byte page in the source database may need to be
  67474. ** copied into the destination database.
  67475. */
  67476. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  67477. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  67478. Pgno iPg;
  67479. int nDstPage;
  67480. i64 iOff;
  67481. i64 iEnd;
  67482. assert( pFile );
  67483. assert( nDestTruncate==0
  67484. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  67485. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  67486. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  67487. ));
  67488. /* This block ensures that all data required to recreate the original
  67489. ** database has been stored in the journal for pDestPager and the
  67490. ** journal synced to disk. So at this point we may safely modify
  67491. ** the database file in any way, knowing that if a power failure
  67492. ** occurs, the original database will be reconstructed from the
  67493. ** journal file. */
  67494. sqlite3PagerPagecount(pDestPager, &nDstPage);
  67495. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  67496. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  67497. DbPage *pPg;
  67498. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  67499. if( rc==SQLITE_OK ){
  67500. rc = sqlite3PagerWrite(pPg);
  67501. sqlite3PagerUnref(pPg);
  67502. }
  67503. }
  67504. }
  67505. if( rc==SQLITE_OK ){
  67506. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  67507. }
  67508. /* Write the extra pages and truncate the database file as required */
  67509. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  67510. for(
  67511. iOff=PENDING_BYTE+pgszSrc;
  67512. rc==SQLITE_OK && iOff<iEnd;
  67513. iOff+=pgszSrc
  67514. ){
  67515. PgHdr *pSrcPg = 0;
  67516. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  67517. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  67518. if( rc==SQLITE_OK ){
  67519. u8 *zData = sqlite3PagerGetData(pSrcPg);
  67520. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  67521. }
  67522. sqlite3PagerUnref(pSrcPg);
  67523. }
  67524. if( rc==SQLITE_OK ){
  67525. rc = backupTruncateFile(pFile, iSize);
  67526. }
  67527. /* Sync the database file to disk. */
  67528. if( rc==SQLITE_OK ){
  67529. rc = sqlite3PagerSync(pDestPager, 0);
  67530. }
  67531. }else{
  67532. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  67533. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  67534. }
  67535. /* Finish committing the transaction to the destination database. */
  67536. if( SQLITE_OK==rc
  67537. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  67538. ){
  67539. rc = SQLITE_DONE;
  67540. }
  67541. }
  67542. }
  67543. /* If bCloseTrans is true, then this function opened a read transaction
  67544. ** on the source database. Close the read transaction here. There is
  67545. ** no need to check the return values of the btree methods here, as
  67546. ** "committing" a read-only transaction cannot fail.
  67547. */
  67548. if( bCloseTrans ){
  67549. TESTONLY( int rc2 );
  67550. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  67551. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  67552. assert( rc2==SQLITE_OK );
  67553. }
  67554. if( rc==SQLITE_IOERR_NOMEM ){
  67555. rc = SQLITE_NOMEM_BKPT;
  67556. }
  67557. p->rc = rc;
  67558. }
  67559. if( p->pDestDb ){
  67560. sqlite3_mutex_leave(p->pDestDb->mutex);
  67561. }
  67562. sqlite3BtreeLeave(p->pSrc);
  67563. sqlite3_mutex_leave(p->pSrcDb->mutex);
  67564. return rc;
  67565. }
  67566. /*
  67567. ** Release all resources associated with an sqlite3_backup* handle.
  67568. */
  67569. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  67570. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  67571. sqlite3 *pSrcDb; /* Source database connection */
  67572. int rc; /* Value to return */
  67573. /* Enter the mutexes */
  67574. if( p==0 ) return SQLITE_OK;
  67575. pSrcDb = p->pSrcDb;
  67576. sqlite3_mutex_enter(pSrcDb->mutex);
  67577. sqlite3BtreeEnter(p->pSrc);
  67578. if( p->pDestDb ){
  67579. sqlite3_mutex_enter(p->pDestDb->mutex);
  67580. }
  67581. /* Detach this backup from the source pager. */
  67582. if( p->pDestDb ){
  67583. p->pSrc->nBackup--;
  67584. }
  67585. if( p->isAttached ){
  67586. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  67587. while( *pp!=p ){
  67588. pp = &(*pp)->pNext;
  67589. }
  67590. *pp = p->pNext;
  67591. }
  67592. /* If a transaction is still open on the Btree, roll it back. */
  67593. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  67594. /* Set the error code of the destination database handle. */
  67595. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  67596. if( p->pDestDb ){
  67597. sqlite3Error(p->pDestDb, rc);
  67598. /* Exit the mutexes and free the backup context structure. */
  67599. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  67600. }
  67601. sqlite3BtreeLeave(p->pSrc);
  67602. if( p->pDestDb ){
  67603. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  67604. ** call to sqlite3_backup_init() and is destroyed by a call to
  67605. ** sqlite3_backup_finish(). */
  67606. sqlite3_free(p);
  67607. }
  67608. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  67609. return rc;
  67610. }
  67611. /*
  67612. ** Return the number of pages still to be backed up as of the most recent
  67613. ** call to sqlite3_backup_step().
  67614. */
  67615. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  67616. #ifdef SQLITE_ENABLE_API_ARMOR
  67617. if( p==0 ){
  67618. (void)SQLITE_MISUSE_BKPT;
  67619. return 0;
  67620. }
  67621. #endif
  67622. return p->nRemaining;
  67623. }
  67624. /*
  67625. ** Return the total number of pages in the source database as of the most
  67626. ** recent call to sqlite3_backup_step().
  67627. */
  67628. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  67629. #ifdef SQLITE_ENABLE_API_ARMOR
  67630. if( p==0 ){
  67631. (void)SQLITE_MISUSE_BKPT;
  67632. return 0;
  67633. }
  67634. #endif
  67635. return p->nPagecount;
  67636. }
  67637. /*
  67638. ** This function is called after the contents of page iPage of the
  67639. ** source database have been modified. If page iPage has already been
  67640. ** copied into the destination database, then the data written to the
  67641. ** destination is now invalidated. The destination copy of iPage needs
  67642. ** to be updated with the new data before the backup operation is
  67643. ** complete.
  67644. **
  67645. ** It is assumed that the mutex associated with the BtShared object
  67646. ** corresponding to the source database is held when this function is
  67647. ** called.
  67648. */
  67649. static SQLITE_NOINLINE void backupUpdate(
  67650. sqlite3_backup *p,
  67651. Pgno iPage,
  67652. const u8 *aData
  67653. ){
  67654. assert( p!=0 );
  67655. do{
  67656. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  67657. if( !isFatalError(p->rc) && iPage<p->iNext ){
  67658. /* The backup process p has already copied page iPage. But now it
  67659. ** has been modified by a transaction on the source pager. Copy
  67660. ** the new data into the backup.
  67661. */
  67662. int rc;
  67663. assert( p->pDestDb );
  67664. sqlite3_mutex_enter(p->pDestDb->mutex);
  67665. rc = backupOnePage(p, iPage, aData, 1);
  67666. sqlite3_mutex_leave(p->pDestDb->mutex);
  67667. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  67668. if( rc!=SQLITE_OK ){
  67669. p->rc = rc;
  67670. }
  67671. }
  67672. }while( (p = p->pNext)!=0 );
  67673. }
  67674. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  67675. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  67676. }
  67677. /*
  67678. ** Restart the backup process. This is called when the pager layer
  67679. ** detects that the database has been modified by an external database
  67680. ** connection. In this case there is no way of knowing which of the
  67681. ** pages that have been copied into the destination database are still
  67682. ** valid and which are not, so the entire process needs to be restarted.
  67683. **
  67684. ** It is assumed that the mutex associated with the BtShared object
  67685. ** corresponding to the source database is held when this function is
  67686. ** called.
  67687. */
  67688. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  67689. sqlite3_backup *p; /* Iterator variable */
  67690. for(p=pBackup; p; p=p->pNext){
  67691. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  67692. p->iNext = 1;
  67693. }
  67694. }
  67695. #ifndef SQLITE_OMIT_VACUUM
  67696. /*
  67697. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  67698. ** must be active for both files.
  67699. **
  67700. ** The size of file pTo may be reduced by this operation. If anything
  67701. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  67702. ** transaction is committed before returning.
  67703. */
  67704. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  67705. int rc;
  67706. sqlite3_file *pFd; /* File descriptor for database pTo */
  67707. sqlite3_backup b;
  67708. sqlite3BtreeEnter(pTo);
  67709. sqlite3BtreeEnter(pFrom);
  67710. assert( sqlite3BtreeIsInTrans(pTo) );
  67711. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  67712. if( pFd->pMethods ){
  67713. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  67714. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  67715. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  67716. if( rc ) goto copy_finished;
  67717. }
  67718. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  67719. ** to 0. This is used by the implementations of sqlite3_backup_step()
  67720. ** and sqlite3_backup_finish() to detect that they are being called
  67721. ** from this function, not directly by the user.
  67722. */
  67723. memset(&b, 0, sizeof(b));
  67724. b.pSrcDb = pFrom->db;
  67725. b.pSrc = pFrom;
  67726. b.pDest = pTo;
  67727. b.iNext = 1;
  67728. #ifdef SQLITE_HAS_CODEC
  67729. sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
  67730. #endif
  67731. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  67732. ** file. By passing this as the number of pages to copy to
  67733. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  67734. ** within a single call (unless an error occurs). The assert() statement
  67735. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  67736. ** or an error code. */
  67737. sqlite3_backup_step(&b, 0x7FFFFFFF);
  67738. assert( b.rc!=SQLITE_OK );
  67739. rc = sqlite3_backup_finish(&b);
  67740. if( rc==SQLITE_OK ){
  67741. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  67742. }else{
  67743. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  67744. }
  67745. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  67746. copy_finished:
  67747. sqlite3BtreeLeave(pFrom);
  67748. sqlite3BtreeLeave(pTo);
  67749. return rc;
  67750. }
  67751. #endif /* SQLITE_OMIT_VACUUM */
  67752. /************** End of backup.c **********************************************/
  67753. /************** Begin file vdbemem.c *****************************************/
  67754. /*
  67755. ** 2004 May 26
  67756. **
  67757. ** The author disclaims copyright to this source code. In place of
  67758. ** a legal notice, here is a blessing:
  67759. **
  67760. ** May you do good and not evil.
  67761. ** May you find forgiveness for yourself and forgive others.
  67762. ** May you share freely, never taking more than you give.
  67763. **
  67764. *************************************************************************
  67765. **
  67766. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  67767. ** stores a single value in the VDBE. Mem is an opaque structure visible
  67768. ** only within the VDBE. Interface routines refer to a Mem using the
  67769. ** name sqlite_value
  67770. */
  67771. /* #include "sqliteInt.h" */
  67772. /* #include "vdbeInt.h" */
  67773. #ifdef SQLITE_DEBUG
  67774. /*
  67775. ** Check invariants on a Mem object.
  67776. **
  67777. ** This routine is intended for use inside of assert() statements, like
  67778. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  67779. */
  67780. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  67781. /* If MEM_Dyn is set then Mem.xDel!=0.
  67782. ** Mem.xDel might not be initialized if MEM_Dyn is clear.
  67783. */
  67784. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  67785. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  67786. ** ensure that if Mem.szMalloc>0 then it is safe to do
  67787. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  67788. ** That saves a few cycles in inner loops. */
  67789. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  67790. /* Cannot be both MEM_Int and MEM_Real at the same time */
  67791. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  67792. if( p->flags & MEM_Null ){
  67793. /* Cannot be both MEM_Null and some other type */
  67794. assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob
  67795. |MEM_RowSet|MEM_Frame|MEM_Agg))==0 );
  67796. /* If MEM_Null is set, then either the value is a pure NULL (the usual
  67797. ** case) or it is a pointer set using sqlite3_bind_pointer() or
  67798. ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be
  67799. ** set.
  67800. */
  67801. if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
  67802. /* This is a pointer type. There may be a flag to indicate what to
  67803. ** do with the pointer. */
  67804. assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  67805. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  67806. ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
  67807. /* No other bits set */
  67808. assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype
  67809. |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
  67810. }else{
  67811. /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
  67812. ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
  67813. }
  67814. }else{
  67815. /* The MEM_Cleared bit is only allowed on NULLs */
  67816. assert( (p->flags & MEM_Cleared)==0 );
  67817. }
  67818. /* The szMalloc field holds the correct memory allocation size */
  67819. assert( p->szMalloc==0
  67820. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  67821. /* If p holds a string or blob, the Mem.z must point to exactly
  67822. ** one of the following:
  67823. **
  67824. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  67825. ** (2) Memory to be freed using Mem.xDel
  67826. ** (3) An ephemeral string or blob
  67827. ** (4) A static string or blob
  67828. */
  67829. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  67830. assert(
  67831. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  67832. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  67833. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  67834. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  67835. );
  67836. }
  67837. return 1;
  67838. }
  67839. #endif
  67840. #ifdef SQLITE_DEBUG
  67841. /*
  67842. ** Check that string value of pMem agrees with its integer or real value.
  67843. **
  67844. ** A single int or real value always converts to the same strings. But
  67845. ** many different strings can be converted into the same int or real.
  67846. ** If a table contains a numeric value and an index is based on the
  67847. ** corresponding string value, then it is important that the string be
  67848. ** derived from the numeric value, not the other way around, to ensure
  67849. ** that the index and table are consistent. See ticket
  67850. ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
  67851. ** an example.
  67852. **
  67853. ** This routine looks at pMem to verify that if it has both a numeric
  67854. ** representation and a string representation then the string rep has
  67855. ** been derived from the numeric and not the other way around. It returns
  67856. ** true if everything is ok and false if there is a problem.
  67857. **
  67858. ** This routine is for use inside of assert() statements only.
  67859. */
  67860. SQLITE_PRIVATE int sqlite3VdbeMemConsistentDualRep(Mem *p){
  67861. char zBuf[100];
  67862. char *z;
  67863. int i, j, incr;
  67864. if( (p->flags & MEM_Str)==0 ) return 1;
  67865. if( (p->flags & (MEM_Int|MEM_Real))==0 ) return 1;
  67866. if( p->flags & MEM_Int ){
  67867. sqlite3_snprintf(sizeof(zBuf),zBuf,"%lld",p->u.i);
  67868. }else{
  67869. sqlite3_snprintf(sizeof(zBuf),zBuf,"%!.15g",p->u.r);
  67870. }
  67871. z = p->z;
  67872. i = j = 0;
  67873. incr = 1;
  67874. if( p->enc!=SQLITE_UTF8 ){
  67875. incr = 2;
  67876. if( p->enc==SQLITE_UTF16BE ) z++;
  67877. }
  67878. while( zBuf[j] ){
  67879. if( zBuf[j++]!=z[i] ) return 0;
  67880. i += incr;
  67881. }
  67882. return 1;
  67883. }
  67884. #endif /* SQLITE_DEBUG */
  67885. /*
  67886. ** If pMem is an object with a valid string representation, this routine
  67887. ** ensures the internal encoding for the string representation is
  67888. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  67889. **
  67890. ** If pMem is not a string object, or the encoding of the string
  67891. ** representation is already stored using the requested encoding, then this
  67892. ** routine is a no-op.
  67893. **
  67894. ** SQLITE_OK is returned if the conversion is successful (or not required).
  67895. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  67896. ** between formats.
  67897. */
  67898. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  67899. #ifndef SQLITE_OMIT_UTF16
  67900. int rc;
  67901. #endif
  67902. assert( (pMem->flags&MEM_RowSet)==0 );
  67903. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  67904. || desiredEnc==SQLITE_UTF16BE );
  67905. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  67906. return SQLITE_OK;
  67907. }
  67908. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  67909. #ifdef SQLITE_OMIT_UTF16
  67910. return SQLITE_ERROR;
  67911. #else
  67912. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  67913. ** then the encoding of the value may not have changed.
  67914. */
  67915. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  67916. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  67917. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  67918. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  67919. return rc;
  67920. #endif
  67921. }
  67922. /*
  67923. ** Make sure pMem->z points to a writable allocation of at least
  67924. ** min(n,32) bytes.
  67925. **
  67926. ** If the bPreserve argument is true, then copy of the content of
  67927. ** pMem->z into the new allocation. pMem must be either a string or
  67928. ** blob if bPreserve is true. If bPreserve is false, any prior content
  67929. ** in pMem->z is discarded.
  67930. */
  67931. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  67932. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  67933. assert( (pMem->flags&MEM_RowSet)==0 );
  67934. testcase( pMem->db==0 );
  67935. /* If the bPreserve flag is set to true, then the memory cell must already
  67936. ** contain a valid string or blob value. */
  67937. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  67938. testcase( bPreserve && pMem->z==0 );
  67939. assert( pMem->szMalloc==0
  67940. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  67941. if( n<32 ) n = 32;
  67942. if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
  67943. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  67944. bPreserve = 0;
  67945. }else{
  67946. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  67947. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  67948. }
  67949. if( pMem->zMalloc==0 ){
  67950. sqlite3VdbeMemSetNull(pMem);
  67951. pMem->z = 0;
  67952. pMem->szMalloc = 0;
  67953. return SQLITE_NOMEM_BKPT;
  67954. }else{
  67955. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  67956. }
  67957. if( bPreserve && pMem->z ){
  67958. assert( pMem->z!=pMem->zMalloc );
  67959. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  67960. }
  67961. if( (pMem->flags&MEM_Dyn)!=0 ){
  67962. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  67963. pMem->xDel((void *)(pMem->z));
  67964. }
  67965. pMem->z = pMem->zMalloc;
  67966. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  67967. return SQLITE_OK;
  67968. }
  67969. /*
  67970. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  67971. ** If pMem->zMalloc already meets or exceeds the requested size, this
  67972. ** routine is a no-op.
  67973. **
  67974. ** Any prior string or blob content in the pMem object may be discarded.
  67975. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  67976. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  67977. ** values are preserved.
  67978. **
  67979. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  67980. ** if unable to complete the resizing.
  67981. */
  67982. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  67983. assert( szNew>0 );
  67984. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  67985. if( pMem->szMalloc<szNew ){
  67986. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  67987. }
  67988. assert( (pMem->flags & MEM_Dyn)==0 );
  67989. pMem->z = pMem->zMalloc;
  67990. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  67991. return SQLITE_OK;
  67992. }
  67993. /*
  67994. ** It is already known that pMem contains an unterminated string.
  67995. ** Add the zero terminator.
  67996. */
  67997. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  67998. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  67999. return SQLITE_NOMEM_BKPT;
  68000. }
  68001. pMem->z[pMem->n] = 0;
  68002. pMem->z[pMem->n+1] = 0;
  68003. pMem->flags |= MEM_Term;
  68004. return SQLITE_OK;
  68005. }
  68006. /*
  68007. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  68008. ** MEM.zMalloc, where it can be safely written.
  68009. **
  68010. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  68011. */
  68012. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  68013. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68014. assert( (pMem->flags&MEM_RowSet)==0 );
  68015. if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
  68016. if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
  68017. if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
  68018. int rc = vdbeMemAddTerminator(pMem);
  68019. if( rc ) return rc;
  68020. }
  68021. }
  68022. pMem->flags &= ~MEM_Ephem;
  68023. #ifdef SQLITE_DEBUG
  68024. pMem->pScopyFrom = 0;
  68025. #endif
  68026. return SQLITE_OK;
  68027. }
  68028. /*
  68029. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  68030. ** blob stored in dynamically allocated space.
  68031. */
  68032. #ifndef SQLITE_OMIT_INCRBLOB
  68033. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  68034. int nByte;
  68035. assert( pMem->flags & MEM_Zero );
  68036. assert( pMem->flags&MEM_Blob );
  68037. assert( (pMem->flags&MEM_RowSet)==0 );
  68038. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68039. /* Set nByte to the number of bytes required to store the expanded blob. */
  68040. nByte = pMem->n + pMem->u.nZero;
  68041. if( nByte<=0 ){
  68042. nByte = 1;
  68043. }
  68044. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  68045. return SQLITE_NOMEM_BKPT;
  68046. }
  68047. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  68048. pMem->n += pMem->u.nZero;
  68049. pMem->flags &= ~(MEM_Zero|MEM_Term);
  68050. return SQLITE_OK;
  68051. }
  68052. #endif
  68053. /*
  68054. ** Make sure the given Mem is \u0000 terminated.
  68055. */
  68056. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  68057. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68058. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  68059. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  68060. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  68061. return SQLITE_OK; /* Nothing to do */
  68062. }else{
  68063. return vdbeMemAddTerminator(pMem);
  68064. }
  68065. }
  68066. /*
  68067. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  68068. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  68069. ** is a no-op.
  68070. **
  68071. ** Existing representations MEM_Int and MEM_Real are invalidated if
  68072. ** bForce is true but are retained if bForce is false.
  68073. **
  68074. ** A MEM_Null value will never be passed to this function. This function is
  68075. ** used for converting values to text for returning to the user (i.e. via
  68076. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  68077. ** keys are strings. In the former case a NULL pointer is returned the
  68078. ** user and the latter is an internal programming error.
  68079. */
  68080. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  68081. int fg = pMem->flags;
  68082. const int nByte = 32;
  68083. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68084. assert( !(fg&MEM_Zero) );
  68085. assert( !(fg&(MEM_Str|MEM_Blob)) );
  68086. assert( fg&(MEM_Int|MEM_Real) );
  68087. assert( (pMem->flags&MEM_RowSet)==0 );
  68088. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68089. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  68090. pMem->enc = 0;
  68091. return SQLITE_NOMEM_BKPT;
  68092. }
  68093. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  68094. ** string representation of the value. Then, if the required encoding
  68095. ** is UTF-16le or UTF-16be do a translation.
  68096. **
  68097. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  68098. */
  68099. if( fg & MEM_Int ){
  68100. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  68101. }else{
  68102. assert( fg & MEM_Real );
  68103. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  68104. }
  68105. pMem->n = sqlite3Strlen30(pMem->z);
  68106. pMem->enc = SQLITE_UTF8;
  68107. pMem->flags |= MEM_Str|MEM_Term;
  68108. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  68109. sqlite3VdbeChangeEncoding(pMem, enc);
  68110. return SQLITE_OK;
  68111. }
  68112. /*
  68113. ** Memory cell pMem contains the context of an aggregate function.
  68114. ** This routine calls the finalize method for that function. The
  68115. ** result of the aggregate is stored back into pMem.
  68116. **
  68117. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  68118. ** otherwise.
  68119. */
  68120. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  68121. sqlite3_context ctx;
  68122. Mem t;
  68123. assert( pFunc!=0 );
  68124. assert( pFunc->xFinalize!=0 );
  68125. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  68126. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68127. memset(&ctx, 0, sizeof(ctx));
  68128. memset(&t, 0, sizeof(t));
  68129. t.flags = MEM_Null;
  68130. t.db = pMem->db;
  68131. ctx.pOut = &t;
  68132. ctx.pMem = pMem;
  68133. ctx.pFunc = pFunc;
  68134. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  68135. assert( (pMem->flags & MEM_Dyn)==0 );
  68136. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  68137. memcpy(pMem, &t, sizeof(t));
  68138. return ctx.isError;
  68139. }
  68140. /*
  68141. ** If the memory cell contains a value that must be freed by
  68142. ** invoking the external callback in Mem.xDel, then this routine
  68143. ** will free that value. It also sets Mem.flags to MEM_Null.
  68144. **
  68145. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  68146. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  68147. ** entry point for releasing Mem resources.
  68148. */
  68149. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  68150. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  68151. assert( VdbeMemDynamic(p) );
  68152. if( p->flags&MEM_Agg ){
  68153. sqlite3VdbeMemFinalize(p, p->u.pDef);
  68154. assert( (p->flags & MEM_Agg)==0 );
  68155. testcase( p->flags & MEM_Dyn );
  68156. }
  68157. if( p->flags&MEM_Dyn ){
  68158. assert( (p->flags&MEM_RowSet)==0 );
  68159. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  68160. p->xDel((void *)p->z);
  68161. }else if( p->flags&MEM_RowSet ){
  68162. sqlite3RowSetClear(p->u.pRowSet);
  68163. }else if( p->flags&MEM_Frame ){
  68164. VdbeFrame *pFrame = p->u.pFrame;
  68165. pFrame->pParent = pFrame->v->pDelFrame;
  68166. pFrame->v->pDelFrame = pFrame;
  68167. }
  68168. p->flags = MEM_Null;
  68169. }
  68170. /*
  68171. ** Release memory held by the Mem p, both external memory cleared
  68172. ** by p->xDel and memory in p->zMalloc.
  68173. **
  68174. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  68175. ** the unusual case where there really is memory in p that needs
  68176. ** to be freed.
  68177. */
  68178. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  68179. if( VdbeMemDynamic(p) ){
  68180. vdbeMemClearExternAndSetNull(p);
  68181. }
  68182. if( p->szMalloc ){
  68183. sqlite3DbFreeNN(p->db, p->zMalloc);
  68184. p->szMalloc = 0;
  68185. }
  68186. p->z = 0;
  68187. }
  68188. /*
  68189. ** Release any memory resources held by the Mem. Both the memory that is
  68190. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  68191. **
  68192. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  68193. ** reset a Mem back to its minimum memory utilization.
  68194. **
  68195. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  68196. ** prior to inserting new content into the Mem.
  68197. */
  68198. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  68199. assert( sqlite3VdbeCheckMemInvariants(p) );
  68200. if( VdbeMemDynamic(p) || p->szMalloc ){
  68201. vdbeMemClear(p);
  68202. }
  68203. }
  68204. /*
  68205. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  68206. ** If the double is out of range of a 64-bit signed integer then
  68207. ** return the closest available 64-bit signed integer.
  68208. */
  68209. static SQLITE_NOINLINE i64 doubleToInt64(double r){
  68210. #ifdef SQLITE_OMIT_FLOATING_POINT
  68211. /* When floating-point is omitted, double and int64 are the same thing */
  68212. return r;
  68213. #else
  68214. /*
  68215. ** Many compilers we encounter do not define constants for the
  68216. ** minimum and maximum 64-bit integers, or they define them
  68217. ** inconsistently. And many do not understand the "LL" notation.
  68218. ** So we define our own static constants here using nothing
  68219. ** larger than a 32-bit integer constant.
  68220. */
  68221. static const i64 maxInt = LARGEST_INT64;
  68222. static const i64 minInt = SMALLEST_INT64;
  68223. if( r<=(double)minInt ){
  68224. return minInt;
  68225. }else if( r>=(double)maxInt ){
  68226. return maxInt;
  68227. }else{
  68228. return (i64)r;
  68229. }
  68230. #endif
  68231. }
  68232. /*
  68233. ** Return some kind of integer value which is the best we can do
  68234. ** at representing the value that *pMem describes as an integer.
  68235. ** If pMem is an integer, then the value is exact. If pMem is
  68236. ** a floating-point then the value returned is the integer part.
  68237. ** If pMem is a string or blob, then we make an attempt to convert
  68238. ** it into an integer and return that. If pMem represents an
  68239. ** an SQL-NULL value, return 0.
  68240. **
  68241. ** If pMem represents a string value, its encoding might be changed.
  68242. */
  68243. static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
  68244. i64 value = 0;
  68245. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  68246. return value;
  68247. }
  68248. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  68249. int flags;
  68250. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68251. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68252. flags = pMem->flags;
  68253. if( flags & MEM_Int ){
  68254. return pMem->u.i;
  68255. }else if( flags & MEM_Real ){
  68256. return doubleToInt64(pMem->u.r);
  68257. }else if( flags & (MEM_Str|MEM_Blob) ){
  68258. assert( pMem->z || pMem->n==0 );
  68259. return memIntValue(pMem);
  68260. }else{
  68261. return 0;
  68262. }
  68263. }
  68264. /*
  68265. ** Return the best representation of pMem that we can get into a
  68266. ** double. If pMem is already a double or an integer, return its
  68267. ** value. If it is a string or blob, try to convert it to a double.
  68268. ** If it is a NULL, return 0.0.
  68269. */
  68270. static SQLITE_NOINLINE double memRealValue(Mem *pMem){
  68271. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  68272. double val = (double)0;
  68273. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  68274. return val;
  68275. }
  68276. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  68277. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68278. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68279. if( pMem->flags & MEM_Real ){
  68280. return pMem->u.r;
  68281. }else if( pMem->flags & MEM_Int ){
  68282. return (double)pMem->u.i;
  68283. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  68284. return memRealValue(pMem);
  68285. }else{
  68286. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  68287. return (double)0;
  68288. }
  68289. }
  68290. /*
  68291. ** Return 1 if pMem represents true, and return 0 if pMem represents false.
  68292. ** Return the value ifNull if pMem is NULL.
  68293. */
  68294. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
  68295. if( pMem->flags & MEM_Int ) return pMem->u.i!=0;
  68296. if( pMem->flags & MEM_Null ) return ifNull;
  68297. return sqlite3VdbeRealValue(pMem)!=0.0;
  68298. }
  68299. /*
  68300. ** The MEM structure is already a MEM_Real. Try to also make it a
  68301. ** MEM_Int if we can.
  68302. */
  68303. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  68304. i64 ix;
  68305. assert( pMem->flags & MEM_Real );
  68306. assert( (pMem->flags & MEM_RowSet)==0 );
  68307. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68308. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68309. ix = doubleToInt64(pMem->u.r);
  68310. /* Only mark the value as an integer if
  68311. **
  68312. ** (1) the round-trip conversion real->int->real is a no-op, and
  68313. ** (2) The integer is neither the largest nor the smallest
  68314. ** possible integer (ticket #3922)
  68315. **
  68316. ** The second and third terms in the following conditional enforces
  68317. ** the second condition under the assumption that addition overflow causes
  68318. ** values to wrap around.
  68319. */
  68320. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  68321. pMem->u.i = ix;
  68322. MemSetTypeFlag(pMem, MEM_Int);
  68323. }
  68324. }
  68325. /*
  68326. ** Convert pMem to type integer. Invalidate any prior representations.
  68327. */
  68328. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  68329. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68330. assert( (pMem->flags & MEM_RowSet)==0 );
  68331. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68332. pMem->u.i = sqlite3VdbeIntValue(pMem);
  68333. MemSetTypeFlag(pMem, MEM_Int);
  68334. return SQLITE_OK;
  68335. }
  68336. /*
  68337. ** Convert pMem so that it is of type MEM_Real.
  68338. ** Invalidate any prior representations.
  68339. */
  68340. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  68341. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68342. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  68343. pMem->u.r = sqlite3VdbeRealValue(pMem);
  68344. MemSetTypeFlag(pMem, MEM_Real);
  68345. return SQLITE_OK;
  68346. }
  68347. /* Compare a floating point value to an integer. Return true if the two
  68348. ** values are the same within the precision of the floating point value.
  68349. **
  68350. ** For some versions of GCC on 32-bit machines, if you do the more obvious
  68351. ** comparison of "r1==(double)i" you sometimes get an answer of false even
  68352. ** though the r1 and (double)i values are bit-for-bit the same.
  68353. */
  68354. static int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
  68355. double r2 = (double)i;
  68356. return memcmp(&r1, &r2, sizeof(r1))==0;
  68357. }
  68358. /*
  68359. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  68360. ** Invalidate any prior representations.
  68361. **
  68362. ** Every effort is made to force the conversion, even if the input
  68363. ** is a string that does not look completely like a number. Convert
  68364. ** as much of the string as we can and ignore the rest.
  68365. */
  68366. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  68367. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  68368. int rc;
  68369. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  68370. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68371. rc = sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc);
  68372. if( rc==0 ){
  68373. MemSetTypeFlag(pMem, MEM_Int);
  68374. }else{
  68375. i64 i = pMem->u.i;
  68376. sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
  68377. if( rc==1 && sqlite3RealSameAsInt(pMem->u.r, i) ){
  68378. pMem->u.i = i;
  68379. MemSetTypeFlag(pMem, MEM_Int);
  68380. }else{
  68381. MemSetTypeFlag(pMem, MEM_Real);
  68382. }
  68383. }
  68384. }
  68385. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  68386. pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
  68387. return SQLITE_OK;
  68388. }
  68389. /*
  68390. ** Cast the datatype of the value in pMem according to the affinity
  68391. ** "aff". Casting is different from applying affinity in that a cast
  68392. ** is forced. In other words, the value is converted into the desired
  68393. ** affinity even if that results in loss of data. This routine is
  68394. ** used (for example) to implement the SQL "cast()" operator.
  68395. */
  68396. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  68397. if( pMem->flags & MEM_Null ) return;
  68398. switch( aff ){
  68399. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  68400. if( (pMem->flags & MEM_Blob)==0 ){
  68401. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  68402. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  68403. if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
  68404. }else{
  68405. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  68406. }
  68407. break;
  68408. }
  68409. case SQLITE_AFF_NUMERIC: {
  68410. sqlite3VdbeMemNumerify(pMem);
  68411. break;
  68412. }
  68413. case SQLITE_AFF_INTEGER: {
  68414. sqlite3VdbeMemIntegerify(pMem);
  68415. break;
  68416. }
  68417. case SQLITE_AFF_REAL: {
  68418. sqlite3VdbeMemRealify(pMem);
  68419. break;
  68420. }
  68421. default: {
  68422. assert( aff==SQLITE_AFF_TEXT );
  68423. assert( MEM_Str==(MEM_Blob>>3) );
  68424. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  68425. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  68426. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  68427. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  68428. break;
  68429. }
  68430. }
  68431. }
  68432. /*
  68433. ** Initialize bulk memory to be a consistent Mem object.
  68434. **
  68435. ** The minimum amount of initialization feasible is performed.
  68436. */
  68437. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  68438. assert( (flags & ~MEM_TypeMask)==0 );
  68439. pMem->flags = flags;
  68440. pMem->db = db;
  68441. pMem->szMalloc = 0;
  68442. }
  68443. /*
  68444. ** Delete any previous value and set the value stored in *pMem to NULL.
  68445. **
  68446. ** This routine calls the Mem.xDel destructor to dispose of values that
  68447. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  68448. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  68449. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  68450. **
  68451. ** Use this routine to reset the Mem prior to insert a new value.
  68452. **
  68453. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  68454. */
  68455. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  68456. if( VdbeMemDynamic(pMem) ){
  68457. vdbeMemClearExternAndSetNull(pMem);
  68458. }else{
  68459. pMem->flags = MEM_Null;
  68460. }
  68461. }
  68462. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  68463. sqlite3VdbeMemSetNull((Mem*)p);
  68464. }
  68465. /*
  68466. ** Delete any previous value and set the value to be a BLOB of length
  68467. ** n containing all zeros.
  68468. */
  68469. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  68470. sqlite3VdbeMemRelease(pMem);
  68471. pMem->flags = MEM_Blob|MEM_Zero;
  68472. pMem->n = 0;
  68473. if( n<0 ) n = 0;
  68474. pMem->u.nZero = n;
  68475. pMem->enc = SQLITE_UTF8;
  68476. pMem->z = 0;
  68477. }
  68478. /*
  68479. ** The pMem is known to contain content that needs to be destroyed prior
  68480. ** to a value change. So invoke the destructor, then set the value to
  68481. ** a 64-bit integer.
  68482. */
  68483. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  68484. sqlite3VdbeMemSetNull(pMem);
  68485. pMem->u.i = val;
  68486. pMem->flags = MEM_Int;
  68487. }
  68488. /*
  68489. ** Delete any previous value and set the value stored in *pMem to val,
  68490. ** manifest type INTEGER.
  68491. */
  68492. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  68493. if( VdbeMemDynamic(pMem) ){
  68494. vdbeReleaseAndSetInt64(pMem, val);
  68495. }else{
  68496. pMem->u.i = val;
  68497. pMem->flags = MEM_Int;
  68498. }
  68499. }
  68500. /* A no-op destructor */
  68501. static void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
  68502. /*
  68503. ** Set the value stored in *pMem should already be a NULL.
  68504. ** Also store a pointer to go with it.
  68505. */
  68506. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
  68507. Mem *pMem,
  68508. void *pPtr,
  68509. const char *zPType,
  68510. void (*xDestructor)(void*)
  68511. ){
  68512. assert( pMem->flags==MEM_Null );
  68513. pMem->u.zPType = zPType ? zPType : "";
  68514. pMem->z = pPtr;
  68515. pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
  68516. pMem->eSubtype = 'p';
  68517. pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
  68518. }
  68519. #ifndef SQLITE_OMIT_FLOATING_POINT
  68520. /*
  68521. ** Delete any previous value and set the value stored in *pMem to val,
  68522. ** manifest type REAL.
  68523. */
  68524. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  68525. sqlite3VdbeMemSetNull(pMem);
  68526. if( !sqlite3IsNaN(val) ){
  68527. pMem->u.r = val;
  68528. pMem->flags = MEM_Real;
  68529. }
  68530. }
  68531. #endif
  68532. /*
  68533. ** Delete any previous value and set the value of pMem to be an
  68534. ** empty boolean index.
  68535. */
  68536. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  68537. sqlite3 *db = pMem->db;
  68538. assert( db!=0 );
  68539. assert( (pMem->flags & MEM_RowSet)==0 );
  68540. sqlite3VdbeMemRelease(pMem);
  68541. pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
  68542. if( db->mallocFailed ){
  68543. pMem->flags = MEM_Null;
  68544. pMem->szMalloc = 0;
  68545. }else{
  68546. assert( pMem->zMalloc );
  68547. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  68548. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  68549. assert( pMem->u.pRowSet!=0 );
  68550. pMem->flags = MEM_RowSet;
  68551. }
  68552. }
  68553. /*
  68554. ** Return true if the Mem object contains a TEXT or BLOB that is
  68555. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  68556. */
  68557. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  68558. assert( p->db!=0 );
  68559. if( p->flags & (MEM_Str|MEM_Blob) ){
  68560. int n = p->n;
  68561. if( p->flags & MEM_Zero ){
  68562. n += p->u.nZero;
  68563. }
  68564. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  68565. }
  68566. return 0;
  68567. }
  68568. #ifdef SQLITE_DEBUG
  68569. /*
  68570. ** This routine prepares a memory cell for modification by breaking
  68571. ** its link to a shallow copy and by marking any current shallow
  68572. ** copies of this cell as invalid.
  68573. **
  68574. ** This is used for testing and debugging only - to make sure shallow
  68575. ** copies are not misused.
  68576. */
  68577. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  68578. int i;
  68579. Mem *pX;
  68580. for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
  68581. if( pX->pScopyFrom==pMem ){
  68582. pX->flags |= MEM_Undefined;
  68583. pX->pScopyFrom = 0;
  68584. }
  68585. }
  68586. pMem->pScopyFrom = 0;
  68587. }
  68588. #endif /* SQLITE_DEBUG */
  68589. /*
  68590. ** Make an shallow copy of pFrom into pTo. Prior contents of
  68591. ** pTo are freed. The pFrom->z field is not duplicated. If
  68592. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  68593. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  68594. */
  68595. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  68596. vdbeMemClearExternAndSetNull(pTo);
  68597. assert( !VdbeMemDynamic(pTo) );
  68598. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  68599. }
  68600. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  68601. assert( (pFrom->flags & MEM_RowSet)==0 );
  68602. assert( pTo->db==pFrom->db );
  68603. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  68604. memcpy(pTo, pFrom, MEMCELLSIZE);
  68605. if( (pFrom->flags&MEM_Static)==0 ){
  68606. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  68607. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  68608. pTo->flags |= srcType;
  68609. }
  68610. }
  68611. /*
  68612. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  68613. ** freed before the copy is made.
  68614. */
  68615. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  68616. int rc = SQLITE_OK;
  68617. assert( (pFrom->flags & MEM_RowSet)==0 );
  68618. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  68619. memcpy(pTo, pFrom, MEMCELLSIZE);
  68620. pTo->flags &= ~MEM_Dyn;
  68621. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  68622. if( 0==(pFrom->flags&MEM_Static) ){
  68623. pTo->flags |= MEM_Ephem;
  68624. rc = sqlite3VdbeMemMakeWriteable(pTo);
  68625. }
  68626. }
  68627. return rc;
  68628. }
  68629. /*
  68630. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  68631. ** freed. If pFrom contains ephemeral data, a copy is made.
  68632. **
  68633. ** pFrom contains an SQL NULL when this routine returns.
  68634. */
  68635. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  68636. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  68637. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  68638. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  68639. sqlite3VdbeMemRelease(pTo);
  68640. memcpy(pTo, pFrom, sizeof(Mem));
  68641. pFrom->flags = MEM_Null;
  68642. pFrom->szMalloc = 0;
  68643. }
  68644. /*
  68645. ** Change the value of a Mem to be a string or a BLOB.
  68646. **
  68647. ** The memory management strategy depends on the value of the xDel
  68648. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  68649. ** string is copied into a (possibly existing) buffer managed by the
  68650. ** Mem structure. Otherwise, any existing buffer is freed and the
  68651. ** pointer copied.
  68652. **
  68653. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  68654. ** size limit) then no memory allocation occurs. If the string can be
  68655. ** stored without allocating memory, then it is. If a memory allocation
  68656. ** is required to store the string, then value of pMem is unchanged. In
  68657. ** either case, SQLITE_TOOBIG is returned.
  68658. */
  68659. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  68660. Mem *pMem, /* Memory cell to set to string value */
  68661. const char *z, /* String pointer */
  68662. int n, /* Bytes in string, or negative */
  68663. u8 enc, /* Encoding of z. 0 for BLOBs */
  68664. void (*xDel)(void*) /* Destructor function */
  68665. ){
  68666. int nByte = n; /* New value for pMem->n */
  68667. int iLimit; /* Maximum allowed string or blob size */
  68668. u16 flags = 0; /* New value for pMem->flags */
  68669. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  68670. assert( (pMem->flags & MEM_RowSet)==0 );
  68671. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  68672. if( !z ){
  68673. sqlite3VdbeMemSetNull(pMem);
  68674. return SQLITE_OK;
  68675. }
  68676. if( pMem->db ){
  68677. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  68678. }else{
  68679. iLimit = SQLITE_MAX_LENGTH;
  68680. }
  68681. flags = (enc==0?MEM_Blob:MEM_Str);
  68682. if( nByte<0 ){
  68683. assert( enc!=0 );
  68684. if( enc==SQLITE_UTF8 ){
  68685. nByte = 0x7fffffff & (int)strlen(z);
  68686. if( nByte>iLimit ) nByte = iLimit+1;
  68687. }else{
  68688. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  68689. }
  68690. flags |= MEM_Term;
  68691. }
  68692. /* The following block sets the new values of Mem.z and Mem.xDel. It
  68693. ** also sets a flag in local variable "flags" to indicate the memory
  68694. ** management (one of MEM_Dyn or MEM_Static).
  68695. */
  68696. if( xDel==SQLITE_TRANSIENT ){
  68697. int nAlloc = nByte;
  68698. if( flags&MEM_Term ){
  68699. nAlloc += (enc==SQLITE_UTF8?1:2);
  68700. }
  68701. if( nByte>iLimit ){
  68702. return SQLITE_TOOBIG;
  68703. }
  68704. testcase( nAlloc==0 );
  68705. testcase( nAlloc==31 );
  68706. testcase( nAlloc==32 );
  68707. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  68708. return SQLITE_NOMEM_BKPT;
  68709. }
  68710. memcpy(pMem->z, z, nAlloc);
  68711. }else if( xDel==SQLITE_DYNAMIC ){
  68712. sqlite3VdbeMemRelease(pMem);
  68713. pMem->zMalloc = pMem->z = (char *)z;
  68714. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  68715. }else{
  68716. sqlite3VdbeMemRelease(pMem);
  68717. pMem->z = (char *)z;
  68718. pMem->xDel = xDel;
  68719. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  68720. }
  68721. pMem->n = nByte;
  68722. pMem->flags = flags;
  68723. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  68724. #ifndef SQLITE_OMIT_UTF16
  68725. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  68726. return SQLITE_NOMEM_BKPT;
  68727. }
  68728. #endif
  68729. if( nByte>iLimit ){
  68730. return SQLITE_TOOBIG;
  68731. }
  68732. return SQLITE_OK;
  68733. }
  68734. /*
  68735. ** Move data out of a btree key or data field and into a Mem structure.
  68736. ** The data is payload from the entry that pCur is currently pointing
  68737. ** to. offset and amt determine what portion of the data or key to retrieve.
  68738. ** The result is written into the pMem element.
  68739. **
  68740. ** The pMem object must have been initialized. This routine will use
  68741. ** pMem->zMalloc to hold the content from the btree, if possible. New
  68742. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  68743. ** is responsible for making sure that the pMem object is eventually
  68744. ** destroyed.
  68745. **
  68746. ** If this routine fails for any reason (malloc returns NULL or unable
  68747. ** to read from the disk) then the pMem is left in an inconsistent state.
  68748. */
  68749. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  68750. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  68751. u32 offset, /* Offset from the start of data to return bytes from. */
  68752. u32 amt, /* Number of bytes to return. */
  68753. Mem *pMem /* OUT: Return data in this Mem structure. */
  68754. ){
  68755. int rc;
  68756. pMem->flags = MEM_Null;
  68757. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
  68758. rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
  68759. if( rc==SQLITE_OK ){
  68760. pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
  68761. pMem->flags = MEM_Blob;
  68762. pMem->n = (int)amt;
  68763. }else{
  68764. sqlite3VdbeMemRelease(pMem);
  68765. }
  68766. }
  68767. return rc;
  68768. }
  68769. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  68770. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  68771. u32 offset, /* Offset from the start of data to return bytes from. */
  68772. u32 amt, /* Number of bytes to return. */
  68773. Mem *pMem /* OUT: Return data in this Mem structure. */
  68774. ){
  68775. char *zData; /* Data from the btree layer */
  68776. u32 available = 0; /* Number of bytes available on the local btree page */
  68777. int rc = SQLITE_OK; /* Return code */
  68778. assert( sqlite3BtreeCursorIsValid(pCur) );
  68779. assert( !VdbeMemDynamic(pMem) );
  68780. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  68781. ** that both the BtShared and database handle mutexes are held. */
  68782. assert( (pMem->flags & MEM_RowSet)==0 );
  68783. zData = (char *)sqlite3BtreePayloadFetch(pCur, &available);
  68784. assert( zData!=0 );
  68785. if( offset+amt<=available ){
  68786. pMem->z = &zData[offset];
  68787. pMem->flags = MEM_Blob|MEM_Ephem;
  68788. pMem->n = (int)amt;
  68789. }else{
  68790. rc = vdbeMemFromBtreeResize(pCur, offset, amt, pMem);
  68791. }
  68792. return rc;
  68793. }
  68794. /*
  68795. ** The pVal argument is known to be a value other than NULL.
  68796. ** Convert it into a string with encoding enc and return a pointer
  68797. ** to a zero-terminated version of that string.
  68798. */
  68799. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  68800. assert( pVal!=0 );
  68801. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  68802. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  68803. assert( (pVal->flags & MEM_RowSet)==0 );
  68804. assert( (pVal->flags & (MEM_Null))==0 );
  68805. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  68806. if( ExpandBlob(pVal) ) return 0;
  68807. pVal->flags |= MEM_Str;
  68808. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  68809. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  68810. }
  68811. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  68812. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  68813. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  68814. return 0;
  68815. }
  68816. }
  68817. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  68818. }else{
  68819. sqlite3VdbeMemStringify(pVal, enc, 0);
  68820. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  68821. }
  68822. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  68823. || pVal->db->mallocFailed );
  68824. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  68825. assert( sqlite3VdbeMemConsistentDualRep(pVal) );
  68826. return pVal->z;
  68827. }else{
  68828. return 0;
  68829. }
  68830. }
  68831. /* This function is only available internally, it is not part of the
  68832. ** external API. It works in a similar way to sqlite3_value_text(),
  68833. ** except the data returned is in the encoding specified by the second
  68834. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  68835. ** SQLITE_UTF8.
  68836. **
  68837. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  68838. ** If that is the case, then the result must be aligned on an even byte
  68839. ** boundary.
  68840. */
  68841. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  68842. if( !pVal ) return 0;
  68843. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  68844. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  68845. assert( (pVal->flags & MEM_RowSet)==0 );
  68846. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  68847. assert( sqlite3VdbeMemConsistentDualRep(pVal) );
  68848. return pVal->z;
  68849. }
  68850. if( pVal->flags&MEM_Null ){
  68851. return 0;
  68852. }
  68853. return valueToText(pVal, enc);
  68854. }
  68855. /*
  68856. ** Create a new sqlite3_value object.
  68857. */
  68858. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  68859. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  68860. if( p ){
  68861. p->flags = MEM_Null;
  68862. p->db = db;
  68863. }
  68864. return p;
  68865. }
  68866. /*
  68867. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  68868. ** valueNew(). See comments above valueNew() for details.
  68869. */
  68870. struct ValueNewStat4Ctx {
  68871. Parse *pParse;
  68872. Index *pIdx;
  68873. UnpackedRecord **ppRec;
  68874. int iVal;
  68875. };
  68876. /*
  68877. ** Allocate and return a pointer to a new sqlite3_value object. If
  68878. ** the second argument to this function is NULL, the object is allocated
  68879. ** by calling sqlite3ValueNew().
  68880. **
  68881. ** Otherwise, if the second argument is non-zero, then this function is
  68882. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  68883. ** already been allocated, allocate the UnpackedRecord structure that
  68884. ** that function will return to its caller here. Then return a pointer to
  68885. ** an sqlite3_value within the UnpackedRecord.a[] array.
  68886. */
  68887. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  68888. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  68889. if( p ){
  68890. UnpackedRecord *pRec = p->ppRec[0];
  68891. if( pRec==0 ){
  68892. Index *pIdx = p->pIdx; /* Index being probed */
  68893. int nByte; /* Bytes of space to allocate */
  68894. int i; /* Counter variable */
  68895. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  68896. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  68897. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  68898. if( pRec ){
  68899. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  68900. if( pRec->pKeyInfo ){
  68901. assert( pRec->pKeyInfo->nAllField==nCol );
  68902. assert( pRec->pKeyInfo->enc==ENC(db) );
  68903. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  68904. for(i=0; i<nCol; i++){
  68905. pRec->aMem[i].flags = MEM_Null;
  68906. pRec->aMem[i].db = db;
  68907. }
  68908. }else{
  68909. sqlite3DbFreeNN(db, pRec);
  68910. pRec = 0;
  68911. }
  68912. }
  68913. if( pRec==0 ) return 0;
  68914. p->ppRec[0] = pRec;
  68915. }
  68916. pRec->nField = p->iVal+1;
  68917. return &pRec->aMem[p->iVal];
  68918. }
  68919. #else
  68920. UNUSED_PARAMETER(p);
  68921. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  68922. return sqlite3ValueNew(db);
  68923. }
  68924. /*
  68925. ** The expression object indicated by the second argument is guaranteed
  68926. ** to be a scalar SQL function. If
  68927. **
  68928. ** * all function arguments are SQL literals,
  68929. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  68930. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  68931. **
  68932. ** then this routine attempts to invoke the SQL function. Assuming no
  68933. ** error occurs, output parameter (*ppVal) is set to point to a value
  68934. ** object containing the result before returning SQLITE_OK.
  68935. **
  68936. ** Affinity aff is applied to the result of the function before returning.
  68937. ** If the result is a text value, the sqlite3_value object uses encoding
  68938. ** enc.
  68939. **
  68940. ** If the conditions above are not met, this function returns SQLITE_OK
  68941. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  68942. ** NULL and an SQLite error code returned.
  68943. */
  68944. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  68945. static int valueFromFunction(
  68946. sqlite3 *db, /* The database connection */
  68947. Expr *p, /* The expression to evaluate */
  68948. u8 enc, /* Encoding to use */
  68949. u8 aff, /* Affinity to use */
  68950. sqlite3_value **ppVal, /* Write the new value here */
  68951. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  68952. ){
  68953. sqlite3_context ctx; /* Context object for function invocation */
  68954. sqlite3_value **apVal = 0; /* Function arguments */
  68955. int nVal = 0; /* Size of apVal[] array */
  68956. FuncDef *pFunc = 0; /* Function definition */
  68957. sqlite3_value *pVal = 0; /* New value */
  68958. int rc = SQLITE_OK; /* Return code */
  68959. ExprList *pList = 0; /* Function arguments */
  68960. int i; /* Iterator variable */
  68961. assert( pCtx!=0 );
  68962. assert( (p->flags & EP_TokenOnly)==0 );
  68963. pList = p->x.pList;
  68964. if( pList ) nVal = pList->nExpr;
  68965. pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
  68966. assert( pFunc );
  68967. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  68968. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  68969. ){
  68970. return SQLITE_OK;
  68971. }
  68972. if( pList ){
  68973. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  68974. if( apVal==0 ){
  68975. rc = SQLITE_NOMEM_BKPT;
  68976. goto value_from_function_out;
  68977. }
  68978. for(i=0; i<nVal; i++){
  68979. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  68980. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  68981. }
  68982. }
  68983. pVal = valueNew(db, pCtx);
  68984. if( pVal==0 ){
  68985. rc = SQLITE_NOMEM_BKPT;
  68986. goto value_from_function_out;
  68987. }
  68988. assert( pCtx->pParse->rc==SQLITE_OK );
  68989. memset(&ctx, 0, sizeof(ctx));
  68990. ctx.pOut = pVal;
  68991. ctx.pFunc = pFunc;
  68992. pFunc->xSFunc(&ctx, nVal, apVal);
  68993. if( ctx.isError ){
  68994. rc = ctx.isError;
  68995. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  68996. }else{
  68997. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  68998. assert( rc==SQLITE_OK );
  68999. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  69000. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  69001. rc = SQLITE_TOOBIG;
  69002. pCtx->pParse->nErr++;
  69003. }
  69004. }
  69005. pCtx->pParse->rc = rc;
  69006. value_from_function_out:
  69007. if( rc!=SQLITE_OK ){
  69008. pVal = 0;
  69009. }
  69010. if( apVal ){
  69011. for(i=0; i<nVal; i++){
  69012. sqlite3ValueFree(apVal[i]);
  69013. }
  69014. sqlite3DbFreeNN(db, apVal);
  69015. }
  69016. *ppVal = pVal;
  69017. return rc;
  69018. }
  69019. #else
  69020. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  69021. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  69022. /*
  69023. ** Extract a value from the supplied expression in the manner described
  69024. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  69025. ** using valueNew().
  69026. **
  69027. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  69028. ** has been allocated, it is freed before returning. Or, if pCtx is not
  69029. ** NULL, it is assumed that the caller will free any allocated object
  69030. ** in all cases.
  69031. */
  69032. static int valueFromExpr(
  69033. sqlite3 *db, /* The database connection */
  69034. Expr *pExpr, /* The expression to evaluate */
  69035. u8 enc, /* Encoding to use */
  69036. u8 affinity, /* Affinity to use */
  69037. sqlite3_value **ppVal, /* Write the new value here */
  69038. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  69039. ){
  69040. int op;
  69041. char *zVal = 0;
  69042. sqlite3_value *pVal = 0;
  69043. int negInt = 1;
  69044. const char *zNeg = "";
  69045. int rc = SQLITE_OK;
  69046. assert( pExpr!=0 );
  69047. while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  69048. #if defined(SQLITE_ENABLE_STAT3_OR_STAT4)
  69049. if( op==TK_REGISTER ) op = pExpr->op2;
  69050. #else
  69051. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  69052. #endif
  69053. /* Compressed expressions only appear when parsing the DEFAULT clause
  69054. ** on a table column definition, and hence only when pCtx==0. This
  69055. ** check ensures that an EP_TokenOnly expression is never passed down
  69056. ** into valueFromFunction(). */
  69057. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  69058. if( op==TK_CAST ){
  69059. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  69060. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  69061. testcase( rc!=SQLITE_OK );
  69062. if( *ppVal ){
  69063. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  69064. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  69065. }
  69066. return rc;
  69067. }
  69068. /* Handle negative integers in a single step. This is needed in the
  69069. ** case when the value is -9223372036854775808.
  69070. */
  69071. if( op==TK_UMINUS
  69072. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  69073. pExpr = pExpr->pLeft;
  69074. op = pExpr->op;
  69075. negInt = -1;
  69076. zNeg = "-";
  69077. }
  69078. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  69079. pVal = valueNew(db, pCtx);
  69080. if( pVal==0 ) goto no_mem;
  69081. if( ExprHasProperty(pExpr, EP_IntValue) ){
  69082. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  69083. }else{
  69084. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  69085. if( zVal==0 ) goto no_mem;
  69086. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  69087. }
  69088. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  69089. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  69090. }else{
  69091. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  69092. }
  69093. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  69094. if( enc!=SQLITE_UTF8 ){
  69095. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  69096. }
  69097. }else if( op==TK_UMINUS ) {
  69098. /* This branch happens for multiple negative signs. Ex: -(-5) */
  69099. if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
  69100. && pVal!=0
  69101. ){
  69102. sqlite3VdbeMemNumerify(pVal);
  69103. if( pVal->flags & MEM_Real ){
  69104. pVal->u.r = -pVal->u.r;
  69105. }else if( pVal->u.i==SMALLEST_INT64 ){
  69106. pVal->u.r = -(double)SMALLEST_INT64;
  69107. MemSetTypeFlag(pVal, MEM_Real);
  69108. }else{
  69109. pVal->u.i = -pVal->u.i;
  69110. }
  69111. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  69112. }
  69113. }else if( op==TK_NULL ){
  69114. pVal = valueNew(db, pCtx);
  69115. if( pVal==0 ) goto no_mem;
  69116. sqlite3VdbeMemNumerify(pVal);
  69117. }
  69118. #ifndef SQLITE_OMIT_BLOB_LITERAL
  69119. else if( op==TK_BLOB ){
  69120. int nVal;
  69121. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  69122. assert( pExpr->u.zToken[1]=='\'' );
  69123. pVal = valueNew(db, pCtx);
  69124. if( !pVal ) goto no_mem;
  69125. zVal = &pExpr->u.zToken[2];
  69126. nVal = sqlite3Strlen30(zVal)-1;
  69127. assert( zVal[nVal]=='\'' );
  69128. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  69129. 0, SQLITE_DYNAMIC);
  69130. }
  69131. #endif
  69132. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  69133. else if( op==TK_FUNCTION && pCtx!=0 ){
  69134. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  69135. }
  69136. #endif
  69137. *ppVal = pVal;
  69138. return rc;
  69139. no_mem:
  69140. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  69141. if( pCtx==0 || pCtx->pParse->nErr==0 )
  69142. #endif
  69143. sqlite3OomFault(db);
  69144. sqlite3DbFree(db, zVal);
  69145. assert( *ppVal==0 );
  69146. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  69147. if( pCtx==0 ) sqlite3ValueFree(pVal);
  69148. #else
  69149. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  69150. #endif
  69151. return SQLITE_NOMEM_BKPT;
  69152. }
  69153. /*
  69154. ** Create a new sqlite3_value object, containing the value of pExpr.
  69155. **
  69156. ** This only works for very simple expressions that consist of one constant
  69157. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  69158. ** be converted directly into a value, then the value is allocated and
  69159. ** a pointer written to *ppVal. The caller is responsible for deallocating
  69160. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  69161. ** cannot be converted to a value, then *ppVal is set to NULL.
  69162. */
  69163. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  69164. sqlite3 *db, /* The database connection */
  69165. Expr *pExpr, /* The expression to evaluate */
  69166. u8 enc, /* Encoding to use */
  69167. u8 affinity, /* Affinity to use */
  69168. sqlite3_value **ppVal /* Write the new value here */
  69169. ){
  69170. return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
  69171. }
  69172. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  69173. /*
  69174. ** The implementation of the sqlite_record() function. This function accepts
  69175. ** a single argument of any type. The return value is a formatted database
  69176. ** record (a blob) containing the argument value.
  69177. **
  69178. ** This is used to convert the value stored in the 'sample' column of the
  69179. ** sqlite_stat3 table to the record format SQLite uses internally.
  69180. */
  69181. static void recordFunc(
  69182. sqlite3_context *context,
  69183. int argc,
  69184. sqlite3_value **argv
  69185. ){
  69186. const int file_format = 1;
  69187. u32 iSerial; /* Serial type */
  69188. int nSerial; /* Bytes of space for iSerial as varint */
  69189. u32 nVal; /* Bytes of space required for argv[0] */
  69190. int nRet;
  69191. sqlite3 *db;
  69192. u8 *aRet;
  69193. UNUSED_PARAMETER( argc );
  69194. iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
  69195. nSerial = sqlite3VarintLen(iSerial);
  69196. db = sqlite3_context_db_handle(context);
  69197. nRet = 1 + nSerial + nVal;
  69198. aRet = sqlite3DbMallocRawNN(db, nRet);
  69199. if( aRet==0 ){
  69200. sqlite3_result_error_nomem(context);
  69201. }else{
  69202. aRet[0] = nSerial+1;
  69203. putVarint32(&aRet[1], iSerial);
  69204. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  69205. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  69206. sqlite3DbFreeNN(db, aRet);
  69207. }
  69208. }
  69209. /*
  69210. ** Register built-in functions used to help read ANALYZE data.
  69211. */
  69212. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  69213. static FuncDef aAnalyzeTableFuncs[] = {
  69214. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  69215. };
  69216. sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
  69217. }
  69218. /*
  69219. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  69220. **
  69221. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  69222. ** pAlloc if one does not exist and the new value is added to the
  69223. ** UnpackedRecord object.
  69224. **
  69225. ** A value is extracted in the following cases:
  69226. **
  69227. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  69228. **
  69229. ** * The expression is a bound variable, and this is a reprepare, or
  69230. **
  69231. ** * The expression is a literal value.
  69232. **
  69233. ** On success, *ppVal is made to point to the extracted value. The caller
  69234. ** is responsible for ensuring that the value is eventually freed.
  69235. */
  69236. static int stat4ValueFromExpr(
  69237. Parse *pParse, /* Parse context */
  69238. Expr *pExpr, /* The expression to extract a value from */
  69239. u8 affinity, /* Affinity to use */
  69240. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  69241. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  69242. ){
  69243. int rc = SQLITE_OK;
  69244. sqlite3_value *pVal = 0;
  69245. sqlite3 *db = pParse->db;
  69246. /* Skip over any TK_COLLATE nodes */
  69247. pExpr = sqlite3ExprSkipCollate(pExpr);
  69248. assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
  69249. if( !pExpr ){
  69250. pVal = valueNew(db, pAlloc);
  69251. if( pVal ){
  69252. sqlite3VdbeMemSetNull((Mem*)pVal);
  69253. }
  69254. }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  69255. Vdbe *v;
  69256. int iBindVar = pExpr->iColumn;
  69257. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  69258. if( (v = pParse->pReprepare)!=0 ){
  69259. pVal = valueNew(db, pAlloc);
  69260. if( pVal ){
  69261. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  69262. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  69263. pVal->db = pParse->db;
  69264. }
  69265. }
  69266. }else{
  69267. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  69268. }
  69269. assert( pVal==0 || pVal->db==db );
  69270. *ppVal = pVal;
  69271. return rc;
  69272. }
  69273. /*
  69274. ** This function is used to allocate and populate UnpackedRecord
  69275. ** structures intended to be compared against sample index keys stored
  69276. ** in the sqlite_stat4 table.
  69277. **
  69278. ** A single call to this function populates zero or more fields of the
  69279. ** record starting with field iVal (fields are numbered from left to
  69280. ** right starting with 0). A single field is populated if:
  69281. **
  69282. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  69283. **
  69284. ** * The expression is a bound variable, and this is a reprepare, or
  69285. **
  69286. ** * The sqlite3ValueFromExpr() function is able to extract a value
  69287. ** from the expression (i.e. the expression is a literal value).
  69288. **
  69289. ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
  69290. ** vector components that match either of the two latter criteria listed
  69291. ** above.
  69292. **
  69293. ** Before any value is appended to the record, the affinity of the
  69294. ** corresponding column within index pIdx is applied to it. Before
  69295. ** this function returns, output parameter *pnExtract is set to the
  69296. ** number of values appended to the record.
  69297. **
  69298. ** When this function is called, *ppRec must either point to an object
  69299. ** allocated by an earlier call to this function, or must be NULL. If it
  69300. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  69301. ** is allocated (and *ppRec set to point to it) before returning.
  69302. **
  69303. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  69304. ** error if a value cannot be extracted from pExpr. If an error does
  69305. ** occur, an SQLite error code is returned.
  69306. */
  69307. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  69308. Parse *pParse, /* Parse context */
  69309. Index *pIdx, /* Index being probed */
  69310. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  69311. Expr *pExpr, /* The expression to extract a value from */
  69312. int nElem, /* Maximum number of values to append */
  69313. int iVal, /* Array element to populate */
  69314. int *pnExtract /* OUT: Values appended to the record */
  69315. ){
  69316. int rc = SQLITE_OK;
  69317. int nExtract = 0;
  69318. if( pExpr==0 || pExpr->op!=TK_SELECT ){
  69319. int i;
  69320. struct ValueNewStat4Ctx alloc;
  69321. alloc.pParse = pParse;
  69322. alloc.pIdx = pIdx;
  69323. alloc.ppRec = ppRec;
  69324. for(i=0; i<nElem; i++){
  69325. sqlite3_value *pVal = 0;
  69326. Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
  69327. u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
  69328. alloc.iVal = iVal+i;
  69329. rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
  69330. if( !pVal ) break;
  69331. nExtract++;
  69332. }
  69333. }
  69334. *pnExtract = nExtract;
  69335. return rc;
  69336. }
  69337. /*
  69338. ** Attempt to extract a value from expression pExpr using the methods
  69339. ** as described for sqlite3Stat4ProbeSetValue() above.
  69340. **
  69341. ** If successful, set *ppVal to point to a new value object and return
  69342. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  69343. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  69344. ** does occur, return an SQLite error code. The final value of *ppVal
  69345. ** is undefined in this case.
  69346. */
  69347. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  69348. Parse *pParse, /* Parse context */
  69349. Expr *pExpr, /* The expression to extract a value from */
  69350. u8 affinity, /* Affinity to use */
  69351. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  69352. ){
  69353. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  69354. }
  69355. /*
  69356. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  69357. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  69358. ** sqlite3_value object is allocated.
  69359. **
  69360. ** If *ppVal is initially NULL then the caller is responsible for
  69361. ** ensuring that the value written into *ppVal is eventually freed.
  69362. */
  69363. SQLITE_PRIVATE int sqlite3Stat4Column(
  69364. sqlite3 *db, /* Database handle */
  69365. const void *pRec, /* Pointer to buffer containing record */
  69366. int nRec, /* Size of buffer pRec in bytes */
  69367. int iCol, /* Column to extract */
  69368. sqlite3_value **ppVal /* OUT: Extracted value */
  69369. ){
  69370. u32 t; /* a column type code */
  69371. int nHdr; /* Size of the header in the record */
  69372. int iHdr; /* Next unread header byte */
  69373. int iField; /* Next unread data byte */
  69374. int szField; /* Size of the current data field */
  69375. int i; /* Column index */
  69376. u8 *a = (u8*)pRec; /* Typecast byte array */
  69377. Mem *pMem = *ppVal; /* Write result into this Mem object */
  69378. assert( iCol>0 );
  69379. iHdr = getVarint32(a, nHdr);
  69380. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  69381. iField = nHdr;
  69382. for(i=0; i<=iCol; i++){
  69383. iHdr += getVarint32(&a[iHdr], t);
  69384. testcase( iHdr==nHdr );
  69385. testcase( iHdr==nHdr+1 );
  69386. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  69387. szField = sqlite3VdbeSerialTypeLen(t);
  69388. iField += szField;
  69389. }
  69390. testcase( iField==nRec );
  69391. testcase( iField==nRec+1 );
  69392. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  69393. if( pMem==0 ){
  69394. pMem = *ppVal = sqlite3ValueNew(db);
  69395. if( pMem==0 ) return SQLITE_NOMEM_BKPT;
  69396. }
  69397. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  69398. pMem->enc = ENC(db);
  69399. return SQLITE_OK;
  69400. }
  69401. /*
  69402. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  69403. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  69404. ** the object.
  69405. */
  69406. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  69407. if( pRec ){
  69408. int i;
  69409. int nCol = pRec->pKeyInfo->nAllField;
  69410. Mem *aMem = pRec->aMem;
  69411. sqlite3 *db = aMem[0].db;
  69412. for(i=0; i<nCol; i++){
  69413. sqlite3VdbeMemRelease(&aMem[i]);
  69414. }
  69415. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  69416. sqlite3DbFreeNN(db, pRec);
  69417. }
  69418. }
  69419. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  69420. /*
  69421. ** Change the string value of an sqlite3_value object
  69422. */
  69423. SQLITE_PRIVATE void sqlite3ValueSetStr(
  69424. sqlite3_value *v, /* Value to be set */
  69425. int n, /* Length of string z */
  69426. const void *z, /* Text of the new string */
  69427. u8 enc, /* Encoding to use */
  69428. void (*xDel)(void*) /* Destructor for the string */
  69429. ){
  69430. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  69431. }
  69432. /*
  69433. ** Free an sqlite3_value object
  69434. */
  69435. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  69436. if( !v ) return;
  69437. sqlite3VdbeMemRelease((Mem *)v);
  69438. sqlite3DbFreeNN(((Mem*)v)->db, v);
  69439. }
  69440. /*
  69441. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  69442. ** sqlite3_value object assuming that it uses the encoding "enc".
  69443. ** The valueBytes() routine is a helper function.
  69444. */
  69445. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  69446. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  69447. }
  69448. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  69449. Mem *p = (Mem*)pVal;
  69450. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  69451. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  69452. return p->n;
  69453. }
  69454. if( (p->flags & MEM_Blob)!=0 ){
  69455. if( p->flags & MEM_Zero ){
  69456. return p->n + p->u.nZero;
  69457. }else{
  69458. return p->n;
  69459. }
  69460. }
  69461. if( p->flags & MEM_Null ) return 0;
  69462. return valueBytes(pVal, enc);
  69463. }
  69464. /************** End of vdbemem.c *********************************************/
  69465. /************** Begin file vdbeaux.c *****************************************/
  69466. /*
  69467. ** 2003 September 6
  69468. **
  69469. ** The author disclaims copyright to this source code. In place of
  69470. ** a legal notice, here is a blessing:
  69471. **
  69472. ** May you do good and not evil.
  69473. ** May you find forgiveness for yourself and forgive others.
  69474. ** May you share freely, never taking more than you give.
  69475. **
  69476. *************************************************************************
  69477. ** This file contains code used for creating, destroying, and populating
  69478. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  69479. */
  69480. /* #include "sqliteInt.h" */
  69481. /* #include "vdbeInt.h" */
  69482. /*
  69483. ** Create a new virtual database engine.
  69484. */
  69485. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  69486. sqlite3 *db = pParse->db;
  69487. Vdbe *p;
  69488. p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
  69489. if( p==0 ) return 0;
  69490. memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
  69491. p->db = db;
  69492. if( db->pVdbe ){
  69493. db->pVdbe->pPrev = p;
  69494. }
  69495. p->pNext = db->pVdbe;
  69496. p->pPrev = 0;
  69497. db->pVdbe = p;
  69498. p->magic = VDBE_MAGIC_INIT;
  69499. p->pParse = pParse;
  69500. pParse->pVdbe = p;
  69501. assert( pParse->aLabel==0 );
  69502. assert( pParse->nLabel==0 );
  69503. assert( pParse->nOpAlloc==0 );
  69504. assert( pParse->szOpAlloc==0 );
  69505. sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
  69506. return p;
  69507. }
  69508. /*
  69509. ** Change the error string stored in Vdbe.zErrMsg
  69510. */
  69511. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  69512. va_list ap;
  69513. sqlite3DbFree(p->db, p->zErrMsg);
  69514. va_start(ap, zFormat);
  69515. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  69516. va_end(ap);
  69517. }
  69518. /*
  69519. ** Remember the SQL string for a prepared statement.
  69520. */
  69521. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
  69522. if( p==0 ) return;
  69523. p->prepFlags = prepFlags;
  69524. if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
  69525. p->expmask = 0;
  69526. }
  69527. assert( p->zSql==0 );
  69528. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  69529. }
  69530. /*
  69531. ** Swap all content between two VDBE structures.
  69532. */
  69533. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  69534. Vdbe tmp, *pTmp;
  69535. char *zTmp;
  69536. assert( pA->db==pB->db );
  69537. tmp = *pA;
  69538. *pA = *pB;
  69539. *pB = tmp;
  69540. pTmp = pA->pNext;
  69541. pA->pNext = pB->pNext;
  69542. pB->pNext = pTmp;
  69543. pTmp = pA->pPrev;
  69544. pA->pPrev = pB->pPrev;
  69545. pB->pPrev = pTmp;
  69546. zTmp = pA->zSql;
  69547. pA->zSql = pB->zSql;
  69548. pB->zSql = zTmp;
  69549. pB->expmask = pA->expmask;
  69550. pB->prepFlags = pA->prepFlags;
  69551. memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
  69552. pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
  69553. }
  69554. /*
  69555. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  69556. ** than its current size. nOp is guaranteed to be less than or equal
  69557. ** to 1024/sizeof(Op).
  69558. **
  69559. ** If an out-of-memory error occurs while resizing the array, return
  69560. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  69561. ** unchanged (this is so that any opcodes already allocated can be
  69562. ** correctly deallocated along with the rest of the Vdbe).
  69563. */
  69564. static int growOpArray(Vdbe *v, int nOp){
  69565. VdbeOp *pNew;
  69566. Parse *p = v->pParse;
  69567. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  69568. ** more frequent reallocs and hence provide more opportunities for
  69569. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  69570. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  69571. ** by the minimum* amount required until the size reaches 512. Normal
  69572. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  69573. ** size of the op array or add 1KB of space, whichever is smaller. */
  69574. #ifdef SQLITE_TEST_REALLOC_STRESS
  69575. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  69576. #else
  69577. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  69578. UNUSED_PARAMETER(nOp);
  69579. #endif
  69580. /* Ensure that the size of a VDBE does not grow too large */
  69581. if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
  69582. sqlite3OomFault(p->db);
  69583. return SQLITE_NOMEM;
  69584. }
  69585. assert( nOp<=(1024/sizeof(Op)) );
  69586. assert( nNew>=(p->nOpAlloc+nOp) );
  69587. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  69588. if( pNew ){
  69589. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  69590. p->nOpAlloc = p->szOpAlloc/sizeof(Op);
  69591. v->aOp = pNew;
  69592. }
  69593. return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
  69594. }
  69595. #ifdef SQLITE_DEBUG
  69596. /* This routine is just a convenient place to set a breakpoint that will
  69597. ** fire after each opcode is inserted and displayed using
  69598. ** "PRAGMA vdbe_addoptrace=on".
  69599. */
  69600. static void test_addop_breakpoint(void){
  69601. static int n = 0;
  69602. n++;
  69603. }
  69604. #endif
  69605. /*
  69606. ** Add a new instruction to the list of instructions current in the
  69607. ** VDBE. Return the address of the new instruction.
  69608. **
  69609. ** Parameters:
  69610. **
  69611. ** p Pointer to the VDBE
  69612. **
  69613. ** op The opcode for this instruction
  69614. **
  69615. ** p1, p2, p3 Operands
  69616. **
  69617. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  69618. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  69619. ** operand.
  69620. */
  69621. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  69622. assert( p->pParse->nOpAlloc<=p->nOp );
  69623. if( growOpArray(p, 1) ) return 1;
  69624. assert( p->pParse->nOpAlloc>p->nOp );
  69625. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  69626. }
  69627. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  69628. int i;
  69629. VdbeOp *pOp;
  69630. i = p->nOp;
  69631. assert( p->magic==VDBE_MAGIC_INIT );
  69632. assert( op>=0 && op<0xff );
  69633. if( p->pParse->nOpAlloc<=i ){
  69634. return growOp3(p, op, p1, p2, p3);
  69635. }
  69636. p->nOp++;
  69637. pOp = &p->aOp[i];
  69638. pOp->opcode = (u8)op;
  69639. pOp->p5 = 0;
  69640. pOp->p1 = p1;
  69641. pOp->p2 = p2;
  69642. pOp->p3 = p3;
  69643. pOp->p4.p = 0;
  69644. pOp->p4type = P4_NOTUSED;
  69645. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  69646. pOp->zComment = 0;
  69647. #endif
  69648. #ifdef SQLITE_DEBUG
  69649. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  69650. int jj, kk;
  69651. Parse *pParse = p->pParse;
  69652. for(jj=kk=0; jj<pParse->nColCache; jj++){
  69653. struct yColCache *x = pParse->aColCache + jj;
  69654. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  69655. kk++;
  69656. }
  69657. if( kk ) printf("\n");
  69658. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  69659. test_addop_breakpoint();
  69660. }
  69661. #endif
  69662. #ifdef VDBE_PROFILE
  69663. pOp->cycles = 0;
  69664. pOp->cnt = 0;
  69665. #endif
  69666. #ifdef SQLITE_VDBE_COVERAGE
  69667. pOp->iSrcLine = 0;
  69668. #endif
  69669. return i;
  69670. }
  69671. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  69672. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  69673. }
  69674. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  69675. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  69676. }
  69677. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  69678. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  69679. }
  69680. /* Generate code for an unconditional jump to instruction iDest
  69681. */
  69682. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  69683. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  69684. }
  69685. /* Generate code to cause the string zStr to be loaded into
  69686. ** register iDest
  69687. */
  69688. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  69689. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  69690. }
  69691. /*
  69692. ** Generate code that initializes multiple registers to string or integer
  69693. ** constants. The registers begin with iDest and increase consecutively.
  69694. ** One register is initialized for each characgter in zTypes[]. For each
  69695. ** "s" character in zTypes[], the register is a string if the argument is
  69696. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  69697. ** in zTypes[], the register is initialized to an integer.
  69698. **
  69699. ** If the input string does not end with "X" then an OP_ResultRow instruction
  69700. ** is generated for the values inserted.
  69701. */
  69702. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  69703. va_list ap;
  69704. int i;
  69705. char c;
  69706. va_start(ap, zTypes);
  69707. for(i=0; (c = zTypes[i])!=0; i++){
  69708. if( c=='s' ){
  69709. const char *z = va_arg(ap, const char*);
  69710. sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
  69711. }else if( c=='i' ){
  69712. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
  69713. }else{
  69714. goto skip_op_resultrow;
  69715. }
  69716. }
  69717. sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
  69718. skip_op_resultrow:
  69719. va_end(ap);
  69720. }
  69721. /*
  69722. ** Add an opcode that includes the p4 value as a pointer.
  69723. */
  69724. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  69725. Vdbe *p, /* Add the opcode to this VM */
  69726. int op, /* The new opcode */
  69727. int p1, /* The P1 operand */
  69728. int p2, /* The P2 operand */
  69729. int p3, /* The P3 operand */
  69730. const char *zP4, /* The P4 operand */
  69731. int p4type /* P4 operand type */
  69732. ){
  69733. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  69734. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  69735. return addr;
  69736. }
  69737. /*
  69738. ** Add an opcode that includes the p4 value with a P4_INT64 or
  69739. ** P4_REAL type.
  69740. */
  69741. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  69742. Vdbe *p, /* Add the opcode to this VM */
  69743. int op, /* The new opcode */
  69744. int p1, /* The P1 operand */
  69745. int p2, /* The P2 operand */
  69746. int p3, /* The P3 operand */
  69747. const u8 *zP4, /* The P4 operand */
  69748. int p4type /* P4 operand type */
  69749. ){
  69750. char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
  69751. if( p4copy ) memcpy(p4copy, zP4, 8);
  69752. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  69753. }
  69754. /*
  69755. ** Add an OP_ParseSchema opcode. This routine is broken out from
  69756. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  69757. ** as having been used.
  69758. **
  69759. ** The zWhere string must have been obtained from sqlite3_malloc().
  69760. ** This routine will take ownership of the allocated memory.
  69761. */
  69762. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  69763. int j;
  69764. sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  69765. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  69766. }
  69767. /*
  69768. ** Add an opcode that includes the p4 value as an integer.
  69769. */
  69770. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  69771. Vdbe *p, /* Add the opcode to this VM */
  69772. int op, /* The new opcode */
  69773. int p1, /* The P1 operand */
  69774. int p2, /* The P2 operand */
  69775. int p3, /* The P3 operand */
  69776. int p4 /* The P4 operand as an integer */
  69777. ){
  69778. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  69779. if( p->db->mallocFailed==0 ){
  69780. VdbeOp *pOp = &p->aOp[addr];
  69781. pOp->p4type = P4_INT32;
  69782. pOp->p4.i = p4;
  69783. }
  69784. return addr;
  69785. }
  69786. /* Insert the end of a co-routine
  69787. */
  69788. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
  69789. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  69790. /* Clear the temporary register cache, thereby ensuring that each
  69791. ** co-routine has its own independent set of registers, because co-routines
  69792. ** might expect their registers to be preserved across an OP_Yield, and
  69793. ** that could cause problems if two or more co-routines are using the same
  69794. ** temporary register.
  69795. */
  69796. v->pParse->nTempReg = 0;
  69797. v->pParse->nRangeReg = 0;
  69798. }
  69799. /*
  69800. ** Create a new symbolic label for an instruction that has yet to be
  69801. ** coded. The symbolic label is really just a negative number. The
  69802. ** label can be used as the P2 value of an operation. Later, when
  69803. ** the label is resolved to a specific address, the VDBE will scan
  69804. ** through its operation list and change all values of P2 which match
  69805. ** the label into the resolved address.
  69806. **
  69807. ** The VDBE knows that a P2 value is a label because labels are
  69808. ** always negative and P2 values are suppose to be non-negative.
  69809. ** Hence, a negative P2 value is a label that has yet to be resolved.
  69810. **
  69811. ** Zero is returned if a malloc() fails.
  69812. */
  69813. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  69814. Parse *p = v->pParse;
  69815. int i = p->nLabel++;
  69816. assert( v->magic==VDBE_MAGIC_INIT );
  69817. if( (i & (i-1))==0 ){
  69818. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  69819. (i*2+1)*sizeof(p->aLabel[0]));
  69820. }
  69821. if( p->aLabel ){
  69822. p->aLabel[i] = -1;
  69823. }
  69824. return ADDR(i);
  69825. }
  69826. /*
  69827. ** Resolve label "x" to be the address of the next instruction to
  69828. ** be inserted. The parameter "x" must have been obtained from
  69829. ** a prior call to sqlite3VdbeMakeLabel().
  69830. */
  69831. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  69832. Parse *p = v->pParse;
  69833. int j = ADDR(x);
  69834. assert( v->magic==VDBE_MAGIC_INIT );
  69835. assert( j<p->nLabel );
  69836. assert( j>=0 );
  69837. if( p->aLabel ){
  69838. p->aLabel[j] = v->nOp;
  69839. }
  69840. }
  69841. /*
  69842. ** Mark the VDBE as one that can only be run one time.
  69843. */
  69844. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  69845. p->runOnlyOnce = 1;
  69846. }
  69847. /*
  69848. ** Mark the VDBE as one that can only be run multiple times.
  69849. */
  69850. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
  69851. p->runOnlyOnce = 0;
  69852. }
  69853. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  69854. /*
  69855. ** The following type and function are used to iterate through all opcodes
  69856. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  69857. ** invoke directly or indirectly. It should be used as follows:
  69858. **
  69859. ** Op *pOp;
  69860. ** VdbeOpIter sIter;
  69861. **
  69862. ** memset(&sIter, 0, sizeof(sIter));
  69863. ** sIter.v = v; // v is of type Vdbe*
  69864. ** while( (pOp = opIterNext(&sIter)) ){
  69865. ** // Do something with pOp
  69866. ** }
  69867. ** sqlite3DbFree(v->db, sIter.apSub);
  69868. **
  69869. */
  69870. typedef struct VdbeOpIter VdbeOpIter;
  69871. struct VdbeOpIter {
  69872. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  69873. SubProgram **apSub; /* Array of subprograms */
  69874. int nSub; /* Number of entries in apSub */
  69875. int iAddr; /* Address of next instruction to return */
  69876. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  69877. };
  69878. static Op *opIterNext(VdbeOpIter *p){
  69879. Vdbe *v = p->v;
  69880. Op *pRet = 0;
  69881. Op *aOp;
  69882. int nOp;
  69883. if( p->iSub<=p->nSub ){
  69884. if( p->iSub==0 ){
  69885. aOp = v->aOp;
  69886. nOp = v->nOp;
  69887. }else{
  69888. aOp = p->apSub[p->iSub-1]->aOp;
  69889. nOp = p->apSub[p->iSub-1]->nOp;
  69890. }
  69891. assert( p->iAddr<nOp );
  69892. pRet = &aOp[p->iAddr];
  69893. p->iAddr++;
  69894. if( p->iAddr==nOp ){
  69895. p->iSub++;
  69896. p->iAddr = 0;
  69897. }
  69898. if( pRet->p4type==P4_SUBPROGRAM ){
  69899. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  69900. int j;
  69901. for(j=0; j<p->nSub; j++){
  69902. if( p->apSub[j]==pRet->p4.pProgram ) break;
  69903. }
  69904. if( j==p->nSub ){
  69905. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  69906. if( !p->apSub ){
  69907. pRet = 0;
  69908. }else{
  69909. p->apSub[p->nSub++] = pRet->p4.pProgram;
  69910. }
  69911. }
  69912. }
  69913. }
  69914. return pRet;
  69915. }
  69916. /*
  69917. ** Check if the program stored in the VM associated with pParse may
  69918. ** throw an ABORT exception (causing the statement, but not entire transaction
  69919. ** to be rolled back). This condition is true if the main program or any
  69920. ** sub-programs contains any of the following:
  69921. **
  69922. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  69923. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  69924. ** * OP_Destroy
  69925. ** * OP_VUpdate
  69926. ** * OP_VRename
  69927. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  69928. ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
  69929. ** (for CREATE TABLE AS SELECT ...)
  69930. **
  69931. ** Then check that the value of Parse.mayAbort is true if an
  69932. ** ABORT may be thrown, or false otherwise. Return true if it does
  69933. ** match, or false otherwise. This function is intended to be used as
  69934. ** part of an assert statement in the compiler. Similar to:
  69935. **
  69936. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  69937. */
  69938. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  69939. int hasAbort = 0;
  69940. int hasFkCounter = 0;
  69941. int hasCreateTable = 0;
  69942. int hasInitCoroutine = 0;
  69943. Op *pOp;
  69944. VdbeOpIter sIter;
  69945. memset(&sIter, 0, sizeof(sIter));
  69946. sIter.v = v;
  69947. while( (pOp = opIterNext(&sIter))!=0 ){
  69948. int opcode = pOp->opcode;
  69949. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  69950. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  69951. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  69952. ){
  69953. hasAbort = 1;
  69954. break;
  69955. }
  69956. if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
  69957. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  69958. #ifndef SQLITE_OMIT_FOREIGN_KEY
  69959. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  69960. hasFkCounter = 1;
  69961. }
  69962. #endif
  69963. }
  69964. sqlite3DbFree(v->db, sIter.apSub);
  69965. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  69966. ** If malloc failed, then the while() loop above may not have iterated
  69967. ** through all opcodes and hasAbort may be set incorrectly. Return
  69968. ** true for this case to prevent the assert() in the callers frame
  69969. ** from failing. */
  69970. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  69971. || (hasCreateTable && hasInitCoroutine) );
  69972. }
  69973. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  69974. /*
  69975. ** This routine is called after all opcodes have been inserted. It loops
  69976. ** through all the opcodes and fixes up some details.
  69977. **
  69978. ** (1) For each jump instruction with a negative P2 value (a label)
  69979. ** resolve the P2 value to an actual address.
  69980. **
  69981. ** (2) Compute the maximum number of arguments used by any SQL function
  69982. ** and store that value in *pMaxFuncArgs.
  69983. **
  69984. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  69985. ** indicate what the prepared statement actually does.
  69986. **
  69987. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  69988. **
  69989. ** (5) Reclaim the memory allocated for storing labels.
  69990. **
  69991. ** This routine will only function correctly if the mkopcodeh.tcl generator
  69992. ** script numbers the opcodes correctly. Changes to this routine must be
  69993. ** coordinated with changes to mkopcodeh.tcl.
  69994. */
  69995. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  69996. int nMaxArgs = *pMaxFuncArgs;
  69997. Op *pOp;
  69998. Parse *pParse = p->pParse;
  69999. int *aLabel = pParse->aLabel;
  70000. p->readOnly = 1;
  70001. p->bIsReader = 0;
  70002. pOp = &p->aOp[p->nOp-1];
  70003. while(1){
  70004. /* Only JUMP opcodes and the short list of special opcodes in the switch
  70005. ** below need to be considered. The mkopcodeh.tcl generator script groups
  70006. ** all these opcodes together near the front of the opcode list. Skip
  70007. ** any opcode that does not need processing by virtual of the fact that
  70008. ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
  70009. */
  70010. if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
  70011. /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
  70012. ** cases from this switch! */
  70013. switch( pOp->opcode ){
  70014. case OP_Transaction: {
  70015. if( pOp->p2!=0 ) p->readOnly = 0;
  70016. /* fall thru */
  70017. }
  70018. case OP_AutoCommit:
  70019. case OP_Savepoint: {
  70020. p->bIsReader = 1;
  70021. break;
  70022. }
  70023. #ifndef SQLITE_OMIT_WAL
  70024. case OP_Checkpoint:
  70025. #endif
  70026. case OP_Vacuum:
  70027. case OP_JournalMode: {
  70028. p->readOnly = 0;
  70029. p->bIsReader = 1;
  70030. break;
  70031. }
  70032. case OP_Next:
  70033. case OP_NextIfOpen:
  70034. case OP_SorterNext: {
  70035. pOp->p4.xAdvance = sqlite3BtreeNext;
  70036. pOp->p4type = P4_ADVANCE;
  70037. /* The code generator never codes any of these opcodes as a jump
  70038. ** to a label. They are always coded as a jump backwards to a
  70039. ** known address */
  70040. assert( pOp->p2>=0 );
  70041. break;
  70042. }
  70043. case OP_Prev:
  70044. case OP_PrevIfOpen: {
  70045. pOp->p4.xAdvance = sqlite3BtreePrevious;
  70046. pOp->p4type = P4_ADVANCE;
  70047. /* The code generator never codes any of these opcodes as a jump
  70048. ** to a label. They are always coded as a jump backwards to a
  70049. ** known address */
  70050. assert( pOp->p2>=0 );
  70051. break;
  70052. }
  70053. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70054. case OP_VUpdate: {
  70055. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  70056. break;
  70057. }
  70058. case OP_VFilter: {
  70059. int n;
  70060. assert( (pOp - p->aOp) >= 3 );
  70061. assert( pOp[-1].opcode==OP_Integer );
  70062. n = pOp[-1].p1;
  70063. if( n>nMaxArgs ) nMaxArgs = n;
  70064. /* Fall through into the default case */
  70065. }
  70066. #endif
  70067. default: {
  70068. if( pOp->p2<0 ){
  70069. /* The mkopcodeh.tcl script has so arranged things that the only
  70070. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  70071. ** have non-negative values for P2. */
  70072. assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
  70073. assert( ADDR(pOp->p2)<pParse->nLabel );
  70074. pOp->p2 = aLabel[ADDR(pOp->p2)];
  70075. }
  70076. break;
  70077. }
  70078. }
  70079. /* The mkopcodeh.tcl script has so arranged things that the only
  70080. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  70081. ** have non-negative values for P2. */
  70082. assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
  70083. }
  70084. if( pOp==p->aOp ) break;
  70085. pOp--;
  70086. }
  70087. sqlite3DbFree(p->db, pParse->aLabel);
  70088. pParse->aLabel = 0;
  70089. pParse->nLabel = 0;
  70090. *pMaxFuncArgs = nMaxArgs;
  70091. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  70092. }
  70093. /*
  70094. ** Return the address of the next instruction to be inserted.
  70095. */
  70096. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  70097. assert( p->magic==VDBE_MAGIC_INIT );
  70098. return p->nOp;
  70099. }
  70100. /*
  70101. ** Verify that at least N opcode slots are available in p without
  70102. ** having to malloc for more space (except when compiled using
  70103. ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
  70104. ** to verify that certain calls to sqlite3VdbeAddOpList() can never
  70105. ** fail due to a OOM fault and hence that the return value from
  70106. ** sqlite3VdbeAddOpList() will always be non-NULL.
  70107. */
  70108. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  70109. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
  70110. assert( p->nOp + N <= p->pParse->nOpAlloc );
  70111. }
  70112. #endif
  70113. /*
  70114. ** Verify that the VM passed as the only argument does not contain
  70115. ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
  70116. ** by code in pragma.c to ensure that the implementation of certain
  70117. ** pragmas comports with the flags specified in the mkpragmatab.tcl
  70118. ** script.
  70119. */
  70120. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  70121. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
  70122. int i;
  70123. for(i=0; i<p->nOp; i++){
  70124. assert( p->aOp[i].opcode!=OP_ResultRow );
  70125. }
  70126. }
  70127. #endif
  70128. /*
  70129. ** This function returns a pointer to the array of opcodes associated with
  70130. ** the Vdbe passed as the first argument. It is the callers responsibility
  70131. ** to arrange for the returned array to be eventually freed using the
  70132. ** vdbeFreeOpArray() function.
  70133. **
  70134. ** Before returning, *pnOp is set to the number of entries in the returned
  70135. ** array. Also, *pnMaxArg is set to the larger of its current value and
  70136. ** the number of entries in the Vdbe.apArg[] array required to execute the
  70137. ** returned program.
  70138. */
  70139. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  70140. VdbeOp *aOp = p->aOp;
  70141. assert( aOp && !p->db->mallocFailed );
  70142. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  70143. assert( DbMaskAllZero(p->btreeMask) );
  70144. resolveP2Values(p, pnMaxArg);
  70145. *pnOp = p->nOp;
  70146. p->aOp = 0;
  70147. return aOp;
  70148. }
  70149. /*
  70150. ** Add a whole list of operations to the operation stack. Return a
  70151. ** pointer to the first operation inserted.
  70152. **
  70153. ** Non-zero P2 arguments to jump instructions are automatically adjusted
  70154. ** so that the jump target is relative to the first operation inserted.
  70155. */
  70156. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
  70157. Vdbe *p, /* Add opcodes to the prepared statement */
  70158. int nOp, /* Number of opcodes to add */
  70159. VdbeOpList const *aOp, /* The opcodes to be added */
  70160. int iLineno /* Source-file line number of first opcode */
  70161. ){
  70162. int i;
  70163. VdbeOp *pOut, *pFirst;
  70164. assert( nOp>0 );
  70165. assert( p->magic==VDBE_MAGIC_INIT );
  70166. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  70167. return 0;
  70168. }
  70169. pFirst = pOut = &p->aOp[p->nOp];
  70170. for(i=0; i<nOp; i++, aOp++, pOut++){
  70171. pOut->opcode = aOp->opcode;
  70172. pOut->p1 = aOp->p1;
  70173. pOut->p2 = aOp->p2;
  70174. assert( aOp->p2>=0 );
  70175. if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
  70176. pOut->p2 += p->nOp;
  70177. }
  70178. pOut->p3 = aOp->p3;
  70179. pOut->p4type = P4_NOTUSED;
  70180. pOut->p4.p = 0;
  70181. pOut->p5 = 0;
  70182. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  70183. pOut->zComment = 0;
  70184. #endif
  70185. #ifdef SQLITE_VDBE_COVERAGE
  70186. pOut->iSrcLine = iLineno+i;
  70187. #else
  70188. (void)iLineno;
  70189. #endif
  70190. #ifdef SQLITE_DEBUG
  70191. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  70192. sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
  70193. }
  70194. #endif
  70195. }
  70196. p->nOp += nOp;
  70197. return pFirst;
  70198. }
  70199. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  70200. /*
  70201. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  70202. */
  70203. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  70204. Vdbe *p, /* VM to add scanstatus() to */
  70205. int addrExplain, /* Address of OP_Explain (or 0) */
  70206. int addrLoop, /* Address of loop counter */
  70207. int addrVisit, /* Address of rows visited counter */
  70208. LogEst nEst, /* Estimated number of output rows */
  70209. const char *zName /* Name of table or index being scanned */
  70210. ){
  70211. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  70212. ScanStatus *aNew;
  70213. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  70214. if( aNew ){
  70215. ScanStatus *pNew = &aNew[p->nScan++];
  70216. pNew->addrExplain = addrExplain;
  70217. pNew->addrLoop = addrLoop;
  70218. pNew->addrVisit = addrVisit;
  70219. pNew->nEst = nEst;
  70220. pNew->zName = sqlite3DbStrDup(p->db, zName);
  70221. p->aScan = aNew;
  70222. }
  70223. }
  70224. #endif
  70225. /*
  70226. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  70227. ** for a specific instruction.
  70228. */
  70229. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
  70230. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  70231. }
  70232. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  70233. sqlite3VdbeGetOp(p,addr)->p1 = val;
  70234. }
  70235. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  70236. sqlite3VdbeGetOp(p,addr)->p2 = val;
  70237. }
  70238. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  70239. sqlite3VdbeGetOp(p,addr)->p3 = val;
  70240. }
  70241. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
  70242. assert( p->nOp>0 || p->db->mallocFailed );
  70243. if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
  70244. }
  70245. /*
  70246. ** Change the P2 operand of instruction addr so that it points to
  70247. ** the address of the next instruction to be coded.
  70248. */
  70249. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  70250. sqlite3VdbeChangeP2(p, addr, p->nOp);
  70251. }
  70252. /*
  70253. ** If the input FuncDef structure is ephemeral, then free it. If
  70254. ** the FuncDef is not ephermal, then do nothing.
  70255. */
  70256. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  70257. if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  70258. sqlite3DbFreeNN(db, pDef);
  70259. }
  70260. }
  70261. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  70262. /*
  70263. ** Delete a P4 value if necessary.
  70264. */
  70265. static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
  70266. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  70267. sqlite3DbFreeNN(db, p);
  70268. }
  70269. static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
  70270. freeEphemeralFunction(db, p->pFunc);
  70271. sqlite3DbFreeNN(db, p);
  70272. }
  70273. static void freeP4(sqlite3 *db, int p4type, void *p4){
  70274. assert( db );
  70275. switch( p4type ){
  70276. case P4_FUNCCTX: {
  70277. freeP4FuncCtx(db, (sqlite3_context*)p4);
  70278. break;
  70279. }
  70280. case P4_REAL:
  70281. case P4_INT64:
  70282. case P4_DYNAMIC:
  70283. case P4_DYNBLOB:
  70284. case P4_INTARRAY: {
  70285. sqlite3DbFree(db, p4);
  70286. break;
  70287. }
  70288. case P4_KEYINFO: {
  70289. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  70290. break;
  70291. }
  70292. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  70293. case P4_EXPR: {
  70294. sqlite3ExprDelete(db, (Expr*)p4);
  70295. break;
  70296. }
  70297. #endif
  70298. case P4_FUNCDEF: {
  70299. freeEphemeralFunction(db, (FuncDef*)p4);
  70300. break;
  70301. }
  70302. case P4_MEM: {
  70303. if( db->pnBytesFreed==0 ){
  70304. sqlite3ValueFree((sqlite3_value*)p4);
  70305. }else{
  70306. freeP4Mem(db, (Mem*)p4);
  70307. }
  70308. break;
  70309. }
  70310. case P4_VTAB : {
  70311. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  70312. break;
  70313. }
  70314. }
  70315. }
  70316. /*
  70317. ** Free the space allocated for aOp and any p4 values allocated for the
  70318. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  70319. ** nOp entries.
  70320. */
  70321. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  70322. if( aOp ){
  70323. Op *pOp;
  70324. for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
  70325. if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
  70326. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  70327. sqlite3DbFree(db, pOp->zComment);
  70328. #endif
  70329. }
  70330. sqlite3DbFreeNN(db, aOp);
  70331. }
  70332. }
  70333. /*
  70334. ** Link the SubProgram object passed as the second argument into the linked
  70335. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  70336. ** objects when the VM is no longer required.
  70337. */
  70338. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  70339. p->pNext = pVdbe->pProgram;
  70340. pVdbe->pProgram = p;
  70341. }
  70342. /*
  70343. ** Change the opcode at addr into OP_Noop
  70344. */
  70345. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  70346. VdbeOp *pOp;
  70347. if( p->db->mallocFailed ) return 0;
  70348. assert( addr>=0 && addr<p->nOp );
  70349. pOp = &p->aOp[addr];
  70350. freeP4(p->db, pOp->p4type, pOp->p4.p);
  70351. pOp->p4type = P4_NOTUSED;
  70352. pOp->p4.z = 0;
  70353. pOp->opcode = OP_Noop;
  70354. return 1;
  70355. }
  70356. /*
  70357. ** If the last opcode is "op" and it is not a jump destination,
  70358. ** then remove it. Return true if and only if an opcode was removed.
  70359. */
  70360. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  70361. if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
  70362. return sqlite3VdbeChangeToNoop(p, p->nOp-1);
  70363. }else{
  70364. return 0;
  70365. }
  70366. }
  70367. /*
  70368. ** Change the value of the P4 operand for a specific instruction.
  70369. ** This routine is useful when a large program is loaded from a
  70370. ** static array using sqlite3VdbeAddOpList but we want to make a
  70371. ** few minor changes to the program.
  70372. **
  70373. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  70374. ** the string is made into memory obtained from sqlite3_malloc().
  70375. ** A value of n==0 means copy bytes of zP4 up to and including the
  70376. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  70377. **
  70378. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  70379. ** to a string or structure that is guaranteed to exist for the lifetime of
  70380. ** the Vdbe. In these cases we can just copy the pointer.
  70381. **
  70382. ** If addr<0 then change P4 on the most recently inserted instruction.
  70383. */
  70384. static void SQLITE_NOINLINE vdbeChangeP4Full(
  70385. Vdbe *p,
  70386. Op *pOp,
  70387. const char *zP4,
  70388. int n
  70389. ){
  70390. if( pOp->p4type ){
  70391. freeP4(p->db, pOp->p4type, pOp->p4.p);
  70392. pOp->p4type = 0;
  70393. pOp->p4.p = 0;
  70394. }
  70395. if( n<0 ){
  70396. sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
  70397. }else{
  70398. if( n==0 ) n = sqlite3Strlen30(zP4);
  70399. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  70400. pOp->p4type = P4_DYNAMIC;
  70401. }
  70402. }
  70403. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  70404. Op *pOp;
  70405. sqlite3 *db;
  70406. assert( p!=0 );
  70407. db = p->db;
  70408. assert( p->magic==VDBE_MAGIC_INIT );
  70409. assert( p->aOp!=0 || db->mallocFailed );
  70410. if( db->mallocFailed ){
  70411. if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
  70412. return;
  70413. }
  70414. assert( p->nOp>0 );
  70415. assert( addr<p->nOp );
  70416. if( addr<0 ){
  70417. addr = p->nOp - 1;
  70418. }
  70419. pOp = &p->aOp[addr];
  70420. if( n>=0 || pOp->p4type ){
  70421. vdbeChangeP4Full(p, pOp, zP4, n);
  70422. return;
  70423. }
  70424. if( n==P4_INT32 ){
  70425. /* Note: this cast is safe, because the origin data point was an int
  70426. ** that was cast to a (const char *). */
  70427. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  70428. pOp->p4type = P4_INT32;
  70429. }else if( zP4!=0 ){
  70430. assert( n<0 );
  70431. pOp->p4.p = (void*)zP4;
  70432. pOp->p4type = (signed char)n;
  70433. if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
  70434. }
  70435. }
  70436. /*
  70437. ** Change the P4 operand of the most recently coded instruction
  70438. ** to the value defined by the arguments. This is a high-speed
  70439. ** version of sqlite3VdbeChangeP4().
  70440. **
  70441. ** The P4 operand must not have been previously defined. And the new
  70442. ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
  70443. ** those cases.
  70444. */
  70445. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
  70446. VdbeOp *pOp;
  70447. assert( n!=P4_INT32 && n!=P4_VTAB );
  70448. assert( n<=0 );
  70449. if( p->db->mallocFailed ){
  70450. freeP4(p->db, n, pP4);
  70451. }else{
  70452. assert( pP4!=0 );
  70453. assert( p->nOp>0 );
  70454. pOp = &p->aOp[p->nOp-1];
  70455. assert( pOp->p4type==P4_NOTUSED );
  70456. pOp->p4type = n;
  70457. pOp->p4.p = pP4;
  70458. }
  70459. }
  70460. /*
  70461. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  70462. ** index given.
  70463. */
  70464. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  70465. Vdbe *v = pParse->pVdbe;
  70466. KeyInfo *pKeyInfo;
  70467. assert( v!=0 );
  70468. assert( pIdx!=0 );
  70469. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
  70470. if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  70471. }
  70472. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  70473. /*
  70474. ** Change the comment on the most recently coded instruction. Or
  70475. ** insert a No-op and add the comment to that new instruction. This
  70476. ** makes the code easier to read during debugging. None of this happens
  70477. ** in a production build.
  70478. */
  70479. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  70480. assert( p->nOp>0 || p->aOp==0 );
  70481. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  70482. if( p->nOp ){
  70483. assert( p->aOp );
  70484. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  70485. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  70486. }
  70487. }
  70488. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  70489. va_list ap;
  70490. if( p ){
  70491. va_start(ap, zFormat);
  70492. vdbeVComment(p, zFormat, ap);
  70493. va_end(ap);
  70494. }
  70495. }
  70496. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  70497. va_list ap;
  70498. if( p ){
  70499. sqlite3VdbeAddOp0(p, OP_Noop);
  70500. va_start(ap, zFormat);
  70501. vdbeVComment(p, zFormat, ap);
  70502. va_end(ap);
  70503. }
  70504. }
  70505. #endif /* NDEBUG */
  70506. #ifdef SQLITE_VDBE_COVERAGE
  70507. /*
  70508. ** Set the value if the iSrcLine field for the previously coded instruction.
  70509. */
  70510. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  70511. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  70512. }
  70513. #endif /* SQLITE_VDBE_COVERAGE */
  70514. /*
  70515. ** Return the opcode for a given address. If the address is -1, then
  70516. ** return the most recently inserted opcode.
  70517. **
  70518. ** If a memory allocation error has occurred prior to the calling of this
  70519. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  70520. ** is readable but not writable, though it is cast to a writable value.
  70521. ** The return of a dummy opcode allows the call to continue functioning
  70522. ** after an OOM fault without having to check to see if the return from
  70523. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  70524. ** dummy will never be written to. This is verified by code inspection and
  70525. ** by running with Valgrind.
  70526. */
  70527. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  70528. /* C89 specifies that the constant "dummy" will be initialized to all
  70529. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  70530. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  70531. assert( p->magic==VDBE_MAGIC_INIT );
  70532. if( addr<0 ){
  70533. addr = p->nOp - 1;
  70534. }
  70535. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  70536. if( p->db->mallocFailed ){
  70537. return (VdbeOp*)&dummy;
  70538. }else{
  70539. return &p->aOp[addr];
  70540. }
  70541. }
  70542. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  70543. /*
  70544. ** Return an integer value for one of the parameters to the opcode pOp
  70545. ** determined by character c.
  70546. */
  70547. static int translateP(char c, const Op *pOp){
  70548. if( c=='1' ) return pOp->p1;
  70549. if( c=='2' ) return pOp->p2;
  70550. if( c=='3' ) return pOp->p3;
  70551. if( c=='4' ) return pOp->p4.i;
  70552. return pOp->p5;
  70553. }
  70554. /*
  70555. ** Compute a string for the "comment" field of a VDBE opcode listing.
  70556. **
  70557. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  70558. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  70559. ** absence of other comments, this synopsis becomes the comment on the opcode.
  70560. ** Some translation occurs:
  70561. **
  70562. ** "PX" -> "r[X]"
  70563. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  70564. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  70565. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  70566. */
  70567. static int displayComment(
  70568. const Op *pOp, /* The opcode to be commented */
  70569. const char *zP4, /* Previously obtained value for P4 */
  70570. char *zTemp, /* Write result here */
  70571. int nTemp /* Space available in zTemp[] */
  70572. ){
  70573. const char *zOpName;
  70574. const char *zSynopsis;
  70575. int nOpName;
  70576. int ii, jj;
  70577. char zAlt[50];
  70578. zOpName = sqlite3OpcodeName(pOp->opcode);
  70579. nOpName = sqlite3Strlen30(zOpName);
  70580. if( zOpName[nOpName+1] ){
  70581. int seenCom = 0;
  70582. char c;
  70583. zSynopsis = zOpName += nOpName + 1;
  70584. if( strncmp(zSynopsis,"IF ",3)==0 ){
  70585. if( pOp->p5 & SQLITE_STOREP2 ){
  70586. sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
  70587. }else{
  70588. sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
  70589. }
  70590. zSynopsis = zAlt;
  70591. }
  70592. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  70593. if( c=='P' ){
  70594. c = zSynopsis[++ii];
  70595. if( c=='4' ){
  70596. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  70597. }else if( c=='X' ){
  70598. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  70599. seenCom = 1;
  70600. }else{
  70601. int v1 = translateP(c, pOp);
  70602. int v2;
  70603. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  70604. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  70605. ii += 3;
  70606. jj += sqlite3Strlen30(zTemp+jj);
  70607. v2 = translateP(zSynopsis[ii], pOp);
  70608. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  70609. ii += 2;
  70610. v2++;
  70611. }
  70612. if( v2>1 ){
  70613. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  70614. }
  70615. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  70616. ii += 4;
  70617. }
  70618. }
  70619. jj += sqlite3Strlen30(zTemp+jj);
  70620. }else{
  70621. zTemp[jj++] = c;
  70622. }
  70623. }
  70624. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  70625. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  70626. jj += sqlite3Strlen30(zTemp+jj);
  70627. }
  70628. if( jj<nTemp ) zTemp[jj] = 0;
  70629. }else if( pOp->zComment ){
  70630. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  70631. jj = sqlite3Strlen30(zTemp);
  70632. }else{
  70633. zTemp[0] = 0;
  70634. jj = 0;
  70635. }
  70636. return jj;
  70637. }
  70638. #endif /* SQLITE_DEBUG */
  70639. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  70640. /*
  70641. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  70642. ** that can be displayed in the P4 column of EXPLAIN output.
  70643. */
  70644. static void displayP4Expr(StrAccum *p, Expr *pExpr){
  70645. const char *zOp = 0;
  70646. switch( pExpr->op ){
  70647. case TK_STRING:
  70648. sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
  70649. break;
  70650. case TK_INTEGER:
  70651. sqlite3XPrintf(p, "%d", pExpr->u.iValue);
  70652. break;
  70653. case TK_NULL:
  70654. sqlite3XPrintf(p, "NULL");
  70655. break;
  70656. case TK_REGISTER: {
  70657. sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
  70658. break;
  70659. }
  70660. case TK_COLUMN: {
  70661. if( pExpr->iColumn<0 ){
  70662. sqlite3XPrintf(p, "rowid");
  70663. }else{
  70664. sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
  70665. }
  70666. break;
  70667. }
  70668. case TK_LT: zOp = "LT"; break;
  70669. case TK_LE: zOp = "LE"; break;
  70670. case TK_GT: zOp = "GT"; break;
  70671. case TK_GE: zOp = "GE"; break;
  70672. case TK_NE: zOp = "NE"; break;
  70673. case TK_EQ: zOp = "EQ"; break;
  70674. case TK_IS: zOp = "IS"; break;
  70675. case TK_ISNOT: zOp = "ISNOT"; break;
  70676. case TK_AND: zOp = "AND"; break;
  70677. case TK_OR: zOp = "OR"; break;
  70678. case TK_PLUS: zOp = "ADD"; break;
  70679. case TK_STAR: zOp = "MUL"; break;
  70680. case TK_MINUS: zOp = "SUB"; break;
  70681. case TK_REM: zOp = "REM"; break;
  70682. case TK_BITAND: zOp = "BITAND"; break;
  70683. case TK_BITOR: zOp = "BITOR"; break;
  70684. case TK_SLASH: zOp = "DIV"; break;
  70685. case TK_LSHIFT: zOp = "LSHIFT"; break;
  70686. case TK_RSHIFT: zOp = "RSHIFT"; break;
  70687. case TK_CONCAT: zOp = "CONCAT"; break;
  70688. case TK_UMINUS: zOp = "MINUS"; break;
  70689. case TK_UPLUS: zOp = "PLUS"; break;
  70690. case TK_BITNOT: zOp = "BITNOT"; break;
  70691. case TK_NOT: zOp = "NOT"; break;
  70692. case TK_ISNULL: zOp = "ISNULL"; break;
  70693. case TK_NOTNULL: zOp = "NOTNULL"; break;
  70694. default:
  70695. sqlite3XPrintf(p, "%s", "expr");
  70696. break;
  70697. }
  70698. if( zOp ){
  70699. sqlite3XPrintf(p, "%s(", zOp);
  70700. displayP4Expr(p, pExpr->pLeft);
  70701. if( pExpr->pRight ){
  70702. sqlite3StrAccumAppend(p, ",", 1);
  70703. displayP4Expr(p, pExpr->pRight);
  70704. }
  70705. sqlite3StrAccumAppend(p, ")", 1);
  70706. }
  70707. }
  70708. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  70709. #if VDBE_DISPLAY_P4
  70710. /*
  70711. ** Compute a string that describes the P4 parameter for an opcode.
  70712. ** Use zTemp for any required temporary buffer space.
  70713. */
  70714. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  70715. char *zP4 = zTemp;
  70716. StrAccum x;
  70717. assert( nTemp>=20 );
  70718. sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
  70719. switch( pOp->p4type ){
  70720. case P4_KEYINFO: {
  70721. int j;
  70722. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  70723. assert( pKeyInfo->aSortOrder!=0 );
  70724. sqlite3XPrintf(&x, "k(%d", pKeyInfo->nKeyField);
  70725. for(j=0; j<pKeyInfo->nKeyField; j++){
  70726. CollSeq *pColl = pKeyInfo->aColl[j];
  70727. const char *zColl = pColl ? pColl->zName : "";
  70728. if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
  70729. sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
  70730. }
  70731. sqlite3StrAccumAppend(&x, ")", 1);
  70732. break;
  70733. }
  70734. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  70735. case P4_EXPR: {
  70736. displayP4Expr(&x, pOp->p4.pExpr);
  70737. break;
  70738. }
  70739. #endif
  70740. case P4_COLLSEQ: {
  70741. CollSeq *pColl = pOp->p4.pColl;
  70742. sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
  70743. break;
  70744. }
  70745. case P4_FUNCDEF: {
  70746. FuncDef *pDef = pOp->p4.pFunc;
  70747. sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  70748. break;
  70749. }
  70750. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  70751. case P4_FUNCCTX: {
  70752. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  70753. sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  70754. break;
  70755. }
  70756. #endif
  70757. case P4_INT64: {
  70758. sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
  70759. break;
  70760. }
  70761. case P4_INT32: {
  70762. sqlite3XPrintf(&x, "%d", pOp->p4.i);
  70763. break;
  70764. }
  70765. case P4_REAL: {
  70766. sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
  70767. break;
  70768. }
  70769. case P4_MEM: {
  70770. Mem *pMem = pOp->p4.pMem;
  70771. if( pMem->flags & MEM_Str ){
  70772. zP4 = pMem->z;
  70773. }else if( pMem->flags & MEM_Int ){
  70774. sqlite3XPrintf(&x, "%lld", pMem->u.i);
  70775. }else if( pMem->flags & MEM_Real ){
  70776. sqlite3XPrintf(&x, "%.16g", pMem->u.r);
  70777. }else if( pMem->flags & MEM_Null ){
  70778. zP4 = "NULL";
  70779. }else{
  70780. assert( pMem->flags & MEM_Blob );
  70781. zP4 = "(blob)";
  70782. }
  70783. break;
  70784. }
  70785. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70786. case P4_VTAB: {
  70787. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  70788. sqlite3XPrintf(&x, "vtab:%p", pVtab);
  70789. break;
  70790. }
  70791. #endif
  70792. case P4_INTARRAY: {
  70793. int i;
  70794. int *ai = pOp->p4.ai;
  70795. int n = ai[0]; /* The first element of an INTARRAY is always the
  70796. ** count of the number of elements to follow */
  70797. for(i=1; i<=n; i++){
  70798. sqlite3XPrintf(&x, ",%d", ai[i]);
  70799. }
  70800. zTemp[0] = '[';
  70801. sqlite3StrAccumAppend(&x, "]", 1);
  70802. break;
  70803. }
  70804. case P4_SUBPROGRAM: {
  70805. sqlite3XPrintf(&x, "program");
  70806. break;
  70807. }
  70808. case P4_DYNBLOB:
  70809. case P4_ADVANCE: {
  70810. zTemp[0] = 0;
  70811. break;
  70812. }
  70813. case P4_TABLE: {
  70814. sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
  70815. break;
  70816. }
  70817. default: {
  70818. zP4 = pOp->p4.z;
  70819. if( zP4==0 ){
  70820. zP4 = zTemp;
  70821. zTemp[0] = 0;
  70822. }
  70823. }
  70824. }
  70825. sqlite3StrAccumFinish(&x);
  70826. assert( zP4!=0 );
  70827. return zP4;
  70828. }
  70829. #endif /* VDBE_DISPLAY_P4 */
  70830. /*
  70831. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  70832. **
  70833. ** The prepared statements need to know in advance the complete set of
  70834. ** attached databases that will be use. A mask of these databases
  70835. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  70836. ** p->btreeMask of databases that will require a lock.
  70837. */
  70838. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  70839. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  70840. assert( i<(int)sizeof(p->btreeMask)*8 );
  70841. DbMaskSet(p->btreeMask, i);
  70842. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  70843. DbMaskSet(p->lockMask, i);
  70844. }
  70845. }
  70846. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  70847. /*
  70848. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  70849. ** this routine obtains the mutex associated with each BtShared structure
  70850. ** that may be accessed by the VM passed as an argument. In doing so it also
  70851. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  70852. ** that the correct busy-handler callback is invoked if required.
  70853. **
  70854. ** If SQLite is not threadsafe but does support shared-cache mode, then
  70855. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  70856. ** of all of BtShared structures accessible via the database handle
  70857. ** associated with the VM.
  70858. **
  70859. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  70860. ** function is a no-op.
  70861. **
  70862. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  70863. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  70864. ** corresponding to btrees that use shared cache. Then the runtime of
  70865. ** this routine is N*N. But as N is rarely more than 1, this should not
  70866. ** be a problem.
  70867. */
  70868. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  70869. int i;
  70870. sqlite3 *db;
  70871. Db *aDb;
  70872. int nDb;
  70873. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  70874. db = p->db;
  70875. aDb = db->aDb;
  70876. nDb = db->nDb;
  70877. for(i=0; i<nDb; i++){
  70878. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  70879. sqlite3BtreeEnter(aDb[i].pBt);
  70880. }
  70881. }
  70882. }
  70883. #endif
  70884. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  70885. /*
  70886. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  70887. */
  70888. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  70889. int i;
  70890. sqlite3 *db;
  70891. Db *aDb;
  70892. int nDb;
  70893. db = p->db;
  70894. aDb = db->aDb;
  70895. nDb = db->nDb;
  70896. for(i=0; i<nDb; i++){
  70897. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  70898. sqlite3BtreeLeave(aDb[i].pBt);
  70899. }
  70900. }
  70901. }
  70902. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  70903. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  70904. vdbeLeave(p);
  70905. }
  70906. #endif
  70907. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  70908. /*
  70909. ** Print a single opcode. This routine is used for debugging only.
  70910. */
  70911. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  70912. char *zP4;
  70913. char zPtr[50];
  70914. char zCom[100];
  70915. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  70916. if( pOut==0 ) pOut = stdout;
  70917. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  70918. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  70919. displayComment(pOp, zP4, zCom, sizeof(zCom));
  70920. #else
  70921. zCom[0] = 0;
  70922. #endif
  70923. /* NB: The sqlite3OpcodeName() function is implemented by code created
  70924. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  70925. ** information from the vdbe.c source text */
  70926. fprintf(pOut, zFormat1, pc,
  70927. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  70928. zCom
  70929. );
  70930. fflush(pOut);
  70931. }
  70932. #endif
  70933. /*
  70934. ** Initialize an array of N Mem element.
  70935. */
  70936. static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
  70937. while( (N--)>0 ){
  70938. p->db = db;
  70939. p->flags = flags;
  70940. p->szMalloc = 0;
  70941. #ifdef SQLITE_DEBUG
  70942. p->pScopyFrom = 0;
  70943. #endif
  70944. p++;
  70945. }
  70946. }
  70947. /*
  70948. ** Release an array of N Mem elements
  70949. */
  70950. static void releaseMemArray(Mem *p, int N){
  70951. if( p && N ){
  70952. Mem *pEnd = &p[N];
  70953. sqlite3 *db = p->db;
  70954. if( db->pnBytesFreed ){
  70955. do{
  70956. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  70957. }while( (++p)<pEnd );
  70958. return;
  70959. }
  70960. do{
  70961. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  70962. assert( sqlite3VdbeCheckMemInvariants(p) );
  70963. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  70964. ** that takes advantage of the fact that the memory cell value is
  70965. ** being set to NULL after releasing any dynamic resources.
  70966. **
  70967. ** The justification for duplicating code is that according to
  70968. ** callgrind, this causes a certain test case to hit the CPU 4.7
  70969. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  70970. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  70971. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  70972. ** with no indexes using a single prepared INSERT statement, bind()
  70973. ** and reset(). Inserts are grouped into a transaction.
  70974. */
  70975. testcase( p->flags & MEM_Agg );
  70976. testcase( p->flags & MEM_Dyn );
  70977. testcase( p->flags & MEM_Frame );
  70978. testcase( p->flags & MEM_RowSet );
  70979. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  70980. sqlite3VdbeMemRelease(p);
  70981. }else if( p->szMalloc ){
  70982. sqlite3DbFreeNN(db, p->zMalloc);
  70983. p->szMalloc = 0;
  70984. }
  70985. p->flags = MEM_Undefined;
  70986. }while( (++p)<pEnd );
  70987. }
  70988. }
  70989. /*
  70990. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  70991. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  70992. */
  70993. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  70994. int i;
  70995. Mem *aMem = VdbeFrameMem(p);
  70996. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  70997. for(i=0; i<p->nChildCsr; i++){
  70998. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  70999. }
  71000. releaseMemArray(aMem, p->nChildMem);
  71001. sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
  71002. sqlite3DbFree(p->v->db, p);
  71003. }
  71004. #ifndef SQLITE_OMIT_EXPLAIN
  71005. /*
  71006. ** Give a listing of the program in the virtual machine.
  71007. **
  71008. ** The interface is the same as sqlite3VdbeExec(). But instead of
  71009. ** running the code, it invokes the callback once for each instruction.
  71010. ** This feature is used to implement "EXPLAIN".
  71011. **
  71012. ** When p->explain==1, each instruction is listed. When
  71013. ** p->explain==2, only OP_Explain instructions are listed and these
  71014. ** are shown in a different format. p->explain==2 is used to implement
  71015. ** EXPLAIN QUERY PLAN.
  71016. **
  71017. ** When p->explain==1, first the main program is listed, then each of
  71018. ** the trigger subprograms are listed one by one.
  71019. */
  71020. SQLITE_PRIVATE int sqlite3VdbeList(
  71021. Vdbe *p /* The VDBE */
  71022. ){
  71023. int nRow; /* Stop when row count reaches this */
  71024. int nSub = 0; /* Number of sub-vdbes seen so far */
  71025. SubProgram **apSub = 0; /* Array of sub-vdbes */
  71026. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  71027. sqlite3 *db = p->db; /* The database connection */
  71028. int i; /* Loop counter */
  71029. int rc = SQLITE_OK; /* Return code */
  71030. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  71031. int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
  71032. Op *pOp = 0;
  71033. assert( p->explain );
  71034. assert( p->magic==VDBE_MAGIC_RUN );
  71035. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  71036. /* Even though this opcode does not use dynamic strings for
  71037. ** the result, result columns may become dynamic if the user calls
  71038. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  71039. */
  71040. releaseMemArray(pMem, 8);
  71041. p->pResultSet = 0;
  71042. if( p->rc==SQLITE_NOMEM ){
  71043. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  71044. ** sqlite3_column_text16() failed. */
  71045. sqlite3OomFault(db);
  71046. return SQLITE_ERROR;
  71047. }
  71048. /* When the number of output rows reaches nRow, that means the
  71049. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  71050. ** nRow is the sum of the number of rows in the main program, plus
  71051. ** the sum of the number of rows in all trigger subprograms encountered
  71052. ** so far. The nRow value will increase as new trigger subprograms are
  71053. ** encountered, but p->pc will eventually catch up to nRow.
  71054. */
  71055. nRow = p->nOp;
  71056. if( bListSubprogs ){
  71057. /* The first 8 memory cells are used for the result set. So we will
  71058. ** commandeer the 9th cell to use as storage for an array of pointers
  71059. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  71060. ** cells. */
  71061. assert( p->nMem>9 );
  71062. pSub = &p->aMem[9];
  71063. if( pSub->flags&MEM_Blob ){
  71064. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  71065. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  71066. nSub = pSub->n/sizeof(Vdbe*);
  71067. apSub = (SubProgram **)pSub->z;
  71068. }
  71069. for(i=0; i<nSub; i++){
  71070. nRow += apSub[i]->nOp;
  71071. }
  71072. }
  71073. do{
  71074. i = p->pc++;
  71075. if( i>=nRow ){
  71076. p->rc = SQLITE_OK;
  71077. rc = SQLITE_DONE;
  71078. break;
  71079. }
  71080. if( i<p->nOp ){
  71081. /* The output line number is small enough that we are still in the
  71082. ** main program. */
  71083. pOp = &p->aOp[i];
  71084. }else{
  71085. /* We are currently listing subprograms. Figure out which one and
  71086. ** pick up the appropriate opcode. */
  71087. int j;
  71088. i -= p->nOp;
  71089. for(j=0; i>=apSub[j]->nOp; j++){
  71090. i -= apSub[j]->nOp;
  71091. }
  71092. pOp = &apSub[j]->aOp[i];
  71093. }
  71094. /* When an OP_Program opcode is encounter (the only opcode that has
  71095. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  71096. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  71097. ** has not already been seen.
  71098. */
  71099. if( bListSubprogs && pOp->p4type==P4_SUBPROGRAM ){
  71100. int nByte = (nSub+1)*sizeof(SubProgram*);
  71101. int j;
  71102. for(j=0; j<nSub; j++){
  71103. if( apSub[j]==pOp->p4.pProgram ) break;
  71104. }
  71105. if( j==nSub ){
  71106. p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
  71107. if( p->rc!=SQLITE_OK ){
  71108. rc = SQLITE_ERROR;
  71109. break;
  71110. }
  71111. apSub = (SubProgram **)pSub->z;
  71112. apSub[nSub++] = pOp->p4.pProgram;
  71113. pSub->flags |= MEM_Blob;
  71114. pSub->n = nSub*sizeof(SubProgram*);
  71115. nRow += pOp->p4.pProgram->nOp;
  71116. }
  71117. }
  71118. }while( p->explain==2 && pOp->opcode!=OP_Explain );
  71119. if( rc==SQLITE_OK ){
  71120. if( db->u1.isInterrupted ){
  71121. p->rc = SQLITE_INTERRUPT;
  71122. rc = SQLITE_ERROR;
  71123. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  71124. }else{
  71125. char *zP4;
  71126. if( p->explain==1 ){
  71127. pMem->flags = MEM_Int;
  71128. pMem->u.i = i; /* Program counter */
  71129. pMem++;
  71130. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  71131. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  71132. assert( pMem->z!=0 );
  71133. pMem->n = sqlite3Strlen30(pMem->z);
  71134. pMem->enc = SQLITE_UTF8;
  71135. pMem++;
  71136. }
  71137. pMem->flags = MEM_Int;
  71138. pMem->u.i = pOp->p1; /* P1 */
  71139. pMem++;
  71140. pMem->flags = MEM_Int;
  71141. pMem->u.i = pOp->p2; /* P2 */
  71142. pMem++;
  71143. pMem->flags = MEM_Int;
  71144. pMem->u.i = pOp->p3; /* P3 */
  71145. pMem++;
  71146. if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
  71147. assert( p->db->mallocFailed );
  71148. return SQLITE_ERROR;
  71149. }
  71150. pMem->flags = MEM_Str|MEM_Term;
  71151. zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
  71152. if( zP4!=pMem->z ){
  71153. pMem->n = 0;
  71154. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  71155. }else{
  71156. assert( pMem->z!=0 );
  71157. pMem->n = sqlite3Strlen30(pMem->z);
  71158. pMem->enc = SQLITE_UTF8;
  71159. }
  71160. pMem++;
  71161. if( p->explain==1 ){
  71162. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  71163. assert( p->db->mallocFailed );
  71164. return SQLITE_ERROR;
  71165. }
  71166. pMem->flags = MEM_Str|MEM_Term;
  71167. pMem->n = 2;
  71168. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  71169. pMem->enc = SQLITE_UTF8;
  71170. pMem++;
  71171. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  71172. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  71173. assert( p->db->mallocFailed );
  71174. return SQLITE_ERROR;
  71175. }
  71176. pMem->flags = MEM_Str|MEM_Term;
  71177. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  71178. pMem->enc = SQLITE_UTF8;
  71179. #else
  71180. pMem->flags = MEM_Null; /* Comment */
  71181. #endif
  71182. }
  71183. p->nResColumn = 8 - 4*(p->explain-1);
  71184. p->pResultSet = &p->aMem[1];
  71185. p->rc = SQLITE_OK;
  71186. rc = SQLITE_ROW;
  71187. }
  71188. }
  71189. return rc;
  71190. }
  71191. #endif /* SQLITE_OMIT_EXPLAIN */
  71192. #ifdef SQLITE_DEBUG
  71193. /*
  71194. ** Print the SQL that was used to generate a VDBE program.
  71195. */
  71196. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  71197. const char *z = 0;
  71198. if( p->zSql ){
  71199. z = p->zSql;
  71200. }else if( p->nOp>=1 ){
  71201. const VdbeOp *pOp = &p->aOp[0];
  71202. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  71203. z = pOp->p4.z;
  71204. while( sqlite3Isspace(*z) ) z++;
  71205. }
  71206. }
  71207. if( z ) printf("SQL: [%s]\n", z);
  71208. }
  71209. #endif
  71210. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  71211. /*
  71212. ** Print an IOTRACE message showing SQL content.
  71213. */
  71214. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  71215. int nOp = p->nOp;
  71216. VdbeOp *pOp;
  71217. if( sqlite3IoTrace==0 ) return;
  71218. if( nOp<1 ) return;
  71219. pOp = &p->aOp[0];
  71220. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  71221. int i, j;
  71222. char z[1000];
  71223. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  71224. for(i=0; sqlite3Isspace(z[i]); i++){}
  71225. for(j=0; z[i]; i++){
  71226. if( sqlite3Isspace(z[i]) ){
  71227. if( z[i-1]!=' ' ){
  71228. z[j++] = ' ';
  71229. }
  71230. }else{
  71231. z[j++] = z[i];
  71232. }
  71233. }
  71234. z[j] = 0;
  71235. sqlite3IoTrace("SQL %s\n", z);
  71236. }
  71237. }
  71238. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  71239. /* An instance of this object describes bulk memory available for use
  71240. ** by subcomponents of a prepared statement. Space is allocated out
  71241. ** of a ReusableSpace object by the allocSpace() routine below.
  71242. */
  71243. struct ReusableSpace {
  71244. u8 *pSpace; /* Available memory */
  71245. int nFree; /* Bytes of available memory */
  71246. int nNeeded; /* Total bytes that could not be allocated */
  71247. };
  71248. /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
  71249. ** from the ReusableSpace object. Return a pointer to the allocated
  71250. ** memory on success. If insufficient memory is available in the
  71251. ** ReusableSpace object, increase the ReusableSpace.nNeeded
  71252. ** value by the amount needed and return NULL.
  71253. **
  71254. ** If pBuf is not initially NULL, that means that the memory has already
  71255. ** been allocated by a prior call to this routine, so just return a copy
  71256. ** of pBuf and leave ReusableSpace unchanged.
  71257. **
  71258. ** This allocator is employed to repurpose unused slots at the end of the
  71259. ** opcode array of prepared state for other memory needs of the prepared
  71260. ** statement.
  71261. */
  71262. static void *allocSpace(
  71263. struct ReusableSpace *p, /* Bulk memory available for allocation */
  71264. void *pBuf, /* Pointer to a prior allocation */
  71265. int nByte /* Bytes of memory needed */
  71266. ){
  71267. assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
  71268. if( pBuf==0 ){
  71269. nByte = ROUND8(nByte);
  71270. if( nByte <= p->nFree ){
  71271. p->nFree -= nByte;
  71272. pBuf = &p->pSpace[p->nFree];
  71273. }else{
  71274. p->nNeeded += nByte;
  71275. }
  71276. }
  71277. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  71278. return pBuf;
  71279. }
  71280. /*
  71281. ** Rewind the VDBE back to the beginning in preparation for
  71282. ** running it.
  71283. */
  71284. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  71285. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  71286. int i;
  71287. #endif
  71288. assert( p!=0 );
  71289. assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
  71290. /* There should be at least one opcode.
  71291. */
  71292. assert( p->nOp>0 );
  71293. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  71294. p->magic = VDBE_MAGIC_RUN;
  71295. #ifdef SQLITE_DEBUG
  71296. for(i=0; i<p->nMem; i++){
  71297. assert( p->aMem[i].db==p->db );
  71298. }
  71299. #endif
  71300. p->pc = -1;
  71301. p->rc = SQLITE_OK;
  71302. p->errorAction = OE_Abort;
  71303. p->nChange = 0;
  71304. p->cacheCtr = 1;
  71305. p->minWriteFileFormat = 255;
  71306. p->iStatement = 0;
  71307. p->nFkConstraint = 0;
  71308. #ifdef VDBE_PROFILE
  71309. for(i=0; i<p->nOp; i++){
  71310. p->aOp[i].cnt = 0;
  71311. p->aOp[i].cycles = 0;
  71312. }
  71313. #endif
  71314. }
  71315. /*
  71316. ** Prepare a virtual machine for execution for the first time after
  71317. ** creating the virtual machine. This involves things such
  71318. ** as allocating registers and initializing the program counter.
  71319. ** After the VDBE has be prepped, it can be executed by one or more
  71320. ** calls to sqlite3VdbeExec().
  71321. **
  71322. ** This function may be called exactly once on each virtual machine.
  71323. ** After this routine is called the VM has been "packaged" and is ready
  71324. ** to run. After this routine is called, further calls to
  71325. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  71326. ** the Vdbe from the Parse object that helped generate it so that the
  71327. ** the Vdbe becomes an independent entity and the Parse object can be
  71328. ** destroyed.
  71329. **
  71330. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  71331. ** to its initial state after it has been run.
  71332. */
  71333. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  71334. Vdbe *p, /* The VDBE */
  71335. Parse *pParse /* Parsing context */
  71336. ){
  71337. sqlite3 *db; /* The database connection */
  71338. int nVar; /* Number of parameters */
  71339. int nMem; /* Number of VM memory registers */
  71340. int nCursor; /* Number of cursors required */
  71341. int nArg; /* Number of arguments in subprograms */
  71342. int n; /* Loop counter */
  71343. struct ReusableSpace x; /* Reusable bulk memory */
  71344. assert( p!=0 );
  71345. assert( p->nOp>0 );
  71346. assert( pParse!=0 );
  71347. assert( p->magic==VDBE_MAGIC_INIT );
  71348. assert( pParse==p->pParse );
  71349. db = p->db;
  71350. assert( db->mallocFailed==0 );
  71351. nVar = pParse->nVar;
  71352. nMem = pParse->nMem;
  71353. nCursor = pParse->nTab;
  71354. nArg = pParse->nMaxArg;
  71355. /* Each cursor uses a memory cell. The first cursor (cursor 0) can
  71356. ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
  71357. ** space at the end of aMem[] for cursors 1 and greater.
  71358. ** See also: allocateCursor().
  71359. */
  71360. nMem += nCursor;
  71361. if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
  71362. /* Figure out how much reusable memory is available at the end of the
  71363. ** opcode array. This extra memory will be reallocated for other elements
  71364. ** of the prepared statement.
  71365. */
  71366. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
  71367. x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
  71368. assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
  71369. x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
  71370. assert( x.nFree>=0 );
  71371. assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
  71372. resolveP2Values(p, &nArg);
  71373. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  71374. if( pParse->explain && nMem<10 ){
  71375. nMem = 10;
  71376. }
  71377. p->expired = 0;
  71378. /* Memory for registers, parameters, cursor, etc, is allocated in one or two
  71379. ** passes. On the first pass, we try to reuse unused memory at the
  71380. ** end of the opcode array. If we are unable to satisfy all memory
  71381. ** requirements by reusing the opcode array tail, then the second
  71382. ** pass will fill in the remainder using a fresh memory allocation.
  71383. **
  71384. ** This two-pass approach that reuses as much memory as possible from
  71385. ** the leftover memory at the end of the opcode array. This can significantly
  71386. ** reduce the amount of memory held by a prepared statement.
  71387. */
  71388. do {
  71389. x.nNeeded = 0;
  71390. p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
  71391. p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
  71392. p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
  71393. p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
  71394. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  71395. p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
  71396. #endif
  71397. if( x.nNeeded==0 ) break;
  71398. x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
  71399. x.nFree = x.nNeeded;
  71400. }while( !db->mallocFailed );
  71401. p->pVList = pParse->pVList;
  71402. pParse->pVList = 0;
  71403. p->explain = pParse->explain;
  71404. if( db->mallocFailed ){
  71405. p->nVar = 0;
  71406. p->nCursor = 0;
  71407. p->nMem = 0;
  71408. }else{
  71409. p->nCursor = nCursor;
  71410. p->nVar = (ynVar)nVar;
  71411. initMemArray(p->aVar, nVar, db, MEM_Null);
  71412. p->nMem = nMem;
  71413. initMemArray(p->aMem, nMem, db, MEM_Undefined);
  71414. memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
  71415. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  71416. memset(p->anExec, 0, p->nOp*sizeof(i64));
  71417. #endif
  71418. }
  71419. sqlite3VdbeRewind(p);
  71420. }
  71421. /*
  71422. ** Close a VDBE cursor and release all the resources that cursor
  71423. ** happens to hold.
  71424. */
  71425. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  71426. if( pCx==0 ){
  71427. return;
  71428. }
  71429. assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
  71430. switch( pCx->eCurType ){
  71431. case CURTYPE_SORTER: {
  71432. sqlite3VdbeSorterClose(p->db, pCx);
  71433. break;
  71434. }
  71435. case CURTYPE_BTREE: {
  71436. if( pCx->isEphemeral ){
  71437. if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
  71438. /* The pCx->pCursor will be close automatically, if it exists, by
  71439. ** the call above. */
  71440. }else{
  71441. assert( pCx->uc.pCursor!=0 );
  71442. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  71443. }
  71444. break;
  71445. }
  71446. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71447. case CURTYPE_VTAB: {
  71448. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  71449. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  71450. assert( pVCur->pVtab->nRef>0 );
  71451. pVCur->pVtab->nRef--;
  71452. pModule->xClose(pVCur);
  71453. break;
  71454. }
  71455. #endif
  71456. }
  71457. }
  71458. /*
  71459. ** Close all cursors in the current frame.
  71460. */
  71461. static void closeCursorsInFrame(Vdbe *p){
  71462. if( p->apCsr ){
  71463. int i;
  71464. for(i=0; i<p->nCursor; i++){
  71465. VdbeCursor *pC = p->apCsr[i];
  71466. if( pC ){
  71467. sqlite3VdbeFreeCursor(p, pC);
  71468. p->apCsr[i] = 0;
  71469. }
  71470. }
  71471. }
  71472. }
  71473. /*
  71474. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  71475. ** is used, for example, when a trigger sub-program is halted to restore
  71476. ** control to the main program.
  71477. */
  71478. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  71479. Vdbe *v = pFrame->v;
  71480. closeCursorsInFrame(v);
  71481. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  71482. v->anExec = pFrame->anExec;
  71483. #endif
  71484. v->aOp = pFrame->aOp;
  71485. v->nOp = pFrame->nOp;
  71486. v->aMem = pFrame->aMem;
  71487. v->nMem = pFrame->nMem;
  71488. v->apCsr = pFrame->apCsr;
  71489. v->nCursor = pFrame->nCursor;
  71490. v->db->lastRowid = pFrame->lastRowid;
  71491. v->nChange = pFrame->nChange;
  71492. v->db->nChange = pFrame->nDbChange;
  71493. sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  71494. v->pAuxData = pFrame->pAuxData;
  71495. pFrame->pAuxData = 0;
  71496. return pFrame->pc;
  71497. }
  71498. /*
  71499. ** Close all cursors.
  71500. **
  71501. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  71502. ** cell array. This is necessary as the memory cell array may contain
  71503. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  71504. ** open cursors.
  71505. */
  71506. static void closeAllCursors(Vdbe *p){
  71507. if( p->pFrame ){
  71508. VdbeFrame *pFrame;
  71509. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  71510. sqlite3VdbeFrameRestore(pFrame);
  71511. p->pFrame = 0;
  71512. p->nFrame = 0;
  71513. }
  71514. assert( p->nFrame==0 );
  71515. closeCursorsInFrame(p);
  71516. if( p->aMem ){
  71517. releaseMemArray(p->aMem, p->nMem);
  71518. }
  71519. while( p->pDelFrame ){
  71520. VdbeFrame *pDel = p->pDelFrame;
  71521. p->pDelFrame = pDel->pParent;
  71522. sqlite3VdbeFrameDelete(pDel);
  71523. }
  71524. /* Delete any auxdata allocations made by the VM */
  71525. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
  71526. assert( p->pAuxData==0 );
  71527. }
  71528. /*
  71529. ** Set the number of result columns that will be returned by this SQL
  71530. ** statement. This is now set at compile time, rather than during
  71531. ** execution of the vdbe program so that sqlite3_column_count() can
  71532. ** be called on an SQL statement before sqlite3_step().
  71533. */
  71534. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  71535. int n;
  71536. sqlite3 *db = p->db;
  71537. if( p->nResColumn ){
  71538. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  71539. sqlite3DbFree(db, p->aColName);
  71540. }
  71541. n = nResColumn*COLNAME_N;
  71542. p->nResColumn = (u16)nResColumn;
  71543. p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
  71544. if( p->aColName==0 ) return;
  71545. initMemArray(p->aColName, n, db, MEM_Null);
  71546. }
  71547. /*
  71548. ** Set the name of the idx'th column to be returned by the SQL statement.
  71549. ** zName must be a pointer to a nul terminated string.
  71550. **
  71551. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  71552. **
  71553. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  71554. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  71555. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  71556. */
  71557. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  71558. Vdbe *p, /* Vdbe being configured */
  71559. int idx, /* Index of column zName applies to */
  71560. int var, /* One of the COLNAME_* constants */
  71561. const char *zName, /* Pointer to buffer containing name */
  71562. void (*xDel)(void*) /* Memory management strategy for zName */
  71563. ){
  71564. int rc;
  71565. Mem *pColName;
  71566. assert( idx<p->nResColumn );
  71567. assert( var<COLNAME_N );
  71568. if( p->db->mallocFailed ){
  71569. assert( !zName || xDel!=SQLITE_DYNAMIC );
  71570. return SQLITE_NOMEM_BKPT;
  71571. }
  71572. assert( p->aColName!=0 );
  71573. pColName = &(p->aColName[idx+var*p->nResColumn]);
  71574. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  71575. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  71576. return rc;
  71577. }
  71578. /*
  71579. ** A read or write transaction may or may not be active on database handle
  71580. ** db. If a transaction is active, commit it. If there is a
  71581. ** write-transaction spanning more than one database file, this routine
  71582. ** takes care of the master journal trickery.
  71583. */
  71584. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  71585. int i;
  71586. int nTrans = 0; /* Number of databases with an active write-transaction
  71587. ** that are candidates for a two-phase commit using a
  71588. ** master-journal */
  71589. int rc = SQLITE_OK;
  71590. int needXcommit = 0;
  71591. #ifdef SQLITE_OMIT_VIRTUALTABLE
  71592. /* With this option, sqlite3VtabSync() is defined to be simply
  71593. ** SQLITE_OK so p is not used.
  71594. */
  71595. UNUSED_PARAMETER(p);
  71596. #endif
  71597. /* Before doing anything else, call the xSync() callback for any
  71598. ** virtual module tables written in this transaction. This has to
  71599. ** be done before determining whether a master journal file is
  71600. ** required, as an xSync() callback may add an attached database
  71601. ** to the transaction.
  71602. */
  71603. rc = sqlite3VtabSync(db, p);
  71604. /* This loop determines (a) if the commit hook should be invoked and
  71605. ** (b) how many database files have open write transactions, not
  71606. ** including the temp database. (b) is important because if more than
  71607. ** one database file has an open write transaction, a master journal
  71608. ** file is required for an atomic commit.
  71609. */
  71610. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  71611. Btree *pBt = db->aDb[i].pBt;
  71612. if( sqlite3BtreeIsInTrans(pBt) ){
  71613. /* Whether or not a database might need a master journal depends upon
  71614. ** its journal mode (among other things). This matrix determines which
  71615. ** journal modes use a master journal and which do not */
  71616. static const u8 aMJNeeded[] = {
  71617. /* DELETE */ 1,
  71618. /* PERSIST */ 1,
  71619. /* OFF */ 0,
  71620. /* TRUNCATE */ 1,
  71621. /* MEMORY */ 0,
  71622. /* WAL */ 0
  71623. };
  71624. Pager *pPager; /* Pager associated with pBt */
  71625. needXcommit = 1;
  71626. sqlite3BtreeEnter(pBt);
  71627. pPager = sqlite3BtreePager(pBt);
  71628. if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
  71629. && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
  71630. && sqlite3PagerIsMemdb(pPager)==0
  71631. ){
  71632. assert( i!=1 );
  71633. nTrans++;
  71634. }
  71635. rc = sqlite3PagerExclusiveLock(pPager);
  71636. sqlite3BtreeLeave(pBt);
  71637. }
  71638. }
  71639. if( rc!=SQLITE_OK ){
  71640. return rc;
  71641. }
  71642. /* If there are any write-transactions at all, invoke the commit hook */
  71643. if( needXcommit && db->xCommitCallback ){
  71644. rc = db->xCommitCallback(db->pCommitArg);
  71645. if( rc ){
  71646. return SQLITE_CONSTRAINT_COMMITHOOK;
  71647. }
  71648. }
  71649. /* The simple case - no more than one database file (not counting the
  71650. ** TEMP database) has a transaction active. There is no need for the
  71651. ** master-journal.
  71652. **
  71653. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  71654. ** string, it means the main database is :memory: or a temp file. In
  71655. ** that case we do not support atomic multi-file commits, so use the
  71656. ** simple case then too.
  71657. */
  71658. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  71659. || nTrans<=1
  71660. ){
  71661. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  71662. Btree *pBt = db->aDb[i].pBt;
  71663. if( pBt ){
  71664. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  71665. }
  71666. }
  71667. /* Do the commit only if all databases successfully complete phase 1.
  71668. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  71669. ** IO error while deleting or truncating a journal file. It is unlikely,
  71670. ** but could happen. In this case abandon processing and return the error.
  71671. */
  71672. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  71673. Btree *pBt = db->aDb[i].pBt;
  71674. if( pBt ){
  71675. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  71676. }
  71677. }
  71678. if( rc==SQLITE_OK ){
  71679. sqlite3VtabCommit(db);
  71680. }
  71681. }
  71682. /* The complex case - There is a multi-file write-transaction active.
  71683. ** This requires a master journal file to ensure the transaction is
  71684. ** committed atomically.
  71685. */
  71686. #ifndef SQLITE_OMIT_DISKIO
  71687. else{
  71688. sqlite3_vfs *pVfs = db->pVfs;
  71689. char *zMaster = 0; /* File-name for the master journal */
  71690. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  71691. sqlite3_file *pMaster = 0;
  71692. i64 offset = 0;
  71693. int res;
  71694. int retryCount = 0;
  71695. int nMainFile;
  71696. /* Select a master journal file name */
  71697. nMainFile = sqlite3Strlen30(zMainFile);
  71698. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  71699. if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
  71700. do {
  71701. u32 iRandom;
  71702. if( retryCount ){
  71703. if( retryCount>100 ){
  71704. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  71705. sqlite3OsDelete(pVfs, zMaster, 0);
  71706. break;
  71707. }else if( retryCount==1 ){
  71708. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  71709. }
  71710. }
  71711. retryCount++;
  71712. sqlite3_randomness(sizeof(iRandom), &iRandom);
  71713. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  71714. (iRandom>>8)&0xffffff, iRandom&0xff);
  71715. /* The antipenultimate character of the master journal name must
  71716. ** be "9" to avoid name collisions when using 8+3 filenames. */
  71717. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  71718. sqlite3FileSuffix3(zMainFile, zMaster);
  71719. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  71720. }while( rc==SQLITE_OK && res );
  71721. if( rc==SQLITE_OK ){
  71722. /* Open the master journal. */
  71723. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  71724. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  71725. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  71726. );
  71727. }
  71728. if( rc!=SQLITE_OK ){
  71729. sqlite3DbFree(db, zMaster);
  71730. return rc;
  71731. }
  71732. /* Write the name of each database file in the transaction into the new
  71733. ** master journal file. If an error occurs at this point close
  71734. ** and delete the master journal file. All the individual journal files
  71735. ** still have 'null' as the master journal pointer, so they will roll
  71736. ** back independently if a failure occurs.
  71737. */
  71738. for(i=0; i<db->nDb; i++){
  71739. Btree *pBt = db->aDb[i].pBt;
  71740. if( sqlite3BtreeIsInTrans(pBt) ){
  71741. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  71742. if( zFile==0 ){
  71743. continue; /* Ignore TEMP and :memory: databases */
  71744. }
  71745. assert( zFile[0]!=0 );
  71746. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  71747. offset += sqlite3Strlen30(zFile)+1;
  71748. if( rc!=SQLITE_OK ){
  71749. sqlite3OsCloseFree(pMaster);
  71750. sqlite3OsDelete(pVfs, zMaster, 0);
  71751. sqlite3DbFree(db, zMaster);
  71752. return rc;
  71753. }
  71754. }
  71755. }
  71756. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  71757. ** flag is set this is not required.
  71758. */
  71759. if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  71760. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  71761. ){
  71762. sqlite3OsCloseFree(pMaster);
  71763. sqlite3OsDelete(pVfs, zMaster, 0);
  71764. sqlite3DbFree(db, zMaster);
  71765. return rc;
  71766. }
  71767. /* Sync all the db files involved in the transaction. The same call
  71768. ** sets the master journal pointer in each individual journal. If
  71769. ** an error occurs here, do not delete the master journal file.
  71770. **
  71771. ** If the error occurs during the first call to
  71772. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  71773. ** master journal file will be orphaned. But we cannot delete it,
  71774. ** in case the master journal file name was written into the journal
  71775. ** file before the failure occurred.
  71776. */
  71777. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  71778. Btree *pBt = db->aDb[i].pBt;
  71779. if( pBt ){
  71780. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  71781. }
  71782. }
  71783. sqlite3OsCloseFree(pMaster);
  71784. assert( rc!=SQLITE_BUSY );
  71785. if( rc!=SQLITE_OK ){
  71786. sqlite3DbFree(db, zMaster);
  71787. return rc;
  71788. }
  71789. /* Delete the master journal file. This commits the transaction. After
  71790. ** doing this the directory is synced again before any individual
  71791. ** transaction files are deleted.
  71792. */
  71793. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  71794. sqlite3DbFree(db, zMaster);
  71795. zMaster = 0;
  71796. if( rc ){
  71797. return rc;
  71798. }
  71799. /* All files and directories have already been synced, so the following
  71800. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  71801. ** deleting or truncating journals. If something goes wrong while
  71802. ** this is happening we don't really care. The integrity of the
  71803. ** transaction is already guaranteed, but some stray 'cold' journals
  71804. ** may be lying around. Returning an error code won't help matters.
  71805. */
  71806. disable_simulated_io_errors();
  71807. sqlite3BeginBenignMalloc();
  71808. for(i=0; i<db->nDb; i++){
  71809. Btree *pBt = db->aDb[i].pBt;
  71810. if( pBt ){
  71811. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  71812. }
  71813. }
  71814. sqlite3EndBenignMalloc();
  71815. enable_simulated_io_errors();
  71816. sqlite3VtabCommit(db);
  71817. }
  71818. #endif
  71819. return rc;
  71820. }
  71821. /*
  71822. ** This routine checks that the sqlite3.nVdbeActive count variable
  71823. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  71824. ** currently active. An assertion fails if the two counts do not match.
  71825. ** This is an internal self-check only - it is not an essential processing
  71826. ** step.
  71827. **
  71828. ** This is a no-op if NDEBUG is defined.
  71829. */
  71830. #ifndef NDEBUG
  71831. static void checkActiveVdbeCnt(sqlite3 *db){
  71832. Vdbe *p;
  71833. int cnt = 0;
  71834. int nWrite = 0;
  71835. int nRead = 0;
  71836. p = db->pVdbe;
  71837. while( p ){
  71838. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  71839. cnt++;
  71840. if( p->readOnly==0 ) nWrite++;
  71841. if( p->bIsReader ) nRead++;
  71842. }
  71843. p = p->pNext;
  71844. }
  71845. assert( cnt==db->nVdbeActive );
  71846. assert( nWrite==db->nVdbeWrite );
  71847. assert( nRead==db->nVdbeRead );
  71848. }
  71849. #else
  71850. #define checkActiveVdbeCnt(x)
  71851. #endif
  71852. /*
  71853. ** If the Vdbe passed as the first argument opened a statement-transaction,
  71854. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  71855. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  71856. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  71857. ** statement transaction is committed.
  71858. **
  71859. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  71860. ** Otherwise SQLITE_OK.
  71861. */
  71862. static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
  71863. sqlite3 *const db = p->db;
  71864. int rc = SQLITE_OK;
  71865. int i;
  71866. const int iSavepoint = p->iStatement-1;
  71867. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  71868. assert( db->nStatement>0 );
  71869. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  71870. for(i=0; i<db->nDb; i++){
  71871. int rc2 = SQLITE_OK;
  71872. Btree *pBt = db->aDb[i].pBt;
  71873. if( pBt ){
  71874. if( eOp==SAVEPOINT_ROLLBACK ){
  71875. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  71876. }
  71877. if( rc2==SQLITE_OK ){
  71878. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  71879. }
  71880. if( rc==SQLITE_OK ){
  71881. rc = rc2;
  71882. }
  71883. }
  71884. }
  71885. db->nStatement--;
  71886. p->iStatement = 0;
  71887. if( rc==SQLITE_OK ){
  71888. if( eOp==SAVEPOINT_ROLLBACK ){
  71889. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  71890. }
  71891. if( rc==SQLITE_OK ){
  71892. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  71893. }
  71894. }
  71895. /* If the statement transaction is being rolled back, also restore the
  71896. ** database handles deferred constraint counter to the value it had when
  71897. ** the statement transaction was opened. */
  71898. if( eOp==SAVEPOINT_ROLLBACK ){
  71899. db->nDeferredCons = p->nStmtDefCons;
  71900. db->nDeferredImmCons = p->nStmtDefImmCons;
  71901. }
  71902. return rc;
  71903. }
  71904. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  71905. if( p->db->nStatement && p->iStatement ){
  71906. return vdbeCloseStatement(p, eOp);
  71907. }
  71908. return SQLITE_OK;
  71909. }
  71910. /*
  71911. ** This function is called when a transaction opened by the database
  71912. ** handle associated with the VM passed as an argument is about to be
  71913. ** committed. If there are outstanding deferred foreign key constraint
  71914. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  71915. **
  71916. ** If there are outstanding FK violations and this function returns
  71917. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  71918. ** and write an error message to it. Then return SQLITE_ERROR.
  71919. */
  71920. #ifndef SQLITE_OMIT_FOREIGN_KEY
  71921. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  71922. sqlite3 *db = p->db;
  71923. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  71924. || (!deferred && p->nFkConstraint>0)
  71925. ){
  71926. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  71927. p->errorAction = OE_Abort;
  71928. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  71929. return SQLITE_ERROR;
  71930. }
  71931. return SQLITE_OK;
  71932. }
  71933. #endif
  71934. /*
  71935. ** This routine is called the when a VDBE tries to halt. If the VDBE
  71936. ** has made changes and is in autocommit mode, then commit those
  71937. ** changes. If a rollback is needed, then do the rollback.
  71938. **
  71939. ** This routine is the only way to move the state of a VM from
  71940. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  71941. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  71942. **
  71943. ** Return an error code. If the commit could not complete because of
  71944. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  71945. ** means the close did not happen and needs to be repeated.
  71946. */
  71947. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  71948. int rc; /* Used to store transient return codes */
  71949. sqlite3 *db = p->db;
  71950. /* This function contains the logic that determines if a statement or
  71951. ** transaction will be committed or rolled back as a result of the
  71952. ** execution of this virtual machine.
  71953. **
  71954. ** If any of the following errors occur:
  71955. **
  71956. ** SQLITE_NOMEM
  71957. ** SQLITE_IOERR
  71958. ** SQLITE_FULL
  71959. ** SQLITE_INTERRUPT
  71960. **
  71961. ** Then the internal cache might have been left in an inconsistent
  71962. ** state. We need to rollback the statement transaction, if there is
  71963. ** one, or the complete transaction if there is no statement transaction.
  71964. */
  71965. if( p->magic!=VDBE_MAGIC_RUN ){
  71966. return SQLITE_OK;
  71967. }
  71968. if( db->mallocFailed ){
  71969. p->rc = SQLITE_NOMEM_BKPT;
  71970. }
  71971. closeAllCursors(p);
  71972. checkActiveVdbeCnt(db);
  71973. /* No commit or rollback needed if the program never started or if the
  71974. ** SQL statement does not read or write a database file. */
  71975. if( p->pc>=0 && p->bIsReader ){
  71976. int mrc; /* Primary error code from p->rc */
  71977. int eStatementOp = 0;
  71978. int isSpecialError; /* Set to true if a 'special' error */
  71979. /* Lock all btrees used by the statement */
  71980. sqlite3VdbeEnter(p);
  71981. /* Check for one of the special errors */
  71982. mrc = p->rc & 0xff;
  71983. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  71984. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  71985. if( isSpecialError ){
  71986. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  71987. ** no rollback is necessary. Otherwise, at least a savepoint
  71988. ** transaction must be rolled back to restore the database to a
  71989. ** consistent state.
  71990. **
  71991. ** Even if the statement is read-only, it is important to perform
  71992. ** a statement or transaction rollback operation. If the error
  71993. ** occurred while writing to the journal, sub-journal or database
  71994. ** file as part of an effort to free up cache space (see function
  71995. ** pagerStress() in pager.c), the rollback is required to restore
  71996. ** the pager to a consistent state.
  71997. */
  71998. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  71999. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  72000. eStatementOp = SAVEPOINT_ROLLBACK;
  72001. }else{
  72002. /* We are forced to roll back the active transaction. Before doing
  72003. ** so, abort any other statements this handle currently has active.
  72004. */
  72005. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  72006. sqlite3CloseSavepoints(db);
  72007. db->autoCommit = 1;
  72008. p->nChange = 0;
  72009. }
  72010. }
  72011. }
  72012. /* Check for immediate foreign key violations. */
  72013. if( p->rc==SQLITE_OK ){
  72014. sqlite3VdbeCheckFk(p, 0);
  72015. }
  72016. /* If the auto-commit flag is set and this is the only active writer
  72017. ** VM, then we do either a commit or rollback of the current transaction.
  72018. **
  72019. ** Note: This block also runs if one of the special errors handled
  72020. ** above has occurred.
  72021. */
  72022. if( !sqlite3VtabInSync(db)
  72023. && db->autoCommit
  72024. && db->nVdbeWrite==(p->readOnly==0)
  72025. ){
  72026. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  72027. rc = sqlite3VdbeCheckFk(p, 1);
  72028. if( rc!=SQLITE_OK ){
  72029. if( NEVER(p->readOnly) ){
  72030. sqlite3VdbeLeave(p);
  72031. return SQLITE_ERROR;
  72032. }
  72033. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  72034. }else{
  72035. /* The auto-commit flag is true, the vdbe program was successful
  72036. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  72037. ** key constraints to hold up the transaction. This means a commit
  72038. ** is required. */
  72039. rc = vdbeCommit(db, p);
  72040. }
  72041. if( rc==SQLITE_BUSY && p->readOnly ){
  72042. sqlite3VdbeLeave(p);
  72043. return SQLITE_BUSY;
  72044. }else if( rc!=SQLITE_OK ){
  72045. p->rc = rc;
  72046. sqlite3RollbackAll(db, SQLITE_OK);
  72047. p->nChange = 0;
  72048. }else{
  72049. db->nDeferredCons = 0;
  72050. db->nDeferredImmCons = 0;
  72051. db->flags &= ~SQLITE_DeferFKs;
  72052. sqlite3CommitInternalChanges(db);
  72053. }
  72054. }else{
  72055. sqlite3RollbackAll(db, SQLITE_OK);
  72056. p->nChange = 0;
  72057. }
  72058. db->nStatement = 0;
  72059. }else if( eStatementOp==0 ){
  72060. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  72061. eStatementOp = SAVEPOINT_RELEASE;
  72062. }else if( p->errorAction==OE_Abort ){
  72063. eStatementOp = SAVEPOINT_ROLLBACK;
  72064. }else{
  72065. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  72066. sqlite3CloseSavepoints(db);
  72067. db->autoCommit = 1;
  72068. p->nChange = 0;
  72069. }
  72070. }
  72071. /* If eStatementOp is non-zero, then a statement transaction needs to
  72072. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  72073. ** do so. If this operation returns an error, and the current statement
  72074. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  72075. ** current statement error code.
  72076. */
  72077. if( eStatementOp ){
  72078. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  72079. if( rc ){
  72080. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  72081. p->rc = rc;
  72082. sqlite3DbFree(db, p->zErrMsg);
  72083. p->zErrMsg = 0;
  72084. }
  72085. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  72086. sqlite3CloseSavepoints(db);
  72087. db->autoCommit = 1;
  72088. p->nChange = 0;
  72089. }
  72090. }
  72091. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  72092. ** has been rolled back, update the database connection change-counter.
  72093. */
  72094. if( p->changeCntOn ){
  72095. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  72096. sqlite3VdbeSetChanges(db, p->nChange);
  72097. }else{
  72098. sqlite3VdbeSetChanges(db, 0);
  72099. }
  72100. p->nChange = 0;
  72101. }
  72102. /* Release the locks */
  72103. sqlite3VdbeLeave(p);
  72104. }
  72105. /* We have successfully halted and closed the VM. Record this fact. */
  72106. if( p->pc>=0 ){
  72107. db->nVdbeActive--;
  72108. if( !p->readOnly ) db->nVdbeWrite--;
  72109. if( p->bIsReader ) db->nVdbeRead--;
  72110. assert( db->nVdbeActive>=db->nVdbeRead );
  72111. assert( db->nVdbeRead>=db->nVdbeWrite );
  72112. assert( db->nVdbeWrite>=0 );
  72113. }
  72114. p->magic = VDBE_MAGIC_HALT;
  72115. checkActiveVdbeCnt(db);
  72116. if( db->mallocFailed ){
  72117. p->rc = SQLITE_NOMEM_BKPT;
  72118. }
  72119. /* If the auto-commit flag is set to true, then any locks that were held
  72120. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  72121. ** to invoke any required unlock-notify callbacks.
  72122. */
  72123. if( db->autoCommit ){
  72124. sqlite3ConnectionUnlocked(db);
  72125. }
  72126. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  72127. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  72128. }
  72129. /*
  72130. ** Each VDBE holds the result of the most recent sqlite3_step() call
  72131. ** in p->rc. This routine sets that result back to SQLITE_OK.
  72132. */
  72133. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  72134. p->rc = SQLITE_OK;
  72135. }
  72136. /*
  72137. ** Copy the error code and error message belonging to the VDBE passed
  72138. ** as the first argument to its database handle (so that they will be
  72139. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  72140. **
  72141. ** This function does not clear the VDBE error code or message, just
  72142. ** copies them to the database handle.
  72143. */
  72144. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  72145. sqlite3 *db = p->db;
  72146. int rc = p->rc;
  72147. if( p->zErrMsg ){
  72148. db->bBenignMalloc++;
  72149. sqlite3BeginBenignMalloc();
  72150. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  72151. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  72152. sqlite3EndBenignMalloc();
  72153. db->bBenignMalloc--;
  72154. }else if( db->pErr ){
  72155. sqlite3ValueSetNull(db->pErr);
  72156. }
  72157. db->errCode = rc;
  72158. return rc;
  72159. }
  72160. #ifdef SQLITE_ENABLE_SQLLOG
  72161. /*
  72162. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  72163. ** invoke it.
  72164. */
  72165. static void vdbeInvokeSqllog(Vdbe *v){
  72166. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  72167. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  72168. assert( v->db->init.busy==0 );
  72169. if( zExpanded ){
  72170. sqlite3GlobalConfig.xSqllog(
  72171. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  72172. );
  72173. sqlite3DbFree(v->db, zExpanded);
  72174. }
  72175. }
  72176. }
  72177. #else
  72178. # define vdbeInvokeSqllog(x)
  72179. #endif
  72180. /*
  72181. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  72182. ** Write any error messages into *pzErrMsg. Return the result code.
  72183. **
  72184. ** After this routine is run, the VDBE should be ready to be executed
  72185. ** again.
  72186. **
  72187. ** To look at it another way, this routine resets the state of the
  72188. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  72189. ** VDBE_MAGIC_INIT.
  72190. */
  72191. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  72192. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  72193. int i;
  72194. #endif
  72195. sqlite3 *db;
  72196. db = p->db;
  72197. /* If the VM did not run to completion or if it encountered an
  72198. ** error, then it might not have been halted properly. So halt
  72199. ** it now.
  72200. */
  72201. sqlite3VdbeHalt(p);
  72202. /* If the VDBE has be run even partially, then transfer the error code
  72203. ** and error message from the VDBE into the main database structure. But
  72204. ** if the VDBE has just been set to run but has not actually executed any
  72205. ** instructions yet, leave the main database error information unchanged.
  72206. */
  72207. if( p->pc>=0 ){
  72208. vdbeInvokeSqllog(p);
  72209. sqlite3VdbeTransferError(p);
  72210. if( p->runOnlyOnce ) p->expired = 1;
  72211. }else if( p->rc && p->expired ){
  72212. /* The expired flag was set on the VDBE before the first call
  72213. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  72214. ** called), set the database error in this case as well.
  72215. */
  72216. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  72217. }
  72218. /* Reset register contents and reclaim error message memory.
  72219. */
  72220. #ifdef SQLITE_DEBUG
  72221. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  72222. ** Vdbe.aMem[] arrays have already been cleaned up. */
  72223. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  72224. if( p->aMem ){
  72225. for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  72226. }
  72227. #endif
  72228. sqlite3DbFree(db, p->zErrMsg);
  72229. p->zErrMsg = 0;
  72230. p->pResultSet = 0;
  72231. /* Save profiling information from this VDBE run.
  72232. */
  72233. #ifdef VDBE_PROFILE
  72234. {
  72235. FILE *out = fopen("vdbe_profile.out", "a");
  72236. if( out ){
  72237. fprintf(out, "---- ");
  72238. for(i=0; i<p->nOp; i++){
  72239. fprintf(out, "%02x", p->aOp[i].opcode);
  72240. }
  72241. fprintf(out, "\n");
  72242. if( p->zSql ){
  72243. char c, pc = 0;
  72244. fprintf(out, "-- ");
  72245. for(i=0; (c = p->zSql[i])!=0; i++){
  72246. if( pc=='\n' ) fprintf(out, "-- ");
  72247. putc(c, out);
  72248. pc = c;
  72249. }
  72250. if( pc!='\n' ) fprintf(out, "\n");
  72251. }
  72252. for(i=0; i<p->nOp; i++){
  72253. char zHdr[100];
  72254. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  72255. p->aOp[i].cnt,
  72256. p->aOp[i].cycles,
  72257. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  72258. );
  72259. fprintf(out, "%s", zHdr);
  72260. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  72261. }
  72262. fclose(out);
  72263. }
  72264. }
  72265. #endif
  72266. p->magic = VDBE_MAGIC_RESET;
  72267. return p->rc & db->errMask;
  72268. }
  72269. /*
  72270. ** Clean up and delete a VDBE after execution. Return an integer which is
  72271. ** the result code. Write any error message text into *pzErrMsg.
  72272. */
  72273. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  72274. int rc = SQLITE_OK;
  72275. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  72276. rc = sqlite3VdbeReset(p);
  72277. assert( (rc & p->db->errMask)==rc );
  72278. }
  72279. sqlite3VdbeDelete(p);
  72280. return rc;
  72281. }
  72282. /*
  72283. ** If parameter iOp is less than zero, then invoke the destructor for
  72284. ** all auxiliary data pointers currently cached by the VM passed as
  72285. ** the first argument.
  72286. **
  72287. ** Or, if iOp is greater than or equal to zero, then the destructor is
  72288. ** only invoked for those auxiliary data pointers created by the user
  72289. ** function invoked by the OP_Function opcode at instruction iOp of
  72290. ** VM pVdbe, and only then if:
  72291. **
  72292. ** * the associated function parameter is the 32nd or later (counting
  72293. ** from left to right), or
  72294. **
  72295. ** * the corresponding bit in argument mask is clear (where the first
  72296. ** function parameter corresponds to bit 0 etc.).
  72297. */
  72298. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
  72299. while( *pp ){
  72300. AuxData *pAux = *pp;
  72301. if( (iOp<0)
  72302. || (pAux->iAuxOp==iOp
  72303. && pAux->iAuxArg>=0
  72304. && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
  72305. ){
  72306. testcase( pAux->iAuxArg==31 );
  72307. if( pAux->xDeleteAux ){
  72308. pAux->xDeleteAux(pAux->pAux);
  72309. }
  72310. *pp = pAux->pNextAux;
  72311. sqlite3DbFree(db, pAux);
  72312. }else{
  72313. pp= &pAux->pNextAux;
  72314. }
  72315. }
  72316. }
  72317. /*
  72318. ** Free all memory associated with the Vdbe passed as the second argument,
  72319. ** except for object itself, which is preserved.
  72320. **
  72321. ** The difference between this function and sqlite3VdbeDelete() is that
  72322. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  72323. ** the database connection and frees the object itself.
  72324. */
  72325. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  72326. SubProgram *pSub, *pNext;
  72327. assert( p->db==0 || p->db==db );
  72328. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  72329. for(pSub=p->pProgram; pSub; pSub=pNext){
  72330. pNext = pSub->pNext;
  72331. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  72332. sqlite3DbFree(db, pSub);
  72333. }
  72334. if( p->magic!=VDBE_MAGIC_INIT ){
  72335. releaseMemArray(p->aVar, p->nVar);
  72336. sqlite3DbFree(db, p->pVList);
  72337. sqlite3DbFree(db, p->pFree);
  72338. }
  72339. vdbeFreeOpArray(db, p->aOp, p->nOp);
  72340. sqlite3DbFree(db, p->aColName);
  72341. sqlite3DbFree(db, p->zSql);
  72342. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  72343. {
  72344. int i;
  72345. for(i=0; i<p->nScan; i++){
  72346. sqlite3DbFree(db, p->aScan[i].zName);
  72347. }
  72348. sqlite3DbFree(db, p->aScan);
  72349. }
  72350. #endif
  72351. }
  72352. /*
  72353. ** Delete an entire VDBE.
  72354. */
  72355. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  72356. sqlite3 *db;
  72357. assert( p!=0 );
  72358. db = p->db;
  72359. assert( sqlite3_mutex_held(db->mutex) );
  72360. sqlite3VdbeClearObject(db, p);
  72361. if( p->pPrev ){
  72362. p->pPrev->pNext = p->pNext;
  72363. }else{
  72364. assert( db->pVdbe==p );
  72365. db->pVdbe = p->pNext;
  72366. }
  72367. if( p->pNext ){
  72368. p->pNext->pPrev = p->pPrev;
  72369. }
  72370. p->magic = VDBE_MAGIC_DEAD;
  72371. p->db = 0;
  72372. sqlite3DbFreeNN(db, p);
  72373. }
  72374. /*
  72375. ** The cursor "p" has a pending seek operation that has not yet been
  72376. ** carried out. Seek the cursor now. If an error occurs, return
  72377. ** the appropriate error code.
  72378. */
  72379. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  72380. int res, rc;
  72381. #ifdef SQLITE_TEST
  72382. extern int sqlite3_search_count;
  72383. #endif
  72384. assert( p->deferredMoveto );
  72385. assert( p->isTable );
  72386. assert( p->eCurType==CURTYPE_BTREE );
  72387. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  72388. if( rc ) return rc;
  72389. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  72390. #ifdef SQLITE_TEST
  72391. sqlite3_search_count++;
  72392. #endif
  72393. p->deferredMoveto = 0;
  72394. p->cacheStatus = CACHE_STALE;
  72395. return SQLITE_OK;
  72396. }
  72397. /*
  72398. ** Something has moved cursor "p" out of place. Maybe the row it was
  72399. ** pointed to was deleted out from under it. Or maybe the btree was
  72400. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  72401. ** is supposed to be pointing. If the row was deleted out from under the
  72402. ** cursor, set the cursor to point to a NULL row.
  72403. */
  72404. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  72405. int isDifferentRow, rc;
  72406. assert( p->eCurType==CURTYPE_BTREE );
  72407. assert( p->uc.pCursor!=0 );
  72408. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  72409. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  72410. p->cacheStatus = CACHE_STALE;
  72411. if( isDifferentRow ) p->nullRow = 1;
  72412. return rc;
  72413. }
  72414. /*
  72415. ** Check to ensure that the cursor is valid. Restore the cursor
  72416. ** if need be. Return any I/O error from the restore operation.
  72417. */
  72418. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  72419. assert( p->eCurType==CURTYPE_BTREE );
  72420. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  72421. return handleMovedCursor(p);
  72422. }
  72423. return SQLITE_OK;
  72424. }
  72425. /*
  72426. ** Make sure the cursor p is ready to read or write the row to which it
  72427. ** was last positioned. Return an error code if an OOM fault or I/O error
  72428. ** prevents us from positioning the cursor to its correct position.
  72429. **
  72430. ** If a MoveTo operation is pending on the given cursor, then do that
  72431. ** MoveTo now. If no move is pending, check to see if the row has been
  72432. ** deleted out from under the cursor and if it has, mark the row as
  72433. ** a NULL row.
  72434. **
  72435. ** If the cursor is already pointing to the correct row and that row has
  72436. ** not been deleted out from under the cursor, then this routine is a no-op.
  72437. */
  72438. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
  72439. VdbeCursor *p = *pp;
  72440. assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
  72441. if( p->deferredMoveto ){
  72442. int iMap;
  72443. if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
  72444. *pp = p->pAltCursor;
  72445. *piCol = iMap - 1;
  72446. return SQLITE_OK;
  72447. }
  72448. return handleDeferredMoveto(p);
  72449. }
  72450. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  72451. return handleMovedCursor(p);
  72452. }
  72453. return SQLITE_OK;
  72454. }
  72455. /*
  72456. ** The following functions:
  72457. **
  72458. ** sqlite3VdbeSerialType()
  72459. ** sqlite3VdbeSerialTypeLen()
  72460. ** sqlite3VdbeSerialLen()
  72461. ** sqlite3VdbeSerialPut()
  72462. ** sqlite3VdbeSerialGet()
  72463. **
  72464. ** encapsulate the code that serializes values for storage in SQLite
  72465. ** data and index records. Each serialized value consists of a
  72466. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  72467. ** integer, stored as a varint.
  72468. **
  72469. ** In an SQLite index record, the serial type is stored directly before
  72470. ** the blob of data that it corresponds to. In a table record, all serial
  72471. ** types are stored at the start of the record, and the blobs of data at
  72472. ** the end. Hence these functions allow the caller to handle the
  72473. ** serial-type and data blob separately.
  72474. **
  72475. ** The following table describes the various storage classes for data:
  72476. **
  72477. ** serial type bytes of data type
  72478. ** -------------- --------------- ---------------
  72479. ** 0 0 NULL
  72480. ** 1 1 signed integer
  72481. ** 2 2 signed integer
  72482. ** 3 3 signed integer
  72483. ** 4 4 signed integer
  72484. ** 5 6 signed integer
  72485. ** 6 8 signed integer
  72486. ** 7 8 IEEE float
  72487. ** 8 0 Integer constant 0
  72488. ** 9 0 Integer constant 1
  72489. ** 10,11 reserved for expansion
  72490. ** N>=12 and even (N-12)/2 BLOB
  72491. ** N>=13 and odd (N-13)/2 text
  72492. **
  72493. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  72494. ** of SQLite will not understand those serial types.
  72495. */
  72496. /*
  72497. ** Return the serial-type for the value stored in pMem.
  72498. */
  72499. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  72500. int flags = pMem->flags;
  72501. u32 n;
  72502. assert( pLen!=0 );
  72503. if( flags&MEM_Null ){
  72504. *pLen = 0;
  72505. return 0;
  72506. }
  72507. if( flags&MEM_Int ){
  72508. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  72509. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  72510. i64 i = pMem->u.i;
  72511. u64 u;
  72512. if( i<0 ){
  72513. u = ~i;
  72514. }else{
  72515. u = i;
  72516. }
  72517. if( u<=127 ){
  72518. if( (i&1)==i && file_format>=4 ){
  72519. *pLen = 0;
  72520. return 8+(u32)u;
  72521. }else{
  72522. *pLen = 1;
  72523. return 1;
  72524. }
  72525. }
  72526. if( u<=32767 ){ *pLen = 2; return 2; }
  72527. if( u<=8388607 ){ *pLen = 3; return 3; }
  72528. if( u<=2147483647 ){ *pLen = 4; return 4; }
  72529. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  72530. *pLen = 8;
  72531. return 6;
  72532. }
  72533. if( flags&MEM_Real ){
  72534. *pLen = 8;
  72535. return 7;
  72536. }
  72537. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  72538. assert( pMem->n>=0 );
  72539. n = (u32)pMem->n;
  72540. if( flags & MEM_Zero ){
  72541. n += pMem->u.nZero;
  72542. }
  72543. *pLen = n;
  72544. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  72545. }
  72546. /*
  72547. ** The sizes for serial types less than 128
  72548. */
  72549. static const u8 sqlite3SmallTypeSizes[] = {
  72550. /* 0 1 2 3 4 5 6 7 8 9 */
  72551. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  72552. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  72553. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  72554. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  72555. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  72556. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  72557. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  72558. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  72559. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  72560. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  72561. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  72562. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  72563. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  72564. };
  72565. /*
  72566. ** Return the length of the data corresponding to the supplied serial-type.
  72567. */
  72568. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  72569. if( serial_type>=128 ){
  72570. return (serial_type-12)/2;
  72571. }else{
  72572. assert( serial_type<12
  72573. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  72574. return sqlite3SmallTypeSizes[serial_type];
  72575. }
  72576. }
  72577. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  72578. assert( serial_type<128 );
  72579. return sqlite3SmallTypeSizes[serial_type];
  72580. }
  72581. /*
  72582. ** If we are on an architecture with mixed-endian floating
  72583. ** points (ex: ARM7) then swap the lower 4 bytes with the
  72584. ** upper 4 bytes. Return the result.
  72585. **
  72586. ** For most architectures, this is a no-op.
  72587. **
  72588. ** (later): It is reported to me that the mixed-endian problem
  72589. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  72590. ** that early versions of GCC stored the two words of a 64-bit
  72591. ** float in the wrong order. And that error has been propagated
  72592. ** ever since. The blame is not necessarily with GCC, though.
  72593. ** GCC might have just copying the problem from a prior compiler.
  72594. ** I am also told that newer versions of GCC that follow a different
  72595. ** ABI get the byte order right.
  72596. **
  72597. ** Developers using SQLite on an ARM7 should compile and run their
  72598. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  72599. ** enabled, some asserts below will ensure that the byte order of
  72600. ** floating point values is correct.
  72601. **
  72602. ** (2007-08-30) Frank van Vugt has studied this problem closely
  72603. ** and has send his findings to the SQLite developers. Frank
  72604. ** writes that some Linux kernels offer floating point hardware
  72605. ** emulation that uses only 32-bit mantissas instead of a full
  72606. ** 48-bits as required by the IEEE standard. (This is the
  72607. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  72608. ** byte swapping becomes very complicated. To avoid problems,
  72609. ** the necessary byte swapping is carried out using a 64-bit integer
  72610. ** rather than a 64-bit float. Frank assures us that the code here
  72611. ** works for him. We, the developers, have no way to independently
  72612. ** verify this, but Frank seems to know what he is talking about
  72613. ** so we trust him.
  72614. */
  72615. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  72616. static u64 floatSwap(u64 in){
  72617. union {
  72618. u64 r;
  72619. u32 i[2];
  72620. } u;
  72621. u32 t;
  72622. u.r = in;
  72623. t = u.i[0];
  72624. u.i[0] = u.i[1];
  72625. u.i[1] = t;
  72626. return u.r;
  72627. }
  72628. # define swapMixedEndianFloat(X) X = floatSwap(X)
  72629. #else
  72630. # define swapMixedEndianFloat(X)
  72631. #endif
  72632. /*
  72633. ** Write the serialized data blob for the value stored in pMem into
  72634. ** buf. It is assumed that the caller has allocated sufficient space.
  72635. ** Return the number of bytes written.
  72636. **
  72637. ** nBuf is the amount of space left in buf[]. The caller is responsible
  72638. ** for allocating enough space to buf[] to hold the entire field, exclusive
  72639. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  72640. **
  72641. ** Return the number of bytes actually written into buf[]. The number
  72642. ** of bytes in the zero-filled tail is included in the return value only
  72643. ** if those bytes were zeroed in buf[].
  72644. */
  72645. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  72646. u32 len;
  72647. /* Integer and Real */
  72648. if( serial_type<=7 && serial_type>0 ){
  72649. u64 v;
  72650. u32 i;
  72651. if( serial_type==7 ){
  72652. assert( sizeof(v)==sizeof(pMem->u.r) );
  72653. memcpy(&v, &pMem->u.r, sizeof(v));
  72654. swapMixedEndianFloat(v);
  72655. }else{
  72656. v = pMem->u.i;
  72657. }
  72658. len = i = sqlite3SmallTypeSizes[serial_type];
  72659. assert( i>0 );
  72660. do{
  72661. buf[--i] = (u8)(v&0xFF);
  72662. v >>= 8;
  72663. }while( i );
  72664. return len;
  72665. }
  72666. /* String or blob */
  72667. if( serial_type>=12 ){
  72668. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  72669. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  72670. len = pMem->n;
  72671. if( len>0 ) memcpy(buf, pMem->z, len);
  72672. return len;
  72673. }
  72674. /* NULL or constants 0 or 1 */
  72675. return 0;
  72676. }
  72677. /* Input "x" is a sequence of unsigned characters that represent a
  72678. ** big-endian integer. Return the equivalent native integer
  72679. */
  72680. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  72681. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  72682. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  72683. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  72684. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  72685. /*
  72686. ** Deserialize the data blob pointed to by buf as serial type serial_type
  72687. ** and store the result in pMem. Return the number of bytes read.
  72688. **
  72689. ** This function is implemented as two separate routines for performance.
  72690. ** The few cases that require local variables are broken out into a separate
  72691. ** routine so that in most cases the overhead of moving the stack pointer
  72692. ** is avoided.
  72693. */
  72694. static u32 SQLITE_NOINLINE serialGet(
  72695. const unsigned char *buf, /* Buffer to deserialize from */
  72696. u32 serial_type, /* Serial type to deserialize */
  72697. Mem *pMem /* Memory cell to write value into */
  72698. ){
  72699. u64 x = FOUR_BYTE_UINT(buf);
  72700. u32 y = FOUR_BYTE_UINT(buf+4);
  72701. x = (x<<32) + y;
  72702. if( serial_type==6 ){
  72703. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  72704. ** twos-complement integer. */
  72705. pMem->u.i = *(i64*)&x;
  72706. pMem->flags = MEM_Int;
  72707. testcase( pMem->u.i<0 );
  72708. }else{
  72709. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  72710. ** floating point number. */
  72711. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  72712. /* Verify that integers and floating point values use the same
  72713. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  72714. ** defined that 64-bit floating point values really are mixed
  72715. ** endian.
  72716. */
  72717. static const u64 t1 = ((u64)0x3ff00000)<<32;
  72718. static const double r1 = 1.0;
  72719. u64 t2 = t1;
  72720. swapMixedEndianFloat(t2);
  72721. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  72722. #endif
  72723. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  72724. swapMixedEndianFloat(x);
  72725. memcpy(&pMem->u.r, &x, sizeof(x));
  72726. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  72727. }
  72728. return 8;
  72729. }
  72730. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  72731. const unsigned char *buf, /* Buffer to deserialize from */
  72732. u32 serial_type, /* Serial type to deserialize */
  72733. Mem *pMem /* Memory cell to write value into */
  72734. ){
  72735. switch( serial_type ){
  72736. case 10: { /* Internal use only: NULL with virtual table
  72737. ** UPDATE no-change flag set */
  72738. pMem->flags = MEM_Null|MEM_Zero;
  72739. pMem->n = 0;
  72740. pMem->u.nZero = 0;
  72741. break;
  72742. }
  72743. case 11: /* Reserved for future use */
  72744. case 0: { /* Null */
  72745. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  72746. pMem->flags = MEM_Null;
  72747. break;
  72748. }
  72749. case 1: {
  72750. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  72751. ** integer. */
  72752. pMem->u.i = ONE_BYTE_INT(buf);
  72753. pMem->flags = MEM_Int;
  72754. testcase( pMem->u.i<0 );
  72755. return 1;
  72756. }
  72757. case 2: { /* 2-byte signed integer */
  72758. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  72759. ** twos-complement integer. */
  72760. pMem->u.i = TWO_BYTE_INT(buf);
  72761. pMem->flags = MEM_Int;
  72762. testcase( pMem->u.i<0 );
  72763. return 2;
  72764. }
  72765. case 3: { /* 3-byte signed integer */
  72766. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  72767. ** twos-complement integer. */
  72768. pMem->u.i = THREE_BYTE_INT(buf);
  72769. pMem->flags = MEM_Int;
  72770. testcase( pMem->u.i<0 );
  72771. return 3;
  72772. }
  72773. case 4: { /* 4-byte signed integer */
  72774. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  72775. ** twos-complement integer. */
  72776. pMem->u.i = FOUR_BYTE_INT(buf);
  72777. #ifdef __HP_cc
  72778. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  72779. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  72780. #endif
  72781. pMem->flags = MEM_Int;
  72782. testcase( pMem->u.i<0 );
  72783. return 4;
  72784. }
  72785. case 5: { /* 6-byte signed integer */
  72786. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  72787. ** twos-complement integer. */
  72788. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  72789. pMem->flags = MEM_Int;
  72790. testcase( pMem->u.i<0 );
  72791. return 6;
  72792. }
  72793. case 6: /* 8-byte signed integer */
  72794. case 7: { /* IEEE floating point */
  72795. /* These use local variables, so do them in a separate routine
  72796. ** to avoid having to move the frame pointer in the common case */
  72797. return serialGet(buf,serial_type,pMem);
  72798. }
  72799. case 8: /* Integer 0 */
  72800. case 9: { /* Integer 1 */
  72801. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  72802. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  72803. pMem->u.i = serial_type-8;
  72804. pMem->flags = MEM_Int;
  72805. return 0;
  72806. }
  72807. default: {
  72808. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  72809. ** length.
  72810. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  72811. ** (N-13)/2 bytes in length. */
  72812. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  72813. pMem->z = (char *)buf;
  72814. pMem->n = (serial_type-12)/2;
  72815. pMem->flags = aFlag[serial_type&1];
  72816. return pMem->n;
  72817. }
  72818. }
  72819. return 0;
  72820. }
  72821. /*
  72822. ** This routine is used to allocate sufficient space for an UnpackedRecord
  72823. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  72824. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  72825. **
  72826. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  72827. ** the unaligned buffer passed via the second and third arguments (presumably
  72828. ** stack space). If the former, then *ppFree is set to a pointer that should
  72829. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  72830. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  72831. ** before returning.
  72832. **
  72833. ** If an OOM error occurs, NULL is returned.
  72834. */
  72835. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  72836. KeyInfo *pKeyInfo /* Description of the record */
  72837. ){
  72838. UnpackedRecord *p; /* Unpacked record to return */
  72839. int nByte; /* Number of bytes required for *p */
  72840. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
  72841. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  72842. if( !p ) return 0;
  72843. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  72844. assert( pKeyInfo->aSortOrder!=0 );
  72845. p->pKeyInfo = pKeyInfo;
  72846. p->nField = pKeyInfo->nKeyField + 1;
  72847. return p;
  72848. }
  72849. /*
  72850. ** Given the nKey-byte encoding of a record in pKey[], populate the
  72851. ** UnpackedRecord structure indicated by the fourth argument with the
  72852. ** contents of the decoded record.
  72853. */
  72854. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  72855. KeyInfo *pKeyInfo, /* Information about the record format */
  72856. int nKey, /* Size of the binary record */
  72857. const void *pKey, /* The binary record */
  72858. UnpackedRecord *p /* Populate this structure before returning. */
  72859. ){
  72860. const unsigned char *aKey = (const unsigned char *)pKey;
  72861. int d;
  72862. u32 idx; /* Offset in aKey[] to read from */
  72863. u16 u; /* Unsigned loop counter */
  72864. u32 szHdr;
  72865. Mem *pMem = p->aMem;
  72866. p->default_rc = 0;
  72867. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  72868. idx = getVarint32(aKey, szHdr);
  72869. d = szHdr;
  72870. u = 0;
  72871. while( idx<szHdr && d<=nKey ){
  72872. u32 serial_type;
  72873. idx += getVarint32(&aKey[idx], serial_type);
  72874. pMem->enc = pKeyInfo->enc;
  72875. pMem->db = pKeyInfo->db;
  72876. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  72877. pMem->szMalloc = 0;
  72878. pMem->z = 0;
  72879. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  72880. pMem++;
  72881. if( (++u)>=p->nField ) break;
  72882. }
  72883. assert( u<=pKeyInfo->nKeyField + 1 );
  72884. p->nField = u;
  72885. }
  72886. #ifdef SQLITE_DEBUG
  72887. /*
  72888. ** This function compares two index or table record keys in the same way
  72889. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  72890. ** this function deserializes and compares values using the
  72891. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  72892. ** in assert() statements to ensure that the optimized code in
  72893. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  72894. **
  72895. ** Return true if the result of comparison is equivalent to desiredResult.
  72896. ** Return false if there is a disagreement.
  72897. */
  72898. static int vdbeRecordCompareDebug(
  72899. int nKey1, const void *pKey1, /* Left key */
  72900. const UnpackedRecord *pPKey2, /* Right key */
  72901. int desiredResult /* Correct answer */
  72902. ){
  72903. u32 d1; /* Offset into aKey[] of next data element */
  72904. u32 idx1; /* Offset into aKey[] of next header element */
  72905. u32 szHdr1; /* Number of bytes in header */
  72906. int i = 0;
  72907. int rc = 0;
  72908. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  72909. KeyInfo *pKeyInfo;
  72910. Mem mem1;
  72911. pKeyInfo = pPKey2->pKeyInfo;
  72912. if( pKeyInfo->db==0 ) return 1;
  72913. mem1.enc = pKeyInfo->enc;
  72914. mem1.db = pKeyInfo->db;
  72915. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  72916. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  72917. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  72918. ** We could initialize it, as shown here, to silence those complaints.
  72919. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  72920. ** the unnecessary initialization has a measurable negative performance
  72921. ** impact, since this routine is a very high runner. And so, we choose
  72922. ** to ignore the compiler warnings and leave this variable uninitialized.
  72923. */
  72924. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  72925. idx1 = getVarint32(aKey1, szHdr1);
  72926. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  72927. d1 = szHdr1;
  72928. assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
  72929. assert( pKeyInfo->aSortOrder!=0 );
  72930. assert( pKeyInfo->nKeyField>0 );
  72931. assert( idx1<=szHdr1 || CORRUPT_DB );
  72932. do{
  72933. u32 serial_type1;
  72934. /* Read the serial types for the next element in each key. */
  72935. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  72936. /* Verify that there is enough key space remaining to avoid
  72937. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  72938. ** always be greater than or equal to the amount of required key space.
  72939. ** Use that approximation to avoid the more expensive call to
  72940. ** sqlite3VdbeSerialTypeLen() in the common case.
  72941. */
  72942. if( d1+serial_type1+2>(u32)nKey1
  72943. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  72944. ){
  72945. break;
  72946. }
  72947. /* Extract the values to be compared.
  72948. */
  72949. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  72950. /* Do the comparison
  72951. */
  72952. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  72953. if( rc!=0 ){
  72954. assert( mem1.szMalloc==0 ); /* See comment below */
  72955. if( pKeyInfo->aSortOrder[i] ){
  72956. rc = -rc; /* Invert the result for DESC sort order. */
  72957. }
  72958. goto debugCompareEnd;
  72959. }
  72960. i++;
  72961. }while( idx1<szHdr1 && i<pPKey2->nField );
  72962. /* No memory allocation is ever used on mem1. Prove this using
  72963. ** the following assert(). If the assert() fails, it indicates a
  72964. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  72965. */
  72966. assert( mem1.szMalloc==0 );
  72967. /* rc==0 here means that one of the keys ran out of fields and
  72968. ** all the fields up to that point were equal. Return the default_rc
  72969. ** value. */
  72970. rc = pPKey2->default_rc;
  72971. debugCompareEnd:
  72972. if( desiredResult==0 && rc==0 ) return 1;
  72973. if( desiredResult<0 && rc<0 ) return 1;
  72974. if( desiredResult>0 && rc>0 ) return 1;
  72975. if( CORRUPT_DB ) return 1;
  72976. if( pKeyInfo->db->mallocFailed ) return 1;
  72977. return 0;
  72978. }
  72979. #endif
  72980. #ifdef SQLITE_DEBUG
  72981. /*
  72982. ** Count the number of fields (a.k.a. columns) in the record given by
  72983. ** pKey,nKey. The verify that this count is less than or equal to the
  72984. ** limit given by pKeyInfo->nAllField.
  72985. **
  72986. ** If this constraint is not satisfied, it means that the high-speed
  72987. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  72988. ** not work correctly. If this assert() ever fires, it probably means
  72989. ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
  72990. ** incorrectly.
  72991. */
  72992. static void vdbeAssertFieldCountWithinLimits(
  72993. int nKey, const void *pKey, /* The record to verify */
  72994. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  72995. ){
  72996. int nField = 0;
  72997. u32 szHdr;
  72998. u32 idx;
  72999. u32 notUsed;
  73000. const unsigned char *aKey = (const unsigned char*)pKey;
  73001. if( CORRUPT_DB ) return;
  73002. idx = getVarint32(aKey, szHdr);
  73003. assert( nKey>=0 );
  73004. assert( szHdr<=(u32)nKey );
  73005. while( idx<szHdr ){
  73006. idx += getVarint32(aKey+idx, notUsed);
  73007. nField++;
  73008. }
  73009. assert( nField <= pKeyInfo->nAllField );
  73010. }
  73011. #else
  73012. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  73013. #endif
  73014. /*
  73015. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  73016. ** using the collation sequence pColl. As usual, return a negative , zero
  73017. ** or positive value if *pMem1 is less than, equal to or greater than
  73018. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  73019. */
  73020. static int vdbeCompareMemString(
  73021. const Mem *pMem1,
  73022. const Mem *pMem2,
  73023. const CollSeq *pColl,
  73024. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  73025. ){
  73026. if( pMem1->enc==pColl->enc ){
  73027. /* The strings are already in the correct encoding. Call the
  73028. ** comparison function directly */
  73029. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  73030. }else{
  73031. int rc;
  73032. const void *v1, *v2;
  73033. Mem c1;
  73034. Mem c2;
  73035. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  73036. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  73037. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  73038. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  73039. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  73040. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  73041. if( (v1==0 || v2==0) ){
  73042. if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
  73043. rc = 0;
  73044. }else{
  73045. rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
  73046. }
  73047. sqlite3VdbeMemRelease(&c1);
  73048. sqlite3VdbeMemRelease(&c2);
  73049. return rc;
  73050. }
  73051. }
  73052. /*
  73053. ** The input pBlob is guaranteed to be a Blob that is not marked
  73054. ** with MEM_Zero. Return true if it could be a zero-blob.
  73055. */
  73056. static int isAllZero(const char *z, int n){
  73057. int i;
  73058. for(i=0; i<n; i++){
  73059. if( z[i] ) return 0;
  73060. }
  73061. return 1;
  73062. }
  73063. /*
  73064. ** Compare two blobs. Return negative, zero, or positive if the first
  73065. ** is less than, equal to, or greater than the second, respectively.
  73066. ** If one blob is a prefix of the other, then the shorter is the lessor.
  73067. */
  73068. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  73069. int c;
  73070. int n1 = pB1->n;
  73071. int n2 = pB2->n;
  73072. /* It is possible to have a Blob value that has some non-zero content
  73073. ** followed by zero content. But that only comes up for Blobs formed
  73074. ** by the OP_MakeRecord opcode, and such Blobs never get passed into
  73075. ** sqlite3MemCompare(). */
  73076. assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
  73077. assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
  73078. if( (pB1->flags|pB2->flags) & MEM_Zero ){
  73079. if( pB1->flags & pB2->flags & MEM_Zero ){
  73080. return pB1->u.nZero - pB2->u.nZero;
  73081. }else if( pB1->flags & MEM_Zero ){
  73082. if( !isAllZero(pB2->z, pB2->n) ) return -1;
  73083. return pB1->u.nZero - n2;
  73084. }else{
  73085. if( !isAllZero(pB1->z, pB1->n) ) return +1;
  73086. return n1 - pB2->u.nZero;
  73087. }
  73088. }
  73089. c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
  73090. if( c ) return c;
  73091. return n1 - n2;
  73092. }
  73093. /*
  73094. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  73095. ** number. Return negative, zero, or positive if the first (i64) is less than,
  73096. ** equal to, or greater than the second (double).
  73097. */
  73098. static int sqlite3IntFloatCompare(i64 i, double r){
  73099. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  73100. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  73101. if( x<r ) return -1;
  73102. if( x>r ) return +1;
  73103. return 0;
  73104. }else{
  73105. i64 y;
  73106. double s;
  73107. if( r<-9223372036854775808.0 ) return +1;
  73108. if( r>9223372036854775807.0 ) return -1;
  73109. y = (i64)r;
  73110. if( i<y ) return -1;
  73111. if( i>y ){
  73112. if( y==SMALLEST_INT64 && r>0.0 ) return -1;
  73113. return +1;
  73114. }
  73115. s = (double)i;
  73116. if( s<r ) return -1;
  73117. if( s>r ) return +1;
  73118. return 0;
  73119. }
  73120. }
  73121. /*
  73122. ** Compare the values contained by the two memory cells, returning
  73123. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  73124. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  73125. ** and reals) sorted numerically, followed by text ordered by the collating
  73126. ** sequence pColl and finally blob's ordered by memcmp().
  73127. **
  73128. ** Two NULL values are considered equal by this function.
  73129. */
  73130. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  73131. int f1, f2;
  73132. int combined_flags;
  73133. f1 = pMem1->flags;
  73134. f2 = pMem2->flags;
  73135. combined_flags = f1|f2;
  73136. assert( (combined_flags & MEM_RowSet)==0 );
  73137. /* If one value is NULL, it is less than the other. If both values
  73138. ** are NULL, return 0.
  73139. */
  73140. if( combined_flags&MEM_Null ){
  73141. return (f2&MEM_Null) - (f1&MEM_Null);
  73142. }
  73143. /* At least one of the two values is a number
  73144. */
  73145. if( combined_flags&(MEM_Int|MEM_Real) ){
  73146. if( (f1 & f2 & MEM_Int)!=0 ){
  73147. if( pMem1->u.i < pMem2->u.i ) return -1;
  73148. if( pMem1->u.i > pMem2->u.i ) return +1;
  73149. return 0;
  73150. }
  73151. if( (f1 & f2 & MEM_Real)!=0 ){
  73152. if( pMem1->u.r < pMem2->u.r ) return -1;
  73153. if( pMem1->u.r > pMem2->u.r ) return +1;
  73154. return 0;
  73155. }
  73156. if( (f1&MEM_Int)!=0 ){
  73157. if( (f2&MEM_Real)!=0 ){
  73158. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  73159. }else{
  73160. return -1;
  73161. }
  73162. }
  73163. if( (f1&MEM_Real)!=0 ){
  73164. if( (f2&MEM_Int)!=0 ){
  73165. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  73166. }else{
  73167. return -1;
  73168. }
  73169. }
  73170. return +1;
  73171. }
  73172. /* If one value is a string and the other is a blob, the string is less.
  73173. ** If both are strings, compare using the collating functions.
  73174. */
  73175. if( combined_flags&MEM_Str ){
  73176. if( (f1 & MEM_Str)==0 ){
  73177. return 1;
  73178. }
  73179. if( (f2 & MEM_Str)==0 ){
  73180. return -1;
  73181. }
  73182. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  73183. assert( pMem1->enc==SQLITE_UTF8 ||
  73184. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  73185. /* The collation sequence must be defined at this point, even if
  73186. ** the user deletes the collation sequence after the vdbe program is
  73187. ** compiled (this was not always the case).
  73188. */
  73189. assert( !pColl || pColl->xCmp );
  73190. if( pColl ){
  73191. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  73192. }
  73193. /* If a NULL pointer was passed as the collate function, fall through
  73194. ** to the blob case and use memcmp(). */
  73195. }
  73196. /* Both values must be blobs. Compare using memcmp(). */
  73197. return sqlite3BlobCompare(pMem1, pMem2);
  73198. }
  73199. /*
  73200. ** The first argument passed to this function is a serial-type that
  73201. ** corresponds to an integer - all values between 1 and 9 inclusive
  73202. ** except 7. The second points to a buffer containing an integer value
  73203. ** serialized according to serial_type. This function deserializes
  73204. ** and returns the value.
  73205. */
  73206. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  73207. u32 y;
  73208. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  73209. switch( serial_type ){
  73210. case 0:
  73211. case 1:
  73212. testcase( aKey[0]&0x80 );
  73213. return ONE_BYTE_INT(aKey);
  73214. case 2:
  73215. testcase( aKey[0]&0x80 );
  73216. return TWO_BYTE_INT(aKey);
  73217. case 3:
  73218. testcase( aKey[0]&0x80 );
  73219. return THREE_BYTE_INT(aKey);
  73220. case 4: {
  73221. testcase( aKey[0]&0x80 );
  73222. y = FOUR_BYTE_UINT(aKey);
  73223. return (i64)*(int*)&y;
  73224. }
  73225. case 5: {
  73226. testcase( aKey[0]&0x80 );
  73227. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  73228. }
  73229. case 6: {
  73230. u64 x = FOUR_BYTE_UINT(aKey);
  73231. testcase( aKey[0]&0x80 );
  73232. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  73233. return (i64)*(i64*)&x;
  73234. }
  73235. }
  73236. return (serial_type - 8);
  73237. }
  73238. /*
  73239. ** This function compares the two table rows or index records
  73240. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  73241. ** or positive integer if key1 is less than, equal to or
  73242. ** greater than key2. The {nKey1, pKey1} key must be a blob
  73243. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  73244. ** key must be a parsed key such as obtained from
  73245. ** sqlite3VdbeParseRecord.
  73246. **
  73247. ** If argument bSkip is non-zero, it is assumed that the caller has already
  73248. ** determined that the first fields of the keys are equal.
  73249. **
  73250. ** Key1 and Key2 do not have to contain the same number of fields. If all
  73251. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  73252. ** returned.
  73253. **
  73254. ** If database corruption is discovered, set pPKey2->errCode to
  73255. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  73256. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  73257. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  73258. */
  73259. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  73260. int nKey1, const void *pKey1, /* Left key */
  73261. UnpackedRecord *pPKey2, /* Right key */
  73262. int bSkip /* If true, skip the first field */
  73263. ){
  73264. u32 d1; /* Offset into aKey[] of next data element */
  73265. int i; /* Index of next field to compare */
  73266. u32 szHdr1; /* Size of record header in bytes */
  73267. u32 idx1; /* Offset of first type in header */
  73268. int rc = 0; /* Return value */
  73269. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  73270. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  73271. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  73272. Mem mem1;
  73273. /* If bSkip is true, then the caller has already determined that the first
  73274. ** two elements in the keys are equal. Fix the various stack variables so
  73275. ** that this routine begins comparing at the second field. */
  73276. if( bSkip ){
  73277. u32 s1;
  73278. idx1 = 1 + getVarint32(&aKey1[1], s1);
  73279. szHdr1 = aKey1[0];
  73280. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  73281. i = 1;
  73282. pRhs++;
  73283. }else{
  73284. idx1 = getVarint32(aKey1, szHdr1);
  73285. d1 = szHdr1;
  73286. if( d1>(unsigned)nKey1 ){
  73287. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  73288. return 0; /* Corruption */
  73289. }
  73290. i = 0;
  73291. }
  73292. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  73293. assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
  73294. || CORRUPT_DB );
  73295. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  73296. assert( pPKey2->pKeyInfo->nKeyField>0 );
  73297. assert( idx1<=szHdr1 || CORRUPT_DB );
  73298. do{
  73299. u32 serial_type;
  73300. /* RHS is an integer */
  73301. if( pRhs->flags & MEM_Int ){
  73302. serial_type = aKey1[idx1];
  73303. testcase( serial_type==12 );
  73304. if( serial_type>=10 ){
  73305. rc = +1;
  73306. }else if( serial_type==0 ){
  73307. rc = -1;
  73308. }else if( serial_type==7 ){
  73309. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  73310. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  73311. }else{
  73312. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  73313. i64 rhs = pRhs->u.i;
  73314. if( lhs<rhs ){
  73315. rc = -1;
  73316. }else if( lhs>rhs ){
  73317. rc = +1;
  73318. }
  73319. }
  73320. }
  73321. /* RHS is real */
  73322. else if( pRhs->flags & MEM_Real ){
  73323. serial_type = aKey1[idx1];
  73324. if( serial_type>=10 ){
  73325. /* Serial types 12 or greater are strings and blobs (greater than
  73326. ** numbers). Types 10 and 11 are currently "reserved for future
  73327. ** use", so it doesn't really matter what the results of comparing
  73328. ** them to numberic values are. */
  73329. rc = +1;
  73330. }else if( serial_type==0 ){
  73331. rc = -1;
  73332. }else{
  73333. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  73334. if( serial_type==7 ){
  73335. if( mem1.u.r<pRhs->u.r ){
  73336. rc = -1;
  73337. }else if( mem1.u.r>pRhs->u.r ){
  73338. rc = +1;
  73339. }
  73340. }else{
  73341. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  73342. }
  73343. }
  73344. }
  73345. /* RHS is a string */
  73346. else if( pRhs->flags & MEM_Str ){
  73347. getVarint32(&aKey1[idx1], serial_type);
  73348. testcase( serial_type==12 );
  73349. if( serial_type<12 ){
  73350. rc = -1;
  73351. }else if( !(serial_type & 0x01) ){
  73352. rc = +1;
  73353. }else{
  73354. mem1.n = (serial_type - 12) / 2;
  73355. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  73356. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  73357. if( (d1+mem1.n) > (unsigned)nKey1 ){
  73358. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  73359. return 0; /* Corruption */
  73360. }else if( pKeyInfo->aColl[i] ){
  73361. mem1.enc = pKeyInfo->enc;
  73362. mem1.db = pKeyInfo->db;
  73363. mem1.flags = MEM_Str;
  73364. mem1.z = (char*)&aKey1[d1];
  73365. rc = vdbeCompareMemString(
  73366. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  73367. );
  73368. }else{
  73369. int nCmp = MIN(mem1.n, pRhs->n);
  73370. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  73371. if( rc==0 ) rc = mem1.n - pRhs->n;
  73372. }
  73373. }
  73374. }
  73375. /* RHS is a blob */
  73376. else if( pRhs->flags & MEM_Blob ){
  73377. assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
  73378. getVarint32(&aKey1[idx1], serial_type);
  73379. testcase( serial_type==12 );
  73380. if( serial_type<12 || (serial_type & 0x01) ){
  73381. rc = -1;
  73382. }else{
  73383. int nStr = (serial_type - 12) / 2;
  73384. testcase( (d1+nStr)==(unsigned)nKey1 );
  73385. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  73386. if( (d1+nStr) > (unsigned)nKey1 ){
  73387. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  73388. return 0; /* Corruption */
  73389. }else if( pRhs->flags & MEM_Zero ){
  73390. if( !isAllZero((const char*)&aKey1[d1],nStr) ){
  73391. rc = 1;
  73392. }else{
  73393. rc = nStr - pRhs->u.nZero;
  73394. }
  73395. }else{
  73396. int nCmp = MIN(nStr, pRhs->n);
  73397. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  73398. if( rc==0 ) rc = nStr - pRhs->n;
  73399. }
  73400. }
  73401. }
  73402. /* RHS is null */
  73403. else{
  73404. serial_type = aKey1[idx1];
  73405. rc = (serial_type!=0);
  73406. }
  73407. if( rc!=0 ){
  73408. if( pKeyInfo->aSortOrder[i] ){
  73409. rc = -rc;
  73410. }
  73411. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  73412. assert( mem1.szMalloc==0 ); /* See comment below */
  73413. return rc;
  73414. }
  73415. i++;
  73416. pRhs++;
  73417. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  73418. idx1 += sqlite3VarintLen(serial_type);
  73419. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  73420. /* No memory allocation is ever used on mem1. Prove this using
  73421. ** the following assert(). If the assert() fails, it indicates a
  73422. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  73423. assert( mem1.szMalloc==0 );
  73424. /* rc==0 here means that one or both of the keys ran out of fields and
  73425. ** all the fields up to that point were equal. Return the default_rc
  73426. ** value. */
  73427. assert( CORRUPT_DB
  73428. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  73429. || pKeyInfo->db->mallocFailed
  73430. );
  73431. pPKey2->eqSeen = 1;
  73432. return pPKey2->default_rc;
  73433. }
  73434. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  73435. int nKey1, const void *pKey1, /* Left key */
  73436. UnpackedRecord *pPKey2 /* Right key */
  73437. ){
  73438. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  73439. }
  73440. /*
  73441. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  73442. ** that (a) the first field of pPKey2 is an integer, and (b) the
  73443. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  73444. ** byte (i.e. is less than 128).
  73445. **
  73446. ** To avoid concerns about buffer overreads, this routine is only used
  73447. ** on schemas where the maximum valid header size is 63 bytes or less.
  73448. */
  73449. static int vdbeRecordCompareInt(
  73450. int nKey1, const void *pKey1, /* Left key */
  73451. UnpackedRecord *pPKey2 /* Right key */
  73452. ){
  73453. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  73454. int serial_type = ((const u8*)pKey1)[1];
  73455. int res;
  73456. u32 y;
  73457. u64 x;
  73458. i64 v;
  73459. i64 lhs;
  73460. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  73461. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  73462. switch( serial_type ){
  73463. case 1: { /* 1-byte signed integer */
  73464. lhs = ONE_BYTE_INT(aKey);
  73465. testcase( lhs<0 );
  73466. break;
  73467. }
  73468. case 2: { /* 2-byte signed integer */
  73469. lhs = TWO_BYTE_INT(aKey);
  73470. testcase( lhs<0 );
  73471. break;
  73472. }
  73473. case 3: { /* 3-byte signed integer */
  73474. lhs = THREE_BYTE_INT(aKey);
  73475. testcase( lhs<0 );
  73476. break;
  73477. }
  73478. case 4: { /* 4-byte signed integer */
  73479. y = FOUR_BYTE_UINT(aKey);
  73480. lhs = (i64)*(int*)&y;
  73481. testcase( lhs<0 );
  73482. break;
  73483. }
  73484. case 5: { /* 6-byte signed integer */
  73485. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  73486. testcase( lhs<0 );
  73487. break;
  73488. }
  73489. case 6: { /* 8-byte signed integer */
  73490. x = FOUR_BYTE_UINT(aKey);
  73491. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  73492. lhs = *(i64*)&x;
  73493. testcase( lhs<0 );
  73494. break;
  73495. }
  73496. case 8:
  73497. lhs = 0;
  73498. break;
  73499. case 9:
  73500. lhs = 1;
  73501. break;
  73502. /* This case could be removed without changing the results of running
  73503. ** this code. Including it causes gcc to generate a faster switch
  73504. ** statement (since the range of switch targets now starts at zero and
  73505. ** is contiguous) but does not cause any duplicate code to be generated
  73506. ** (as gcc is clever enough to combine the two like cases). Other
  73507. ** compilers might be similar. */
  73508. case 0: case 7:
  73509. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  73510. default:
  73511. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  73512. }
  73513. v = pPKey2->aMem[0].u.i;
  73514. if( v>lhs ){
  73515. res = pPKey2->r1;
  73516. }else if( v<lhs ){
  73517. res = pPKey2->r2;
  73518. }else if( pPKey2->nField>1 ){
  73519. /* The first fields of the two keys are equal. Compare the trailing
  73520. ** fields. */
  73521. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  73522. }else{
  73523. /* The first fields of the two keys are equal and there are no trailing
  73524. ** fields. Return pPKey2->default_rc in this case. */
  73525. res = pPKey2->default_rc;
  73526. pPKey2->eqSeen = 1;
  73527. }
  73528. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  73529. return res;
  73530. }
  73531. /*
  73532. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  73533. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  73534. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  73535. ** at the start of (pKey1/nKey1) fits in a single byte.
  73536. */
  73537. static int vdbeRecordCompareString(
  73538. int nKey1, const void *pKey1, /* Left key */
  73539. UnpackedRecord *pPKey2 /* Right key */
  73540. ){
  73541. const u8 *aKey1 = (const u8*)pKey1;
  73542. int serial_type;
  73543. int res;
  73544. assert( pPKey2->aMem[0].flags & MEM_Str );
  73545. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  73546. getVarint32(&aKey1[1], serial_type);
  73547. if( serial_type<12 ){
  73548. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  73549. }else if( !(serial_type & 0x01) ){
  73550. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  73551. }else{
  73552. int nCmp;
  73553. int nStr;
  73554. int szHdr = aKey1[0];
  73555. nStr = (serial_type-12) / 2;
  73556. if( (szHdr + nStr) > nKey1 ){
  73557. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  73558. return 0; /* Corruption */
  73559. }
  73560. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  73561. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  73562. if( res==0 ){
  73563. res = nStr - pPKey2->aMem[0].n;
  73564. if( res==0 ){
  73565. if( pPKey2->nField>1 ){
  73566. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  73567. }else{
  73568. res = pPKey2->default_rc;
  73569. pPKey2->eqSeen = 1;
  73570. }
  73571. }else if( res>0 ){
  73572. res = pPKey2->r2;
  73573. }else{
  73574. res = pPKey2->r1;
  73575. }
  73576. }else if( res>0 ){
  73577. res = pPKey2->r2;
  73578. }else{
  73579. res = pPKey2->r1;
  73580. }
  73581. }
  73582. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  73583. || CORRUPT_DB
  73584. || pPKey2->pKeyInfo->db->mallocFailed
  73585. );
  73586. return res;
  73587. }
  73588. /*
  73589. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  73590. ** suitable for comparing serialized records to the unpacked record passed
  73591. ** as the only argument.
  73592. */
  73593. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  73594. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  73595. ** that the size-of-header varint that occurs at the start of each record
  73596. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  73597. ** also assumes that it is safe to overread a buffer by at least the
  73598. ** maximum possible legal header size plus 8 bytes. Because there is
  73599. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  73600. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  73601. ** limit the size of the header to 64 bytes in cases where the first field
  73602. ** is an integer.
  73603. **
  73604. ** The easiest way to enforce this limit is to consider only records with
  73605. ** 13 fields or less. If the first field is an integer, the maximum legal
  73606. ** header size is (12*5 + 1 + 1) bytes. */
  73607. if( p->pKeyInfo->nAllField<=13 ){
  73608. int flags = p->aMem[0].flags;
  73609. if( p->pKeyInfo->aSortOrder[0] ){
  73610. p->r1 = 1;
  73611. p->r2 = -1;
  73612. }else{
  73613. p->r1 = -1;
  73614. p->r2 = 1;
  73615. }
  73616. if( (flags & MEM_Int) ){
  73617. return vdbeRecordCompareInt;
  73618. }
  73619. testcase( flags & MEM_Real );
  73620. testcase( flags & MEM_Null );
  73621. testcase( flags & MEM_Blob );
  73622. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  73623. assert( flags & MEM_Str );
  73624. return vdbeRecordCompareString;
  73625. }
  73626. }
  73627. return sqlite3VdbeRecordCompare;
  73628. }
  73629. /*
  73630. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  73631. ** Read the rowid (the last field in the record) and store it in *rowid.
  73632. ** Return SQLITE_OK if everything works, or an error code otherwise.
  73633. **
  73634. ** pCur might be pointing to text obtained from a corrupt database file.
  73635. ** So the content cannot be trusted. Do appropriate checks on the content.
  73636. */
  73637. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  73638. i64 nCellKey = 0;
  73639. int rc;
  73640. u32 szHdr; /* Size of the header */
  73641. u32 typeRowid; /* Serial type of the rowid */
  73642. u32 lenRowid; /* Size of the rowid */
  73643. Mem m, v;
  73644. /* Get the size of the index entry. Only indices entries of less
  73645. ** than 2GiB are support - anything large must be database corruption.
  73646. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  73647. ** this code can safely assume that nCellKey is 32-bits
  73648. */
  73649. assert( sqlite3BtreeCursorIsValid(pCur) );
  73650. nCellKey = sqlite3BtreePayloadSize(pCur);
  73651. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  73652. /* Read in the complete content of the index entry */
  73653. sqlite3VdbeMemInit(&m, db, 0);
  73654. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  73655. if( rc ){
  73656. return rc;
  73657. }
  73658. /* The index entry must begin with a header size */
  73659. (void)getVarint32((u8*)m.z, szHdr);
  73660. testcase( szHdr==3 );
  73661. testcase( szHdr==m.n );
  73662. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  73663. goto idx_rowid_corruption;
  73664. }
  73665. /* The last field of the index should be an integer - the ROWID.
  73666. ** Verify that the last entry really is an integer. */
  73667. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  73668. testcase( typeRowid==1 );
  73669. testcase( typeRowid==2 );
  73670. testcase( typeRowid==3 );
  73671. testcase( typeRowid==4 );
  73672. testcase( typeRowid==5 );
  73673. testcase( typeRowid==6 );
  73674. testcase( typeRowid==8 );
  73675. testcase( typeRowid==9 );
  73676. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  73677. goto idx_rowid_corruption;
  73678. }
  73679. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  73680. testcase( (u32)m.n==szHdr+lenRowid );
  73681. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  73682. goto idx_rowid_corruption;
  73683. }
  73684. /* Fetch the integer off the end of the index record */
  73685. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  73686. *rowid = v.u.i;
  73687. sqlite3VdbeMemRelease(&m);
  73688. return SQLITE_OK;
  73689. /* Jump here if database corruption is detected after m has been
  73690. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  73691. idx_rowid_corruption:
  73692. testcase( m.szMalloc!=0 );
  73693. sqlite3VdbeMemRelease(&m);
  73694. return SQLITE_CORRUPT_BKPT;
  73695. }
  73696. /*
  73697. ** Compare the key of the index entry that cursor pC is pointing to against
  73698. ** the key string in pUnpacked. Write into *pRes a number
  73699. ** that is negative, zero, or positive if pC is less than, equal to,
  73700. ** or greater than pUnpacked. Return SQLITE_OK on success.
  73701. **
  73702. ** pUnpacked is either created without a rowid or is truncated so that it
  73703. ** omits the rowid at the end. The rowid at the end of the index entry
  73704. ** is ignored as well. Hence, this routine only compares the prefixes
  73705. ** of the keys prior to the final rowid, not the entire key.
  73706. */
  73707. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  73708. sqlite3 *db, /* Database connection */
  73709. VdbeCursor *pC, /* The cursor to compare against */
  73710. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  73711. int *res /* Write the comparison result here */
  73712. ){
  73713. i64 nCellKey = 0;
  73714. int rc;
  73715. BtCursor *pCur;
  73716. Mem m;
  73717. assert( pC->eCurType==CURTYPE_BTREE );
  73718. pCur = pC->uc.pCursor;
  73719. assert( sqlite3BtreeCursorIsValid(pCur) );
  73720. nCellKey = sqlite3BtreePayloadSize(pCur);
  73721. /* nCellKey will always be between 0 and 0xffffffff because of the way
  73722. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  73723. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  73724. *res = 0;
  73725. return SQLITE_CORRUPT_BKPT;
  73726. }
  73727. sqlite3VdbeMemInit(&m, db, 0);
  73728. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, &m);
  73729. if( rc ){
  73730. return rc;
  73731. }
  73732. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  73733. sqlite3VdbeMemRelease(&m);
  73734. return SQLITE_OK;
  73735. }
  73736. /*
  73737. ** This routine sets the value to be returned by subsequent calls to
  73738. ** sqlite3_changes() on the database handle 'db'.
  73739. */
  73740. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  73741. assert( sqlite3_mutex_held(db->mutex) );
  73742. db->nChange = nChange;
  73743. db->nTotalChange += nChange;
  73744. }
  73745. /*
  73746. ** Set a flag in the vdbe to update the change counter when it is finalised
  73747. ** or reset.
  73748. */
  73749. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  73750. v->changeCntOn = 1;
  73751. }
  73752. /*
  73753. ** Mark every prepared statement associated with a database connection
  73754. ** as expired.
  73755. **
  73756. ** An expired statement means that recompilation of the statement is
  73757. ** recommend. Statements expire when things happen that make their
  73758. ** programs obsolete. Removing user-defined functions or collating
  73759. ** sequences, or changing an authorization function are the types of
  73760. ** things that make prepared statements obsolete.
  73761. */
  73762. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  73763. Vdbe *p;
  73764. for(p = db->pVdbe; p; p=p->pNext){
  73765. p->expired = 1;
  73766. }
  73767. }
  73768. /*
  73769. ** Return the database associated with the Vdbe.
  73770. */
  73771. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  73772. return v->db;
  73773. }
  73774. /*
  73775. ** Return the SQLITE_PREPARE flags for a Vdbe.
  73776. */
  73777. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
  73778. return v->prepFlags;
  73779. }
  73780. /*
  73781. ** Return a pointer to an sqlite3_value structure containing the value bound
  73782. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  73783. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  73784. ** constants) to the value before returning it.
  73785. **
  73786. ** The returned value must be freed by the caller using sqlite3ValueFree().
  73787. */
  73788. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  73789. assert( iVar>0 );
  73790. if( v ){
  73791. Mem *pMem = &v->aVar[iVar-1];
  73792. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  73793. if( 0==(pMem->flags & MEM_Null) ){
  73794. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  73795. if( pRet ){
  73796. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  73797. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  73798. }
  73799. return pRet;
  73800. }
  73801. }
  73802. return 0;
  73803. }
  73804. /*
  73805. ** Configure SQL variable iVar so that binding a new value to it signals
  73806. ** to sqlite3_reoptimize() that re-preparing the statement may result
  73807. ** in a better query plan.
  73808. */
  73809. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  73810. assert( iVar>0 );
  73811. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  73812. if( iVar>=32 ){
  73813. v->expmask |= 0x80000000;
  73814. }else{
  73815. v->expmask |= ((u32)1 << (iVar-1));
  73816. }
  73817. }
  73818. /*
  73819. ** Cause a function to throw an error if it was call from OP_PureFunc
  73820. ** rather than OP_Function.
  73821. **
  73822. ** OP_PureFunc means that the function must be deterministic, and should
  73823. ** throw an error if it is given inputs that would make it non-deterministic.
  73824. ** This routine is invoked by date/time functions that use non-deterministic
  73825. ** features such as 'now'.
  73826. */
  73827. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
  73828. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  73829. if( pCtx->pVdbe==0 ) return 1;
  73830. #endif
  73831. if( pCtx->pVdbe->aOp[pCtx->iOp].opcode==OP_PureFunc ){
  73832. sqlite3_result_error(pCtx,
  73833. "non-deterministic function in index expression or CHECK constraint",
  73834. -1);
  73835. return 0;
  73836. }
  73837. return 1;
  73838. }
  73839. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73840. /*
  73841. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  73842. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  73843. ** in memory obtained from sqlite3DbMalloc).
  73844. */
  73845. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  73846. if( pVtab->zErrMsg ){
  73847. sqlite3 *db = p->db;
  73848. sqlite3DbFree(db, p->zErrMsg);
  73849. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  73850. sqlite3_free(pVtab->zErrMsg);
  73851. pVtab->zErrMsg = 0;
  73852. }
  73853. }
  73854. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73855. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  73856. /*
  73857. ** If the second argument is not NULL, release any allocations associated
  73858. ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
  73859. ** structure itself, using sqlite3DbFree().
  73860. **
  73861. ** This function is used to free UnpackedRecord structures allocated by
  73862. ** the vdbeUnpackRecord() function found in vdbeapi.c.
  73863. */
  73864. static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
  73865. if( p ){
  73866. int i;
  73867. for(i=0; i<nField; i++){
  73868. Mem *pMem = &p->aMem[i];
  73869. if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
  73870. }
  73871. sqlite3DbFreeNN(db, p);
  73872. }
  73873. }
  73874. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  73875. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  73876. /*
  73877. ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
  73878. ** then cursor passed as the second argument should point to the row about
  73879. ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
  73880. ** the required value will be read from the row the cursor points to.
  73881. */
  73882. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
  73883. Vdbe *v, /* Vdbe pre-update hook is invoked by */
  73884. VdbeCursor *pCsr, /* Cursor to grab old.* values from */
  73885. int op, /* SQLITE_INSERT, UPDATE or DELETE */
  73886. const char *zDb, /* Database name */
  73887. Table *pTab, /* Modified table */
  73888. i64 iKey1, /* Initial key value */
  73889. int iReg /* Register for new.* record */
  73890. ){
  73891. sqlite3 *db = v->db;
  73892. i64 iKey2;
  73893. PreUpdate preupdate;
  73894. const char *zTbl = pTab->zName;
  73895. static const u8 fakeSortOrder = 0;
  73896. assert( db->pPreUpdate==0 );
  73897. memset(&preupdate, 0, sizeof(PreUpdate));
  73898. if( HasRowid(pTab)==0 ){
  73899. iKey1 = iKey2 = 0;
  73900. preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  73901. }else{
  73902. if( op==SQLITE_UPDATE ){
  73903. iKey2 = v->aMem[iReg].u.i;
  73904. }else{
  73905. iKey2 = iKey1;
  73906. }
  73907. }
  73908. assert( pCsr->nField==pTab->nCol
  73909. || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
  73910. );
  73911. preupdate.v = v;
  73912. preupdate.pCsr = pCsr;
  73913. preupdate.op = op;
  73914. preupdate.iNewReg = iReg;
  73915. preupdate.keyinfo.db = db;
  73916. preupdate.keyinfo.enc = ENC(db);
  73917. preupdate.keyinfo.nKeyField = pTab->nCol;
  73918. preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
  73919. preupdate.iKey1 = iKey1;
  73920. preupdate.iKey2 = iKey2;
  73921. preupdate.pTab = pTab;
  73922. db->pPreUpdate = &preupdate;
  73923. db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
  73924. db->pPreUpdate = 0;
  73925. sqlite3DbFree(db, preupdate.aRecord);
  73926. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
  73927. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
  73928. if( preupdate.aNew ){
  73929. int i;
  73930. for(i=0; i<pCsr->nField; i++){
  73931. sqlite3VdbeMemRelease(&preupdate.aNew[i]);
  73932. }
  73933. sqlite3DbFreeNN(db, preupdate.aNew);
  73934. }
  73935. }
  73936. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  73937. /************** End of vdbeaux.c *********************************************/
  73938. /************** Begin file vdbeapi.c *****************************************/
  73939. /*
  73940. ** 2004 May 26
  73941. **
  73942. ** The author disclaims copyright to this source code. In place of
  73943. ** a legal notice, here is a blessing:
  73944. **
  73945. ** May you do good and not evil.
  73946. ** May you find forgiveness for yourself and forgive others.
  73947. ** May you share freely, never taking more than you give.
  73948. **
  73949. *************************************************************************
  73950. **
  73951. ** This file contains code use to implement APIs that are part of the
  73952. ** VDBE.
  73953. */
  73954. /* #include "sqliteInt.h" */
  73955. /* #include "vdbeInt.h" */
  73956. #ifndef SQLITE_OMIT_DEPRECATED
  73957. /*
  73958. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  73959. ** to be recompiled. A statement needs to be recompiled whenever the
  73960. ** execution environment changes in a way that would alter the program
  73961. ** that sqlite3_prepare() generates. For example, if new functions or
  73962. ** collating sequences are registered or if an authorizer function is
  73963. ** added or changed.
  73964. */
  73965. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  73966. Vdbe *p = (Vdbe*)pStmt;
  73967. return p==0 || p->expired;
  73968. }
  73969. #endif
  73970. /*
  73971. ** Check on a Vdbe to make sure it has not been finalized. Log
  73972. ** an error and return true if it has been finalized (or is otherwise
  73973. ** invalid). Return false if it is ok.
  73974. */
  73975. static int vdbeSafety(Vdbe *p){
  73976. if( p->db==0 ){
  73977. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  73978. return 1;
  73979. }else{
  73980. return 0;
  73981. }
  73982. }
  73983. static int vdbeSafetyNotNull(Vdbe *p){
  73984. if( p==0 ){
  73985. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  73986. return 1;
  73987. }else{
  73988. return vdbeSafety(p);
  73989. }
  73990. }
  73991. #ifndef SQLITE_OMIT_TRACE
  73992. /*
  73993. ** Invoke the profile callback. This routine is only called if we already
  73994. ** know that the profile callback is defined and needs to be invoked.
  73995. */
  73996. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  73997. sqlite3_int64 iNow;
  73998. sqlite3_int64 iElapse;
  73999. assert( p->startTime>0 );
  74000. assert( db->xProfile!=0 || (db->mTrace & SQLITE_TRACE_PROFILE)!=0 );
  74001. assert( db->init.busy==0 );
  74002. assert( p->zSql!=0 );
  74003. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  74004. iElapse = (iNow - p->startTime)*1000000;
  74005. if( db->xProfile ){
  74006. db->xProfile(db->pProfileArg, p->zSql, iElapse);
  74007. }
  74008. if( db->mTrace & SQLITE_TRACE_PROFILE ){
  74009. db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
  74010. }
  74011. p->startTime = 0;
  74012. }
  74013. /*
  74014. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  74015. ** is needed, and it invokes the callback if it is needed.
  74016. */
  74017. # define checkProfileCallback(DB,P) \
  74018. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  74019. #else
  74020. # define checkProfileCallback(DB,P) /*no-op*/
  74021. #endif
  74022. /*
  74023. ** The following routine destroys a virtual machine that is created by
  74024. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  74025. ** success/failure code that describes the result of executing the virtual
  74026. ** machine.
  74027. **
  74028. ** This routine sets the error code and string returned by
  74029. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  74030. */
  74031. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  74032. int rc;
  74033. if( pStmt==0 ){
  74034. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  74035. ** pointer is a harmless no-op. */
  74036. rc = SQLITE_OK;
  74037. }else{
  74038. Vdbe *v = (Vdbe*)pStmt;
  74039. sqlite3 *db = v->db;
  74040. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  74041. sqlite3_mutex_enter(db->mutex);
  74042. checkProfileCallback(db, v);
  74043. rc = sqlite3VdbeFinalize(v);
  74044. rc = sqlite3ApiExit(db, rc);
  74045. sqlite3LeaveMutexAndCloseZombie(db);
  74046. }
  74047. return rc;
  74048. }
  74049. /*
  74050. ** Terminate the current execution of an SQL statement and reset it
  74051. ** back to its starting state so that it can be reused. A success code from
  74052. ** the prior execution is returned.
  74053. **
  74054. ** This routine sets the error code and string returned by
  74055. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  74056. */
  74057. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  74058. int rc;
  74059. if( pStmt==0 ){
  74060. rc = SQLITE_OK;
  74061. }else{
  74062. Vdbe *v = (Vdbe*)pStmt;
  74063. sqlite3 *db = v->db;
  74064. sqlite3_mutex_enter(db->mutex);
  74065. checkProfileCallback(db, v);
  74066. rc = sqlite3VdbeReset(v);
  74067. sqlite3VdbeRewind(v);
  74068. assert( (rc & (db->errMask))==rc );
  74069. rc = sqlite3ApiExit(db, rc);
  74070. sqlite3_mutex_leave(db->mutex);
  74071. }
  74072. return rc;
  74073. }
  74074. /*
  74075. ** Set all the parameters in the compiled SQL statement to NULL.
  74076. */
  74077. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  74078. int i;
  74079. int rc = SQLITE_OK;
  74080. Vdbe *p = (Vdbe*)pStmt;
  74081. #if SQLITE_THREADSAFE
  74082. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  74083. #endif
  74084. sqlite3_mutex_enter(mutex);
  74085. for(i=0; i<p->nVar; i++){
  74086. sqlite3VdbeMemRelease(&p->aVar[i]);
  74087. p->aVar[i].flags = MEM_Null;
  74088. }
  74089. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  74090. if( p->expmask ){
  74091. p->expired = 1;
  74092. }
  74093. sqlite3_mutex_leave(mutex);
  74094. return rc;
  74095. }
  74096. /**************************** sqlite3_value_ *******************************
  74097. ** The following routines extract information from a Mem or sqlite3_value
  74098. ** structure.
  74099. */
  74100. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  74101. Mem *p = (Mem*)pVal;
  74102. if( p->flags & (MEM_Blob|MEM_Str) ){
  74103. if( ExpandBlob(p)!=SQLITE_OK ){
  74104. assert( p->flags==MEM_Null && p->z==0 );
  74105. return 0;
  74106. }
  74107. p->flags |= MEM_Blob;
  74108. return p->n ? p->z : 0;
  74109. }else{
  74110. return sqlite3_value_text(pVal);
  74111. }
  74112. }
  74113. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  74114. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  74115. }
  74116. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  74117. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  74118. }
  74119. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  74120. return sqlite3VdbeRealValue((Mem*)pVal);
  74121. }
  74122. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  74123. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  74124. }
  74125. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  74126. return sqlite3VdbeIntValue((Mem*)pVal);
  74127. }
  74128. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
  74129. Mem *pMem = (Mem*)pVal;
  74130. return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
  74131. }
  74132. SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
  74133. Mem *p = (Mem*)pVal;
  74134. if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
  74135. (MEM_Null|MEM_Term|MEM_Subtype)
  74136. && zPType!=0
  74137. && p->eSubtype=='p'
  74138. && strcmp(p->u.zPType, zPType)==0
  74139. ){
  74140. return (void*)p->z;
  74141. }else{
  74142. return 0;
  74143. }
  74144. }
  74145. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  74146. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  74147. }
  74148. #ifndef SQLITE_OMIT_UTF16
  74149. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  74150. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  74151. }
  74152. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  74153. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  74154. }
  74155. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  74156. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  74157. }
  74158. #endif /* SQLITE_OMIT_UTF16 */
  74159. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  74160. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  74161. ** point number string BLOB NULL
  74162. */
  74163. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  74164. static const u8 aType[] = {
  74165. SQLITE_BLOB, /* 0x00 */
  74166. SQLITE_NULL, /* 0x01 */
  74167. SQLITE_TEXT, /* 0x02 */
  74168. SQLITE_NULL, /* 0x03 */
  74169. SQLITE_INTEGER, /* 0x04 */
  74170. SQLITE_NULL, /* 0x05 */
  74171. SQLITE_INTEGER, /* 0x06 */
  74172. SQLITE_NULL, /* 0x07 */
  74173. SQLITE_FLOAT, /* 0x08 */
  74174. SQLITE_NULL, /* 0x09 */
  74175. SQLITE_FLOAT, /* 0x0a */
  74176. SQLITE_NULL, /* 0x0b */
  74177. SQLITE_INTEGER, /* 0x0c */
  74178. SQLITE_NULL, /* 0x0d */
  74179. SQLITE_INTEGER, /* 0x0e */
  74180. SQLITE_NULL, /* 0x0f */
  74181. SQLITE_BLOB, /* 0x10 */
  74182. SQLITE_NULL, /* 0x11 */
  74183. SQLITE_TEXT, /* 0x12 */
  74184. SQLITE_NULL, /* 0x13 */
  74185. SQLITE_INTEGER, /* 0x14 */
  74186. SQLITE_NULL, /* 0x15 */
  74187. SQLITE_INTEGER, /* 0x16 */
  74188. SQLITE_NULL, /* 0x17 */
  74189. SQLITE_FLOAT, /* 0x18 */
  74190. SQLITE_NULL, /* 0x19 */
  74191. SQLITE_FLOAT, /* 0x1a */
  74192. SQLITE_NULL, /* 0x1b */
  74193. SQLITE_INTEGER, /* 0x1c */
  74194. SQLITE_NULL, /* 0x1d */
  74195. SQLITE_INTEGER, /* 0x1e */
  74196. SQLITE_NULL, /* 0x1f */
  74197. };
  74198. return aType[pVal->flags&MEM_AffMask];
  74199. }
  74200. /* Return true if a parameter to xUpdate represents an unchanged column */
  74201. SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){
  74202. return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
  74203. }
  74204. /* Make a copy of an sqlite3_value object
  74205. */
  74206. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
  74207. sqlite3_value *pNew;
  74208. if( pOrig==0 ) return 0;
  74209. pNew = sqlite3_malloc( sizeof(*pNew) );
  74210. if( pNew==0 ) return 0;
  74211. memset(pNew, 0, sizeof(*pNew));
  74212. memcpy(pNew, pOrig, MEMCELLSIZE);
  74213. pNew->flags &= ~MEM_Dyn;
  74214. pNew->db = 0;
  74215. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  74216. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  74217. pNew->flags |= MEM_Ephem;
  74218. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  74219. sqlite3ValueFree(pNew);
  74220. pNew = 0;
  74221. }
  74222. }
  74223. return pNew;
  74224. }
  74225. /* Destroy an sqlite3_value object previously obtained from
  74226. ** sqlite3_value_dup().
  74227. */
  74228. SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
  74229. sqlite3ValueFree(pOld);
  74230. }
  74231. /**************************** sqlite3_result_ *******************************
  74232. ** The following routines are used by user-defined functions to specify
  74233. ** the function result.
  74234. **
  74235. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  74236. ** result as a string or blob but if the string or blob is too large, it
  74237. ** then sets the error code to SQLITE_TOOBIG
  74238. **
  74239. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  74240. ** on value P is not going to be used and need to be destroyed.
  74241. */
  74242. static void setResultStrOrError(
  74243. sqlite3_context *pCtx, /* Function context */
  74244. const char *z, /* String pointer */
  74245. int n, /* Bytes in string, or negative */
  74246. u8 enc, /* Encoding of z. 0 for BLOBs */
  74247. void (*xDel)(void*) /* Destructor function */
  74248. ){
  74249. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  74250. sqlite3_result_error_toobig(pCtx);
  74251. }
  74252. }
  74253. static int invokeValueDestructor(
  74254. const void *p, /* Value to destroy */
  74255. void (*xDel)(void*), /* The destructor */
  74256. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  74257. ){
  74258. assert( xDel!=SQLITE_DYNAMIC );
  74259. if( xDel==0 ){
  74260. /* noop */
  74261. }else if( xDel==SQLITE_TRANSIENT ){
  74262. /* noop */
  74263. }else{
  74264. xDel((void*)p);
  74265. }
  74266. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  74267. return SQLITE_TOOBIG;
  74268. }
  74269. SQLITE_API void sqlite3_result_blob(
  74270. sqlite3_context *pCtx,
  74271. const void *z,
  74272. int n,
  74273. void (*xDel)(void *)
  74274. ){
  74275. assert( n>=0 );
  74276. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74277. setResultStrOrError(pCtx, z, n, 0, xDel);
  74278. }
  74279. SQLITE_API void sqlite3_result_blob64(
  74280. sqlite3_context *pCtx,
  74281. const void *z,
  74282. sqlite3_uint64 n,
  74283. void (*xDel)(void *)
  74284. ){
  74285. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74286. assert( xDel!=SQLITE_DYNAMIC );
  74287. if( n>0x7fffffff ){
  74288. (void)invokeValueDestructor(z, xDel, pCtx);
  74289. }else{
  74290. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  74291. }
  74292. }
  74293. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  74294. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74295. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  74296. }
  74297. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  74298. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74299. pCtx->isError = SQLITE_ERROR;
  74300. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  74301. }
  74302. #ifndef SQLITE_OMIT_UTF16
  74303. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  74304. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74305. pCtx->isError = SQLITE_ERROR;
  74306. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  74307. }
  74308. #endif
  74309. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  74310. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74311. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  74312. }
  74313. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  74314. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74315. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  74316. }
  74317. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  74318. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74319. sqlite3VdbeMemSetNull(pCtx->pOut);
  74320. }
  74321. SQLITE_API void sqlite3_result_pointer(
  74322. sqlite3_context *pCtx,
  74323. void *pPtr,
  74324. const char *zPType,
  74325. void (*xDestructor)(void*)
  74326. ){
  74327. Mem *pOut = pCtx->pOut;
  74328. assert( sqlite3_mutex_held(pOut->db->mutex) );
  74329. sqlite3VdbeMemRelease(pOut);
  74330. pOut->flags = MEM_Null;
  74331. sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
  74332. }
  74333. SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  74334. Mem *pOut = pCtx->pOut;
  74335. assert( sqlite3_mutex_held(pOut->db->mutex) );
  74336. pOut->eSubtype = eSubtype & 0xff;
  74337. pOut->flags |= MEM_Subtype;
  74338. }
  74339. SQLITE_API void sqlite3_result_text(
  74340. sqlite3_context *pCtx,
  74341. const char *z,
  74342. int n,
  74343. void (*xDel)(void *)
  74344. ){
  74345. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74346. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  74347. }
  74348. SQLITE_API void sqlite3_result_text64(
  74349. sqlite3_context *pCtx,
  74350. const char *z,
  74351. sqlite3_uint64 n,
  74352. void (*xDel)(void *),
  74353. unsigned char enc
  74354. ){
  74355. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74356. assert( xDel!=SQLITE_DYNAMIC );
  74357. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  74358. if( n>0x7fffffff ){
  74359. (void)invokeValueDestructor(z, xDel, pCtx);
  74360. }else{
  74361. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  74362. }
  74363. }
  74364. #ifndef SQLITE_OMIT_UTF16
  74365. SQLITE_API void sqlite3_result_text16(
  74366. sqlite3_context *pCtx,
  74367. const void *z,
  74368. int n,
  74369. void (*xDel)(void *)
  74370. ){
  74371. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74372. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  74373. }
  74374. SQLITE_API void sqlite3_result_text16be(
  74375. sqlite3_context *pCtx,
  74376. const void *z,
  74377. int n,
  74378. void (*xDel)(void *)
  74379. ){
  74380. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74381. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  74382. }
  74383. SQLITE_API void sqlite3_result_text16le(
  74384. sqlite3_context *pCtx,
  74385. const void *z,
  74386. int n,
  74387. void (*xDel)(void *)
  74388. ){
  74389. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74390. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  74391. }
  74392. #endif /* SQLITE_OMIT_UTF16 */
  74393. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  74394. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74395. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  74396. }
  74397. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  74398. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74399. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  74400. }
  74401. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  74402. Mem *pOut = pCtx->pOut;
  74403. assert( sqlite3_mutex_held(pOut->db->mutex) );
  74404. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  74405. return SQLITE_TOOBIG;
  74406. }
  74407. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  74408. return SQLITE_OK;
  74409. }
  74410. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  74411. pCtx->isError = errCode ? errCode : -1;
  74412. #ifdef SQLITE_DEBUG
  74413. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  74414. #endif
  74415. if( pCtx->pOut->flags & MEM_Null ){
  74416. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  74417. SQLITE_UTF8, SQLITE_STATIC);
  74418. }
  74419. }
  74420. /* Force an SQLITE_TOOBIG error. */
  74421. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  74422. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74423. pCtx->isError = SQLITE_TOOBIG;
  74424. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  74425. SQLITE_UTF8, SQLITE_STATIC);
  74426. }
  74427. /* An SQLITE_NOMEM error. */
  74428. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  74429. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74430. sqlite3VdbeMemSetNull(pCtx->pOut);
  74431. pCtx->isError = SQLITE_NOMEM_BKPT;
  74432. sqlite3OomFault(pCtx->pOut->db);
  74433. }
  74434. /*
  74435. ** This function is called after a transaction has been committed. It
  74436. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  74437. */
  74438. static int doWalCallbacks(sqlite3 *db){
  74439. int rc = SQLITE_OK;
  74440. #ifndef SQLITE_OMIT_WAL
  74441. int i;
  74442. for(i=0; i<db->nDb; i++){
  74443. Btree *pBt = db->aDb[i].pBt;
  74444. if( pBt ){
  74445. int nEntry;
  74446. sqlite3BtreeEnter(pBt);
  74447. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  74448. sqlite3BtreeLeave(pBt);
  74449. if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
  74450. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
  74451. }
  74452. }
  74453. }
  74454. #endif
  74455. return rc;
  74456. }
  74457. /*
  74458. ** Execute the statement pStmt, either until a row of data is ready, the
  74459. ** statement is completely executed or an error occurs.
  74460. **
  74461. ** This routine implements the bulk of the logic behind the sqlite_step()
  74462. ** API. The only thing omitted is the automatic recompile if a
  74463. ** schema change has occurred. That detail is handled by the
  74464. ** outer sqlite3_step() wrapper procedure.
  74465. */
  74466. static int sqlite3Step(Vdbe *p){
  74467. sqlite3 *db;
  74468. int rc;
  74469. assert(p);
  74470. if( p->magic!=VDBE_MAGIC_RUN ){
  74471. /* We used to require that sqlite3_reset() be called before retrying
  74472. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  74473. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  74474. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  74475. ** This "automatic-reset" change is not technically an incompatibility,
  74476. ** since any application that receives an SQLITE_MISUSE is broken by
  74477. ** definition.
  74478. **
  74479. ** Nevertheless, some published applications that were originally written
  74480. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  74481. ** returns, and those were broken by the automatic-reset change. As a
  74482. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  74483. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  74484. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  74485. ** or SQLITE_BUSY error.
  74486. */
  74487. #ifdef SQLITE_OMIT_AUTORESET
  74488. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  74489. sqlite3_reset((sqlite3_stmt*)p);
  74490. }else{
  74491. return SQLITE_MISUSE_BKPT;
  74492. }
  74493. #else
  74494. sqlite3_reset((sqlite3_stmt*)p);
  74495. #endif
  74496. }
  74497. /* Check that malloc() has not failed. If it has, return early. */
  74498. db = p->db;
  74499. if( db->mallocFailed ){
  74500. p->rc = SQLITE_NOMEM;
  74501. return SQLITE_NOMEM_BKPT;
  74502. }
  74503. if( p->pc<=0 && p->expired ){
  74504. p->rc = SQLITE_SCHEMA;
  74505. rc = SQLITE_ERROR;
  74506. goto end_of_step;
  74507. }
  74508. if( p->pc<0 ){
  74509. /* If there are no other statements currently running, then
  74510. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  74511. ** from interrupting a statement that has not yet started.
  74512. */
  74513. if( db->nVdbeActive==0 ){
  74514. db->u1.isInterrupted = 0;
  74515. }
  74516. assert( db->nVdbeWrite>0 || db->autoCommit==0
  74517. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  74518. );
  74519. #ifndef SQLITE_OMIT_TRACE
  74520. if( (db->xProfile || (db->mTrace & SQLITE_TRACE_PROFILE)!=0)
  74521. && !db->init.busy && p->zSql ){
  74522. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  74523. }else{
  74524. assert( p->startTime==0 );
  74525. }
  74526. #endif
  74527. db->nVdbeActive++;
  74528. if( p->readOnly==0 ) db->nVdbeWrite++;
  74529. if( p->bIsReader ) db->nVdbeRead++;
  74530. p->pc = 0;
  74531. }
  74532. #ifdef SQLITE_DEBUG
  74533. p->rcApp = SQLITE_OK;
  74534. #endif
  74535. #ifndef SQLITE_OMIT_EXPLAIN
  74536. if( p->explain ){
  74537. rc = sqlite3VdbeList(p);
  74538. }else
  74539. #endif /* SQLITE_OMIT_EXPLAIN */
  74540. {
  74541. db->nVdbeExec++;
  74542. rc = sqlite3VdbeExec(p);
  74543. db->nVdbeExec--;
  74544. }
  74545. #ifndef SQLITE_OMIT_TRACE
  74546. /* If the statement completed successfully, invoke the profile callback */
  74547. if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
  74548. #endif
  74549. if( rc==SQLITE_DONE && db->autoCommit ){
  74550. assert( p->rc==SQLITE_OK );
  74551. p->rc = doWalCallbacks(db);
  74552. if( p->rc!=SQLITE_OK ){
  74553. rc = SQLITE_ERROR;
  74554. }
  74555. }
  74556. db->errCode = rc;
  74557. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  74558. p->rc = SQLITE_NOMEM_BKPT;
  74559. }
  74560. end_of_step:
  74561. /* At this point local variable rc holds the value that should be
  74562. ** returned if this statement was compiled using the legacy
  74563. ** sqlite3_prepare() interface. According to the docs, this can only
  74564. ** be one of the values in the first assert() below. Variable p->rc
  74565. ** contains the value that would be returned if sqlite3_finalize()
  74566. ** were called on statement p.
  74567. */
  74568. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  74569. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  74570. );
  74571. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  74572. if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
  74573. && rc!=SQLITE_ROW
  74574. && rc!=SQLITE_DONE
  74575. ){
  74576. /* If this statement was prepared using saved SQL and an
  74577. ** error has occurred, then return the error code in p->rc to the
  74578. ** caller. Set the error code in the database handle to the same value.
  74579. */
  74580. rc = sqlite3VdbeTransferError(p);
  74581. }
  74582. return (rc&db->errMask);
  74583. }
  74584. /*
  74585. ** This is the top-level implementation of sqlite3_step(). Call
  74586. ** sqlite3Step() to do most of the work. If a schema error occurs,
  74587. ** call sqlite3Reprepare() and try again.
  74588. */
  74589. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  74590. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  74591. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  74592. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  74593. sqlite3 *db; /* The database connection */
  74594. if( vdbeSafetyNotNull(v) ){
  74595. return SQLITE_MISUSE_BKPT;
  74596. }
  74597. db = v->db;
  74598. sqlite3_mutex_enter(db->mutex);
  74599. v->doingRerun = 0;
  74600. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  74601. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  74602. int savedPc = v->pc;
  74603. rc = sqlite3Reprepare(v);
  74604. if( rc!=SQLITE_OK ){
  74605. /* This case occurs after failing to recompile an sql statement.
  74606. ** The error message from the SQL compiler has already been loaded
  74607. ** into the database handle. This block copies the error message
  74608. ** from the database handle into the statement and sets the statement
  74609. ** program counter to 0 to ensure that when the statement is
  74610. ** finalized or reset the parser error message is available via
  74611. ** sqlite3_errmsg() and sqlite3_errcode().
  74612. */
  74613. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  74614. sqlite3DbFree(db, v->zErrMsg);
  74615. if( !db->mallocFailed ){
  74616. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  74617. v->rc = rc = sqlite3ApiExit(db, rc);
  74618. } else {
  74619. v->zErrMsg = 0;
  74620. v->rc = rc = SQLITE_NOMEM_BKPT;
  74621. }
  74622. break;
  74623. }
  74624. sqlite3_reset(pStmt);
  74625. if( savedPc>=0 ) v->doingRerun = 1;
  74626. assert( v->expired==0 );
  74627. }
  74628. sqlite3_mutex_leave(db->mutex);
  74629. return rc;
  74630. }
  74631. /*
  74632. ** Extract the user data from a sqlite3_context structure and return a
  74633. ** pointer to it.
  74634. */
  74635. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  74636. assert( p && p->pFunc );
  74637. return p->pFunc->pUserData;
  74638. }
  74639. /*
  74640. ** Extract the user data from a sqlite3_context structure and return a
  74641. ** pointer to it.
  74642. **
  74643. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  74644. ** returns a copy of the pointer to the database connection (the 1st
  74645. ** parameter) of the sqlite3_create_function() and
  74646. ** sqlite3_create_function16() routines that originally registered the
  74647. ** application defined function.
  74648. */
  74649. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  74650. assert( p && p->pOut );
  74651. return p->pOut->db;
  74652. }
  74653. /*
  74654. ** If this routine is invoked from within an xColumn method of a virtual
  74655. ** table, then it returns true if and only if the the call is during an
  74656. ** UPDATE operation and the value of the column will not be modified
  74657. ** by the UPDATE.
  74658. **
  74659. ** If this routine is called from any context other than within the
  74660. ** xColumn method of a virtual table, then the return value is meaningless
  74661. ** and arbitrary.
  74662. **
  74663. ** Virtual table implements might use this routine to optimize their
  74664. ** performance by substituting a NULL result, or some other light-weight
  74665. ** value, as a signal to the xUpdate routine that the column is unchanged.
  74666. */
  74667. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
  74668. assert( p );
  74669. return sqlite3_value_nochange(p->pOut);
  74670. }
  74671. /*
  74672. ** Return the current time for a statement. If the current time
  74673. ** is requested more than once within the same run of a single prepared
  74674. ** statement, the exact same time is returned for each invocation regardless
  74675. ** of the amount of time that elapses between invocations. In other words,
  74676. ** the time returned is always the time of the first call.
  74677. */
  74678. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  74679. int rc;
  74680. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  74681. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  74682. assert( p->pVdbe!=0 );
  74683. #else
  74684. sqlite3_int64 iTime = 0;
  74685. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  74686. #endif
  74687. if( *piTime==0 ){
  74688. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  74689. if( rc ) *piTime = 0;
  74690. }
  74691. return *piTime;
  74692. }
  74693. /*
  74694. ** The following is the implementation of an SQL function that always
  74695. ** fails with an error message stating that the function is used in the
  74696. ** wrong context. The sqlite3_overload_function() API might construct
  74697. ** SQL function that use this routine so that the functions will exist
  74698. ** for name resolution but are actually overloaded by the xFindFunction
  74699. ** method of virtual tables.
  74700. */
  74701. SQLITE_PRIVATE void sqlite3InvalidFunction(
  74702. sqlite3_context *context, /* The function calling context */
  74703. int NotUsed, /* Number of arguments to the function */
  74704. sqlite3_value **NotUsed2 /* Value of each argument */
  74705. ){
  74706. const char *zName = context->pFunc->zName;
  74707. char *zErr;
  74708. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  74709. zErr = sqlite3_mprintf(
  74710. "unable to use function %s in the requested context", zName);
  74711. sqlite3_result_error(context, zErr, -1);
  74712. sqlite3_free(zErr);
  74713. }
  74714. /*
  74715. ** Create a new aggregate context for p and return a pointer to
  74716. ** its pMem->z element.
  74717. */
  74718. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  74719. Mem *pMem = p->pMem;
  74720. assert( (pMem->flags & MEM_Agg)==0 );
  74721. if( nByte<=0 ){
  74722. sqlite3VdbeMemSetNull(pMem);
  74723. pMem->z = 0;
  74724. }else{
  74725. sqlite3VdbeMemClearAndResize(pMem, nByte);
  74726. pMem->flags = MEM_Agg;
  74727. pMem->u.pDef = p->pFunc;
  74728. if( pMem->z ){
  74729. memset(pMem->z, 0, nByte);
  74730. }
  74731. }
  74732. return (void*)pMem->z;
  74733. }
  74734. /*
  74735. ** Allocate or return the aggregate context for a user function. A new
  74736. ** context is allocated on the first call. Subsequent calls return the
  74737. ** same context that was returned on prior calls.
  74738. */
  74739. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  74740. assert( p && p->pFunc && p->pFunc->xFinalize );
  74741. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  74742. testcase( nByte<0 );
  74743. if( (p->pMem->flags & MEM_Agg)==0 ){
  74744. return createAggContext(p, nByte);
  74745. }else{
  74746. return (void*)p->pMem->z;
  74747. }
  74748. }
  74749. /*
  74750. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  74751. ** the user-function defined by pCtx.
  74752. **
  74753. ** The left-most argument is 0.
  74754. **
  74755. ** Undocumented behavior: If iArg is negative then access a cache of
  74756. ** auxiliary data pointers that is available to all functions within a
  74757. ** single prepared statement. The iArg values must match.
  74758. */
  74759. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  74760. AuxData *pAuxData;
  74761. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74762. #if SQLITE_ENABLE_STAT3_OR_STAT4
  74763. if( pCtx->pVdbe==0 ) return 0;
  74764. #else
  74765. assert( pCtx->pVdbe!=0 );
  74766. #endif
  74767. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  74768. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  74769. return pAuxData->pAux;
  74770. }
  74771. }
  74772. return 0;
  74773. }
  74774. /*
  74775. ** Set the auxiliary data pointer and delete function, for the iArg'th
  74776. ** argument to the user-function defined by pCtx. Any previous value is
  74777. ** deleted by calling the delete function specified when it was set.
  74778. **
  74779. ** The left-most argument is 0.
  74780. **
  74781. ** Undocumented behavior: If iArg is negative then make the data available
  74782. ** to all functions within the current prepared statement using iArg as an
  74783. ** access code.
  74784. */
  74785. SQLITE_API void sqlite3_set_auxdata(
  74786. sqlite3_context *pCtx,
  74787. int iArg,
  74788. void *pAux,
  74789. void (*xDelete)(void*)
  74790. ){
  74791. AuxData *pAuxData;
  74792. Vdbe *pVdbe = pCtx->pVdbe;
  74793. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  74794. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  74795. if( pVdbe==0 ) goto failed;
  74796. #else
  74797. assert( pVdbe!=0 );
  74798. #endif
  74799. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  74800. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  74801. break;
  74802. }
  74803. }
  74804. if( pAuxData==0 ){
  74805. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  74806. if( !pAuxData ) goto failed;
  74807. pAuxData->iAuxOp = pCtx->iOp;
  74808. pAuxData->iAuxArg = iArg;
  74809. pAuxData->pNextAux = pVdbe->pAuxData;
  74810. pVdbe->pAuxData = pAuxData;
  74811. if( pCtx->isError==0 ) pCtx->isError = -1;
  74812. }else if( pAuxData->xDeleteAux ){
  74813. pAuxData->xDeleteAux(pAuxData->pAux);
  74814. }
  74815. pAuxData->pAux = pAux;
  74816. pAuxData->xDeleteAux = xDelete;
  74817. return;
  74818. failed:
  74819. if( xDelete ){
  74820. xDelete(pAux);
  74821. }
  74822. }
  74823. #ifndef SQLITE_OMIT_DEPRECATED
  74824. /*
  74825. ** Return the number of times the Step function of an aggregate has been
  74826. ** called.
  74827. **
  74828. ** This function is deprecated. Do not use it for new code. It is
  74829. ** provide only to avoid breaking legacy code. New aggregate function
  74830. ** implementations should keep their own counts within their aggregate
  74831. ** context.
  74832. */
  74833. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  74834. assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
  74835. return p->pMem->n;
  74836. }
  74837. #endif
  74838. /*
  74839. ** Return the number of columns in the result set for the statement pStmt.
  74840. */
  74841. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  74842. Vdbe *pVm = (Vdbe *)pStmt;
  74843. return pVm ? pVm->nResColumn : 0;
  74844. }
  74845. /*
  74846. ** Return the number of values available from the current row of the
  74847. ** currently executing statement pStmt.
  74848. */
  74849. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  74850. Vdbe *pVm = (Vdbe *)pStmt;
  74851. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  74852. return pVm->nResColumn;
  74853. }
  74854. /*
  74855. ** Return a pointer to static memory containing an SQL NULL value.
  74856. */
  74857. static const Mem *columnNullValue(void){
  74858. /* Even though the Mem structure contains an element
  74859. ** of type i64, on certain architectures (x86) with certain compiler
  74860. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  74861. ** instead of an 8-byte one. This all works fine, except that when
  74862. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  74863. ** that a Mem structure is located on an 8-byte boundary. To prevent
  74864. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  74865. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  74866. ** __attribute__((aligned(8))) macro. */
  74867. static const Mem nullMem
  74868. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  74869. __attribute__((aligned(8)))
  74870. #endif
  74871. = {
  74872. /* .u = */ {0},
  74873. /* .flags = */ (u16)MEM_Null,
  74874. /* .enc = */ (u8)0,
  74875. /* .eSubtype = */ (u8)0,
  74876. /* .n = */ (int)0,
  74877. /* .z = */ (char*)0,
  74878. /* .zMalloc = */ (char*)0,
  74879. /* .szMalloc = */ (int)0,
  74880. /* .uTemp = */ (u32)0,
  74881. /* .db = */ (sqlite3*)0,
  74882. /* .xDel = */ (void(*)(void*))0,
  74883. #ifdef SQLITE_DEBUG
  74884. /* .pScopyFrom = */ (Mem*)0,
  74885. /* .pFiller = */ (void*)0,
  74886. #endif
  74887. };
  74888. return &nullMem;
  74889. }
  74890. /*
  74891. ** Check to see if column iCol of the given statement is valid. If
  74892. ** it is, return a pointer to the Mem for the value of that column.
  74893. ** If iCol is not valid, return a pointer to a Mem which has a value
  74894. ** of NULL.
  74895. */
  74896. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  74897. Vdbe *pVm;
  74898. Mem *pOut;
  74899. pVm = (Vdbe *)pStmt;
  74900. if( pVm==0 ) return (Mem*)columnNullValue();
  74901. assert( pVm->db );
  74902. sqlite3_mutex_enter(pVm->db->mutex);
  74903. if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  74904. pOut = &pVm->pResultSet[i];
  74905. }else{
  74906. sqlite3Error(pVm->db, SQLITE_RANGE);
  74907. pOut = (Mem*)columnNullValue();
  74908. }
  74909. return pOut;
  74910. }
  74911. /*
  74912. ** This function is called after invoking an sqlite3_value_XXX function on a
  74913. ** column value (i.e. a value returned by evaluating an SQL expression in the
  74914. ** select list of a SELECT statement) that may cause a malloc() failure. If
  74915. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  74916. ** code of statement pStmt set to SQLITE_NOMEM.
  74917. **
  74918. ** Specifically, this is called from within:
  74919. **
  74920. ** sqlite3_column_int()
  74921. ** sqlite3_column_int64()
  74922. ** sqlite3_column_text()
  74923. ** sqlite3_column_text16()
  74924. ** sqlite3_column_real()
  74925. ** sqlite3_column_bytes()
  74926. ** sqlite3_column_bytes16()
  74927. ** sqiite3_column_blob()
  74928. */
  74929. static void columnMallocFailure(sqlite3_stmt *pStmt)
  74930. {
  74931. /* If malloc() failed during an encoding conversion within an
  74932. ** sqlite3_column_XXX API, then set the return code of the statement to
  74933. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  74934. ** and _finalize() will return NOMEM.
  74935. */
  74936. Vdbe *p = (Vdbe *)pStmt;
  74937. if( p ){
  74938. assert( p->db!=0 );
  74939. assert( sqlite3_mutex_held(p->db->mutex) );
  74940. p->rc = sqlite3ApiExit(p->db, p->rc);
  74941. sqlite3_mutex_leave(p->db->mutex);
  74942. }
  74943. }
  74944. /**************************** sqlite3_column_ *******************************
  74945. ** The following routines are used to access elements of the current row
  74946. ** in the result set.
  74947. */
  74948. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  74949. const void *val;
  74950. val = sqlite3_value_blob( columnMem(pStmt,i) );
  74951. /* Even though there is no encoding conversion, value_blob() might
  74952. ** need to call malloc() to expand the result of a zeroblob()
  74953. ** expression.
  74954. */
  74955. columnMallocFailure(pStmt);
  74956. return val;
  74957. }
  74958. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  74959. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  74960. columnMallocFailure(pStmt);
  74961. return val;
  74962. }
  74963. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  74964. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  74965. columnMallocFailure(pStmt);
  74966. return val;
  74967. }
  74968. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  74969. double val = sqlite3_value_double( columnMem(pStmt,i) );
  74970. columnMallocFailure(pStmt);
  74971. return val;
  74972. }
  74973. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  74974. int val = sqlite3_value_int( columnMem(pStmt,i) );
  74975. columnMallocFailure(pStmt);
  74976. return val;
  74977. }
  74978. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  74979. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  74980. columnMallocFailure(pStmt);
  74981. return val;
  74982. }
  74983. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  74984. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  74985. columnMallocFailure(pStmt);
  74986. return val;
  74987. }
  74988. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  74989. Mem *pOut = columnMem(pStmt, i);
  74990. if( pOut->flags&MEM_Static ){
  74991. pOut->flags &= ~MEM_Static;
  74992. pOut->flags |= MEM_Ephem;
  74993. }
  74994. columnMallocFailure(pStmt);
  74995. return (sqlite3_value *)pOut;
  74996. }
  74997. #ifndef SQLITE_OMIT_UTF16
  74998. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  74999. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  75000. columnMallocFailure(pStmt);
  75001. return val;
  75002. }
  75003. #endif /* SQLITE_OMIT_UTF16 */
  75004. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  75005. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  75006. columnMallocFailure(pStmt);
  75007. return iType;
  75008. }
  75009. /*
  75010. ** Convert the N-th element of pStmt->pColName[] into a string using
  75011. ** xFunc() then return that string. If N is out of range, return 0.
  75012. **
  75013. ** There are up to 5 names for each column. useType determines which
  75014. ** name is returned. Here are the names:
  75015. **
  75016. ** 0 The column name as it should be displayed for output
  75017. ** 1 The datatype name for the column
  75018. ** 2 The name of the database that the column derives from
  75019. ** 3 The name of the table that the column derives from
  75020. ** 4 The name of the table column that the result column derives from
  75021. **
  75022. ** If the result is not a simple column reference (if it is an expression
  75023. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  75024. */
  75025. static const void *columnName(
  75026. sqlite3_stmt *pStmt,
  75027. int N,
  75028. const void *(*xFunc)(Mem*),
  75029. int useType
  75030. ){
  75031. const void *ret;
  75032. Vdbe *p;
  75033. int n;
  75034. sqlite3 *db;
  75035. #ifdef SQLITE_ENABLE_API_ARMOR
  75036. if( pStmt==0 ){
  75037. (void)SQLITE_MISUSE_BKPT;
  75038. return 0;
  75039. }
  75040. #endif
  75041. ret = 0;
  75042. p = (Vdbe *)pStmt;
  75043. db = p->db;
  75044. assert( db!=0 );
  75045. n = sqlite3_column_count(pStmt);
  75046. if( N<n && N>=0 ){
  75047. N += useType*n;
  75048. sqlite3_mutex_enter(db->mutex);
  75049. assert( db->mallocFailed==0 );
  75050. ret = xFunc(&p->aColName[N]);
  75051. /* A malloc may have failed inside of the xFunc() call. If this
  75052. ** is the case, clear the mallocFailed flag and return NULL.
  75053. */
  75054. if( db->mallocFailed ){
  75055. sqlite3OomClear(db);
  75056. ret = 0;
  75057. }
  75058. sqlite3_mutex_leave(db->mutex);
  75059. }
  75060. return ret;
  75061. }
  75062. /*
  75063. ** Return the name of the Nth column of the result set returned by SQL
  75064. ** statement pStmt.
  75065. */
  75066. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  75067. return columnName(
  75068. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  75069. }
  75070. #ifndef SQLITE_OMIT_UTF16
  75071. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  75072. return columnName(
  75073. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  75074. }
  75075. #endif
  75076. /*
  75077. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  75078. ** not define OMIT_DECLTYPE.
  75079. */
  75080. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  75081. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  75082. and SQLITE_ENABLE_COLUMN_METADATA"
  75083. #endif
  75084. #ifndef SQLITE_OMIT_DECLTYPE
  75085. /*
  75086. ** Return the column declaration type (if applicable) of the 'i'th column
  75087. ** of the result set of SQL statement pStmt.
  75088. */
  75089. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  75090. return columnName(
  75091. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  75092. }
  75093. #ifndef SQLITE_OMIT_UTF16
  75094. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  75095. return columnName(
  75096. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  75097. }
  75098. #endif /* SQLITE_OMIT_UTF16 */
  75099. #endif /* SQLITE_OMIT_DECLTYPE */
  75100. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  75101. /*
  75102. ** Return the name of the database from which a result column derives.
  75103. ** NULL is returned if the result column is an expression or constant or
  75104. ** anything else which is not an unambiguous reference to a database column.
  75105. */
  75106. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  75107. return columnName(
  75108. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  75109. }
  75110. #ifndef SQLITE_OMIT_UTF16
  75111. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  75112. return columnName(
  75113. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  75114. }
  75115. #endif /* SQLITE_OMIT_UTF16 */
  75116. /*
  75117. ** Return the name of the table from which a result column derives.
  75118. ** NULL is returned if the result column is an expression or constant or
  75119. ** anything else which is not an unambiguous reference to a database column.
  75120. */
  75121. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  75122. return columnName(
  75123. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  75124. }
  75125. #ifndef SQLITE_OMIT_UTF16
  75126. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  75127. return columnName(
  75128. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  75129. }
  75130. #endif /* SQLITE_OMIT_UTF16 */
  75131. /*
  75132. ** Return the name of the table column from which a result column derives.
  75133. ** NULL is returned if the result column is an expression or constant or
  75134. ** anything else which is not an unambiguous reference to a database column.
  75135. */
  75136. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  75137. return columnName(
  75138. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  75139. }
  75140. #ifndef SQLITE_OMIT_UTF16
  75141. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  75142. return columnName(
  75143. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  75144. }
  75145. #endif /* SQLITE_OMIT_UTF16 */
  75146. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  75147. /******************************* sqlite3_bind_ ***************************
  75148. **
  75149. ** Routines used to attach values to wildcards in a compiled SQL statement.
  75150. */
  75151. /*
  75152. ** Unbind the value bound to variable i in virtual machine p. This is the
  75153. ** the same as binding a NULL value to the column. If the "i" parameter is
  75154. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  75155. **
  75156. ** A successful evaluation of this routine acquires the mutex on p.
  75157. ** the mutex is released if any kind of error occurs.
  75158. **
  75159. ** The error code stored in database p->db is overwritten with the return
  75160. ** value in any case.
  75161. */
  75162. static int vdbeUnbind(Vdbe *p, int i){
  75163. Mem *pVar;
  75164. if( vdbeSafetyNotNull(p) ){
  75165. return SQLITE_MISUSE_BKPT;
  75166. }
  75167. sqlite3_mutex_enter(p->db->mutex);
  75168. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  75169. sqlite3Error(p->db, SQLITE_MISUSE);
  75170. sqlite3_mutex_leave(p->db->mutex);
  75171. sqlite3_log(SQLITE_MISUSE,
  75172. "bind on a busy prepared statement: [%s]", p->zSql);
  75173. return SQLITE_MISUSE_BKPT;
  75174. }
  75175. if( i<1 || i>p->nVar ){
  75176. sqlite3Error(p->db, SQLITE_RANGE);
  75177. sqlite3_mutex_leave(p->db->mutex);
  75178. return SQLITE_RANGE;
  75179. }
  75180. i--;
  75181. pVar = &p->aVar[i];
  75182. sqlite3VdbeMemRelease(pVar);
  75183. pVar->flags = MEM_Null;
  75184. sqlite3Error(p->db, SQLITE_OK);
  75185. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  75186. ** binding a new value to this variable invalidates the current query plan.
  75187. **
  75188. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  75189. ** parameter in the WHERE clause might influence the choice of query plan
  75190. ** for a statement, then the statement will be automatically recompiled,
  75191. ** as if there had been a schema change, on the first sqlite3_step() call
  75192. ** following any change to the bindings of that parameter.
  75193. */
  75194. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  75195. if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
  75196. p->expired = 1;
  75197. }
  75198. return SQLITE_OK;
  75199. }
  75200. /*
  75201. ** Bind a text or BLOB value.
  75202. */
  75203. static int bindText(
  75204. sqlite3_stmt *pStmt, /* The statement to bind against */
  75205. int i, /* Index of the parameter to bind */
  75206. const void *zData, /* Pointer to the data to be bound */
  75207. int nData, /* Number of bytes of data to be bound */
  75208. void (*xDel)(void*), /* Destructor for the data */
  75209. u8 encoding /* Encoding for the data */
  75210. ){
  75211. Vdbe *p = (Vdbe *)pStmt;
  75212. Mem *pVar;
  75213. int rc;
  75214. rc = vdbeUnbind(p, i);
  75215. if( rc==SQLITE_OK ){
  75216. if( zData!=0 ){
  75217. pVar = &p->aVar[i-1];
  75218. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  75219. if( rc==SQLITE_OK && encoding!=0 ){
  75220. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  75221. }
  75222. if( rc ){
  75223. sqlite3Error(p->db, rc);
  75224. rc = sqlite3ApiExit(p->db, rc);
  75225. }
  75226. }
  75227. sqlite3_mutex_leave(p->db->mutex);
  75228. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  75229. xDel((void*)zData);
  75230. }
  75231. return rc;
  75232. }
  75233. /*
  75234. ** Bind a blob value to an SQL statement variable.
  75235. */
  75236. SQLITE_API int sqlite3_bind_blob(
  75237. sqlite3_stmt *pStmt,
  75238. int i,
  75239. const void *zData,
  75240. int nData,
  75241. void (*xDel)(void*)
  75242. ){
  75243. #ifdef SQLITE_ENABLE_API_ARMOR
  75244. if( nData<0 ) return SQLITE_MISUSE_BKPT;
  75245. #endif
  75246. return bindText(pStmt, i, zData, nData, xDel, 0);
  75247. }
  75248. SQLITE_API int sqlite3_bind_blob64(
  75249. sqlite3_stmt *pStmt,
  75250. int i,
  75251. const void *zData,
  75252. sqlite3_uint64 nData,
  75253. void (*xDel)(void*)
  75254. ){
  75255. assert( xDel!=SQLITE_DYNAMIC );
  75256. if( nData>0x7fffffff ){
  75257. return invokeValueDestructor(zData, xDel, 0);
  75258. }else{
  75259. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  75260. }
  75261. }
  75262. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  75263. int rc;
  75264. Vdbe *p = (Vdbe *)pStmt;
  75265. rc = vdbeUnbind(p, i);
  75266. if( rc==SQLITE_OK ){
  75267. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  75268. sqlite3_mutex_leave(p->db->mutex);
  75269. }
  75270. return rc;
  75271. }
  75272. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  75273. return sqlite3_bind_int64(p, i, (i64)iValue);
  75274. }
  75275. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  75276. int rc;
  75277. Vdbe *p = (Vdbe *)pStmt;
  75278. rc = vdbeUnbind(p, i);
  75279. if( rc==SQLITE_OK ){
  75280. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  75281. sqlite3_mutex_leave(p->db->mutex);
  75282. }
  75283. return rc;
  75284. }
  75285. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  75286. int rc;
  75287. Vdbe *p = (Vdbe*)pStmt;
  75288. rc = vdbeUnbind(p, i);
  75289. if( rc==SQLITE_OK ){
  75290. sqlite3_mutex_leave(p->db->mutex);
  75291. }
  75292. return rc;
  75293. }
  75294. SQLITE_API int sqlite3_bind_pointer(
  75295. sqlite3_stmt *pStmt,
  75296. int i,
  75297. void *pPtr,
  75298. const char *zPTtype,
  75299. void (*xDestructor)(void*)
  75300. ){
  75301. int rc;
  75302. Vdbe *p = (Vdbe*)pStmt;
  75303. rc = vdbeUnbind(p, i);
  75304. if( rc==SQLITE_OK ){
  75305. sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
  75306. sqlite3_mutex_leave(p->db->mutex);
  75307. }else if( xDestructor ){
  75308. xDestructor(pPtr);
  75309. }
  75310. return rc;
  75311. }
  75312. SQLITE_API int sqlite3_bind_text(
  75313. sqlite3_stmt *pStmt,
  75314. int i,
  75315. const char *zData,
  75316. int nData,
  75317. void (*xDel)(void*)
  75318. ){
  75319. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  75320. }
  75321. SQLITE_API int sqlite3_bind_text64(
  75322. sqlite3_stmt *pStmt,
  75323. int i,
  75324. const char *zData,
  75325. sqlite3_uint64 nData,
  75326. void (*xDel)(void*),
  75327. unsigned char enc
  75328. ){
  75329. assert( xDel!=SQLITE_DYNAMIC );
  75330. if( nData>0x7fffffff ){
  75331. return invokeValueDestructor(zData, xDel, 0);
  75332. }else{
  75333. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  75334. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  75335. }
  75336. }
  75337. #ifndef SQLITE_OMIT_UTF16
  75338. SQLITE_API int sqlite3_bind_text16(
  75339. sqlite3_stmt *pStmt,
  75340. int i,
  75341. const void *zData,
  75342. int nData,
  75343. void (*xDel)(void*)
  75344. ){
  75345. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  75346. }
  75347. #endif /* SQLITE_OMIT_UTF16 */
  75348. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  75349. int rc;
  75350. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  75351. case SQLITE_INTEGER: {
  75352. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  75353. break;
  75354. }
  75355. case SQLITE_FLOAT: {
  75356. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  75357. break;
  75358. }
  75359. case SQLITE_BLOB: {
  75360. if( pValue->flags & MEM_Zero ){
  75361. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  75362. }else{
  75363. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  75364. }
  75365. break;
  75366. }
  75367. case SQLITE_TEXT: {
  75368. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  75369. pValue->enc);
  75370. break;
  75371. }
  75372. default: {
  75373. rc = sqlite3_bind_null(pStmt, i);
  75374. break;
  75375. }
  75376. }
  75377. return rc;
  75378. }
  75379. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  75380. int rc;
  75381. Vdbe *p = (Vdbe *)pStmt;
  75382. rc = vdbeUnbind(p, i);
  75383. if( rc==SQLITE_OK ){
  75384. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  75385. sqlite3_mutex_leave(p->db->mutex);
  75386. }
  75387. return rc;
  75388. }
  75389. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  75390. int rc;
  75391. Vdbe *p = (Vdbe *)pStmt;
  75392. sqlite3_mutex_enter(p->db->mutex);
  75393. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  75394. rc = SQLITE_TOOBIG;
  75395. }else{
  75396. assert( (n & 0x7FFFFFFF)==n );
  75397. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  75398. }
  75399. rc = sqlite3ApiExit(p->db, rc);
  75400. sqlite3_mutex_leave(p->db->mutex);
  75401. return rc;
  75402. }
  75403. /*
  75404. ** Return the number of wildcards that can be potentially bound to.
  75405. ** This routine is added to support DBD::SQLite.
  75406. */
  75407. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  75408. Vdbe *p = (Vdbe*)pStmt;
  75409. return p ? p->nVar : 0;
  75410. }
  75411. /*
  75412. ** Return the name of a wildcard parameter. Return NULL if the index
  75413. ** is out of range or if the wildcard is unnamed.
  75414. **
  75415. ** The result is always UTF-8.
  75416. */
  75417. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  75418. Vdbe *p = (Vdbe*)pStmt;
  75419. if( p==0 ) return 0;
  75420. return sqlite3VListNumToName(p->pVList, i);
  75421. }
  75422. /*
  75423. ** Given a wildcard parameter name, return the index of the variable
  75424. ** with that name. If there is no variable with the given name,
  75425. ** return 0.
  75426. */
  75427. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  75428. if( p==0 || zName==0 ) return 0;
  75429. return sqlite3VListNameToNum(p->pVList, zName, nName);
  75430. }
  75431. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  75432. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  75433. }
  75434. /*
  75435. ** Transfer all bindings from the first statement over to the second.
  75436. */
  75437. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  75438. Vdbe *pFrom = (Vdbe*)pFromStmt;
  75439. Vdbe *pTo = (Vdbe*)pToStmt;
  75440. int i;
  75441. assert( pTo->db==pFrom->db );
  75442. assert( pTo->nVar==pFrom->nVar );
  75443. sqlite3_mutex_enter(pTo->db->mutex);
  75444. for(i=0; i<pFrom->nVar; i++){
  75445. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  75446. }
  75447. sqlite3_mutex_leave(pTo->db->mutex);
  75448. return SQLITE_OK;
  75449. }
  75450. #ifndef SQLITE_OMIT_DEPRECATED
  75451. /*
  75452. ** Deprecated external interface. Internal/core SQLite code
  75453. ** should call sqlite3TransferBindings.
  75454. **
  75455. ** It is misuse to call this routine with statements from different
  75456. ** database connections. But as this is a deprecated interface, we
  75457. ** will not bother to check for that condition.
  75458. **
  75459. ** If the two statements contain a different number of bindings, then
  75460. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  75461. ** SQLITE_OK is returned.
  75462. */
  75463. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  75464. Vdbe *pFrom = (Vdbe*)pFromStmt;
  75465. Vdbe *pTo = (Vdbe*)pToStmt;
  75466. if( pFrom->nVar!=pTo->nVar ){
  75467. return SQLITE_ERROR;
  75468. }
  75469. assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
  75470. if( pTo->expmask ){
  75471. pTo->expired = 1;
  75472. }
  75473. assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
  75474. if( pFrom->expmask ){
  75475. pFrom->expired = 1;
  75476. }
  75477. return sqlite3TransferBindings(pFromStmt, pToStmt);
  75478. }
  75479. #endif
  75480. /*
  75481. ** Return the sqlite3* database handle to which the prepared statement given
  75482. ** in the argument belongs. This is the same database handle that was
  75483. ** the first argument to the sqlite3_prepare() that was used to create
  75484. ** the statement in the first place.
  75485. */
  75486. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  75487. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  75488. }
  75489. /*
  75490. ** Return true if the prepared statement is guaranteed to not modify the
  75491. ** database.
  75492. */
  75493. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  75494. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  75495. }
  75496. /*
  75497. ** Return true if the prepared statement is in need of being reset.
  75498. */
  75499. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  75500. Vdbe *v = (Vdbe*)pStmt;
  75501. return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
  75502. }
  75503. /*
  75504. ** Return a pointer to the next prepared statement after pStmt associated
  75505. ** with database connection pDb. If pStmt is NULL, return the first
  75506. ** prepared statement for the database connection. Return NULL if there
  75507. ** are no more.
  75508. */
  75509. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  75510. sqlite3_stmt *pNext;
  75511. #ifdef SQLITE_ENABLE_API_ARMOR
  75512. if( !sqlite3SafetyCheckOk(pDb) ){
  75513. (void)SQLITE_MISUSE_BKPT;
  75514. return 0;
  75515. }
  75516. #endif
  75517. sqlite3_mutex_enter(pDb->mutex);
  75518. if( pStmt==0 ){
  75519. pNext = (sqlite3_stmt*)pDb->pVdbe;
  75520. }else{
  75521. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  75522. }
  75523. sqlite3_mutex_leave(pDb->mutex);
  75524. return pNext;
  75525. }
  75526. /*
  75527. ** Return the value of a status counter for a prepared statement
  75528. */
  75529. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  75530. Vdbe *pVdbe = (Vdbe*)pStmt;
  75531. u32 v;
  75532. #ifdef SQLITE_ENABLE_API_ARMOR
  75533. if( !pStmt
  75534. || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
  75535. ){
  75536. (void)SQLITE_MISUSE_BKPT;
  75537. return 0;
  75538. }
  75539. #endif
  75540. if( op==SQLITE_STMTSTATUS_MEMUSED ){
  75541. sqlite3 *db = pVdbe->db;
  75542. sqlite3_mutex_enter(db->mutex);
  75543. v = 0;
  75544. db->pnBytesFreed = (int*)&v;
  75545. sqlite3VdbeClearObject(db, pVdbe);
  75546. sqlite3DbFree(db, pVdbe);
  75547. db->pnBytesFreed = 0;
  75548. sqlite3_mutex_leave(db->mutex);
  75549. }else{
  75550. v = pVdbe->aCounter[op];
  75551. if( resetFlag ) pVdbe->aCounter[op] = 0;
  75552. }
  75553. return (int)v;
  75554. }
  75555. /*
  75556. ** Return the SQL associated with a prepared statement
  75557. */
  75558. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  75559. Vdbe *p = (Vdbe *)pStmt;
  75560. return p ? p->zSql : 0;
  75561. }
  75562. /*
  75563. ** Return the SQL associated with a prepared statement with
  75564. ** bound parameters expanded. Space to hold the returned string is
  75565. ** obtained from sqlite3_malloc(). The caller is responsible for
  75566. ** freeing the returned string by passing it to sqlite3_free().
  75567. **
  75568. ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
  75569. ** expanded bound parameters.
  75570. */
  75571. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
  75572. #ifdef SQLITE_OMIT_TRACE
  75573. return 0;
  75574. #else
  75575. char *z = 0;
  75576. const char *zSql = sqlite3_sql(pStmt);
  75577. if( zSql ){
  75578. Vdbe *p = (Vdbe *)pStmt;
  75579. sqlite3_mutex_enter(p->db->mutex);
  75580. z = sqlite3VdbeExpandSql(p, zSql);
  75581. sqlite3_mutex_leave(p->db->mutex);
  75582. }
  75583. return z;
  75584. #endif
  75585. }
  75586. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  75587. /*
  75588. ** Allocate and populate an UnpackedRecord structure based on the serialized
  75589. ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
  75590. ** if successful, or a NULL pointer if an OOM error is encountered.
  75591. */
  75592. static UnpackedRecord *vdbeUnpackRecord(
  75593. KeyInfo *pKeyInfo,
  75594. int nKey,
  75595. const void *pKey
  75596. ){
  75597. UnpackedRecord *pRet; /* Return value */
  75598. pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  75599. if( pRet ){
  75600. memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
  75601. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
  75602. }
  75603. return pRet;
  75604. }
  75605. /*
  75606. ** This function is called from within a pre-update callback to retrieve
  75607. ** a field of the row currently being updated or deleted.
  75608. */
  75609. SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  75610. PreUpdate *p = db->pPreUpdate;
  75611. Mem *pMem;
  75612. int rc = SQLITE_OK;
  75613. /* Test that this call is being made from within an SQLITE_DELETE or
  75614. ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
  75615. if( !p || p->op==SQLITE_INSERT ){
  75616. rc = SQLITE_MISUSE_BKPT;
  75617. goto preupdate_old_out;
  75618. }
  75619. if( p->pPk ){
  75620. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  75621. }
  75622. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  75623. rc = SQLITE_RANGE;
  75624. goto preupdate_old_out;
  75625. }
  75626. /* If the old.* record has not yet been loaded into memory, do so now. */
  75627. if( p->pUnpacked==0 ){
  75628. u32 nRec;
  75629. u8 *aRec;
  75630. nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
  75631. aRec = sqlite3DbMallocRaw(db, nRec);
  75632. if( !aRec ) goto preupdate_old_out;
  75633. rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
  75634. if( rc==SQLITE_OK ){
  75635. p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
  75636. if( !p->pUnpacked ) rc = SQLITE_NOMEM;
  75637. }
  75638. if( rc!=SQLITE_OK ){
  75639. sqlite3DbFree(db, aRec);
  75640. goto preupdate_old_out;
  75641. }
  75642. p->aRecord = aRec;
  75643. }
  75644. pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
  75645. if( iIdx==p->pTab->iPKey ){
  75646. sqlite3VdbeMemSetInt64(pMem, p->iKey1);
  75647. }else if( iIdx>=p->pUnpacked->nField ){
  75648. *ppValue = (sqlite3_value *)columnNullValue();
  75649. }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
  75650. if( pMem->flags & MEM_Int ){
  75651. sqlite3VdbeMemRealify(pMem);
  75652. }
  75653. }
  75654. preupdate_old_out:
  75655. sqlite3Error(db, rc);
  75656. return sqlite3ApiExit(db, rc);
  75657. }
  75658. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  75659. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  75660. /*
  75661. ** This function is called from within a pre-update callback to retrieve
  75662. ** the number of columns in the row being updated, deleted or inserted.
  75663. */
  75664. SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
  75665. PreUpdate *p = db->pPreUpdate;
  75666. return (p ? p->keyinfo.nKeyField : 0);
  75667. }
  75668. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  75669. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  75670. /*
  75671. ** This function is designed to be called from within a pre-update callback
  75672. ** only. It returns zero if the change that caused the callback was made
  75673. ** immediately by a user SQL statement. Or, if the change was made by a
  75674. ** trigger program, it returns the number of trigger programs currently
  75675. ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
  75676. ** top-level trigger etc.).
  75677. **
  75678. ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
  75679. ** or SET DEFAULT action is considered a trigger.
  75680. */
  75681. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
  75682. PreUpdate *p = db->pPreUpdate;
  75683. return (p ? p->v->nFrame : 0);
  75684. }
  75685. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  75686. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  75687. /*
  75688. ** This function is called from within a pre-update callback to retrieve
  75689. ** a field of the row currently being updated or inserted.
  75690. */
  75691. SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  75692. PreUpdate *p = db->pPreUpdate;
  75693. int rc = SQLITE_OK;
  75694. Mem *pMem;
  75695. if( !p || p->op==SQLITE_DELETE ){
  75696. rc = SQLITE_MISUSE_BKPT;
  75697. goto preupdate_new_out;
  75698. }
  75699. if( p->pPk && p->op!=SQLITE_UPDATE ){
  75700. iIdx = sqlite3ColumnOfIndex(p->pPk, iIdx);
  75701. }
  75702. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  75703. rc = SQLITE_RANGE;
  75704. goto preupdate_new_out;
  75705. }
  75706. if( p->op==SQLITE_INSERT ){
  75707. /* For an INSERT, memory cell p->iNewReg contains the serialized record
  75708. ** that is being inserted. Deserialize it. */
  75709. UnpackedRecord *pUnpack = p->pNewUnpacked;
  75710. if( !pUnpack ){
  75711. Mem *pData = &p->v->aMem[p->iNewReg];
  75712. rc = ExpandBlob(pData);
  75713. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  75714. pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
  75715. if( !pUnpack ){
  75716. rc = SQLITE_NOMEM;
  75717. goto preupdate_new_out;
  75718. }
  75719. p->pNewUnpacked = pUnpack;
  75720. }
  75721. pMem = &pUnpack->aMem[iIdx];
  75722. if( iIdx==p->pTab->iPKey ){
  75723. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  75724. }else if( iIdx>=pUnpack->nField ){
  75725. pMem = (sqlite3_value *)columnNullValue();
  75726. }
  75727. }else{
  75728. /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
  75729. ** value. Make a copy of the cell contents and return a pointer to it.
  75730. ** It is not safe to return a pointer to the memory cell itself as the
  75731. ** caller may modify the value text encoding.
  75732. */
  75733. assert( p->op==SQLITE_UPDATE );
  75734. if( !p->aNew ){
  75735. p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
  75736. if( !p->aNew ){
  75737. rc = SQLITE_NOMEM;
  75738. goto preupdate_new_out;
  75739. }
  75740. }
  75741. assert( iIdx>=0 && iIdx<p->pCsr->nField );
  75742. pMem = &p->aNew[iIdx];
  75743. if( pMem->flags==0 ){
  75744. if( iIdx==p->pTab->iPKey ){
  75745. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  75746. }else{
  75747. rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
  75748. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  75749. }
  75750. }
  75751. }
  75752. *ppValue = pMem;
  75753. preupdate_new_out:
  75754. sqlite3Error(db, rc);
  75755. return sqlite3ApiExit(db, rc);
  75756. }
  75757. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  75758. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  75759. /*
  75760. ** Return status data for a single loop within query pStmt.
  75761. */
  75762. SQLITE_API int sqlite3_stmt_scanstatus(
  75763. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  75764. int idx, /* Index of loop to report on */
  75765. int iScanStatusOp, /* Which metric to return */
  75766. void *pOut /* OUT: Write the answer here */
  75767. ){
  75768. Vdbe *p = (Vdbe*)pStmt;
  75769. ScanStatus *pScan;
  75770. if( idx<0 || idx>=p->nScan ) return 1;
  75771. pScan = &p->aScan[idx];
  75772. switch( iScanStatusOp ){
  75773. case SQLITE_SCANSTAT_NLOOP: {
  75774. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  75775. break;
  75776. }
  75777. case SQLITE_SCANSTAT_NVISIT: {
  75778. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  75779. break;
  75780. }
  75781. case SQLITE_SCANSTAT_EST: {
  75782. double r = 1.0;
  75783. LogEst x = pScan->nEst;
  75784. while( x<100 ){
  75785. x += 10;
  75786. r *= 0.5;
  75787. }
  75788. *(double*)pOut = r*sqlite3LogEstToInt(x);
  75789. break;
  75790. }
  75791. case SQLITE_SCANSTAT_NAME: {
  75792. *(const char**)pOut = pScan->zName;
  75793. break;
  75794. }
  75795. case SQLITE_SCANSTAT_EXPLAIN: {
  75796. if( pScan->addrExplain ){
  75797. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  75798. }else{
  75799. *(const char**)pOut = 0;
  75800. }
  75801. break;
  75802. }
  75803. case SQLITE_SCANSTAT_SELECTID: {
  75804. if( pScan->addrExplain ){
  75805. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  75806. }else{
  75807. *(int*)pOut = -1;
  75808. }
  75809. break;
  75810. }
  75811. default: {
  75812. return 1;
  75813. }
  75814. }
  75815. return 0;
  75816. }
  75817. /*
  75818. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  75819. */
  75820. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  75821. Vdbe *p = (Vdbe*)pStmt;
  75822. memset(p->anExec, 0, p->nOp * sizeof(i64));
  75823. }
  75824. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  75825. /************** End of vdbeapi.c *********************************************/
  75826. /************** Begin file vdbetrace.c ***************************************/
  75827. /*
  75828. ** 2009 November 25
  75829. **
  75830. ** The author disclaims copyright to this source code. In place of
  75831. ** a legal notice, here is a blessing:
  75832. **
  75833. ** May you do good and not evil.
  75834. ** May you find forgiveness for yourself and forgive others.
  75835. ** May you share freely, never taking more than you give.
  75836. **
  75837. *************************************************************************
  75838. **
  75839. ** This file contains code used to insert the values of host parameters
  75840. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  75841. **
  75842. ** The Vdbe parse-tree explainer is also found here.
  75843. */
  75844. /* #include "sqliteInt.h" */
  75845. /* #include "vdbeInt.h" */
  75846. #ifndef SQLITE_OMIT_TRACE
  75847. /*
  75848. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  75849. ** bytes in this text up to but excluding the first character in
  75850. ** a host parameter. If the text contains no host parameters, return
  75851. ** the total number of bytes in the text.
  75852. */
  75853. static int findNextHostParameter(const char *zSql, int *pnToken){
  75854. int tokenType;
  75855. int nTotal = 0;
  75856. int n;
  75857. *pnToken = 0;
  75858. while( zSql[0] ){
  75859. n = sqlite3GetToken((u8*)zSql, &tokenType);
  75860. assert( n>0 && tokenType!=TK_ILLEGAL );
  75861. if( tokenType==TK_VARIABLE ){
  75862. *pnToken = n;
  75863. break;
  75864. }
  75865. nTotal += n;
  75866. zSql += n;
  75867. }
  75868. return nTotal;
  75869. }
  75870. /*
  75871. ** This function returns a pointer to a nul-terminated string in memory
  75872. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  75873. ** string contains a copy of zRawSql but with host parameters expanded to
  75874. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  75875. ** then the returned string holds a copy of zRawSql with "-- " prepended
  75876. ** to each line of text.
  75877. **
  75878. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  75879. ** then long strings and blobs are truncated to that many bytes. This
  75880. ** can be used to prevent unreasonably large trace strings when dealing
  75881. ** with large (multi-megabyte) strings and blobs.
  75882. **
  75883. ** The calling function is responsible for making sure the memory returned
  75884. ** is eventually freed.
  75885. **
  75886. ** ALGORITHM: Scan the input string looking for host parameters in any of
  75887. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  75888. ** string literals, quoted identifier names, and comments. For text forms,
  75889. ** the host parameter index is found by scanning the prepared
  75890. ** statement for the corresponding OP_Variable opcode. Once the host
  75891. ** parameter index is known, locate the value in p->aVar[]. Then render
  75892. ** the value as a literal in place of the host parameter name.
  75893. */
  75894. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  75895. Vdbe *p, /* The prepared statement being evaluated */
  75896. const char *zRawSql /* Raw text of the SQL statement */
  75897. ){
  75898. sqlite3 *db; /* The database connection */
  75899. int idx = 0; /* Index of a host parameter */
  75900. int nextIndex = 1; /* Index of next ? host parameter */
  75901. int n; /* Length of a token prefix */
  75902. int nToken; /* Length of the parameter token */
  75903. int i; /* Loop counter */
  75904. Mem *pVar; /* Value of a host parameter */
  75905. StrAccum out; /* Accumulate the output here */
  75906. #ifndef SQLITE_OMIT_UTF16
  75907. Mem utf8; /* Used to convert UTF16 into UTF8 for display */
  75908. #endif
  75909. char zBase[100]; /* Initial working space */
  75910. db = p->db;
  75911. sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
  75912. db->aLimit[SQLITE_LIMIT_LENGTH]);
  75913. if( db->nVdbeExec>1 ){
  75914. while( *zRawSql ){
  75915. const char *zStart = zRawSql;
  75916. while( *(zRawSql++)!='\n' && *zRawSql );
  75917. sqlite3StrAccumAppend(&out, "-- ", 3);
  75918. assert( (zRawSql - zStart) > 0 );
  75919. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  75920. }
  75921. }else if( p->nVar==0 ){
  75922. sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
  75923. }else{
  75924. while( zRawSql[0] ){
  75925. n = findNextHostParameter(zRawSql, &nToken);
  75926. assert( n>0 );
  75927. sqlite3StrAccumAppend(&out, zRawSql, n);
  75928. zRawSql += n;
  75929. assert( zRawSql[0] || nToken==0 );
  75930. if( nToken==0 ) break;
  75931. if( zRawSql[0]=='?' ){
  75932. if( nToken>1 ){
  75933. assert( sqlite3Isdigit(zRawSql[1]) );
  75934. sqlite3GetInt32(&zRawSql[1], &idx);
  75935. }else{
  75936. idx = nextIndex;
  75937. }
  75938. }else{
  75939. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  75940. zRawSql[0]=='@' || zRawSql[0]=='#' );
  75941. testcase( zRawSql[0]==':' );
  75942. testcase( zRawSql[0]=='$' );
  75943. testcase( zRawSql[0]=='@' );
  75944. testcase( zRawSql[0]=='#' );
  75945. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  75946. assert( idx>0 );
  75947. }
  75948. zRawSql += nToken;
  75949. nextIndex = idx + 1;
  75950. assert( idx>0 && idx<=p->nVar );
  75951. pVar = &p->aVar[idx-1];
  75952. if( pVar->flags & MEM_Null ){
  75953. sqlite3StrAccumAppend(&out, "NULL", 4);
  75954. }else if( pVar->flags & MEM_Int ){
  75955. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  75956. }else if( pVar->flags & MEM_Real ){
  75957. sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
  75958. }else if( pVar->flags & MEM_Str ){
  75959. int nOut; /* Number of bytes of the string text to include in output */
  75960. #ifndef SQLITE_OMIT_UTF16
  75961. u8 enc = ENC(db);
  75962. if( enc!=SQLITE_UTF8 ){
  75963. memset(&utf8, 0, sizeof(utf8));
  75964. utf8.db = db;
  75965. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  75966. if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
  75967. out.accError = STRACCUM_NOMEM;
  75968. out.nAlloc = 0;
  75969. }
  75970. pVar = &utf8;
  75971. }
  75972. #endif
  75973. nOut = pVar->n;
  75974. #ifdef SQLITE_TRACE_SIZE_LIMIT
  75975. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  75976. nOut = SQLITE_TRACE_SIZE_LIMIT;
  75977. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  75978. }
  75979. #endif
  75980. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  75981. #ifdef SQLITE_TRACE_SIZE_LIMIT
  75982. if( nOut<pVar->n ){
  75983. sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  75984. }
  75985. #endif
  75986. #ifndef SQLITE_OMIT_UTF16
  75987. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  75988. #endif
  75989. }else if( pVar->flags & MEM_Zero ){
  75990. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  75991. }else{
  75992. int nOut; /* Number of bytes of the blob to include in output */
  75993. assert( pVar->flags & MEM_Blob );
  75994. sqlite3StrAccumAppend(&out, "x'", 2);
  75995. nOut = pVar->n;
  75996. #ifdef SQLITE_TRACE_SIZE_LIMIT
  75997. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  75998. #endif
  75999. for(i=0; i<nOut; i++){
  76000. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  76001. }
  76002. sqlite3StrAccumAppend(&out, "'", 1);
  76003. #ifdef SQLITE_TRACE_SIZE_LIMIT
  76004. if( nOut<pVar->n ){
  76005. sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  76006. }
  76007. #endif
  76008. }
  76009. }
  76010. }
  76011. if( out.accError ) sqlite3StrAccumReset(&out);
  76012. return sqlite3StrAccumFinish(&out);
  76013. }
  76014. #endif /* #ifndef SQLITE_OMIT_TRACE */
  76015. /************** End of vdbetrace.c *******************************************/
  76016. /************** Begin file vdbe.c ********************************************/
  76017. /*
  76018. ** 2001 September 15
  76019. **
  76020. ** The author disclaims copyright to this source code. In place of
  76021. ** a legal notice, here is a blessing:
  76022. **
  76023. ** May you do good and not evil.
  76024. ** May you find forgiveness for yourself and forgive others.
  76025. ** May you share freely, never taking more than you give.
  76026. **
  76027. *************************************************************************
  76028. ** The code in this file implements the function that runs the
  76029. ** bytecode of a prepared statement.
  76030. **
  76031. ** Various scripts scan this source file in order to generate HTML
  76032. ** documentation, headers files, or other derived files. The formatting
  76033. ** of the code in this file is, therefore, important. See other comments
  76034. ** in this file for details. If in doubt, do not deviate from existing
  76035. ** commenting and indentation practices when changing or adding code.
  76036. */
  76037. /* #include "sqliteInt.h" */
  76038. /* #include "vdbeInt.h" */
  76039. /*
  76040. ** Invoke this macro on memory cells just prior to changing the
  76041. ** value of the cell. This macro verifies that shallow copies are
  76042. ** not misused. A shallow copy of a string or blob just copies a
  76043. ** pointer to the string or blob, not the content. If the original
  76044. ** is changed while the copy is still in use, the string or blob might
  76045. ** be changed out from under the copy. This macro verifies that nothing
  76046. ** like that ever happens.
  76047. */
  76048. #ifdef SQLITE_DEBUG
  76049. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  76050. #else
  76051. # define memAboutToChange(P,M)
  76052. #endif
  76053. /*
  76054. ** The following global variable is incremented every time a cursor
  76055. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  76056. ** procedures use this information to make sure that indices are
  76057. ** working correctly. This variable has no function other than to
  76058. ** help verify the correct operation of the library.
  76059. */
  76060. #ifdef SQLITE_TEST
  76061. SQLITE_API int sqlite3_search_count = 0;
  76062. #endif
  76063. /*
  76064. ** When this global variable is positive, it gets decremented once before
  76065. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  76066. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  76067. **
  76068. ** This facility is used for testing purposes only. It does not function
  76069. ** in an ordinary build.
  76070. */
  76071. #ifdef SQLITE_TEST
  76072. SQLITE_API int sqlite3_interrupt_count = 0;
  76073. #endif
  76074. /*
  76075. ** The next global variable is incremented each type the OP_Sort opcode
  76076. ** is executed. The test procedures use this information to make sure that
  76077. ** sorting is occurring or not occurring at appropriate times. This variable
  76078. ** has no function other than to help verify the correct operation of the
  76079. ** library.
  76080. */
  76081. #ifdef SQLITE_TEST
  76082. SQLITE_API int sqlite3_sort_count = 0;
  76083. #endif
  76084. /*
  76085. ** The next global variable records the size of the largest MEM_Blob
  76086. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  76087. ** use this information to make sure that the zero-blob functionality
  76088. ** is working correctly. This variable has no function other than to
  76089. ** help verify the correct operation of the library.
  76090. */
  76091. #ifdef SQLITE_TEST
  76092. SQLITE_API int sqlite3_max_blobsize = 0;
  76093. static void updateMaxBlobsize(Mem *p){
  76094. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  76095. sqlite3_max_blobsize = p->n;
  76096. }
  76097. }
  76098. #endif
  76099. /*
  76100. ** This macro evaluates to true if either the update hook or the preupdate
  76101. ** hook are enabled for database connect DB.
  76102. */
  76103. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  76104. # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
  76105. #else
  76106. # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
  76107. #endif
  76108. /*
  76109. ** The next global variable is incremented each time the OP_Found opcode
  76110. ** is executed. This is used to test whether or not the foreign key
  76111. ** operation implemented using OP_FkIsZero is working. This variable
  76112. ** has no function other than to help verify the correct operation of the
  76113. ** library.
  76114. */
  76115. #ifdef SQLITE_TEST
  76116. SQLITE_API int sqlite3_found_count = 0;
  76117. #endif
  76118. /*
  76119. ** Test a register to see if it exceeds the current maximum blob size.
  76120. ** If it does, record the new maximum blob size.
  76121. */
  76122. #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
  76123. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  76124. #else
  76125. # define UPDATE_MAX_BLOBSIZE(P)
  76126. #endif
  76127. /*
  76128. ** Invoke the VDBE coverage callback, if that callback is defined. This
  76129. ** feature is used for test suite validation only and does not appear an
  76130. ** production builds.
  76131. **
  76132. ** M is an integer, 2 or 3, that indices how many different ways the
  76133. ** branch can go. It is usually 2. "I" is the direction the branch
  76134. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  76135. ** second alternative branch is taken.
  76136. **
  76137. ** iSrcLine is the source code line (from the __LINE__ macro) that
  76138. ** generated the VDBE instruction. This instrumentation assumes that all
  76139. ** source code is in a single file (the amalgamation). Special values 1
  76140. ** and 2 for the iSrcLine parameter mean that this particular branch is
  76141. ** always taken or never taken, respectively.
  76142. */
  76143. #if !defined(SQLITE_VDBE_COVERAGE)
  76144. # define VdbeBranchTaken(I,M)
  76145. #else
  76146. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  76147. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  76148. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  76149. M = iSrcLine;
  76150. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  76151. ** VdbeCoverageNeverTaken() */
  76152. assert( (M & I)==I );
  76153. }else{
  76154. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  76155. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  76156. iSrcLine,I,M);
  76157. }
  76158. }
  76159. #endif
  76160. /*
  76161. ** Convert the given register into a string if it isn't one
  76162. ** already. Return non-zero if a malloc() fails.
  76163. */
  76164. #define Stringify(P, enc) \
  76165. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  76166. { goto no_mem; }
  76167. /*
  76168. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  76169. ** a pointer to a dynamically allocated string where some other entity
  76170. ** is responsible for deallocating that string. Because the register
  76171. ** does not control the string, it might be deleted without the register
  76172. ** knowing it.
  76173. **
  76174. ** This routine converts an ephemeral string into a dynamically allocated
  76175. ** string that the register itself controls. In other words, it
  76176. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  76177. */
  76178. #define Deephemeralize(P) \
  76179. if( ((P)->flags&MEM_Ephem)!=0 \
  76180. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  76181. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  76182. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  76183. /*
  76184. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  76185. ** if we run out of memory.
  76186. */
  76187. static VdbeCursor *allocateCursor(
  76188. Vdbe *p, /* The virtual machine */
  76189. int iCur, /* Index of the new VdbeCursor */
  76190. int nField, /* Number of fields in the table or index */
  76191. int iDb, /* Database the cursor belongs to, or -1 */
  76192. u8 eCurType /* Type of the new cursor */
  76193. ){
  76194. /* Find the memory cell that will be used to store the blob of memory
  76195. ** required for this VdbeCursor structure. It is convenient to use a
  76196. ** vdbe memory cell to manage the memory allocation required for a
  76197. ** VdbeCursor structure for the following reasons:
  76198. **
  76199. ** * Sometimes cursor numbers are used for a couple of different
  76200. ** purposes in a vdbe program. The different uses might require
  76201. ** different sized allocations. Memory cells provide growable
  76202. ** allocations.
  76203. **
  76204. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  76205. ** be freed lazily via the sqlite3_release_memory() API. This
  76206. ** minimizes the number of malloc calls made by the system.
  76207. **
  76208. ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
  76209. ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
  76210. ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
  76211. */
  76212. Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
  76213. int nByte;
  76214. VdbeCursor *pCx = 0;
  76215. nByte =
  76216. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  76217. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  76218. assert( iCur>=0 && iCur<p->nCursor );
  76219. if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
  76220. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  76221. p->apCsr[iCur] = 0;
  76222. }
  76223. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  76224. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  76225. memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
  76226. pCx->eCurType = eCurType;
  76227. pCx->iDb = iDb;
  76228. pCx->nField = nField;
  76229. pCx->aOffset = &pCx->aType[nField];
  76230. if( eCurType==CURTYPE_BTREE ){
  76231. pCx->uc.pCursor = (BtCursor*)
  76232. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  76233. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  76234. }
  76235. }
  76236. return pCx;
  76237. }
  76238. /*
  76239. ** Try to convert a value into a numeric representation if we can
  76240. ** do so without loss of information. In other words, if the string
  76241. ** looks like a number, convert it into a number. If it does not
  76242. ** look like a number, leave it alone.
  76243. **
  76244. ** If the bTryForInt flag is true, then extra effort is made to give
  76245. ** an integer representation. Strings that look like floating point
  76246. ** values but which have no fractional component (example: '48.00')
  76247. ** will have a MEM_Int representation when bTryForInt is true.
  76248. **
  76249. ** If bTryForInt is false, then if the input string contains a decimal
  76250. ** point or exponential notation, the result is only MEM_Real, even
  76251. ** if there is an exact integer representation of the quantity.
  76252. */
  76253. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  76254. double rValue;
  76255. i64 iValue;
  76256. u8 enc = pRec->enc;
  76257. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  76258. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  76259. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  76260. pRec->u.i = iValue;
  76261. pRec->flags |= MEM_Int;
  76262. }else{
  76263. pRec->u.r = rValue;
  76264. pRec->flags |= MEM_Real;
  76265. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  76266. }
  76267. /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
  76268. ** string representation after computing a numeric equivalent, because the
  76269. ** string representation might not be the canonical representation for the
  76270. ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
  76271. pRec->flags &= ~MEM_Str;
  76272. }
  76273. /*
  76274. ** Processing is determine by the affinity parameter:
  76275. **
  76276. ** SQLITE_AFF_INTEGER:
  76277. ** SQLITE_AFF_REAL:
  76278. ** SQLITE_AFF_NUMERIC:
  76279. ** Try to convert pRec to an integer representation or a
  76280. ** floating-point representation if an integer representation
  76281. ** is not possible. Note that the integer representation is
  76282. ** always preferred, even if the affinity is REAL, because
  76283. ** an integer representation is more space efficient on disk.
  76284. **
  76285. ** SQLITE_AFF_TEXT:
  76286. ** Convert pRec to a text representation.
  76287. **
  76288. ** SQLITE_AFF_BLOB:
  76289. ** No-op. pRec is unchanged.
  76290. */
  76291. static void applyAffinity(
  76292. Mem *pRec, /* The value to apply affinity to */
  76293. char affinity, /* The affinity to be applied */
  76294. u8 enc /* Use this text encoding */
  76295. ){
  76296. if( affinity>=SQLITE_AFF_NUMERIC ){
  76297. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  76298. || affinity==SQLITE_AFF_NUMERIC );
  76299. if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  76300. if( (pRec->flags & MEM_Real)==0 ){
  76301. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  76302. }else{
  76303. sqlite3VdbeIntegerAffinity(pRec);
  76304. }
  76305. }
  76306. }else if( affinity==SQLITE_AFF_TEXT ){
  76307. /* Only attempt the conversion to TEXT if there is an integer or real
  76308. ** representation (blob and NULL do not get converted) but no string
  76309. ** representation. It would be harmless to repeat the conversion if
  76310. ** there is already a string rep, but it is pointless to waste those
  76311. ** CPU cycles. */
  76312. if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
  76313. if( (pRec->flags&(MEM_Real|MEM_Int)) ){
  76314. sqlite3VdbeMemStringify(pRec, enc, 1);
  76315. }
  76316. }
  76317. pRec->flags &= ~(MEM_Real|MEM_Int);
  76318. }
  76319. }
  76320. /*
  76321. ** Try to convert the type of a function argument or a result column
  76322. ** into a numeric representation. Use either INTEGER or REAL whichever
  76323. ** is appropriate. But only do the conversion if it is possible without
  76324. ** loss of information and return the revised type of the argument.
  76325. */
  76326. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  76327. int eType = sqlite3_value_type(pVal);
  76328. if( eType==SQLITE_TEXT ){
  76329. Mem *pMem = (Mem*)pVal;
  76330. applyNumericAffinity(pMem, 0);
  76331. eType = sqlite3_value_type(pVal);
  76332. }
  76333. return eType;
  76334. }
  76335. /*
  76336. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  76337. ** not the internal Mem* type.
  76338. */
  76339. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  76340. sqlite3_value *pVal,
  76341. u8 affinity,
  76342. u8 enc
  76343. ){
  76344. applyAffinity((Mem *)pVal, affinity, enc);
  76345. }
  76346. /*
  76347. ** pMem currently only holds a string type (or maybe a BLOB that we can
  76348. ** interpret as a string if we want to). Compute its corresponding
  76349. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  76350. ** accordingly.
  76351. */
  76352. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  76353. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  76354. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  76355. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  76356. return 0;
  76357. }
  76358. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==0 ){
  76359. return MEM_Int;
  76360. }
  76361. return MEM_Real;
  76362. }
  76363. /*
  76364. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  76365. ** none.
  76366. **
  76367. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  76368. ** But it does set pMem->u.r and pMem->u.i appropriately.
  76369. */
  76370. static u16 numericType(Mem *pMem){
  76371. if( pMem->flags & (MEM_Int|MEM_Real) ){
  76372. return pMem->flags & (MEM_Int|MEM_Real);
  76373. }
  76374. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  76375. return computeNumericType(pMem);
  76376. }
  76377. return 0;
  76378. }
  76379. #ifdef SQLITE_DEBUG
  76380. /*
  76381. ** Write a nice string representation of the contents of cell pMem
  76382. ** into buffer zBuf, length nBuf.
  76383. */
  76384. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  76385. char *zCsr = zBuf;
  76386. int f = pMem->flags;
  76387. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  76388. if( f&MEM_Blob ){
  76389. int i;
  76390. char c;
  76391. if( f & MEM_Dyn ){
  76392. c = 'z';
  76393. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  76394. }else if( f & MEM_Static ){
  76395. c = 't';
  76396. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  76397. }else if( f & MEM_Ephem ){
  76398. c = 'e';
  76399. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  76400. }else{
  76401. c = 's';
  76402. }
  76403. *(zCsr++) = c;
  76404. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  76405. zCsr += sqlite3Strlen30(zCsr);
  76406. for(i=0; i<16 && i<pMem->n; i++){
  76407. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  76408. zCsr += sqlite3Strlen30(zCsr);
  76409. }
  76410. for(i=0; i<16 && i<pMem->n; i++){
  76411. char z = pMem->z[i];
  76412. if( z<32 || z>126 ) *zCsr++ = '.';
  76413. else *zCsr++ = z;
  76414. }
  76415. *(zCsr++) = ']';
  76416. if( f & MEM_Zero ){
  76417. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  76418. zCsr += sqlite3Strlen30(zCsr);
  76419. }
  76420. *zCsr = '\0';
  76421. }else if( f & MEM_Str ){
  76422. int j, k;
  76423. zBuf[0] = ' ';
  76424. if( f & MEM_Dyn ){
  76425. zBuf[1] = 'z';
  76426. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  76427. }else if( f & MEM_Static ){
  76428. zBuf[1] = 't';
  76429. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  76430. }else if( f & MEM_Ephem ){
  76431. zBuf[1] = 'e';
  76432. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  76433. }else{
  76434. zBuf[1] = 's';
  76435. }
  76436. k = 2;
  76437. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  76438. k += sqlite3Strlen30(&zBuf[k]);
  76439. zBuf[k++] = '[';
  76440. for(j=0; j<15 && j<pMem->n; j++){
  76441. u8 c = pMem->z[j];
  76442. if( c>=0x20 && c<0x7f ){
  76443. zBuf[k++] = c;
  76444. }else{
  76445. zBuf[k++] = '.';
  76446. }
  76447. }
  76448. zBuf[k++] = ']';
  76449. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  76450. k += sqlite3Strlen30(&zBuf[k]);
  76451. zBuf[k++] = 0;
  76452. }
  76453. }
  76454. #endif
  76455. #ifdef SQLITE_DEBUG
  76456. /*
  76457. ** Print the value of a register for tracing purposes:
  76458. */
  76459. static void memTracePrint(Mem *p){
  76460. if( p->flags & MEM_Undefined ){
  76461. printf(" undefined");
  76462. }else if( p->flags & MEM_Null ){
  76463. printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
  76464. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  76465. printf(" si:%lld", p->u.i);
  76466. }else if( p->flags & MEM_Int ){
  76467. printf(" i:%lld", p->u.i);
  76468. #ifndef SQLITE_OMIT_FLOATING_POINT
  76469. }else if( p->flags & MEM_Real ){
  76470. printf(" r:%g", p->u.r);
  76471. #endif
  76472. }else if( p->flags & MEM_RowSet ){
  76473. printf(" (rowset)");
  76474. }else{
  76475. char zBuf[200];
  76476. sqlite3VdbeMemPrettyPrint(p, zBuf);
  76477. printf(" %s", zBuf);
  76478. }
  76479. if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
  76480. }
  76481. static void registerTrace(int iReg, Mem *p){
  76482. printf("REG[%d] = ", iReg);
  76483. memTracePrint(p);
  76484. printf("\n");
  76485. sqlite3VdbeCheckMemInvariants(p);
  76486. }
  76487. #endif
  76488. #ifdef SQLITE_DEBUG
  76489. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  76490. #else
  76491. # define REGISTER_TRACE(R,M)
  76492. #endif
  76493. #ifdef VDBE_PROFILE
  76494. /*
  76495. ** hwtime.h contains inline assembler code for implementing
  76496. ** high-performance timing routines.
  76497. */
  76498. /************** Include hwtime.h in the middle of vdbe.c *********************/
  76499. /************** Begin file hwtime.h ******************************************/
  76500. /*
  76501. ** 2008 May 27
  76502. **
  76503. ** The author disclaims copyright to this source code. In place of
  76504. ** a legal notice, here is a blessing:
  76505. **
  76506. ** May you do good and not evil.
  76507. ** May you find forgiveness for yourself and forgive others.
  76508. ** May you share freely, never taking more than you give.
  76509. **
  76510. ******************************************************************************
  76511. **
  76512. ** This file contains inline asm code for retrieving "high-performance"
  76513. ** counters for x86 class CPUs.
  76514. */
  76515. #ifndef SQLITE_HWTIME_H
  76516. #define SQLITE_HWTIME_H
  76517. /*
  76518. ** The following routine only works on pentium-class (or newer) processors.
  76519. ** It uses the RDTSC opcode to read the cycle count value out of the
  76520. ** processor and returns that value. This can be used for high-res
  76521. ** profiling.
  76522. */
  76523. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  76524. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  76525. #if defined(__GNUC__)
  76526. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  76527. unsigned int lo, hi;
  76528. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  76529. return (sqlite_uint64)hi << 32 | lo;
  76530. }
  76531. #elif defined(_MSC_VER)
  76532. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  76533. __asm {
  76534. rdtsc
  76535. ret ; return value at EDX:EAX
  76536. }
  76537. }
  76538. #endif
  76539. #elif (defined(__GNUC__) && defined(__x86_64__))
  76540. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  76541. unsigned long val;
  76542. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  76543. return val;
  76544. }
  76545. #elif (defined(__GNUC__) && defined(__ppc__))
  76546. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  76547. unsigned long long retval;
  76548. unsigned long junk;
  76549. __asm__ __volatile__ ("\n\
  76550. 1: mftbu %1\n\
  76551. mftb %L0\n\
  76552. mftbu %0\n\
  76553. cmpw %0,%1\n\
  76554. bne 1b"
  76555. : "=r" (retval), "=r" (junk));
  76556. return retval;
  76557. }
  76558. #else
  76559. #error Need implementation of sqlite3Hwtime() for your platform.
  76560. /*
  76561. ** To compile without implementing sqlite3Hwtime() for your platform,
  76562. ** you can remove the above #error and use the following
  76563. ** stub function. You will lose timing support for many
  76564. ** of the debugging and testing utilities, but it should at
  76565. ** least compile and run.
  76566. */
  76567. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  76568. #endif
  76569. #endif /* !defined(SQLITE_HWTIME_H) */
  76570. /************** End of hwtime.h **********************************************/
  76571. /************** Continuing where we left off in vdbe.c ***********************/
  76572. #endif
  76573. #ifndef NDEBUG
  76574. /*
  76575. ** This function is only called from within an assert() expression. It
  76576. ** checks that the sqlite3.nTransaction variable is correctly set to
  76577. ** the number of non-transaction savepoints currently in the
  76578. ** linked list starting at sqlite3.pSavepoint.
  76579. **
  76580. ** Usage:
  76581. **
  76582. ** assert( checkSavepointCount(db) );
  76583. */
  76584. static int checkSavepointCount(sqlite3 *db){
  76585. int n = 0;
  76586. Savepoint *p;
  76587. for(p=db->pSavepoint; p; p=p->pNext) n++;
  76588. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  76589. return 1;
  76590. }
  76591. #endif
  76592. /*
  76593. ** Return the register of pOp->p2 after first preparing it to be
  76594. ** overwritten with an integer value.
  76595. */
  76596. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  76597. sqlite3VdbeMemSetNull(pOut);
  76598. pOut->flags = MEM_Int;
  76599. return pOut;
  76600. }
  76601. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  76602. Mem *pOut;
  76603. assert( pOp->p2>0 );
  76604. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  76605. pOut = &p->aMem[pOp->p2];
  76606. memAboutToChange(p, pOut);
  76607. if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
  76608. return out2PrereleaseWithClear(pOut);
  76609. }else{
  76610. pOut->flags = MEM_Int;
  76611. return pOut;
  76612. }
  76613. }
  76614. /*
  76615. ** Execute as much of a VDBE program as we can.
  76616. ** This is the core of sqlite3_step().
  76617. */
  76618. SQLITE_PRIVATE int sqlite3VdbeExec(
  76619. Vdbe *p /* The VDBE */
  76620. ){
  76621. Op *aOp = p->aOp; /* Copy of p->aOp */
  76622. Op *pOp = aOp; /* Current operation */
  76623. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  76624. Op *pOrigOp; /* Value of pOp at the top of the loop */
  76625. #endif
  76626. #ifdef SQLITE_DEBUG
  76627. int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
  76628. #endif
  76629. int rc = SQLITE_OK; /* Value to return */
  76630. sqlite3 *db = p->db; /* The database */
  76631. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  76632. u8 encoding = ENC(db); /* The database encoding */
  76633. int iCompare = 0; /* Result of last comparison */
  76634. unsigned nVmStep = 0; /* Number of virtual machine steps */
  76635. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  76636. unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
  76637. #endif
  76638. Mem *aMem = p->aMem; /* Copy of p->aMem */
  76639. Mem *pIn1 = 0; /* 1st input operand */
  76640. Mem *pIn2 = 0; /* 2nd input operand */
  76641. Mem *pIn3 = 0; /* 3rd input operand */
  76642. Mem *pOut = 0; /* Output operand */
  76643. #ifdef VDBE_PROFILE
  76644. u64 start; /* CPU clock count at start of opcode */
  76645. #endif
  76646. /*** INSERT STACK UNION HERE ***/
  76647. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  76648. sqlite3VdbeEnter(p);
  76649. if( p->rc==SQLITE_NOMEM ){
  76650. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  76651. ** sqlite3_column_text16() failed. */
  76652. goto no_mem;
  76653. }
  76654. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  76655. assert( p->bIsReader || p->readOnly!=0 );
  76656. p->iCurrentTime = 0;
  76657. assert( p->explain==0 );
  76658. p->pResultSet = 0;
  76659. db->busyHandler.nBusy = 0;
  76660. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  76661. sqlite3VdbeIOTraceSql(p);
  76662. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  76663. if( db->xProgress ){
  76664. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  76665. assert( 0 < db->nProgressOps );
  76666. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  76667. }else{
  76668. nProgressLimit = 0xffffffff;
  76669. }
  76670. #endif
  76671. #ifdef SQLITE_DEBUG
  76672. sqlite3BeginBenignMalloc();
  76673. if( p->pc==0
  76674. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  76675. ){
  76676. int i;
  76677. int once = 1;
  76678. sqlite3VdbePrintSql(p);
  76679. if( p->db->flags & SQLITE_VdbeListing ){
  76680. printf("VDBE Program Listing:\n");
  76681. for(i=0; i<p->nOp; i++){
  76682. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  76683. }
  76684. }
  76685. if( p->db->flags & SQLITE_VdbeEQP ){
  76686. for(i=0; i<p->nOp; i++){
  76687. if( aOp[i].opcode==OP_Explain ){
  76688. if( once ) printf("VDBE Query Plan:\n");
  76689. printf("%s\n", aOp[i].p4.z);
  76690. once = 0;
  76691. }
  76692. }
  76693. }
  76694. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  76695. }
  76696. sqlite3EndBenignMalloc();
  76697. #endif
  76698. for(pOp=&aOp[p->pc]; 1; pOp++){
  76699. /* Errors are detected by individual opcodes, with an immediate
  76700. ** jumps to abort_due_to_error. */
  76701. assert( rc==SQLITE_OK );
  76702. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  76703. #ifdef VDBE_PROFILE
  76704. start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  76705. #endif
  76706. nVmStep++;
  76707. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  76708. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  76709. #endif
  76710. /* Only allow tracing if SQLITE_DEBUG is defined.
  76711. */
  76712. #ifdef SQLITE_DEBUG
  76713. if( db->flags & SQLITE_VdbeTrace ){
  76714. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  76715. }
  76716. #endif
  76717. /* Check to see if we need to simulate an interrupt. This only happens
  76718. ** if we have a special test build.
  76719. */
  76720. #ifdef SQLITE_TEST
  76721. if( sqlite3_interrupt_count>0 ){
  76722. sqlite3_interrupt_count--;
  76723. if( sqlite3_interrupt_count==0 ){
  76724. sqlite3_interrupt(db);
  76725. }
  76726. }
  76727. #endif
  76728. /* Sanity checking on other operands */
  76729. #ifdef SQLITE_DEBUG
  76730. {
  76731. u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
  76732. if( (opProperty & OPFLG_IN1)!=0 ){
  76733. assert( pOp->p1>0 );
  76734. assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
  76735. assert( memIsValid(&aMem[pOp->p1]) );
  76736. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  76737. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  76738. }
  76739. if( (opProperty & OPFLG_IN2)!=0 ){
  76740. assert( pOp->p2>0 );
  76741. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  76742. assert( memIsValid(&aMem[pOp->p2]) );
  76743. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  76744. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  76745. }
  76746. if( (opProperty & OPFLG_IN3)!=0 ){
  76747. assert( pOp->p3>0 );
  76748. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  76749. assert( memIsValid(&aMem[pOp->p3]) );
  76750. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  76751. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  76752. }
  76753. if( (opProperty & OPFLG_OUT2)!=0 ){
  76754. assert( pOp->p2>0 );
  76755. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  76756. memAboutToChange(p, &aMem[pOp->p2]);
  76757. }
  76758. if( (opProperty & OPFLG_OUT3)!=0 ){
  76759. assert( pOp->p3>0 );
  76760. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  76761. memAboutToChange(p, &aMem[pOp->p3]);
  76762. }
  76763. }
  76764. #endif
  76765. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  76766. pOrigOp = pOp;
  76767. #endif
  76768. switch( pOp->opcode ){
  76769. /*****************************************************************************
  76770. ** What follows is a massive switch statement where each case implements a
  76771. ** separate instruction in the virtual machine. If we follow the usual
  76772. ** indentation conventions, each case should be indented by 6 spaces. But
  76773. ** that is a lot of wasted space on the left margin. So the code within
  76774. ** the switch statement will break with convention and be flush-left. Another
  76775. ** big comment (similar to this one) will mark the point in the code where
  76776. ** we transition back to normal indentation.
  76777. **
  76778. ** The formatting of each case is important. The makefile for SQLite
  76779. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  76780. ** file looking for lines that begin with "case OP_". The opcodes.h files
  76781. ** will be filled with #defines that give unique integer values to each
  76782. ** opcode and the opcodes.c file is filled with an array of strings where
  76783. ** each string is the symbolic name for the corresponding opcode. If the
  76784. ** case statement is followed by a comment of the form "/# same as ... #/"
  76785. ** that comment is used to determine the particular value of the opcode.
  76786. **
  76787. ** Other keywords in the comment that follows each case are used to
  76788. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  76789. ** Keywords include: in1, in2, in3, out2, out3. See
  76790. ** the mkopcodeh.awk script for additional information.
  76791. **
  76792. ** Documentation about VDBE opcodes is generated by scanning this file
  76793. ** for lines of that contain "Opcode:". That line and all subsequent
  76794. ** comment lines are used in the generation of the opcode.html documentation
  76795. ** file.
  76796. **
  76797. ** SUMMARY:
  76798. **
  76799. ** Formatting is important to scripts that scan this file.
  76800. ** Do not deviate from the formatting style currently in use.
  76801. **
  76802. *****************************************************************************/
  76803. /* Opcode: Goto * P2 * * *
  76804. **
  76805. ** An unconditional jump to address P2.
  76806. ** The next instruction executed will be
  76807. ** the one at index P2 from the beginning of
  76808. ** the program.
  76809. **
  76810. ** The P1 parameter is not actually used by this opcode. However, it
  76811. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  76812. ** that this Goto is the bottom of a loop and that the lines from P2 down
  76813. ** to the current line should be indented for EXPLAIN output.
  76814. */
  76815. case OP_Goto: { /* jump */
  76816. jump_to_p2_and_check_for_interrupt:
  76817. pOp = &aOp[pOp->p2 - 1];
  76818. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  76819. ** OP_VNext, or OP_SorterNext) all jump here upon
  76820. ** completion. Check to see if sqlite3_interrupt() has been called
  76821. ** or if the progress callback needs to be invoked.
  76822. **
  76823. ** This code uses unstructured "goto" statements and does not look clean.
  76824. ** But that is not due to sloppy coding habits. The code is written this
  76825. ** way for performance, to avoid having to run the interrupt and progress
  76826. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  76827. ** faster according to "valgrind --tool=cachegrind" */
  76828. check_for_interrupt:
  76829. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  76830. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  76831. /* Call the progress callback if it is configured and the required number
  76832. ** of VDBE ops have been executed (either since this invocation of
  76833. ** sqlite3VdbeExec() or since last time the progress callback was called).
  76834. ** If the progress callback returns non-zero, exit the virtual machine with
  76835. ** a return code SQLITE_ABORT.
  76836. */
  76837. if( nVmStep>=nProgressLimit && db->xProgress!=0 ){
  76838. assert( db->nProgressOps!=0 );
  76839. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  76840. if( db->xProgress(db->pProgressArg) ){
  76841. rc = SQLITE_INTERRUPT;
  76842. goto abort_due_to_error;
  76843. }
  76844. }
  76845. #endif
  76846. break;
  76847. }
  76848. /* Opcode: Gosub P1 P2 * * *
  76849. **
  76850. ** Write the current address onto register P1
  76851. ** and then jump to address P2.
  76852. */
  76853. case OP_Gosub: { /* jump */
  76854. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  76855. pIn1 = &aMem[pOp->p1];
  76856. assert( VdbeMemDynamic(pIn1)==0 );
  76857. memAboutToChange(p, pIn1);
  76858. pIn1->flags = MEM_Int;
  76859. pIn1->u.i = (int)(pOp-aOp);
  76860. REGISTER_TRACE(pOp->p1, pIn1);
  76861. /* Most jump operations do a goto to this spot in order to update
  76862. ** the pOp pointer. */
  76863. jump_to_p2:
  76864. pOp = &aOp[pOp->p2 - 1];
  76865. break;
  76866. }
  76867. /* Opcode: Return P1 * * * *
  76868. **
  76869. ** Jump to the next instruction after the address in register P1. After
  76870. ** the jump, register P1 becomes undefined.
  76871. */
  76872. case OP_Return: { /* in1 */
  76873. pIn1 = &aMem[pOp->p1];
  76874. assert( pIn1->flags==MEM_Int );
  76875. pOp = &aOp[pIn1->u.i];
  76876. pIn1->flags = MEM_Undefined;
  76877. break;
  76878. }
  76879. /* Opcode: InitCoroutine P1 P2 P3 * *
  76880. **
  76881. ** Set up register P1 so that it will Yield to the coroutine
  76882. ** located at address P3.
  76883. **
  76884. ** If P2!=0 then the coroutine implementation immediately follows
  76885. ** this opcode. So jump over the coroutine implementation to
  76886. ** address P2.
  76887. **
  76888. ** See also: EndCoroutine
  76889. */
  76890. case OP_InitCoroutine: { /* jump */
  76891. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  76892. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  76893. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  76894. pOut = &aMem[pOp->p1];
  76895. assert( !VdbeMemDynamic(pOut) );
  76896. pOut->u.i = pOp->p3 - 1;
  76897. pOut->flags = MEM_Int;
  76898. if( pOp->p2 ) goto jump_to_p2;
  76899. break;
  76900. }
  76901. /* Opcode: EndCoroutine P1 * * * *
  76902. **
  76903. ** The instruction at the address in register P1 is a Yield.
  76904. ** Jump to the P2 parameter of that Yield.
  76905. ** After the jump, register P1 becomes undefined.
  76906. **
  76907. ** See also: InitCoroutine
  76908. */
  76909. case OP_EndCoroutine: { /* in1 */
  76910. VdbeOp *pCaller;
  76911. pIn1 = &aMem[pOp->p1];
  76912. assert( pIn1->flags==MEM_Int );
  76913. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  76914. pCaller = &aOp[pIn1->u.i];
  76915. assert( pCaller->opcode==OP_Yield );
  76916. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  76917. pOp = &aOp[pCaller->p2 - 1];
  76918. pIn1->flags = MEM_Undefined;
  76919. break;
  76920. }
  76921. /* Opcode: Yield P1 P2 * * *
  76922. **
  76923. ** Swap the program counter with the value in register P1. This
  76924. ** has the effect of yielding to a coroutine.
  76925. **
  76926. ** If the coroutine that is launched by this instruction ends with
  76927. ** Yield or Return then continue to the next instruction. But if
  76928. ** the coroutine launched by this instruction ends with
  76929. ** EndCoroutine, then jump to P2 rather than continuing with the
  76930. ** next instruction.
  76931. **
  76932. ** See also: InitCoroutine
  76933. */
  76934. case OP_Yield: { /* in1, jump */
  76935. int pcDest;
  76936. pIn1 = &aMem[pOp->p1];
  76937. assert( VdbeMemDynamic(pIn1)==0 );
  76938. pIn1->flags = MEM_Int;
  76939. pcDest = (int)pIn1->u.i;
  76940. pIn1->u.i = (int)(pOp - aOp);
  76941. REGISTER_TRACE(pOp->p1, pIn1);
  76942. pOp = &aOp[pcDest];
  76943. break;
  76944. }
  76945. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  76946. ** Synopsis: if r[P3]=null halt
  76947. **
  76948. ** Check the value in register P3. If it is NULL then Halt using
  76949. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  76950. ** value in register P3 is not NULL, then this routine is a no-op.
  76951. ** The P5 parameter should be 1.
  76952. */
  76953. case OP_HaltIfNull: { /* in3 */
  76954. pIn3 = &aMem[pOp->p3];
  76955. if( (pIn3->flags & MEM_Null)==0 ) break;
  76956. /* Fall through into OP_Halt */
  76957. }
  76958. /* Opcode: Halt P1 P2 * P4 P5
  76959. **
  76960. ** Exit immediately. All open cursors, etc are closed
  76961. ** automatically.
  76962. **
  76963. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  76964. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  76965. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  76966. ** whether or not to rollback the current transaction. Do not rollback
  76967. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  76968. ** then back out all changes that have occurred during this execution of the
  76969. ** VDBE, but do not rollback the transaction.
  76970. **
  76971. ** If P4 is not null then it is an error message string.
  76972. **
  76973. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  76974. **
  76975. ** 0: (no change)
  76976. ** 1: NOT NULL contraint failed: P4
  76977. ** 2: UNIQUE constraint failed: P4
  76978. ** 3: CHECK constraint failed: P4
  76979. ** 4: FOREIGN KEY constraint failed: P4
  76980. **
  76981. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  76982. ** omitted.
  76983. **
  76984. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  76985. ** every program. So a jump past the last instruction of the program
  76986. ** is the same as executing Halt.
  76987. */
  76988. case OP_Halt: {
  76989. VdbeFrame *pFrame;
  76990. int pcx;
  76991. pcx = (int)(pOp - aOp);
  76992. if( pOp->p1==SQLITE_OK && p->pFrame ){
  76993. /* Halt the sub-program. Return control to the parent frame. */
  76994. pFrame = p->pFrame;
  76995. p->pFrame = pFrame->pParent;
  76996. p->nFrame--;
  76997. sqlite3VdbeSetChanges(db, p->nChange);
  76998. pcx = sqlite3VdbeFrameRestore(pFrame);
  76999. if( pOp->p2==OE_Ignore ){
  77000. /* Instruction pcx is the OP_Program that invoked the sub-program
  77001. ** currently being halted. If the p2 instruction of this OP_Halt
  77002. ** instruction is set to OE_Ignore, then the sub-program is throwing
  77003. ** an IGNORE exception. In this case jump to the address specified
  77004. ** as the p2 of the calling OP_Program. */
  77005. pcx = p->aOp[pcx].p2-1;
  77006. }
  77007. aOp = p->aOp;
  77008. aMem = p->aMem;
  77009. pOp = &aOp[pcx];
  77010. break;
  77011. }
  77012. p->rc = pOp->p1;
  77013. p->errorAction = (u8)pOp->p2;
  77014. p->pc = pcx;
  77015. assert( pOp->p5<=4 );
  77016. if( p->rc ){
  77017. if( pOp->p5 ){
  77018. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  77019. "FOREIGN KEY" };
  77020. testcase( pOp->p5==1 );
  77021. testcase( pOp->p5==2 );
  77022. testcase( pOp->p5==3 );
  77023. testcase( pOp->p5==4 );
  77024. sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
  77025. if( pOp->p4.z ){
  77026. p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
  77027. }
  77028. }else{
  77029. sqlite3VdbeError(p, "%s", pOp->p4.z);
  77030. }
  77031. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
  77032. }
  77033. rc = sqlite3VdbeHalt(p);
  77034. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  77035. if( rc==SQLITE_BUSY ){
  77036. p->rc = SQLITE_BUSY;
  77037. }else{
  77038. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  77039. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  77040. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  77041. }
  77042. goto vdbe_return;
  77043. }
  77044. /* Opcode: Integer P1 P2 * * *
  77045. ** Synopsis: r[P2]=P1
  77046. **
  77047. ** The 32-bit integer value P1 is written into register P2.
  77048. */
  77049. case OP_Integer: { /* out2 */
  77050. pOut = out2Prerelease(p, pOp);
  77051. pOut->u.i = pOp->p1;
  77052. break;
  77053. }
  77054. /* Opcode: Int64 * P2 * P4 *
  77055. ** Synopsis: r[P2]=P4
  77056. **
  77057. ** P4 is a pointer to a 64-bit integer value.
  77058. ** Write that value into register P2.
  77059. */
  77060. case OP_Int64: { /* out2 */
  77061. pOut = out2Prerelease(p, pOp);
  77062. assert( pOp->p4.pI64!=0 );
  77063. pOut->u.i = *pOp->p4.pI64;
  77064. break;
  77065. }
  77066. #ifndef SQLITE_OMIT_FLOATING_POINT
  77067. /* Opcode: Real * P2 * P4 *
  77068. ** Synopsis: r[P2]=P4
  77069. **
  77070. ** P4 is a pointer to a 64-bit floating point value.
  77071. ** Write that value into register P2.
  77072. */
  77073. case OP_Real: { /* same as TK_FLOAT, out2 */
  77074. pOut = out2Prerelease(p, pOp);
  77075. pOut->flags = MEM_Real;
  77076. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  77077. pOut->u.r = *pOp->p4.pReal;
  77078. break;
  77079. }
  77080. #endif
  77081. /* Opcode: String8 * P2 * P4 *
  77082. ** Synopsis: r[P2]='P4'
  77083. **
  77084. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  77085. ** into a String opcode before it is executed for the first time. During
  77086. ** this transformation, the length of string P4 is computed and stored
  77087. ** as the P1 parameter.
  77088. */
  77089. case OP_String8: { /* same as TK_STRING, out2 */
  77090. assert( pOp->p4.z!=0 );
  77091. pOut = out2Prerelease(p, pOp);
  77092. pOp->opcode = OP_String;
  77093. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  77094. #ifndef SQLITE_OMIT_UTF16
  77095. if( encoding!=SQLITE_UTF8 ){
  77096. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  77097. assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
  77098. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  77099. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  77100. assert( VdbeMemDynamic(pOut)==0 );
  77101. pOut->szMalloc = 0;
  77102. pOut->flags |= MEM_Static;
  77103. if( pOp->p4type==P4_DYNAMIC ){
  77104. sqlite3DbFree(db, pOp->p4.z);
  77105. }
  77106. pOp->p4type = P4_DYNAMIC;
  77107. pOp->p4.z = pOut->z;
  77108. pOp->p1 = pOut->n;
  77109. }
  77110. testcase( rc==SQLITE_TOOBIG );
  77111. #endif
  77112. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  77113. goto too_big;
  77114. }
  77115. assert( rc==SQLITE_OK );
  77116. /* Fall through to the next case, OP_String */
  77117. }
  77118. /* Opcode: String P1 P2 P3 P4 P5
  77119. ** Synopsis: r[P2]='P4' (len=P1)
  77120. **
  77121. ** The string value P4 of length P1 (bytes) is stored in register P2.
  77122. **
  77123. ** If P3 is not zero and the content of register P3 is equal to P5, then
  77124. ** the datatype of the register P2 is converted to BLOB. The content is
  77125. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  77126. ** of a string, as if it had been CAST. In other words:
  77127. **
  77128. ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
  77129. */
  77130. case OP_String: { /* out2 */
  77131. assert( pOp->p4.z!=0 );
  77132. pOut = out2Prerelease(p, pOp);
  77133. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  77134. pOut->z = pOp->p4.z;
  77135. pOut->n = pOp->p1;
  77136. pOut->enc = encoding;
  77137. UPDATE_MAX_BLOBSIZE(pOut);
  77138. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  77139. if( pOp->p3>0 ){
  77140. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  77141. pIn3 = &aMem[pOp->p3];
  77142. assert( pIn3->flags & MEM_Int );
  77143. if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  77144. }
  77145. #endif
  77146. break;
  77147. }
  77148. /* Opcode: Null P1 P2 P3 * *
  77149. ** Synopsis: r[P2..P3]=NULL
  77150. **
  77151. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  77152. ** NULL into register P3 and every register in between P2 and P3. If P3
  77153. ** is less than P2 (typically P3 is zero) then only register P2 is
  77154. ** set to NULL.
  77155. **
  77156. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  77157. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  77158. ** OP_Ne or OP_Eq.
  77159. */
  77160. case OP_Null: { /* out2 */
  77161. int cnt;
  77162. u16 nullFlag;
  77163. pOut = out2Prerelease(p, pOp);
  77164. cnt = pOp->p3-pOp->p2;
  77165. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  77166. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  77167. pOut->n = 0;
  77168. while( cnt>0 ){
  77169. pOut++;
  77170. memAboutToChange(p, pOut);
  77171. sqlite3VdbeMemSetNull(pOut);
  77172. pOut->flags = nullFlag;
  77173. pOut->n = 0;
  77174. cnt--;
  77175. }
  77176. break;
  77177. }
  77178. /* Opcode: SoftNull P1 * * * *
  77179. ** Synopsis: r[P1]=NULL
  77180. **
  77181. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  77182. ** instruction, but do not free any string or blob memory associated with
  77183. ** the register, so that if the value was a string or blob that was
  77184. ** previously copied using OP_SCopy, the copies will continue to be valid.
  77185. */
  77186. case OP_SoftNull: {
  77187. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  77188. pOut = &aMem[pOp->p1];
  77189. pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
  77190. break;
  77191. }
  77192. /* Opcode: Blob P1 P2 * P4 *
  77193. ** Synopsis: r[P2]=P4 (len=P1)
  77194. **
  77195. ** P4 points to a blob of data P1 bytes long. Store this
  77196. ** blob in register P2.
  77197. */
  77198. case OP_Blob: { /* out2 */
  77199. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  77200. pOut = out2Prerelease(p, pOp);
  77201. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  77202. pOut->enc = encoding;
  77203. UPDATE_MAX_BLOBSIZE(pOut);
  77204. break;
  77205. }
  77206. /* Opcode: Variable P1 P2 * P4 *
  77207. ** Synopsis: r[P2]=parameter(P1,P4)
  77208. **
  77209. ** Transfer the values of bound parameter P1 into register P2
  77210. **
  77211. ** If the parameter is named, then its name appears in P4.
  77212. ** The P4 value is used by sqlite3_bind_parameter_name().
  77213. */
  77214. case OP_Variable: { /* out2 */
  77215. Mem *pVar; /* Value being transferred */
  77216. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  77217. assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
  77218. pVar = &p->aVar[pOp->p1 - 1];
  77219. if( sqlite3VdbeMemTooBig(pVar) ){
  77220. goto too_big;
  77221. }
  77222. pOut = &aMem[pOp->p2];
  77223. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  77224. UPDATE_MAX_BLOBSIZE(pOut);
  77225. break;
  77226. }
  77227. /* Opcode: Move P1 P2 P3 * *
  77228. ** Synopsis: r[P2@P3]=r[P1@P3]
  77229. **
  77230. ** Move the P3 values in register P1..P1+P3-1 over into
  77231. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  77232. ** left holding a NULL. It is an error for register ranges
  77233. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  77234. ** for P3 to be less than 1.
  77235. */
  77236. case OP_Move: {
  77237. int n; /* Number of registers left to copy */
  77238. int p1; /* Register to copy from */
  77239. int p2; /* Register to copy to */
  77240. n = pOp->p3;
  77241. p1 = pOp->p1;
  77242. p2 = pOp->p2;
  77243. assert( n>0 && p1>0 && p2>0 );
  77244. assert( p1+n<=p2 || p2+n<=p1 );
  77245. pIn1 = &aMem[p1];
  77246. pOut = &aMem[p2];
  77247. do{
  77248. assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
  77249. assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
  77250. assert( memIsValid(pIn1) );
  77251. memAboutToChange(p, pOut);
  77252. sqlite3VdbeMemMove(pOut, pIn1);
  77253. #ifdef SQLITE_DEBUG
  77254. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  77255. pOut->pScopyFrom += pOp->p2 - p1;
  77256. }
  77257. #endif
  77258. Deephemeralize(pOut);
  77259. REGISTER_TRACE(p2++, pOut);
  77260. pIn1++;
  77261. pOut++;
  77262. }while( --n );
  77263. break;
  77264. }
  77265. /* Opcode: Copy P1 P2 P3 * *
  77266. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  77267. **
  77268. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  77269. **
  77270. ** This instruction makes a deep copy of the value. A duplicate
  77271. ** is made of any string or blob constant. See also OP_SCopy.
  77272. */
  77273. case OP_Copy: {
  77274. int n;
  77275. n = pOp->p3;
  77276. pIn1 = &aMem[pOp->p1];
  77277. pOut = &aMem[pOp->p2];
  77278. assert( pOut!=pIn1 );
  77279. while( 1 ){
  77280. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  77281. Deephemeralize(pOut);
  77282. #ifdef SQLITE_DEBUG
  77283. pOut->pScopyFrom = 0;
  77284. #endif
  77285. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  77286. if( (n--)==0 ) break;
  77287. pOut++;
  77288. pIn1++;
  77289. }
  77290. break;
  77291. }
  77292. /* Opcode: SCopy P1 P2 * * *
  77293. ** Synopsis: r[P2]=r[P1]
  77294. **
  77295. ** Make a shallow copy of register P1 into register P2.
  77296. **
  77297. ** This instruction makes a shallow copy of the value. If the value
  77298. ** is a string or blob, then the copy is only a pointer to the
  77299. ** original and hence if the original changes so will the copy.
  77300. ** Worse, if the original is deallocated, the copy becomes invalid.
  77301. ** Thus the program must guarantee that the original will not change
  77302. ** during the lifetime of the copy. Use OP_Copy to make a complete
  77303. ** copy.
  77304. */
  77305. case OP_SCopy: { /* out2 */
  77306. pIn1 = &aMem[pOp->p1];
  77307. pOut = &aMem[pOp->p2];
  77308. assert( pOut!=pIn1 );
  77309. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  77310. #ifdef SQLITE_DEBUG
  77311. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  77312. #endif
  77313. break;
  77314. }
  77315. /* Opcode: IntCopy P1 P2 * * *
  77316. ** Synopsis: r[P2]=r[P1]
  77317. **
  77318. ** Transfer the integer value held in register P1 into register P2.
  77319. **
  77320. ** This is an optimized version of SCopy that works only for integer
  77321. ** values.
  77322. */
  77323. case OP_IntCopy: { /* out2 */
  77324. pIn1 = &aMem[pOp->p1];
  77325. assert( (pIn1->flags & MEM_Int)!=0 );
  77326. pOut = &aMem[pOp->p2];
  77327. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  77328. break;
  77329. }
  77330. /* Opcode: ResultRow P1 P2 * * *
  77331. ** Synopsis: output=r[P1@P2]
  77332. **
  77333. ** The registers P1 through P1+P2-1 contain a single row of
  77334. ** results. This opcode causes the sqlite3_step() call to terminate
  77335. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  77336. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  77337. ** the result row.
  77338. */
  77339. case OP_ResultRow: {
  77340. Mem *pMem;
  77341. int i;
  77342. assert( p->nResColumn==pOp->p2 );
  77343. assert( pOp->p1>0 );
  77344. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  77345. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  77346. /* Run the progress counter just before returning.
  77347. */
  77348. if( db->xProgress!=0
  77349. && nVmStep>=nProgressLimit
  77350. && db->xProgress(db->pProgressArg)!=0
  77351. ){
  77352. rc = SQLITE_INTERRUPT;
  77353. goto abort_due_to_error;
  77354. }
  77355. #endif
  77356. /* If this statement has violated immediate foreign key constraints, do
  77357. ** not return the number of rows modified. And do not RELEASE the statement
  77358. ** transaction. It needs to be rolled back. */
  77359. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  77360. assert( db->flags&SQLITE_CountRows );
  77361. assert( p->usesStmtJournal );
  77362. goto abort_due_to_error;
  77363. }
  77364. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  77365. ** DML statements invoke this opcode to return the number of rows
  77366. ** modified to the user. This is the only way that a VM that
  77367. ** opens a statement transaction may invoke this opcode.
  77368. **
  77369. ** In case this is such a statement, close any statement transaction
  77370. ** opened by this VM before returning control to the user. This is to
  77371. ** ensure that statement-transactions are always nested, not overlapping.
  77372. ** If the open statement-transaction is not closed here, then the user
  77373. ** may step another VM that opens its own statement transaction. This
  77374. ** may lead to overlapping statement transactions.
  77375. **
  77376. ** The statement transaction is never a top-level transaction. Hence
  77377. ** the RELEASE call below can never fail.
  77378. */
  77379. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  77380. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  77381. assert( rc==SQLITE_OK );
  77382. /* Invalidate all ephemeral cursor row caches */
  77383. p->cacheCtr = (p->cacheCtr + 2)|1;
  77384. /* Make sure the results of the current row are \000 terminated
  77385. ** and have an assigned type. The results are de-ephemeralized as
  77386. ** a side effect.
  77387. */
  77388. pMem = p->pResultSet = &aMem[pOp->p1];
  77389. for(i=0; i<pOp->p2; i++){
  77390. assert( memIsValid(&pMem[i]) );
  77391. Deephemeralize(&pMem[i]);
  77392. assert( (pMem[i].flags & MEM_Ephem)==0
  77393. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  77394. sqlite3VdbeMemNulTerminate(&pMem[i]);
  77395. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  77396. }
  77397. if( db->mallocFailed ) goto no_mem;
  77398. if( db->mTrace & SQLITE_TRACE_ROW ){
  77399. db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
  77400. }
  77401. /* Return SQLITE_ROW
  77402. */
  77403. p->pc = (int)(pOp - aOp) + 1;
  77404. rc = SQLITE_ROW;
  77405. goto vdbe_return;
  77406. }
  77407. /* Opcode: Concat P1 P2 P3 * *
  77408. ** Synopsis: r[P3]=r[P2]+r[P1]
  77409. **
  77410. ** Add the text in register P1 onto the end of the text in
  77411. ** register P2 and store the result in register P3.
  77412. ** If either the P1 or P2 text are NULL then store NULL in P3.
  77413. **
  77414. ** P3 = P2 || P1
  77415. **
  77416. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  77417. ** if P3 is the same register as P2, the implementation is able
  77418. ** to avoid a memcpy().
  77419. */
  77420. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  77421. i64 nByte;
  77422. pIn1 = &aMem[pOp->p1];
  77423. pIn2 = &aMem[pOp->p2];
  77424. pOut = &aMem[pOp->p3];
  77425. assert( pIn1!=pOut );
  77426. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  77427. sqlite3VdbeMemSetNull(pOut);
  77428. break;
  77429. }
  77430. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  77431. Stringify(pIn1, encoding);
  77432. Stringify(pIn2, encoding);
  77433. nByte = pIn1->n + pIn2->n;
  77434. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  77435. goto too_big;
  77436. }
  77437. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  77438. goto no_mem;
  77439. }
  77440. MemSetTypeFlag(pOut, MEM_Str);
  77441. if( pOut!=pIn2 ){
  77442. memcpy(pOut->z, pIn2->z, pIn2->n);
  77443. }
  77444. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  77445. pOut->z[nByte]=0;
  77446. pOut->z[nByte+1] = 0;
  77447. pOut->flags |= MEM_Term;
  77448. pOut->n = (int)nByte;
  77449. pOut->enc = encoding;
  77450. UPDATE_MAX_BLOBSIZE(pOut);
  77451. break;
  77452. }
  77453. /* Opcode: Add P1 P2 P3 * *
  77454. ** Synopsis: r[P3]=r[P1]+r[P2]
  77455. **
  77456. ** Add the value in register P1 to the value in register P2
  77457. ** and store the result in register P3.
  77458. ** If either input is NULL, the result is NULL.
  77459. */
  77460. /* Opcode: Multiply P1 P2 P3 * *
  77461. ** Synopsis: r[P3]=r[P1]*r[P2]
  77462. **
  77463. **
  77464. ** Multiply the value in register P1 by the value in register P2
  77465. ** and store the result in register P3.
  77466. ** If either input is NULL, the result is NULL.
  77467. */
  77468. /* Opcode: Subtract P1 P2 P3 * *
  77469. ** Synopsis: r[P3]=r[P2]-r[P1]
  77470. **
  77471. ** Subtract the value in register P1 from the value in register P2
  77472. ** and store the result in register P3.
  77473. ** If either input is NULL, the result is NULL.
  77474. */
  77475. /* Opcode: Divide P1 P2 P3 * *
  77476. ** Synopsis: r[P3]=r[P2]/r[P1]
  77477. **
  77478. ** Divide the value in register P1 by the value in register P2
  77479. ** and store the result in register P3 (P3=P2/P1). If the value in
  77480. ** register P1 is zero, then the result is NULL. If either input is
  77481. ** NULL, the result is NULL.
  77482. */
  77483. /* Opcode: Remainder P1 P2 P3 * *
  77484. ** Synopsis: r[P3]=r[P2]%r[P1]
  77485. **
  77486. ** Compute the remainder after integer register P2 is divided by
  77487. ** register P1 and store the result in register P3.
  77488. ** If the value in register P1 is zero the result is NULL.
  77489. ** If either operand is NULL, the result is NULL.
  77490. */
  77491. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  77492. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  77493. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  77494. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  77495. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  77496. char bIntint; /* Started out as two integer operands */
  77497. u16 flags; /* Combined MEM_* flags from both inputs */
  77498. u16 type1; /* Numeric type of left operand */
  77499. u16 type2; /* Numeric type of right operand */
  77500. i64 iA; /* Integer value of left operand */
  77501. i64 iB; /* Integer value of right operand */
  77502. double rA; /* Real value of left operand */
  77503. double rB; /* Real value of right operand */
  77504. pIn1 = &aMem[pOp->p1];
  77505. type1 = numericType(pIn1);
  77506. pIn2 = &aMem[pOp->p2];
  77507. type2 = numericType(pIn2);
  77508. pOut = &aMem[pOp->p3];
  77509. flags = pIn1->flags | pIn2->flags;
  77510. if( (type1 & type2 & MEM_Int)!=0 ){
  77511. iA = pIn1->u.i;
  77512. iB = pIn2->u.i;
  77513. bIntint = 1;
  77514. switch( pOp->opcode ){
  77515. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  77516. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  77517. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  77518. case OP_Divide: {
  77519. if( iA==0 ) goto arithmetic_result_is_null;
  77520. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  77521. iB /= iA;
  77522. break;
  77523. }
  77524. default: {
  77525. if( iA==0 ) goto arithmetic_result_is_null;
  77526. if( iA==-1 ) iA = 1;
  77527. iB %= iA;
  77528. break;
  77529. }
  77530. }
  77531. pOut->u.i = iB;
  77532. MemSetTypeFlag(pOut, MEM_Int);
  77533. }else if( (flags & MEM_Null)!=0 ){
  77534. goto arithmetic_result_is_null;
  77535. }else{
  77536. bIntint = 0;
  77537. fp_math:
  77538. rA = sqlite3VdbeRealValue(pIn1);
  77539. rB = sqlite3VdbeRealValue(pIn2);
  77540. switch( pOp->opcode ){
  77541. case OP_Add: rB += rA; break;
  77542. case OP_Subtract: rB -= rA; break;
  77543. case OP_Multiply: rB *= rA; break;
  77544. case OP_Divide: {
  77545. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  77546. if( rA==(double)0 ) goto arithmetic_result_is_null;
  77547. rB /= rA;
  77548. break;
  77549. }
  77550. default: {
  77551. iA = (i64)rA;
  77552. iB = (i64)rB;
  77553. if( iA==0 ) goto arithmetic_result_is_null;
  77554. if( iA==-1 ) iA = 1;
  77555. rB = (double)(iB % iA);
  77556. break;
  77557. }
  77558. }
  77559. #ifdef SQLITE_OMIT_FLOATING_POINT
  77560. pOut->u.i = rB;
  77561. MemSetTypeFlag(pOut, MEM_Int);
  77562. #else
  77563. if( sqlite3IsNaN(rB) ){
  77564. goto arithmetic_result_is_null;
  77565. }
  77566. pOut->u.r = rB;
  77567. MemSetTypeFlag(pOut, MEM_Real);
  77568. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  77569. sqlite3VdbeIntegerAffinity(pOut);
  77570. }
  77571. #endif
  77572. }
  77573. break;
  77574. arithmetic_result_is_null:
  77575. sqlite3VdbeMemSetNull(pOut);
  77576. break;
  77577. }
  77578. /* Opcode: CollSeq P1 * * P4
  77579. **
  77580. ** P4 is a pointer to a CollSeq object. If the next call to a user function
  77581. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  77582. ** be returned. This is used by the built-in min(), max() and nullif()
  77583. ** functions.
  77584. **
  77585. ** If P1 is not zero, then it is a register that a subsequent min() or
  77586. ** max() aggregate will set to 1 if the current row is not the minimum or
  77587. ** maximum. The P1 register is initialized to 0 by this instruction.
  77588. **
  77589. ** The interface used by the implementation of the aforementioned functions
  77590. ** to retrieve the collation sequence set by this opcode is not available
  77591. ** publicly. Only built-in functions have access to this feature.
  77592. */
  77593. case OP_CollSeq: {
  77594. assert( pOp->p4type==P4_COLLSEQ );
  77595. if( pOp->p1 ){
  77596. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  77597. }
  77598. break;
  77599. }
  77600. /* Opcode: BitAnd P1 P2 P3 * *
  77601. ** Synopsis: r[P3]=r[P1]&r[P2]
  77602. **
  77603. ** Take the bit-wise AND of the values in register P1 and P2 and
  77604. ** store the result in register P3.
  77605. ** If either input is NULL, the result is NULL.
  77606. */
  77607. /* Opcode: BitOr P1 P2 P3 * *
  77608. ** Synopsis: r[P3]=r[P1]|r[P2]
  77609. **
  77610. ** Take the bit-wise OR of the values in register P1 and P2 and
  77611. ** store the result in register P3.
  77612. ** If either input is NULL, the result is NULL.
  77613. */
  77614. /* Opcode: ShiftLeft P1 P2 P3 * *
  77615. ** Synopsis: r[P3]=r[P2]<<r[P1]
  77616. **
  77617. ** Shift the integer value in register P2 to the left by the
  77618. ** number of bits specified by the integer in register P1.
  77619. ** Store the result in register P3.
  77620. ** If either input is NULL, the result is NULL.
  77621. */
  77622. /* Opcode: ShiftRight P1 P2 P3 * *
  77623. ** Synopsis: r[P3]=r[P2]>>r[P1]
  77624. **
  77625. ** Shift the integer value in register P2 to the right by the
  77626. ** number of bits specified by the integer in register P1.
  77627. ** Store the result in register P3.
  77628. ** If either input is NULL, the result is NULL.
  77629. */
  77630. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  77631. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  77632. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  77633. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  77634. i64 iA;
  77635. u64 uA;
  77636. i64 iB;
  77637. u8 op;
  77638. pIn1 = &aMem[pOp->p1];
  77639. pIn2 = &aMem[pOp->p2];
  77640. pOut = &aMem[pOp->p3];
  77641. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  77642. sqlite3VdbeMemSetNull(pOut);
  77643. break;
  77644. }
  77645. iA = sqlite3VdbeIntValue(pIn2);
  77646. iB = sqlite3VdbeIntValue(pIn1);
  77647. op = pOp->opcode;
  77648. if( op==OP_BitAnd ){
  77649. iA &= iB;
  77650. }else if( op==OP_BitOr ){
  77651. iA |= iB;
  77652. }else if( iB!=0 ){
  77653. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  77654. /* If shifting by a negative amount, shift in the other direction */
  77655. if( iB<0 ){
  77656. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  77657. op = 2*OP_ShiftLeft + 1 - op;
  77658. iB = iB>(-64) ? -iB : 64;
  77659. }
  77660. if( iB>=64 ){
  77661. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  77662. }else{
  77663. memcpy(&uA, &iA, sizeof(uA));
  77664. if( op==OP_ShiftLeft ){
  77665. uA <<= iB;
  77666. }else{
  77667. uA >>= iB;
  77668. /* Sign-extend on a right shift of a negative number */
  77669. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  77670. }
  77671. memcpy(&iA, &uA, sizeof(iA));
  77672. }
  77673. }
  77674. pOut->u.i = iA;
  77675. MemSetTypeFlag(pOut, MEM_Int);
  77676. break;
  77677. }
  77678. /* Opcode: AddImm P1 P2 * * *
  77679. ** Synopsis: r[P1]=r[P1]+P2
  77680. **
  77681. ** Add the constant P2 to the value in register P1.
  77682. ** The result is always an integer.
  77683. **
  77684. ** To force any register to be an integer, just add 0.
  77685. */
  77686. case OP_AddImm: { /* in1 */
  77687. pIn1 = &aMem[pOp->p1];
  77688. memAboutToChange(p, pIn1);
  77689. sqlite3VdbeMemIntegerify(pIn1);
  77690. pIn1->u.i += pOp->p2;
  77691. break;
  77692. }
  77693. /* Opcode: MustBeInt P1 P2 * * *
  77694. **
  77695. ** Force the value in register P1 to be an integer. If the value
  77696. ** in P1 is not an integer and cannot be converted into an integer
  77697. ** without data loss, then jump immediately to P2, or if P2==0
  77698. ** raise an SQLITE_MISMATCH exception.
  77699. */
  77700. case OP_MustBeInt: { /* jump, in1 */
  77701. pIn1 = &aMem[pOp->p1];
  77702. if( (pIn1->flags & MEM_Int)==0 ){
  77703. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  77704. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  77705. if( (pIn1->flags & MEM_Int)==0 ){
  77706. if( pOp->p2==0 ){
  77707. rc = SQLITE_MISMATCH;
  77708. goto abort_due_to_error;
  77709. }else{
  77710. goto jump_to_p2;
  77711. }
  77712. }
  77713. }
  77714. MemSetTypeFlag(pIn1, MEM_Int);
  77715. break;
  77716. }
  77717. #ifndef SQLITE_OMIT_FLOATING_POINT
  77718. /* Opcode: RealAffinity P1 * * * *
  77719. **
  77720. ** If register P1 holds an integer convert it to a real value.
  77721. **
  77722. ** This opcode is used when extracting information from a column that
  77723. ** has REAL affinity. Such column values may still be stored as
  77724. ** integers, for space efficiency, but after extraction we want them
  77725. ** to have only a real value.
  77726. */
  77727. case OP_RealAffinity: { /* in1 */
  77728. pIn1 = &aMem[pOp->p1];
  77729. if( pIn1->flags & MEM_Int ){
  77730. sqlite3VdbeMemRealify(pIn1);
  77731. }
  77732. break;
  77733. }
  77734. #endif
  77735. #ifndef SQLITE_OMIT_CAST
  77736. /* Opcode: Cast P1 P2 * * *
  77737. ** Synopsis: affinity(r[P1])
  77738. **
  77739. ** Force the value in register P1 to be the type defined by P2.
  77740. **
  77741. ** <ul>
  77742. ** <li> P2=='A' &rarr; BLOB
  77743. ** <li> P2=='B' &rarr; TEXT
  77744. ** <li> P2=='C' &rarr; NUMERIC
  77745. ** <li> P2=='D' &rarr; INTEGER
  77746. ** <li> P2=='E' &rarr; REAL
  77747. ** </ul>
  77748. **
  77749. ** A NULL value is not changed by this routine. It remains NULL.
  77750. */
  77751. case OP_Cast: { /* in1 */
  77752. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  77753. testcase( pOp->p2==SQLITE_AFF_TEXT );
  77754. testcase( pOp->p2==SQLITE_AFF_BLOB );
  77755. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  77756. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  77757. testcase( pOp->p2==SQLITE_AFF_REAL );
  77758. pIn1 = &aMem[pOp->p1];
  77759. memAboutToChange(p, pIn1);
  77760. rc = ExpandBlob(pIn1);
  77761. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  77762. UPDATE_MAX_BLOBSIZE(pIn1);
  77763. if( rc ) goto abort_due_to_error;
  77764. break;
  77765. }
  77766. #endif /* SQLITE_OMIT_CAST */
  77767. /* Opcode: Eq P1 P2 P3 P4 P5
  77768. ** Synopsis: IF r[P3]==r[P1]
  77769. **
  77770. ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
  77771. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
  77772. ** store the result of comparison in register P2.
  77773. **
  77774. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  77775. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  77776. ** to coerce both inputs according to this affinity before the
  77777. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  77778. ** affinity is used. Note that the affinity conversions are stored
  77779. ** back into the input registers P1 and P3. So this opcode can cause
  77780. ** persistent changes to registers P1 and P3.
  77781. **
  77782. ** Once any conversions have taken place, and neither value is NULL,
  77783. ** the values are compared. If both values are blobs then memcmp() is
  77784. ** used to determine the results of the comparison. If both values
  77785. ** are text, then the appropriate collating function specified in
  77786. ** P4 is used to do the comparison. If P4 is not specified then
  77787. ** memcmp() is used to compare text string. If both values are
  77788. ** numeric, then a numeric comparison is used. If the two values
  77789. ** are of different types, then numbers are considered less than
  77790. ** strings and strings are considered less than blobs.
  77791. **
  77792. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  77793. ** true or false and is never NULL. If both operands are NULL then the result
  77794. ** of comparison is true. If either operand is NULL then the result is false.
  77795. ** If neither operand is NULL the result is the same as it would be if
  77796. ** the SQLITE_NULLEQ flag were omitted from P5.
  77797. **
  77798. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  77799. ** content of r[P2] is only changed if the new value is NULL or 0 (false).
  77800. ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
  77801. */
  77802. /* Opcode: Ne P1 P2 P3 P4 P5
  77803. ** Synopsis: IF r[P3]!=r[P1]
  77804. **
  77805. ** This works just like the Eq opcode except that the jump is taken if
  77806. ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
  77807. ** additional information.
  77808. **
  77809. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  77810. ** content of r[P2] is only changed if the new value is NULL or 1 (true).
  77811. ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
  77812. */
  77813. /* Opcode: Lt P1 P2 P3 P4 P5
  77814. ** Synopsis: IF r[P3]<r[P1]
  77815. **
  77816. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  77817. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
  77818. ** the result of comparison (0 or 1 or NULL) into register P2.
  77819. **
  77820. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  77821. ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
  77822. ** bit is clear then fall through if either operand is NULL.
  77823. **
  77824. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  77825. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  77826. ** to coerce both inputs according to this affinity before the
  77827. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  77828. ** affinity is used. Note that the affinity conversions are stored
  77829. ** back into the input registers P1 and P3. So this opcode can cause
  77830. ** persistent changes to registers P1 and P3.
  77831. **
  77832. ** Once any conversions have taken place, and neither value is NULL,
  77833. ** the values are compared. If both values are blobs then memcmp() is
  77834. ** used to determine the results of the comparison. If both values
  77835. ** are text, then the appropriate collating function specified in
  77836. ** P4 is used to do the comparison. If P4 is not specified then
  77837. ** memcmp() is used to compare text string. If both values are
  77838. ** numeric, then a numeric comparison is used. If the two values
  77839. ** are of different types, then numbers are considered less than
  77840. ** strings and strings are considered less than blobs.
  77841. */
  77842. /* Opcode: Le P1 P2 P3 P4 P5
  77843. ** Synopsis: IF r[P3]<=r[P1]
  77844. **
  77845. ** This works just like the Lt opcode except that the jump is taken if
  77846. ** the content of register P3 is less than or equal to the content of
  77847. ** register P1. See the Lt opcode for additional information.
  77848. */
  77849. /* Opcode: Gt P1 P2 P3 P4 P5
  77850. ** Synopsis: IF r[P3]>r[P1]
  77851. **
  77852. ** This works just like the Lt opcode except that the jump is taken if
  77853. ** the content of register P3 is greater than the content of
  77854. ** register P1. See the Lt opcode for additional information.
  77855. */
  77856. /* Opcode: Ge P1 P2 P3 P4 P5
  77857. ** Synopsis: IF r[P3]>=r[P1]
  77858. **
  77859. ** This works just like the Lt opcode except that the jump is taken if
  77860. ** the content of register P3 is greater than or equal to the content of
  77861. ** register P1. See the Lt opcode for additional information.
  77862. */
  77863. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  77864. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  77865. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  77866. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  77867. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  77868. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  77869. int res, res2; /* Result of the comparison of pIn1 against pIn3 */
  77870. char affinity; /* Affinity to use for comparison */
  77871. u16 flags1; /* Copy of initial value of pIn1->flags */
  77872. u16 flags3; /* Copy of initial value of pIn3->flags */
  77873. pIn1 = &aMem[pOp->p1];
  77874. pIn3 = &aMem[pOp->p3];
  77875. flags1 = pIn1->flags;
  77876. flags3 = pIn3->flags;
  77877. if( (flags1 | flags3)&MEM_Null ){
  77878. /* One or both operands are NULL */
  77879. if( pOp->p5 & SQLITE_NULLEQ ){
  77880. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  77881. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  77882. ** or not both operands are null.
  77883. */
  77884. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  77885. assert( (flags1 & MEM_Cleared)==0 );
  77886. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  77887. if( (flags1&flags3&MEM_Null)!=0
  77888. && (flags3&MEM_Cleared)==0
  77889. ){
  77890. res = 0; /* Operands are equal */
  77891. }else{
  77892. res = 1; /* Operands are not equal */
  77893. }
  77894. }else{
  77895. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  77896. ** then the result is always NULL.
  77897. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  77898. */
  77899. if( pOp->p5 & SQLITE_STOREP2 ){
  77900. pOut = &aMem[pOp->p2];
  77901. iCompare = 1; /* Operands are not equal */
  77902. memAboutToChange(p, pOut);
  77903. MemSetTypeFlag(pOut, MEM_Null);
  77904. REGISTER_TRACE(pOp->p2, pOut);
  77905. }else{
  77906. VdbeBranchTaken(2,3);
  77907. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  77908. goto jump_to_p2;
  77909. }
  77910. }
  77911. break;
  77912. }
  77913. }else{
  77914. /* Neither operand is NULL. Do a comparison. */
  77915. affinity = pOp->p5 & SQLITE_AFF_MASK;
  77916. if( affinity>=SQLITE_AFF_NUMERIC ){
  77917. if( (flags1 | flags3)&MEM_Str ){
  77918. if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  77919. applyNumericAffinity(pIn1,0);
  77920. testcase( flags3!=pIn3->flags ); /* Possible if pIn1==pIn3 */
  77921. flags3 = pIn3->flags;
  77922. }
  77923. if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  77924. applyNumericAffinity(pIn3,0);
  77925. }
  77926. }
  77927. /* Handle the common case of integer comparison here, as an
  77928. ** optimization, to avoid a call to sqlite3MemCompare() */
  77929. if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
  77930. if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
  77931. if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
  77932. res = 0;
  77933. goto compare_op;
  77934. }
  77935. }else if( affinity==SQLITE_AFF_TEXT ){
  77936. if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
  77937. testcase( pIn1->flags & MEM_Int );
  77938. testcase( pIn1->flags & MEM_Real );
  77939. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  77940. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  77941. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  77942. assert( pIn1!=pIn3 );
  77943. }
  77944. if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
  77945. testcase( pIn3->flags & MEM_Int );
  77946. testcase( pIn3->flags & MEM_Real );
  77947. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  77948. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  77949. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  77950. }
  77951. }
  77952. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  77953. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  77954. }
  77955. compare_op:
  77956. /* At this point, res is negative, zero, or positive if reg[P1] is
  77957. ** less than, equal to, or greater than reg[P3], respectively. Compute
  77958. ** the answer to this operator in res2, depending on what the comparison
  77959. ** operator actually is. The next block of code depends on the fact
  77960. ** that the 6 comparison operators are consecutive integers in this
  77961. ** order: NE, EQ, GT, LE, LT, GE */
  77962. assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
  77963. assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
  77964. if( res<0 ){ /* ne, eq, gt, le, lt, ge */
  77965. static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
  77966. res2 = aLTb[pOp->opcode - OP_Ne];
  77967. }else if( res==0 ){
  77968. static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
  77969. res2 = aEQb[pOp->opcode - OP_Ne];
  77970. }else{
  77971. static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
  77972. res2 = aGTb[pOp->opcode - OP_Ne];
  77973. }
  77974. /* Undo any changes made by applyAffinity() to the input registers. */
  77975. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  77976. pIn1->flags = flags1;
  77977. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  77978. pIn3->flags = flags3;
  77979. if( pOp->p5 & SQLITE_STOREP2 ){
  77980. pOut = &aMem[pOp->p2];
  77981. iCompare = res;
  77982. if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
  77983. /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
  77984. ** and prevents OP_Ne from overwriting NULL with 0. This flag
  77985. ** is only used in contexts where either:
  77986. ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
  77987. ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
  77988. ** Therefore it is not necessary to check the content of r[P2] for
  77989. ** NULL. */
  77990. assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
  77991. assert( res2==0 || res2==1 );
  77992. testcase( res2==0 && pOp->opcode==OP_Eq );
  77993. testcase( res2==1 && pOp->opcode==OP_Eq );
  77994. testcase( res2==0 && pOp->opcode==OP_Ne );
  77995. testcase( res2==1 && pOp->opcode==OP_Ne );
  77996. if( (pOp->opcode==OP_Eq)==res2 ) break;
  77997. }
  77998. memAboutToChange(p, pOut);
  77999. MemSetTypeFlag(pOut, MEM_Int);
  78000. pOut->u.i = res2;
  78001. REGISTER_TRACE(pOp->p2, pOut);
  78002. }else{
  78003. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  78004. if( res2 ){
  78005. goto jump_to_p2;
  78006. }
  78007. }
  78008. break;
  78009. }
  78010. /* Opcode: ElseNotEq * P2 * * *
  78011. **
  78012. ** This opcode must immediately follow an OP_Lt or OP_Gt comparison operator.
  78013. ** If result of an OP_Eq comparison on the same two operands
  78014. ** would have be NULL or false (0), then then jump to P2.
  78015. ** If the result of an OP_Eq comparison on the two previous operands
  78016. ** would have been true (1), then fall through.
  78017. */
  78018. case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
  78019. assert( pOp>aOp );
  78020. assert( pOp[-1].opcode==OP_Lt || pOp[-1].opcode==OP_Gt );
  78021. assert( pOp[-1].p5 & SQLITE_STOREP2 );
  78022. VdbeBranchTaken(iCompare!=0, 2);
  78023. if( iCompare!=0 ) goto jump_to_p2;
  78024. break;
  78025. }
  78026. /* Opcode: Permutation * * * P4 *
  78027. **
  78028. ** Set the permutation used by the OP_Compare operator in the next
  78029. ** instruction. The permutation is stored in the P4 operand.
  78030. **
  78031. ** The permutation is only valid until the next OP_Compare that has
  78032. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  78033. ** occur immediately prior to the OP_Compare.
  78034. **
  78035. ** The first integer in the P4 integer array is the length of the array
  78036. ** and does not become part of the permutation.
  78037. */
  78038. case OP_Permutation: {
  78039. assert( pOp->p4type==P4_INTARRAY );
  78040. assert( pOp->p4.ai );
  78041. assert( pOp[1].opcode==OP_Compare );
  78042. assert( pOp[1].p5 & OPFLAG_PERMUTE );
  78043. break;
  78044. }
  78045. /* Opcode: Compare P1 P2 P3 P4 P5
  78046. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  78047. **
  78048. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  78049. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  78050. ** the comparison for use by the next OP_Jump instruct.
  78051. **
  78052. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  78053. ** determined by the most recent OP_Permutation operator. If the
  78054. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  78055. ** order.
  78056. **
  78057. ** P4 is a KeyInfo structure that defines collating sequences and sort
  78058. ** orders for the comparison. The permutation applies to registers
  78059. ** only. The KeyInfo elements are used sequentially.
  78060. **
  78061. ** The comparison is a sort comparison, so NULLs compare equal,
  78062. ** NULLs are less than numbers, numbers are less than strings,
  78063. ** and strings are less than blobs.
  78064. */
  78065. case OP_Compare: {
  78066. int n;
  78067. int i;
  78068. int p1;
  78069. int p2;
  78070. const KeyInfo *pKeyInfo;
  78071. int idx;
  78072. CollSeq *pColl; /* Collating sequence to use on this term */
  78073. int bRev; /* True for DESCENDING sort order */
  78074. int *aPermute; /* The permutation */
  78075. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
  78076. aPermute = 0;
  78077. }else{
  78078. assert( pOp>aOp );
  78079. assert( pOp[-1].opcode==OP_Permutation );
  78080. assert( pOp[-1].p4type==P4_INTARRAY );
  78081. aPermute = pOp[-1].p4.ai + 1;
  78082. assert( aPermute!=0 );
  78083. }
  78084. n = pOp->p3;
  78085. pKeyInfo = pOp->p4.pKeyInfo;
  78086. assert( n>0 );
  78087. assert( pKeyInfo!=0 );
  78088. p1 = pOp->p1;
  78089. p2 = pOp->p2;
  78090. #ifdef SQLITE_DEBUG
  78091. if( aPermute ){
  78092. int k, mx = 0;
  78093. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  78094. assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
  78095. assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
  78096. }else{
  78097. assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
  78098. assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
  78099. }
  78100. #endif /* SQLITE_DEBUG */
  78101. for(i=0; i<n; i++){
  78102. idx = aPermute ? aPermute[i] : i;
  78103. assert( memIsValid(&aMem[p1+idx]) );
  78104. assert( memIsValid(&aMem[p2+idx]) );
  78105. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  78106. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  78107. assert( i<pKeyInfo->nKeyField );
  78108. pColl = pKeyInfo->aColl[i];
  78109. bRev = pKeyInfo->aSortOrder[i];
  78110. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  78111. if( iCompare ){
  78112. if( bRev ) iCompare = -iCompare;
  78113. break;
  78114. }
  78115. }
  78116. break;
  78117. }
  78118. /* Opcode: Jump P1 P2 P3 * *
  78119. **
  78120. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  78121. ** in the most recent OP_Compare instruction the P1 vector was less than
  78122. ** equal to, or greater than the P2 vector, respectively.
  78123. */
  78124. case OP_Jump: { /* jump */
  78125. if( iCompare<0 ){
  78126. VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
  78127. }else if( iCompare==0 ){
  78128. VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
  78129. }else{
  78130. VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
  78131. }
  78132. break;
  78133. }
  78134. /* Opcode: And P1 P2 P3 * *
  78135. ** Synopsis: r[P3]=(r[P1] && r[P2])
  78136. **
  78137. ** Take the logical AND of the values in registers P1 and P2 and
  78138. ** write the result into register P3.
  78139. **
  78140. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  78141. ** the other input is NULL. A NULL and true or two NULLs give
  78142. ** a NULL output.
  78143. */
  78144. /* Opcode: Or P1 P2 P3 * *
  78145. ** Synopsis: r[P3]=(r[P1] || r[P2])
  78146. **
  78147. ** Take the logical OR of the values in register P1 and P2 and
  78148. ** store the answer in register P3.
  78149. **
  78150. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  78151. ** even if the other input is NULL. A NULL and false or two NULLs
  78152. ** give a NULL output.
  78153. */
  78154. case OP_And: /* same as TK_AND, in1, in2, out3 */
  78155. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  78156. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  78157. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  78158. v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
  78159. v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
  78160. if( pOp->opcode==OP_And ){
  78161. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  78162. v1 = and_logic[v1*3+v2];
  78163. }else{
  78164. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  78165. v1 = or_logic[v1*3+v2];
  78166. }
  78167. pOut = &aMem[pOp->p3];
  78168. if( v1==2 ){
  78169. MemSetTypeFlag(pOut, MEM_Null);
  78170. }else{
  78171. pOut->u.i = v1;
  78172. MemSetTypeFlag(pOut, MEM_Int);
  78173. }
  78174. break;
  78175. }
  78176. /* Opcode: IsTrue P1 P2 P3 P4 *
  78177. ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
  78178. **
  78179. ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
  78180. ** IS NOT FALSE operators.
  78181. **
  78182. ** Interpret the value in register P1 as a boolean value. Store that
  78183. ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
  78184. ** NULL, then the P3 is stored in register P2. Invert the answer if P4
  78185. ** is 1.
  78186. **
  78187. ** The logic is summarized like this:
  78188. **
  78189. ** <ul>
  78190. ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
  78191. ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
  78192. ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
  78193. ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
  78194. ** </ul>
  78195. */
  78196. case OP_IsTrue: { /* in1, out2 */
  78197. assert( pOp->p4type==P4_INT32 );
  78198. assert( pOp->p4.i==0 || pOp->p4.i==1 );
  78199. assert( pOp->p3==0 || pOp->p3==1 );
  78200. sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
  78201. sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
  78202. break;
  78203. }
  78204. /* Opcode: Not P1 P2 * * *
  78205. ** Synopsis: r[P2]= !r[P1]
  78206. **
  78207. ** Interpret the value in register P1 as a boolean value. Store the
  78208. ** boolean complement in register P2. If the value in register P1 is
  78209. ** NULL, then a NULL is stored in P2.
  78210. */
  78211. case OP_Not: { /* same as TK_NOT, in1, out2 */
  78212. pIn1 = &aMem[pOp->p1];
  78213. pOut = &aMem[pOp->p2];
  78214. if( (pIn1->flags & MEM_Null)==0 ){
  78215. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
  78216. }else{
  78217. sqlite3VdbeMemSetNull(pOut);
  78218. }
  78219. break;
  78220. }
  78221. /* Opcode: BitNot P1 P2 * * *
  78222. ** Synopsis: r[P1]= ~r[P1]
  78223. **
  78224. ** Interpret the content of register P1 as an integer. Store the
  78225. ** ones-complement of the P1 value into register P2. If P1 holds
  78226. ** a NULL then store a NULL in P2.
  78227. */
  78228. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  78229. pIn1 = &aMem[pOp->p1];
  78230. pOut = &aMem[pOp->p2];
  78231. sqlite3VdbeMemSetNull(pOut);
  78232. if( (pIn1->flags & MEM_Null)==0 ){
  78233. pOut->flags = MEM_Int;
  78234. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  78235. }
  78236. break;
  78237. }
  78238. /* Opcode: Once P1 P2 * * *
  78239. **
  78240. ** Fall through to the next instruction the first time this opcode is
  78241. ** encountered on each invocation of the byte-code program. Jump to P2
  78242. ** on the second and all subsequent encounters during the same invocation.
  78243. **
  78244. ** Top-level programs determine first invocation by comparing the P1
  78245. ** operand against the P1 operand on the OP_Init opcode at the beginning
  78246. ** of the program. If the P1 values differ, then fall through and make
  78247. ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
  78248. ** the same then take the jump.
  78249. **
  78250. ** For subprograms, there is a bitmask in the VdbeFrame that determines
  78251. ** whether or not the jump should be taken. The bitmask is necessary
  78252. ** because the self-altering code trick does not work for recursive
  78253. ** triggers.
  78254. */
  78255. case OP_Once: { /* jump */
  78256. u32 iAddr; /* Address of this instruction */
  78257. assert( p->aOp[0].opcode==OP_Init );
  78258. if( p->pFrame ){
  78259. iAddr = (int)(pOp - p->aOp);
  78260. if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
  78261. VdbeBranchTaken(1, 2);
  78262. goto jump_to_p2;
  78263. }
  78264. p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
  78265. }else{
  78266. if( p->aOp[0].p1==pOp->p1 ){
  78267. VdbeBranchTaken(1, 2);
  78268. goto jump_to_p2;
  78269. }
  78270. }
  78271. VdbeBranchTaken(0, 2);
  78272. pOp->p1 = p->aOp[0].p1;
  78273. break;
  78274. }
  78275. /* Opcode: If P1 P2 P3 * *
  78276. **
  78277. ** Jump to P2 if the value in register P1 is true. The value
  78278. ** is considered true if it is numeric and non-zero. If the value
  78279. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  78280. */
  78281. case OP_If: { /* jump, in1 */
  78282. int c;
  78283. c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
  78284. VdbeBranchTaken(c!=0, 2);
  78285. if( c ) goto jump_to_p2;
  78286. break;
  78287. }
  78288. /* Opcode: IfNot P1 P2 P3 * *
  78289. **
  78290. ** Jump to P2 if the value in register P1 is False. The value
  78291. ** is considered false if it has a numeric value of zero. If the value
  78292. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  78293. */
  78294. case OP_IfNot: { /* jump, in1 */
  78295. int c;
  78296. c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
  78297. VdbeBranchTaken(c!=0, 2);
  78298. if( c ) goto jump_to_p2;
  78299. break;
  78300. }
  78301. /* Opcode: IsNull P1 P2 * * *
  78302. ** Synopsis: if r[P1]==NULL goto P2
  78303. **
  78304. ** Jump to P2 if the value in register P1 is NULL.
  78305. */
  78306. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  78307. pIn1 = &aMem[pOp->p1];
  78308. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  78309. if( (pIn1->flags & MEM_Null)!=0 ){
  78310. goto jump_to_p2;
  78311. }
  78312. break;
  78313. }
  78314. /* Opcode: NotNull P1 P2 * * *
  78315. ** Synopsis: if r[P1]!=NULL goto P2
  78316. **
  78317. ** Jump to P2 if the value in register P1 is not NULL.
  78318. */
  78319. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  78320. pIn1 = &aMem[pOp->p1];
  78321. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  78322. if( (pIn1->flags & MEM_Null)==0 ){
  78323. goto jump_to_p2;
  78324. }
  78325. break;
  78326. }
  78327. /* Opcode: IfNullRow P1 P2 P3 * *
  78328. ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
  78329. **
  78330. ** Check the cursor P1 to see if it is currently pointing at a NULL row.
  78331. ** If it is, then set register P3 to NULL and jump immediately to P2.
  78332. ** If P1 is not on a NULL row, then fall through without making any
  78333. ** changes.
  78334. */
  78335. case OP_IfNullRow: { /* jump */
  78336. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78337. assert( p->apCsr[pOp->p1]!=0 );
  78338. if( p->apCsr[pOp->p1]->nullRow ){
  78339. sqlite3VdbeMemSetNull(aMem + pOp->p3);
  78340. goto jump_to_p2;
  78341. }
  78342. break;
  78343. }
  78344. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  78345. /* Opcode: Offset P1 P2 P3 * *
  78346. ** Synopsis: r[P3] = sqlite_offset(P1)
  78347. **
  78348. ** Store in register r[P3] the byte offset into the database file that is the
  78349. ** start of the payload for the record at which that cursor P1 is currently
  78350. ** pointing.
  78351. **
  78352. ** P2 is the column number for the argument to the sqlite_offset() function.
  78353. ** This opcode does not use P2 itself, but the P2 value is used by the
  78354. ** code generator. The P1, P2, and P3 operands to this opcode are the
  78355. ** same as for OP_Column.
  78356. **
  78357. ** This opcode is only available if SQLite is compiled with the
  78358. ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
  78359. */
  78360. case OP_Offset: { /* out3 */
  78361. VdbeCursor *pC; /* The VDBE cursor */
  78362. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78363. pC = p->apCsr[pOp->p1];
  78364. pOut = &p->aMem[pOp->p3];
  78365. if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
  78366. sqlite3VdbeMemSetNull(pOut);
  78367. }else{
  78368. sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
  78369. }
  78370. break;
  78371. }
  78372. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  78373. /* Opcode: Column P1 P2 P3 P4 P5
  78374. ** Synopsis: r[P3]=PX
  78375. **
  78376. ** Interpret the data that cursor P1 points to as a structure built using
  78377. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  78378. ** information about the format of the data.) Extract the P2-th column
  78379. ** from this record. If there are less that (P2+1)
  78380. ** values in the record, extract a NULL.
  78381. **
  78382. ** The value extracted is stored in register P3.
  78383. **
  78384. ** If the record contains fewer than P2 fields, then extract a NULL. Or,
  78385. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  78386. ** the result.
  78387. **
  78388. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  78389. ** then the cache of the cursor is reset prior to extracting the column.
  78390. ** The first OP_Column against a pseudo-table after the value of the content
  78391. ** register has changed should have this bit set.
  78392. **
  78393. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
  78394. ** the result is guaranteed to only be used as the argument of a length()
  78395. ** or typeof() function, respectively. The loading of large blobs can be
  78396. ** skipped for length() and all content loading can be skipped for typeof().
  78397. */
  78398. case OP_Column: {
  78399. int p2; /* column number to retrieve */
  78400. VdbeCursor *pC; /* The VDBE cursor */
  78401. BtCursor *pCrsr; /* The BTree cursor */
  78402. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  78403. int len; /* The length of the serialized data for the column */
  78404. int i; /* Loop counter */
  78405. Mem *pDest; /* Where to write the extracted value */
  78406. Mem sMem; /* For storing the record being decoded */
  78407. const u8 *zData; /* Part of the record being decoded */
  78408. const u8 *zHdr; /* Next unparsed byte of the header */
  78409. const u8 *zEndHdr; /* Pointer to first byte after the header */
  78410. u64 offset64; /* 64-bit offset */
  78411. u32 t; /* A type code from the record header */
  78412. Mem *pReg; /* PseudoTable input register */
  78413. pC = p->apCsr[pOp->p1];
  78414. p2 = pOp->p2;
  78415. /* If the cursor cache is stale (meaning it is not currently point at
  78416. ** the correct row) then bring it up-to-date by doing the necessary
  78417. ** B-Tree seek. */
  78418. rc = sqlite3VdbeCursorMoveto(&pC, &p2);
  78419. if( rc ) goto abort_due_to_error;
  78420. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  78421. pDest = &aMem[pOp->p3];
  78422. memAboutToChange(p, pDest);
  78423. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  78424. assert( pC!=0 );
  78425. assert( p2<pC->nField );
  78426. aOffset = pC->aOffset;
  78427. assert( pC->eCurType!=CURTYPE_VTAB );
  78428. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  78429. assert( pC->eCurType!=CURTYPE_SORTER );
  78430. if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
  78431. if( pC->nullRow ){
  78432. if( pC->eCurType==CURTYPE_PSEUDO ){
  78433. /* For the special case of as pseudo-cursor, the seekResult field
  78434. ** identifies the register that holds the record */
  78435. assert( pC->seekResult>0 );
  78436. pReg = &aMem[pC->seekResult];
  78437. assert( pReg->flags & MEM_Blob );
  78438. assert( memIsValid(pReg) );
  78439. pC->payloadSize = pC->szRow = pReg->n;
  78440. pC->aRow = (u8*)pReg->z;
  78441. }else{
  78442. sqlite3VdbeMemSetNull(pDest);
  78443. goto op_column_out;
  78444. }
  78445. }else{
  78446. pCrsr = pC->uc.pCursor;
  78447. assert( pC->eCurType==CURTYPE_BTREE );
  78448. assert( pCrsr );
  78449. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  78450. pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
  78451. pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
  78452. assert( pC->szRow<=pC->payloadSize );
  78453. assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
  78454. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  78455. goto too_big;
  78456. }
  78457. }
  78458. pC->cacheStatus = p->cacheCtr;
  78459. pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
  78460. pC->nHdrParsed = 0;
  78461. if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
  78462. /* pC->aRow does not have to hold the entire row, but it does at least
  78463. ** need to cover the header of the record. If pC->aRow does not contain
  78464. ** the complete header, then set it to zero, forcing the header to be
  78465. ** dynamically allocated. */
  78466. pC->aRow = 0;
  78467. pC->szRow = 0;
  78468. /* Make sure a corrupt database has not given us an oversize header.
  78469. ** Do this now to avoid an oversize memory allocation.
  78470. **
  78471. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  78472. ** types use so much data space that there can only be 4096 and 32 of
  78473. ** them, respectively. So the maximum header length results from a
  78474. ** 3-byte type for each of the maximum of 32768 columns plus three
  78475. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  78476. */
  78477. if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
  78478. goto op_column_corrupt;
  78479. }
  78480. }else{
  78481. /* This is an optimization. By skipping over the first few tests
  78482. ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
  78483. ** measurable performance gain.
  78484. **
  78485. ** This branch is taken even if aOffset[0]==0. Such a record is never
  78486. ** generated by SQLite, and could be considered corruption, but we
  78487. ** accept it for historical reasons. When aOffset[0]==0, the code this
  78488. ** branch jumps to reads past the end of the record, but never more
  78489. ** than a few bytes. Even if the record occurs at the end of the page
  78490. ** content area, the "page header" comes after the page content and so
  78491. ** this overread is harmless. Similar overreads can occur for a corrupt
  78492. ** database file.
  78493. */
  78494. zData = pC->aRow;
  78495. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  78496. testcase( aOffset[0]==0 );
  78497. goto op_column_read_header;
  78498. }
  78499. }
  78500. /* Make sure at least the first p2+1 entries of the header have been
  78501. ** parsed and valid information is in aOffset[] and pC->aType[].
  78502. */
  78503. if( pC->nHdrParsed<=p2 ){
  78504. /* If there is more header available for parsing in the record, try
  78505. ** to extract additional fields up through the p2+1-th field
  78506. */
  78507. if( pC->iHdrOffset<aOffset[0] ){
  78508. /* Make sure zData points to enough of the record to cover the header. */
  78509. if( pC->aRow==0 ){
  78510. memset(&sMem, 0, sizeof(sMem));
  78511. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, 0, aOffset[0], &sMem);
  78512. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  78513. zData = (u8*)sMem.z;
  78514. }else{
  78515. zData = pC->aRow;
  78516. }
  78517. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  78518. op_column_read_header:
  78519. i = pC->nHdrParsed;
  78520. offset64 = aOffset[i];
  78521. zHdr = zData + pC->iHdrOffset;
  78522. zEndHdr = zData + aOffset[0];
  78523. testcase( zHdr>=zEndHdr );
  78524. do{
  78525. if( (t = zHdr[0])<0x80 ){
  78526. zHdr++;
  78527. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  78528. }else{
  78529. zHdr += sqlite3GetVarint32(zHdr, &t);
  78530. offset64 += sqlite3VdbeSerialTypeLen(t);
  78531. }
  78532. pC->aType[i++] = t;
  78533. aOffset[i] = (u32)(offset64 & 0xffffffff);
  78534. }while( i<=p2 && zHdr<zEndHdr );
  78535. /* The record is corrupt if any of the following are true:
  78536. ** (1) the bytes of the header extend past the declared header size
  78537. ** (2) the entire header was used but not all data was used
  78538. ** (3) the end of the data extends beyond the end of the record.
  78539. */
  78540. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  78541. || (offset64 > pC->payloadSize)
  78542. ){
  78543. if( aOffset[0]==0 ){
  78544. i = 0;
  78545. zHdr = zEndHdr;
  78546. }else{
  78547. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  78548. goto op_column_corrupt;
  78549. }
  78550. }
  78551. pC->nHdrParsed = i;
  78552. pC->iHdrOffset = (u32)(zHdr - zData);
  78553. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  78554. }else{
  78555. t = 0;
  78556. }
  78557. /* If after trying to extract new entries from the header, nHdrParsed is
  78558. ** still not up to p2, that means that the record has fewer than p2
  78559. ** columns. So the result will be either the default value or a NULL.
  78560. */
  78561. if( pC->nHdrParsed<=p2 ){
  78562. if( pOp->p4type==P4_MEM ){
  78563. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  78564. }else{
  78565. sqlite3VdbeMemSetNull(pDest);
  78566. }
  78567. goto op_column_out;
  78568. }
  78569. }else{
  78570. t = pC->aType[p2];
  78571. }
  78572. /* Extract the content for the p2+1-th column. Control can only
  78573. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  78574. ** all valid.
  78575. */
  78576. assert( p2<pC->nHdrParsed );
  78577. assert( rc==SQLITE_OK );
  78578. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  78579. if( VdbeMemDynamic(pDest) ){
  78580. sqlite3VdbeMemSetNull(pDest);
  78581. }
  78582. assert( t==pC->aType[p2] );
  78583. if( pC->szRow>=aOffset[p2+1] ){
  78584. /* This is the common case where the desired content fits on the original
  78585. ** page - where the content is not on an overflow page */
  78586. zData = pC->aRow + aOffset[p2];
  78587. if( t<12 ){
  78588. sqlite3VdbeSerialGet(zData, t, pDest);
  78589. }else{
  78590. /* If the column value is a string, we need a persistent value, not
  78591. ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
  78592. ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
  78593. */
  78594. static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
  78595. pDest->n = len = (t-12)/2;
  78596. pDest->enc = encoding;
  78597. if( pDest->szMalloc < len+2 ){
  78598. pDest->flags = MEM_Null;
  78599. if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
  78600. }else{
  78601. pDest->z = pDest->zMalloc;
  78602. }
  78603. memcpy(pDest->z, zData, len);
  78604. pDest->z[len] = 0;
  78605. pDest->z[len+1] = 0;
  78606. pDest->flags = aFlag[t&1];
  78607. }
  78608. }else{
  78609. pDest->enc = encoding;
  78610. /* This branch happens only when content is on overflow pages */
  78611. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  78612. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  78613. || (len = sqlite3VdbeSerialTypeLen(t))==0
  78614. ){
  78615. /* Content is irrelevant for
  78616. ** 1. the typeof() function,
  78617. ** 2. the length(X) function if X is a blob, and
  78618. ** 3. if the content length is zero.
  78619. ** So we might as well use bogus content rather than reading
  78620. ** content from disk.
  78621. **
  78622. ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
  78623. ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
  78624. ** read up to 16. So 16 bytes of bogus content is supplied.
  78625. */
  78626. static u8 aZero[16]; /* This is the bogus content */
  78627. sqlite3VdbeSerialGet(aZero, t, pDest);
  78628. }else{
  78629. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
  78630. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  78631. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  78632. pDest->flags &= ~MEM_Ephem;
  78633. }
  78634. }
  78635. op_column_out:
  78636. UPDATE_MAX_BLOBSIZE(pDest);
  78637. REGISTER_TRACE(pOp->p3, pDest);
  78638. break;
  78639. op_column_corrupt:
  78640. if( aOp[0].p3>0 ){
  78641. pOp = &aOp[aOp[0].p3-1];
  78642. break;
  78643. }else{
  78644. rc = SQLITE_CORRUPT_BKPT;
  78645. goto abort_due_to_error;
  78646. }
  78647. }
  78648. /* Opcode: Affinity P1 P2 * P4 *
  78649. ** Synopsis: affinity(r[P1@P2])
  78650. **
  78651. ** Apply affinities to a range of P2 registers starting with P1.
  78652. **
  78653. ** P4 is a string that is P2 characters long. The N-th character of the
  78654. ** string indicates the column affinity that should be used for the N-th
  78655. ** memory cell in the range.
  78656. */
  78657. case OP_Affinity: {
  78658. const char *zAffinity; /* The affinity to be applied */
  78659. zAffinity = pOp->p4.z;
  78660. assert( zAffinity!=0 );
  78661. assert( pOp->p2>0 );
  78662. assert( zAffinity[pOp->p2]==0 );
  78663. pIn1 = &aMem[pOp->p1];
  78664. do{
  78665. assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
  78666. assert( memIsValid(pIn1) );
  78667. applyAffinity(pIn1, *(zAffinity++), encoding);
  78668. pIn1++;
  78669. }while( zAffinity[0] );
  78670. break;
  78671. }
  78672. /* Opcode: MakeRecord P1 P2 P3 P4 *
  78673. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  78674. **
  78675. ** Convert P2 registers beginning with P1 into the [record format]
  78676. ** use as a data record in a database table or as a key
  78677. ** in an index. The OP_Column opcode can decode the record later.
  78678. **
  78679. ** P4 may be a string that is P2 characters long. The N-th character of the
  78680. ** string indicates the column affinity that should be used for the N-th
  78681. ** field of the index key.
  78682. **
  78683. ** The mapping from character to affinity is given by the SQLITE_AFF_
  78684. ** macros defined in sqliteInt.h.
  78685. **
  78686. ** If P4 is NULL then all index fields have the affinity BLOB.
  78687. */
  78688. case OP_MakeRecord: {
  78689. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  78690. Mem *pRec; /* The new record */
  78691. u64 nData; /* Number of bytes of data space */
  78692. int nHdr; /* Number of bytes of header space */
  78693. i64 nByte; /* Data space required for this record */
  78694. i64 nZero; /* Number of zero bytes at the end of the record */
  78695. int nVarint; /* Number of bytes in a varint */
  78696. u32 serial_type; /* Type field */
  78697. Mem *pData0; /* First field to be combined into the record */
  78698. Mem *pLast; /* Last field of the record */
  78699. int nField; /* Number of fields in the record */
  78700. char *zAffinity; /* The affinity string for the record */
  78701. int file_format; /* File format to use for encoding */
  78702. int i; /* Space used in zNewRecord[] header */
  78703. int j; /* Space used in zNewRecord[] content */
  78704. u32 len; /* Length of a field */
  78705. /* Assuming the record contains N fields, the record format looks
  78706. ** like this:
  78707. **
  78708. ** ------------------------------------------------------------------------
  78709. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  78710. ** ------------------------------------------------------------------------
  78711. **
  78712. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  78713. ** and so forth.
  78714. **
  78715. ** Each type field is a varint representing the serial type of the
  78716. ** corresponding data element (see sqlite3VdbeSerialType()). The
  78717. ** hdr-size field is also a varint which is the offset from the beginning
  78718. ** of the record to data0.
  78719. */
  78720. nData = 0; /* Number of bytes of data space */
  78721. nHdr = 0; /* Number of bytes of header space */
  78722. nZero = 0; /* Number of zero bytes at the end of the record */
  78723. nField = pOp->p1;
  78724. zAffinity = pOp->p4.z;
  78725. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
  78726. pData0 = &aMem[nField];
  78727. nField = pOp->p2;
  78728. pLast = &pData0[nField-1];
  78729. file_format = p->minWriteFileFormat;
  78730. /* Identify the output register */
  78731. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  78732. pOut = &aMem[pOp->p3];
  78733. memAboutToChange(p, pOut);
  78734. /* Apply the requested affinity to all inputs
  78735. */
  78736. assert( pData0<=pLast );
  78737. if( zAffinity ){
  78738. pRec = pData0;
  78739. do{
  78740. applyAffinity(pRec++, *(zAffinity++), encoding);
  78741. assert( zAffinity[0]==0 || pRec<=pLast );
  78742. }while( zAffinity[0] );
  78743. }
  78744. #ifdef SQLITE_ENABLE_NULL_TRIM
  78745. /* NULLs can be safely trimmed from the end of the record, as long as
  78746. ** as the schema format is 2 or more and none of the omitted columns
  78747. ** have a non-NULL default value. Also, the record must be left with
  78748. ** at least one field. If P5>0 then it will be one more than the
  78749. ** index of the right-most column with a non-NULL default value */
  78750. if( pOp->p5 ){
  78751. while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
  78752. pLast--;
  78753. nField--;
  78754. }
  78755. }
  78756. #endif
  78757. /* Loop through the elements that will make up the record to figure
  78758. ** out how much space is required for the new record.
  78759. */
  78760. pRec = pLast;
  78761. do{
  78762. assert( memIsValid(pRec) );
  78763. serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
  78764. if( pRec->flags & MEM_Zero ){
  78765. if( serial_type==0 ){
  78766. /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
  78767. ** table methods that never invoke sqlite3_result_xxxxx() while
  78768. ** computing an unchanging column value in an UPDATE statement.
  78769. ** Give such values a special internal-use-only serial-type of 10
  78770. ** so that they can be passed through to xUpdate and have
  78771. ** a true sqlite3_value_nochange(). */
  78772. assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
  78773. serial_type = 10;
  78774. }else if( nData ){
  78775. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  78776. }else{
  78777. nZero += pRec->u.nZero;
  78778. len -= pRec->u.nZero;
  78779. }
  78780. }
  78781. nData += len;
  78782. testcase( serial_type==127 );
  78783. testcase( serial_type==128 );
  78784. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  78785. pRec->uTemp = serial_type;
  78786. if( pRec==pData0 ) break;
  78787. pRec--;
  78788. }while(1);
  78789. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  78790. ** which determines the total number of bytes in the header. The varint
  78791. ** value is the size of the header in bytes including the size varint
  78792. ** itself. */
  78793. testcase( nHdr==126 );
  78794. testcase( nHdr==127 );
  78795. if( nHdr<=126 ){
  78796. /* The common case */
  78797. nHdr += 1;
  78798. }else{
  78799. /* Rare case of a really large header */
  78800. nVarint = sqlite3VarintLen(nHdr);
  78801. nHdr += nVarint;
  78802. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  78803. }
  78804. nByte = nHdr+nData;
  78805. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  78806. goto too_big;
  78807. }
  78808. /* Make sure the output register has a buffer large enough to store
  78809. ** the new record. The output register (pOp->p3) is not allowed to
  78810. ** be one of the input registers (because the following call to
  78811. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  78812. */
  78813. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  78814. goto no_mem;
  78815. }
  78816. zNewRecord = (u8 *)pOut->z;
  78817. /* Write the record */
  78818. i = putVarint32(zNewRecord, nHdr);
  78819. j = nHdr;
  78820. assert( pData0<=pLast );
  78821. pRec = pData0;
  78822. do{
  78823. serial_type = pRec->uTemp;
  78824. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  78825. ** additional varints, one per column. */
  78826. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  78827. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  78828. ** immediately follow the header. */
  78829. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  78830. }while( (++pRec)<=pLast );
  78831. assert( i==nHdr );
  78832. assert( j==nByte );
  78833. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  78834. pOut->n = (int)nByte;
  78835. pOut->flags = MEM_Blob;
  78836. if( nZero ){
  78837. pOut->u.nZero = nZero;
  78838. pOut->flags |= MEM_Zero;
  78839. }
  78840. REGISTER_TRACE(pOp->p3, pOut);
  78841. UPDATE_MAX_BLOBSIZE(pOut);
  78842. break;
  78843. }
  78844. /* Opcode: Count P1 P2 * * *
  78845. ** Synopsis: r[P2]=count()
  78846. **
  78847. ** Store the number of entries (an integer value) in the table or index
  78848. ** opened by cursor P1 in register P2
  78849. */
  78850. #ifndef SQLITE_OMIT_BTREECOUNT
  78851. case OP_Count: { /* out2 */
  78852. i64 nEntry;
  78853. BtCursor *pCrsr;
  78854. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  78855. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  78856. assert( pCrsr );
  78857. nEntry = 0; /* Not needed. Only used to silence a warning. */
  78858. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  78859. if( rc ) goto abort_due_to_error;
  78860. pOut = out2Prerelease(p, pOp);
  78861. pOut->u.i = nEntry;
  78862. break;
  78863. }
  78864. #endif
  78865. /* Opcode: Savepoint P1 * * P4 *
  78866. **
  78867. ** Open, release or rollback the savepoint named by parameter P4, depending
  78868. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  78869. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  78870. */
  78871. case OP_Savepoint: {
  78872. int p1; /* Value of P1 operand */
  78873. char *zName; /* Name of savepoint */
  78874. int nName;
  78875. Savepoint *pNew;
  78876. Savepoint *pSavepoint;
  78877. Savepoint *pTmp;
  78878. int iSavepoint;
  78879. int ii;
  78880. p1 = pOp->p1;
  78881. zName = pOp->p4.z;
  78882. /* Assert that the p1 parameter is valid. Also that if there is no open
  78883. ** transaction, then there cannot be any savepoints.
  78884. */
  78885. assert( db->pSavepoint==0 || db->autoCommit==0 );
  78886. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  78887. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  78888. assert( checkSavepointCount(db) );
  78889. assert( p->bIsReader );
  78890. if( p1==SAVEPOINT_BEGIN ){
  78891. if( db->nVdbeWrite>0 ){
  78892. /* A new savepoint cannot be created if there are active write
  78893. ** statements (i.e. open read/write incremental blob handles).
  78894. */
  78895. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  78896. rc = SQLITE_BUSY;
  78897. }else{
  78898. nName = sqlite3Strlen30(zName);
  78899. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78900. /* This call is Ok even if this savepoint is actually a transaction
  78901. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  78902. ** If this is a transaction savepoint being opened, it is guaranteed
  78903. ** that the db->aVTrans[] array is empty. */
  78904. assert( db->autoCommit==0 || db->nVTrans==0 );
  78905. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  78906. db->nStatement+db->nSavepoint);
  78907. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  78908. #endif
  78909. /* Create a new savepoint structure. */
  78910. pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  78911. if( pNew ){
  78912. pNew->zName = (char *)&pNew[1];
  78913. memcpy(pNew->zName, zName, nName+1);
  78914. /* If there is no open transaction, then mark this as a special
  78915. ** "transaction savepoint". */
  78916. if( db->autoCommit ){
  78917. db->autoCommit = 0;
  78918. db->isTransactionSavepoint = 1;
  78919. }else{
  78920. db->nSavepoint++;
  78921. }
  78922. /* Link the new savepoint into the database handle's list. */
  78923. pNew->pNext = db->pSavepoint;
  78924. db->pSavepoint = pNew;
  78925. pNew->nDeferredCons = db->nDeferredCons;
  78926. pNew->nDeferredImmCons = db->nDeferredImmCons;
  78927. }
  78928. }
  78929. }else{
  78930. iSavepoint = 0;
  78931. /* Find the named savepoint. If there is no such savepoint, then an
  78932. ** an error is returned to the user. */
  78933. for(
  78934. pSavepoint = db->pSavepoint;
  78935. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  78936. pSavepoint = pSavepoint->pNext
  78937. ){
  78938. iSavepoint++;
  78939. }
  78940. if( !pSavepoint ){
  78941. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  78942. rc = SQLITE_ERROR;
  78943. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  78944. /* It is not possible to release (commit) a savepoint if there are
  78945. ** active write statements.
  78946. */
  78947. sqlite3VdbeError(p, "cannot release savepoint - "
  78948. "SQL statements in progress");
  78949. rc = SQLITE_BUSY;
  78950. }else{
  78951. /* Determine whether or not this is a transaction savepoint. If so,
  78952. ** and this is a RELEASE command, then the current transaction
  78953. ** is committed.
  78954. */
  78955. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  78956. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  78957. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  78958. goto vdbe_return;
  78959. }
  78960. db->autoCommit = 1;
  78961. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  78962. p->pc = (int)(pOp - aOp);
  78963. db->autoCommit = 0;
  78964. p->rc = rc = SQLITE_BUSY;
  78965. goto vdbe_return;
  78966. }
  78967. db->isTransactionSavepoint = 0;
  78968. rc = p->rc;
  78969. }else{
  78970. int isSchemaChange;
  78971. iSavepoint = db->nSavepoint - iSavepoint - 1;
  78972. if( p1==SAVEPOINT_ROLLBACK ){
  78973. isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
  78974. for(ii=0; ii<db->nDb; ii++){
  78975. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  78976. SQLITE_ABORT_ROLLBACK,
  78977. isSchemaChange==0);
  78978. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  78979. }
  78980. }else{
  78981. isSchemaChange = 0;
  78982. }
  78983. for(ii=0; ii<db->nDb; ii++){
  78984. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  78985. if( rc!=SQLITE_OK ){
  78986. goto abort_due_to_error;
  78987. }
  78988. }
  78989. if( isSchemaChange ){
  78990. sqlite3ExpirePreparedStatements(db);
  78991. sqlite3ResetAllSchemasOfConnection(db);
  78992. db->mDbFlags |= DBFLAG_SchemaChange;
  78993. }
  78994. }
  78995. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  78996. ** savepoints nested inside of the savepoint being operated on. */
  78997. while( db->pSavepoint!=pSavepoint ){
  78998. pTmp = db->pSavepoint;
  78999. db->pSavepoint = pTmp->pNext;
  79000. sqlite3DbFree(db, pTmp);
  79001. db->nSavepoint--;
  79002. }
  79003. /* If it is a RELEASE, then destroy the savepoint being operated on
  79004. ** too. If it is a ROLLBACK TO, then set the number of deferred
  79005. ** constraint violations present in the database to the value stored
  79006. ** when the savepoint was created. */
  79007. if( p1==SAVEPOINT_RELEASE ){
  79008. assert( pSavepoint==db->pSavepoint );
  79009. db->pSavepoint = pSavepoint->pNext;
  79010. sqlite3DbFree(db, pSavepoint);
  79011. if( !isTransaction ){
  79012. db->nSavepoint--;
  79013. }
  79014. }else{
  79015. db->nDeferredCons = pSavepoint->nDeferredCons;
  79016. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  79017. }
  79018. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  79019. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  79020. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  79021. }
  79022. }
  79023. }
  79024. if( rc ) goto abort_due_to_error;
  79025. break;
  79026. }
  79027. /* Opcode: AutoCommit P1 P2 * * *
  79028. **
  79029. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  79030. ** back any currently active btree transactions. If there are any active
  79031. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  79032. ** there are active writing VMs or active VMs that use shared cache.
  79033. **
  79034. ** This instruction causes the VM to halt.
  79035. */
  79036. case OP_AutoCommit: {
  79037. int desiredAutoCommit;
  79038. int iRollback;
  79039. desiredAutoCommit = pOp->p1;
  79040. iRollback = pOp->p2;
  79041. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  79042. assert( desiredAutoCommit==1 || iRollback==0 );
  79043. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  79044. assert( p->bIsReader );
  79045. if( desiredAutoCommit!=db->autoCommit ){
  79046. if( iRollback ){
  79047. assert( desiredAutoCommit==1 );
  79048. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  79049. db->autoCommit = 1;
  79050. }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
  79051. /* If this instruction implements a COMMIT and other VMs are writing
  79052. ** return an error indicating that the other VMs must complete first.
  79053. */
  79054. sqlite3VdbeError(p, "cannot commit transaction - "
  79055. "SQL statements in progress");
  79056. rc = SQLITE_BUSY;
  79057. goto abort_due_to_error;
  79058. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  79059. goto vdbe_return;
  79060. }else{
  79061. db->autoCommit = (u8)desiredAutoCommit;
  79062. }
  79063. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  79064. p->pc = (int)(pOp - aOp);
  79065. db->autoCommit = (u8)(1-desiredAutoCommit);
  79066. p->rc = rc = SQLITE_BUSY;
  79067. goto vdbe_return;
  79068. }
  79069. assert( db->nStatement==0 );
  79070. sqlite3CloseSavepoints(db);
  79071. if( p->rc==SQLITE_OK ){
  79072. rc = SQLITE_DONE;
  79073. }else{
  79074. rc = SQLITE_ERROR;
  79075. }
  79076. goto vdbe_return;
  79077. }else{
  79078. sqlite3VdbeError(p,
  79079. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  79080. (iRollback)?"cannot rollback - no transaction is active":
  79081. "cannot commit - no transaction is active"));
  79082. rc = SQLITE_ERROR;
  79083. goto abort_due_to_error;
  79084. }
  79085. break;
  79086. }
  79087. /* Opcode: Transaction P1 P2 P3 P4 P5
  79088. **
  79089. ** Begin a transaction on database P1 if a transaction is not already
  79090. ** active.
  79091. ** If P2 is non-zero, then a write-transaction is started, or if a
  79092. ** read-transaction is already active, it is upgraded to a write-transaction.
  79093. ** If P2 is zero, then a read-transaction is started.
  79094. **
  79095. ** P1 is the index of the database file on which the transaction is
  79096. ** started. Index 0 is the main database file and index 1 is the
  79097. ** file used for temporary tables. Indices of 2 or more are used for
  79098. ** attached databases.
  79099. **
  79100. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  79101. ** true (this flag is set if the Vdbe may modify more than one row and may
  79102. ** throw an ABORT exception), a statement transaction may also be opened.
  79103. ** More specifically, a statement transaction is opened iff the database
  79104. ** connection is currently not in autocommit mode, or if there are other
  79105. ** active statements. A statement transaction allows the changes made by this
  79106. ** VDBE to be rolled back after an error without having to roll back the
  79107. ** entire transaction. If no error is encountered, the statement transaction
  79108. ** will automatically commit when the VDBE halts.
  79109. **
  79110. ** If P5!=0 then this opcode also checks the schema cookie against P3
  79111. ** and the schema generation counter against P4.
  79112. ** The cookie changes its value whenever the database schema changes.
  79113. ** This operation is used to detect when that the cookie has changed
  79114. ** and that the current process needs to reread the schema. If the schema
  79115. ** cookie in P3 differs from the schema cookie in the database header or
  79116. ** if the schema generation counter in P4 differs from the current
  79117. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  79118. ** halts. The sqlite3_step() wrapper function might then reprepare the
  79119. ** statement and rerun it from the beginning.
  79120. */
  79121. case OP_Transaction: {
  79122. Btree *pBt;
  79123. int iMeta;
  79124. int iGen;
  79125. assert( p->bIsReader );
  79126. assert( p->readOnly==0 || pOp->p2==0 );
  79127. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  79128. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  79129. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  79130. rc = SQLITE_READONLY;
  79131. goto abort_due_to_error;
  79132. }
  79133. pBt = db->aDb[pOp->p1].pBt;
  79134. if( pBt ){
  79135. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  79136. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  79137. testcase( rc==SQLITE_BUSY_RECOVERY );
  79138. if( rc!=SQLITE_OK ){
  79139. if( (rc&0xff)==SQLITE_BUSY ){
  79140. p->pc = (int)(pOp - aOp);
  79141. p->rc = rc;
  79142. goto vdbe_return;
  79143. }
  79144. goto abort_due_to_error;
  79145. }
  79146. if( pOp->p2 && p->usesStmtJournal
  79147. && (db->autoCommit==0 || db->nVdbeRead>1)
  79148. ){
  79149. assert( sqlite3BtreeIsInTrans(pBt) );
  79150. if( p->iStatement==0 ){
  79151. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  79152. db->nStatement++;
  79153. p->iStatement = db->nSavepoint + db->nStatement;
  79154. }
  79155. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  79156. if( rc==SQLITE_OK ){
  79157. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  79158. }
  79159. /* Store the current value of the database handles deferred constraint
  79160. ** counter. If the statement transaction needs to be rolled back,
  79161. ** the value of this counter needs to be restored too. */
  79162. p->nStmtDefCons = db->nDeferredCons;
  79163. p->nStmtDefImmCons = db->nDeferredImmCons;
  79164. }
  79165. /* Gather the schema version number for checking:
  79166. ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
  79167. ** version is checked to ensure that the schema has not changed since the
  79168. ** SQL statement was prepared.
  79169. */
  79170. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  79171. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  79172. }else{
  79173. iGen = iMeta = 0;
  79174. }
  79175. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  79176. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  79177. sqlite3DbFree(db, p->zErrMsg);
  79178. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  79179. /* If the schema-cookie from the database file matches the cookie
  79180. ** stored with the in-memory representation of the schema, do
  79181. ** not reload the schema from the database file.
  79182. **
  79183. ** If virtual-tables are in use, this is not just an optimization.
  79184. ** Often, v-tables store their data in other SQLite tables, which
  79185. ** are queried from within xNext() and other v-table methods using
  79186. ** prepared queries. If such a query is out-of-date, we do not want to
  79187. ** discard the database schema, as the user code implementing the
  79188. ** v-table would have to be ready for the sqlite3_vtab structure itself
  79189. ** to be invalidated whenever sqlite3_step() is called from within
  79190. ** a v-table method.
  79191. */
  79192. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  79193. sqlite3ResetOneSchema(db, pOp->p1);
  79194. }
  79195. p->expired = 1;
  79196. rc = SQLITE_SCHEMA;
  79197. }
  79198. if( rc ) goto abort_due_to_error;
  79199. break;
  79200. }
  79201. /* Opcode: ReadCookie P1 P2 P3 * *
  79202. **
  79203. ** Read cookie number P3 from database P1 and write it into register P2.
  79204. ** P3==1 is the schema version. P3==2 is the database format.
  79205. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  79206. ** the main database file and P1==1 is the database file used to store
  79207. ** temporary tables.
  79208. **
  79209. ** There must be a read-lock on the database (either a transaction
  79210. ** must be started or there must be an open cursor) before
  79211. ** executing this instruction.
  79212. */
  79213. case OP_ReadCookie: { /* out2 */
  79214. int iMeta;
  79215. int iDb;
  79216. int iCookie;
  79217. assert( p->bIsReader );
  79218. iDb = pOp->p1;
  79219. iCookie = pOp->p3;
  79220. assert( pOp->p3<SQLITE_N_BTREE_META );
  79221. assert( iDb>=0 && iDb<db->nDb );
  79222. assert( db->aDb[iDb].pBt!=0 );
  79223. assert( DbMaskTest(p->btreeMask, iDb) );
  79224. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  79225. pOut = out2Prerelease(p, pOp);
  79226. pOut->u.i = iMeta;
  79227. break;
  79228. }
  79229. /* Opcode: SetCookie P1 P2 P3 * *
  79230. **
  79231. ** Write the integer value P3 into cookie number P2 of database P1.
  79232. ** P2==1 is the schema version. P2==2 is the database format.
  79233. ** P2==3 is the recommended pager cache
  79234. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  79235. ** database file used to store temporary tables.
  79236. **
  79237. ** A transaction must be started before executing this opcode.
  79238. */
  79239. case OP_SetCookie: {
  79240. Db *pDb;
  79241. assert( pOp->p2<SQLITE_N_BTREE_META );
  79242. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  79243. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  79244. assert( p->readOnly==0 );
  79245. pDb = &db->aDb[pOp->p1];
  79246. assert( pDb->pBt!=0 );
  79247. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  79248. /* See note about index shifting on OP_ReadCookie */
  79249. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
  79250. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  79251. /* When the schema cookie changes, record the new cookie internally */
  79252. pDb->pSchema->schema_cookie = pOp->p3;
  79253. db->mDbFlags |= DBFLAG_SchemaChange;
  79254. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  79255. /* Record changes in the file format */
  79256. pDb->pSchema->file_format = pOp->p3;
  79257. }
  79258. if( pOp->p1==1 ){
  79259. /* Invalidate all prepared statements whenever the TEMP database
  79260. ** schema is changed. Ticket #1644 */
  79261. sqlite3ExpirePreparedStatements(db);
  79262. p->expired = 0;
  79263. }
  79264. if( rc ) goto abort_due_to_error;
  79265. break;
  79266. }
  79267. /* Opcode: OpenRead P1 P2 P3 P4 P5
  79268. ** Synopsis: root=P2 iDb=P3
  79269. **
  79270. ** Open a read-only cursor for the database table whose root page is
  79271. ** P2 in a database file. The database file is determined by P3.
  79272. ** P3==0 means the main database, P3==1 means the database used for
  79273. ** temporary tables, and P3>1 means used the corresponding attached
  79274. ** database. Give the new cursor an identifier of P1. The P1
  79275. ** values need not be contiguous but all P1 values should be small integers.
  79276. ** It is an error for P1 to be negative.
  79277. **
  79278. ** If P5!=0 then use the content of register P2 as the root page, not
  79279. ** the value of P2 itself.
  79280. **
  79281. ** There will be a read lock on the database whenever there is an
  79282. ** open cursor. If the database was unlocked prior to this instruction
  79283. ** then a read lock is acquired as part of this instruction. A read
  79284. ** lock allows other processes to read the database but prohibits
  79285. ** any other process from modifying the database. The read lock is
  79286. ** released when all cursors are closed. If this instruction attempts
  79287. ** to get a read lock but fails, the script terminates with an
  79288. ** SQLITE_BUSY error code.
  79289. **
  79290. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  79291. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  79292. ** structure, then said structure defines the content and collating
  79293. ** sequence of the index being opened. Otherwise, if P4 is an integer
  79294. ** value, it is set to the number of columns in the table.
  79295. **
  79296. ** See also: OpenWrite, ReopenIdx
  79297. */
  79298. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  79299. ** Synopsis: root=P2 iDb=P3
  79300. **
  79301. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  79302. ** checks to see if the cursor on P1 is already open with a root page
  79303. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  79304. ** if the cursor is already open, do not reopen it.
  79305. **
  79306. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  79307. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  79308. ** every other ReopenIdx or OpenRead for the same cursor number.
  79309. **
  79310. ** See the OpenRead opcode documentation for additional information.
  79311. */
  79312. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  79313. ** Synopsis: root=P2 iDb=P3
  79314. **
  79315. ** Open a read/write cursor named P1 on the table or index whose root
  79316. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  79317. ** root page.
  79318. **
  79319. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  79320. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  79321. ** structure, then said structure defines the content and collating
  79322. ** sequence of the index being opened. Otherwise, if P4 is an integer
  79323. ** value, it is set to the number of columns in the table, or to the
  79324. ** largest index of any column of the table that is actually used.
  79325. **
  79326. ** This instruction works just like OpenRead except that it opens the cursor
  79327. ** in read/write mode. For a given table, there can be one or more read-only
  79328. ** cursors or a single read/write cursor but not both.
  79329. **
  79330. ** See also OpenRead.
  79331. */
  79332. case OP_ReopenIdx: {
  79333. int nField;
  79334. KeyInfo *pKeyInfo;
  79335. int p2;
  79336. int iDb;
  79337. int wrFlag;
  79338. Btree *pX;
  79339. VdbeCursor *pCur;
  79340. Db *pDb;
  79341. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  79342. assert( pOp->p4type==P4_KEYINFO );
  79343. pCur = p->apCsr[pOp->p1];
  79344. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  79345. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  79346. goto open_cursor_set_hints;
  79347. }
  79348. /* If the cursor is not currently open or is open on a different
  79349. ** index, then fall through into OP_OpenRead to force a reopen */
  79350. case OP_OpenRead:
  79351. case OP_OpenWrite:
  79352. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  79353. assert( p->bIsReader );
  79354. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  79355. || p->readOnly==0 );
  79356. if( p->expired ){
  79357. rc = SQLITE_ABORT_ROLLBACK;
  79358. goto abort_due_to_error;
  79359. }
  79360. nField = 0;
  79361. pKeyInfo = 0;
  79362. p2 = pOp->p2;
  79363. iDb = pOp->p3;
  79364. assert( iDb>=0 && iDb<db->nDb );
  79365. assert( DbMaskTest(p->btreeMask, iDb) );
  79366. pDb = &db->aDb[iDb];
  79367. pX = pDb->pBt;
  79368. assert( pX!=0 );
  79369. if( pOp->opcode==OP_OpenWrite ){
  79370. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  79371. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  79372. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  79373. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  79374. p->minWriteFileFormat = pDb->pSchema->file_format;
  79375. }
  79376. }else{
  79377. wrFlag = 0;
  79378. }
  79379. if( pOp->p5 & OPFLAG_P2ISREG ){
  79380. assert( p2>0 );
  79381. assert( p2<=(p->nMem+1 - p->nCursor) );
  79382. pIn2 = &aMem[p2];
  79383. assert( memIsValid(pIn2) );
  79384. assert( (pIn2->flags & MEM_Int)!=0 );
  79385. sqlite3VdbeMemIntegerify(pIn2);
  79386. p2 = (int)pIn2->u.i;
  79387. /* The p2 value always comes from a prior OP_CreateBtree opcode and
  79388. ** that opcode will always set the p2 value to 2 or more or else fail.
  79389. ** If there were a failure, the prepared statement would have halted
  79390. ** before reaching this instruction. */
  79391. assert( p2>=2 );
  79392. }
  79393. if( pOp->p4type==P4_KEYINFO ){
  79394. pKeyInfo = pOp->p4.pKeyInfo;
  79395. assert( pKeyInfo->enc==ENC(db) );
  79396. assert( pKeyInfo->db==db );
  79397. nField = pKeyInfo->nAllField;
  79398. }else if( pOp->p4type==P4_INT32 ){
  79399. nField = pOp->p4.i;
  79400. }
  79401. assert( pOp->p1>=0 );
  79402. assert( nField>=0 );
  79403. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  79404. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  79405. if( pCur==0 ) goto no_mem;
  79406. pCur->nullRow = 1;
  79407. pCur->isOrdered = 1;
  79408. pCur->pgnoRoot = p2;
  79409. #ifdef SQLITE_DEBUG
  79410. pCur->wrFlag = wrFlag;
  79411. #endif
  79412. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  79413. pCur->pKeyInfo = pKeyInfo;
  79414. /* Set the VdbeCursor.isTable variable. Previous versions of
  79415. ** SQLite used to check if the root-page flags were sane at this point
  79416. ** and report database corruption if they were not, but this check has
  79417. ** since moved into the btree layer. */
  79418. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  79419. open_cursor_set_hints:
  79420. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  79421. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  79422. testcase( pOp->p5 & OPFLAG_BULKCSR );
  79423. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  79424. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  79425. #endif
  79426. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  79427. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  79428. if( rc ) goto abort_due_to_error;
  79429. break;
  79430. }
  79431. /* Opcode: OpenDup P1 P2 * * *
  79432. **
  79433. ** Open a new cursor P1 that points to the same ephemeral table as
  79434. ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
  79435. ** opcode. Only ephemeral cursors may be duplicated.
  79436. **
  79437. ** Duplicate ephemeral cursors are used for self-joins of materialized views.
  79438. */
  79439. case OP_OpenDup: {
  79440. VdbeCursor *pOrig; /* The original cursor to be duplicated */
  79441. VdbeCursor *pCx; /* The new cursor */
  79442. pOrig = p->apCsr[pOp->p2];
  79443. assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
  79444. pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
  79445. if( pCx==0 ) goto no_mem;
  79446. pCx->nullRow = 1;
  79447. pCx->isEphemeral = 1;
  79448. pCx->pKeyInfo = pOrig->pKeyInfo;
  79449. pCx->isTable = pOrig->isTable;
  79450. rc = sqlite3BtreeCursor(pOrig->pBtx, MASTER_ROOT, BTREE_WRCSR,
  79451. pCx->pKeyInfo, pCx->uc.pCursor);
  79452. /* The sqlite3BtreeCursor() routine can only fail for the first cursor
  79453. ** opened for a database. Since there is already an open cursor when this
  79454. ** opcode is run, the sqlite3BtreeCursor() cannot fail */
  79455. assert( rc==SQLITE_OK );
  79456. break;
  79457. }
  79458. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  79459. ** Synopsis: nColumn=P2
  79460. **
  79461. ** Open a new cursor P1 to a transient table.
  79462. ** The cursor is always opened read/write even if
  79463. ** the main database is read-only. The ephemeral
  79464. ** table is deleted automatically when the cursor is closed.
  79465. **
  79466. ** P2 is the number of columns in the ephemeral table.
  79467. ** The cursor points to a BTree table if P4==0 and to a BTree index
  79468. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  79469. ** that defines the format of keys in the index.
  79470. **
  79471. ** The P5 parameter can be a mask of the BTREE_* flags defined
  79472. ** in btree.h. These flags control aspects of the operation of
  79473. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  79474. ** added automatically.
  79475. */
  79476. /* Opcode: OpenAutoindex P1 P2 * P4 *
  79477. ** Synopsis: nColumn=P2
  79478. **
  79479. ** This opcode works the same as OP_OpenEphemeral. It has a
  79480. ** different name to distinguish its use. Tables created using
  79481. ** by this opcode will be used for automatically created transient
  79482. ** indices in joins.
  79483. */
  79484. case OP_OpenAutoindex:
  79485. case OP_OpenEphemeral: {
  79486. VdbeCursor *pCx;
  79487. KeyInfo *pKeyInfo;
  79488. static const int vfsFlags =
  79489. SQLITE_OPEN_READWRITE |
  79490. SQLITE_OPEN_CREATE |
  79491. SQLITE_OPEN_EXCLUSIVE |
  79492. SQLITE_OPEN_DELETEONCLOSE |
  79493. SQLITE_OPEN_TRANSIENT_DB;
  79494. assert( pOp->p1>=0 );
  79495. assert( pOp->p2>=0 );
  79496. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  79497. if( pCx==0 ) goto no_mem;
  79498. pCx->nullRow = 1;
  79499. pCx->isEphemeral = 1;
  79500. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
  79501. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  79502. if( rc==SQLITE_OK ){
  79503. rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1);
  79504. }
  79505. if( rc==SQLITE_OK ){
  79506. /* If a transient index is required, create it by calling
  79507. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  79508. ** opening it. If a transient table is required, just use the
  79509. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  79510. */
  79511. if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  79512. int pgno;
  79513. assert( pOp->p4type==P4_KEYINFO );
  79514. rc = sqlite3BtreeCreateTable(pCx->pBtx, &pgno, BTREE_BLOBKEY | pOp->p5);
  79515. if( rc==SQLITE_OK ){
  79516. assert( pgno==MASTER_ROOT+1 );
  79517. assert( pKeyInfo->db==db );
  79518. assert( pKeyInfo->enc==ENC(db) );
  79519. rc = sqlite3BtreeCursor(pCx->pBtx, pgno, BTREE_WRCSR,
  79520. pKeyInfo, pCx->uc.pCursor);
  79521. }
  79522. pCx->isTable = 0;
  79523. }else{
  79524. rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
  79525. 0, pCx->uc.pCursor);
  79526. pCx->isTable = 1;
  79527. }
  79528. }
  79529. if( rc ) goto abort_due_to_error;
  79530. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  79531. break;
  79532. }
  79533. /* Opcode: SorterOpen P1 P2 P3 P4 *
  79534. **
  79535. ** This opcode works like OP_OpenEphemeral except that it opens
  79536. ** a transient index that is specifically designed to sort large
  79537. ** tables using an external merge-sort algorithm.
  79538. **
  79539. ** If argument P3 is non-zero, then it indicates that the sorter may
  79540. ** assume that a stable sort considering the first P3 fields of each
  79541. ** key is sufficient to produce the required results.
  79542. */
  79543. case OP_SorterOpen: {
  79544. VdbeCursor *pCx;
  79545. assert( pOp->p1>=0 );
  79546. assert( pOp->p2>=0 );
  79547. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  79548. if( pCx==0 ) goto no_mem;
  79549. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  79550. assert( pCx->pKeyInfo->db==db );
  79551. assert( pCx->pKeyInfo->enc==ENC(db) );
  79552. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  79553. if( rc ) goto abort_due_to_error;
  79554. break;
  79555. }
  79556. /* Opcode: SequenceTest P1 P2 * * *
  79557. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  79558. **
  79559. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  79560. ** to P2. Regardless of whether or not the jump is taken, increment the
  79561. ** the sequence value.
  79562. */
  79563. case OP_SequenceTest: {
  79564. VdbeCursor *pC;
  79565. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79566. pC = p->apCsr[pOp->p1];
  79567. assert( isSorter(pC) );
  79568. if( (pC->seqCount++)==0 ){
  79569. goto jump_to_p2;
  79570. }
  79571. break;
  79572. }
  79573. /* Opcode: OpenPseudo P1 P2 P3 * *
  79574. ** Synopsis: P3 columns in r[P2]
  79575. **
  79576. ** Open a new cursor that points to a fake table that contains a single
  79577. ** row of data. The content of that one row is the content of memory
  79578. ** register P2. In other words, cursor P1 becomes an alias for the
  79579. ** MEM_Blob content contained in register P2.
  79580. **
  79581. ** A pseudo-table created by this opcode is used to hold a single
  79582. ** row output from the sorter so that the row can be decomposed into
  79583. ** individual columns using the OP_Column opcode. The OP_Column opcode
  79584. ** is the only cursor opcode that works with a pseudo-table.
  79585. **
  79586. ** P3 is the number of fields in the records that will be stored by
  79587. ** the pseudo-table.
  79588. */
  79589. case OP_OpenPseudo: {
  79590. VdbeCursor *pCx;
  79591. assert( pOp->p1>=0 );
  79592. assert( pOp->p3>=0 );
  79593. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  79594. if( pCx==0 ) goto no_mem;
  79595. pCx->nullRow = 1;
  79596. pCx->seekResult = pOp->p2;
  79597. pCx->isTable = 1;
  79598. /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
  79599. ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
  79600. ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
  79601. ** which is a performance optimization */
  79602. pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
  79603. assert( pOp->p5==0 );
  79604. break;
  79605. }
  79606. /* Opcode: Close P1 * * * *
  79607. **
  79608. ** Close a cursor previously opened as P1. If P1 is not
  79609. ** currently open, this instruction is a no-op.
  79610. */
  79611. case OP_Close: {
  79612. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79613. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  79614. p->apCsr[pOp->p1] = 0;
  79615. break;
  79616. }
  79617. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  79618. /* Opcode: ColumnsUsed P1 * * P4 *
  79619. **
  79620. ** This opcode (which only exists if SQLite was compiled with
  79621. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  79622. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  79623. ** (P4_INT64) in which the first 63 bits are one for each of the
  79624. ** first 63 columns of the table or index that are actually used
  79625. ** by the cursor. The high-order bit is set if any column after
  79626. ** the 64th is used.
  79627. */
  79628. case OP_ColumnsUsed: {
  79629. VdbeCursor *pC;
  79630. pC = p->apCsr[pOp->p1];
  79631. assert( pC->eCurType==CURTYPE_BTREE );
  79632. pC->maskUsed = *(u64*)pOp->p4.pI64;
  79633. break;
  79634. }
  79635. #endif
  79636. /* Opcode: SeekGE P1 P2 P3 P4 *
  79637. ** Synopsis: key=r[P3@P4]
  79638. **
  79639. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  79640. ** use the value in register P3 as the key. If cursor P1 refers
  79641. ** to an SQL index, then P3 is the first in an array of P4 registers
  79642. ** that are used as an unpacked index key.
  79643. **
  79644. ** Reposition cursor P1 so that it points to the smallest entry that
  79645. ** is greater than or equal to the key value. If there are no records
  79646. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  79647. **
  79648. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  79649. ** opcode will always land on a record that equally equals the key, or
  79650. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  79651. ** opcode must be followed by an IdxLE opcode with the same arguments.
  79652. ** The IdxLE opcode will be skipped if this opcode succeeds, but the
  79653. ** IdxLE opcode will be used on subsequent loop iterations.
  79654. **
  79655. ** This opcode leaves the cursor configured to move in forward order,
  79656. ** from the beginning toward the end. In other words, the cursor is
  79657. ** configured to use Next, not Prev.
  79658. **
  79659. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  79660. */
  79661. /* Opcode: SeekGT P1 P2 P3 P4 *
  79662. ** Synopsis: key=r[P3@P4]
  79663. **
  79664. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  79665. ** use the value in register P3 as a key. If cursor P1 refers
  79666. ** to an SQL index, then P3 is the first in an array of P4 registers
  79667. ** that are used as an unpacked index key.
  79668. **
  79669. ** Reposition cursor P1 so that it points to the smallest entry that
  79670. ** is greater than the key value. If there are no records greater than
  79671. ** the key and P2 is not zero, then jump to P2.
  79672. **
  79673. ** This opcode leaves the cursor configured to move in forward order,
  79674. ** from the beginning toward the end. In other words, the cursor is
  79675. ** configured to use Next, not Prev.
  79676. **
  79677. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  79678. */
  79679. /* Opcode: SeekLT P1 P2 P3 P4 *
  79680. ** Synopsis: key=r[P3@P4]
  79681. **
  79682. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  79683. ** use the value in register P3 as a key. If cursor P1 refers
  79684. ** to an SQL index, then P3 is the first in an array of P4 registers
  79685. ** that are used as an unpacked index key.
  79686. **
  79687. ** Reposition cursor P1 so that it points to the largest entry that
  79688. ** is less than the key value. If there are no records less than
  79689. ** the key and P2 is not zero, then jump to P2.
  79690. **
  79691. ** This opcode leaves the cursor configured to move in reverse order,
  79692. ** from the end toward the beginning. In other words, the cursor is
  79693. ** configured to use Prev, not Next.
  79694. **
  79695. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  79696. */
  79697. /* Opcode: SeekLE P1 P2 P3 P4 *
  79698. ** Synopsis: key=r[P3@P4]
  79699. **
  79700. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  79701. ** use the value in register P3 as a key. If cursor P1 refers
  79702. ** to an SQL index, then P3 is the first in an array of P4 registers
  79703. ** that are used as an unpacked index key.
  79704. **
  79705. ** Reposition cursor P1 so that it points to the largest entry that
  79706. ** is less than or equal to the key value. If there are no records
  79707. ** less than or equal to the key and P2 is not zero, then jump to P2.
  79708. **
  79709. ** This opcode leaves the cursor configured to move in reverse order,
  79710. ** from the end toward the beginning. In other words, the cursor is
  79711. ** configured to use Prev, not Next.
  79712. **
  79713. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  79714. ** opcode will always land on a record that equally equals the key, or
  79715. ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
  79716. ** opcode must be followed by an IdxGE opcode with the same arguments.
  79717. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  79718. ** IdxGE opcode will be used on subsequent loop iterations.
  79719. **
  79720. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  79721. */
  79722. case OP_SeekLT: /* jump, in3 */
  79723. case OP_SeekLE: /* jump, in3 */
  79724. case OP_SeekGE: /* jump, in3 */
  79725. case OP_SeekGT: { /* jump, in3 */
  79726. int res; /* Comparison result */
  79727. int oc; /* Opcode */
  79728. VdbeCursor *pC; /* The cursor to seek */
  79729. UnpackedRecord r; /* The key to seek for */
  79730. int nField; /* Number of columns or fields in the key */
  79731. i64 iKey; /* The rowid we are to seek to */
  79732. int eqOnly; /* Only interested in == results */
  79733. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79734. assert( pOp->p2!=0 );
  79735. pC = p->apCsr[pOp->p1];
  79736. assert( pC!=0 );
  79737. assert( pC->eCurType==CURTYPE_BTREE );
  79738. assert( OP_SeekLE == OP_SeekLT+1 );
  79739. assert( OP_SeekGE == OP_SeekLT+2 );
  79740. assert( OP_SeekGT == OP_SeekLT+3 );
  79741. assert( pC->isOrdered );
  79742. assert( pC->uc.pCursor!=0 );
  79743. oc = pOp->opcode;
  79744. eqOnly = 0;
  79745. pC->nullRow = 0;
  79746. #ifdef SQLITE_DEBUG
  79747. pC->seekOp = pOp->opcode;
  79748. #endif
  79749. if( pC->isTable ){
  79750. /* The BTREE_SEEK_EQ flag is only set on index cursors */
  79751. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
  79752. || CORRUPT_DB );
  79753. /* The input value in P3 might be of any type: integer, real, string,
  79754. ** blob, or NULL. But it needs to be an integer before we can do
  79755. ** the seek, so convert it. */
  79756. pIn3 = &aMem[pOp->p3];
  79757. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  79758. applyNumericAffinity(pIn3, 0);
  79759. }
  79760. iKey = sqlite3VdbeIntValue(pIn3);
  79761. /* If the P3 value could not be converted into an integer without
  79762. ** loss of information, then special processing is required... */
  79763. if( (pIn3->flags & MEM_Int)==0 ){
  79764. if( (pIn3->flags & MEM_Real)==0 ){
  79765. /* If the P3 value cannot be converted into any kind of a number,
  79766. ** then the seek is not possible, so jump to P2 */
  79767. VdbeBranchTaken(1,2); goto jump_to_p2;
  79768. break;
  79769. }
  79770. /* If the approximation iKey is larger than the actual real search
  79771. ** term, substitute >= for > and < for <=. e.g. if the search term
  79772. ** is 4.9 and the integer approximation 5:
  79773. **
  79774. ** (x > 4.9) -> (x >= 5)
  79775. ** (x <= 4.9) -> (x < 5)
  79776. */
  79777. if( pIn3->u.r<(double)iKey ){
  79778. assert( OP_SeekGE==(OP_SeekGT-1) );
  79779. assert( OP_SeekLT==(OP_SeekLE-1) );
  79780. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  79781. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  79782. }
  79783. /* If the approximation iKey is smaller than the actual real search
  79784. ** term, substitute <= for < and > for >=. */
  79785. else if( pIn3->u.r>(double)iKey ){
  79786. assert( OP_SeekLE==(OP_SeekLT+1) );
  79787. assert( OP_SeekGT==(OP_SeekGE+1) );
  79788. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  79789. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  79790. }
  79791. }
  79792. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  79793. pC->movetoTarget = iKey; /* Used by OP_Delete */
  79794. if( rc!=SQLITE_OK ){
  79795. goto abort_due_to_error;
  79796. }
  79797. }else{
  79798. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  79799. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  79800. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  79801. */
  79802. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  79803. eqOnly = 1;
  79804. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  79805. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  79806. assert( pOp[1].p1==pOp[0].p1 );
  79807. assert( pOp[1].p2==pOp[0].p2 );
  79808. assert( pOp[1].p3==pOp[0].p3 );
  79809. assert( pOp[1].p4.i==pOp[0].p4.i );
  79810. }
  79811. nField = pOp->p4.i;
  79812. assert( pOp->p4type==P4_INT32 );
  79813. assert( nField>0 );
  79814. r.pKeyInfo = pC->pKeyInfo;
  79815. r.nField = (u16)nField;
  79816. /* The next line of code computes as follows, only faster:
  79817. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  79818. ** r.default_rc = -1;
  79819. ** }else{
  79820. ** r.default_rc = +1;
  79821. ** }
  79822. */
  79823. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  79824. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  79825. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  79826. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  79827. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  79828. r.aMem = &aMem[pOp->p3];
  79829. #ifdef SQLITE_DEBUG
  79830. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  79831. #endif
  79832. r.eqSeen = 0;
  79833. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  79834. if( rc!=SQLITE_OK ){
  79835. goto abort_due_to_error;
  79836. }
  79837. if( eqOnly && r.eqSeen==0 ){
  79838. assert( res!=0 );
  79839. goto seek_not_found;
  79840. }
  79841. }
  79842. pC->deferredMoveto = 0;
  79843. pC->cacheStatus = CACHE_STALE;
  79844. #ifdef SQLITE_TEST
  79845. sqlite3_search_count++;
  79846. #endif
  79847. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  79848. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  79849. res = 0;
  79850. rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
  79851. if( rc!=SQLITE_OK ){
  79852. if( rc==SQLITE_DONE ){
  79853. rc = SQLITE_OK;
  79854. res = 1;
  79855. }else{
  79856. goto abort_due_to_error;
  79857. }
  79858. }
  79859. }else{
  79860. res = 0;
  79861. }
  79862. }else{
  79863. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  79864. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  79865. res = 0;
  79866. rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
  79867. if( rc!=SQLITE_OK ){
  79868. if( rc==SQLITE_DONE ){
  79869. rc = SQLITE_OK;
  79870. res = 1;
  79871. }else{
  79872. goto abort_due_to_error;
  79873. }
  79874. }
  79875. }else{
  79876. /* res might be negative because the table is empty. Check to
  79877. ** see if this is the case.
  79878. */
  79879. res = sqlite3BtreeEof(pC->uc.pCursor);
  79880. }
  79881. }
  79882. seek_not_found:
  79883. assert( pOp->p2>0 );
  79884. VdbeBranchTaken(res!=0,2);
  79885. if( res ){
  79886. goto jump_to_p2;
  79887. }else if( eqOnly ){
  79888. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  79889. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  79890. }
  79891. break;
  79892. }
  79893. /* Opcode: Found P1 P2 P3 P4 *
  79894. ** Synopsis: key=r[P3@P4]
  79895. **
  79896. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  79897. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  79898. ** record.
  79899. **
  79900. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  79901. ** is a prefix of any entry in P1 then a jump is made to P2 and
  79902. ** P1 is left pointing at the matching entry.
  79903. **
  79904. ** This operation leaves the cursor in a state where it can be
  79905. ** advanced in the forward direction. The Next instruction will work,
  79906. ** but not the Prev instruction.
  79907. **
  79908. ** See also: NotFound, NoConflict, NotExists. SeekGe
  79909. */
  79910. /* Opcode: NotFound P1 P2 P3 P4 *
  79911. ** Synopsis: key=r[P3@P4]
  79912. **
  79913. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  79914. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  79915. ** record.
  79916. **
  79917. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  79918. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  79919. ** does contain an entry whose prefix matches the P3/P4 record then control
  79920. ** falls through to the next instruction and P1 is left pointing at the
  79921. ** matching entry.
  79922. **
  79923. ** This operation leaves the cursor in a state where it cannot be
  79924. ** advanced in either direction. In other words, the Next and Prev
  79925. ** opcodes do not work after this operation.
  79926. **
  79927. ** See also: Found, NotExists, NoConflict
  79928. */
  79929. /* Opcode: NoConflict P1 P2 P3 P4 *
  79930. ** Synopsis: key=r[P3@P4]
  79931. **
  79932. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  79933. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  79934. ** record.
  79935. **
  79936. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  79937. ** contains any NULL value, jump immediately to P2. If all terms of the
  79938. ** record are not-NULL then a check is done to determine if any row in the
  79939. ** P1 index btree has a matching key prefix. If there are no matches, jump
  79940. ** immediately to P2. If there is a match, fall through and leave the P1
  79941. ** cursor pointing to the matching row.
  79942. **
  79943. ** This opcode is similar to OP_NotFound with the exceptions that the
  79944. ** branch is always taken if any part of the search key input is NULL.
  79945. **
  79946. ** This operation leaves the cursor in a state where it cannot be
  79947. ** advanced in either direction. In other words, the Next and Prev
  79948. ** opcodes do not work after this operation.
  79949. **
  79950. ** See also: NotFound, Found, NotExists
  79951. */
  79952. case OP_NoConflict: /* jump, in3 */
  79953. case OP_NotFound: /* jump, in3 */
  79954. case OP_Found: { /* jump, in3 */
  79955. int alreadyExists;
  79956. int takeJump;
  79957. int ii;
  79958. VdbeCursor *pC;
  79959. int res;
  79960. UnpackedRecord *pFree;
  79961. UnpackedRecord *pIdxKey;
  79962. UnpackedRecord r;
  79963. #ifdef SQLITE_TEST
  79964. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  79965. #endif
  79966. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  79967. assert( pOp->p4type==P4_INT32 );
  79968. pC = p->apCsr[pOp->p1];
  79969. assert( pC!=0 );
  79970. #ifdef SQLITE_DEBUG
  79971. pC->seekOp = pOp->opcode;
  79972. #endif
  79973. pIn3 = &aMem[pOp->p3];
  79974. assert( pC->eCurType==CURTYPE_BTREE );
  79975. assert( pC->uc.pCursor!=0 );
  79976. assert( pC->isTable==0 );
  79977. if( pOp->p4.i>0 ){
  79978. r.pKeyInfo = pC->pKeyInfo;
  79979. r.nField = (u16)pOp->p4.i;
  79980. r.aMem = pIn3;
  79981. #ifdef SQLITE_DEBUG
  79982. for(ii=0; ii<r.nField; ii++){
  79983. assert( memIsValid(&r.aMem[ii]) );
  79984. assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
  79985. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  79986. }
  79987. #endif
  79988. pIdxKey = &r;
  79989. pFree = 0;
  79990. }else{
  79991. assert( pIn3->flags & MEM_Blob );
  79992. rc = ExpandBlob(pIn3);
  79993. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  79994. if( rc ) goto no_mem;
  79995. pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
  79996. if( pIdxKey==0 ) goto no_mem;
  79997. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  79998. }
  79999. pIdxKey->default_rc = 0;
  80000. takeJump = 0;
  80001. if( pOp->opcode==OP_NoConflict ){
  80002. /* For the OP_NoConflict opcode, take the jump if any of the
  80003. ** input fields are NULL, since any key with a NULL will not
  80004. ** conflict */
  80005. for(ii=0; ii<pIdxKey->nField; ii++){
  80006. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  80007. takeJump = 1;
  80008. break;
  80009. }
  80010. }
  80011. }
  80012. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  80013. if( pFree ) sqlite3DbFreeNN(db, pFree);
  80014. if( rc!=SQLITE_OK ){
  80015. goto abort_due_to_error;
  80016. }
  80017. pC->seekResult = res;
  80018. alreadyExists = (res==0);
  80019. pC->nullRow = 1-alreadyExists;
  80020. pC->deferredMoveto = 0;
  80021. pC->cacheStatus = CACHE_STALE;
  80022. if( pOp->opcode==OP_Found ){
  80023. VdbeBranchTaken(alreadyExists!=0,2);
  80024. if( alreadyExists ) goto jump_to_p2;
  80025. }else{
  80026. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  80027. if( takeJump || !alreadyExists ) goto jump_to_p2;
  80028. }
  80029. break;
  80030. }
  80031. /* Opcode: SeekRowid P1 P2 P3 * *
  80032. ** Synopsis: intkey=r[P3]
  80033. **
  80034. ** P1 is the index of a cursor open on an SQL table btree (with integer
  80035. ** keys). If register P3 does not contain an integer or if P1 does not
  80036. ** contain a record with rowid P3 then jump immediately to P2.
  80037. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
  80038. ** a record with rowid P3 then
  80039. ** leave the cursor pointing at that record and fall through to the next
  80040. ** instruction.
  80041. **
  80042. ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
  80043. ** the P3 register must be guaranteed to contain an integer value. With this
  80044. ** opcode, register P3 might not contain an integer.
  80045. **
  80046. ** The OP_NotFound opcode performs the same operation on index btrees
  80047. ** (with arbitrary multi-value keys).
  80048. **
  80049. ** This opcode leaves the cursor in a state where it cannot be advanced
  80050. ** in either direction. In other words, the Next and Prev opcodes will
  80051. ** not work following this opcode.
  80052. **
  80053. ** See also: Found, NotFound, NoConflict, SeekRowid
  80054. */
  80055. /* Opcode: NotExists P1 P2 P3 * *
  80056. ** Synopsis: intkey=r[P3]
  80057. **
  80058. ** P1 is the index of a cursor open on an SQL table btree (with integer
  80059. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  80060. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  80061. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  80062. ** leave the cursor pointing at that record and fall through to the next
  80063. ** instruction.
  80064. **
  80065. ** The OP_SeekRowid opcode performs the same operation but also allows the
  80066. ** P3 register to contain a non-integer value, in which case the jump is
  80067. ** always taken. This opcode requires that P3 always contain an integer.
  80068. **
  80069. ** The OP_NotFound opcode performs the same operation on index btrees
  80070. ** (with arbitrary multi-value keys).
  80071. **
  80072. ** This opcode leaves the cursor in a state where it cannot be advanced
  80073. ** in either direction. In other words, the Next and Prev opcodes will
  80074. ** not work following this opcode.
  80075. **
  80076. ** See also: Found, NotFound, NoConflict, SeekRowid
  80077. */
  80078. case OP_SeekRowid: { /* jump, in3 */
  80079. VdbeCursor *pC;
  80080. BtCursor *pCrsr;
  80081. int res;
  80082. u64 iKey;
  80083. pIn3 = &aMem[pOp->p3];
  80084. if( (pIn3->flags & MEM_Int)==0 ){
  80085. applyAffinity(pIn3, SQLITE_AFF_NUMERIC, encoding);
  80086. if( (pIn3->flags & MEM_Int)==0 ) goto jump_to_p2;
  80087. }
  80088. /* Fall through into OP_NotExists */
  80089. case OP_NotExists: /* jump, in3 */
  80090. pIn3 = &aMem[pOp->p3];
  80091. assert( pIn3->flags & MEM_Int );
  80092. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80093. pC = p->apCsr[pOp->p1];
  80094. assert( pC!=0 );
  80095. #ifdef SQLITE_DEBUG
  80096. pC->seekOp = 0;
  80097. #endif
  80098. assert( pC->isTable );
  80099. assert( pC->eCurType==CURTYPE_BTREE );
  80100. pCrsr = pC->uc.pCursor;
  80101. assert( pCrsr!=0 );
  80102. res = 0;
  80103. iKey = pIn3->u.i;
  80104. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  80105. assert( rc==SQLITE_OK || res==0 );
  80106. pC->movetoTarget = iKey; /* Used by OP_Delete */
  80107. pC->nullRow = 0;
  80108. pC->cacheStatus = CACHE_STALE;
  80109. pC->deferredMoveto = 0;
  80110. VdbeBranchTaken(res!=0,2);
  80111. pC->seekResult = res;
  80112. if( res!=0 ){
  80113. assert( rc==SQLITE_OK );
  80114. if( pOp->p2==0 ){
  80115. rc = SQLITE_CORRUPT_BKPT;
  80116. }else{
  80117. goto jump_to_p2;
  80118. }
  80119. }
  80120. if( rc ) goto abort_due_to_error;
  80121. break;
  80122. }
  80123. /* Opcode: Sequence P1 P2 * * *
  80124. ** Synopsis: r[P2]=cursor[P1].ctr++
  80125. **
  80126. ** Find the next available sequence number for cursor P1.
  80127. ** Write the sequence number into register P2.
  80128. ** The sequence number on the cursor is incremented after this
  80129. ** instruction.
  80130. */
  80131. case OP_Sequence: { /* out2 */
  80132. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80133. assert( p->apCsr[pOp->p1]!=0 );
  80134. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  80135. pOut = out2Prerelease(p, pOp);
  80136. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  80137. break;
  80138. }
  80139. /* Opcode: NewRowid P1 P2 P3 * *
  80140. ** Synopsis: r[P2]=rowid
  80141. **
  80142. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  80143. ** The record number is not previously used as a key in the database
  80144. ** table that cursor P1 points to. The new record number is written
  80145. ** written to register P2.
  80146. **
  80147. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  80148. ** the largest previously generated record number. No new record numbers are
  80149. ** allowed to be less than this value. When this value reaches its maximum,
  80150. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  80151. ** generated record number. This P3 mechanism is used to help implement the
  80152. ** AUTOINCREMENT feature.
  80153. */
  80154. case OP_NewRowid: { /* out2 */
  80155. i64 v; /* The new rowid */
  80156. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  80157. int res; /* Result of an sqlite3BtreeLast() */
  80158. int cnt; /* Counter to limit the number of searches */
  80159. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  80160. VdbeFrame *pFrame; /* Root frame of VDBE */
  80161. v = 0;
  80162. res = 0;
  80163. pOut = out2Prerelease(p, pOp);
  80164. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80165. pC = p->apCsr[pOp->p1];
  80166. if( !pC->isTable ){
  80167. rc = SQLITE_CORRUPT_BKPT;
  80168. goto abort_due_to_error;
  80169. }
  80170. assert( pC!=0 );
  80171. assert( pC->eCurType==CURTYPE_BTREE );
  80172. assert( pC->uc.pCursor!=0 );
  80173. {
  80174. /* The next rowid or record number (different terms for the same
  80175. ** thing) is obtained in a two-step algorithm.
  80176. **
  80177. ** First we attempt to find the largest existing rowid and add one
  80178. ** to that. But if the largest existing rowid is already the maximum
  80179. ** positive integer, we have to fall through to the second
  80180. ** probabilistic algorithm
  80181. **
  80182. ** The second algorithm is to select a rowid at random and see if
  80183. ** it already exists in the table. If it does not exist, we have
  80184. ** succeeded. If the random rowid does exist, we select a new one
  80185. ** and try again, up to 100 times.
  80186. */
  80187. assert( pC->isTable );
  80188. #ifdef SQLITE_32BIT_ROWID
  80189. # define MAX_ROWID 0x7fffffff
  80190. #else
  80191. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  80192. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  80193. ** to provide the constant while making all compilers happy.
  80194. */
  80195. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  80196. #endif
  80197. if( !pC->useRandomRowid ){
  80198. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  80199. if( rc!=SQLITE_OK ){
  80200. goto abort_due_to_error;
  80201. }
  80202. if( res ){
  80203. v = 1; /* IMP: R-61914-48074 */
  80204. }else{
  80205. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  80206. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  80207. if( v>=MAX_ROWID ){
  80208. pC->useRandomRowid = 1;
  80209. }else{
  80210. v++; /* IMP: R-29538-34987 */
  80211. }
  80212. }
  80213. }
  80214. #ifndef SQLITE_OMIT_AUTOINCREMENT
  80215. if( pOp->p3 ){
  80216. /* Assert that P3 is a valid memory cell. */
  80217. assert( pOp->p3>0 );
  80218. if( p->pFrame ){
  80219. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  80220. /* Assert that P3 is a valid memory cell. */
  80221. assert( pOp->p3<=pFrame->nMem );
  80222. pMem = &pFrame->aMem[pOp->p3];
  80223. }else{
  80224. /* Assert that P3 is a valid memory cell. */
  80225. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  80226. pMem = &aMem[pOp->p3];
  80227. memAboutToChange(p, pMem);
  80228. }
  80229. assert( memIsValid(pMem) );
  80230. REGISTER_TRACE(pOp->p3, pMem);
  80231. sqlite3VdbeMemIntegerify(pMem);
  80232. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  80233. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  80234. rc = SQLITE_FULL; /* IMP: R-17817-00630 */
  80235. goto abort_due_to_error;
  80236. }
  80237. if( v<pMem->u.i+1 ){
  80238. v = pMem->u.i + 1;
  80239. }
  80240. pMem->u.i = v;
  80241. }
  80242. #endif
  80243. if( pC->useRandomRowid ){
  80244. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  80245. ** largest possible integer (9223372036854775807) then the database
  80246. ** engine starts picking positive candidate ROWIDs at random until
  80247. ** it finds one that is not previously used. */
  80248. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  80249. ** an AUTOINCREMENT table. */
  80250. cnt = 0;
  80251. do{
  80252. sqlite3_randomness(sizeof(v), &v);
  80253. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  80254. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  80255. 0, &res))==SQLITE_OK)
  80256. && (res==0)
  80257. && (++cnt<100));
  80258. if( rc ) goto abort_due_to_error;
  80259. if( res==0 ){
  80260. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  80261. goto abort_due_to_error;
  80262. }
  80263. assert( v>0 ); /* EV: R-40812-03570 */
  80264. }
  80265. pC->deferredMoveto = 0;
  80266. pC->cacheStatus = CACHE_STALE;
  80267. }
  80268. pOut->u.i = v;
  80269. break;
  80270. }
  80271. /* Opcode: Insert P1 P2 P3 P4 P5
  80272. ** Synopsis: intkey=r[P3] data=r[P2]
  80273. **
  80274. ** Write an entry into the table of cursor P1. A new entry is
  80275. ** created if it doesn't already exist or the data for an existing
  80276. ** entry is overwritten. The data is the value MEM_Blob stored in register
  80277. ** number P2. The key is stored in register P3. The key must
  80278. ** be a MEM_Int.
  80279. **
  80280. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  80281. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  80282. ** then rowid is stored for subsequent return by the
  80283. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  80284. **
  80285. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  80286. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  80287. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  80288. ** seeks on the cursor or if the most recent seek used a key equal to P3.
  80289. **
  80290. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  80291. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  80292. ** is part of an INSERT operation. The difference is only important to
  80293. ** the update hook.
  80294. **
  80295. ** Parameter P4 may point to a Table structure, or may be NULL. If it is
  80296. ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
  80297. ** following a successful insert.
  80298. **
  80299. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  80300. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  80301. ** and register P2 becomes ephemeral. If the cursor is changed, the
  80302. ** value of register P2 will then change. Make sure this does not
  80303. ** cause any problems.)
  80304. **
  80305. ** This instruction only works on tables. The equivalent instruction
  80306. ** for indices is OP_IdxInsert.
  80307. */
  80308. /* Opcode: InsertInt P1 P2 P3 P4 P5
  80309. ** Synopsis: intkey=P3 data=r[P2]
  80310. **
  80311. ** This works exactly like OP_Insert except that the key is the
  80312. ** integer value P3, not the value of the integer stored in register P3.
  80313. */
  80314. case OP_Insert:
  80315. case OP_InsertInt: {
  80316. Mem *pData; /* MEM cell holding data for the record to be inserted */
  80317. Mem *pKey; /* MEM cell holding key for the record */
  80318. VdbeCursor *pC; /* Cursor to table into which insert is written */
  80319. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  80320. const char *zDb; /* database name - used by the update hook */
  80321. Table *pTab; /* Table structure - used by update and pre-update hooks */
  80322. BtreePayload x; /* Payload to be inserted */
  80323. pData = &aMem[pOp->p2];
  80324. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80325. assert( memIsValid(pData) );
  80326. pC = p->apCsr[pOp->p1];
  80327. assert( pC!=0 );
  80328. assert( pC->eCurType==CURTYPE_BTREE );
  80329. assert( pC->uc.pCursor!=0 );
  80330. assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
  80331. assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
  80332. REGISTER_TRACE(pOp->p2, pData);
  80333. if( pOp->opcode==OP_Insert ){
  80334. pKey = &aMem[pOp->p3];
  80335. assert( pKey->flags & MEM_Int );
  80336. assert( memIsValid(pKey) );
  80337. REGISTER_TRACE(pOp->p3, pKey);
  80338. x.nKey = pKey->u.i;
  80339. }else{
  80340. assert( pOp->opcode==OP_InsertInt );
  80341. x.nKey = pOp->p3;
  80342. }
  80343. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  80344. assert( pC->iDb>=0 );
  80345. zDb = db->aDb[pC->iDb].zDbSName;
  80346. pTab = pOp->p4.pTab;
  80347. assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
  80348. }else{
  80349. pTab = 0;
  80350. zDb = 0; /* Not needed. Silence a compiler warning. */
  80351. }
  80352. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  80353. /* Invoke the pre-update hook, if any */
  80354. if( pTab ){
  80355. if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
  80356. sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
  80357. }
  80358. if( db->xUpdateCallback==0 || pTab->aCol==0 ){
  80359. /* Prevent post-update hook from running in cases when it should not */
  80360. pTab = 0;
  80361. }
  80362. }
  80363. if( pOp->p5 & OPFLAG_ISNOOP ) break;
  80364. #endif
  80365. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  80366. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
  80367. assert( pData->flags & (MEM_Blob|MEM_Str) );
  80368. x.pData = pData->z;
  80369. x.nData = pData->n;
  80370. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  80371. if( pData->flags & MEM_Zero ){
  80372. x.nZero = pData->u.nZero;
  80373. }else{
  80374. x.nZero = 0;
  80375. }
  80376. x.pKey = 0;
  80377. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  80378. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
  80379. );
  80380. pC->deferredMoveto = 0;
  80381. pC->cacheStatus = CACHE_STALE;
  80382. /* Invoke the update-hook if required. */
  80383. if( rc ) goto abort_due_to_error;
  80384. if( pTab ){
  80385. assert( db->xUpdateCallback!=0 );
  80386. assert( pTab->aCol!=0 );
  80387. db->xUpdateCallback(db->pUpdateArg,
  80388. (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
  80389. zDb, pTab->zName, x.nKey);
  80390. }
  80391. break;
  80392. }
  80393. /* Opcode: Delete P1 P2 P3 P4 P5
  80394. **
  80395. ** Delete the record at which the P1 cursor is currently pointing.
  80396. **
  80397. ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
  80398. ** the cursor will be left pointing at either the next or the previous
  80399. ** record in the table. If it is left pointing at the next record, then
  80400. ** the next Next instruction will be a no-op. As a result, in this case
  80401. ** it is ok to delete a record from within a Next loop. If
  80402. ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
  80403. ** left in an undefined state.
  80404. **
  80405. ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
  80406. ** delete one of several associated with deleting a table row and all its
  80407. ** associated index entries. Exactly one of those deletes is the "primary"
  80408. ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
  80409. ** marked with the AUXDELETE flag.
  80410. **
  80411. ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
  80412. ** change count is incremented (otherwise not).
  80413. **
  80414. ** P1 must not be pseudo-table. It has to be a real table with
  80415. ** multiple rows.
  80416. **
  80417. ** If P4 is not NULL then it points to a Table object. In this case either
  80418. ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
  80419. ** have been positioned using OP_NotFound prior to invoking this opcode in
  80420. ** this case. Specifically, if one is configured, the pre-update hook is
  80421. ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
  80422. ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
  80423. **
  80424. ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
  80425. ** of the memory cell that contains the value that the rowid of the row will
  80426. ** be set to by the update.
  80427. */
  80428. case OP_Delete: {
  80429. VdbeCursor *pC;
  80430. const char *zDb;
  80431. Table *pTab;
  80432. int opflags;
  80433. opflags = pOp->p2;
  80434. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80435. pC = p->apCsr[pOp->p1];
  80436. assert( pC!=0 );
  80437. assert( pC->eCurType==CURTYPE_BTREE );
  80438. assert( pC->uc.pCursor!=0 );
  80439. assert( pC->deferredMoveto==0 );
  80440. #ifdef SQLITE_DEBUG
  80441. if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
  80442. /* If p5 is zero, the seek operation that positioned the cursor prior to
  80443. ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
  80444. ** the row that is being deleted */
  80445. i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  80446. assert( pC->movetoTarget==iKey );
  80447. }
  80448. #endif
  80449. /* If the update-hook or pre-update-hook will be invoked, set zDb to
  80450. ** the name of the db to pass as to it. Also set local pTab to a copy
  80451. ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
  80452. ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
  80453. ** VdbeCursor.movetoTarget to the current rowid. */
  80454. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  80455. assert( pC->iDb>=0 );
  80456. assert( pOp->p4.pTab!=0 );
  80457. zDb = db->aDb[pC->iDb].zDbSName;
  80458. pTab = pOp->p4.pTab;
  80459. if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
  80460. pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  80461. }
  80462. }else{
  80463. zDb = 0; /* Not needed. Silence a compiler warning. */
  80464. pTab = 0; /* Not needed. Silence a compiler warning. */
  80465. }
  80466. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  80467. /* Invoke the pre-update-hook if required. */
  80468. if( db->xPreUpdateCallback && pOp->p4.pTab ){
  80469. assert( !(opflags & OPFLAG_ISUPDATE)
  80470. || HasRowid(pTab)==0
  80471. || (aMem[pOp->p3].flags & MEM_Int)
  80472. );
  80473. sqlite3VdbePreUpdateHook(p, pC,
  80474. (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
  80475. zDb, pTab, pC->movetoTarget,
  80476. pOp->p3
  80477. );
  80478. }
  80479. if( opflags & OPFLAG_ISNOOP ) break;
  80480. #endif
  80481. /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
  80482. assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
  80483. assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
  80484. assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
  80485. #ifdef SQLITE_DEBUG
  80486. if( p->pFrame==0 ){
  80487. if( pC->isEphemeral==0
  80488. && (pOp->p5 & OPFLAG_AUXDELETE)==0
  80489. && (pC->wrFlag & OPFLAG_FORDELETE)==0
  80490. ){
  80491. nExtraDelete++;
  80492. }
  80493. if( pOp->p2 & OPFLAG_NCHANGE ){
  80494. nExtraDelete--;
  80495. }
  80496. }
  80497. #endif
  80498. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  80499. pC->cacheStatus = CACHE_STALE;
  80500. pC->seekResult = 0;
  80501. if( rc ) goto abort_due_to_error;
  80502. /* Invoke the update-hook if required. */
  80503. if( opflags & OPFLAG_NCHANGE ){
  80504. p->nChange++;
  80505. if( db->xUpdateCallback && HasRowid(pTab) ){
  80506. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
  80507. pC->movetoTarget);
  80508. assert( pC->iDb>=0 );
  80509. }
  80510. }
  80511. break;
  80512. }
  80513. /* Opcode: ResetCount * * * * *
  80514. **
  80515. ** The value of the change counter is copied to the database handle
  80516. ** change counter (returned by subsequent calls to sqlite3_changes()).
  80517. ** Then the VMs internal change counter resets to 0.
  80518. ** This is used by trigger programs.
  80519. */
  80520. case OP_ResetCount: {
  80521. sqlite3VdbeSetChanges(db, p->nChange);
  80522. p->nChange = 0;
  80523. break;
  80524. }
  80525. /* Opcode: SorterCompare P1 P2 P3 P4
  80526. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  80527. **
  80528. ** P1 is a sorter cursor. This instruction compares a prefix of the
  80529. ** record blob in register P3 against a prefix of the entry that
  80530. ** the sorter cursor currently points to. Only the first P4 fields
  80531. ** of r[P3] and the sorter record are compared.
  80532. **
  80533. ** If either P3 or the sorter contains a NULL in one of their significant
  80534. ** fields (not counting the P4 fields at the end which are ignored) then
  80535. ** the comparison is assumed to be equal.
  80536. **
  80537. ** Fall through to next instruction if the two records compare equal to
  80538. ** each other. Jump to P2 if they are different.
  80539. */
  80540. case OP_SorterCompare: {
  80541. VdbeCursor *pC;
  80542. int res;
  80543. int nKeyCol;
  80544. pC = p->apCsr[pOp->p1];
  80545. assert( isSorter(pC) );
  80546. assert( pOp->p4type==P4_INT32 );
  80547. pIn3 = &aMem[pOp->p3];
  80548. nKeyCol = pOp->p4.i;
  80549. res = 0;
  80550. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  80551. VdbeBranchTaken(res!=0,2);
  80552. if( rc ) goto abort_due_to_error;
  80553. if( res ) goto jump_to_p2;
  80554. break;
  80555. };
  80556. /* Opcode: SorterData P1 P2 P3 * *
  80557. ** Synopsis: r[P2]=data
  80558. **
  80559. ** Write into register P2 the current sorter data for sorter cursor P1.
  80560. ** Then clear the column header cache on cursor P3.
  80561. **
  80562. ** This opcode is normally use to move a record out of the sorter and into
  80563. ** a register that is the source for a pseudo-table cursor created using
  80564. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  80565. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  80566. ** us from having to issue a separate NullRow instruction to clear that cache.
  80567. */
  80568. case OP_SorterData: {
  80569. VdbeCursor *pC;
  80570. pOut = &aMem[pOp->p2];
  80571. pC = p->apCsr[pOp->p1];
  80572. assert( isSorter(pC) );
  80573. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  80574. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  80575. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80576. if( rc ) goto abort_due_to_error;
  80577. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  80578. break;
  80579. }
  80580. /* Opcode: RowData P1 P2 P3 * *
  80581. ** Synopsis: r[P2]=data
  80582. **
  80583. ** Write into register P2 the complete row content for the row at
  80584. ** which cursor P1 is currently pointing.
  80585. ** There is no interpretation of the data.
  80586. ** It is just copied onto the P2 register exactly as
  80587. ** it is found in the database file.
  80588. **
  80589. ** If cursor P1 is an index, then the content is the key of the row.
  80590. ** If cursor P2 is a table, then the content extracted is the data.
  80591. **
  80592. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  80593. ** of a real table, not a pseudo-table.
  80594. **
  80595. ** If P3!=0 then this opcode is allowed to make an ephermeral pointer
  80596. ** into the database page. That means that the content of the output
  80597. ** register will be invalidated as soon as the cursor moves - including
  80598. ** moves caused by other cursors that "save" the the current cursors
  80599. ** position in order that they can write to the same table. If P3==0
  80600. ** then a copy of the data is made into memory. P3!=0 is faster, but
  80601. ** P3==0 is safer.
  80602. **
  80603. ** If P3!=0 then the content of the P2 register is unsuitable for use
  80604. ** in OP_Result and any OP_Result will invalidate the P2 register content.
  80605. ** The P2 register content is invalidated by opcodes like OP_Function or
  80606. ** by any use of another cursor pointing to the same table.
  80607. */
  80608. case OP_RowData: {
  80609. VdbeCursor *pC;
  80610. BtCursor *pCrsr;
  80611. u32 n;
  80612. pOut = out2Prerelease(p, pOp);
  80613. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80614. pC = p->apCsr[pOp->p1];
  80615. assert( pC!=0 );
  80616. assert( pC->eCurType==CURTYPE_BTREE );
  80617. assert( isSorter(pC)==0 );
  80618. assert( pC->nullRow==0 );
  80619. assert( pC->uc.pCursor!=0 );
  80620. pCrsr = pC->uc.pCursor;
  80621. /* The OP_RowData opcodes always follow OP_NotExists or
  80622. ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
  80623. ** that might invalidate the cursor.
  80624. ** If this where not the case, on of the following assert()s
  80625. ** would fail. Should this ever change (because of changes in the code
  80626. ** generator) then the fix would be to insert a call to
  80627. ** sqlite3VdbeCursorMoveto().
  80628. */
  80629. assert( pC->deferredMoveto==0 );
  80630. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  80631. #if 0 /* Not required due to the previous to assert() statements */
  80632. rc = sqlite3VdbeCursorMoveto(pC);
  80633. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  80634. #endif
  80635. n = sqlite3BtreePayloadSize(pCrsr);
  80636. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  80637. goto too_big;
  80638. }
  80639. testcase( n==0 );
  80640. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, n, pOut);
  80641. if( rc ) goto abort_due_to_error;
  80642. if( !pOp->p3 ) Deephemeralize(pOut);
  80643. UPDATE_MAX_BLOBSIZE(pOut);
  80644. REGISTER_TRACE(pOp->p2, pOut);
  80645. break;
  80646. }
  80647. /* Opcode: Rowid P1 P2 * * *
  80648. ** Synopsis: r[P2]=rowid
  80649. **
  80650. ** Store in register P2 an integer which is the key of the table entry that
  80651. ** P1 is currently point to.
  80652. **
  80653. ** P1 can be either an ordinary table or a virtual table. There used to
  80654. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  80655. ** one opcode now works for both table types.
  80656. */
  80657. case OP_Rowid: { /* out2 */
  80658. VdbeCursor *pC;
  80659. i64 v;
  80660. sqlite3_vtab *pVtab;
  80661. const sqlite3_module *pModule;
  80662. pOut = out2Prerelease(p, pOp);
  80663. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80664. pC = p->apCsr[pOp->p1];
  80665. assert( pC!=0 );
  80666. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  80667. if( pC->nullRow ){
  80668. pOut->flags = MEM_Null;
  80669. break;
  80670. }else if( pC->deferredMoveto ){
  80671. v = pC->movetoTarget;
  80672. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80673. }else if( pC->eCurType==CURTYPE_VTAB ){
  80674. assert( pC->uc.pVCur!=0 );
  80675. pVtab = pC->uc.pVCur->pVtab;
  80676. pModule = pVtab->pModule;
  80677. assert( pModule->xRowid );
  80678. rc = pModule->xRowid(pC->uc.pVCur, &v);
  80679. sqlite3VtabImportErrmsg(p, pVtab);
  80680. if( rc ) goto abort_due_to_error;
  80681. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  80682. }else{
  80683. assert( pC->eCurType==CURTYPE_BTREE );
  80684. assert( pC->uc.pCursor!=0 );
  80685. rc = sqlite3VdbeCursorRestore(pC);
  80686. if( rc ) goto abort_due_to_error;
  80687. if( pC->nullRow ){
  80688. pOut->flags = MEM_Null;
  80689. break;
  80690. }
  80691. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  80692. }
  80693. pOut->u.i = v;
  80694. break;
  80695. }
  80696. /* Opcode: NullRow P1 * * * *
  80697. **
  80698. ** Move the cursor P1 to a null row. Any OP_Column operations
  80699. ** that occur while the cursor is on the null row will always
  80700. ** write a NULL.
  80701. */
  80702. case OP_NullRow: {
  80703. VdbeCursor *pC;
  80704. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80705. pC = p->apCsr[pOp->p1];
  80706. assert( pC!=0 );
  80707. pC->nullRow = 1;
  80708. pC->cacheStatus = CACHE_STALE;
  80709. if( pC->eCurType==CURTYPE_BTREE ){
  80710. assert( pC->uc.pCursor!=0 );
  80711. sqlite3BtreeClearCursor(pC->uc.pCursor);
  80712. }
  80713. break;
  80714. }
  80715. /* Opcode: SeekEnd P1 * * * *
  80716. **
  80717. ** Position cursor P1 at the end of the btree for the purpose of
  80718. ** appending a new entry onto the btree.
  80719. **
  80720. ** It is assumed that the cursor is used only for appending and so
  80721. ** if the cursor is valid, then the cursor must already be pointing
  80722. ** at the end of the btree and so no changes are made to
  80723. ** the cursor.
  80724. */
  80725. /* Opcode: Last P1 P2 * * *
  80726. **
  80727. ** The next use of the Rowid or Column or Prev instruction for P1
  80728. ** will refer to the last entry in the database table or index.
  80729. ** If the table or index is empty and P2>0, then jump immediately to P2.
  80730. ** If P2 is 0 or if the table or index is not empty, fall through
  80731. ** to the following instruction.
  80732. **
  80733. ** This opcode leaves the cursor configured to move in reverse order,
  80734. ** from the end toward the beginning. In other words, the cursor is
  80735. ** configured to use Prev, not Next.
  80736. */
  80737. case OP_SeekEnd:
  80738. case OP_Last: { /* jump */
  80739. VdbeCursor *pC;
  80740. BtCursor *pCrsr;
  80741. int res;
  80742. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80743. pC = p->apCsr[pOp->p1];
  80744. assert( pC!=0 );
  80745. assert( pC->eCurType==CURTYPE_BTREE );
  80746. pCrsr = pC->uc.pCursor;
  80747. res = 0;
  80748. assert( pCrsr!=0 );
  80749. #ifdef SQLITE_DEBUG
  80750. pC->seekOp = pOp->opcode;
  80751. #endif
  80752. if( pOp->opcode==OP_SeekEnd ){
  80753. assert( pOp->p2==0 );
  80754. pC->seekResult = -1;
  80755. if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
  80756. break;
  80757. }
  80758. }
  80759. rc = sqlite3BtreeLast(pCrsr, &res);
  80760. pC->nullRow = (u8)res;
  80761. pC->deferredMoveto = 0;
  80762. pC->cacheStatus = CACHE_STALE;
  80763. if( rc ) goto abort_due_to_error;
  80764. if( pOp->p2>0 ){
  80765. VdbeBranchTaken(res!=0,2);
  80766. if( res ) goto jump_to_p2;
  80767. }
  80768. break;
  80769. }
  80770. /* Opcode: IfSmaller P1 P2 P3 * *
  80771. **
  80772. ** Estimate the number of rows in the table P1. Jump to P2 if that
  80773. ** estimate is less than approximately 2**(0.1*P3).
  80774. */
  80775. case OP_IfSmaller: { /* jump */
  80776. VdbeCursor *pC;
  80777. BtCursor *pCrsr;
  80778. int res;
  80779. i64 sz;
  80780. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80781. pC = p->apCsr[pOp->p1];
  80782. assert( pC!=0 );
  80783. pCrsr = pC->uc.pCursor;
  80784. assert( pCrsr );
  80785. rc = sqlite3BtreeFirst(pCrsr, &res);
  80786. if( rc ) goto abort_due_to_error;
  80787. if( res==0 ){
  80788. sz = sqlite3BtreeRowCountEst(pCrsr);
  80789. if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
  80790. }
  80791. VdbeBranchTaken(res!=0,2);
  80792. if( res ) goto jump_to_p2;
  80793. break;
  80794. }
  80795. /* Opcode: SorterSort P1 P2 * * *
  80796. **
  80797. ** After all records have been inserted into the Sorter object
  80798. ** identified by P1, invoke this opcode to actually do the sorting.
  80799. ** Jump to P2 if there are no records to be sorted.
  80800. **
  80801. ** This opcode is an alias for OP_Sort and OP_Rewind that is used
  80802. ** for Sorter objects.
  80803. */
  80804. /* Opcode: Sort P1 P2 * * *
  80805. **
  80806. ** This opcode does exactly the same thing as OP_Rewind except that
  80807. ** it increments an undocumented global variable used for testing.
  80808. **
  80809. ** Sorting is accomplished by writing records into a sorting index,
  80810. ** then rewinding that index and playing it back from beginning to
  80811. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  80812. ** rewinding so that the global variable will be incremented and
  80813. ** regression tests can determine whether or not the optimizer is
  80814. ** correctly optimizing out sorts.
  80815. */
  80816. case OP_SorterSort: /* jump */
  80817. case OP_Sort: { /* jump */
  80818. #ifdef SQLITE_TEST
  80819. sqlite3_sort_count++;
  80820. sqlite3_search_count--;
  80821. #endif
  80822. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  80823. /* Fall through into OP_Rewind */
  80824. }
  80825. /* Opcode: Rewind P1 P2 * * *
  80826. **
  80827. ** The next use of the Rowid or Column or Next instruction for P1
  80828. ** will refer to the first entry in the database table or index.
  80829. ** If the table or index is empty, jump immediately to P2.
  80830. ** If the table or index is not empty, fall through to the following
  80831. ** instruction.
  80832. **
  80833. ** This opcode leaves the cursor configured to move in forward order,
  80834. ** from the beginning toward the end. In other words, the cursor is
  80835. ** configured to use Next, not Prev.
  80836. */
  80837. case OP_Rewind: { /* jump */
  80838. VdbeCursor *pC;
  80839. BtCursor *pCrsr;
  80840. int res;
  80841. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80842. pC = p->apCsr[pOp->p1];
  80843. assert( pC!=0 );
  80844. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  80845. res = 1;
  80846. #ifdef SQLITE_DEBUG
  80847. pC->seekOp = OP_Rewind;
  80848. #endif
  80849. if( isSorter(pC) ){
  80850. rc = sqlite3VdbeSorterRewind(pC, &res);
  80851. }else{
  80852. assert( pC->eCurType==CURTYPE_BTREE );
  80853. pCrsr = pC->uc.pCursor;
  80854. assert( pCrsr );
  80855. rc = sqlite3BtreeFirst(pCrsr, &res);
  80856. pC->deferredMoveto = 0;
  80857. pC->cacheStatus = CACHE_STALE;
  80858. }
  80859. if( rc ) goto abort_due_to_error;
  80860. pC->nullRow = (u8)res;
  80861. assert( pOp->p2>0 && pOp->p2<p->nOp );
  80862. VdbeBranchTaken(res!=0,2);
  80863. if( res ) goto jump_to_p2;
  80864. break;
  80865. }
  80866. /* Opcode: Next P1 P2 P3 P4 P5
  80867. **
  80868. ** Advance cursor P1 so that it points to the next key/data pair in its
  80869. ** table or index. If there are no more key/value pairs then fall through
  80870. ** to the following instruction. But if the cursor advance was successful,
  80871. ** jump immediately to P2.
  80872. **
  80873. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  80874. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  80875. ** to follow SeekLT, SeekLE, or OP_Last.
  80876. **
  80877. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  80878. ** been opened prior to this opcode or the program will segfault.
  80879. **
  80880. ** The P3 value is a hint to the btree implementation. If P3==1, that
  80881. ** means P1 is an SQL index and that this instruction could have been
  80882. ** omitted if that index had been unique. P3 is usually 0. P3 is
  80883. ** always either 0 or 1.
  80884. **
  80885. ** P4 is always of type P4_ADVANCE. The function pointer points to
  80886. ** sqlite3BtreeNext().
  80887. **
  80888. ** If P5 is positive and the jump is taken, then event counter
  80889. ** number P5-1 in the prepared statement is incremented.
  80890. **
  80891. ** See also: Prev, NextIfOpen
  80892. */
  80893. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  80894. **
  80895. ** This opcode works just like Next except that if cursor P1 is not
  80896. ** open it behaves a no-op.
  80897. */
  80898. /* Opcode: Prev P1 P2 P3 P4 P5
  80899. **
  80900. ** Back up cursor P1 so that it points to the previous key/data pair in its
  80901. ** table or index. If there is no previous key/value pairs then fall through
  80902. ** to the following instruction. But if the cursor backup was successful,
  80903. ** jump immediately to P2.
  80904. **
  80905. **
  80906. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  80907. ** OP_Last opcode used to position the cursor. Prev is not allowed
  80908. ** to follow SeekGT, SeekGE, or OP_Rewind.
  80909. **
  80910. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  80911. ** not open then the behavior is undefined.
  80912. **
  80913. ** The P3 value is a hint to the btree implementation. If P3==1, that
  80914. ** means P1 is an SQL index and that this instruction could have been
  80915. ** omitted if that index had been unique. P3 is usually 0. P3 is
  80916. ** always either 0 or 1.
  80917. **
  80918. ** P4 is always of type P4_ADVANCE. The function pointer points to
  80919. ** sqlite3BtreePrevious().
  80920. **
  80921. ** If P5 is positive and the jump is taken, then event counter
  80922. ** number P5-1 in the prepared statement is incremented.
  80923. */
  80924. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  80925. **
  80926. ** This opcode works just like Prev except that if cursor P1 is not
  80927. ** open it behaves a no-op.
  80928. */
  80929. /* Opcode: SorterNext P1 P2 * * P5
  80930. **
  80931. ** This opcode works just like OP_Next except that P1 must be a
  80932. ** sorter object for which the OP_SorterSort opcode has been
  80933. ** invoked. This opcode advances the cursor to the next sorted
  80934. ** record, or jumps to P2 if there are no more sorted records.
  80935. */
  80936. case OP_SorterNext: { /* jump */
  80937. VdbeCursor *pC;
  80938. pC = p->apCsr[pOp->p1];
  80939. assert( isSorter(pC) );
  80940. rc = sqlite3VdbeSorterNext(db, pC);
  80941. goto next_tail;
  80942. case OP_PrevIfOpen: /* jump */
  80943. case OP_NextIfOpen: /* jump */
  80944. if( p->apCsr[pOp->p1]==0 ) break;
  80945. /* Fall through */
  80946. case OP_Prev: /* jump */
  80947. case OP_Next: /* jump */
  80948. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  80949. assert( pOp->p5<ArraySize(p->aCounter) );
  80950. pC = p->apCsr[pOp->p1];
  80951. assert( pC!=0 );
  80952. assert( pC->deferredMoveto==0 );
  80953. assert( pC->eCurType==CURTYPE_BTREE );
  80954. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  80955. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  80956. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  80957. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  80958. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  80959. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  80960. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  80961. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  80962. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  80963. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  80964. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  80965. || pC->seekOp==OP_Last );
  80966. rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
  80967. next_tail:
  80968. pC->cacheStatus = CACHE_STALE;
  80969. VdbeBranchTaken(rc==SQLITE_OK,2);
  80970. if( rc==SQLITE_OK ){
  80971. pC->nullRow = 0;
  80972. p->aCounter[pOp->p5]++;
  80973. #ifdef SQLITE_TEST
  80974. sqlite3_search_count++;
  80975. #endif
  80976. goto jump_to_p2_and_check_for_interrupt;
  80977. }
  80978. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  80979. rc = SQLITE_OK;
  80980. pC->nullRow = 1;
  80981. goto check_for_interrupt;
  80982. }
  80983. /* Opcode: IdxInsert P1 P2 P3 P4 P5
  80984. ** Synopsis: key=r[P2]
  80985. **
  80986. ** Register P2 holds an SQL index key made using the
  80987. ** MakeRecord instructions. This opcode writes that key
  80988. ** into the index P1. Data for the entry is nil.
  80989. **
  80990. ** If P4 is not zero, then it is the number of values in the unpacked
  80991. ** key of reg(P2). In that case, P3 is the index of the first register
  80992. ** for the unpacked key. The availability of the unpacked key can sometimes
  80993. ** be an optimization.
  80994. **
  80995. ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
  80996. ** that this insert is likely to be an append.
  80997. **
  80998. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  80999. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  81000. ** then the change counter is unchanged.
  81001. **
  81002. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  81003. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  81004. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  81005. ** seeks on the cursor or if the most recent seek used a key equivalent
  81006. ** to P2.
  81007. **
  81008. ** This instruction only works for indices. The equivalent instruction
  81009. ** for tables is OP_Insert.
  81010. */
  81011. /* Opcode: SorterInsert P1 P2 * * *
  81012. ** Synopsis: key=r[P2]
  81013. **
  81014. ** Register P2 holds an SQL index key made using the
  81015. ** MakeRecord instructions. This opcode writes that key
  81016. ** into the sorter P1. Data for the entry is nil.
  81017. */
  81018. case OP_SorterInsert: /* in2 */
  81019. case OP_IdxInsert: { /* in2 */
  81020. VdbeCursor *pC;
  81021. BtreePayload x;
  81022. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81023. pC = p->apCsr[pOp->p1];
  81024. assert( pC!=0 );
  81025. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  81026. pIn2 = &aMem[pOp->p2];
  81027. assert( pIn2->flags & MEM_Blob );
  81028. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  81029. assert( pC->eCurType==CURTYPE_BTREE || pOp->opcode==OP_SorterInsert );
  81030. assert( pC->isTable==0 );
  81031. rc = ExpandBlob(pIn2);
  81032. if( rc ) goto abort_due_to_error;
  81033. if( pOp->opcode==OP_SorterInsert ){
  81034. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  81035. }else{
  81036. x.nKey = pIn2->n;
  81037. x.pKey = pIn2->z;
  81038. x.aMem = aMem + pOp->p3;
  81039. x.nMem = (u16)pOp->p4.i;
  81040. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  81041. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
  81042. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  81043. );
  81044. assert( pC->deferredMoveto==0 );
  81045. pC->cacheStatus = CACHE_STALE;
  81046. }
  81047. if( rc) goto abort_due_to_error;
  81048. break;
  81049. }
  81050. /* Opcode: IdxDelete P1 P2 P3 * *
  81051. ** Synopsis: key=r[P2@P3]
  81052. **
  81053. ** The content of P3 registers starting at register P2 form
  81054. ** an unpacked index key. This opcode removes that entry from the
  81055. ** index opened by cursor P1.
  81056. */
  81057. case OP_IdxDelete: {
  81058. VdbeCursor *pC;
  81059. BtCursor *pCrsr;
  81060. int res;
  81061. UnpackedRecord r;
  81062. assert( pOp->p3>0 );
  81063. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
  81064. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81065. pC = p->apCsr[pOp->p1];
  81066. assert( pC!=0 );
  81067. assert( pC->eCurType==CURTYPE_BTREE );
  81068. pCrsr = pC->uc.pCursor;
  81069. assert( pCrsr!=0 );
  81070. assert( pOp->p5==0 );
  81071. r.pKeyInfo = pC->pKeyInfo;
  81072. r.nField = (u16)pOp->p3;
  81073. r.default_rc = 0;
  81074. r.aMem = &aMem[pOp->p2];
  81075. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  81076. if( rc ) goto abort_due_to_error;
  81077. if( res==0 ){
  81078. rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
  81079. if( rc ) goto abort_due_to_error;
  81080. }
  81081. assert( pC->deferredMoveto==0 );
  81082. pC->cacheStatus = CACHE_STALE;
  81083. pC->seekResult = 0;
  81084. break;
  81085. }
  81086. /* Opcode: DeferredSeek P1 * P3 P4 *
  81087. ** Synopsis: Move P3 to P1.rowid if needed
  81088. **
  81089. ** P1 is an open index cursor and P3 is a cursor on the corresponding
  81090. ** table. This opcode does a deferred seek of the P3 table cursor
  81091. ** to the row that corresponds to the current row of P1.
  81092. **
  81093. ** This is a deferred seek. Nothing actually happens until
  81094. ** the cursor is used to read a record. That way, if no reads
  81095. ** occur, no unnecessary I/O happens.
  81096. **
  81097. ** P4 may be an array of integers (type P4_INTARRAY) containing
  81098. ** one entry for each column in the P3 table. If array entry a(i)
  81099. ** is non-zero, then reading column a(i)-1 from cursor P3 is
  81100. ** equivalent to performing the deferred seek and then reading column i
  81101. ** from P1. This information is stored in P3 and used to redirect
  81102. ** reads against P3 over to P1, thus possibly avoiding the need to
  81103. ** seek and read cursor P3.
  81104. */
  81105. /* Opcode: IdxRowid P1 P2 * * *
  81106. ** Synopsis: r[P2]=rowid
  81107. **
  81108. ** Write into register P2 an integer which is the last entry in the record at
  81109. ** the end of the index key pointed to by cursor P1. This integer should be
  81110. ** the rowid of the table entry to which this index entry points.
  81111. **
  81112. ** See also: Rowid, MakeRecord.
  81113. */
  81114. case OP_DeferredSeek:
  81115. case OP_IdxRowid: { /* out2 */
  81116. VdbeCursor *pC; /* The P1 index cursor */
  81117. VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
  81118. i64 rowid; /* Rowid that P1 current points to */
  81119. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81120. pC = p->apCsr[pOp->p1];
  81121. assert( pC!=0 );
  81122. assert( pC->eCurType==CURTYPE_BTREE );
  81123. assert( pC->uc.pCursor!=0 );
  81124. assert( pC->isTable==0 );
  81125. assert( pC->deferredMoveto==0 );
  81126. assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
  81127. /* The IdxRowid and Seek opcodes are combined because of the commonality
  81128. ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
  81129. rc = sqlite3VdbeCursorRestore(pC);
  81130. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  81131. ** out from under the cursor. That will never happens for an IdxRowid
  81132. ** or Seek opcode */
  81133. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  81134. if( !pC->nullRow ){
  81135. rowid = 0; /* Not needed. Only used to silence a warning. */
  81136. rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
  81137. if( rc!=SQLITE_OK ){
  81138. goto abort_due_to_error;
  81139. }
  81140. if( pOp->opcode==OP_DeferredSeek ){
  81141. assert( pOp->p3>=0 && pOp->p3<p->nCursor );
  81142. pTabCur = p->apCsr[pOp->p3];
  81143. assert( pTabCur!=0 );
  81144. assert( pTabCur->eCurType==CURTYPE_BTREE );
  81145. assert( pTabCur->uc.pCursor!=0 );
  81146. assert( pTabCur->isTable );
  81147. pTabCur->nullRow = 0;
  81148. pTabCur->movetoTarget = rowid;
  81149. pTabCur->deferredMoveto = 1;
  81150. assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
  81151. pTabCur->aAltMap = pOp->p4.ai;
  81152. pTabCur->pAltCursor = pC;
  81153. }else{
  81154. pOut = out2Prerelease(p, pOp);
  81155. pOut->u.i = rowid;
  81156. }
  81157. }else{
  81158. assert( pOp->opcode==OP_IdxRowid );
  81159. sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
  81160. }
  81161. break;
  81162. }
  81163. /* Opcode: IdxGE P1 P2 P3 P4 P5
  81164. ** Synopsis: key=r[P3@P4]
  81165. **
  81166. ** The P4 register values beginning with P3 form an unpacked index
  81167. ** key that omits the PRIMARY KEY. Compare this key value against the index
  81168. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  81169. ** fields at the end.
  81170. **
  81171. ** If the P1 index entry is greater than or equal to the key value
  81172. ** then jump to P2. Otherwise fall through to the next instruction.
  81173. */
  81174. /* Opcode: IdxGT P1 P2 P3 P4 P5
  81175. ** Synopsis: key=r[P3@P4]
  81176. **
  81177. ** The P4 register values beginning with P3 form an unpacked index
  81178. ** key that omits the PRIMARY KEY. Compare this key value against the index
  81179. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  81180. ** fields at the end.
  81181. **
  81182. ** If the P1 index entry is greater than the key value
  81183. ** then jump to P2. Otherwise fall through to the next instruction.
  81184. */
  81185. /* Opcode: IdxLT P1 P2 P3 P4 P5
  81186. ** Synopsis: key=r[P3@P4]
  81187. **
  81188. ** The P4 register values beginning with P3 form an unpacked index
  81189. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  81190. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  81191. ** ROWID on the P1 index.
  81192. **
  81193. ** If the P1 index entry is less than the key value then jump to P2.
  81194. ** Otherwise fall through to the next instruction.
  81195. */
  81196. /* Opcode: IdxLE P1 P2 P3 P4 P5
  81197. ** Synopsis: key=r[P3@P4]
  81198. **
  81199. ** The P4 register values beginning with P3 form an unpacked index
  81200. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  81201. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  81202. ** ROWID on the P1 index.
  81203. **
  81204. ** If the P1 index entry is less than or equal to the key value then jump
  81205. ** to P2. Otherwise fall through to the next instruction.
  81206. */
  81207. case OP_IdxLE: /* jump */
  81208. case OP_IdxGT: /* jump */
  81209. case OP_IdxLT: /* jump */
  81210. case OP_IdxGE: { /* jump */
  81211. VdbeCursor *pC;
  81212. int res;
  81213. UnpackedRecord r;
  81214. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81215. pC = p->apCsr[pOp->p1];
  81216. assert( pC!=0 );
  81217. assert( pC->isOrdered );
  81218. assert( pC->eCurType==CURTYPE_BTREE );
  81219. assert( pC->uc.pCursor!=0);
  81220. assert( pC->deferredMoveto==0 );
  81221. assert( pOp->p5==0 || pOp->p5==1 );
  81222. assert( pOp->p4type==P4_INT32 );
  81223. r.pKeyInfo = pC->pKeyInfo;
  81224. r.nField = (u16)pOp->p4.i;
  81225. if( pOp->opcode<OP_IdxLT ){
  81226. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  81227. r.default_rc = -1;
  81228. }else{
  81229. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  81230. r.default_rc = 0;
  81231. }
  81232. r.aMem = &aMem[pOp->p3];
  81233. #ifdef SQLITE_DEBUG
  81234. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  81235. #endif
  81236. res = 0; /* Not needed. Only used to silence a warning. */
  81237. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  81238. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  81239. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  81240. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  81241. res = -res;
  81242. }else{
  81243. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  81244. res++;
  81245. }
  81246. VdbeBranchTaken(res>0,2);
  81247. if( rc ) goto abort_due_to_error;
  81248. if( res>0 ) goto jump_to_p2;
  81249. break;
  81250. }
  81251. /* Opcode: Destroy P1 P2 P3 * *
  81252. **
  81253. ** Delete an entire database table or index whose root page in the database
  81254. ** file is given by P1.
  81255. **
  81256. ** The table being destroyed is in the main database file if P3==0. If
  81257. ** P3==1 then the table to be clear is in the auxiliary database file
  81258. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  81259. **
  81260. ** If AUTOVACUUM is enabled then it is possible that another root page
  81261. ** might be moved into the newly deleted root page in order to keep all
  81262. ** root pages contiguous at the beginning of the database. The former
  81263. ** value of the root page that moved - its value before the move occurred -
  81264. ** is stored in register P2. If no page movement was required (because the
  81265. ** table being dropped was already the last one in the database) then a
  81266. ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
  81267. ** is stored in register P2.
  81268. **
  81269. ** This opcode throws an error if there are any active reader VMs when
  81270. ** it is invoked. This is done to avoid the difficulty associated with
  81271. ** updating existing cursors when a root page is moved in an AUTOVACUUM
  81272. ** database. This error is thrown even if the database is not an AUTOVACUUM
  81273. ** db in order to avoid introducing an incompatibility between autovacuum
  81274. ** and non-autovacuum modes.
  81275. **
  81276. ** See also: Clear
  81277. */
  81278. case OP_Destroy: { /* out2 */
  81279. int iMoved;
  81280. int iDb;
  81281. assert( p->readOnly==0 );
  81282. assert( pOp->p1>1 );
  81283. pOut = out2Prerelease(p, pOp);
  81284. pOut->flags = MEM_Null;
  81285. if( db->nVdbeRead > db->nVDestroy+1 ){
  81286. rc = SQLITE_LOCKED;
  81287. p->errorAction = OE_Abort;
  81288. goto abort_due_to_error;
  81289. }else{
  81290. iDb = pOp->p3;
  81291. assert( DbMaskTest(p->btreeMask, iDb) );
  81292. iMoved = 0; /* Not needed. Only to silence a warning. */
  81293. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  81294. pOut->flags = MEM_Int;
  81295. pOut->u.i = iMoved;
  81296. if( rc ) goto abort_due_to_error;
  81297. #ifndef SQLITE_OMIT_AUTOVACUUM
  81298. if( iMoved!=0 ){
  81299. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  81300. /* All OP_Destroy operations occur on the same btree */
  81301. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  81302. resetSchemaOnFault = iDb+1;
  81303. }
  81304. #endif
  81305. }
  81306. break;
  81307. }
  81308. /* Opcode: Clear P1 P2 P3
  81309. **
  81310. ** Delete all contents of the database table or index whose root page
  81311. ** in the database file is given by P1. But, unlike Destroy, do not
  81312. ** remove the table or index from the database file.
  81313. **
  81314. ** The table being clear is in the main database file if P2==0. If
  81315. ** P2==1 then the table to be clear is in the auxiliary database file
  81316. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  81317. **
  81318. ** If the P3 value is non-zero, then the table referred to must be an
  81319. ** intkey table (an SQL table, not an index). In this case the row change
  81320. ** count is incremented by the number of rows in the table being cleared.
  81321. ** If P3 is greater than zero, then the value stored in register P3 is
  81322. ** also incremented by the number of rows in the table being cleared.
  81323. **
  81324. ** See also: Destroy
  81325. */
  81326. case OP_Clear: {
  81327. int nChange;
  81328. nChange = 0;
  81329. assert( p->readOnly==0 );
  81330. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  81331. rc = sqlite3BtreeClearTable(
  81332. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  81333. );
  81334. if( pOp->p3 ){
  81335. p->nChange += nChange;
  81336. if( pOp->p3>0 ){
  81337. assert( memIsValid(&aMem[pOp->p3]) );
  81338. memAboutToChange(p, &aMem[pOp->p3]);
  81339. aMem[pOp->p3].u.i += nChange;
  81340. }
  81341. }
  81342. if( rc ) goto abort_due_to_error;
  81343. break;
  81344. }
  81345. /* Opcode: ResetSorter P1 * * * *
  81346. **
  81347. ** Delete all contents from the ephemeral table or sorter
  81348. ** that is open on cursor P1.
  81349. **
  81350. ** This opcode only works for cursors used for sorting and
  81351. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  81352. */
  81353. case OP_ResetSorter: {
  81354. VdbeCursor *pC;
  81355. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  81356. pC = p->apCsr[pOp->p1];
  81357. assert( pC!=0 );
  81358. if( isSorter(pC) ){
  81359. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  81360. }else{
  81361. assert( pC->eCurType==CURTYPE_BTREE );
  81362. assert( pC->isEphemeral );
  81363. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  81364. if( rc ) goto abort_due_to_error;
  81365. }
  81366. break;
  81367. }
  81368. /* Opcode: CreateBtree P1 P2 P3 * *
  81369. ** Synopsis: r[P2]=root iDb=P1 flags=P3
  81370. **
  81371. ** Allocate a new b-tree in the main database file if P1==0 or in the
  81372. ** TEMP database file if P1==1 or in an attached database if
  81373. ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
  81374. ** it must be 2 (BTREE_BLOBKEY) for a index or WITHOUT ROWID table.
  81375. ** The root page number of the new b-tree is stored in register P2.
  81376. */
  81377. case OP_CreateBtree: { /* out2 */
  81378. int pgno;
  81379. Db *pDb;
  81380. pOut = out2Prerelease(p, pOp);
  81381. pgno = 0;
  81382. assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
  81383. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  81384. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  81385. assert( p->readOnly==0 );
  81386. pDb = &db->aDb[pOp->p1];
  81387. assert( pDb->pBt!=0 );
  81388. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
  81389. if( rc ) goto abort_due_to_error;
  81390. pOut->u.i = pgno;
  81391. break;
  81392. }
  81393. /* Opcode: SqlExec * * * P4 *
  81394. **
  81395. ** Run the SQL statement or statements specified in the P4 string.
  81396. */
  81397. case OP_SqlExec: {
  81398. db->nSqlExec++;
  81399. rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
  81400. db->nSqlExec--;
  81401. if( rc ) goto abort_due_to_error;
  81402. break;
  81403. }
  81404. /* Opcode: ParseSchema P1 * * P4 *
  81405. **
  81406. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  81407. ** that match the WHERE clause P4.
  81408. **
  81409. ** This opcode invokes the parser to create a new virtual machine,
  81410. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  81411. */
  81412. case OP_ParseSchema: {
  81413. int iDb;
  81414. const char *zMaster;
  81415. char *zSql;
  81416. InitData initData;
  81417. /* Any prepared statement that invokes this opcode will hold mutexes
  81418. ** on every btree. This is a prerequisite for invoking
  81419. ** sqlite3InitCallback().
  81420. */
  81421. #ifdef SQLITE_DEBUG
  81422. for(iDb=0; iDb<db->nDb; iDb++){
  81423. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  81424. }
  81425. #endif
  81426. iDb = pOp->p1;
  81427. assert( iDb>=0 && iDb<db->nDb );
  81428. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  81429. /* Used to be a conditional */ {
  81430. zMaster = MASTER_NAME;
  81431. initData.db = db;
  81432. initData.iDb = pOp->p1;
  81433. initData.pzErrMsg = &p->zErrMsg;
  81434. zSql = sqlite3MPrintf(db,
  81435. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  81436. db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
  81437. if( zSql==0 ){
  81438. rc = SQLITE_NOMEM_BKPT;
  81439. }else{
  81440. assert( db->init.busy==0 );
  81441. db->init.busy = 1;
  81442. initData.rc = SQLITE_OK;
  81443. assert( !db->mallocFailed );
  81444. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  81445. if( rc==SQLITE_OK ) rc = initData.rc;
  81446. sqlite3DbFreeNN(db, zSql);
  81447. db->init.busy = 0;
  81448. }
  81449. }
  81450. if( rc ){
  81451. sqlite3ResetAllSchemasOfConnection(db);
  81452. if( rc==SQLITE_NOMEM ){
  81453. goto no_mem;
  81454. }
  81455. goto abort_due_to_error;
  81456. }
  81457. break;
  81458. }
  81459. #if !defined(SQLITE_OMIT_ANALYZE)
  81460. /* Opcode: LoadAnalysis P1 * * * *
  81461. **
  81462. ** Read the sqlite_stat1 table for database P1 and load the content
  81463. ** of that table into the internal index hash table. This will cause
  81464. ** the analysis to be used when preparing all subsequent queries.
  81465. */
  81466. case OP_LoadAnalysis: {
  81467. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  81468. rc = sqlite3AnalysisLoad(db, pOp->p1);
  81469. if( rc ) goto abort_due_to_error;
  81470. break;
  81471. }
  81472. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  81473. /* Opcode: DropTable P1 * * P4 *
  81474. **
  81475. ** Remove the internal (in-memory) data structures that describe
  81476. ** the table named P4 in database P1. This is called after a table
  81477. ** is dropped from disk (using the Destroy opcode) in order to keep
  81478. ** the internal representation of the
  81479. ** schema consistent with what is on disk.
  81480. */
  81481. case OP_DropTable: {
  81482. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  81483. break;
  81484. }
  81485. /* Opcode: DropIndex P1 * * P4 *
  81486. **
  81487. ** Remove the internal (in-memory) data structures that describe
  81488. ** the index named P4 in database P1. This is called after an index
  81489. ** is dropped from disk (using the Destroy opcode)
  81490. ** in order to keep the internal representation of the
  81491. ** schema consistent with what is on disk.
  81492. */
  81493. case OP_DropIndex: {
  81494. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  81495. break;
  81496. }
  81497. /* Opcode: DropTrigger P1 * * P4 *
  81498. **
  81499. ** Remove the internal (in-memory) data structures that describe
  81500. ** the trigger named P4 in database P1. This is called after a trigger
  81501. ** is dropped from disk (using the Destroy opcode) in order to keep
  81502. ** the internal representation of the
  81503. ** schema consistent with what is on disk.
  81504. */
  81505. case OP_DropTrigger: {
  81506. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  81507. break;
  81508. }
  81509. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  81510. /* Opcode: IntegrityCk P1 P2 P3 P4 P5
  81511. **
  81512. ** Do an analysis of the currently open database. Store in
  81513. ** register P1 the text of an error message describing any problems.
  81514. ** If no problems are found, store a NULL in register P1.
  81515. **
  81516. ** The register P3 contains one less than the maximum number of allowed errors.
  81517. ** At most reg(P3) errors will be reported.
  81518. ** In other words, the analysis stops as soon as reg(P1) errors are
  81519. ** seen. Reg(P1) is updated with the number of errors remaining.
  81520. **
  81521. ** The root page numbers of all tables in the database are integers
  81522. ** stored in P4_INTARRAY argument.
  81523. **
  81524. ** If P5 is not zero, the check is done on the auxiliary database
  81525. ** file, not the main database file.
  81526. **
  81527. ** This opcode is used to implement the integrity_check pragma.
  81528. */
  81529. case OP_IntegrityCk: {
  81530. int nRoot; /* Number of tables to check. (Number of root pages.) */
  81531. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  81532. int nErr; /* Number of errors reported */
  81533. char *z; /* Text of the error report */
  81534. Mem *pnErr; /* Register keeping track of errors remaining */
  81535. assert( p->bIsReader );
  81536. nRoot = pOp->p2;
  81537. aRoot = pOp->p4.ai;
  81538. assert( nRoot>0 );
  81539. assert( aRoot[0]==nRoot );
  81540. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  81541. pnErr = &aMem[pOp->p3];
  81542. assert( (pnErr->flags & MEM_Int)!=0 );
  81543. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  81544. pIn1 = &aMem[pOp->p1];
  81545. assert( pOp->p5<db->nDb );
  81546. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  81547. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
  81548. (int)pnErr->u.i+1, &nErr);
  81549. sqlite3VdbeMemSetNull(pIn1);
  81550. if( nErr==0 ){
  81551. assert( z==0 );
  81552. }else if( z==0 ){
  81553. goto no_mem;
  81554. }else{
  81555. pnErr->u.i -= nErr-1;
  81556. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  81557. }
  81558. UPDATE_MAX_BLOBSIZE(pIn1);
  81559. sqlite3VdbeChangeEncoding(pIn1, encoding);
  81560. break;
  81561. }
  81562. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  81563. /* Opcode: RowSetAdd P1 P2 * * *
  81564. ** Synopsis: rowset(P1)=r[P2]
  81565. **
  81566. ** Insert the integer value held by register P2 into a RowSet object
  81567. ** held in register P1.
  81568. **
  81569. ** An assertion fails if P2 is not an integer.
  81570. */
  81571. case OP_RowSetAdd: { /* in1, in2 */
  81572. pIn1 = &aMem[pOp->p1];
  81573. pIn2 = &aMem[pOp->p2];
  81574. assert( (pIn2->flags & MEM_Int)!=0 );
  81575. if( (pIn1->flags & MEM_RowSet)==0 ){
  81576. sqlite3VdbeMemSetRowSet(pIn1);
  81577. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  81578. }
  81579. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  81580. break;
  81581. }
  81582. /* Opcode: RowSetRead P1 P2 P3 * *
  81583. ** Synopsis: r[P3]=rowset(P1)
  81584. **
  81585. ** Extract the smallest value from the RowSet object in P1
  81586. ** and put that value into register P3.
  81587. ** Or, if RowSet object P1 is initially empty, leave P3
  81588. ** unchanged and jump to instruction P2.
  81589. */
  81590. case OP_RowSetRead: { /* jump, in1, out3 */
  81591. i64 val;
  81592. pIn1 = &aMem[pOp->p1];
  81593. if( (pIn1->flags & MEM_RowSet)==0
  81594. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  81595. ){
  81596. /* The boolean index is empty */
  81597. sqlite3VdbeMemSetNull(pIn1);
  81598. VdbeBranchTaken(1,2);
  81599. goto jump_to_p2_and_check_for_interrupt;
  81600. }else{
  81601. /* A value was pulled from the index */
  81602. VdbeBranchTaken(0,2);
  81603. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  81604. }
  81605. goto check_for_interrupt;
  81606. }
  81607. /* Opcode: RowSetTest P1 P2 P3 P4
  81608. ** Synopsis: if r[P3] in rowset(P1) goto P2
  81609. **
  81610. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  81611. ** contains a RowSet object and that RowSet object contains
  81612. ** the value held in P3, jump to register P2. Otherwise, insert the
  81613. ** integer in P3 into the RowSet and continue on to the
  81614. ** next opcode.
  81615. **
  81616. ** The RowSet object is optimized for the case where sets of integers
  81617. ** are inserted in distinct phases, which each set contains no duplicates.
  81618. ** Each set is identified by a unique P4 value. The first set
  81619. ** must have P4==0, the final set must have P4==-1, and for all other sets
  81620. ** must have P4>0.
  81621. **
  81622. ** This allows optimizations: (a) when P4==0 there is no need to test
  81623. ** the RowSet object for P3, as it is guaranteed not to contain it,
  81624. ** (b) when P4==-1 there is no need to insert the value, as it will
  81625. ** never be tested for, and (c) when a value that is part of set X is
  81626. ** inserted, there is no need to search to see if the same value was
  81627. ** previously inserted as part of set X (only if it was previously
  81628. ** inserted as part of some other set).
  81629. */
  81630. case OP_RowSetTest: { /* jump, in1, in3 */
  81631. int iSet;
  81632. int exists;
  81633. pIn1 = &aMem[pOp->p1];
  81634. pIn3 = &aMem[pOp->p3];
  81635. iSet = pOp->p4.i;
  81636. assert( pIn3->flags&MEM_Int );
  81637. /* If there is anything other than a rowset object in memory cell P1,
  81638. ** delete it now and initialize P1 with an empty rowset
  81639. */
  81640. if( (pIn1->flags & MEM_RowSet)==0 ){
  81641. sqlite3VdbeMemSetRowSet(pIn1);
  81642. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  81643. }
  81644. assert( pOp->p4type==P4_INT32 );
  81645. assert( iSet==-1 || iSet>=0 );
  81646. if( iSet ){
  81647. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  81648. VdbeBranchTaken(exists!=0,2);
  81649. if( exists ) goto jump_to_p2;
  81650. }
  81651. if( iSet>=0 ){
  81652. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  81653. }
  81654. break;
  81655. }
  81656. #ifndef SQLITE_OMIT_TRIGGER
  81657. /* Opcode: Program P1 P2 P3 P4 P5
  81658. **
  81659. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  81660. **
  81661. ** P1 contains the address of the memory cell that contains the first memory
  81662. ** cell in an array of values used as arguments to the sub-program. P2
  81663. ** contains the address to jump to if the sub-program throws an IGNORE
  81664. ** exception using the RAISE() function. Register P3 contains the address
  81665. ** of a memory cell in this (the parent) VM that is used to allocate the
  81666. ** memory required by the sub-vdbe at runtime.
  81667. **
  81668. ** P4 is a pointer to the VM containing the trigger program.
  81669. **
  81670. ** If P5 is non-zero, then recursive program invocation is enabled.
  81671. */
  81672. case OP_Program: { /* jump */
  81673. int nMem; /* Number of memory registers for sub-program */
  81674. int nByte; /* Bytes of runtime space required for sub-program */
  81675. Mem *pRt; /* Register to allocate runtime space */
  81676. Mem *pMem; /* Used to iterate through memory cells */
  81677. Mem *pEnd; /* Last memory cell in new array */
  81678. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  81679. SubProgram *pProgram; /* Sub-program to execute */
  81680. void *t; /* Token identifying trigger */
  81681. pProgram = pOp->p4.pProgram;
  81682. pRt = &aMem[pOp->p3];
  81683. assert( pProgram->nOp>0 );
  81684. /* If the p5 flag is clear, then recursive invocation of triggers is
  81685. ** disabled for backwards compatibility (p5 is set if this sub-program
  81686. ** is really a trigger, not a foreign key action, and the flag set
  81687. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  81688. **
  81689. ** It is recursive invocation of triggers, at the SQL level, that is
  81690. ** disabled. In some cases a single trigger may generate more than one
  81691. ** SubProgram (if the trigger may be executed with more than one different
  81692. ** ON CONFLICT algorithm). SubProgram structures associated with a
  81693. ** single trigger all have the same value for the SubProgram.token
  81694. ** variable. */
  81695. if( pOp->p5 ){
  81696. t = pProgram->token;
  81697. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  81698. if( pFrame ) break;
  81699. }
  81700. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  81701. rc = SQLITE_ERROR;
  81702. sqlite3VdbeError(p, "too many levels of trigger recursion");
  81703. goto abort_due_to_error;
  81704. }
  81705. /* Register pRt is used to store the memory required to save the state
  81706. ** of the current program, and the memory required at runtime to execute
  81707. ** the trigger program. If this trigger has been fired before, then pRt
  81708. ** is already allocated. Otherwise, it must be initialized. */
  81709. if( (pRt->flags&MEM_Frame)==0 ){
  81710. /* SubProgram.nMem is set to the number of memory cells used by the
  81711. ** program stored in SubProgram.aOp. As well as these, one memory
  81712. ** cell is required for each cursor used by the program. Set local
  81713. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  81714. */
  81715. nMem = pProgram->nMem + pProgram->nCsr;
  81716. assert( nMem>0 );
  81717. if( pProgram->nCsr==0 ) nMem++;
  81718. nByte = ROUND8(sizeof(VdbeFrame))
  81719. + nMem * sizeof(Mem)
  81720. + pProgram->nCsr * sizeof(VdbeCursor*)
  81721. + (pProgram->nOp + 7)/8;
  81722. pFrame = sqlite3DbMallocZero(db, nByte);
  81723. if( !pFrame ){
  81724. goto no_mem;
  81725. }
  81726. sqlite3VdbeMemRelease(pRt);
  81727. pRt->flags = MEM_Frame;
  81728. pRt->u.pFrame = pFrame;
  81729. pFrame->v = p;
  81730. pFrame->nChildMem = nMem;
  81731. pFrame->nChildCsr = pProgram->nCsr;
  81732. pFrame->pc = (int)(pOp - aOp);
  81733. pFrame->aMem = p->aMem;
  81734. pFrame->nMem = p->nMem;
  81735. pFrame->apCsr = p->apCsr;
  81736. pFrame->nCursor = p->nCursor;
  81737. pFrame->aOp = p->aOp;
  81738. pFrame->nOp = p->nOp;
  81739. pFrame->token = pProgram->token;
  81740. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  81741. pFrame->anExec = p->anExec;
  81742. #endif
  81743. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  81744. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  81745. pMem->flags = MEM_Undefined;
  81746. pMem->db = db;
  81747. }
  81748. }else{
  81749. pFrame = pRt->u.pFrame;
  81750. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
  81751. || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
  81752. assert( pProgram->nCsr==pFrame->nChildCsr );
  81753. assert( (int)(pOp - aOp)==pFrame->pc );
  81754. }
  81755. p->nFrame++;
  81756. pFrame->pParent = p->pFrame;
  81757. pFrame->lastRowid = db->lastRowid;
  81758. pFrame->nChange = p->nChange;
  81759. pFrame->nDbChange = p->db->nChange;
  81760. assert( pFrame->pAuxData==0 );
  81761. pFrame->pAuxData = p->pAuxData;
  81762. p->pAuxData = 0;
  81763. p->nChange = 0;
  81764. p->pFrame = pFrame;
  81765. p->aMem = aMem = VdbeFrameMem(pFrame);
  81766. p->nMem = pFrame->nChildMem;
  81767. p->nCursor = (u16)pFrame->nChildCsr;
  81768. p->apCsr = (VdbeCursor **)&aMem[p->nMem];
  81769. pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
  81770. memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
  81771. p->aOp = aOp = pProgram->aOp;
  81772. p->nOp = pProgram->nOp;
  81773. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  81774. p->anExec = 0;
  81775. #endif
  81776. pOp = &aOp[-1];
  81777. break;
  81778. }
  81779. /* Opcode: Param P1 P2 * * *
  81780. **
  81781. ** This opcode is only ever present in sub-programs called via the
  81782. ** OP_Program instruction. Copy a value currently stored in a memory
  81783. ** cell of the calling (parent) frame to cell P2 in the current frames
  81784. ** address space. This is used by trigger programs to access the new.*
  81785. ** and old.* values.
  81786. **
  81787. ** The address of the cell in the parent frame is determined by adding
  81788. ** the value of the P1 argument to the value of the P1 argument to the
  81789. ** calling OP_Program instruction.
  81790. */
  81791. case OP_Param: { /* out2 */
  81792. VdbeFrame *pFrame;
  81793. Mem *pIn;
  81794. pOut = out2Prerelease(p, pOp);
  81795. pFrame = p->pFrame;
  81796. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  81797. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  81798. break;
  81799. }
  81800. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  81801. #ifndef SQLITE_OMIT_FOREIGN_KEY
  81802. /* Opcode: FkCounter P1 P2 * * *
  81803. ** Synopsis: fkctr[P1]+=P2
  81804. **
  81805. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  81806. ** If P1 is non-zero, the database constraint counter is incremented
  81807. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  81808. ** statement counter is incremented (immediate foreign key constraints).
  81809. */
  81810. case OP_FkCounter: {
  81811. if( db->flags & SQLITE_DeferFKs ){
  81812. db->nDeferredImmCons += pOp->p2;
  81813. }else if( pOp->p1 ){
  81814. db->nDeferredCons += pOp->p2;
  81815. }else{
  81816. p->nFkConstraint += pOp->p2;
  81817. }
  81818. break;
  81819. }
  81820. /* Opcode: FkIfZero P1 P2 * * *
  81821. ** Synopsis: if fkctr[P1]==0 goto P2
  81822. **
  81823. ** This opcode tests if a foreign key constraint-counter is currently zero.
  81824. ** If so, jump to instruction P2. Otherwise, fall through to the next
  81825. ** instruction.
  81826. **
  81827. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  81828. ** is zero (the one that counts deferred constraint violations). If P1 is
  81829. ** zero, the jump is taken if the statement constraint-counter is zero
  81830. ** (immediate foreign key constraint violations).
  81831. */
  81832. case OP_FkIfZero: { /* jump */
  81833. if( pOp->p1 ){
  81834. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  81835. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  81836. }else{
  81837. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  81838. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  81839. }
  81840. break;
  81841. }
  81842. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  81843. #ifndef SQLITE_OMIT_AUTOINCREMENT
  81844. /* Opcode: MemMax P1 P2 * * *
  81845. ** Synopsis: r[P1]=max(r[P1],r[P2])
  81846. **
  81847. ** P1 is a register in the root frame of this VM (the root frame is
  81848. ** different from the current frame if this instruction is being executed
  81849. ** within a sub-program). Set the value of register P1 to the maximum of
  81850. ** its current value and the value in register P2.
  81851. **
  81852. ** This instruction throws an error if the memory cell is not initially
  81853. ** an integer.
  81854. */
  81855. case OP_MemMax: { /* in2 */
  81856. VdbeFrame *pFrame;
  81857. if( p->pFrame ){
  81858. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  81859. pIn1 = &pFrame->aMem[pOp->p1];
  81860. }else{
  81861. pIn1 = &aMem[pOp->p1];
  81862. }
  81863. assert( memIsValid(pIn1) );
  81864. sqlite3VdbeMemIntegerify(pIn1);
  81865. pIn2 = &aMem[pOp->p2];
  81866. sqlite3VdbeMemIntegerify(pIn2);
  81867. if( pIn1->u.i<pIn2->u.i){
  81868. pIn1->u.i = pIn2->u.i;
  81869. }
  81870. break;
  81871. }
  81872. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  81873. /* Opcode: IfPos P1 P2 P3 * *
  81874. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  81875. **
  81876. ** Register P1 must contain an integer.
  81877. ** If the value of register P1 is 1 or greater, subtract P3 from the
  81878. ** value in P1 and jump to P2.
  81879. **
  81880. ** If the initial value of register P1 is less than 1, then the
  81881. ** value is unchanged and control passes through to the next instruction.
  81882. */
  81883. case OP_IfPos: { /* jump, in1 */
  81884. pIn1 = &aMem[pOp->p1];
  81885. assert( pIn1->flags&MEM_Int );
  81886. VdbeBranchTaken( pIn1->u.i>0, 2);
  81887. if( pIn1->u.i>0 ){
  81888. pIn1->u.i -= pOp->p3;
  81889. goto jump_to_p2;
  81890. }
  81891. break;
  81892. }
  81893. /* Opcode: OffsetLimit P1 P2 P3 * *
  81894. ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
  81895. **
  81896. ** This opcode performs a commonly used computation associated with
  81897. ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
  81898. ** holds the offset counter. The opcode computes the combined value
  81899. ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
  81900. ** value computed is the total number of rows that will need to be
  81901. ** visited in order to complete the query.
  81902. **
  81903. ** If r[P3] is zero or negative, that means there is no OFFSET
  81904. ** and r[P2] is set to be the value of the LIMIT, r[P1].
  81905. **
  81906. ** if r[P1] is zero or negative, that means there is no LIMIT
  81907. ** and r[P2] is set to -1.
  81908. **
  81909. ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
  81910. */
  81911. case OP_OffsetLimit: { /* in1, out2, in3 */
  81912. i64 x;
  81913. pIn1 = &aMem[pOp->p1];
  81914. pIn3 = &aMem[pOp->p3];
  81915. pOut = out2Prerelease(p, pOp);
  81916. assert( pIn1->flags & MEM_Int );
  81917. assert( pIn3->flags & MEM_Int );
  81918. x = pIn1->u.i;
  81919. if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
  81920. /* If the LIMIT is less than or equal to zero, loop forever. This
  81921. ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
  81922. ** also loop forever. This is undocumented. In fact, one could argue
  81923. ** that the loop should terminate. But assuming 1 billion iterations
  81924. ** per second (far exceeding the capabilities of any current hardware)
  81925. ** it would take nearly 300 years to actually reach the limit. So
  81926. ** looping forever is a reasonable approximation. */
  81927. pOut->u.i = -1;
  81928. }else{
  81929. pOut->u.i = x;
  81930. }
  81931. break;
  81932. }
  81933. /* Opcode: IfNotZero P1 P2 * * *
  81934. ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
  81935. **
  81936. ** Register P1 must contain an integer. If the content of register P1 is
  81937. ** initially greater than zero, then decrement the value in register P1.
  81938. ** If it is non-zero (negative or positive) and then also jump to P2.
  81939. ** If register P1 is initially zero, leave it unchanged and fall through.
  81940. */
  81941. case OP_IfNotZero: { /* jump, in1 */
  81942. pIn1 = &aMem[pOp->p1];
  81943. assert( pIn1->flags&MEM_Int );
  81944. VdbeBranchTaken(pIn1->u.i<0, 2);
  81945. if( pIn1->u.i ){
  81946. if( pIn1->u.i>0 ) pIn1->u.i--;
  81947. goto jump_to_p2;
  81948. }
  81949. break;
  81950. }
  81951. /* Opcode: DecrJumpZero P1 P2 * * *
  81952. ** Synopsis: if (--r[P1])==0 goto P2
  81953. **
  81954. ** Register P1 must hold an integer. Decrement the value in P1
  81955. ** and jump to P2 if the new value is exactly zero.
  81956. */
  81957. case OP_DecrJumpZero: { /* jump, in1 */
  81958. pIn1 = &aMem[pOp->p1];
  81959. assert( pIn1->flags&MEM_Int );
  81960. if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
  81961. VdbeBranchTaken(pIn1->u.i==0, 2);
  81962. if( pIn1->u.i==0 ) goto jump_to_p2;
  81963. break;
  81964. }
  81965. /* Opcode: AggStep0 * P2 P3 P4 P5
  81966. ** Synopsis: accum=r[P3] step(r[P2@P5])
  81967. **
  81968. ** Execute the step function for an aggregate. The
  81969. ** function has P5 arguments. P4 is a pointer to the FuncDef
  81970. ** structure that specifies the function. Register P3 is the
  81971. ** accumulator.
  81972. **
  81973. ** The P5 arguments are taken from register P2 and its
  81974. ** successors.
  81975. */
  81976. /* Opcode: AggStep * P2 P3 P4 P5
  81977. ** Synopsis: accum=r[P3] step(r[P2@P5])
  81978. **
  81979. ** Execute the step function for an aggregate. The
  81980. ** function has P5 arguments. P4 is a pointer to an sqlite3_context
  81981. ** object that is used to run the function. Register P3 is
  81982. ** as the accumulator.
  81983. **
  81984. ** The P5 arguments are taken from register P2 and its
  81985. ** successors.
  81986. **
  81987. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  81988. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  81989. ** the opcode is changed. In this way, the initialization of the
  81990. ** sqlite3_context only happens once, instead of on each call to the
  81991. ** step function.
  81992. */
  81993. case OP_AggStep0: {
  81994. int n;
  81995. sqlite3_context *pCtx;
  81996. assert( pOp->p4type==P4_FUNCDEF );
  81997. n = pOp->p5;
  81998. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  81999. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  82000. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  82001. pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
  82002. (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
  82003. if( pCtx==0 ) goto no_mem;
  82004. pCtx->pMem = 0;
  82005. pCtx->pOut = (Mem*)&(pCtx->argv[n]);
  82006. sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
  82007. pCtx->pFunc = pOp->p4.pFunc;
  82008. pCtx->iOp = (int)(pOp - aOp);
  82009. pCtx->pVdbe = p;
  82010. pCtx->skipFlag = 0;
  82011. pCtx->isError = 0;
  82012. pCtx->argc = n;
  82013. pOp->p4type = P4_FUNCCTX;
  82014. pOp->p4.pCtx = pCtx;
  82015. pOp->opcode = OP_AggStep;
  82016. /* Fall through into OP_AggStep */
  82017. }
  82018. case OP_AggStep: {
  82019. int i;
  82020. sqlite3_context *pCtx;
  82021. Mem *pMem;
  82022. assert( pOp->p4type==P4_FUNCCTX );
  82023. pCtx = pOp->p4.pCtx;
  82024. pMem = &aMem[pOp->p3];
  82025. /* If this function is inside of a trigger, the register array in aMem[]
  82026. ** might change from one evaluation to the next. The next block of code
  82027. ** checks to see if the register array has changed, and if so it
  82028. ** reinitializes the relavant parts of the sqlite3_context object */
  82029. if( pCtx->pMem != pMem ){
  82030. pCtx->pMem = pMem;
  82031. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  82032. }
  82033. #ifdef SQLITE_DEBUG
  82034. for(i=0; i<pCtx->argc; i++){
  82035. assert( memIsValid(pCtx->argv[i]) );
  82036. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  82037. }
  82038. #endif
  82039. pMem->n++;
  82040. assert( pCtx->pOut->flags==MEM_Null );
  82041. assert( pCtx->isError==0 );
  82042. assert( pCtx->skipFlag==0 );
  82043. (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  82044. if( pCtx->isError ){
  82045. if( pCtx->isError>0 ){
  82046. sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
  82047. rc = pCtx->isError;
  82048. }
  82049. if( pCtx->skipFlag ){
  82050. assert( pOp[-1].opcode==OP_CollSeq );
  82051. i = pOp[-1].p1;
  82052. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  82053. pCtx->skipFlag = 0;
  82054. }
  82055. sqlite3VdbeMemRelease(pCtx->pOut);
  82056. pCtx->pOut->flags = MEM_Null;
  82057. pCtx->isError = 0;
  82058. if( rc ) goto abort_due_to_error;
  82059. }
  82060. assert( pCtx->pOut->flags==MEM_Null );
  82061. assert( pCtx->skipFlag==0 );
  82062. break;
  82063. }
  82064. /* Opcode: AggFinal P1 P2 * P4 *
  82065. ** Synopsis: accum=r[P1] N=P2
  82066. **
  82067. ** Execute the finalizer function for an aggregate. P1 is
  82068. ** the memory location that is the accumulator for the aggregate.
  82069. **
  82070. ** P2 is the number of arguments that the step function takes and
  82071. ** P4 is a pointer to the FuncDef for this function. The P2
  82072. ** argument is not used by this opcode. It is only there to disambiguate
  82073. ** functions that can take varying numbers of arguments. The
  82074. ** P4 argument is only needed for the degenerate case where
  82075. ** the step function was not previously called.
  82076. */
  82077. case OP_AggFinal: {
  82078. Mem *pMem;
  82079. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  82080. pMem = &aMem[pOp->p1];
  82081. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  82082. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  82083. if( rc ){
  82084. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  82085. goto abort_due_to_error;
  82086. }
  82087. sqlite3VdbeChangeEncoding(pMem, encoding);
  82088. UPDATE_MAX_BLOBSIZE(pMem);
  82089. if( sqlite3VdbeMemTooBig(pMem) ){
  82090. goto too_big;
  82091. }
  82092. break;
  82093. }
  82094. #ifndef SQLITE_OMIT_WAL
  82095. /* Opcode: Checkpoint P1 P2 P3 * *
  82096. **
  82097. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  82098. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  82099. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  82100. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  82101. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  82102. ** in the WAL that have been checkpointed after the checkpoint
  82103. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  82104. ** mem[P3+2] are initialized to -1.
  82105. */
  82106. case OP_Checkpoint: {
  82107. int i; /* Loop counter */
  82108. int aRes[3]; /* Results */
  82109. Mem *pMem; /* Write results here */
  82110. assert( p->readOnly==0 );
  82111. aRes[0] = 0;
  82112. aRes[1] = aRes[2] = -1;
  82113. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  82114. || pOp->p2==SQLITE_CHECKPOINT_FULL
  82115. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  82116. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  82117. );
  82118. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  82119. if( rc ){
  82120. if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
  82121. rc = SQLITE_OK;
  82122. aRes[0] = 1;
  82123. }
  82124. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  82125. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  82126. }
  82127. break;
  82128. };
  82129. #endif
  82130. #ifndef SQLITE_OMIT_PRAGMA
  82131. /* Opcode: JournalMode P1 P2 P3 * *
  82132. **
  82133. ** Change the journal mode of database P1 to P3. P3 must be one of the
  82134. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  82135. ** modes (delete, truncate, persist, off and memory), this is a simple
  82136. ** operation. No IO is required.
  82137. **
  82138. ** If changing into or out of WAL mode the procedure is more complicated.
  82139. **
  82140. ** Write a string containing the final journal-mode to register P2.
  82141. */
  82142. case OP_JournalMode: { /* out2 */
  82143. Btree *pBt; /* Btree to change journal mode of */
  82144. Pager *pPager; /* Pager associated with pBt */
  82145. int eNew; /* New journal mode */
  82146. int eOld; /* The old journal mode */
  82147. #ifndef SQLITE_OMIT_WAL
  82148. const char *zFilename; /* Name of database file for pPager */
  82149. #endif
  82150. pOut = out2Prerelease(p, pOp);
  82151. eNew = pOp->p3;
  82152. assert( eNew==PAGER_JOURNALMODE_DELETE
  82153. || eNew==PAGER_JOURNALMODE_TRUNCATE
  82154. || eNew==PAGER_JOURNALMODE_PERSIST
  82155. || eNew==PAGER_JOURNALMODE_OFF
  82156. || eNew==PAGER_JOURNALMODE_MEMORY
  82157. || eNew==PAGER_JOURNALMODE_WAL
  82158. || eNew==PAGER_JOURNALMODE_QUERY
  82159. );
  82160. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  82161. assert( p->readOnly==0 );
  82162. pBt = db->aDb[pOp->p1].pBt;
  82163. pPager = sqlite3BtreePager(pBt);
  82164. eOld = sqlite3PagerGetJournalMode(pPager);
  82165. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  82166. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  82167. #ifndef SQLITE_OMIT_WAL
  82168. zFilename = sqlite3PagerFilename(pPager, 1);
  82169. /* Do not allow a transition to journal_mode=WAL for a database
  82170. ** in temporary storage or if the VFS does not support shared memory
  82171. */
  82172. if( eNew==PAGER_JOURNALMODE_WAL
  82173. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  82174. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  82175. ){
  82176. eNew = eOld;
  82177. }
  82178. if( (eNew!=eOld)
  82179. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  82180. ){
  82181. if( !db->autoCommit || db->nVdbeRead>1 ){
  82182. rc = SQLITE_ERROR;
  82183. sqlite3VdbeError(p,
  82184. "cannot change %s wal mode from within a transaction",
  82185. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  82186. );
  82187. goto abort_due_to_error;
  82188. }else{
  82189. if( eOld==PAGER_JOURNALMODE_WAL ){
  82190. /* If leaving WAL mode, close the log file. If successful, the call
  82191. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  82192. ** file. An EXCLUSIVE lock may still be held on the database file
  82193. ** after a successful return.
  82194. */
  82195. rc = sqlite3PagerCloseWal(pPager, db);
  82196. if( rc==SQLITE_OK ){
  82197. sqlite3PagerSetJournalMode(pPager, eNew);
  82198. }
  82199. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  82200. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  82201. ** as an intermediate */
  82202. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  82203. }
  82204. /* Open a transaction on the database file. Regardless of the journal
  82205. ** mode, this transaction always uses a rollback journal.
  82206. */
  82207. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  82208. if( rc==SQLITE_OK ){
  82209. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  82210. }
  82211. }
  82212. }
  82213. #endif /* ifndef SQLITE_OMIT_WAL */
  82214. if( rc ) eNew = eOld;
  82215. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  82216. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  82217. pOut->z = (char *)sqlite3JournalModename(eNew);
  82218. pOut->n = sqlite3Strlen30(pOut->z);
  82219. pOut->enc = SQLITE_UTF8;
  82220. sqlite3VdbeChangeEncoding(pOut, encoding);
  82221. if( rc ) goto abort_due_to_error;
  82222. break;
  82223. };
  82224. #endif /* SQLITE_OMIT_PRAGMA */
  82225. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  82226. /* Opcode: Vacuum P1 * * * *
  82227. **
  82228. ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
  82229. ** for an attached database. The "temp" database may not be vacuumed.
  82230. */
  82231. case OP_Vacuum: {
  82232. assert( p->readOnly==0 );
  82233. rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1);
  82234. if( rc ) goto abort_due_to_error;
  82235. break;
  82236. }
  82237. #endif
  82238. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  82239. /* Opcode: IncrVacuum P1 P2 * * *
  82240. **
  82241. ** Perform a single step of the incremental vacuum procedure on
  82242. ** the P1 database. If the vacuum has finished, jump to instruction
  82243. ** P2. Otherwise, fall through to the next instruction.
  82244. */
  82245. case OP_IncrVacuum: { /* jump */
  82246. Btree *pBt;
  82247. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  82248. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  82249. assert( p->readOnly==0 );
  82250. pBt = db->aDb[pOp->p1].pBt;
  82251. rc = sqlite3BtreeIncrVacuum(pBt);
  82252. VdbeBranchTaken(rc==SQLITE_DONE,2);
  82253. if( rc ){
  82254. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  82255. rc = SQLITE_OK;
  82256. goto jump_to_p2;
  82257. }
  82258. break;
  82259. }
  82260. #endif
  82261. /* Opcode: Expire P1 * * * *
  82262. **
  82263. ** Cause precompiled statements to expire. When an expired statement
  82264. ** is executed using sqlite3_step() it will either automatically
  82265. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  82266. ** or it will fail with SQLITE_SCHEMA.
  82267. **
  82268. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  82269. ** then only the currently executing statement is expired.
  82270. */
  82271. case OP_Expire: {
  82272. if( !pOp->p1 ){
  82273. sqlite3ExpirePreparedStatements(db);
  82274. }else{
  82275. p->expired = 1;
  82276. }
  82277. break;
  82278. }
  82279. #ifndef SQLITE_OMIT_SHARED_CACHE
  82280. /* Opcode: TableLock P1 P2 P3 P4 *
  82281. ** Synopsis: iDb=P1 root=P2 write=P3
  82282. **
  82283. ** Obtain a lock on a particular table. This instruction is only used when
  82284. ** the shared-cache feature is enabled.
  82285. **
  82286. ** P1 is the index of the database in sqlite3.aDb[] of the database
  82287. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  82288. ** a write lock if P3==1.
  82289. **
  82290. ** P2 contains the root-page of the table to lock.
  82291. **
  82292. ** P4 contains a pointer to the name of the table being locked. This is only
  82293. ** used to generate an error message if the lock cannot be obtained.
  82294. */
  82295. case OP_TableLock: {
  82296. u8 isWriteLock = (u8)pOp->p3;
  82297. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
  82298. int p1 = pOp->p1;
  82299. assert( p1>=0 && p1<db->nDb );
  82300. assert( DbMaskTest(p->btreeMask, p1) );
  82301. assert( isWriteLock==0 || isWriteLock==1 );
  82302. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  82303. if( rc ){
  82304. if( (rc&0xFF)==SQLITE_LOCKED ){
  82305. const char *z = pOp->p4.z;
  82306. sqlite3VdbeError(p, "database table is locked: %s", z);
  82307. }
  82308. goto abort_due_to_error;
  82309. }
  82310. }
  82311. break;
  82312. }
  82313. #endif /* SQLITE_OMIT_SHARED_CACHE */
  82314. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82315. /* Opcode: VBegin * * * P4 *
  82316. **
  82317. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  82318. ** xBegin method for that table.
  82319. **
  82320. ** Also, whether or not P4 is set, check that this is not being called from
  82321. ** within a callback to a virtual table xSync() method. If it is, the error
  82322. ** code will be set to SQLITE_LOCKED.
  82323. */
  82324. case OP_VBegin: {
  82325. VTable *pVTab;
  82326. pVTab = pOp->p4.pVtab;
  82327. rc = sqlite3VtabBegin(db, pVTab);
  82328. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  82329. if( rc ) goto abort_due_to_error;
  82330. break;
  82331. }
  82332. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  82333. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82334. /* Opcode: VCreate P1 P2 * * *
  82335. **
  82336. ** P2 is a register that holds the name of a virtual table in database
  82337. ** P1. Call the xCreate method for that table.
  82338. */
  82339. case OP_VCreate: {
  82340. Mem sMem; /* For storing the record being decoded */
  82341. const char *zTab; /* Name of the virtual table */
  82342. memset(&sMem, 0, sizeof(sMem));
  82343. sMem.db = db;
  82344. /* Because P2 is always a static string, it is impossible for the
  82345. ** sqlite3VdbeMemCopy() to fail */
  82346. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  82347. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  82348. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  82349. assert( rc==SQLITE_OK );
  82350. zTab = (const char*)sqlite3_value_text(&sMem);
  82351. assert( zTab || db->mallocFailed );
  82352. if( zTab ){
  82353. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  82354. }
  82355. sqlite3VdbeMemRelease(&sMem);
  82356. if( rc ) goto abort_due_to_error;
  82357. break;
  82358. }
  82359. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  82360. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82361. /* Opcode: VDestroy P1 * * P4 *
  82362. **
  82363. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  82364. ** of that table.
  82365. */
  82366. case OP_VDestroy: {
  82367. db->nVDestroy++;
  82368. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  82369. db->nVDestroy--;
  82370. if( rc ) goto abort_due_to_error;
  82371. break;
  82372. }
  82373. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  82374. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82375. /* Opcode: VOpen P1 * * P4 *
  82376. **
  82377. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  82378. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  82379. ** table and stores that cursor in P1.
  82380. */
  82381. case OP_VOpen: {
  82382. VdbeCursor *pCur;
  82383. sqlite3_vtab_cursor *pVCur;
  82384. sqlite3_vtab *pVtab;
  82385. const sqlite3_module *pModule;
  82386. assert( p->bIsReader );
  82387. pCur = 0;
  82388. pVCur = 0;
  82389. pVtab = pOp->p4.pVtab->pVtab;
  82390. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  82391. rc = SQLITE_LOCKED;
  82392. goto abort_due_to_error;
  82393. }
  82394. pModule = pVtab->pModule;
  82395. rc = pModule->xOpen(pVtab, &pVCur);
  82396. sqlite3VtabImportErrmsg(p, pVtab);
  82397. if( rc ) goto abort_due_to_error;
  82398. /* Initialize sqlite3_vtab_cursor base class */
  82399. pVCur->pVtab = pVtab;
  82400. /* Initialize vdbe cursor object */
  82401. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  82402. if( pCur ){
  82403. pCur->uc.pVCur = pVCur;
  82404. pVtab->nRef++;
  82405. }else{
  82406. assert( db->mallocFailed );
  82407. pModule->xClose(pVCur);
  82408. goto no_mem;
  82409. }
  82410. break;
  82411. }
  82412. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  82413. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82414. /* Opcode: VFilter P1 P2 P3 P4 *
  82415. ** Synopsis: iplan=r[P3] zplan='P4'
  82416. **
  82417. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  82418. ** the filtered result set is empty.
  82419. **
  82420. ** P4 is either NULL or a string that was generated by the xBestIndex
  82421. ** method of the module. The interpretation of the P4 string is left
  82422. ** to the module implementation.
  82423. **
  82424. ** This opcode invokes the xFilter method on the virtual table specified
  82425. ** by P1. The integer query plan parameter to xFilter is stored in register
  82426. ** P3. Register P3+1 stores the argc parameter to be passed to the
  82427. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  82428. ** additional parameters which are passed to
  82429. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  82430. **
  82431. ** A jump is made to P2 if the result set after filtering would be empty.
  82432. */
  82433. case OP_VFilter: { /* jump */
  82434. int nArg;
  82435. int iQuery;
  82436. const sqlite3_module *pModule;
  82437. Mem *pQuery;
  82438. Mem *pArgc;
  82439. sqlite3_vtab_cursor *pVCur;
  82440. sqlite3_vtab *pVtab;
  82441. VdbeCursor *pCur;
  82442. int res;
  82443. int i;
  82444. Mem **apArg;
  82445. pQuery = &aMem[pOp->p3];
  82446. pArgc = &pQuery[1];
  82447. pCur = p->apCsr[pOp->p1];
  82448. assert( memIsValid(pQuery) );
  82449. REGISTER_TRACE(pOp->p3, pQuery);
  82450. assert( pCur->eCurType==CURTYPE_VTAB );
  82451. pVCur = pCur->uc.pVCur;
  82452. pVtab = pVCur->pVtab;
  82453. pModule = pVtab->pModule;
  82454. /* Grab the index number and argc parameters */
  82455. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  82456. nArg = (int)pArgc->u.i;
  82457. iQuery = (int)pQuery->u.i;
  82458. /* Invoke the xFilter method */
  82459. res = 0;
  82460. apArg = p->apArg;
  82461. for(i = 0; i<nArg; i++){
  82462. apArg[i] = &pArgc[i+1];
  82463. }
  82464. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  82465. sqlite3VtabImportErrmsg(p, pVtab);
  82466. if( rc ) goto abort_due_to_error;
  82467. res = pModule->xEof(pVCur);
  82468. pCur->nullRow = 0;
  82469. VdbeBranchTaken(res!=0,2);
  82470. if( res ) goto jump_to_p2;
  82471. break;
  82472. }
  82473. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  82474. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82475. /* Opcode: VColumn P1 P2 P3 * P5
  82476. ** Synopsis: r[P3]=vcolumn(P2)
  82477. **
  82478. ** Store in register P3 the value of the P2-th column of
  82479. ** the current row of the virtual-table of cursor P1.
  82480. **
  82481. ** If the VColumn opcode is being used to fetch the value of
  82482. ** an unchanging column during an UPDATE operation, then the P5
  82483. ** value is 1. Otherwise, P5 is 0. The P5 value is returned
  82484. ** by sqlite3_vtab_nochange() routine can can be used
  82485. ** by virtual table implementations to return special "no-change"
  82486. ** marks which can be more efficient, depending on the virtual table.
  82487. */
  82488. case OP_VColumn: {
  82489. sqlite3_vtab *pVtab;
  82490. const sqlite3_module *pModule;
  82491. Mem *pDest;
  82492. sqlite3_context sContext;
  82493. VdbeCursor *pCur = p->apCsr[pOp->p1];
  82494. assert( pCur->eCurType==CURTYPE_VTAB );
  82495. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  82496. pDest = &aMem[pOp->p3];
  82497. memAboutToChange(p, pDest);
  82498. if( pCur->nullRow ){
  82499. sqlite3VdbeMemSetNull(pDest);
  82500. break;
  82501. }
  82502. pVtab = pCur->uc.pVCur->pVtab;
  82503. pModule = pVtab->pModule;
  82504. assert( pModule->xColumn );
  82505. memset(&sContext, 0, sizeof(sContext));
  82506. sContext.pOut = pDest;
  82507. if( pOp->p5 ){
  82508. sqlite3VdbeMemSetNull(pDest);
  82509. pDest->flags = MEM_Null|MEM_Zero;
  82510. pDest->u.nZero = 0;
  82511. }else{
  82512. MemSetTypeFlag(pDest, MEM_Null);
  82513. }
  82514. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  82515. sqlite3VtabImportErrmsg(p, pVtab);
  82516. if( sContext.isError>0 ){
  82517. sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
  82518. rc = sContext.isError;
  82519. }
  82520. sqlite3VdbeChangeEncoding(pDest, encoding);
  82521. REGISTER_TRACE(pOp->p3, pDest);
  82522. UPDATE_MAX_BLOBSIZE(pDest);
  82523. if( sqlite3VdbeMemTooBig(pDest) ){
  82524. goto too_big;
  82525. }
  82526. if( rc ) goto abort_due_to_error;
  82527. break;
  82528. }
  82529. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  82530. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82531. /* Opcode: VNext P1 P2 * * *
  82532. **
  82533. ** Advance virtual table P1 to the next row in its result set and
  82534. ** jump to instruction P2. Or, if the virtual table has reached
  82535. ** the end of its result set, then fall through to the next instruction.
  82536. */
  82537. case OP_VNext: { /* jump */
  82538. sqlite3_vtab *pVtab;
  82539. const sqlite3_module *pModule;
  82540. int res;
  82541. VdbeCursor *pCur;
  82542. res = 0;
  82543. pCur = p->apCsr[pOp->p1];
  82544. assert( pCur->eCurType==CURTYPE_VTAB );
  82545. if( pCur->nullRow ){
  82546. break;
  82547. }
  82548. pVtab = pCur->uc.pVCur->pVtab;
  82549. pModule = pVtab->pModule;
  82550. assert( pModule->xNext );
  82551. /* Invoke the xNext() method of the module. There is no way for the
  82552. ** underlying implementation to return an error if one occurs during
  82553. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  82554. ** data is available) and the error code returned when xColumn or
  82555. ** some other method is next invoked on the save virtual table cursor.
  82556. */
  82557. rc = pModule->xNext(pCur->uc.pVCur);
  82558. sqlite3VtabImportErrmsg(p, pVtab);
  82559. if( rc ) goto abort_due_to_error;
  82560. res = pModule->xEof(pCur->uc.pVCur);
  82561. VdbeBranchTaken(!res,2);
  82562. if( !res ){
  82563. /* If there is data, jump to P2 */
  82564. goto jump_to_p2_and_check_for_interrupt;
  82565. }
  82566. goto check_for_interrupt;
  82567. }
  82568. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  82569. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82570. /* Opcode: VRename P1 * * P4 *
  82571. **
  82572. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  82573. ** This opcode invokes the corresponding xRename method. The value
  82574. ** in register P1 is passed as the zName argument to the xRename method.
  82575. */
  82576. case OP_VRename: {
  82577. sqlite3_vtab *pVtab;
  82578. Mem *pName;
  82579. pVtab = pOp->p4.pVtab->pVtab;
  82580. pName = &aMem[pOp->p1];
  82581. assert( pVtab->pModule->xRename );
  82582. assert( memIsValid(pName) );
  82583. assert( p->readOnly==0 );
  82584. REGISTER_TRACE(pOp->p1, pName);
  82585. assert( pName->flags & MEM_Str );
  82586. testcase( pName->enc==SQLITE_UTF8 );
  82587. testcase( pName->enc==SQLITE_UTF16BE );
  82588. testcase( pName->enc==SQLITE_UTF16LE );
  82589. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  82590. if( rc ) goto abort_due_to_error;
  82591. rc = pVtab->pModule->xRename(pVtab, pName->z);
  82592. sqlite3VtabImportErrmsg(p, pVtab);
  82593. p->expired = 0;
  82594. if( rc ) goto abort_due_to_error;
  82595. break;
  82596. }
  82597. #endif
  82598. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82599. /* Opcode: VUpdate P1 P2 P3 P4 P5
  82600. ** Synopsis: data=r[P3@P2]
  82601. **
  82602. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  82603. ** This opcode invokes the corresponding xUpdate method. P2 values
  82604. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  82605. ** invocation. The value in register (P3+P2-1) corresponds to the
  82606. ** p2th element of the argv array passed to xUpdate.
  82607. **
  82608. ** The xUpdate method will do a DELETE or an INSERT or both.
  82609. ** The argv[0] element (which corresponds to memory cell P3)
  82610. ** is the rowid of a row to delete. If argv[0] is NULL then no
  82611. ** deletion occurs. The argv[1] element is the rowid of the new
  82612. ** row. This can be NULL to have the virtual table select the new
  82613. ** rowid for itself. The subsequent elements in the array are
  82614. ** the values of columns in the new row.
  82615. **
  82616. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  82617. ** a row to delete.
  82618. **
  82619. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  82620. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  82621. ** is set to the value of the rowid for the row just inserted.
  82622. **
  82623. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  82624. ** apply in the case of a constraint failure on an insert or update.
  82625. */
  82626. case OP_VUpdate: {
  82627. sqlite3_vtab *pVtab;
  82628. const sqlite3_module *pModule;
  82629. int nArg;
  82630. int i;
  82631. sqlite_int64 rowid;
  82632. Mem **apArg;
  82633. Mem *pX;
  82634. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  82635. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  82636. );
  82637. assert( p->readOnly==0 );
  82638. pVtab = pOp->p4.pVtab->pVtab;
  82639. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  82640. rc = SQLITE_LOCKED;
  82641. goto abort_due_to_error;
  82642. }
  82643. pModule = pVtab->pModule;
  82644. nArg = pOp->p2;
  82645. assert( pOp->p4type==P4_VTAB );
  82646. if( ALWAYS(pModule->xUpdate) ){
  82647. u8 vtabOnConflict = db->vtabOnConflict;
  82648. apArg = p->apArg;
  82649. pX = &aMem[pOp->p3];
  82650. for(i=0; i<nArg; i++){
  82651. assert( memIsValid(pX) );
  82652. memAboutToChange(p, pX);
  82653. apArg[i] = pX;
  82654. pX++;
  82655. }
  82656. db->vtabOnConflict = pOp->p5;
  82657. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  82658. db->vtabOnConflict = vtabOnConflict;
  82659. sqlite3VtabImportErrmsg(p, pVtab);
  82660. if( rc==SQLITE_OK && pOp->p1 ){
  82661. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  82662. db->lastRowid = rowid;
  82663. }
  82664. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  82665. if( pOp->p5==OE_Ignore ){
  82666. rc = SQLITE_OK;
  82667. }else{
  82668. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  82669. }
  82670. }else{
  82671. p->nChange++;
  82672. }
  82673. if( rc ) goto abort_due_to_error;
  82674. }
  82675. break;
  82676. }
  82677. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  82678. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  82679. /* Opcode: Pagecount P1 P2 * * *
  82680. **
  82681. ** Write the current number of pages in database P1 to memory cell P2.
  82682. */
  82683. case OP_Pagecount: { /* out2 */
  82684. pOut = out2Prerelease(p, pOp);
  82685. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  82686. break;
  82687. }
  82688. #endif
  82689. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  82690. /* Opcode: MaxPgcnt P1 P2 P3 * *
  82691. **
  82692. ** Try to set the maximum page count for database P1 to the value in P3.
  82693. ** Do not let the maximum page count fall below the current page count and
  82694. ** do not change the maximum page count value if P3==0.
  82695. **
  82696. ** Store the maximum page count after the change in register P2.
  82697. */
  82698. case OP_MaxPgcnt: { /* out2 */
  82699. unsigned int newMax;
  82700. Btree *pBt;
  82701. pOut = out2Prerelease(p, pOp);
  82702. pBt = db->aDb[pOp->p1].pBt;
  82703. newMax = 0;
  82704. if( pOp->p3 ){
  82705. newMax = sqlite3BtreeLastPage(pBt);
  82706. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  82707. }
  82708. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  82709. break;
  82710. }
  82711. #endif
  82712. /* Opcode: Function0 P1 P2 P3 P4 P5
  82713. ** Synopsis: r[P3]=func(r[P2@P5])
  82714. **
  82715. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  82716. ** defines the function) with P5 arguments taken from register P2 and
  82717. ** successors. The result of the function is stored in register P3.
  82718. ** Register P3 must not be one of the function inputs.
  82719. **
  82720. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  82721. ** function was determined to be constant at compile time. If the first
  82722. ** argument was constant then bit 0 of P1 is set. This is used to determine
  82723. ** whether meta data associated with a user function argument using the
  82724. ** sqlite3_set_auxdata() API may be safely retained until the next
  82725. ** invocation of this opcode.
  82726. **
  82727. ** See also: Function, AggStep, AggFinal
  82728. */
  82729. /* Opcode: Function P1 P2 P3 P4 P5
  82730. ** Synopsis: r[P3]=func(r[P2@P5])
  82731. **
  82732. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  82733. ** contains a pointer to the function to be run) with P5 arguments taken
  82734. ** from register P2 and successors. The result of the function is stored
  82735. ** in register P3. Register P3 must not be one of the function inputs.
  82736. **
  82737. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  82738. ** function was determined to be constant at compile time. If the first
  82739. ** argument was constant then bit 0 of P1 is set. This is used to determine
  82740. ** whether meta data associated with a user function argument using the
  82741. ** sqlite3_set_auxdata() API may be safely retained until the next
  82742. ** invocation of this opcode.
  82743. **
  82744. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  82745. ** to a FuncDef object. But on first evaluation, the P4 operand is
  82746. ** automatically converted into an sqlite3_context object and the operation
  82747. ** changed to this OP_Function opcode. In this way, the initialization of
  82748. ** the sqlite3_context object occurs only once, rather than once for each
  82749. ** evaluation of the function.
  82750. **
  82751. ** See also: Function0, AggStep, AggFinal
  82752. */
  82753. case OP_PureFunc0:
  82754. case OP_Function0: {
  82755. int n;
  82756. sqlite3_context *pCtx;
  82757. assert( pOp->p4type==P4_FUNCDEF );
  82758. n = pOp->p5;
  82759. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  82760. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  82761. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  82762. pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  82763. if( pCtx==0 ) goto no_mem;
  82764. pCtx->pOut = 0;
  82765. pCtx->pFunc = pOp->p4.pFunc;
  82766. pCtx->iOp = (int)(pOp - aOp);
  82767. pCtx->pVdbe = p;
  82768. pCtx->isError = 0;
  82769. pCtx->argc = n;
  82770. pOp->p4type = P4_FUNCCTX;
  82771. pOp->p4.pCtx = pCtx;
  82772. assert( OP_PureFunc == OP_PureFunc0+2 );
  82773. assert( OP_Function == OP_Function0+2 );
  82774. pOp->opcode += 2;
  82775. /* Fall through into OP_Function */
  82776. }
  82777. case OP_PureFunc:
  82778. case OP_Function: {
  82779. int i;
  82780. sqlite3_context *pCtx;
  82781. assert( pOp->p4type==P4_FUNCCTX );
  82782. pCtx = pOp->p4.pCtx;
  82783. /* If this function is inside of a trigger, the register array in aMem[]
  82784. ** might change from one evaluation to the next. The next block of code
  82785. ** checks to see if the register array has changed, and if so it
  82786. ** reinitializes the relavant parts of the sqlite3_context object */
  82787. pOut = &aMem[pOp->p3];
  82788. if( pCtx->pOut != pOut ){
  82789. pCtx->pOut = pOut;
  82790. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  82791. }
  82792. memAboutToChange(p, pOut);
  82793. #ifdef SQLITE_DEBUG
  82794. for(i=0; i<pCtx->argc; i++){
  82795. assert( memIsValid(pCtx->argv[i]) );
  82796. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  82797. }
  82798. #endif
  82799. MemSetTypeFlag(pOut, MEM_Null);
  82800. assert( pCtx->isError==0 );
  82801. (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
  82802. /* If the function returned an error, throw an exception */
  82803. if( pCtx->isError ){
  82804. if( pCtx->isError>0 ){
  82805. sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
  82806. rc = pCtx->isError;
  82807. }
  82808. sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
  82809. pCtx->isError = 0;
  82810. if( rc ) goto abort_due_to_error;
  82811. }
  82812. /* Copy the result of the function into register P3 */
  82813. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  82814. sqlite3VdbeChangeEncoding(pOut, encoding);
  82815. if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
  82816. }
  82817. REGISTER_TRACE(pOp->p3, pOut);
  82818. UPDATE_MAX_BLOBSIZE(pOut);
  82819. break;
  82820. }
  82821. /* Opcode: Trace P1 P2 * P4 *
  82822. **
  82823. ** Write P4 on the statement trace output if statement tracing is
  82824. ** enabled.
  82825. **
  82826. ** Operand P1 must be 0x7fffffff and P2 must positive.
  82827. */
  82828. /* Opcode: Init P1 P2 P3 P4 *
  82829. ** Synopsis: Start at P2
  82830. **
  82831. ** Programs contain a single instance of this opcode as the very first
  82832. ** opcode.
  82833. **
  82834. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  82835. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  82836. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  82837. **
  82838. ** If P2 is not zero, jump to instruction P2.
  82839. **
  82840. ** Increment the value of P1 so that OP_Once opcodes will jump the
  82841. ** first time they are evaluated for this run.
  82842. **
  82843. ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
  82844. ** error is encountered.
  82845. */
  82846. case OP_Trace:
  82847. case OP_Init: { /* jump */
  82848. int i;
  82849. #ifndef SQLITE_OMIT_TRACE
  82850. char *zTrace;
  82851. #endif
  82852. /* If the P4 argument is not NULL, then it must be an SQL comment string.
  82853. ** The "--" string is broken up to prevent false-positives with srcck1.c.
  82854. **
  82855. ** This assert() provides evidence for:
  82856. ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
  82857. ** would have been returned by the legacy sqlite3_trace() interface by
  82858. ** using the X argument when X begins with "--" and invoking
  82859. ** sqlite3_expanded_sql(P) otherwise.
  82860. */
  82861. assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
  82862. /* OP_Init is always instruction 0 */
  82863. assert( pOp==p->aOp || pOp->opcode==OP_Trace );
  82864. #ifndef SQLITE_OMIT_TRACE
  82865. if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
  82866. && !p->doingRerun
  82867. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  82868. ){
  82869. #ifndef SQLITE_OMIT_DEPRECATED
  82870. if( db->mTrace & SQLITE_TRACE_LEGACY ){
  82871. void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
  82872. char *z = sqlite3VdbeExpandSql(p, zTrace);
  82873. x(db->pTraceArg, z);
  82874. sqlite3_free(z);
  82875. }else
  82876. #endif
  82877. if( db->nVdbeExec>1 ){
  82878. char *z = sqlite3MPrintf(db, "-- %s", zTrace);
  82879. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
  82880. sqlite3DbFree(db, z);
  82881. }else{
  82882. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
  82883. }
  82884. }
  82885. #ifdef SQLITE_USE_FCNTL_TRACE
  82886. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  82887. if( zTrace ){
  82888. int j;
  82889. for(j=0; j<db->nDb; j++){
  82890. if( DbMaskTest(p->btreeMask, j)==0 ) continue;
  82891. sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
  82892. }
  82893. }
  82894. #endif /* SQLITE_USE_FCNTL_TRACE */
  82895. #ifdef SQLITE_DEBUG
  82896. if( (db->flags & SQLITE_SqlTrace)!=0
  82897. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  82898. ){
  82899. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  82900. }
  82901. #endif /* SQLITE_DEBUG */
  82902. #endif /* SQLITE_OMIT_TRACE */
  82903. assert( pOp->p2>0 );
  82904. if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
  82905. if( pOp->opcode==OP_Trace ) break;
  82906. for(i=1; i<p->nOp; i++){
  82907. if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
  82908. }
  82909. pOp->p1 = 0;
  82910. }
  82911. pOp->p1++;
  82912. p->aCounter[SQLITE_STMTSTATUS_RUN]++;
  82913. goto jump_to_p2;
  82914. }
  82915. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  82916. /* Opcode: CursorHint P1 * * P4 *
  82917. **
  82918. ** Provide a hint to cursor P1 that it only needs to return rows that
  82919. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  82920. ** to values currently held in registers. TK_COLUMN terms in the P4
  82921. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  82922. */
  82923. case OP_CursorHint: {
  82924. VdbeCursor *pC;
  82925. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82926. assert( pOp->p4type==P4_EXPR );
  82927. pC = p->apCsr[pOp->p1];
  82928. if( pC ){
  82929. assert( pC->eCurType==CURTYPE_BTREE );
  82930. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  82931. pOp->p4.pExpr, aMem);
  82932. }
  82933. break;
  82934. }
  82935. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  82936. /* Opcode: Noop * * * * *
  82937. **
  82938. ** Do nothing. This instruction is often useful as a jump
  82939. ** destination.
  82940. */
  82941. /*
  82942. ** The magic Explain opcode are only inserted when explain==2 (which
  82943. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  82944. ** This opcode records information from the optimizer. It is the
  82945. ** the same as a no-op. This opcodesnever appears in a real VM program.
  82946. */
  82947. default: { /* This is really OP_Noop and OP_Explain */
  82948. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  82949. break;
  82950. }
  82951. /*****************************************************************************
  82952. ** The cases of the switch statement above this line should all be indented
  82953. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  82954. ** readability. From this point on down, the normal indentation rules are
  82955. ** restored.
  82956. *****************************************************************************/
  82957. }
  82958. #ifdef VDBE_PROFILE
  82959. {
  82960. u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  82961. if( endTime>start ) pOrigOp->cycles += endTime - start;
  82962. pOrigOp->cnt++;
  82963. }
  82964. #endif
  82965. /* The following code adds nothing to the actual functionality
  82966. ** of the program. It is only here for testing and debugging.
  82967. ** On the other hand, it does burn CPU cycles every time through
  82968. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  82969. */
  82970. #ifndef NDEBUG
  82971. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  82972. #ifdef SQLITE_DEBUG
  82973. if( db->flags & SQLITE_VdbeTrace ){
  82974. u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
  82975. if( rc!=0 ) printf("rc=%d\n",rc);
  82976. if( opProperty & (OPFLG_OUT2) ){
  82977. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  82978. }
  82979. if( opProperty & OPFLG_OUT3 ){
  82980. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  82981. }
  82982. }
  82983. #endif /* SQLITE_DEBUG */
  82984. #endif /* NDEBUG */
  82985. } /* The end of the for(;;) loop the loops through opcodes */
  82986. /* If we reach this point, it means that execution is finished with
  82987. ** an error of some kind.
  82988. */
  82989. abort_due_to_error:
  82990. if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
  82991. assert( rc );
  82992. if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
  82993. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  82994. }
  82995. p->rc = rc;
  82996. sqlite3SystemError(db, rc);
  82997. testcase( sqlite3GlobalConfig.xLog!=0 );
  82998. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  82999. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  83000. sqlite3VdbeHalt(p);
  83001. if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  83002. rc = SQLITE_ERROR;
  83003. if( resetSchemaOnFault>0 ){
  83004. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  83005. }
  83006. /* This is the only way out of this procedure. We have to
  83007. ** release the mutexes on btrees that were acquired at the
  83008. ** top. */
  83009. vdbe_return:
  83010. testcase( nVmStep>0 );
  83011. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  83012. sqlite3VdbeLeave(p);
  83013. assert( rc!=SQLITE_OK || nExtraDelete==0
  83014. || sqlite3_strlike("DELETE%",p->zSql,0)!=0
  83015. );
  83016. return rc;
  83017. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  83018. ** is encountered.
  83019. */
  83020. too_big:
  83021. sqlite3VdbeError(p, "string or blob too big");
  83022. rc = SQLITE_TOOBIG;
  83023. goto abort_due_to_error;
  83024. /* Jump to here if a malloc() fails.
  83025. */
  83026. no_mem:
  83027. sqlite3OomFault(db);
  83028. sqlite3VdbeError(p, "out of memory");
  83029. rc = SQLITE_NOMEM_BKPT;
  83030. goto abort_due_to_error;
  83031. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  83032. ** flag.
  83033. */
  83034. abort_due_to_interrupt:
  83035. assert( db->u1.isInterrupted );
  83036. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  83037. p->rc = rc;
  83038. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  83039. goto abort_due_to_error;
  83040. }
  83041. /************** End of vdbe.c ************************************************/
  83042. /************** Begin file vdbeblob.c ****************************************/
  83043. /*
  83044. ** 2007 May 1
  83045. **
  83046. ** The author disclaims copyright to this source code. In place of
  83047. ** a legal notice, here is a blessing:
  83048. **
  83049. ** May you do good and not evil.
  83050. ** May you find forgiveness for yourself and forgive others.
  83051. ** May you share freely, never taking more than you give.
  83052. **
  83053. *************************************************************************
  83054. **
  83055. ** This file contains code used to implement incremental BLOB I/O.
  83056. */
  83057. /* #include "sqliteInt.h" */
  83058. /* #include "vdbeInt.h" */
  83059. #ifndef SQLITE_OMIT_INCRBLOB
  83060. /*
  83061. ** Valid sqlite3_blob* handles point to Incrblob structures.
  83062. */
  83063. typedef struct Incrblob Incrblob;
  83064. struct Incrblob {
  83065. int nByte; /* Size of open blob, in bytes */
  83066. int iOffset; /* Byte offset of blob in cursor data */
  83067. u16 iCol; /* Table column this handle is open on */
  83068. BtCursor *pCsr; /* Cursor pointing at blob row */
  83069. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  83070. sqlite3 *db; /* The associated database */
  83071. char *zDb; /* Database name */
  83072. Table *pTab; /* Table object */
  83073. };
  83074. /*
  83075. ** This function is used by both blob_open() and blob_reopen(). It seeks
  83076. ** the b-tree cursor associated with blob handle p to point to row iRow.
  83077. ** If successful, SQLITE_OK is returned and subsequent calls to
  83078. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  83079. **
  83080. ** If an error occurs, or if the specified row does not exist or does not
  83081. ** contain a value of type TEXT or BLOB in the column nominated when the
  83082. ** blob handle was opened, then an error code is returned and *pzErr may
  83083. ** be set to point to a buffer containing an error message. It is the
  83084. ** responsibility of the caller to free the error message buffer using
  83085. ** sqlite3DbFree().
  83086. **
  83087. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  83088. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  83089. ** immediately return SQLITE_ABORT.
  83090. */
  83091. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  83092. int rc; /* Error code */
  83093. char *zErr = 0; /* Error message */
  83094. Vdbe *v = (Vdbe *)p->pStmt;
  83095. /* Set the value of register r[1] in the SQL statement to integer iRow.
  83096. ** This is done directly as a performance optimization
  83097. */
  83098. v->aMem[1].flags = MEM_Int;
  83099. v->aMem[1].u.i = iRow;
  83100. /* If the statement has been run before (and is paused at the OP_ResultRow)
  83101. ** then back it up to the point where it does the OP_NotExists. This could
  83102. ** have been down with an extra OP_Goto, but simply setting the program
  83103. ** counter is faster. */
  83104. if( v->pc>4 ){
  83105. v->pc = 4;
  83106. assert( v->aOp[v->pc].opcode==OP_NotExists );
  83107. rc = sqlite3VdbeExec(v);
  83108. }else{
  83109. rc = sqlite3_step(p->pStmt);
  83110. }
  83111. if( rc==SQLITE_ROW ){
  83112. VdbeCursor *pC = v->apCsr[0];
  83113. u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
  83114. testcase( pC->nHdrParsed==p->iCol );
  83115. testcase( pC->nHdrParsed==p->iCol+1 );
  83116. if( type<12 ){
  83117. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  83118. type==0?"null": type==7?"real": "integer"
  83119. );
  83120. rc = SQLITE_ERROR;
  83121. sqlite3_finalize(p->pStmt);
  83122. p->pStmt = 0;
  83123. }else{
  83124. p->iOffset = pC->aType[p->iCol + pC->nField];
  83125. p->nByte = sqlite3VdbeSerialTypeLen(type);
  83126. p->pCsr = pC->uc.pCursor;
  83127. sqlite3BtreeIncrblobCursor(p->pCsr);
  83128. }
  83129. }
  83130. if( rc==SQLITE_ROW ){
  83131. rc = SQLITE_OK;
  83132. }else if( p->pStmt ){
  83133. rc = sqlite3_finalize(p->pStmt);
  83134. p->pStmt = 0;
  83135. if( rc==SQLITE_OK ){
  83136. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  83137. rc = SQLITE_ERROR;
  83138. }else{
  83139. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  83140. }
  83141. }
  83142. assert( rc!=SQLITE_OK || zErr==0 );
  83143. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  83144. *pzErr = zErr;
  83145. return rc;
  83146. }
  83147. /*
  83148. ** Open a blob handle.
  83149. */
  83150. SQLITE_API int sqlite3_blob_open(
  83151. sqlite3* db, /* The database connection */
  83152. const char *zDb, /* The attached database containing the blob */
  83153. const char *zTable, /* The table containing the blob */
  83154. const char *zColumn, /* The column containing the blob */
  83155. sqlite_int64 iRow, /* The row containing the glob */
  83156. int wrFlag, /* True -> read/write access, false -> read-only */
  83157. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  83158. ){
  83159. int nAttempt = 0;
  83160. int iCol; /* Index of zColumn in row-record */
  83161. int rc = SQLITE_OK;
  83162. char *zErr = 0;
  83163. Table *pTab;
  83164. Incrblob *pBlob = 0;
  83165. Parse sParse;
  83166. #ifdef SQLITE_ENABLE_API_ARMOR
  83167. if( ppBlob==0 ){
  83168. return SQLITE_MISUSE_BKPT;
  83169. }
  83170. #endif
  83171. *ppBlob = 0;
  83172. #ifdef SQLITE_ENABLE_API_ARMOR
  83173. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  83174. return SQLITE_MISUSE_BKPT;
  83175. }
  83176. #endif
  83177. wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
  83178. sqlite3_mutex_enter(db->mutex);
  83179. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  83180. do {
  83181. memset(&sParse, 0, sizeof(Parse));
  83182. if( !pBlob ) goto blob_open_out;
  83183. sParse.db = db;
  83184. sqlite3DbFree(db, zErr);
  83185. zErr = 0;
  83186. sqlite3BtreeEnterAll(db);
  83187. pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
  83188. if( pTab && IsVirtual(pTab) ){
  83189. pTab = 0;
  83190. sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
  83191. }
  83192. if( pTab && !HasRowid(pTab) ){
  83193. pTab = 0;
  83194. sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
  83195. }
  83196. #ifndef SQLITE_OMIT_VIEW
  83197. if( pTab && pTab->pSelect ){
  83198. pTab = 0;
  83199. sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
  83200. }
  83201. #endif
  83202. if( !pTab ){
  83203. if( sParse.zErrMsg ){
  83204. sqlite3DbFree(db, zErr);
  83205. zErr = sParse.zErrMsg;
  83206. sParse.zErrMsg = 0;
  83207. }
  83208. rc = SQLITE_ERROR;
  83209. sqlite3BtreeLeaveAll(db);
  83210. goto blob_open_out;
  83211. }
  83212. pBlob->pTab = pTab;
  83213. pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
  83214. /* Now search pTab for the exact column. */
  83215. for(iCol=0; iCol<pTab->nCol; iCol++) {
  83216. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  83217. break;
  83218. }
  83219. }
  83220. if( iCol==pTab->nCol ){
  83221. sqlite3DbFree(db, zErr);
  83222. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  83223. rc = SQLITE_ERROR;
  83224. sqlite3BtreeLeaveAll(db);
  83225. goto blob_open_out;
  83226. }
  83227. /* If the value is being opened for writing, check that the
  83228. ** column is not indexed, and that it is not part of a foreign key.
  83229. */
  83230. if( wrFlag ){
  83231. const char *zFault = 0;
  83232. Index *pIdx;
  83233. #ifndef SQLITE_OMIT_FOREIGN_KEY
  83234. if( db->flags&SQLITE_ForeignKeys ){
  83235. /* Check that the column is not part of an FK child key definition. It
  83236. ** is not necessary to check if it is part of a parent key, as parent
  83237. ** key columns must be indexed. The check below will pick up this
  83238. ** case. */
  83239. FKey *pFKey;
  83240. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  83241. int j;
  83242. for(j=0; j<pFKey->nCol; j++){
  83243. if( pFKey->aCol[j].iFrom==iCol ){
  83244. zFault = "foreign key";
  83245. }
  83246. }
  83247. }
  83248. }
  83249. #endif
  83250. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  83251. int j;
  83252. for(j=0; j<pIdx->nKeyCol; j++){
  83253. /* FIXME: Be smarter about indexes that use expressions */
  83254. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  83255. zFault = "indexed";
  83256. }
  83257. }
  83258. }
  83259. if( zFault ){
  83260. sqlite3DbFree(db, zErr);
  83261. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  83262. rc = SQLITE_ERROR;
  83263. sqlite3BtreeLeaveAll(db);
  83264. goto blob_open_out;
  83265. }
  83266. }
  83267. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
  83268. assert( pBlob->pStmt || db->mallocFailed );
  83269. if( pBlob->pStmt ){
  83270. /* This VDBE program seeks a btree cursor to the identified
  83271. ** db/table/row entry. The reason for using a vdbe program instead
  83272. ** of writing code to use the b-tree layer directly is that the
  83273. ** vdbe program will take advantage of the various transaction,
  83274. ** locking and error handling infrastructure built into the vdbe.
  83275. **
  83276. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  83277. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  83278. ** uses it to implement the blob_read(), blob_write() and
  83279. ** blob_bytes() functions.
  83280. **
  83281. ** The sqlite3_blob_close() function finalizes the vdbe program,
  83282. ** which closes the b-tree cursor and (possibly) commits the
  83283. ** transaction.
  83284. */
  83285. static const int iLn = VDBE_OFFSET_LINENO(2);
  83286. static const VdbeOpList openBlob[] = {
  83287. {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
  83288. {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
  83289. /* blobSeekToRow() will initialize r[1] to the desired rowid */
  83290. {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
  83291. {OP_Column, 0, 0, 1}, /* 3 */
  83292. {OP_ResultRow, 1, 0, 0}, /* 4 */
  83293. {OP_Halt, 0, 0, 0}, /* 5 */
  83294. };
  83295. Vdbe *v = (Vdbe *)pBlob->pStmt;
  83296. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  83297. VdbeOp *aOp;
  83298. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
  83299. pTab->pSchema->schema_cookie,
  83300. pTab->pSchema->iGeneration);
  83301. sqlite3VdbeChangeP5(v, 1);
  83302. assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
  83303. aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  83304. /* Make sure a mutex is held on the table to be accessed */
  83305. sqlite3VdbeUsesBtree(v, iDb);
  83306. if( db->mallocFailed==0 ){
  83307. assert( aOp!=0 );
  83308. /* Configure the OP_TableLock instruction */
  83309. #ifdef SQLITE_OMIT_SHARED_CACHE
  83310. aOp[0].opcode = OP_Noop;
  83311. #else
  83312. aOp[0].p1 = iDb;
  83313. aOp[0].p2 = pTab->tnum;
  83314. aOp[0].p3 = wrFlag;
  83315. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  83316. }
  83317. if( db->mallocFailed==0 ){
  83318. #endif
  83319. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  83320. ** parameter of the other to pTab->tnum. */
  83321. if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
  83322. aOp[1].p2 = pTab->tnum;
  83323. aOp[1].p3 = iDb;
  83324. /* Configure the number of columns. Configure the cursor to
  83325. ** think that the table has one more column than it really
  83326. ** does. An OP_Column to retrieve this imaginary column will
  83327. ** always return an SQL NULL. This is useful because it means
  83328. ** we can invoke OP_Column to fill in the vdbe cursors type
  83329. ** and offset cache without causing any IO.
  83330. */
  83331. aOp[1].p4type = P4_INT32;
  83332. aOp[1].p4.i = pTab->nCol+1;
  83333. aOp[3].p2 = pTab->nCol;
  83334. sParse.nVar = 0;
  83335. sParse.nMem = 1;
  83336. sParse.nTab = 1;
  83337. sqlite3VdbeMakeReady(v, &sParse);
  83338. }
  83339. }
  83340. pBlob->iCol = iCol;
  83341. pBlob->db = db;
  83342. sqlite3BtreeLeaveAll(db);
  83343. if( db->mallocFailed ){
  83344. goto blob_open_out;
  83345. }
  83346. rc = blobSeekToRow(pBlob, iRow, &zErr);
  83347. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  83348. blob_open_out:
  83349. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  83350. *ppBlob = (sqlite3_blob *)pBlob;
  83351. }else{
  83352. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  83353. sqlite3DbFree(db, pBlob);
  83354. }
  83355. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  83356. sqlite3DbFree(db, zErr);
  83357. sqlite3ParserReset(&sParse);
  83358. rc = sqlite3ApiExit(db, rc);
  83359. sqlite3_mutex_leave(db->mutex);
  83360. return rc;
  83361. }
  83362. /*
  83363. ** Close a blob handle that was previously created using
  83364. ** sqlite3_blob_open().
  83365. */
  83366. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  83367. Incrblob *p = (Incrblob *)pBlob;
  83368. int rc;
  83369. sqlite3 *db;
  83370. if( p ){
  83371. db = p->db;
  83372. sqlite3_mutex_enter(db->mutex);
  83373. rc = sqlite3_finalize(p->pStmt);
  83374. sqlite3DbFree(db, p);
  83375. sqlite3_mutex_leave(db->mutex);
  83376. }else{
  83377. rc = SQLITE_OK;
  83378. }
  83379. return rc;
  83380. }
  83381. /*
  83382. ** Perform a read or write operation on a blob
  83383. */
  83384. static int blobReadWrite(
  83385. sqlite3_blob *pBlob,
  83386. void *z,
  83387. int n,
  83388. int iOffset,
  83389. int (*xCall)(BtCursor*, u32, u32, void*)
  83390. ){
  83391. int rc;
  83392. Incrblob *p = (Incrblob *)pBlob;
  83393. Vdbe *v;
  83394. sqlite3 *db;
  83395. if( p==0 ) return SQLITE_MISUSE_BKPT;
  83396. db = p->db;
  83397. sqlite3_mutex_enter(db->mutex);
  83398. v = (Vdbe*)p->pStmt;
  83399. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  83400. /* Request is out of range. Return a transient error. */
  83401. rc = SQLITE_ERROR;
  83402. }else if( v==0 ){
  83403. /* If there is no statement handle, then the blob-handle has
  83404. ** already been invalidated. Return SQLITE_ABORT in this case.
  83405. */
  83406. rc = SQLITE_ABORT;
  83407. }else{
  83408. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  83409. ** returned, clean-up the statement handle.
  83410. */
  83411. assert( db == v->db );
  83412. sqlite3BtreeEnterCursor(p->pCsr);
  83413. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  83414. if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
  83415. /* If a pre-update hook is registered and this is a write cursor,
  83416. ** invoke it here.
  83417. **
  83418. ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
  83419. ** operation should really be an SQLITE_UPDATE. This is probably
  83420. ** incorrect, but is convenient because at this point the new.* values
  83421. ** are not easily obtainable. And for the sessions module, an
  83422. ** SQLITE_UPDATE where the PK columns do not change is handled in the
  83423. ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
  83424. ** slightly more efficient). Since you cannot write to a PK column
  83425. ** using the incremental-blob API, this works. For the sessions module
  83426. ** anyhow.
  83427. */
  83428. sqlite3_int64 iKey;
  83429. iKey = sqlite3BtreeIntegerKey(p->pCsr);
  83430. sqlite3VdbePreUpdateHook(
  83431. v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
  83432. );
  83433. }
  83434. #endif
  83435. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  83436. sqlite3BtreeLeaveCursor(p->pCsr);
  83437. if( rc==SQLITE_ABORT ){
  83438. sqlite3VdbeFinalize(v);
  83439. p->pStmt = 0;
  83440. }else{
  83441. v->rc = rc;
  83442. }
  83443. }
  83444. sqlite3Error(db, rc);
  83445. rc = sqlite3ApiExit(db, rc);
  83446. sqlite3_mutex_leave(db->mutex);
  83447. return rc;
  83448. }
  83449. /*
  83450. ** Read data from a blob handle.
  83451. */
  83452. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  83453. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
  83454. }
  83455. /*
  83456. ** Write data to a blob handle.
  83457. */
  83458. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  83459. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  83460. }
  83461. /*
  83462. ** Query a blob handle for the size of the data.
  83463. **
  83464. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  83465. ** so no mutex is required for access.
  83466. */
  83467. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  83468. Incrblob *p = (Incrblob *)pBlob;
  83469. return (p && p->pStmt) ? p->nByte : 0;
  83470. }
  83471. /*
  83472. ** Move an existing blob handle to point to a different row of the same
  83473. ** database table.
  83474. **
  83475. ** If an error occurs, or if the specified row does not exist or does not
  83476. ** contain a blob or text value, then an error code is returned and the
  83477. ** database handle error code and message set. If this happens, then all
  83478. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  83479. ** immediately return SQLITE_ABORT.
  83480. */
  83481. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  83482. int rc;
  83483. Incrblob *p = (Incrblob *)pBlob;
  83484. sqlite3 *db;
  83485. if( p==0 ) return SQLITE_MISUSE_BKPT;
  83486. db = p->db;
  83487. sqlite3_mutex_enter(db->mutex);
  83488. if( p->pStmt==0 ){
  83489. /* If there is no statement handle, then the blob-handle has
  83490. ** already been invalidated. Return SQLITE_ABORT in this case.
  83491. */
  83492. rc = SQLITE_ABORT;
  83493. }else{
  83494. char *zErr;
  83495. rc = blobSeekToRow(p, iRow, &zErr);
  83496. if( rc!=SQLITE_OK ){
  83497. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  83498. sqlite3DbFree(db, zErr);
  83499. }
  83500. assert( rc!=SQLITE_SCHEMA );
  83501. }
  83502. rc = sqlite3ApiExit(db, rc);
  83503. assert( rc==SQLITE_OK || p->pStmt==0 );
  83504. sqlite3_mutex_leave(db->mutex);
  83505. return rc;
  83506. }
  83507. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  83508. /************** End of vdbeblob.c ********************************************/
  83509. /************** Begin file vdbesort.c ****************************************/
  83510. /*
  83511. ** 2011-07-09
  83512. **
  83513. ** The author disclaims copyright to this source code. In place of
  83514. ** a legal notice, here is a blessing:
  83515. **
  83516. ** May you do good and not evil.
  83517. ** May you find forgiveness for yourself and forgive others.
  83518. ** May you share freely, never taking more than you give.
  83519. **
  83520. *************************************************************************
  83521. ** This file contains code for the VdbeSorter object, used in concert with
  83522. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  83523. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  83524. ** using indexes and without LIMIT clauses.
  83525. **
  83526. ** The VdbeSorter object implements a multi-threaded external merge sort
  83527. ** algorithm that is efficient even if the number of elements being sorted
  83528. ** exceeds the available memory.
  83529. **
  83530. ** Here is the (internal, non-API) interface between this module and the
  83531. ** rest of the SQLite system:
  83532. **
  83533. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  83534. **
  83535. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  83536. ** object. The row is a binary blob in the
  83537. ** OP_MakeRecord format that contains both
  83538. ** the ORDER BY key columns and result columns
  83539. ** in the case of a SELECT w/ ORDER BY, or
  83540. ** the complete record for an index entry
  83541. ** in the case of a CREATE INDEX.
  83542. **
  83543. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  83544. ** Position the read cursor on the
  83545. ** first sorted element.
  83546. **
  83547. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  83548. ** element.
  83549. **
  83550. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  83551. ** row currently under the read cursor.
  83552. **
  83553. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  83554. ** currently under the read cursor against
  83555. ** another binary blob X and report if
  83556. ** X is strictly less than the read cursor.
  83557. ** Used to enforce uniqueness in a
  83558. ** CREATE UNIQUE INDEX statement.
  83559. **
  83560. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  83561. ** all resources.
  83562. **
  83563. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  83564. ** is like Close() followed by Init() only
  83565. ** much faster.
  83566. **
  83567. ** The interfaces above must be called in a particular order. Write() can
  83568. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  83569. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  83570. **
  83571. ** Init()
  83572. ** for each record: Write()
  83573. ** Rewind()
  83574. ** Rowkey()/Compare()
  83575. ** Next()
  83576. ** Close()
  83577. **
  83578. ** Algorithm:
  83579. **
  83580. ** Records passed to the sorter via calls to Write() are initially held
  83581. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  83582. ** a threshold, when Rewind() is called the set of records is sorted using
  83583. ** an in-memory merge sort. In this case, no temporary files are required
  83584. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  83585. ** directly from main memory.
  83586. **
  83587. ** If the amount of space used to store records in main memory exceeds the
  83588. ** threshold, then the set of records currently in memory are sorted and
  83589. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  83590. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  83591. ** of PMAs may be created by merging existing PMAs together - for example
  83592. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  83593. **
  83594. ** The threshold for the amount of main memory to use before flushing
  83595. ** records to a PMA is roughly the same as the limit configured for the
  83596. ** page-cache of the main database. Specifically, the threshold is set to
  83597. ** the value returned by "PRAGMA main.page_size" multipled by
  83598. ** that returned by "PRAGMA main.cache_size", in bytes.
  83599. **
  83600. ** If the sorter is running in single-threaded mode, then all PMAs generated
  83601. ** are appended to a single temporary file. Or, if the sorter is running in
  83602. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  83603. ** N is the configured number of worker threads. In this case, instead of
  83604. ** sorting the records and writing the PMA to a temporary file itself, the
  83605. ** calling thread usually launches a worker thread to do so. Except, if
  83606. ** there are already N worker threads running, the main thread does the work
  83607. ** itself.
  83608. **
  83609. ** The sorter is running in multi-threaded mode if (a) the library was built
  83610. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  83611. ** than zero, and (b) worker threads have been enabled at runtime by calling
  83612. ** "PRAGMA threads=N" with some value of N greater than 0.
  83613. **
  83614. ** When Rewind() is called, any data remaining in memory is flushed to a
  83615. ** final PMA. So at this point the data is stored in some number of sorted
  83616. ** PMAs within temporary files on disk.
  83617. **
  83618. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  83619. ** sorter is running in single-threaded mode, then these PMAs are merged
  83620. ** incrementally as keys are retreived from the sorter by the VDBE. The
  83621. ** MergeEngine object, described in further detail below, performs this
  83622. ** merge.
  83623. **
  83624. ** Or, if running in multi-threaded mode, then a background thread is
  83625. ** launched to merge the existing PMAs. Once the background thread has
  83626. ** merged T bytes of data into a single sorted PMA, the main thread
  83627. ** begins reading keys from that PMA while the background thread proceeds
  83628. ** with merging the next T bytes of data. And so on.
  83629. **
  83630. ** Parameter T is set to half the value of the memory threshold used
  83631. ** by Write() above to determine when to create a new PMA.
  83632. **
  83633. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  83634. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  83635. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  83636. ** disk are merged together. Then T bytes of data from the second set, and
  83637. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  83638. ** PMAs at a time. This done is to improve locality.
  83639. **
  83640. ** If running in multi-threaded mode and there are more than
  83641. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  83642. ** than one background thread may be created. Specifically, there may be
  83643. ** one background thread for each temporary file on disk, and one background
  83644. ** thread to merge the output of each of the others to a single PMA for
  83645. ** the main thread to read from.
  83646. */
  83647. /* #include "sqliteInt.h" */
  83648. /* #include "vdbeInt.h" */
  83649. /*
  83650. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  83651. ** messages to stderr that may be helpful in understanding the performance
  83652. ** characteristics of the sorter in multi-threaded mode.
  83653. */
  83654. #if 0
  83655. # define SQLITE_DEBUG_SORTER_THREADS 1
  83656. #endif
  83657. /*
  83658. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  83659. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  83660. ** overflows. 512MiB.
  83661. */
  83662. #define SQLITE_MAX_PMASZ (1<<29)
  83663. /*
  83664. ** Private objects used by the sorter
  83665. */
  83666. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  83667. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  83668. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  83669. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  83670. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  83671. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  83672. typedef struct SorterList SorterList; /* In-memory list of records */
  83673. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  83674. /*
  83675. ** A container for a temp file handle and the current amount of data
  83676. ** stored in the file.
  83677. */
  83678. struct SorterFile {
  83679. sqlite3_file *pFd; /* File handle */
  83680. i64 iEof; /* Bytes of data stored in pFd */
  83681. };
  83682. /*
  83683. ** An in-memory list of objects to be sorted.
  83684. **
  83685. ** If aMemory==0 then each object is allocated separately and the objects
  83686. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  83687. ** are stored in the aMemory[] bulk memory, one right after the other, and
  83688. ** are connected using SorterRecord.u.iNext.
  83689. */
  83690. struct SorterList {
  83691. SorterRecord *pList; /* Linked list of records */
  83692. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  83693. int szPMA; /* Size of pList as PMA in bytes */
  83694. };
  83695. /*
  83696. ** The MergeEngine object is used to combine two or more smaller PMAs into
  83697. ** one big PMA using a merge operation. Separate PMAs all need to be
  83698. ** combined into one big PMA in order to be able to step through the sorted
  83699. ** records in order.
  83700. **
  83701. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  83702. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  83703. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  83704. ** For the purposes of the paragraphs below, we assume that the array is
  83705. ** actually N elements in size, where N is the smallest power of 2 greater
  83706. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  83707. ** are treated as if they are empty (always at EOF).
  83708. **
  83709. ** The aTree[] array is also N elements in size. The value of N is stored in
  83710. ** the MergeEngine.nTree variable.
  83711. **
  83712. ** The final (N/2) elements of aTree[] contain the results of comparing
  83713. ** pairs of PMA keys together. Element i contains the result of
  83714. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  83715. ** aTree element is set to the index of it.
  83716. **
  83717. ** For the purposes of this comparison, EOF is considered greater than any
  83718. ** other key value. If the keys are equal (only possible with two EOF
  83719. ** values), it doesn't matter which index is stored.
  83720. **
  83721. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  83722. ** above contains the index of the smallest of each block of 4 PmaReaders
  83723. ** And so on. So that aTree[1] contains the index of the PmaReader that
  83724. ** currently points to the smallest key value. aTree[0] is unused.
  83725. **
  83726. ** Example:
  83727. **
  83728. ** aReadr[0] -> Banana
  83729. ** aReadr[1] -> Feijoa
  83730. ** aReadr[2] -> Elderberry
  83731. ** aReadr[3] -> Currant
  83732. ** aReadr[4] -> Grapefruit
  83733. ** aReadr[5] -> Apple
  83734. ** aReadr[6] -> Durian
  83735. ** aReadr[7] -> EOF
  83736. **
  83737. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  83738. **
  83739. ** The current element is "Apple" (the value of the key indicated by
  83740. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  83741. ** be advanced to the next key in its segment. Say the next key is
  83742. ** "Eggplant":
  83743. **
  83744. ** aReadr[5] -> Eggplant
  83745. **
  83746. ** The contents of aTree[] are updated first by comparing the new PmaReader
  83747. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  83748. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  83749. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  83750. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  83751. ** so the value written into element 1 of the array is 0. As follows:
  83752. **
  83753. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  83754. **
  83755. ** In other words, each time we advance to the next sorter element, log2(N)
  83756. ** key comparison operations are required, where N is the number of segments
  83757. ** being merged (rounded up to the next power of 2).
  83758. */
  83759. struct MergeEngine {
  83760. int nTree; /* Used size of aTree/aReadr (power of 2) */
  83761. SortSubtask *pTask; /* Used by this thread only */
  83762. int *aTree; /* Current state of incremental merge */
  83763. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  83764. };
  83765. /*
  83766. ** This object represents a single thread of control in a sort operation.
  83767. ** Exactly VdbeSorter.nTask instances of this object are allocated
  83768. ** as part of each VdbeSorter object. Instances are never allocated any
  83769. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  83770. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  83771. ** single-threaded operation, there is exactly one instance of this object
  83772. ** and for multi-threaded operation there are two or more instances.
  83773. **
  83774. ** Essentially, this structure contains all those fields of the VdbeSorter
  83775. ** structure for which each thread requires a separate instance. For example,
  83776. ** each thread requries its own UnpackedRecord object to unpack records in
  83777. ** as part of comparison operations.
  83778. **
  83779. ** Before a background thread is launched, variable bDone is set to 0. Then,
  83780. ** right before it exits, the thread itself sets bDone to 1. This is used for
  83781. ** two purposes:
  83782. **
  83783. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  83784. ** attempt to select a SortSubtask for which there is not already an
  83785. ** active background thread (since doing so causes the main thread
  83786. ** to block until it finishes).
  83787. **
  83788. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  83789. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  83790. ** block provoke debugging output.
  83791. **
  83792. ** In both cases, the effects of the main thread seeing (bDone==0) even
  83793. ** after the thread has finished are not dire. So we don't worry about
  83794. ** memory barriers and such here.
  83795. */
  83796. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  83797. struct SortSubtask {
  83798. SQLiteThread *pThread; /* Background thread, if any */
  83799. int bDone; /* Set if thread is finished but not joined */
  83800. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  83801. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  83802. SorterList list; /* List for thread to write to a PMA */
  83803. int nPMA; /* Number of PMAs currently in file */
  83804. SorterCompare xCompare; /* Compare function to use */
  83805. SorterFile file; /* Temp file for level-0 PMAs */
  83806. SorterFile file2; /* Space for other PMAs */
  83807. };
  83808. /*
  83809. ** Main sorter structure. A single instance of this is allocated for each
  83810. ** sorter cursor created by the VDBE.
  83811. **
  83812. ** mxKeysize:
  83813. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  83814. ** this variable is updated so as to be set to the size on disk of the
  83815. ** largest record in the sorter.
  83816. */
  83817. struct VdbeSorter {
  83818. int mnPmaSize; /* Minimum PMA size, in bytes */
  83819. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  83820. int mxKeysize; /* Largest serialized key seen so far */
  83821. int pgsz; /* Main database page size */
  83822. PmaReader *pReader; /* Readr data from here after Rewind() */
  83823. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  83824. sqlite3 *db; /* Database connection */
  83825. KeyInfo *pKeyInfo; /* How to compare records */
  83826. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  83827. SorterList list; /* List of in-memory records */
  83828. int iMemory; /* Offset of free space in list.aMemory */
  83829. int nMemory; /* Size of list.aMemory allocation in bytes */
  83830. u8 bUsePMA; /* True if one or more PMAs created */
  83831. u8 bUseThreads; /* True to use background threads */
  83832. u8 iPrev; /* Previous thread used to flush PMA */
  83833. u8 nTask; /* Size of aTask[] array */
  83834. u8 typeMask;
  83835. SortSubtask aTask[1]; /* One or more subtasks */
  83836. };
  83837. #define SORTER_TYPE_INTEGER 0x01
  83838. #define SORTER_TYPE_TEXT 0x02
  83839. /*
  83840. ** An instance of the following object is used to read records out of a
  83841. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  83842. ** aKey might point into aMap or into aBuffer. If neither of those locations
  83843. ** contain a contiguous representation of the key, then aAlloc is allocated
  83844. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  83845. **
  83846. ** pFd==0 at EOF.
  83847. */
  83848. struct PmaReader {
  83849. i64 iReadOff; /* Current read offset */
  83850. i64 iEof; /* 1 byte past EOF for this PmaReader */
  83851. int nAlloc; /* Bytes of space at aAlloc */
  83852. int nKey; /* Number of bytes in key */
  83853. sqlite3_file *pFd; /* File handle we are reading from */
  83854. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  83855. u8 *aKey; /* Pointer to current key */
  83856. u8 *aBuffer; /* Current read buffer */
  83857. int nBuffer; /* Size of read buffer in bytes */
  83858. u8 *aMap; /* Pointer to mapping of entire file */
  83859. IncrMerger *pIncr; /* Incremental merger */
  83860. };
  83861. /*
  83862. ** Normally, a PmaReader object iterates through an existing PMA stored
  83863. ** within a temp file. However, if the PmaReader.pIncr variable points to
  83864. ** an object of the following type, it may be used to iterate/merge through
  83865. ** multiple PMAs simultaneously.
  83866. **
  83867. ** There are two types of IncrMerger object - single (bUseThread==0) and
  83868. ** multi-threaded (bUseThread==1).
  83869. **
  83870. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  83871. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  83872. ** size. When the IncrMerger is initialized, it reads enough data from
  83873. ** pMerger to populate aFile[0]. It then sets variables within the
  83874. ** corresponding PmaReader object to read from that file and kicks off
  83875. ** a background thread to populate aFile[1] with the next mxSz bytes of
  83876. ** sorted record data from pMerger.
  83877. **
  83878. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  83879. ** background thread has finished populating aFile[1]. It then exchanges
  83880. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  83881. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  83882. ** another background thread to populate the new aFile[1]. And so on, until
  83883. ** the contents of pMerger are exhausted.
  83884. **
  83885. ** A single-threaded IncrMerger does not open any temporary files of its
  83886. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  83887. ** at offset iStartOff of file pTask->file2. And instead of using a
  83888. ** background thread to prepare data for the PmaReader, with a single
  83889. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  83890. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  83891. ** of data.
  83892. */
  83893. struct IncrMerger {
  83894. SortSubtask *pTask; /* Task that owns this merger */
  83895. MergeEngine *pMerger; /* Merge engine thread reads data from */
  83896. i64 iStartOff; /* Offset to start writing file at */
  83897. int mxSz; /* Maximum bytes of data to store */
  83898. int bEof; /* Set to true when merge is finished */
  83899. int bUseThread; /* True to use a bg thread for this object */
  83900. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  83901. };
  83902. /*
  83903. ** An instance of this object is used for writing a PMA.
  83904. **
  83905. ** The PMA is written one record at a time. Each record is of an arbitrary
  83906. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  83907. ** each block is aligned on a page boundary. This object caches writes to
  83908. ** the PMA so that aligned, page-size blocks are written.
  83909. */
  83910. struct PmaWriter {
  83911. int eFWErr; /* Non-zero if in an error state */
  83912. u8 *aBuffer; /* Pointer to write buffer */
  83913. int nBuffer; /* Size of write buffer in bytes */
  83914. int iBufStart; /* First byte of buffer to write */
  83915. int iBufEnd; /* Last byte of buffer to write */
  83916. i64 iWriteOff; /* Offset of start of buffer in file */
  83917. sqlite3_file *pFd; /* File handle to write to */
  83918. };
  83919. /*
  83920. ** This object is the header on a single record while that record is being
  83921. ** held in memory and prior to being written out as part of a PMA.
  83922. **
  83923. ** How the linked list is connected depends on how memory is being managed
  83924. ** by this module. If using a separate allocation for each in-memory record
  83925. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  83926. ** SorterRecord.u.pNext pointers.
  83927. **
  83928. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  83929. ** then while records are being accumulated the list is linked using the
  83930. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  83931. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  83932. ** has finished passing records to the sorter, or when the in-memory buffer
  83933. ** is full, the list is sorted. As part of the sorting process, it is
  83934. ** converted to use the SorterRecord.u.pNext pointers. See function
  83935. ** vdbeSorterSort() for details.
  83936. */
  83937. struct SorterRecord {
  83938. int nVal; /* Size of the record in bytes */
  83939. union {
  83940. SorterRecord *pNext; /* Pointer to next record in list */
  83941. int iNext; /* Offset within aMemory of next record */
  83942. } u;
  83943. /* The data for the record immediately follows this header */
  83944. };
  83945. /* Return a pointer to the buffer containing the record data for SorterRecord
  83946. ** object p. Should be used as if:
  83947. **
  83948. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  83949. */
  83950. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  83951. /* Maximum number of PMAs that a single MergeEngine can merge */
  83952. #define SORTER_MAX_MERGE_COUNT 16
  83953. static int vdbeIncrSwap(IncrMerger*);
  83954. static void vdbeIncrFree(IncrMerger *);
  83955. /*
  83956. ** Free all memory belonging to the PmaReader object passed as the
  83957. ** argument. All structure fields are set to zero before returning.
  83958. */
  83959. static void vdbePmaReaderClear(PmaReader *pReadr){
  83960. sqlite3_free(pReadr->aAlloc);
  83961. sqlite3_free(pReadr->aBuffer);
  83962. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  83963. vdbeIncrFree(pReadr->pIncr);
  83964. memset(pReadr, 0, sizeof(PmaReader));
  83965. }
  83966. /*
  83967. ** Read the next nByte bytes of data from the PMA p.
  83968. ** If successful, set *ppOut to point to a buffer containing the data
  83969. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  83970. ** error code.
  83971. **
  83972. ** The buffer returned in *ppOut is only valid until the
  83973. ** next call to this function.
  83974. */
  83975. static int vdbePmaReadBlob(
  83976. PmaReader *p, /* PmaReader from which to take the blob */
  83977. int nByte, /* Bytes of data to read */
  83978. u8 **ppOut /* OUT: Pointer to buffer containing data */
  83979. ){
  83980. int iBuf; /* Offset within buffer to read from */
  83981. int nAvail; /* Bytes of data available in buffer */
  83982. if( p->aMap ){
  83983. *ppOut = &p->aMap[p->iReadOff];
  83984. p->iReadOff += nByte;
  83985. return SQLITE_OK;
  83986. }
  83987. assert( p->aBuffer );
  83988. /* If there is no more data to be read from the buffer, read the next
  83989. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  83990. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  83991. iBuf = p->iReadOff % p->nBuffer;
  83992. if( iBuf==0 ){
  83993. int nRead; /* Bytes to read from disk */
  83994. int rc; /* sqlite3OsRead() return code */
  83995. /* Determine how many bytes of data to read. */
  83996. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  83997. nRead = p->nBuffer;
  83998. }else{
  83999. nRead = (int)(p->iEof - p->iReadOff);
  84000. }
  84001. assert( nRead>0 );
  84002. /* Readr data from the file. Return early if an error occurs. */
  84003. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  84004. assert( rc!=SQLITE_IOERR_SHORT_READ );
  84005. if( rc!=SQLITE_OK ) return rc;
  84006. }
  84007. nAvail = p->nBuffer - iBuf;
  84008. if( nByte<=nAvail ){
  84009. /* The requested data is available in the in-memory buffer. In this
  84010. ** case there is no need to make a copy of the data, just return a
  84011. ** pointer into the buffer to the caller. */
  84012. *ppOut = &p->aBuffer[iBuf];
  84013. p->iReadOff += nByte;
  84014. }else{
  84015. /* The requested data is not all available in the in-memory buffer.
  84016. ** In this case, allocate space at p->aAlloc[] to copy the requested
  84017. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  84018. int nRem; /* Bytes remaining to copy */
  84019. /* Extend the p->aAlloc[] allocation if required. */
  84020. if( p->nAlloc<nByte ){
  84021. u8 *aNew;
  84022. int nNew = MAX(128, p->nAlloc*2);
  84023. while( nByte>nNew ) nNew = nNew*2;
  84024. aNew = sqlite3Realloc(p->aAlloc, nNew);
  84025. if( !aNew ) return SQLITE_NOMEM_BKPT;
  84026. p->nAlloc = nNew;
  84027. p->aAlloc = aNew;
  84028. }
  84029. /* Copy as much data as is available in the buffer into the start of
  84030. ** p->aAlloc[]. */
  84031. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  84032. p->iReadOff += nAvail;
  84033. nRem = nByte - nAvail;
  84034. /* The following loop copies up to p->nBuffer bytes per iteration into
  84035. ** the p->aAlloc[] buffer. */
  84036. while( nRem>0 ){
  84037. int rc; /* vdbePmaReadBlob() return code */
  84038. int nCopy; /* Number of bytes to copy */
  84039. u8 *aNext; /* Pointer to buffer to copy data from */
  84040. nCopy = nRem;
  84041. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  84042. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  84043. if( rc!=SQLITE_OK ) return rc;
  84044. assert( aNext!=p->aAlloc );
  84045. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  84046. nRem -= nCopy;
  84047. }
  84048. *ppOut = p->aAlloc;
  84049. }
  84050. return SQLITE_OK;
  84051. }
  84052. /*
  84053. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  84054. ** the value read.
  84055. */
  84056. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  84057. int iBuf;
  84058. if( p->aMap ){
  84059. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  84060. }else{
  84061. iBuf = p->iReadOff % p->nBuffer;
  84062. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  84063. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  84064. }else{
  84065. u8 aVarint[16], *a;
  84066. int i = 0, rc;
  84067. do{
  84068. rc = vdbePmaReadBlob(p, 1, &a);
  84069. if( rc ) return rc;
  84070. aVarint[(i++)&0xf] = a[0];
  84071. }while( (a[0]&0x80)!=0 );
  84072. sqlite3GetVarint(aVarint, pnOut);
  84073. }
  84074. }
  84075. return SQLITE_OK;
  84076. }
  84077. /*
  84078. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  84079. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  84080. ** (because the file is too large or the VFS layer is configured not to use
  84081. ** mmap), return SQLITE_OK and set *pp to NULL.
  84082. **
  84083. ** Or, if an error occurs, return an SQLite error code. The final value of
  84084. ** *pp is undefined in this case.
  84085. */
  84086. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  84087. int rc = SQLITE_OK;
  84088. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  84089. sqlite3_file *pFd = pFile->pFd;
  84090. if( pFd->pMethods->iVersion>=3 ){
  84091. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  84092. testcase( rc!=SQLITE_OK );
  84093. }
  84094. }
  84095. return rc;
  84096. }
  84097. /*
  84098. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  84099. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  84100. ** if successful, or an SQLite error code if an error occurs.
  84101. */
  84102. static int vdbePmaReaderSeek(
  84103. SortSubtask *pTask, /* Task context */
  84104. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  84105. SorterFile *pFile, /* Sorter file to read from */
  84106. i64 iOff /* Offset in pFile */
  84107. ){
  84108. int rc = SQLITE_OK;
  84109. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  84110. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  84111. if( pReadr->aMap ){
  84112. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  84113. pReadr->aMap = 0;
  84114. }
  84115. pReadr->iReadOff = iOff;
  84116. pReadr->iEof = pFile->iEof;
  84117. pReadr->pFd = pFile->pFd;
  84118. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  84119. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  84120. int pgsz = pTask->pSorter->pgsz;
  84121. int iBuf = pReadr->iReadOff % pgsz;
  84122. if( pReadr->aBuffer==0 ){
  84123. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  84124. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
  84125. pReadr->nBuffer = pgsz;
  84126. }
  84127. if( rc==SQLITE_OK && iBuf ){
  84128. int nRead = pgsz - iBuf;
  84129. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  84130. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  84131. }
  84132. rc = sqlite3OsRead(
  84133. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  84134. );
  84135. testcase( rc!=SQLITE_OK );
  84136. }
  84137. }
  84138. return rc;
  84139. }
  84140. /*
  84141. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  84142. ** no error occurs, or an SQLite error code if one does.
  84143. */
  84144. static int vdbePmaReaderNext(PmaReader *pReadr){
  84145. int rc = SQLITE_OK; /* Return Code */
  84146. u64 nRec = 0; /* Size of record in bytes */
  84147. if( pReadr->iReadOff>=pReadr->iEof ){
  84148. IncrMerger *pIncr = pReadr->pIncr;
  84149. int bEof = 1;
  84150. if( pIncr ){
  84151. rc = vdbeIncrSwap(pIncr);
  84152. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  84153. rc = vdbePmaReaderSeek(
  84154. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  84155. );
  84156. bEof = 0;
  84157. }
  84158. }
  84159. if( bEof ){
  84160. /* This is an EOF condition */
  84161. vdbePmaReaderClear(pReadr);
  84162. testcase( rc!=SQLITE_OK );
  84163. return rc;
  84164. }
  84165. }
  84166. if( rc==SQLITE_OK ){
  84167. rc = vdbePmaReadVarint(pReadr, &nRec);
  84168. }
  84169. if( rc==SQLITE_OK ){
  84170. pReadr->nKey = (int)nRec;
  84171. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  84172. testcase( rc!=SQLITE_OK );
  84173. }
  84174. return rc;
  84175. }
  84176. /*
  84177. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  84178. ** starting at offset iStart and ending at offset iEof-1. This function
  84179. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  84180. ** PMA is empty).
  84181. **
  84182. ** If the pnByte parameter is NULL, then it is assumed that the file
  84183. ** contains a single PMA, and that that PMA omits the initial length varint.
  84184. */
  84185. static int vdbePmaReaderInit(
  84186. SortSubtask *pTask, /* Task context */
  84187. SorterFile *pFile, /* Sorter file to read from */
  84188. i64 iStart, /* Start offset in pFile */
  84189. PmaReader *pReadr, /* PmaReader to populate */
  84190. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  84191. ){
  84192. int rc;
  84193. assert( pFile->iEof>iStart );
  84194. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  84195. assert( pReadr->aBuffer==0 );
  84196. assert( pReadr->aMap==0 );
  84197. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  84198. if( rc==SQLITE_OK ){
  84199. u64 nByte = 0; /* Size of PMA in bytes */
  84200. rc = vdbePmaReadVarint(pReadr, &nByte);
  84201. pReadr->iEof = pReadr->iReadOff + nByte;
  84202. *pnByte += nByte;
  84203. }
  84204. if( rc==SQLITE_OK ){
  84205. rc = vdbePmaReaderNext(pReadr);
  84206. }
  84207. return rc;
  84208. }
  84209. /*
  84210. ** A version of vdbeSorterCompare() that assumes that it has already been
  84211. ** determined that the first field of key1 is equal to the first field of
  84212. ** key2.
  84213. */
  84214. static int vdbeSorterCompareTail(
  84215. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  84216. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  84217. const void *pKey1, int nKey1, /* Left side of comparison */
  84218. const void *pKey2, int nKey2 /* Right side of comparison */
  84219. ){
  84220. UnpackedRecord *r2 = pTask->pUnpacked;
  84221. if( *pbKey2Cached==0 ){
  84222. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  84223. *pbKey2Cached = 1;
  84224. }
  84225. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  84226. }
  84227. /*
  84228. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  84229. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  84230. ** used by the comparison. Return the result of the comparison.
  84231. **
  84232. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  84233. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  84234. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  84235. ** version of key2 and *pbKey2Cached set to true before returning.
  84236. **
  84237. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  84238. ** to SQLITE_NOMEM.
  84239. */
  84240. static int vdbeSorterCompare(
  84241. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  84242. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  84243. const void *pKey1, int nKey1, /* Left side of comparison */
  84244. const void *pKey2, int nKey2 /* Right side of comparison */
  84245. ){
  84246. UnpackedRecord *r2 = pTask->pUnpacked;
  84247. if( !*pbKey2Cached ){
  84248. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  84249. *pbKey2Cached = 1;
  84250. }
  84251. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  84252. }
  84253. /*
  84254. ** A specially optimized version of vdbeSorterCompare() that assumes that
  84255. ** the first field of each key is a TEXT value and that the collation
  84256. ** sequence to compare them with is BINARY.
  84257. */
  84258. static int vdbeSorterCompareText(
  84259. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  84260. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  84261. const void *pKey1, int nKey1, /* Left side of comparison */
  84262. const void *pKey2, int nKey2 /* Right side of comparison */
  84263. ){
  84264. const u8 * const p1 = (const u8 * const)pKey1;
  84265. const u8 * const p2 = (const u8 * const)pKey2;
  84266. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  84267. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  84268. int n1;
  84269. int n2;
  84270. int res;
  84271. getVarint32(&p1[1], n1);
  84272. getVarint32(&p2[1], n2);
  84273. res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
  84274. if( res==0 ){
  84275. res = n1 - n2;
  84276. }
  84277. if( res==0 ){
  84278. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  84279. res = vdbeSorterCompareTail(
  84280. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  84281. );
  84282. }
  84283. }else{
  84284. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  84285. res = res * -1;
  84286. }
  84287. }
  84288. return res;
  84289. }
  84290. /*
  84291. ** A specially optimized version of vdbeSorterCompare() that assumes that
  84292. ** the first field of each key is an INTEGER value.
  84293. */
  84294. static int vdbeSorterCompareInt(
  84295. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  84296. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  84297. const void *pKey1, int nKey1, /* Left side of comparison */
  84298. const void *pKey2, int nKey2 /* Right side of comparison */
  84299. ){
  84300. const u8 * const p1 = (const u8 * const)pKey1;
  84301. const u8 * const p2 = (const u8 * const)pKey2;
  84302. const int s1 = p1[1]; /* Left hand serial type */
  84303. const int s2 = p2[1]; /* Right hand serial type */
  84304. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  84305. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  84306. int res; /* Return value */
  84307. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  84308. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  84309. if( s1==s2 ){
  84310. /* The two values have the same sign. Compare using memcmp(). */
  84311. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
  84312. const u8 n = aLen[s1];
  84313. int i;
  84314. res = 0;
  84315. for(i=0; i<n; i++){
  84316. if( (res = v1[i] - v2[i])!=0 ){
  84317. if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
  84318. res = v1[0] & 0x80 ? -1 : +1;
  84319. }
  84320. break;
  84321. }
  84322. }
  84323. }else if( s1>7 && s2>7 ){
  84324. res = s1 - s2;
  84325. }else{
  84326. if( s2>7 ){
  84327. res = +1;
  84328. }else if( s1>7 ){
  84329. res = -1;
  84330. }else{
  84331. res = s1 - s2;
  84332. }
  84333. assert( res!=0 );
  84334. if( res>0 ){
  84335. if( *v1 & 0x80 ) res = -1;
  84336. }else{
  84337. if( *v2 & 0x80 ) res = +1;
  84338. }
  84339. }
  84340. if( res==0 ){
  84341. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  84342. res = vdbeSorterCompareTail(
  84343. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  84344. );
  84345. }
  84346. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  84347. res = res * -1;
  84348. }
  84349. return res;
  84350. }
  84351. /*
  84352. ** Initialize the temporary index cursor just opened as a sorter cursor.
  84353. **
  84354. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
  84355. ** to determine the number of fields that should be compared from the
  84356. ** records being sorted. However, if the value passed as argument nField
  84357. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  84358. ** is used instead. This is used when sorting records for a CREATE INDEX
  84359. ** statement. In this case, keys are always delivered to the sorter in
  84360. ** order of the primary key, which happens to be make up the final part
  84361. ** of the records being sorted. So if the sort is stable, there is never
  84362. ** any reason to compare PK fields and they can be ignored for a small
  84363. ** performance boost.
  84364. **
  84365. ** The sorter can guarantee a stable sort when running in single-threaded
  84366. ** mode, but not in multi-threaded mode.
  84367. **
  84368. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  84369. */
  84370. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  84371. sqlite3 *db, /* Database connection (for malloc()) */
  84372. int nField, /* Number of key fields in each record */
  84373. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  84374. ){
  84375. int pgsz; /* Page size of main database */
  84376. int i; /* Used to iterate through aTask[] */
  84377. VdbeSorter *pSorter; /* The new sorter */
  84378. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  84379. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  84380. int sz; /* Size of pSorter in bytes */
  84381. int rc = SQLITE_OK;
  84382. #if SQLITE_MAX_WORKER_THREADS==0
  84383. # define nWorker 0
  84384. #else
  84385. int nWorker;
  84386. #endif
  84387. /* Initialize the upper limit on the number of worker threads */
  84388. #if SQLITE_MAX_WORKER_THREADS>0
  84389. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  84390. nWorker = 0;
  84391. }else{
  84392. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  84393. }
  84394. #endif
  84395. /* Do not allow the total number of threads (main thread + all workers)
  84396. ** to exceed the maximum merge count */
  84397. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  84398. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  84399. nWorker = SORTER_MAX_MERGE_COUNT-1;
  84400. }
  84401. #endif
  84402. assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
  84403. assert( pCsr->eCurType==CURTYPE_SORTER );
  84404. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
  84405. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  84406. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  84407. pCsr->uc.pSorter = pSorter;
  84408. if( pSorter==0 ){
  84409. rc = SQLITE_NOMEM_BKPT;
  84410. }else{
  84411. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  84412. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  84413. pKeyInfo->db = 0;
  84414. if( nField && nWorker==0 ){
  84415. pKeyInfo->nKeyField = nField;
  84416. }
  84417. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  84418. pSorter->nTask = nWorker + 1;
  84419. pSorter->iPrev = (u8)(nWorker - 1);
  84420. pSorter->bUseThreads = (pSorter->nTask>1);
  84421. pSorter->db = db;
  84422. for(i=0; i<pSorter->nTask; i++){
  84423. SortSubtask *pTask = &pSorter->aTask[i];
  84424. pTask->pSorter = pSorter;
  84425. }
  84426. if( !sqlite3TempInMemory(db) ){
  84427. i64 mxCache; /* Cache size in bytes*/
  84428. u32 szPma = sqlite3GlobalConfig.szPma;
  84429. pSorter->mnPmaSize = szPma * pgsz;
  84430. mxCache = db->aDb[0].pSchema->cache_size;
  84431. if( mxCache<0 ){
  84432. /* A negative cache-size value C indicates that the cache is abs(C)
  84433. ** KiB in size. */
  84434. mxCache = mxCache * -1024;
  84435. }else{
  84436. mxCache = mxCache * pgsz;
  84437. }
  84438. mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
  84439. pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
  84440. /* Avoid large memory allocations if the application has requested
  84441. ** SQLITE_CONFIG_SMALL_MALLOC. */
  84442. if( sqlite3GlobalConfig.bSmallMalloc==0 ){
  84443. assert( pSorter->iMemory==0 );
  84444. pSorter->nMemory = pgsz;
  84445. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  84446. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
  84447. }
  84448. }
  84449. if( pKeyInfo->nAllField<13
  84450. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  84451. ){
  84452. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  84453. }
  84454. }
  84455. return rc;
  84456. }
  84457. #undef nWorker /* Defined at the top of this function */
  84458. /*
  84459. ** Free the list of sorted records starting at pRecord.
  84460. */
  84461. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  84462. SorterRecord *p;
  84463. SorterRecord *pNext;
  84464. for(p=pRecord; p; p=pNext){
  84465. pNext = p->u.pNext;
  84466. sqlite3DbFree(db, p);
  84467. }
  84468. }
  84469. /*
  84470. ** Free all resources owned by the object indicated by argument pTask. All
  84471. ** fields of *pTask are zeroed before returning.
  84472. */
  84473. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  84474. sqlite3DbFree(db, pTask->pUnpacked);
  84475. #if SQLITE_MAX_WORKER_THREADS>0
  84476. /* pTask->list.aMemory can only be non-zero if it was handed memory
  84477. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  84478. if( pTask->list.aMemory ){
  84479. sqlite3_free(pTask->list.aMemory);
  84480. }else
  84481. #endif
  84482. {
  84483. assert( pTask->list.aMemory==0 );
  84484. vdbeSorterRecordFree(0, pTask->list.pList);
  84485. }
  84486. if( pTask->file.pFd ){
  84487. sqlite3OsCloseFree(pTask->file.pFd);
  84488. }
  84489. if( pTask->file2.pFd ){
  84490. sqlite3OsCloseFree(pTask->file2.pFd);
  84491. }
  84492. memset(pTask, 0, sizeof(SortSubtask));
  84493. }
  84494. #ifdef SQLITE_DEBUG_SORTER_THREADS
  84495. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  84496. i64 t;
  84497. int iTask = (pTask - pTask->pSorter->aTask);
  84498. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  84499. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  84500. }
  84501. static void vdbeSorterRewindDebug(const char *zEvent){
  84502. i64 t;
  84503. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  84504. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  84505. }
  84506. static void vdbeSorterPopulateDebug(
  84507. SortSubtask *pTask,
  84508. const char *zEvent
  84509. ){
  84510. i64 t;
  84511. int iTask = (pTask - pTask->pSorter->aTask);
  84512. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  84513. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  84514. }
  84515. static void vdbeSorterBlockDebug(
  84516. SortSubtask *pTask,
  84517. int bBlocked,
  84518. const char *zEvent
  84519. ){
  84520. if( bBlocked ){
  84521. i64 t;
  84522. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  84523. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  84524. }
  84525. }
  84526. #else
  84527. # define vdbeSorterWorkDebug(x,y)
  84528. # define vdbeSorterRewindDebug(y)
  84529. # define vdbeSorterPopulateDebug(x,y)
  84530. # define vdbeSorterBlockDebug(x,y,z)
  84531. #endif
  84532. #if SQLITE_MAX_WORKER_THREADS>0
  84533. /*
  84534. ** Join thread pTask->thread.
  84535. */
  84536. static int vdbeSorterJoinThread(SortSubtask *pTask){
  84537. int rc = SQLITE_OK;
  84538. if( pTask->pThread ){
  84539. #ifdef SQLITE_DEBUG_SORTER_THREADS
  84540. int bDone = pTask->bDone;
  84541. #endif
  84542. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  84543. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  84544. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  84545. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  84546. rc = SQLITE_PTR_TO_INT(pRet);
  84547. assert( pTask->bDone==1 );
  84548. pTask->bDone = 0;
  84549. pTask->pThread = 0;
  84550. }
  84551. return rc;
  84552. }
  84553. /*
  84554. ** Launch a background thread to run xTask(pIn).
  84555. */
  84556. static int vdbeSorterCreateThread(
  84557. SortSubtask *pTask, /* Thread will use this task object */
  84558. void *(*xTask)(void*), /* Routine to run in a separate thread */
  84559. void *pIn /* Argument passed into xTask() */
  84560. ){
  84561. assert( pTask->pThread==0 && pTask->bDone==0 );
  84562. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  84563. }
  84564. /*
  84565. ** Join all outstanding threads launched by SorterWrite() to create
  84566. ** level-0 PMAs.
  84567. */
  84568. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  84569. int rc = rcin;
  84570. int i;
  84571. /* This function is always called by the main user thread.
  84572. **
  84573. ** If this function is being called after SorterRewind() has been called,
  84574. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  84575. ** is currently attempt to join one of the other threads. To avoid a race
  84576. ** condition where this thread also attempts to join the same object, join
  84577. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  84578. for(i=pSorter->nTask-1; i>=0; i--){
  84579. SortSubtask *pTask = &pSorter->aTask[i];
  84580. int rc2 = vdbeSorterJoinThread(pTask);
  84581. if( rc==SQLITE_OK ) rc = rc2;
  84582. }
  84583. return rc;
  84584. }
  84585. #else
  84586. # define vdbeSorterJoinAll(x,rcin) (rcin)
  84587. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  84588. #endif
  84589. /*
  84590. ** Allocate a new MergeEngine object capable of handling up to
  84591. ** nReader PmaReader inputs.
  84592. **
  84593. ** nReader is automatically rounded up to the next power of two.
  84594. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  84595. */
  84596. static MergeEngine *vdbeMergeEngineNew(int nReader){
  84597. int N = 2; /* Smallest power of two >= nReader */
  84598. int nByte; /* Total bytes of space to allocate */
  84599. MergeEngine *pNew; /* Pointer to allocated object to return */
  84600. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  84601. while( N<nReader ) N += N;
  84602. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  84603. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  84604. if( pNew ){
  84605. pNew->nTree = N;
  84606. pNew->pTask = 0;
  84607. pNew->aReadr = (PmaReader*)&pNew[1];
  84608. pNew->aTree = (int*)&pNew->aReadr[N];
  84609. }
  84610. return pNew;
  84611. }
  84612. /*
  84613. ** Free the MergeEngine object passed as the only argument.
  84614. */
  84615. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  84616. int i;
  84617. if( pMerger ){
  84618. for(i=0; i<pMerger->nTree; i++){
  84619. vdbePmaReaderClear(&pMerger->aReadr[i]);
  84620. }
  84621. }
  84622. sqlite3_free(pMerger);
  84623. }
  84624. /*
  84625. ** Free all resources associated with the IncrMerger object indicated by
  84626. ** the first argument.
  84627. */
  84628. static void vdbeIncrFree(IncrMerger *pIncr){
  84629. if( pIncr ){
  84630. #if SQLITE_MAX_WORKER_THREADS>0
  84631. if( pIncr->bUseThread ){
  84632. vdbeSorterJoinThread(pIncr->pTask);
  84633. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  84634. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  84635. }
  84636. #endif
  84637. vdbeMergeEngineFree(pIncr->pMerger);
  84638. sqlite3_free(pIncr);
  84639. }
  84640. }
  84641. /*
  84642. ** Reset a sorting cursor back to its original empty state.
  84643. */
  84644. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  84645. int i;
  84646. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  84647. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  84648. #if SQLITE_MAX_WORKER_THREADS>0
  84649. if( pSorter->pReader ){
  84650. vdbePmaReaderClear(pSorter->pReader);
  84651. sqlite3DbFree(db, pSorter->pReader);
  84652. pSorter->pReader = 0;
  84653. }
  84654. #endif
  84655. vdbeMergeEngineFree(pSorter->pMerger);
  84656. pSorter->pMerger = 0;
  84657. for(i=0; i<pSorter->nTask; i++){
  84658. SortSubtask *pTask = &pSorter->aTask[i];
  84659. vdbeSortSubtaskCleanup(db, pTask);
  84660. pTask->pSorter = pSorter;
  84661. }
  84662. if( pSorter->list.aMemory==0 ){
  84663. vdbeSorterRecordFree(0, pSorter->list.pList);
  84664. }
  84665. pSorter->list.pList = 0;
  84666. pSorter->list.szPMA = 0;
  84667. pSorter->bUsePMA = 0;
  84668. pSorter->iMemory = 0;
  84669. pSorter->mxKeysize = 0;
  84670. sqlite3DbFree(db, pSorter->pUnpacked);
  84671. pSorter->pUnpacked = 0;
  84672. }
  84673. /*
  84674. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  84675. */
  84676. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  84677. VdbeSorter *pSorter;
  84678. assert( pCsr->eCurType==CURTYPE_SORTER );
  84679. pSorter = pCsr->uc.pSorter;
  84680. if( pSorter ){
  84681. sqlite3VdbeSorterReset(db, pSorter);
  84682. sqlite3_free(pSorter->list.aMemory);
  84683. sqlite3DbFree(db, pSorter);
  84684. pCsr->uc.pSorter = 0;
  84685. }
  84686. }
  84687. #if SQLITE_MAX_MMAP_SIZE>0
  84688. /*
  84689. ** The first argument is a file-handle open on a temporary file. The file
  84690. ** is guaranteed to be nByte bytes or smaller in size. This function
  84691. ** attempts to extend the file to nByte bytes in size and to ensure that
  84692. ** the VFS has memory mapped it.
  84693. **
  84694. ** Whether or not the file does end up memory mapped of course depends on
  84695. ** the specific VFS implementation.
  84696. */
  84697. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  84698. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  84699. void *p = 0;
  84700. int chunksize = 4*1024;
  84701. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  84702. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  84703. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  84704. sqlite3OsUnfetch(pFd, 0, p);
  84705. }
  84706. }
  84707. #else
  84708. # define vdbeSorterExtendFile(x,y,z)
  84709. #endif
  84710. /*
  84711. ** Allocate space for a file-handle and open a temporary file. If successful,
  84712. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  84713. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  84714. */
  84715. static int vdbeSorterOpenTempFile(
  84716. sqlite3 *db, /* Database handle doing sort */
  84717. i64 nExtend, /* Attempt to extend file to this size */
  84718. sqlite3_file **ppFd
  84719. ){
  84720. int rc;
  84721. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  84722. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  84723. SQLITE_OPEN_TEMP_JOURNAL |
  84724. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  84725. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  84726. );
  84727. if( rc==SQLITE_OK ){
  84728. i64 max = SQLITE_MAX_MMAP_SIZE;
  84729. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  84730. if( nExtend>0 ){
  84731. vdbeSorterExtendFile(db, *ppFd, nExtend);
  84732. }
  84733. }
  84734. return rc;
  84735. }
  84736. /*
  84737. ** If it has not already been allocated, allocate the UnpackedRecord
  84738. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  84739. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  84740. */
  84741. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  84742. if( pTask->pUnpacked==0 ){
  84743. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
  84744. if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
  84745. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
  84746. pTask->pUnpacked->errCode = 0;
  84747. }
  84748. return SQLITE_OK;
  84749. }
  84750. /*
  84751. ** Merge the two sorted lists p1 and p2 into a single list.
  84752. */
  84753. static SorterRecord *vdbeSorterMerge(
  84754. SortSubtask *pTask, /* Calling thread context */
  84755. SorterRecord *p1, /* First list to merge */
  84756. SorterRecord *p2 /* Second list to merge */
  84757. ){
  84758. SorterRecord *pFinal = 0;
  84759. SorterRecord **pp = &pFinal;
  84760. int bCached = 0;
  84761. assert( p1!=0 && p2!=0 );
  84762. for(;;){
  84763. int res;
  84764. res = pTask->xCompare(
  84765. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  84766. );
  84767. if( res<=0 ){
  84768. *pp = p1;
  84769. pp = &p1->u.pNext;
  84770. p1 = p1->u.pNext;
  84771. if( p1==0 ){
  84772. *pp = p2;
  84773. break;
  84774. }
  84775. }else{
  84776. *pp = p2;
  84777. pp = &p2->u.pNext;
  84778. p2 = p2->u.pNext;
  84779. bCached = 0;
  84780. if( p2==0 ){
  84781. *pp = p1;
  84782. break;
  84783. }
  84784. }
  84785. }
  84786. return pFinal;
  84787. }
  84788. /*
  84789. ** Return the SorterCompare function to compare values collected by the
  84790. ** sorter object passed as the only argument.
  84791. */
  84792. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  84793. if( p->typeMask==SORTER_TYPE_INTEGER ){
  84794. return vdbeSorterCompareInt;
  84795. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  84796. return vdbeSorterCompareText;
  84797. }
  84798. return vdbeSorterCompare;
  84799. }
  84800. /*
  84801. ** Sort the linked list of records headed at pTask->pList. Return
  84802. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  84803. ** an error occurs.
  84804. */
  84805. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  84806. int i;
  84807. SorterRecord **aSlot;
  84808. SorterRecord *p;
  84809. int rc;
  84810. rc = vdbeSortAllocUnpacked(pTask);
  84811. if( rc!=SQLITE_OK ) return rc;
  84812. p = pList->pList;
  84813. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  84814. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  84815. if( !aSlot ){
  84816. return SQLITE_NOMEM_BKPT;
  84817. }
  84818. while( p ){
  84819. SorterRecord *pNext;
  84820. if( pList->aMemory ){
  84821. if( (u8*)p==pList->aMemory ){
  84822. pNext = 0;
  84823. }else{
  84824. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  84825. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  84826. }
  84827. }else{
  84828. pNext = p->u.pNext;
  84829. }
  84830. p->u.pNext = 0;
  84831. for(i=0; aSlot[i]; i++){
  84832. p = vdbeSorterMerge(pTask, p, aSlot[i]);
  84833. aSlot[i] = 0;
  84834. }
  84835. aSlot[i] = p;
  84836. p = pNext;
  84837. }
  84838. p = 0;
  84839. for(i=0; i<64; i++){
  84840. if( aSlot[i]==0 ) continue;
  84841. p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
  84842. }
  84843. pList->pList = p;
  84844. sqlite3_free(aSlot);
  84845. assert( pTask->pUnpacked->errCode==SQLITE_OK
  84846. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  84847. );
  84848. return pTask->pUnpacked->errCode;
  84849. }
  84850. /*
  84851. ** Initialize a PMA-writer object.
  84852. */
  84853. static void vdbePmaWriterInit(
  84854. sqlite3_file *pFd, /* File handle to write to */
  84855. PmaWriter *p, /* Object to populate */
  84856. int nBuf, /* Buffer size */
  84857. i64 iStart /* Offset of pFd to begin writing at */
  84858. ){
  84859. memset(p, 0, sizeof(PmaWriter));
  84860. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  84861. if( !p->aBuffer ){
  84862. p->eFWErr = SQLITE_NOMEM_BKPT;
  84863. }else{
  84864. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  84865. p->iWriteOff = iStart - p->iBufStart;
  84866. p->nBuffer = nBuf;
  84867. p->pFd = pFd;
  84868. }
  84869. }
  84870. /*
  84871. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  84872. ** if successful, or an SQLite error code if an error occurs.
  84873. */
  84874. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  84875. int nRem = nData;
  84876. while( nRem>0 && p->eFWErr==0 ){
  84877. int nCopy = nRem;
  84878. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  84879. nCopy = p->nBuffer - p->iBufEnd;
  84880. }
  84881. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  84882. p->iBufEnd += nCopy;
  84883. if( p->iBufEnd==p->nBuffer ){
  84884. p->eFWErr = sqlite3OsWrite(p->pFd,
  84885. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  84886. p->iWriteOff + p->iBufStart
  84887. );
  84888. p->iBufStart = p->iBufEnd = 0;
  84889. p->iWriteOff += p->nBuffer;
  84890. }
  84891. assert( p->iBufEnd<p->nBuffer );
  84892. nRem -= nCopy;
  84893. }
  84894. }
  84895. /*
  84896. ** Flush any buffered data to disk and clean up the PMA-writer object.
  84897. ** The results of using the PMA-writer after this call are undefined.
  84898. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  84899. ** required. Otherwise, return an SQLite error code.
  84900. **
  84901. ** Before returning, set *piEof to the offset immediately following the
  84902. ** last byte written to the file.
  84903. */
  84904. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  84905. int rc;
  84906. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  84907. p->eFWErr = sqlite3OsWrite(p->pFd,
  84908. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  84909. p->iWriteOff + p->iBufStart
  84910. );
  84911. }
  84912. *piEof = (p->iWriteOff + p->iBufEnd);
  84913. sqlite3_free(p->aBuffer);
  84914. rc = p->eFWErr;
  84915. memset(p, 0, sizeof(PmaWriter));
  84916. return rc;
  84917. }
  84918. /*
  84919. ** Write value iVal encoded as a varint to the PMA. Return
  84920. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  84921. */
  84922. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  84923. int nByte;
  84924. u8 aByte[10];
  84925. nByte = sqlite3PutVarint(aByte, iVal);
  84926. vdbePmaWriteBlob(p, aByte, nByte);
  84927. }
  84928. /*
  84929. ** Write the current contents of in-memory linked-list pList to a level-0
  84930. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  84931. ** successful, or an SQLite error code otherwise.
  84932. **
  84933. ** The format of a PMA is:
  84934. **
  84935. ** * A varint. This varint contains the total number of bytes of content
  84936. ** in the PMA (not including the varint itself).
  84937. **
  84938. ** * One or more records packed end-to-end in order of ascending keys.
  84939. ** Each record consists of a varint followed by a blob of data (the
  84940. ** key). The varint is the number of bytes in the blob of data.
  84941. */
  84942. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  84943. sqlite3 *db = pTask->pSorter->db;
  84944. int rc = SQLITE_OK; /* Return code */
  84945. PmaWriter writer; /* Object used to write to the file */
  84946. #ifdef SQLITE_DEBUG
  84947. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  84948. ** This is used by an assert() statement at the end of this function. */
  84949. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  84950. #endif
  84951. vdbeSorterWorkDebug(pTask, "enter");
  84952. memset(&writer, 0, sizeof(PmaWriter));
  84953. assert( pList->szPMA>0 );
  84954. /* If the first temporary PMA file has not been opened, open it now. */
  84955. if( pTask->file.pFd==0 ){
  84956. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  84957. assert( rc!=SQLITE_OK || pTask->file.pFd );
  84958. assert( pTask->file.iEof==0 );
  84959. assert( pTask->nPMA==0 );
  84960. }
  84961. /* Try to get the file to memory map */
  84962. if( rc==SQLITE_OK ){
  84963. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  84964. }
  84965. /* Sort the list */
  84966. if( rc==SQLITE_OK ){
  84967. rc = vdbeSorterSort(pTask, pList);
  84968. }
  84969. if( rc==SQLITE_OK ){
  84970. SorterRecord *p;
  84971. SorterRecord *pNext = 0;
  84972. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  84973. pTask->file.iEof);
  84974. pTask->nPMA++;
  84975. vdbePmaWriteVarint(&writer, pList->szPMA);
  84976. for(p=pList->pList; p; p=pNext){
  84977. pNext = p->u.pNext;
  84978. vdbePmaWriteVarint(&writer, p->nVal);
  84979. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  84980. if( pList->aMemory==0 ) sqlite3_free(p);
  84981. }
  84982. pList->pList = p;
  84983. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  84984. }
  84985. vdbeSorterWorkDebug(pTask, "exit");
  84986. assert( rc!=SQLITE_OK || pList->pList==0 );
  84987. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  84988. return rc;
  84989. }
  84990. /*
  84991. ** Advance the MergeEngine to its next entry.
  84992. ** Set *pbEof to true there is no next entry because
  84993. ** the MergeEngine has reached the end of all its inputs.
  84994. **
  84995. ** Return SQLITE_OK if successful or an error code if an error occurs.
  84996. */
  84997. static int vdbeMergeEngineStep(
  84998. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  84999. int *pbEof /* Set TRUE at EOF. Set false for more content */
  85000. ){
  85001. int rc;
  85002. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  85003. SortSubtask *pTask = pMerger->pTask;
  85004. /* Advance the current PmaReader */
  85005. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  85006. /* Update contents of aTree[] */
  85007. if( rc==SQLITE_OK ){
  85008. int i; /* Index of aTree[] to recalculate */
  85009. PmaReader *pReadr1; /* First PmaReader to compare */
  85010. PmaReader *pReadr2; /* Second PmaReader to compare */
  85011. int bCached = 0;
  85012. /* Find the first two PmaReaders to compare. The one that was just
  85013. ** advanced (iPrev) and the one next to it in the array. */
  85014. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  85015. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  85016. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  85017. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  85018. int iRes;
  85019. if( pReadr1->pFd==0 ){
  85020. iRes = +1;
  85021. }else if( pReadr2->pFd==0 ){
  85022. iRes = -1;
  85023. }else{
  85024. iRes = pTask->xCompare(pTask, &bCached,
  85025. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  85026. );
  85027. }
  85028. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  85029. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  85030. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  85031. ** pKey2 to point to the record belonging to pReadr2.
  85032. **
  85033. ** Alternatively, if pReadr2 contains the smaller of the two values,
  85034. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  85035. ** was actually called above, then pTask->pUnpacked now contains
  85036. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  85037. ** vdbeSorterCompare() from decoding pReadr2 again.
  85038. **
  85039. ** If the two values were equal, then the value from the oldest
  85040. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  85041. ** is sorted from oldest to newest, so pReadr1 contains older values
  85042. ** than pReadr2 iff (pReadr1<pReadr2). */
  85043. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  85044. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  85045. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  85046. bCached = 0;
  85047. }else{
  85048. if( pReadr1->pFd ) bCached = 0;
  85049. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  85050. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  85051. }
  85052. }
  85053. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  85054. }
  85055. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  85056. }
  85057. #if SQLITE_MAX_WORKER_THREADS>0
  85058. /*
  85059. ** The main routine for background threads that write level-0 PMAs.
  85060. */
  85061. static void *vdbeSorterFlushThread(void *pCtx){
  85062. SortSubtask *pTask = (SortSubtask*)pCtx;
  85063. int rc; /* Return code */
  85064. assert( pTask->bDone==0 );
  85065. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  85066. pTask->bDone = 1;
  85067. return SQLITE_INT_TO_PTR(rc);
  85068. }
  85069. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  85070. /*
  85071. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  85072. ** using a background thread.
  85073. */
  85074. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  85075. #if SQLITE_MAX_WORKER_THREADS==0
  85076. pSorter->bUsePMA = 1;
  85077. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  85078. #else
  85079. int rc = SQLITE_OK;
  85080. int i;
  85081. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  85082. int nWorker = (pSorter->nTask-1);
  85083. /* Set the flag to indicate that at least one PMA has been written.
  85084. ** Or will be, anyhow. */
  85085. pSorter->bUsePMA = 1;
  85086. /* Select a sub-task to sort and flush the current list of in-memory
  85087. ** records to disk. If the sorter is running in multi-threaded mode,
  85088. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  85089. ** the background thread from a sub-tasks previous turn is still running,
  85090. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  85091. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  85092. ** sub-tasks are prefered as they use background threads - the final
  85093. ** sub-task uses the main thread. */
  85094. for(i=0; i<nWorker; i++){
  85095. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  85096. pTask = &pSorter->aTask[iTest];
  85097. if( pTask->bDone ){
  85098. rc = vdbeSorterJoinThread(pTask);
  85099. }
  85100. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  85101. }
  85102. if( rc==SQLITE_OK ){
  85103. if( i==nWorker ){
  85104. /* Use the foreground thread for this operation */
  85105. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  85106. }else{
  85107. /* Launch a background thread for this operation */
  85108. u8 *aMem = pTask->list.aMemory;
  85109. void *pCtx = (void*)pTask;
  85110. assert( pTask->pThread==0 && pTask->bDone==0 );
  85111. assert( pTask->list.pList==0 );
  85112. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  85113. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  85114. pTask->list = pSorter->list;
  85115. pSorter->list.pList = 0;
  85116. pSorter->list.szPMA = 0;
  85117. if( aMem ){
  85118. pSorter->list.aMemory = aMem;
  85119. pSorter->nMemory = sqlite3MallocSize(aMem);
  85120. }else if( pSorter->list.aMemory ){
  85121. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  85122. if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
  85123. }
  85124. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  85125. }
  85126. }
  85127. return rc;
  85128. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  85129. }
  85130. /*
  85131. ** Add a record to the sorter.
  85132. */
  85133. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  85134. const VdbeCursor *pCsr, /* Sorter cursor */
  85135. Mem *pVal /* Memory cell containing record */
  85136. ){
  85137. VdbeSorter *pSorter;
  85138. int rc = SQLITE_OK; /* Return Code */
  85139. SorterRecord *pNew; /* New list element */
  85140. int bFlush; /* True to flush contents of memory to PMA */
  85141. int nReq; /* Bytes of memory required */
  85142. int nPMA; /* Bytes of PMA space required */
  85143. int t; /* serial type of first record field */
  85144. assert( pCsr->eCurType==CURTYPE_SORTER );
  85145. pSorter = pCsr->uc.pSorter;
  85146. getVarint32((const u8*)&pVal->z[1], t);
  85147. if( t>0 && t<10 && t!=7 ){
  85148. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  85149. }else if( t>10 && (t & 0x01) ){
  85150. pSorter->typeMask &= SORTER_TYPE_TEXT;
  85151. }else{
  85152. pSorter->typeMask = 0;
  85153. }
  85154. assert( pSorter );
  85155. /* Figure out whether or not the current contents of memory should be
  85156. ** flushed to a PMA before continuing. If so, do so.
  85157. **
  85158. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  85159. ** flush the contents of memory to a new PMA if (a) at least one value is
  85160. ** already in memory and (b) the new value will not fit in memory.
  85161. **
  85162. ** Or, if using separate allocations for each record, flush the contents
  85163. ** of memory to a PMA if either of the following are true:
  85164. **
  85165. ** * The total memory allocated for the in-memory list is greater
  85166. ** than (page-size * cache-size), or
  85167. **
  85168. ** * The total memory allocated for the in-memory list is greater
  85169. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  85170. */
  85171. nReq = pVal->n + sizeof(SorterRecord);
  85172. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  85173. if( pSorter->mxPmaSize ){
  85174. if( pSorter->list.aMemory ){
  85175. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  85176. }else{
  85177. bFlush = (
  85178. (pSorter->list.szPMA > pSorter->mxPmaSize)
  85179. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  85180. );
  85181. }
  85182. if( bFlush ){
  85183. rc = vdbeSorterFlushPMA(pSorter);
  85184. pSorter->list.szPMA = 0;
  85185. pSorter->iMemory = 0;
  85186. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  85187. }
  85188. }
  85189. pSorter->list.szPMA += nPMA;
  85190. if( nPMA>pSorter->mxKeysize ){
  85191. pSorter->mxKeysize = nPMA;
  85192. }
  85193. if( pSorter->list.aMemory ){
  85194. int nMin = pSorter->iMemory + nReq;
  85195. if( nMin>pSorter->nMemory ){
  85196. u8 *aNew;
  85197. int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
  85198. int nNew = pSorter->nMemory * 2;
  85199. while( nNew < nMin ) nNew = nNew*2;
  85200. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  85201. if( nNew < nMin ) nNew = nMin;
  85202. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  85203. if( !aNew ) return SQLITE_NOMEM_BKPT;
  85204. pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
  85205. pSorter->list.aMemory = aNew;
  85206. pSorter->nMemory = nNew;
  85207. }
  85208. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  85209. pSorter->iMemory += ROUND8(nReq);
  85210. if( pSorter->list.pList ){
  85211. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  85212. }
  85213. }else{
  85214. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  85215. if( pNew==0 ){
  85216. return SQLITE_NOMEM_BKPT;
  85217. }
  85218. pNew->u.pNext = pSorter->list.pList;
  85219. }
  85220. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  85221. pNew->nVal = pVal->n;
  85222. pSorter->list.pList = pNew;
  85223. return rc;
  85224. }
  85225. /*
  85226. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  85227. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  85228. ** except that the number-of-bytes varint is omitted from the start.
  85229. */
  85230. static int vdbeIncrPopulate(IncrMerger *pIncr){
  85231. int rc = SQLITE_OK;
  85232. int rc2;
  85233. i64 iStart = pIncr->iStartOff;
  85234. SorterFile *pOut = &pIncr->aFile[1];
  85235. SortSubtask *pTask = pIncr->pTask;
  85236. MergeEngine *pMerger = pIncr->pMerger;
  85237. PmaWriter writer;
  85238. assert( pIncr->bEof==0 );
  85239. vdbeSorterPopulateDebug(pTask, "enter");
  85240. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  85241. while( rc==SQLITE_OK ){
  85242. int dummy;
  85243. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  85244. int nKey = pReader->nKey;
  85245. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  85246. /* Check if the output file is full or if the input has been exhausted.
  85247. ** In either case exit the loop. */
  85248. if( pReader->pFd==0 ) break;
  85249. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  85250. /* Write the next key to the output. */
  85251. vdbePmaWriteVarint(&writer, nKey);
  85252. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  85253. assert( pIncr->pMerger->pTask==pTask );
  85254. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  85255. }
  85256. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  85257. if( rc==SQLITE_OK ) rc = rc2;
  85258. vdbeSorterPopulateDebug(pTask, "exit");
  85259. return rc;
  85260. }
  85261. #if SQLITE_MAX_WORKER_THREADS>0
  85262. /*
  85263. ** The main routine for background threads that populate aFile[1] of
  85264. ** multi-threaded IncrMerger objects.
  85265. */
  85266. static void *vdbeIncrPopulateThread(void *pCtx){
  85267. IncrMerger *pIncr = (IncrMerger*)pCtx;
  85268. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  85269. pIncr->pTask->bDone = 1;
  85270. return pRet;
  85271. }
  85272. /*
  85273. ** Launch a background thread to populate aFile[1] of pIncr.
  85274. */
  85275. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  85276. void *p = (void*)pIncr;
  85277. assert( pIncr->bUseThread );
  85278. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  85279. }
  85280. #endif
  85281. /*
  85282. ** This function is called when the PmaReader corresponding to pIncr has
  85283. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  85284. ** aFile[0] such that the PmaReader should start rereading it from the
  85285. ** beginning.
  85286. **
  85287. ** For single-threaded objects, this is accomplished by literally reading
  85288. ** keys from pIncr->pMerger and repopulating aFile[0].
  85289. **
  85290. ** For multi-threaded objects, all that is required is to wait until the
  85291. ** background thread is finished (if it is not already) and then swap
  85292. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  85293. ** been exhausted, this function also launches a new background thread
  85294. ** to populate the new aFile[1].
  85295. **
  85296. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  85297. */
  85298. static int vdbeIncrSwap(IncrMerger *pIncr){
  85299. int rc = SQLITE_OK;
  85300. #if SQLITE_MAX_WORKER_THREADS>0
  85301. if( pIncr->bUseThread ){
  85302. rc = vdbeSorterJoinThread(pIncr->pTask);
  85303. if( rc==SQLITE_OK ){
  85304. SorterFile f0 = pIncr->aFile[0];
  85305. pIncr->aFile[0] = pIncr->aFile[1];
  85306. pIncr->aFile[1] = f0;
  85307. }
  85308. if( rc==SQLITE_OK ){
  85309. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  85310. pIncr->bEof = 1;
  85311. }else{
  85312. rc = vdbeIncrBgPopulate(pIncr);
  85313. }
  85314. }
  85315. }else
  85316. #endif
  85317. {
  85318. rc = vdbeIncrPopulate(pIncr);
  85319. pIncr->aFile[0] = pIncr->aFile[1];
  85320. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  85321. pIncr->bEof = 1;
  85322. }
  85323. }
  85324. return rc;
  85325. }
  85326. /*
  85327. ** Allocate and return a new IncrMerger object to read data from pMerger.
  85328. **
  85329. ** If an OOM condition is encountered, return NULL. In this case free the
  85330. ** pMerger argument before returning.
  85331. */
  85332. static int vdbeIncrMergerNew(
  85333. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  85334. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  85335. IncrMerger **ppOut /* Write the new IncrMerger here */
  85336. ){
  85337. int rc = SQLITE_OK;
  85338. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  85339. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  85340. if( pIncr ){
  85341. pIncr->pMerger = pMerger;
  85342. pIncr->pTask = pTask;
  85343. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  85344. pTask->file2.iEof += pIncr->mxSz;
  85345. }else{
  85346. vdbeMergeEngineFree(pMerger);
  85347. rc = SQLITE_NOMEM_BKPT;
  85348. }
  85349. return rc;
  85350. }
  85351. #if SQLITE_MAX_WORKER_THREADS>0
  85352. /*
  85353. ** Set the "use-threads" flag on object pIncr.
  85354. */
  85355. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  85356. pIncr->bUseThread = 1;
  85357. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  85358. }
  85359. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  85360. /*
  85361. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  85362. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  85363. ** are advanced. This routine merely does the comparison.
  85364. */
  85365. static void vdbeMergeEngineCompare(
  85366. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  85367. int iOut /* Store the result in pMerger->aTree[iOut] */
  85368. ){
  85369. int i1;
  85370. int i2;
  85371. int iRes;
  85372. PmaReader *p1;
  85373. PmaReader *p2;
  85374. assert( iOut<pMerger->nTree && iOut>0 );
  85375. if( iOut>=(pMerger->nTree/2) ){
  85376. i1 = (iOut - pMerger->nTree/2) * 2;
  85377. i2 = i1 + 1;
  85378. }else{
  85379. i1 = pMerger->aTree[iOut*2];
  85380. i2 = pMerger->aTree[iOut*2+1];
  85381. }
  85382. p1 = &pMerger->aReadr[i1];
  85383. p2 = &pMerger->aReadr[i2];
  85384. if( p1->pFd==0 ){
  85385. iRes = i2;
  85386. }else if( p2->pFd==0 ){
  85387. iRes = i1;
  85388. }else{
  85389. SortSubtask *pTask = pMerger->pTask;
  85390. int bCached = 0;
  85391. int res;
  85392. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  85393. res = pTask->xCompare(
  85394. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  85395. );
  85396. if( res<=0 ){
  85397. iRes = i1;
  85398. }else{
  85399. iRes = i2;
  85400. }
  85401. }
  85402. pMerger->aTree[iOut] = iRes;
  85403. }
  85404. /*
  85405. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  85406. ** and vdbePmaReaderIncrMergeInit().
  85407. **
  85408. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  85409. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  85410. ** when there exists one or more separate worker threads.
  85411. */
  85412. #define INCRINIT_NORMAL 0
  85413. #define INCRINIT_TASK 1
  85414. #define INCRINIT_ROOT 2
  85415. /*
  85416. ** Forward reference required as the vdbeIncrMergeInit() and
  85417. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  85418. ** building a merge tree.
  85419. */
  85420. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  85421. /*
  85422. ** Initialize the MergeEngine object passed as the second argument. Once this
  85423. ** function returns, the first key of merged data may be read from the
  85424. ** MergeEngine object in the usual fashion.
  85425. **
  85426. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  85427. ** objects attached to the PmaReader objects that the merger reads from have
  85428. ** already been populated, but that they have not yet populated aFile[0] and
  85429. ** set the PmaReader objects up to read from it. In this case all that is
  85430. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  85431. ** its first key.
  85432. **
  85433. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  85434. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  85435. ** to pMerger.
  85436. **
  85437. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  85438. */
  85439. static int vdbeMergeEngineInit(
  85440. SortSubtask *pTask, /* Thread that will run pMerger */
  85441. MergeEngine *pMerger, /* MergeEngine to initialize */
  85442. int eMode /* One of the INCRINIT_XXX constants */
  85443. ){
  85444. int rc = SQLITE_OK; /* Return code */
  85445. int i; /* For looping over PmaReader objects */
  85446. int nTree = pMerger->nTree;
  85447. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  85448. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  85449. /* Verify that the MergeEngine is assigned to a single thread */
  85450. assert( pMerger->pTask==0 );
  85451. pMerger->pTask = pTask;
  85452. for(i=0; i<nTree; i++){
  85453. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  85454. /* PmaReaders should be normally initialized in order, as if they are
  85455. ** reading from the same temp file this makes for more linear file IO.
  85456. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  85457. ** in use it will block the vdbePmaReaderNext() call while it uses
  85458. ** the main thread to fill its buffer. So calling PmaReaderNext()
  85459. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  85460. ** better advantage of multi-processor hardware. */
  85461. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  85462. }else{
  85463. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  85464. }
  85465. if( rc!=SQLITE_OK ) return rc;
  85466. }
  85467. for(i=pMerger->nTree-1; i>0; i--){
  85468. vdbeMergeEngineCompare(pMerger, i);
  85469. }
  85470. return pTask->pUnpacked->errCode;
  85471. }
  85472. /*
  85473. ** The PmaReader passed as the first argument is guaranteed to be an
  85474. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  85475. ** and/or initialize the temp file related fields of the IncrMerge
  85476. ** object at (pReadr->pIncr).
  85477. **
  85478. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  85479. ** in the sub-tree headed by pReadr are also initialized. Data is then
  85480. ** loaded into the buffers belonging to pReadr and it is set to point to
  85481. ** the first key in its range.
  85482. **
  85483. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  85484. ** to be a multi-threaded PmaReader and this function is being called in a
  85485. ** background thread. In this case all PmaReaders in the sub-tree are
  85486. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  85487. ** pReadr is populated. However, pReadr itself is not set up to point
  85488. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  85489. ** that.
  85490. **
  85491. ** The reason this function does not call vdbePmaReaderNext() immediately
  85492. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  85493. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  85494. ** this entire function is being run by thread (pTask->thread), that will
  85495. ** lead to the current background thread attempting to join itself.
  85496. **
  85497. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  85498. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  85499. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  85500. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  85501. ** the current PmaReader set to point to the first key in its range.
  85502. **
  85503. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  85504. */
  85505. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  85506. int rc = SQLITE_OK;
  85507. IncrMerger *pIncr = pReadr->pIncr;
  85508. SortSubtask *pTask = pIncr->pTask;
  85509. sqlite3 *db = pTask->pSorter->db;
  85510. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  85511. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  85512. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  85513. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  85514. ** requires two temp files to itself, whereas a single-threaded object
  85515. ** only requires a region of pTask->file2. */
  85516. if( rc==SQLITE_OK ){
  85517. int mxSz = pIncr->mxSz;
  85518. #if SQLITE_MAX_WORKER_THREADS>0
  85519. if( pIncr->bUseThread ){
  85520. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  85521. if( rc==SQLITE_OK ){
  85522. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  85523. }
  85524. }else
  85525. #endif
  85526. /*if( !pIncr->bUseThread )*/{
  85527. if( pTask->file2.pFd==0 ){
  85528. assert( pTask->file2.iEof>0 );
  85529. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  85530. pTask->file2.iEof = 0;
  85531. }
  85532. if( rc==SQLITE_OK ){
  85533. pIncr->aFile[1].pFd = pTask->file2.pFd;
  85534. pIncr->iStartOff = pTask->file2.iEof;
  85535. pTask->file2.iEof += mxSz;
  85536. }
  85537. }
  85538. }
  85539. #if SQLITE_MAX_WORKER_THREADS>0
  85540. if( rc==SQLITE_OK && pIncr->bUseThread ){
  85541. /* Use the current thread to populate aFile[1], even though this
  85542. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  85543. ** then this function is already running in background thread
  85544. ** pIncr->pTask->thread.
  85545. **
  85546. ** If this is the INCRINIT_ROOT object, then it is running in the
  85547. ** main VDBE thread. But that is Ok, as that thread cannot return
  85548. ** control to the VDBE or proceed with anything useful until the
  85549. ** first results are ready from this merger object anyway.
  85550. */
  85551. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  85552. rc = vdbeIncrPopulate(pIncr);
  85553. }
  85554. #endif
  85555. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  85556. rc = vdbePmaReaderNext(pReadr);
  85557. }
  85558. return rc;
  85559. }
  85560. #if SQLITE_MAX_WORKER_THREADS>0
  85561. /*
  85562. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  85563. ** background threads.
  85564. */
  85565. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  85566. PmaReader *pReader = (PmaReader*)pCtx;
  85567. void *pRet = SQLITE_INT_TO_PTR(
  85568. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  85569. );
  85570. pReader->pIncr->pTask->bDone = 1;
  85571. return pRet;
  85572. }
  85573. #endif
  85574. /*
  85575. ** If the PmaReader passed as the first argument is not an incremental-reader
  85576. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  85577. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  85578. ** this routine to initialize the incremental merge.
  85579. **
  85580. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  85581. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  85582. ** Or, if the IncrMerger is single threaded, the same function is called
  85583. ** using the current thread.
  85584. */
  85585. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  85586. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  85587. int rc = SQLITE_OK; /* Return code */
  85588. if( pIncr ){
  85589. #if SQLITE_MAX_WORKER_THREADS>0
  85590. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  85591. if( pIncr->bUseThread ){
  85592. void *pCtx = (void*)pReadr;
  85593. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  85594. }else
  85595. #endif
  85596. {
  85597. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  85598. }
  85599. }
  85600. return rc;
  85601. }
  85602. /*
  85603. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  85604. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  85605. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  85606. ** to NULL and return an SQLite error code.
  85607. **
  85608. ** When this function is called, *piOffset is set to the offset of the
  85609. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  85610. ** set to the offset immediately following the last byte of the last
  85611. ** PMA before returning. If an error does occur, then the final value of
  85612. ** *piOffset is undefined.
  85613. */
  85614. static int vdbeMergeEngineLevel0(
  85615. SortSubtask *pTask, /* Sorter task to read from */
  85616. int nPMA, /* Number of PMAs to read */
  85617. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  85618. MergeEngine **ppOut /* OUT: New merge-engine */
  85619. ){
  85620. MergeEngine *pNew; /* Merge engine to return */
  85621. i64 iOff = *piOffset;
  85622. int i;
  85623. int rc = SQLITE_OK;
  85624. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  85625. if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
  85626. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  85627. i64 nDummy = 0;
  85628. PmaReader *pReadr = &pNew->aReadr[i];
  85629. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  85630. iOff = pReadr->iEof;
  85631. }
  85632. if( rc!=SQLITE_OK ){
  85633. vdbeMergeEngineFree(pNew);
  85634. *ppOut = 0;
  85635. }
  85636. *piOffset = iOff;
  85637. return rc;
  85638. }
  85639. /*
  85640. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  85641. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  85642. **
  85643. ** i.e.
  85644. **
  85645. ** nPMA<=16 -> TreeDepth() == 0
  85646. ** nPMA<=256 -> TreeDepth() == 1
  85647. ** nPMA<=65536 -> TreeDepth() == 2
  85648. */
  85649. static int vdbeSorterTreeDepth(int nPMA){
  85650. int nDepth = 0;
  85651. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  85652. while( nDiv < (i64)nPMA ){
  85653. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  85654. nDepth++;
  85655. }
  85656. return nDepth;
  85657. }
  85658. /*
  85659. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  85660. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  85661. ** tree, counting from zero. This function adds pLeaf to the tree.
  85662. **
  85663. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  85664. ** code is returned and pLeaf is freed.
  85665. */
  85666. static int vdbeSorterAddToTree(
  85667. SortSubtask *pTask, /* Task context */
  85668. int nDepth, /* Depth of tree according to TreeDepth() */
  85669. int iSeq, /* Sequence number of leaf within tree */
  85670. MergeEngine *pRoot, /* Root of tree */
  85671. MergeEngine *pLeaf /* Leaf to add to tree */
  85672. ){
  85673. int rc = SQLITE_OK;
  85674. int nDiv = 1;
  85675. int i;
  85676. MergeEngine *p = pRoot;
  85677. IncrMerger *pIncr;
  85678. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  85679. for(i=1; i<nDepth; i++){
  85680. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  85681. }
  85682. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  85683. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  85684. PmaReader *pReadr = &p->aReadr[iIter];
  85685. if( pReadr->pIncr==0 ){
  85686. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  85687. if( pNew==0 ){
  85688. rc = SQLITE_NOMEM_BKPT;
  85689. }else{
  85690. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  85691. }
  85692. }
  85693. if( rc==SQLITE_OK ){
  85694. p = pReadr->pIncr->pMerger;
  85695. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  85696. }
  85697. }
  85698. if( rc==SQLITE_OK ){
  85699. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  85700. }else{
  85701. vdbeIncrFree(pIncr);
  85702. }
  85703. return rc;
  85704. }
  85705. /*
  85706. ** This function is called as part of a SorterRewind() operation on a sorter
  85707. ** that has already written two or more level-0 PMAs to one or more temp
  85708. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  85709. ** can be used to incrementally merge all PMAs on disk.
  85710. **
  85711. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  85712. ** MergeEngine object at the root of the tree before returning. Or, if an
  85713. ** error occurs, an SQLite error code is returned and the final value
  85714. ** of *ppOut is undefined.
  85715. */
  85716. static int vdbeSorterMergeTreeBuild(
  85717. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  85718. MergeEngine **ppOut /* Write the MergeEngine here */
  85719. ){
  85720. MergeEngine *pMain = 0;
  85721. int rc = SQLITE_OK;
  85722. int iTask;
  85723. #if SQLITE_MAX_WORKER_THREADS>0
  85724. /* If the sorter uses more than one task, then create the top-level
  85725. ** MergeEngine here. This MergeEngine will read data from exactly
  85726. ** one PmaReader per sub-task. */
  85727. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  85728. if( pSorter->nTask>1 ){
  85729. pMain = vdbeMergeEngineNew(pSorter->nTask);
  85730. if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
  85731. }
  85732. #endif
  85733. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  85734. SortSubtask *pTask = &pSorter->aTask[iTask];
  85735. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  85736. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  85737. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  85738. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  85739. i64 iReadOff = 0;
  85740. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  85741. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  85742. }else{
  85743. int i;
  85744. int iSeq = 0;
  85745. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  85746. if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
  85747. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  85748. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  85749. int nReader; /* Number of level-0 PMAs to merge */
  85750. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  85751. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  85752. if( rc==SQLITE_OK ){
  85753. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  85754. }
  85755. }
  85756. }
  85757. if( rc==SQLITE_OK ){
  85758. #if SQLITE_MAX_WORKER_THREADS>0
  85759. if( pMain!=0 ){
  85760. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  85761. }else
  85762. #endif
  85763. {
  85764. assert( pMain==0 );
  85765. pMain = pRoot;
  85766. }
  85767. }else{
  85768. vdbeMergeEngineFree(pRoot);
  85769. }
  85770. }
  85771. }
  85772. if( rc!=SQLITE_OK ){
  85773. vdbeMergeEngineFree(pMain);
  85774. pMain = 0;
  85775. }
  85776. *ppOut = pMain;
  85777. return rc;
  85778. }
  85779. /*
  85780. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  85781. ** on a sorter that has written two or more PMAs to temporary files. It sets
  85782. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  85783. ** (for multi-threaded sorters) so that it can be used to iterate through
  85784. ** all records stored in the sorter.
  85785. **
  85786. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  85787. */
  85788. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  85789. int rc; /* Return code */
  85790. SortSubtask *pTask0 = &pSorter->aTask[0];
  85791. MergeEngine *pMain = 0;
  85792. #if SQLITE_MAX_WORKER_THREADS
  85793. sqlite3 *db = pTask0->pSorter->db;
  85794. int i;
  85795. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  85796. for(i=0; i<pSorter->nTask; i++){
  85797. pSorter->aTask[i].xCompare = xCompare;
  85798. }
  85799. #endif
  85800. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  85801. if( rc==SQLITE_OK ){
  85802. #if SQLITE_MAX_WORKER_THREADS
  85803. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  85804. if( pSorter->bUseThreads ){
  85805. int iTask;
  85806. PmaReader *pReadr = 0;
  85807. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  85808. rc = vdbeSortAllocUnpacked(pLast);
  85809. if( rc==SQLITE_OK ){
  85810. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  85811. pSorter->pReader = pReadr;
  85812. if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
  85813. }
  85814. if( rc==SQLITE_OK ){
  85815. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  85816. if( rc==SQLITE_OK ){
  85817. vdbeIncrMergerSetThreads(pReadr->pIncr);
  85818. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  85819. IncrMerger *pIncr;
  85820. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  85821. vdbeIncrMergerSetThreads(pIncr);
  85822. assert( pIncr->pTask!=pLast );
  85823. }
  85824. }
  85825. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  85826. /* Check that:
  85827. **
  85828. ** a) The incremental merge object is configured to use the
  85829. ** right task, and
  85830. ** b) If it is using task (nTask-1), it is configured to run
  85831. ** in single-threaded mode. This is important, as the
  85832. ** root merge (INCRINIT_ROOT) will be using the same task
  85833. ** object.
  85834. */
  85835. PmaReader *p = &pMain->aReadr[iTask];
  85836. assert( p->pIncr==0 || (
  85837. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  85838. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  85839. ));
  85840. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  85841. }
  85842. }
  85843. pMain = 0;
  85844. }
  85845. if( rc==SQLITE_OK ){
  85846. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  85847. }
  85848. }else
  85849. #endif
  85850. {
  85851. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  85852. pSorter->pMerger = pMain;
  85853. pMain = 0;
  85854. }
  85855. }
  85856. if( rc!=SQLITE_OK ){
  85857. vdbeMergeEngineFree(pMain);
  85858. }
  85859. return rc;
  85860. }
  85861. /*
  85862. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  85863. ** this function is called to prepare for iterating through the records
  85864. ** in sorted order.
  85865. */
  85866. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  85867. VdbeSorter *pSorter;
  85868. int rc = SQLITE_OK; /* Return code */
  85869. assert( pCsr->eCurType==CURTYPE_SORTER );
  85870. pSorter = pCsr->uc.pSorter;
  85871. assert( pSorter );
  85872. /* If no data has been written to disk, then do not do so now. Instead,
  85873. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  85874. ** from the in-memory list. */
  85875. if( pSorter->bUsePMA==0 ){
  85876. if( pSorter->list.pList ){
  85877. *pbEof = 0;
  85878. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  85879. }else{
  85880. *pbEof = 1;
  85881. }
  85882. return rc;
  85883. }
  85884. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  85885. ** function flushes the contents of memory to disk, it immediately always
  85886. ** creates a new list consisting of a single key immediately afterwards.
  85887. ** So the list is never empty at this point. */
  85888. assert( pSorter->list.pList );
  85889. rc = vdbeSorterFlushPMA(pSorter);
  85890. /* Join all threads */
  85891. rc = vdbeSorterJoinAll(pSorter, rc);
  85892. vdbeSorterRewindDebug("rewind");
  85893. /* Assuming no errors have occurred, set up a merger structure to
  85894. ** incrementally read and merge all remaining PMAs. */
  85895. assert( pSorter->pReader==0 );
  85896. if( rc==SQLITE_OK ){
  85897. rc = vdbeSorterSetupMerge(pSorter);
  85898. *pbEof = 0;
  85899. }
  85900. vdbeSorterRewindDebug("rewinddone");
  85901. return rc;
  85902. }
  85903. /*
  85904. ** Advance to the next element in the sorter. Return value:
  85905. **
  85906. ** SQLITE_OK success
  85907. ** SQLITE_DONE end of data
  85908. ** otherwise some kind of error.
  85909. */
  85910. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
  85911. VdbeSorter *pSorter;
  85912. int rc; /* Return code */
  85913. assert( pCsr->eCurType==CURTYPE_SORTER );
  85914. pSorter = pCsr->uc.pSorter;
  85915. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  85916. if( pSorter->bUsePMA ){
  85917. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  85918. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  85919. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  85920. #if SQLITE_MAX_WORKER_THREADS>0
  85921. if( pSorter->bUseThreads ){
  85922. rc = vdbePmaReaderNext(pSorter->pReader);
  85923. if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
  85924. }else
  85925. #endif
  85926. /*if( !pSorter->bUseThreads )*/ {
  85927. int res = 0;
  85928. assert( pSorter->pMerger!=0 );
  85929. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  85930. rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
  85931. if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
  85932. }
  85933. }else{
  85934. SorterRecord *pFree = pSorter->list.pList;
  85935. pSorter->list.pList = pFree->u.pNext;
  85936. pFree->u.pNext = 0;
  85937. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  85938. rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
  85939. }
  85940. return rc;
  85941. }
  85942. /*
  85943. ** Return a pointer to a buffer owned by the sorter that contains the
  85944. ** current key.
  85945. */
  85946. static void *vdbeSorterRowkey(
  85947. const VdbeSorter *pSorter, /* Sorter object */
  85948. int *pnKey /* OUT: Size of current key in bytes */
  85949. ){
  85950. void *pKey;
  85951. if( pSorter->bUsePMA ){
  85952. PmaReader *pReader;
  85953. #if SQLITE_MAX_WORKER_THREADS>0
  85954. if( pSorter->bUseThreads ){
  85955. pReader = pSorter->pReader;
  85956. }else
  85957. #endif
  85958. /*if( !pSorter->bUseThreads )*/{
  85959. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  85960. }
  85961. *pnKey = pReader->nKey;
  85962. pKey = pReader->aKey;
  85963. }else{
  85964. *pnKey = pSorter->list.pList->nVal;
  85965. pKey = SRVAL(pSorter->list.pList);
  85966. }
  85967. return pKey;
  85968. }
  85969. /*
  85970. ** Copy the current sorter key into the memory cell pOut.
  85971. */
  85972. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  85973. VdbeSorter *pSorter;
  85974. void *pKey; int nKey; /* Sorter key to copy into pOut */
  85975. assert( pCsr->eCurType==CURTYPE_SORTER );
  85976. pSorter = pCsr->uc.pSorter;
  85977. pKey = vdbeSorterRowkey(pSorter, &nKey);
  85978. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  85979. return SQLITE_NOMEM_BKPT;
  85980. }
  85981. pOut->n = nKey;
  85982. MemSetTypeFlag(pOut, MEM_Blob);
  85983. memcpy(pOut->z, pKey, nKey);
  85984. return SQLITE_OK;
  85985. }
  85986. /*
  85987. ** Compare the key in memory cell pVal with the key that the sorter cursor
  85988. ** passed as the first argument currently points to. For the purposes of
  85989. ** the comparison, ignore the rowid field at the end of each record.
  85990. **
  85991. ** If the sorter cursor key contains any NULL values, consider it to be
  85992. ** less than pVal. Even if pVal also contains NULL values.
  85993. **
  85994. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  85995. ** Otherwise, set *pRes to a negative, zero or positive value if the
  85996. ** key in pVal is smaller than, equal to or larger than the current sorter
  85997. ** key.
  85998. **
  85999. ** This routine forms the core of the OP_SorterCompare opcode, which in
  86000. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  86001. */
  86002. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  86003. const VdbeCursor *pCsr, /* Sorter cursor */
  86004. Mem *pVal, /* Value to compare to current sorter key */
  86005. int nKeyCol, /* Compare this many columns */
  86006. int *pRes /* OUT: Result of comparison */
  86007. ){
  86008. VdbeSorter *pSorter;
  86009. UnpackedRecord *r2;
  86010. KeyInfo *pKeyInfo;
  86011. int i;
  86012. void *pKey; int nKey; /* Sorter key to compare pVal with */
  86013. assert( pCsr->eCurType==CURTYPE_SORTER );
  86014. pSorter = pCsr->uc.pSorter;
  86015. r2 = pSorter->pUnpacked;
  86016. pKeyInfo = pCsr->pKeyInfo;
  86017. if( r2==0 ){
  86018. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  86019. if( r2==0 ) return SQLITE_NOMEM_BKPT;
  86020. r2->nField = nKeyCol;
  86021. }
  86022. assert( r2->nField==nKeyCol );
  86023. pKey = vdbeSorterRowkey(pSorter, &nKey);
  86024. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  86025. for(i=0; i<nKeyCol; i++){
  86026. if( r2->aMem[i].flags & MEM_Null ){
  86027. *pRes = -1;
  86028. return SQLITE_OK;
  86029. }
  86030. }
  86031. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  86032. return SQLITE_OK;
  86033. }
  86034. /************** End of vdbesort.c ********************************************/
  86035. /************** Begin file memjournal.c **************************************/
  86036. /*
  86037. ** 2008 October 7
  86038. **
  86039. ** The author disclaims copyright to this source code. In place of
  86040. ** a legal notice, here is a blessing:
  86041. **
  86042. ** May you do good and not evil.
  86043. ** May you find forgiveness for yourself and forgive others.
  86044. ** May you share freely, never taking more than you give.
  86045. **
  86046. *************************************************************************
  86047. **
  86048. ** This file contains code use to implement an in-memory rollback journal.
  86049. ** The in-memory rollback journal is used to journal transactions for
  86050. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  86051. **
  86052. ** Update: The in-memory journal is also used to temporarily cache
  86053. ** smaller journals that are not critical for power-loss recovery.
  86054. ** For example, statement journals that are not too big will be held
  86055. ** entirely in memory, thus reducing the number of file I/O calls, and
  86056. ** more importantly, reducing temporary file creation events. If these
  86057. ** journals become too large for memory, they are spilled to disk. But
  86058. ** in the common case, they are usually small and no file I/O needs to
  86059. ** occur.
  86060. */
  86061. /* #include "sqliteInt.h" */
  86062. /* Forward references to internal structures */
  86063. typedef struct MemJournal MemJournal;
  86064. typedef struct FilePoint FilePoint;
  86065. typedef struct FileChunk FileChunk;
  86066. /*
  86067. ** The rollback journal is composed of a linked list of these structures.
  86068. **
  86069. ** The zChunk array is always at least 8 bytes in size - usually much more.
  86070. ** Its actual size is stored in the MemJournal.nChunkSize variable.
  86071. */
  86072. struct FileChunk {
  86073. FileChunk *pNext; /* Next chunk in the journal */
  86074. u8 zChunk[8]; /* Content of this chunk */
  86075. };
  86076. /*
  86077. ** By default, allocate this many bytes of memory for each FileChunk object.
  86078. */
  86079. #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
  86080. /*
  86081. ** For chunk size nChunkSize, return the number of bytes that should
  86082. ** be allocated for each FileChunk structure.
  86083. */
  86084. #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
  86085. /*
  86086. ** An instance of this object serves as a cursor into the rollback journal.
  86087. ** The cursor can be either for reading or writing.
  86088. */
  86089. struct FilePoint {
  86090. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  86091. FileChunk *pChunk; /* Specific chunk into which cursor points */
  86092. };
  86093. /*
  86094. ** This structure is a subclass of sqlite3_file. Each open memory-journal
  86095. ** is an instance of this class.
  86096. */
  86097. struct MemJournal {
  86098. const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  86099. int nChunkSize; /* In-memory chunk-size */
  86100. int nSpill; /* Bytes of data before flushing */
  86101. int nSize; /* Bytes of data currently in memory */
  86102. FileChunk *pFirst; /* Head of in-memory chunk-list */
  86103. FilePoint endpoint; /* Pointer to the end of the file */
  86104. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  86105. int flags; /* xOpen flags */
  86106. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  86107. const char *zJournal; /* Name of the journal file */
  86108. };
  86109. /*
  86110. ** Read data from the in-memory journal file. This is the implementation
  86111. ** of the sqlite3_vfs.xRead method.
  86112. */
  86113. static int memjrnlRead(
  86114. sqlite3_file *pJfd, /* The journal file from which to read */
  86115. void *zBuf, /* Put the results here */
  86116. int iAmt, /* Number of bytes to read */
  86117. sqlite_int64 iOfst /* Begin reading at this offset */
  86118. ){
  86119. MemJournal *p = (MemJournal *)pJfd;
  86120. u8 *zOut = zBuf;
  86121. int nRead = iAmt;
  86122. int iChunkOffset;
  86123. FileChunk *pChunk;
  86124. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  86125. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  86126. if( (iAmt+iOfst)>p->endpoint.iOffset ){
  86127. return SQLITE_IOERR_SHORT_READ;
  86128. }
  86129. #endif
  86130. assert( (iAmt+iOfst)<=p->endpoint.iOffset );
  86131. assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
  86132. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  86133. sqlite3_int64 iOff = 0;
  86134. for(pChunk=p->pFirst;
  86135. ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
  86136. pChunk=pChunk->pNext
  86137. ){
  86138. iOff += p->nChunkSize;
  86139. }
  86140. }else{
  86141. pChunk = p->readpoint.pChunk;
  86142. assert( pChunk!=0 );
  86143. }
  86144. iChunkOffset = (int)(iOfst%p->nChunkSize);
  86145. do {
  86146. int iSpace = p->nChunkSize - iChunkOffset;
  86147. int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
  86148. memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
  86149. zOut += nCopy;
  86150. nRead -= iSpace;
  86151. iChunkOffset = 0;
  86152. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  86153. p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
  86154. p->readpoint.pChunk = pChunk;
  86155. return SQLITE_OK;
  86156. }
  86157. /*
  86158. ** Free the list of FileChunk structures headed at MemJournal.pFirst.
  86159. */
  86160. static void memjrnlFreeChunks(MemJournal *p){
  86161. FileChunk *pIter;
  86162. FileChunk *pNext;
  86163. for(pIter=p->pFirst; pIter; pIter=pNext){
  86164. pNext = pIter->pNext;
  86165. sqlite3_free(pIter);
  86166. }
  86167. p->pFirst = 0;
  86168. }
  86169. /*
  86170. ** Flush the contents of memory to a real file on disk.
  86171. */
  86172. static int memjrnlCreateFile(MemJournal *p){
  86173. int rc;
  86174. sqlite3_file *pReal = (sqlite3_file*)p;
  86175. MemJournal copy = *p;
  86176. memset(p, 0, sizeof(MemJournal));
  86177. rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
  86178. if( rc==SQLITE_OK ){
  86179. int nChunk = copy.nChunkSize;
  86180. i64 iOff = 0;
  86181. FileChunk *pIter;
  86182. for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
  86183. if( iOff + nChunk > copy.endpoint.iOffset ){
  86184. nChunk = copy.endpoint.iOffset - iOff;
  86185. }
  86186. rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
  86187. if( rc ) break;
  86188. iOff += nChunk;
  86189. }
  86190. if( rc==SQLITE_OK ){
  86191. /* No error has occurred. Free the in-memory buffers. */
  86192. memjrnlFreeChunks(&copy);
  86193. }
  86194. }
  86195. if( rc!=SQLITE_OK ){
  86196. /* If an error occurred while creating or writing to the file, restore
  86197. ** the original before returning. This way, SQLite uses the in-memory
  86198. ** journal data to roll back changes made to the internal page-cache
  86199. ** before this function was called. */
  86200. sqlite3OsClose(pReal);
  86201. *p = copy;
  86202. }
  86203. return rc;
  86204. }
  86205. /*
  86206. ** Write data to the file.
  86207. */
  86208. static int memjrnlWrite(
  86209. sqlite3_file *pJfd, /* The journal file into which to write */
  86210. const void *zBuf, /* Take data to be written from here */
  86211. int iAmt, /* Number of bytes to write */
  86212. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  86213. ){
  86214. MemJournal *p = (MemJournal *)pJfd;
  86215. int nWrite = iAmt;
  86216. u8 *zWrite = (u8 *)zBuf;
  86217. /* If the file should be created now, create it and write the new data
  86218. ** into the file on disk. */
  86219. if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
  86220. int rc = memjrnlCreateFile(p);
  86221. if( rc==SQLITE_OK ){
  86222. rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
  86223. }
  86224. return rc;
  86225. }
  86226. /* If the contents of this write should be stored in memory */
  86227. else{
  86228. /* An in-memory journal file should only ever be appended to. Random
  86229. ** access writes are not required. The only exception to this is when
  86230. ** the in-memory journal is being used by a connection using the
  86231. ** atomic-write optimization. In this case the first 28 bytes of the
  86232. ** journal file may be written as part of committing the transaction. */
  86233. assert( iOfst==p->endpoint.iOffset || iOfst==0 );
  86234. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  86235. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  86236. if( iOfst==0 && p->pFirst ){
  86237. assert( p->nChunkSize>iAmt );
  86238. memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
  86239. }else
  86240. #else
  86241. assert( iOfst>0 || p->pFirst==0 );
  86242. #endif
  86243. {
  86244. while( nWrite>0 ){
  86245. FileChunk *pChunk = p->endpoint.pChunk;
  86246. int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
  86247. int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
  86248. if( iChunkOffset==0 ){
  86249. /* New chunk is required to extend the file. */
  86250. FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
  86251. if( !pNew ){
  86252. return SQLITE_IOERR_NOMEM_BKPT;
  86253. }
  86254. pNew->pNext = 0;
  86255. if( pChunk ){
  86256. assert( p->pFirst );
  86257. pChunk->pNext = pNew;
  86258. }else{
  86259. assert( !p->pFirst );
  86260. p->pFirst = pNew;
  86261. }
  86262. p->endpoint.pChunk = pNew;
  86263. }
  86264. memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
  86265. zWrite += iSpace;
  86266. nWrite -= iSpace;
  86267. p->endpoint.iOffset += iSpace;
  86268. }
  86269. p->nSize = iAmt + iOfst;
  86270. }
  86271. }
  86272. return SQLITE_OK;
  86273. }
  86274. /*
  86275. ** Truncate the file.
  86276. **
  86277. ** If the journal file is already on disk, truncate it there. Or, if it
  86278. ** is still in main memory but is being truncated to zero bytes in size,
  86279. ** ignore
  86280. */
  86281. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  86282. MemJournal *p = (MemJournal *)pJfd;
  86283. if( ALWAYS(size==0) ){
  86284. memjrnlFreeChunks(p);
  86285. p->nSize = 0;
  86286. p->endpoint.pChunk = 0;
  86287. p->endpoint.iOffset = 0;
  86288. p->readpoint.pChunk = 0;
  86289. p->readpoint.iOffset = 0;
  86290. }
  86291. return SQLITE_OK;
  86292. }
  86293. /*
  86294. ** Close the file.
  86295. */
  86296. static int memjrnlClose(sqlite3_file *pJfd){
  86297. MemJournal *p = (MemJournal *)pJfd;
  86298. memjrnlFreeChunks(p);
  86299. return SQLITE_OK;
  86300. }
  86301. /*
  86302. ** Sync the file.
  86303. **
  86304. ** If the real file has been created, call its xSync method. Otherwise,
  86305. ** syncing an in-memory journal is a no-op.
  86306. */
  86307. static int memjrnlSync(sqlite3_file *pJfd, int flags){
  86308. UNUSED_PARAMETER2(pJfd, flags);
  86309. return SQLITE_OK;
  86310. }
  86311. /*
  86312. ** Query the size of the file in bytes.
  86313. */
  86314. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  86315. MemJournal *p = (MemJournal *)pJfd;
  86316. *pSize = (sqlite_int64) p->endpoint.iOffset;
  86317. return SQLITE_OK;
  86318. }
  86319. /*
  86320. ** Table of methods for MemJournal sqlite3_file object.
  86321. */
  86322. static const struct sqlite3_io_methods MemJournalMethods = {
  86323. 1, /* iVersion */
  86324. memjrnlClose, /* xClose */
  86325. memjrnlRead, /* xRead */
  86326. memjrnlWrite, /* xWrite */
  86327. memjrnlTruncate, /* xTruncate */
  86328. memjrnlSync, /* xSync */
  86329. memjrnlFileSize, /* xFileSize */
  86330. 0, /* xLock */
  86331. 0, /* xUnlock */
  86332. 0, /* xCheckReservedLock */
  86333. 0, /* xFileControl */
  86334. 0, /* xSectorSize */
  86335. 0, /* xDeviceCharacteristics */
  86336. 0, /* xShmMap */
  86337. 0, /* xShmLock */
  86338. 0, /* xShmBarrier */
  86339. 0, /* xShmUnmap */
  86340. 0, /* xFetch */
  86341. 0 /* xUnfetch */
  86342. };
  86343. /*
  86344. ** Open a journal file.
  86345. **
  86346. ** The behaviour of the journal file depends on the value of parameter
  86347. ** nSpill. If nSpill is 0, then the journal file is always create and
  86348. ** accessed using the underlying VFS. If nSpill is less than zero, then
  86349. ** all content is always stored in main-memory. Finally, if nSpill is a
  86350. ** positive value, then the journal file is initially created in-memory
  86351. ** but may be flushed to disk later on. In this case the journal file is
  86352. ** flushed to disk either when it grows larger than nSpill bytes in size,
  86353. ** or when sqlite3JournalCreate() is called.
  86354. */
  86355. SQLITE_PRIVATE int sqlite3JournalOpen(
  86356. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  86357. const char *zName, /* Name of the journal file */
  86358. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  86359. int flags, /* Opening flags */
  86360. int nSpill /* Bytes buffered before opening the file */
  86361. ){
  86362. MemJournal *p = (MemJournal*)pJfd;
  86363. /* Zero the file-handle object. If nSpill was passed zero, initialize
  86364. ** it using the sqlite3OsOpen() function of the underlying VFS. In this
  86365. ** case none of the code in this module is executed as a result of calls
  86366. ** made on the journal file-handle. */
  86367. memset(p, 0, sizeof(MemJournal));
  86368. if( nSpill==0 ){
  86369. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  86370. }
  86371. if( nSpill>0 ){
  86372. p->nChunkSize = nSpill;
  86373. }else{
  86374. p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
  86375. assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
  86376. }
  86377. p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
  86378. p->nSpill = nSpill;
  86379. p->flags = flags;
  86380. p->zJournal = zName;
  86381. p->pVfs = pVfs;
  86382. return SQLITE_OK;
  86383. }
  86384. /*
  86385. ** Open an in-memory journal file.
  86386. */
  86387. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  86388. sqlite3JournalOpen(0, 0, pJfd, 0, -1);
  86389. }
  86390. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  86391. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  86392. /*
  86393. ** If the argument p points to a MemJournal structure that is not an
  86394. ** in-memory-only journal file (i.e. is one that was opened with a +ve
  86395. ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
  86396. ** file has not yet been created, create it now.
  86397. */
  86398. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
  86399. int rc = SQLITE_OK;
  86400. MemJournal *p = (MemJournal*)pJfd;
  86401. if( p->pMethod==&MemJournalMethods && (
  86402. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  86403. p->nSpill>0
  86404. #else
  86405. /* While this appears to not be possible without ATOMIC_WRITE, the
  86406. ** paths are complex, so it seems prudent to leave the test in as
  86407. ** a NEVER(), in case our analysis is subtly flawed. */
  86408. NEVER(p->nSpill>0)
  86409. #endif
  86410. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  86411. || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
  86412. #endif
  86413. )){
  86414. rc = memjrnlCreateFile(p);
  86415. }
  86416. return rc;
  86417. }
  86418. #endif
  86419. /*
  86420. ** The file-handle passed as the only argument is open on a journal file.
  86421. ** Return true if this "journal file" is currently stored in heap memory,
  86422. ** or false otherwise.
  86423. */
  86424. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
  86425. return p->pMethods==&MemJournalMethods;
  86426. }
  86427. /*
  86428. ** Return the number of bytes required to store a JournalFile that uses vfs
  86429. ** pVfs to create the underlying on-disk files.
  86430. */
  86431. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  86432. return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
  86433. }
  86434. /************** End of memjournal.c ******************************************/
  86435. /************** Begin file walker.c ******************************************/
  86436. /*
  86437. ** 2008 August 16
  86438. **
  86439. ** The author disclaims copyright to this source code. In place of
  86440. ** a legal notice, here is a blessing:
  86441. **
  86442. ** May you do good and not evil.
  86443. ** May you find forgiveness for yourself and forgive others.
  86444. ** May you share freely, never taking more than you give.
  86445. **
  86446. *************************************************************************
  86447. ** This file contains routines used for walking the parser tree for
  86448. ** an SQL statement.
  86449. */
  86450. /* #include "sqliteInt.h" */
  86451. /* #include <stdlib.h> */
  86452. /* #include <string.h> */
  86453. /*
  86454. ** Walk an expression tree. Invoke the callback once for each node
  86455. ** of the expression, while descending. (In other words, the callback
  86456. ** is invoked before visiting children.)
  86457. **
  86458. ** The return value from the callback should be one of the WRC_*
  86459. ** constants to specify how to proceed with the walk.
  86460. **
  86461. ** WRC_Continue Continue descending down the tree.
  86462. **
  86463. ** WRC_Prune Do not descend into child nodes, but allow
  86464. ** the walk to continue with sibling nodes.
  86465. **
  86466. ** WRC_Abort Do no more callbacks. Unwind the stack and
  86467. ** return from the top-level walk call.
  86468. **
  86469. ** The return value from this routine is WRC_Abort to abandon the tree walk
  86470. ** and WRC_Continue to continue.
  86471. */
  86472. static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
  86473. int rc;
  86474. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  86475. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  86476. while(1){
  86477. rc = pWalker->xExprCallback(pWalker, pExpr);
  86478. if( rc ) return rc & WRC_Abort;
  86479. if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
  86480. if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  86481. assert( pExpr->x.pList==0 || pExpr->pRight==0 );
  86482. if( pExpr->pRight ){
  86483. pExpr = pExpr->pRight;
  86484. continue;
  86485. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  86486. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  86487. }else if( pExpr->x.pList ){
  86488. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  86489. }
  86490. }
  86491. break;
  86492. }
  86493. return WRC_Continue;
  86494. }
  86495. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  86496. return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
  86497. }
  86498. /*
  86499. ** Call sqlite3WalkExpr() for every expression in list p or until
  86500. ** an abort request is seen.
  86501. */
  86502. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  86503. int i;
  86504. struct ExprList_item *pItem;
  86505. if( p ){
  86506. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  86507. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  86508. }
  86509. }
  86510. return WRC_Continue;
  86511. }
  86512. /*
  86513. ** Walk all expressions associated with SELECT statement p. Do
  86514. ** not invoke the SELECT callback on p, but do (of course) invoke
  86515. ** any expr callbacks and SELECT callbacks that come from subqueries.
  86516. ** Return WRC_Abort or WRC_Continue.
  86517. */
  86518. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  86519. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  86520. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  86521. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  86522. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  86523. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  86524. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  86525. return WRC_Continue;
  86526. }
  86527. /*
  86528. ** Walk the parse trees associated with all subqueries in the
  86529. ** FROM clause of SELECT statement p. Do not invoke the select
  86530. ** callback on p, but do invoke it on each FROM clause subquery
  86531. ** and on any subqueries further down in the tree. Return
  86532. ** WRC_Abort or WRC_Continue;
  86533. */
  86534. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  86535. SrcList *pSrc;
  86536. int i;
  86537. struct SrcList_item *pItem;
  86538. pSrc = p->pSrc;
  86539. assert( pSrc!=0 );
  86540. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  86541. if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  86542. return WRC_Abort;
  86543. }
  86544. if( pItem->fg.isTabFunc
  86545. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  86546. ){
  86547. return WRC_Abort;
  86548. }
  86549. }
  86550. return WRC_Continue;
  86551. }
  86552. /*
  86553. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  86554. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  86555. ** on the compound select chain, p->pPrior.
  86556. **
  86557. ** If it is not NULL, the xSelectCallback() callback is invoked before
  86558. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  86559. ** method is invoked following the walk of the expressions and FROM clause,
  86560. ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
  86561. ** and if the expressions and FROM clause both return WRC_Continue;
  86562. **
  86563. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  86564. ** there is an abort request.
  86565. **
  86566. ** If the Walker does not have an xSelectCallback() then this routine
  86567. ** is a no-op returning WRC_Continue.
  86568. */
  86569. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  86570. int rc;
  86571. if( p==0 ) return WRC_Continue;
  86572. if( pWalker->xSelectCallback==0 ) return WRC_Continue;
  86573. do{
  86574. rc = pWalker->xSelectCallback(pWalker, p);
  86575. if( rc ) return rc & WRC_Abort;
  86576. if( sqlite3WalkSelectExpr(pWalker, p)
  86577. || sqlite3WalkSelectFrom(pWalker, p)
  86578. ){
  86579. return WRC_Abort;
  86580. }
  86581. if( pWalker->xSelectCallback2 ){
  86582. pWalker->xSelectCallback2(pWalker, p);
  86583. }
  86584. p = p->pPrior;
  86585. }while( p!=0 );
  86586. return WRC_Continue;
  86587. }
  86588. /************** End of walker.c **********************************************/
  86589. /************** Begin file resolve.c *****************************************/
  86590. /*
  86591. ** 2008 August 18
  86592. **
  86593. ** The author disclaims copyright to this source code. In place of
  86594. ** a legal notice, here is a blessing:
  86595. **
  86596. ** May you do good and not evil.
  86597. ** May you find forgiveness for yourself and forgive others.
  86598. ** May you share freely, never taking more than you give.
  86599. **
  86600. *************************************************************************
  86601. **
  86602. ** This file contains routines used for walking the parser tree and
  86603. ** resolve all identifiers by associating them with a particular
  86604. ** table and column.
  86605. */
  86606. /* #include "sqliteInt.h" */
  86607. /*
  86608. ** Walk the expression tree pExpr and increase the aggregate function
  86609. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  86610. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  86611. ** outer query into an inner subquery.
  86612. **
  86613. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  86614. ** is a helper function - a callback for the tree walker.
  86615. */
  86616. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  86617. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  86618. return WRC_Continue;
  86619. }
  86620. static void incrAggFunctionDepth(Expr *pExpr, int N){
  86621. if( N>0 ){
  86622. Walker w;
  86623. memset(&w, 0, sizeof(w));
  86624. w.xExprCallback = incrAggDepth;
  86625. w.u.n = N;
  86626. sqlite3WalkExpr(&w, pExpr);
  86627. }
  86628. }
  86629. /*
  86630. ** Turn the pExpr expression into an alias for the iCol-th column of the
  86631. ** result set in pEList.
  86632. **
  86633. ** If the reference is followed by a COLLATE operator, then make sure
  86634. ** the COLLATE operator is preserved. For example:
  86635. **
  86636. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  86637. **
  86638. ** Should be transformed into:
  86639. **
  86640. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  86641. **
  86642. ** The nSubquery parameter specifies how many levels of subquery the
  86643. ** alias is removed from the original expression. The usual value is
  86644. ** zero but it might be more if the alias is contained within a subquery
  86645. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  86646. ** structures must be increased by the nSubquery amount.
  86647. */
  86648. static void resolveAlias(
  86649. Parse *pParse, /* Parsing context */
  86650. ExprList *pEList, /* A result set */
  86651. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  86652. Expr *pExpr, /* Transform this into an alias to the result set */
  86653. const char *zType, /* "GROUP" or "ORDER" or "" */
  86654. int nSubquery /* Number of subqueries that the label is moving */
  86655. ){
  86656. Expr *pOrig; /* The iCol-th column of the result set */
  86657. Expr *pDup; /* Copy of pOrig */
  86658. sqlite3 *db; /* The database connection */
  86659. assert( iCol>=0 && iCol<pEList->nExpr );
  86660. pOrig = pEList->a[iCol].pExpr;
  86661. assert( pOrig!=0 );
  86662. db = pParse->db;
  86663. pDup = sqlite3ExprDup(db, pOrig, 0);
  86664. if( pDup==0 ) return;
  86665. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  86666. if( pExpr->op==TK_COLLATE ){
  86667. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  86668. }
  86669. ExprSetProperty(pDup, EP_Alias);
  86670. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  86671. ** prevents ExprDelete() from deleting the Expr structure itself,
  86672. ** allowing it to be repopulated by the memcpy() on the following line.
  86673. ** The pExpr->u.zToken might point into memory that will be freed by the
  86674. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  86675. ** make a copy of the token before doing the sqlite3DbFree().
  86676. */
  86677. ExprSetProperty(pExpr, EP_Static);
  86678. sqlite3ExprDelete(db, pExpr);
  86679. memcpy(pExpr, pDup, sizeof(*pExpr));
  86680. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  86681. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  86682. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  86683. pExpr->flags |= EP_MemToken;
  86684. }
  86685. sqlite3DbFree(db, pDup);
  86686. }
  86687. /*
  86688. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  86689. **
  86690. ** Return FALSE if the USING clause is NULL or if it does not contain
  86691. ** zCol.
  86692. */
  86693. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  86694. if( pUsing ){
  86695. int k;
  86696. for(k=0; k<pUsing->nId; k++){
  86697. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  86698. }
  86699. }
  86700. return 0;
  86701. }
  86702. /*
  86703. ** Subqueries stores the original database, table and column names for their
  86704. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  86705. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  86706. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  86707. ** match anything.
  86708. */
  86709. SQLITE_PRIVATE int sqlite3MatchSpanName(
  86710. const char *zSpan,
  86711. const char *zCol,
  86712. const char *zTab,
  86713. const char *zDb
  86714. ){
  86715. int n;
  86716. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  86717. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  86718. return 0;
  86719. }
  86720. zSpan += n+1;
  86721. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  86722. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  86723. return 0;
  86724. }
  86725. zSpan += n+1;
  86726. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  86727. return 0;
  86728. }
  86729. return 1;
  86730. }
  86731. /*
  86732. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  86733. ** that name in the set of source tables in pSrcList and make the pExpr
  86734. ** expression node refer back to that source column. The following changes
  86735. ** are made to pExpr:
  86736. **
  86737. ** pExpr->iDb Set the index in db->aDb[] of the database X
  86738. ** (even if X is implied).
  86739. ** pExpr->iTable Set to the cursor number for the table obtained
  86740. ** from pSrcList.
  86741. ** pExpr->pTab Points to the Table structure of X.Y (even if
  86742. ** X and/or Y are implied.)
  86743. ** pExpr->iColumn Set to the column number within the table.
  86744. ** pExpr->op Set to TK_COLUMN.
  86745. ** pExpr->pLeft Any expression this points to is deleted
  86746. ** pExpr->pRight Any expression this points to is deleted.
  86747. **
  86748. ** The zDb variable is the name of the database (the "X"). This value may be
  86749. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  86750. ** can be used. The zTable variable is the name of the table (the "Y"). This
  86751. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  86752. ** means that the form of the name is Z and that columns from any table
  86753. ** can be used.
  86754. **
  86755. ** If the name cannot be resolved unambiguously, leave an error message
  86756. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  86757. */
  86758. static int lookupName(
  86759. Parse *pParse, /* The parsing context */
  86760. const char *zDb, /* Name of the database containing table, or NULL */
  86761. const char *zTab, /* Name of table containing column, or NULL */
  86762. const char *zCol, /* Name of the column. */
  86763. NameContext *pNC, /* The name context used to resolve the name */
  86764. Expr *pExpr /* Make this EXPR node point to the selected column */
  86765. ){
  86766. int i, j; /* Loop counters */
  86767. int cnt = 0; /* Number of matching column names */
  86768. int cntTab = 0; /* Number of matching table names */
  86769. int nSubquery = 0; /* How many levels of subquery */
  86770. sqlite3 *db = pParse->db; /* The database connection */
  86771. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  86772. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  86773. NameContext *pTopNC = pNC; /* First namecontext in the list */
  86774. Schema *pSchema = 0; /* Schema of the expression */
  86775. int isTrigger = 0; /* True if resolved to a trigger column */
  86776. Table *pTab = 0; /* Table hold the row */
  86777. Column *pCol; /* A column of pTab */
  86778. assert( pNC ); /* the name context cannot be NULL. */
  86779. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  86780. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  86781. /* Initialize the node to no-match */
  86782. pExpr->iTable = -1;
  86783. pExpr->pTab = 0;
  86784. ExprSetVVAProperty(pExpr, EP_NoReduce);
  86785. /* Translate the schema name in zDb into a pointer to the corresponding
  86786. ** schema. If not found, pSchema will remain NULL and nothing will match
  86787. ** resulting in an appropriate error message toward the end of this routine
  86788. */
  86789. if( zDb ){
  86790. testcase( pNC->ncFlags & NC_PartIdx );
  86791. testcase( pNC->ncFlags & NC_IsCheck );
  86792. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  86793. /* Silently ignore database qualifiers inside CHECK constraints and
  86794. ** partial indices. Do not raise errors because that might break
  86795. ** legacy and because it does not hurt anything to just ignore the
  86796. ** database name. */
  86797. zDb = 0;
  86798. }else{
  86799. for(i=0; i<db->nDb; i++){
  86800. assert( db->aDb[i].zDbSName );
  86801. if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
  86802. pSchema = db->aDb[i].pSchema;
  86803. break;
  86804. }
  86805. }
  86806. }
  86807. }
  86808. /* Start at the inner-most context and move outward until a match is found */
  86809. assert( pNC && cnt==0 );
  86810. do{
  86811. ExprList *pEList;
  86812. SrcList *pSrcList = pNC->pSrcList;
  86813. if( pSrcList ){
  86814. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  86815. pTab = pItem->pTab;
  86816. assert( pTab!=0 && pTab->zName!=0 );
  86817. assert( pTab->nCol>0 );
  86818. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  86819. int hit = 0;
  86820. pEList = pItem->pSelect->pEList;
  86821. for(j=0; j<pEList->nExpr; j++){
  86822. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  86823. cnt++;
  86824. cntTab = 2;
  86825. pMatch = pItem;
  86826. pExpr->iColumn = j;
  86827. hit = 1;
  86828. }
  86829. }
  86830. if( hit || zTab==0 ) continue;
  86831. }
  86832. if( zDb && pTab->pSchema!=pSchema ){
  86833. continue;
  86834. }
  86835. if( zTab ){
  86836. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  86837. assert( zTabName!=0 );
  86838. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  86839. continue;
  86840. }
  86841. }
  86842. if( 0==(cntTab++) ){
  86843. pMatch = pItem;
  86844. }
  86845. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  86846. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  86847. /* If there has been exactly one prior match and this match
  86848. ** is for the right-hand table of a NATURAL JOIN or is in a
  86849. ** USING clause, then skip this match.
  86850. */
  86851. if( cnt==1 ){
  86852. if( pItem->fg.jointype & JT_NATURAL ) continue;
  86853. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  86854. }
  86855. cnt++;
  86856. pMatch = pItem;
  86857. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  86858. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  86859. break;
  86860. }
  86861. }
  86862. }
  86863. if( pMatch ){
  86864. pExpr->iTable = pMatch->iCursor;
  86865. pExpr->pTab = pMatch->pTab;
  86866. /* RIGHT JOIN not (yet) supported */
  86867. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  86868. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  86869. ExprSetProperty(pExpr, EP_CanBeNull);
  86870. }
  86871. pSchema = pExpr->pTab->pSchema;
  86872. }
  86873. } /* if( pSrcList ) */
  86874. #ifndef SQLITE_OMIT_TRIGGER
  86875. /* If we have not already resolved the name, then maybe
  86876. ** it is a new.* or old.* trigger argument reference
  86877. */
  86878. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  86879. int op = pParse->eTriggerOp;
  86880. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  86881. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  86882. pExpr->iTable = 1;
  86883. pTab = pParse->pTriggerTab;
  86884. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  86885. pExpr->iTable = 0;
  86886. pTab = pParse->pTriggerTab;
  86887. }else{
  86888. pTab = 0;
  86889. }
  86890. if( pTab ){
  86891. int iCol;
  86892. pSchema = pTab->pSchema;
  86893. cntTab++;
  86894. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  86895. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  86896. if( iCol==pTab->iPKey ){
  86897. iCol = -1;
  86898. }
  86899. break;
  86900. }
  86901. }
  86902. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  86903. /* IMP: R-51414-32910 */
  86904. iCol = -1;
  86905. }
  86906. if( iCol<pTab->nCol ){
  86907. cnt++;
  86908. if( iCol<0 ){
  86909. pExpr->affinity = SQLITE_AFF_INTEGER;
  86910. }else if( pExpr->iTable==0 ){
  86911. testcase( iCol==31 );
  86912. testcase( iCol==32 );
  86913. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  86914. }else{
  86915. testcase( iCol==31 );
  86916. testcase( iCol==32 );
  86917. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  86918. }
  86919. pExpr->iColumn = (i16)iCol;
  86920. pExpr->pTab = pTab;
  86921. isTrigger = 1;
  86922. }
  86923. }
  86924. }
  86925. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  86926. /*
  86927. ** Perhaps the name is a reference to the ROWID
  86928. */
  86929. if( cnt==0
  86930. && cntTab==1
  86931. && pMatch
  86932. && (pNC->ncFlags & NC_IdxExpr)==0
  86933. && sqlite3IsRowid(zCol)
  86934. && VisibleRowid(pMatch->pTab)
  86935. ){
  86936. cnt = 1;
  86937. pExpr->iColumn = -1;
  86938. pExpr->affinity = SQLITE_AFF_INTEGER;
  86939. }
  86940. /*
  86941. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  86942. ** might refer to an result-set alias. This happens, for example, when
  86943. ** we are resolving names in the WHERE clause of the following command:
  86944. **
  86945. ** SELECT a+b AS x FROM table WHERE x<10;
  86946. **
  86947. ** In cases like this, replace pExpr with a copy of the expression that
  86948. ** forms the result set entry ("a+b" in the example) and return immediately.
  86949. ** Note that the expression in the result set should have already been
  86950. ** resolved by the time the WHERE clause is resolved.
  86951. **
  86952. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  86953. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  86954. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  86955. ** is supported for backwards compatibility only. Hence, we issue a warning
  86956. ** on sqlite3_log() whenever the capability is used.
  86957. */
  86958. if( (pEList = pNC->pEList)!=0
  86959. && zTab==0
  86960. && cnt==0
  86961. ){
  86962. for(j=0; j<pEList->nExpr; j++){
  86963. char *zAs = pEList->a[j].zName;
  86964. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  86965. Expr *pOrig;
  86966. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  86967. assert( pExpr->x.pList==0 );
  86968. assert( pExpr->x.pSelect==0 );
  86969. pOrig = pEList->a[j].pExpr;
  86970. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  86971. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  86972. return WRC_Abort;
  86973. }
  86974. if( sqlite3ExprVectorSize(pOrig)!=1 ){
  86975. sqlite3ErrorMsg(pParse, "row value misused");
  86976. return WRC_Abort;
  86977. }
  86978. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  86979. cnt = 1;
  86980. pMatch = 0;
  86981. assert( zTab==0 && zDb==0 );
  86982. goto lookupname_end;
  86983. }
  86984. }
  86985. }
  86986. /* Advance to the next name context. The loop will exit when either
  86987. ** we have a match (cnt>0) or when we run out of name contexts.
  86988. */
  86989. if( cnt ) break;
  86990. pNC = pNC->pNext;
  86991. nSubquery++;
  86992. }while( pNC );
  86993. /*
  86994. ** If X and Y are NULL (in other words if only the column name Z is
  86995. ** supplied) and the value of Z is enclosed in double-quotes, then
  86996. ** Z is a string literal if it doesn't match any column names. In that
  86997. ** case, we need to return right away and not make any changes to
  86998. ** pExpr.
  86999. **
  87000. ** Because no reference was made to outer contexts, the pNC->nRef
  87001. ** fields are not changed in any context.
  87002. */
  87003. if( cnt==0 && zTab==0 ){
  87004. assert( pExpr->op==TK_ID );
  87005. if( ExprHasProperty(pExpr,EP_DblQuoted) ){
  87006. pExpr->op = TK_STRING;
  87007. pExpr->pTab = 0;
  87008. return WRC_Prune;
  87009. }
  87010. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  87011. return WRC_Prune;
  87012. }
  87013. }
  87014. /*
  87015. ** cnt==0 means there was not match. cnt>1 means there were two or
  87016. ** more matches. Either way, we have an error.
  87017. */
  87018. if( cnt!=1 ){
  87019. const char *zErr;
  87020. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  87021. if( zDb ){
  87022. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  87023. }else if( zTab ){
  87024. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  87025. }else{
  87026. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  87027. }
  87028. pParse->checkSchema = 1;
  87029. pTopNC->nErr++;
  87030. }
  87031. /* If a column from a table in pSrcList is referenced, then record
  87032. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  87033. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  87034. ** column number is greater than the number of bits in the bitmask
  87035. ** then set the high-order bit of the bitmask.
  87036. */
  87037. if( pExpr->iColumn>=0 && pMatch!=0 ){
  87038. int n = pExpr->iColumn;
  87039. testcase( n==BMS-1 );
  87040. if( n>=BMS ){
  87041. n = BMS-1;
  87042. }
  87043. assert( pMatch->iCursor==pExpr->iTable );
  87044. pMatch->colUsed |= ((Bitmask)1)<<n;
  87045. }
  87046. /* Clean up and return
  87047. */
  87048. sqlite3ExprDelete(db, pExpr->pLeft);
  87049. pExpr->pLeft = 0;
  87050. sqlite3ExprDelete(db, pExpr->pRight);
  87051. pExpr->pRight = 0;
  87052. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  87053. ExprSetProperty(pExpr, EP_Leaf);
  87054. lookupname_end:
  87055. if( cnt==1 ){
  87056. assert( pNC!=0 );
  87057. if( !ExprHasProperty(pExpr, EP_Alias) ){
  87058. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  87059. }
  87060. /* Increment the nRef value on all name contexts from TopNC up to
  87061. ** the point where the name matched. */
  87062. for(;;){
  87063. assert( pTopNC!=0 );
  87064. pTopNC->nRef++;
  87065. if( pTopNC==pNC ) break;
  87066. pTopNC = pTopNC->pNext;
  87067. }
  87068. return WRC_Prune;
  87069. } else {
  87070. return WRC_Abort;
  87071. }
  87072. }
  87073. /*
  87074. ** Allocate and return a pointer to an expression to load the column iCol
  87075. ** from datasource iSrc in SrcList pSrc.
  87076. */
  87077. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  87078. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  87079. if( p ){
  87080. struct SrcList_item *pItem = &pSrc->a[iSrc];
  87081. p->pTab = pItem->pTab;
  87082. p->iTable = pItem->iCursor;
  87083. if( p->pTab->iPKey==iCol ){
  87084. p->iColumn = -1;
  87085. }else{
  87086. p->iColumn = (ynVar)iCol;
  87087. testcase( iCol==BMS );
  87088. testcase( iCol==BMS-1 );
  87089. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  87090. }
  87091. }
  87092. return p;
  87093. }
  87094. /*
  87095. ** Report an error that an expression is not valid for some set of
  87096. ** pNC->ncFlags values determined by validMask.
  87097. */
  87098. static void notValid(
  87099. Parse *pParse, /* Leave error message here */
  87100. NameContext *pNC, /* The name context */
  87101. const char *zMsg, /* Type of error */
  87102. int validMask /* Set of contexts for which prohibited */
  87103. ){
  87104. assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
  87105. if( (pNC->ncFlags & validMask)!=0 ){
  87106. const char *zIn = "partial index WHERE clauses";
  87107. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  87108. #ifndef SQLITE_OMIT_CHECK
  87109. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  87110. #endif
  87111. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  87112. }
  87113. }
  87114. /*
  87115. ** Expression p should encode a floating point value between 1.0 and 0.0.
  87116. ** Return 1024 times this value. Or return -1 if p is not a floating point
  87117. ** value between 1.0 and 0.0.
  87118. */
  87119. static int exprProbability(Expr *p){
  87120. double r = -1.0;
  87121. if( p->op!=TK_FLOAT ) return -1;
  87122. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  87123. assert( r>=0.0 );
  87124. if( r>1.0 ) return -1;
  87125. return (int)(r*134217728.0);
  87126. }
  87127. /*
  87128. ** This routine is callback for sqlite3WalkExpr().
  87129. **
  87130. ** Resolve symbolic names into TK_COLUMN operators for the current
  87131. ** node in the expression tree. Return 0 to continue the search down
  87132. ** the tree or 2 to abort the tree walk.
  87133. **
  87134. ** This routine also does error checking and name resolution for
  87135. ** function names. The operator for aggregate functions is changed
  87136. ** to TK_AGG_FUNCTION.
  87137. */
  87138. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  87139. NameContext *pNC;
  87140. Parse *pParse;
  87141. pNC = pWalker->u.pNC;
  87142. assert( pNC!=0 );
  87143. pParse = pNC->pParse;
  87144. assert( pParse==pWalker->pParse );
  87145. #ifndef NDEBUG
  87146. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  87147. SrcList *pSrcList = pNC->pSrcList;
  87148. int i;
  87149. for(i=0; i<pNC->pSrcList->nSrc; i++){
  87150. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  87151. }
  87152. }
  87153. #endif
  87154. switch( pExpr->op ){
  87155. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  87156. /* The special operator TK_ROW means use the rowid for the first
  87157. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  87158. ** clause processing on UPDATE and DELETE statements.
  87159. */
  87160. case TK_ROW: {
  87161. SrcList *pSrcList = pNC->pSrcList;
  87162. struct SrcList_item *pItem;
  87163. assert( pSrcList && pSrcList->nSrc==1 );
  87164. pItem = pSrcList->a;
  87165. assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
  87166. pExpr->op = TK_COLUMN;
  87167. pExpr->pTab = pItem->pTab;
  87168. pExpr->iTable = pItem->iCursor;
  87169. pExpr->iColumn = -1;
  87170. pExpr->affinity = SQLITE_AFF_INTEGER;
  87171. break;
  87172. }
  87173. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  87174. && !defined(SQLITE_OMIT_SUBQUERY) */
  87175. /* A column name: ID
  87176. ** Or table name and column name: ID.ID
  87177. ** Or a database, table and column: ID.ID.ID
  87178. **
  87179. ** The TK_ID and TK_OUT cases are combined so that there will only
  87180. ** be one call to lookupName(). Then the compiler will in-line
  87181. ** lookupName() for a size reduction and performance increase.
  87182. */
  87183. case TK_ID:
  87184. case TK_DOT: {
  87185. const char *zColumn;
  87186. const char *zTable;
  87187. const char *zDb;
  87188. Expr *pRight;
  87189. if( pExpr->op==TK_ID ){
  87190. zDb = 0;
  87191. zTable = 0;
  87192. zColumn = pExpr->u.zToken;
  87193. }else{
  87194. notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
  87195. pRight = pExpr->pRight;
  87196. if( pRight->op==TK_ID ){
  87197. zDb = 0;
  87198. zTable = pExpr->pLeft->u.zToken;
  87199. zColumn = pRight->u.zToken;
  87200. }else{
  87201. assert( pRight->op==TK_DOT );
  87202. zDb = pExpr->pLeft->u.zToken;
  87203. zTable = pRight->pLeft->u.zToken;
  87204. zColumn = pRight->pRight->u.zToken;
  87205. }
  87206. }
  87207. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  87208. }
  87209. /* Resolve function names
  87210. */
  87211. case TK_FUNCTION: {
  87212. ExprList *pList = pExpr->x.pList; /* The argument list */
  87213. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  87214. int no_such_func = 0; /* True if no such function exists */
  87215. int wrong_num_args = 0; /* True if wrong number of arguments */
  87216. int is_agg = 0; /* True if is an aggregate function */
  87217. int nId; /* Number of characters in function name */
  87218. const char *zId; /* The function name. */
  87219. FuncDef *pDef; /* Information about the function */
  87220. u8 enc = ENC(pParse->db); /* The database encoding */
  87221. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  87222. zId = pExpr->u.zToken;
  87223. nId = sqlite3Strlen30(zId);
  87224. pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
  87225. if( pDef==0 ){
  87226. pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
  87227. if( pDef==0 ){
  87228. no_such_func = 1;
  87229. }else{
  87230. wrong_num_args = 1;
  87231. }
  87232. }else{
  87233. is_agg = pDef->xFinalize!=0;
  87234. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  87235. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  87236. if( n==2 ){
  87237. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  87238. if( pExpr->iTable<0 ){
  87239. sqlite3ErrorMsg(pParse,
  87240. "second argument to likelihood() must be a "
  87241. "constant between 0.0 and 1.0");
  87242. pNC->nErr++;
  87243. }
  87244. }else{
  87245. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  87246. ** equivalent to likelihood(X, 0.0625).
  87247. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  87248. ** short-hand for likelihood(X,0.0625).
  87249. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  87250. ** for likelihood(X,0.9375).
  87251. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  87252. ** to likelihood(X,0.9375). */
  87253. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  87254. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  87255. }
  87256. }
  87257. #ifndef SQLITE_OMIT_AUTHORIZATION
  87258. {
  87259. int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
  87260. if( auth!=SQLITE_OK ){
  87261. if( auth==SQLITE_DENY ){
  87262. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  87263. pDef->zName);
  87264. pNC->nErr++;
  87265. }
  87266. pExpr->op = TK_NULL;
  87267. return WRC_Prune;
  87268. }
  87269. }
  87270. #endif
  87271. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  87272. /* For the purposes of the EP_ConstFunc flag, date and time
  87273. ** functions and other functions that change slowly are considered
  87274. ** constant because they are constant for the duration of one query */
  87275. ExprSetProperty(pExpr,EP_ConstFunc);
  87276. }
  87277. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  87278. /* Date/time functions that use 'now', and other functions like
  87279. ** sqlite_version() that might change over time cannot be used
  87280. ** in an index. */
  87281. notValid(pParse, pNC, "non-deterministic functions",
  87282. NC_IdxExpr|NC_PartIdx);
  87283. }
  87284. }
  87285. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  87286. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  87287. pNC->nErr++;
  87288. is_agg = 0;
  87289. }else if( no_such_func && pParse->db->init.busy==0
  87290. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  87291. && pParse->explain==0
  87292. #endif
  87293. ){
  87294. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  87295. pNC->nErr++;
  87296. }else if( wrong_num_args ){
  87297. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  87298. nId, zId);
  87299. pNC->nErr++;
  87300. }
  87301. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  87302. sqlite3WalkExprList(pWalker, pList);
  87303. if( is_agg ){
  87304. NameContext *pNC2 = pNC;
  87305. pExpr->op = TK_AGG_FUNCTION;
  87306. pExpr->op2 = 0;
  87307. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  87308. pExpr->op2++;
  87309. pNC2 = pNC2->pNext;
  87310. }
  87311. assert( pDef!=0 );
  87312. if( pNC2 ){
  87313. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  87314. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  87315. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  87316. }
  87317. pNC->ncFlags |= NC_AllowAgg;
  87318. }
  87319. /* FIX ME: Compute pExpr->affinity based on the expected return
  87320. ** type of the function
  87321. */
  87322. return WRC_Prune;
  87323. }
  87324. #ifndef SQLITE_OMIT_SUBQUERY
  87325. case TK_SELECT:
  87326. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  87327. #endif
  87328. case TK_IN: {
  87329. testcase( pExpr->op==TK_IN );
  87330. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  87331. int nRef = pNC->nRef;
  87332. notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  87333. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  87334. assert( pNC->nRef>=nRef );
  87335. if( nRef!=pNC->nRef ){
  87336. ExprSetProperty(pExpr, EP_VarSelect);
  87337. pNC->ncFlags |= NC_VarSelect;
  87338. }
  87339. }
  87340. break;
  87341. }
  87342. case TK_VARIABLE: {
  87343. notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
  87344. break;
  87345. }
  87346. case TK_IS:
  87347. case TK_ISNOT: {
  87348. Expr *pRight;
  87349. assert( !ExprHasProperty(pExpr, EP_Reduced) );
  87350. /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
  87351. ** and "x IS NOT FALSE". */
  87352. if( (pRight = pExpr->pRight)->op==TK_ID ){
  87353. int rc = resolveExprStep(pWalker, pRight);
  87354. if( rc==WRC_Abort ) return WRC_Abort;
  87355. if( pRight->op==TK_TRUEFALSE ){
  87356. pExpr->op2 = pExpr->op;
  87357. pExpr->op = TK_TRUTH;
  87358. return WRC_Continue;
  87359. }
  87360. }
  87361. /* Fall thru */
  87362. }
  87363. case TK_BETWEEN:
  87364. case TK_EQ:
  87365. case TK_NE:
  87366. case TK_LT:
  87367. case TK_LE:
  87368. case TK_GT:
  87369. case TK_GE: {
  87370. int nLeft, nRight;
  87371. if( pParse->db->mallocFailed ) break;
  87372. assert( pExpr->pLeft!=0 );
  87373. nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
  87374. if( pExpr->op==TK_BETWEEN ){
  87375. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
  87376. if( nRight==nLeft ){
  87377. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
  87378. }
  87379. }else{
  87380. assert( pExpr->pRight!=0 );
  87381. nRight = sqlite3ExprVectorSize(pExpr->pRight);
  87382. }
  87383. if( nLeft!=nRight ){
  87384. testcase( pExpr->op==TK_EQ );
  87385. testcase( pExpr->op==TK_NE );
  87386. testcase( pExpr->op==TK_LT );
  87387. testcase( pExpr->op==TK_LE );
  87388. testcase( pExpr->op==TK_GT );
  87389. testcase( pExpr->op==TK_GE );
  87390. testcase( pExpr->op==TK_IS );
  87391. testcase( pExpr->op==TK_ISNOT );
  87392. testcase( pExpr->op==TK_BETWEEN );
  87393. sqlite3ErrorMsg(pParse, "row value misused");
  87394. }
  87395. break;
  87396. }
  87397. }
  87398. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  87399. }
  87400. /*
  87401. ** pEList is a list of expressions which are really the result set of the
  87402. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  87403. ** This routine checks to see if pE is a simple identifier which corresponds
  87404. ** to the AS-name of one of the terms of the expression list. If it is,
  87405. ** this routine return an integer between 1 and N where N is the number of
  87406. ** elements in pEList, corresponding to the matching entry. If there is
  87407. ** no match, or if pE is not a simple identifier, then this routine
  87408. ** return 0.
  87409. **
  87410. ** pEList has been resolved. pE has not.
  87411. */
  87412. static int resolveAsName(
  87413. Parse *pParse, /* Parsing context for error messages */
  87414. ExprList *pEList, /* List of expressions to scan */
  87415. Expr *pE /* Expression we are trying to match */
  87416. ){
  87417. int i; /* Loop counter */
  87418. UNUSED_PARAMETER(pParse);
  87419. if( pE->op==TK_ID ){
  87420. char *zCol = pE->u.zToken;
  87421. for(i=0; i<pEList->nExpr; i++){
  87422. char *zAs = pEList->a[i].zName;
  87423. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  87424. return i+1;
  87425. }
  87426. }
  87427. }
  87428. return 0;
  87429. }
  87430. /*
  87431. ** pE is a pointer to an expression which is a single term in the
  87432. ** ORDER BY of a compound SELECT. The expression has not been
  87433. ** name resolved.
  87434. **
  87435. ** At the point this routine is called, we already know that the
  87436. ** ORDER BY term is not an integer index into the result set. That
  87437. ** case is handled by the calling routine.
  87438. **
  87439. ** Attempt to match pE against result set columns in the left-most
  87440. ** SELECT statement. Return the index i of the matching column,
  87441. ** as an indication to the caller that it should sort by the i-th column.
  87442. ** The left-most column is 1. In other words, the value returned is the
  87443. ** same integer value that would be used in the SQL statement to indicate
  87444. ** the column.
  87445. **
  87446. ** If there is no match, return 0. Return -1 if an error occurs.
  87447. */
  87448. static int resolveOrderByTermToExprList(
  87449. Parse *pParse, /* Parsing context for error messages */
  87450. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  87451. Expr *pE /* The specific ORDER BY term */
  87452. ){
  87453. int i; /* Loop counter */
  87454. ExprList *pEList; /* The columns of the result set */
  87455. NameContext nc; /* Name context for resolving pE */
  87456. sqlite3 *db; /* Database connection */
  87457. int rc; /* Return code from subprocedures */
  87458. u8 savedSuppErr; /* Saved value of db->suppressErr */
  87459. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  87460. pEList = pSelect->pEList;
  87461. /* Resolve all names in the ORDER BY term expression
  87462. */
  87463. memset(&nc, 0, sizeof(nc));
  87464. nc.pParse = pParse;
  87465. nc.pSrcList = pSelect->pSrc;
  87466. nc.pEList = pEList;
  87467. nc.ncFlags = NC_AllowAgg;
  87468. nc.nErr = 0;
  87469. db = pParse->db;
  87470. savedSuppErr = db->suppressErr;
  87471. db->suppressErr = 1;
  87472. rc = sqlite3ResolveExprNames(&nc, pE);
  87473. db->suppressErr = savedSuppErr;
  87474. if( rc ) return 0;
  87475. /* Try to match the ORDER BY expression against an expression
  87476. ** in the result set. Return an 1-based index of the matching
  87477. ** result-set entry.
  87478. */
  87479. for(i=0; i<pEList->nExpr; i++){
  87480. if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
  87481. return i+1;
  87482. }
  87483. }
  87484. /* If no match, return 0. */
  87485. return 0;
  87486. }
  87487. /*
  87488. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  87489. */
  87490. static void resolveOutOfRangeError(
  87491. Parse *pParse, /* The error context into which to write the error */
  87492. const char *zType, /* "ORDER" or "GROUP" */
  87493. int i, /* The index (1-based) of the term out of range */
  87494. int mx /* Largest permissible value of i */
  87495. ){
  87496. sqlite3ErrorMsg(pParse,
  87497. "%r %s BY term out of range - should be "
  87498. "between 1 and %d", i, zType, mx);
  87499. }
  87500. /*
  87501. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  87502. ** each term of the ORDER BY clause is a constant integer between 1
  87503. ** and N where N is the number of columns in the compound SELECT.
  87504. **
  87505. ** ORDER BY terms that are already an integer between 1 and N are
  87506. ** unmodified. ORDER BY terms that are integers outside the range of
  87507. ** 1 through N generate an error. ORDER BY terms that are expressions
  87508. ** are matched against result set expressions of compound SELECT
  87509. ** beginning with the left-most SELECT and working toward the right.
  87510. ** At the first match, the ORDER BY expression is transformed into
  87511. ** the integer column number.
  87512. **
  87513. ** Return the number of errors seen.
  87514. */
  87515. static int resolveCompoundOrderBy(
  87516. Parse *pParse, /* Parsing context. Leave error messages here */
  87517. Select *pSelect /* The SELECT statement containing the ORDER BY */
  87518. ){
  87519. int i;
  87520. ExprList *pOrderBy;
  87521. ExprList *pEList;
  87522. sqlite3 *db;
  87523. int moreToDo = 1;
  87524. pOrderBy = pSelect->pOrderBy;
  87525. if( pOrderBy==0 ) return 0;
  87526. db = pParse->db;
  87527. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  87528. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  87529. return 1;
  87530. }
  87531. for(i=0; i<pOrderBy->nExpr; i++){
  87532. pOrderBy->a[i].done = 0;
  87533. }
  87534. pSelect->pNext = 0;
  87535. while( pSelect->pPrior ){
  87536. pSelect->pPrior->pNext = pSelect;
  87537. pSelect = pSelect->pPrior;
  87538. }
  87539. while( pSelect && moreToDo ){
  87540. struct ExprList_item *pItem;
  87541. moreToDo = 0;
  87542. pEList = pSelect->pEList;
  87543. assert( pEList!=0 );
  87544. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  87545. int iCol = -1;
  87546. Expr *pE, *pDup;
  87547. if( pItem->done ) continue;
  87548. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  87549. if( sqlite3ExprIsInteger(pE, &iCol) ){
  87550. if( iCol<=0 || iCol>pEList->nExpr ){
  87551. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  87552. return 1;
  87553. }
  87554. }else{
  87555. iCol = resolveAsName(pParse, pEList, pE);
  87556. if( iCol==0 ){
  87557. pDup = sqlite3ExprDup(db, pE, 0);
  87558. if( !db->mallocFailed ){
  87559. assert(pDup);
  87560. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  87561. }
  87562. sqlite3ExprDelete(db, pDup);
  87563. }
  87564. }
  87565. if( iCol>0 ){
  87566. /* Convert the ORDER BY term into an integer column number iCol,
  87567. ** taking care to preserve the COLLATE clause if it exists */
  87568. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  87569. if( pNew==0 ) return 1;
  87570. pNew->flags |= EP_IntValue;
  87571. pNew->u.iValue = iCol;
  87572. if( pItem->pExpr==pE ){
  87573. pItem->pExpr = pNew;
  87574. }else{
  87575. Expr *pParent = pItem->pExpr;
  87576. assert( pParent->op==TK_COLLATE );
  87577. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  87578. assert( pParent->pLeft==pE );
  87579. pParent->pLeft = pNew;
  87580. }
  87581. sqlite3ExprDelete(db, pE);
  87582. pItem->u.x.iOrderByCol = (u16)iCol;
  87583. pItem->done = 1;
  87584. }else{
  87585. moreToDo = 1;
  87586. }
  87587. }
  87588. pSelect = pSelect->pNext;
  87589. }
  87590. for(i=0; i<pOrderBy->nExpr; i++){
  87591. if( pOrderBy->a[i].done==0 ){
  87592. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  87593. "column in the result set", i+1);
  87594. return 1;
  87595. }
  87596. }
  87597. return 0;
  87598. }
  87599. /*
  87600. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  87601. ** the SELECT statement pSelect. If any term is reference to a
  87602. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  87603. ** field) then convert that term into a copy of the corresponding result set
  87604. ** column.
  87605. **
  87606. ** If any errors are detected, add an error message to pParse and
  87607. ** return non-zero. Return zero if no errors are seen.
  87608. */
  87609. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  87610. Parse *pParse, /* Parsing context. Leave error messages here */
  87611. Select *pSelect, /* The SELECT statement containing the clause */
  87612. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  87613. const char *zType /* "ORDER" or "GROUP" */
  87614. ){
  87615. int i;
  87616. sqlite3 *db = pParse->db;
  87617. ExprList *pEList;
  87618. struct ExprList_item *pItem;
  87619. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  87620. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  87621. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  87622. return 1;
  87623. }
  87624. pEList = pSelect->pEList;
  87625. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  87626. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  87627. if( pItem->u.x.iOrderByCol ){
  87628. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  87629. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  87630. return 1;
  87631. }
  87632. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  87633. zType,0);
  87634. }
  87635. }
  87636. return 0;
  87637. }
  87638. /*
  87639. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  87640. ** The Name context of the SELECT statement is pNC. zType is either
  87641. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  87642. **
  87643. ** This routine resolves each term of the clause into an expression.
  87644. ** If the order-by term is an integer I between 1 and N (where N is the
  87645. ** number of columns in the result set of the SELECT) then the expression
  87646. ** in the resolution is a copy of the I-th result-set expression. If
  87647. ** the order-by term is an identifier that corresponds to the AS-name of
  87648. ** a result-set expression, then the term resolves to a copy of the
  87649. ** result-set expression. Otherwise, the expression is resolved in
  87650. ** the usual way - using sqlite3ResolveExprNames().
  87651. **
  87652. ** This routine returns the number of errors. If errors occur, then
  87653. ** an appropriate error message might be left in pParse. (OOM errors
  87654. ** excepted.)
  87655. */
  87656. static int resolveOrderGroupBy(
  87657. NameContext *pNC, /* The name context of the SELECT statement */
  87658. Select *pSelect, /* The SELECT statement holding pOrderBy */
  87659. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  87660. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  87661. ){
  87662. int i, j; /* Loop counters */
  87663. int iCol; /* Column number */
  87664. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  87665. Parse *pParse; /* Parsing context */
  87666. int nResult; /* Number of terms in the result set */
  87667. if( pOrderBy==0 ) return 0;
  87668. nResult = pSelect->pEList->nExpr;
  87669. pParse = pNC->pParse;
  87670. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  87671. Expr *pE = pItem->pExpr;
  87672. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  87673. if( zType[0]!='G' ){
  87674. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  87675. if( iCol>0 ){
  87676. /* If an AS-name match is found, mark this ORDER BY column as being
  87677. ** a copy of the iCol-th result-set column. The subsequent call to
  87678. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  87679. ** copy of the iCol-th result-set expression. */
  87680. pItem->u.x.iOrderByCol = (u16)iCol;
  87681. continue;
  87682. }
  87683. }
  87684. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  87685. /* The ORDER BY term is an integer constant. Again, set the column
  87686. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  87687. ** order-by term to a copy of the result-set expression */
  87688. if( iCol<1 || iCol>0xffff ){
  87689. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  87690. return 1;
  87691. }
  87692. pItem->u.x.iOrderByCol = (u16)iCol;
  87693. continue;
  87694. }
  87695. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  87696. pItem->u.x.iOrderByCol = 0;
  87697. if( sqlite3ResolveExprNames(pNC, pE) ){
  87698. return 1;
  87699. }
  87700. for(j=0; j<pSelect->pEList->nExpr; j++){
  87701. if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  87702. pItem->u.x.iOrderByCol = j+1;
  87703. }
  87704. }
  87705. }
  87706. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  87707. }
  87708. /*
  87709. ** Resolve names in the SELECT statement p and all of its descendants.
  87710. */
  87711. static int resolveSelectStep(Walker *pWalker, Select *p){
  87712. NameContext *pOuterNC; /* Context that contains this SELECT */
  87713. NameContext sNC; /* Name context of this SELECT */
  87714. int isCompound; /* True if p is a compound select */
  87715. int nCompound; /* Number of compound terms processed so far */
  87716. Parse *pParse; /* Parsing context */
  87717. int i; /* Loop counter */
  87718. ExprList *pGroupBy; /* The GROUP BY clause */
  87719. Select *pLeftmost; /* Left-most of SELECT of a compound */
  87720. sqlite3 *db; /* Database connection */
  87721. assert( p!=0 );
  87722. if( p->selFlags & SF_Resolved ){
  87723. return WRC_Prune;
  87724. }
  87725. pOuterNC = pWalker->u.pNC;
  87726. pParse = pWalker->pParse;
  87727. db = pParse->db;
  87728. /* Normally sqlite3SelectExpand() will be called first and will have
  87729. ** already expanded this SELECT. However, if this is a subquery within
  87730. ** an expression, sqlite3ResolveExprNames() will be called without a
  87731. ** prior call to sqlite3SelectExpand(). When that happens, let
  87732. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  87733. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  87734. ** this routine in the correct order.
  87735. */
  87736. if( (p->selFlags & SF_Expanded)==0 ){
  87737. sqlite3SelectPrep(pParse, p, pOuterNC);
  87738. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  87739. }
  87740. isCompound = p->pPrior!=0;
  87741. nCompound = 0;
  87742. pLeftmost = p;
  87743. while( p ){
  87744. assert( (p->selFlags & SF_Expanded)!=0 );
  87745. assert( (p->selFlags & SF_Resolved)==0 );
  87746. p->selFlags |= SF_Resolved;
  87747. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  87748. ** are not allowed to refer to any names, so pass an empty NameContext.
  87749. */
  87750. memset(&sNC, 0, sizeof(sNC));
  87751. sNC.pParse = pParse;
  87752. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
  87753. return WRC_Abort;
  87754. }
  87755. /* If the SF_Converted flags is set, then this Select object was
  87756. ** was created by the convertCompoundSelectToSubquery() function.
  87757. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  87758. ** as if it were part of the sub-query, not the parent. This block
  87759. ** moves the pOrderBy down to the sub-query. It will be moved back
  87760. ** after the names have been resolved. */
  87761. if( p->selFlags & SF_Converted ){
  87762. Select *pSub = p->pSrc->a[0].pSelect;
  87763. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  87764. assert( pSub->pPrior && pSub->pOrderBy==0 );
  87765. pSub->pOrderBy = p->pOrderBy;
  87766. p->pOrderBy = 0;
  87767. }
  87768. /* Recursively resolve names in all subqueries
  87769. */
  87770. for(i=0; i<p->pSrc->nSrc; i++){
  87771. struct SrcList_item *pItem = &p->pSrc->a[i];
  87772. if( pItem->pSelect ){
  87773. NameContext *pNC; /* Used to iterate name contexts */
  87774. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  87775. const char *zSavedContext = pParse->zAuthContext;
  87776. /* Count the total number of references to pOuterNC and all of its
  87777. ** parent contexts. After resolving references to expressions in
  87778. ** pItem->pSelect, check if this value has changed. If so, then
  87779. ** SELECT statement pItem->pSelect must be correlated. Set the
  87780. ** pItem->fg.isCorrelated flag if this is the case. */
  87781. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  87782. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  87783. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  87784. pParse->zAuthContext = zSavedContext;
  87785. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  87786. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  87787. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  87788. pItem->fg.isCorrelated = (nRef!=0);
  87789. }
  87790. }
  87791. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  87792. ** resolve the result-set expression list.
  87793. */
  87794. sNC.ncFlags = NC_AllowAgg;
  87795. sNC.pSrcList = p->pSrc;
  87796. sNC.pNext = pOuterNC;
  87797. /* Resolve names in the result set. */
  87798. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  87799. /* If there are no aggregate functions in the result-set, and no GROUP BY
  87800. ** expression, do not allow aggregates in any of the other expressions.
  87801. */
  87802. assert( (p->selFlags & SF_Aggregate)==0 );
  87803. pGroupBy = p->pGroupBy;
  87804. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  87805. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  87806. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  87807. }else{
  87808. sNC.ncFlags &= ~NC_AllowAgg;
  87809. }
  87810. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  87811. */
  87812. if( p->pHaving && !pGroupBy ){
  87813. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  87814. return WRC_Abort;
  87815. }
  87816. /* Add the output column list to the name-context before parsing the
  87817. ** other expressions in the SELECT statement. This is so that
  87818. ** expressions in the WHERE clause (etc.) can refer to expressions by
  87819. ** aliases in the result set.
  87820. **
  87821. ** Minor point: If this is the case, then the expression will be
  87822. ** re-evaluated for each reference to it.
  87823. */
  87824. sNC.pEList = p->pEList;
  87825. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  87826. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  87827. /* Resolve names in table-valued-function arguments */
  87828. for(i=0; i<p->pSrc->nSrc; i++){
  87829. struct SrcList_item *pItem = &p->pSrc->a[i];
  87830. if( pItem->fg.isTabFunc
  87831. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  87832. ){
  87833. return WRC_Abort;
  87834. }
  87835. }
  87836. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  87837. ** outer queries
  87838. */
  87839. sNC.pNext = 0;
  87840. sNC.ncFlags |= NC_AllowAgg;
  87841. /* If this is a converted compound query, move the ORDER BY clause from
  87842. ** the sub-query back to the parent query. At this point each term
  87843. ** within the ORDER BY clause has been transformed to an integer value.
  87844. ** These integers will be replaced by copies of the corresponding result
  87845. ** set expressions by the call to resolveOrderGroupBy() below. */
  87846. if( p->selFlags & SF_Converted ){
  87847. Select *pSub = p->pSrc->a[0].pSelect;
  87848. p->pOrderBy = pSub->pOrderBy;
  87849. pSub->pOrderBy = 0;
  87850. }
  87851. /* Process the ORDER BY clause for singleton SELECT statements.
  87852. ** The ORDER BY clause for compounds SELECT statements is handled
  87853. ** below, after all of the result-sets for all of the elements of
  87854. ** the compound have been resolved.
  87855. **
  87856. ** If there is an ORDER BY clause on a term of a compound-select other
  87857. ** than the right-most term, then that is a syntax error. But the error
  87858. ** is not detected until much later, and so we need to go ahead and
  87859. ** resolve those symbols on the incorrect ORDER BY for consistency.
  87860. */
  87861. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  87862. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  87863. ){
  87864. return WRC_Abort;
  87865. }
  87866. if( db->mallocFailed ){
  87867. return WRC_Abort;
  87868. }
  87869. /* Resolve the GROUP BY clause. At the same time, make sure
  87870. ** the GROUP BY clause does not contain aggregate functions.
  87871. */
  87872. if( pGroupBy ){
  87873. struct ExprList_item *pItem;
  87874. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  87875. return WRC_Abort;
  87876. }
  87877. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  87878. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  87879. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  87880. "the GROUP BY clause");
  87881. return WRC_Abort;
  87882. }
  87883. }
  87884. }
  87885. /* If this is part of a compound SELECT, check that it has the right
  87886. ** number of expressions in the select list. */
  87887. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  87888. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  87889. return WRC_Abort;
  87890. }
  87891. /* Advance to the next term of the compound
  87892. */
  87893. p = p->pPrior;
  87894. nCompound++;
  87895. }
  87896. /* Resolve the ORDER BY on a compound SELECT after all terms of
  87897. ** the compound have been resolved.
  87898. */
  87899. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  87900. return WRC_Abort;
  87901. }
  87902. return WRC_Prune;
  87903. }
  87904. /*
  87905. ** This routine walks an expression tree and resolves references to
  87906. ** table columns and result-set columns. At the same time, do error
  87907. ** checking on function usage and set a flag if any aggregate functions
  87908. ** are seen.
  87909. **
  87910. ** To resolve table columns references we look for nodes (or subtrees) of the
  87911. ** form X.Y.Z or Y.Z or just Z where
  87912. **
  87913. ** X: The name of a database. Ex: "main" or "temp" or
  87914. ** the symbolic name assigned to an ATTACH-ed database.
  87915. **
  87916. ** Y: The name of a table in a FROM clause. Or in a trigger
  87917. ** one of the special names "old" or "new".
  87918. **
  87919. ** Z: The name of a column in table Y.
  87920. **
  87921. ** The node at the root of the subtree is modified as follows:
  87922. **
  87923. ** Expr.op Changed to TK_COLUMN
  87924. ** Expr.pTab Points to the Table object for X.Y
  87925. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  87926. ** Expr.iTable The VDBE cursor number for X.Y
  87927. **
  87928. **
  87929. ** To resolve result-set references, look for expression nodes of the
  87930. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  87931. ** size of an AS clause in the result-set of a SELECT. The Z expression
  87932. ** is replaced by a copy of the left-hand side of the result-set expression.
  87933. ** Table-name and function resolution occurs on the substituted expression
  87934. ** tree. For example, in:
  87935. **
  87936. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  87937. **
  87938. ** The "x" term of the order by is replaced by "a+b" to render:
  87939. **
  87940. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  87941. **
  87942. ** Function calls are checked to make sure that the function is
  87943. ** defined and that the correct number of arguments are specified.
  87944. ** If the function is an aggregate function, then the NC_HasAgg flag is
  87945. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  87946. ** If an expression contains aggregate functions then the EP_Agg
  87947. ** property on the expression is set.
  87948. **
  87949. ** An error message is left in pParse if anything is amiss. The number
  87950. ** if errors is returned.
  87951. */
  87952. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  87953. NameContext *pNC, /* Namespace to resolve expressions in. */
  87954. Expr *pExpr /* The expression to be analyzed. */
  87955. ){
  87956. u16 savedHasAgg;
  87957. Walker w;
  87958. if( pExpr==0 ) return SQLITE_OK;
  87959. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  87960. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  87961. w.pParse = pNC->pParse;
  87962. w.xExprCallback = resolveExprStep;
  87963. w.xSelectCallback = resolveSelectStep;
  87964. w.xSelectCallback2 = 0;
  87965. w.u.pNC = pNC;
  87966. #if SQLITE_MAX_EXPR_DEPTH>0
  87967. w.pParse->nHeight += pExpr->nHeight;
  87968. if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
  87969. return SQLITE_ERROR;
  87970. }
  87971. #endif
  87972. sqlite3WalkExpr(&w, pExpr);
  87973. #if SQLITE_MAX_EXPR_DEPTH>0
  87974. w.pParse->nHeight -= pExpr->nHeight;
  87975. #endif
  87976. if( pNC->ncFlags & NC_HasAgg ){
  87977. ExprSetProperty(pExpr, EP_Agg);
  87978. }
  87979. pNC->ncFlags |= savedHasAgg;
  87980. return pNC->nErr>0 || w.pParse->nErr>0;
  87981. }
  87982. /*
  87983. ** Resolve all names for all expression in an expression list. This is
  87984. ** just like sqlite3ResolveExprNames() except that it works for an expression
  87985. ** list rather than a single expression.
  87986. */
  87987. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  87988. NameContext *pNC, /* Namespace to resolve expressions in. */
  87989. ExprList *pList /* The expression list to be analyzed. */
  87990. ){
  87991. int i;
  87992. if( pList ){
  87993. for(i=0; i<pList->nExpr; i++){
  87994. if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
  87995. }
  87996. }
  87997. return WRC_Continue;
  87998. }
  87999. /*
  88000. ** Resolve all names in all expressions of a SELECT and in all
  88001. ** decendents of the SELECT, including compounds off of p->pPrior,
  88002. ** subqueries in expressions, and subqueries used as FROM clause
  88003. ** terms.
  88004. **
  88005. ** See sqlite3ResolveExprNames() for a description of the kinds of
  88006. ** transformations that occur.
  88007. **
  88008. ** All SELECT statements should have been expanded using
  88009. ** sqlite3SelectExpand() prior to invoking this routine.
  88010. */
  88011. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  88012. Parse *pParse, /* The parser context */
  88013. Select *p, /* The SELECT statement being coded. */
  88014. NameContext *pOuterNC /* Name context for parent SELECT statement */
  88015. ){
  88016. Walker w;
  88017. assert( p!=0 );
  88018. w.xExprCallback = resolveExprStep;
  88019. w.xSelectCallback = resolveSelectStep;
  88020. w.xSelectCallback2 = 0;
  88021. w.pParse = pParse;
  88022. w.u.pNC = pOuterNC;
  88023. sqlite3WalkSelect(&w, p);
  88024. }
  88025. /*
  88026. ** Resolve names in expressions that can only reference a single table:
  88027. **
  88028. ** * CHECK constraints
  88029. ** * WHERE clauses on partial indices
  88030. **
  88031. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  88032. ** is set to -1 and the Expr.iColumn value is set to the column number.
  88033. **
  88034. ** Any errors cause an error message to be set in pParse.
  88035. */
  88036. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  88037. Parse *pParse, /* Parsing context */
  88038. Table *pTab, /* The table being referenced */
  88039. int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
  88040. Expr *pExpr, /* Expression to resolve. May be NULL. */
  88041. ExprList *pList /* Expression list to resolve. May be NUL. */
  88042. ){
  88043. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  88044. NameContext sNC; /* Name context for pParse->pNewTable */
  88045. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
  88046. memset(&sNC, 0, sizeof(sNC));
  88047. memset(&sSrc, 0, sizeof(sSrc));
  88048. sSrc.nSrc = 1;
  88049. sSrc.a[0].zName = pTab->zName;
  88050. sSrc.a[0].pTab = pTab;
  88051. sSrc.a[0].iCursor = -1;
  88052. sNC.pParse = pParse;
  88053. sNC.pSrcList = &sSrc;
  88054. sNC.ncFlags = type;
  88055. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  88056. if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
  88057. }
  88058. /************** End of resolve.c *********************************************/
  88059. /************** Begin file expr.c ********************************************/
  88060. /*
  88061. ** 2001 September 15
  88062. **
  88063. ** The author disclaims copyright to this source code. In place of
  88064. ** a legal notice, here is a blessing:
  88065. **
  88066. ** May you do good and not evil.
  88067. ** May you find forgiveness for yourself and forgive others.
  88068. ** May you share freely, never taking more than you give.
  88069. **
  88070. *************************************************************************
  88071. ** This file contains routines used for analyzing expressions and
  88072. ** for generating VDBE code that evaluates expressions in SQLite.
  88073. */
  88074. /* #include "sqliteInt.h" */
  88075. /* Forward declarations */
  88076. static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
  88077. static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
  88078. /*
  88079. ** Return the affinity character for a single column of a table.
  88080. */
  88081. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
  88082. assert( iCol<pTab->nCol );
  88083. return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  88084. }
  88085. /*
  88086. ** Return the 'affinity' of the expression pExpr if any.
  88087. **
  88088. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  88089. ** or a sub-select with a column as the return value, then the
  88090. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  88091. ** indicating no affinity for the expression.
  88092. **
  88093. ** i.e. the WHERE clause expressions in the following statements all
  88094. ** have an affinity:
  88095. **
  88096. ** CREATE TABLE t1(a);
  88097. ** SELECT * FROM t1 WHERE a;
  88098. ** SELECT a AS b FROM t1 WHERE b;
  88099. ** SELECT * FROM t1 WHERE (select a from t1);
  88100. */
  88101. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  88102. int op;
  88103. pExpr = sqlite3ExprSkipCollate(pExpr);
  88104. if( pExpr->flags & EP_Generic ) return 0;
  88105. op = pExpr->op;
  88106. if( op==TK_SELECT ){
  88107. assert( pExpr->flags&EP_xIsSelect );
  88108. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  88109. }
  88110. if( op==TK_REGISTER ) op = pExpr->op2;
  88111. #ifndef SQLITE_OMIT_CAST
  88112. if( op==TK_CAST ){
  88113. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  88114. return sqlite3AffinityType(pExpr->u.zToken, 0);
  88115. }
  88116. #endif
  88117. if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
  88118. return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
  88119. }
  88120. if( op==TK_SELECT_COLUMN ){
  88121. assert( pExpr->pLeft->flags&EP_xIsSelect );
  88122. return sqlite3ExprAffinity(
  88123. pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
  88124. );
  88125. }
  88126. return pExpr->affinity;
  88127. }
  88128. /*
  88129. ** Set the collating sequence for expression pExpr to be the collating
  88130. ** sequence named by pToken. Return a pointer to a new Expr node that
  88131. ** implements the COLLATE operator.
  88132. **
  88133. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  88134. ** and the pExpr parameter is returned unchanged.
  88135. */
  88136. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  88137. Parse *pParse, /* Parsing context */
  88138. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  88139. const Token *pCollName, /* Name of collating sequence */
  88140. int dequote /* True to dequote pCollName */
  88141. ){
  88142. if( pCollName->n>0 ){
  88143. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  88144. if( pNew ){
  88145. pNew->pLeft = pExpr;
  88146. pNew->flags |= EP_Collate|EP_Skip;
  88147. pExpr = pNew;
  88148. }
  88149. }
  88150. return pExpr;
  88151. }
  88152. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  88153. Token s;
  88154. assert( zC!=0 );
  88155. sqlite3TokenInit(&s, (char*)zC);
  88156. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  88157. }
  88158. /*
  88159. ** Skip over any TK_COLLATE operators and any unlikely()
  88160. ** or likelihood() function at the root of an expression.
  88161. */
  88162. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  88163. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  88164. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  88165. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  88166. assert( pExpr->x.pList->nExpr>0 );
  88167. assert( pExpr->op==TK_FUNCTION );
  88168. pExpr = pExpr->x.pList->a[0].pExpr;
  88169. }else{
  88170. assert( pExpr->op==TK_COLLATE );
  88171. pExpr = pExpr->pLeft;
  88172. }
  88173. }
  88174. return pExpr;
  88175. }
  88176. /*
  88177. ** Return the collation sequence for the expression pExpr. If
  88178. ** there is no defined collating sequence, return NULL.
  88179. **
  88180. ** See also: sqlite3ExprNNCollSeq()
  88181. **
  88182. ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
  88183. ** default collation if pExpr has no defined collation.
  88184. **
  88185. ** The collating sequence might be determined by a COLLATE operator
  88186. ** or by the presence of a column with a defined collating sequence.
  88187. ** COLLATE operators take first precedence. Left operands take
  88188. ** precedence over right operands.
  88189. */
  88190. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  88191. sqlite3 *db = pParse->db;
  88192. CollSeq *pColl = 0;
  88193. Expr *p = pExpr;
  88194. while( p ){
  88195. int op = p->op;
  88196. if( p->flags & EP_Generic ) break;
  88197. if( op==TK_CAST || op==TK_UPLUS ){
  88198. p = p->pLeft;
  88199. continue;
  88200. }
  88201. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  88202. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  88203. break;
  88204. }
  88205. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  88206. || op==TK_REGISTER || op==TK_TRIGGER)
  88207. && p->pTab!=0
  88208. ){
  88209. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  88210. ** a TK_COLUMN but was previously evaluated and cached in a register */
  88211. int j = p->iColumn;
  88212. if( j>=0 ){
  88213. const char *zColl = p->pTab->aCol[j].zColl;
  88214. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  88215. }
  88216. break;
  88217. }
  88218. if( p->flags & EP_Collate ){
  88219. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  88220. p = p->pLeft;
  88221. }else{
  88222. Expr *pNext = p->pRight;
  88223. /* The Expr.x union is never used at the same time as Expr.pRight */
  88224. assert( p->x.pList==0 || p->pRight==0 );
  88225. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  88226. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  88227. ** least one EP_Collate. Thus the following two ALWAYS. */
  88228. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  88229. int i;
  88230. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  88231. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  88232. pNext = p->x.pList->a[i].pExpr;
  88233. break;
  88234. }
  88235. }
  88236. }
  88237. p = pNext;
  88238. }
  88239. }else{
  88240. break;
  88241. }
  88242. }
  88243. if( sqlite3CheckCollSeq(pParse, pColl) ){
  88244. pColl = 0;
  88245. }
  88246. return pColl;
  88247. }
  88248. /*
  88249. ** Return the collation sequence for the expression pExpr. If
  88250. ** there is no defined collating sequence, return a pointer to the
  88251. ** defautl collation sequence.
  88252. **
  88253. ** See also: sqlite3ExprCollSeq()
  88254. **
  88255. ** The sqlite3ExprCollSeq() routine works the same except that it
  88256. ** returns NULL if there is no defined collation.
  88257. */
  88258. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
  88259. CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
  88260. if( p==0 ) p = pParse->db->pDfltColl;
  88261. assert( p!=0 );
  88262. return p;
  88263. }
  88264. /*
  88265. ** Return TRUE if the two expressions have equivalent collating sequences.
  88266. */
  88267. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
  88268. CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
  88269. CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
  88270. return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
  88271. }
  88272. /*
  88273. ** pExpr is an operand of a comparison operator. aff2 is the
  88274. ** type affinity of the other operand. This routine returns the
  88275. ** type affinity that should be used for the comparison operator.
  88276. */
  88277. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  88278. char aff1 = sqlite3ExprAffinity(pExpr);
  88279. if( aff1 && aff2 ){
  88280. /* Both sides of the comparison are columns. If one has numeric
  88281. ** affinity, use that. Otherwise use no affinity.
  88282. */
  88283. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  88284. return SQLITE_AFF_NUMERIC;
  88285. }else{
  88286. return SQLITE_AFF_BLOB;
  88287. }
  88288. }else if( !aff1 && !aff2 ){
  88289. /* Neither side of the comparison is a column. Compare the
  88290. ** results directly.
  88291. */
  88292. return SQLITE_AFF_BLOB;
  88293. }else{
  88294. /* One side is a column, the other is not. Use the columns affinity. */
  88295. assert( aff1==0 || aff2==0 );
  88296. return (aff1 + aff2);
  88297. }
  88298. }
  88299. /*
  88300. ** pExpr is a comparison operator. Return the type affinity that should
  88301. ** be applied to both operands prior to doing the comparison.
  88302. */
  88303. static char comparisonAffinity(Expr *pExpr){
  88304. char aff;
  88305. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  88306. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  88307. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  88308. assert( pExpr->pLeft );
  88309. aff = sqlite3ExprAffinity(pExpr->pLeft);
  88310. if( pExpr->pRight ){
  88311. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  88312. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  88313. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  88314. }else if( aff==0 ){
  88315. aff = SQLITE_AFF_BLOB;
  88316. }
  88317. return aff;
  88318. }
  88319. /*
  88320. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  88321. ** idx_affinity is the affinity of an indexed column. Return true
  88322. ** if the index with affinity idx_affinity may be used to implement
  88323. ** the comparison in pExpr.
  88324. */
  88325. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  88326. char aff = comparisonAffinity(pExpr);
  88327. switch( aff ){
  88328. case SQLITE_AFF_BLOB:
  88329. return 1;
  88330. case SQLITE_AFF_TEXT:
  88331. return idx_affinity==SQLITE_AFF_TEXT;
  88332. default:
  88333. return sqlite3IsNumericAffinity(idx_affinity);
  88334. }
  88335. }
  88336. /*
  88337. ** Return the P5 value that should be used for a binary comparison
  88338. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  88339. */
  88340. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  88341. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  88342. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  88343. return aff;
  88344. }
  88345. /*
  88346. ** Return a pointer to the collation sequence that should be used by
  88347. ** a binary comparison operator comparing pLeft and pRight.
  88348. **
  88349. ** If the left hand expression has a collating sequence type, then it is
  88350. ** used. Otherwise the collation sequence for the right hand expression
  88351. ** is used, or the default (BINARY) if neither expression has a collating
  88352. ** type.
  88353. **
  88354. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  88355. ** it is not considered.
  88356. */
  88357. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  88358. Parse *pParse,
  88359. Expr *pLeft,
  88360. Expr *pRight
  88361. ){
  88362. CollSeq *pColl;
  88363. assert( pLeft );
  88364. if( pLeft->flags & EP_Collate ){
  88365. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  88366. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  88367. pColl = sqlite3ExprCollSeq(pParse, pRight);
  88368. }else{
  88369. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  88370. if( !pColl ){
  88371. pColl = sqlite3ExprCollSeq(pParse, pRight);
  88372. }
  88373. }
  88374. return pColl;
  88375. }
  88376. /*
  88377. ** Generate code for a comparison operator.
  88378. */
  88379. static int codeCompare(
  88380. Parse *pParse, /* The parsing (and code generating) context */
  88381. Expr *pLeft, /* The left operand */
  88382. Expr *pRight, /* The right operand */
  88383. int opcode, /* The comparison opcode */
  88384. int in1, int in2, /* Register holding operands */
  88385. int dest, /* Jump here if true. */
  88386. int jumpIfNull /* If true, jump if either operand is NULL */
  88387. ){
  88388. int p5;
  88389. int addr;
  88390. CollSeq *p4;
  88391. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  88392. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  88393. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  88394. (void*)p4, P4_COLLSEQ);
  88395. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  88396. return addr;
  88397. }
  88398. /*
  88399. ** Return true if expression pExpr is a vector, or false otherwise.
  88400. **
  88401. ** A vector is defined as any expression that results in two or more
  88402. ** columns of result. Every TK_VECTOR node is an vector because the
  88403. ** parser will not generate a TK_VECTOR with fewer than two entries.
  88404. ** But a TK_SELECT might be either a vector or a scalar. It is only
  88405. ** considered a vector if it has two or more result columns.
  88406. */
  88407. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
  88408. return sqlite3ExprVectorSize(pExpr)>1;
  88409. }
  88410. /*
  88411. ** If the expression passed as the only argument is of type TK_VECTOR
  88412. ** return the number of expressions in the vector. Or, if the expression
  88413. ** is a sub-select, return the number of columns in the sub-select. For
  88414. ** any other type of expression, return 1.
  88415. */
  88416. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
  88417. u8 op = pExpr->op;
  88418. if( op==TK_REGISTER ) op = pExpr->op2;
  88419. if( op==TK_VECTOR ){
  88420. return pExpr->x.pList->nExpr;
  88421. }else if( op==TK_SELECT ){
  88422. return pExpr->x.pSelect->pEList->nExpr;
  88423. }else{
  88424. return 1;
  88425. }
  88426. }
  88427. /*
  88428. ** Return a pointer to a subexpression of pVector that is the i-th
  88429. ** column of the vector (numbered starting with 0). The caller must
  88430. ** ensure that i is within range.
  88431. **
  88432. ** If pVector is really a scalar (and "scalar" here includes subqueries
  88433. ** that return a single column!) then return pVector unmodified.
  88434. **
  88435. ** pVector retains ownership of the returned subexpression.
  88436. **
  88437. ** If the vector is a (SELECT ...) then the expression returned is
  88438. ** just the expression for the i-th term of the result set, and may
  88439. ** not be ready for evaluation because the table cursor has not yet
  88440. ** been positioned.
  88441. */
  88442. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
  88443. assert( i<sqlite3ExprVectorSize(pVector) );
  88444. if( sqlite3ExprIsVector(pVector) ){
  88445. assert( pVector->op2==0 || pVector->op==TK_REGISTER );
  88446. if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
  88447. return pVector->x.pSelect->pEList->a[i].pExpr;
  88448. }else{
  88449. return pVector->x.pList->a[i].pExpr;
  88450. }
  88451. }
  88452. return pVector;
  88453. }
  88454. /*
  88455. ** Compute and return a new Expr object which when passed to
  88456. ** sqlite3ExprCode() will generate all necessary code to compute
  88457. ** the iField-th column of the vector expression pVector.
  88458. **
  88459. ** It is ok for pVector to be a scalar (as long as iField==0).
  88460. ** In that case, this routine works like sqlite3ExprDup().
  88461. **
  88462. ** The caller owns the returned Expr object and is responsible for
  88463. ** ensuring that the returned value eventually gets freed.
  88464. **
  88465. ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
  88466. ** then the returned object will reference pVector and so pVector must remain
  88467. ** valid for the life of the returned object. If pVector is a TK_VECTOR
  88468. ** or a scalar expression, then it can be deleted as soon as this routine
  88469. ** returns.
  88470. **
  88471. ** A trick to cause a TK_SELECT pVector to be deleted together with
  88472. ** the returned Expr object is to attach the pVector to the pRight field
  88473. ** of the returned TK_SELECT_COLUMN Expr object.
  88474. */
  88475. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
  88476. Parse *pParse, /* Parsing context */
  88477. Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
  88478. int iField /* Which column of the vector to return */
  88479. ){
  88480. Expr *pRet;
  88481. if( pVector->op==TK_SELECT ){
  88482. assert( pVector->flags & EP_xIsSelect );
  88483. /* The TK_SELECT_COLUMN Expr node:
  88484. **
  88485. ** pLeft: pVector containing TK_SELECT. Not deleted.
  88486. ** pRight: not used. But recursively deleted.
  88487. ** iColumn: Index of a column in pVector
  88488. ** iTable: 0 or the number of columns on the LHS of an assignment
  88489. ** pLeft->iTable: First in an array of register holding result, or 0
  88490. ** if the result is not yet computed.
  88491. **
  88492. ** sqlite3ExprDelete() specifically skips the recursive delete of
  88493. ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
  88494. ** can be attached to pRight to cause this node to take ownership of
  88495. ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
  88496. ** with the same pLeft pointer to the pVector, but only one of them
  88497. ** will own the pVector.
  88498. */
  88499. pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
  88500. if( pRet ){
  88501. pRet->iColumn = iField;
  88502. pRet->pLeft = pVector;
  88503. }
  88504. assert( pRet==0 || pRet->iTable==0 );
  88505. }else{
  88506. if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
  88507. pRet = sqlite3ExprDup(pParse->db, pVector, 0);
  88508. }
  88509. return pRet;
  88510. }
  88511. /*
  88512. ** If expression pExpr is of type TK_SELECT, generate code to evaluate
  88513. ** it. Return the register in which the result is stored (or, if the
  88514. ** sub-select returns more than one column, the first in an array
  88515. ** of registers in which the result is stored).
  88516. **
  88517. ** If pExpr is not a TK_SELECT expression, return 0.
  88518. */
  88519. static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
  88520. int reg = 0;
  88521. #ifndef SQLITE_OMIT_SUBQUERY
  88522. if( pExpr->op==TK_SELECT ){
  88523. reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  88524. }
  88525. #endif
  88526. return reg;
  88527. }
  88528. /*
  88529. ** Argument pVector points to a vector expression - either a TK_VECTOR
  88530. ** or TK_SELECT that returns more than one column. This function returns
  88531. ** the register number of a register that contains the value of
  88532. ** element iField of the vector.
  88533. **
  88534. ** If pVector is a TK_SELECT expression, then code for it must have
  88535. ** already been generated using the exprCodeSubselect() routine. In this
  88536. ** case parameter regSelect should be the first in an array of registers
  88537. ** containing the results of the sub-select.
  88538. **
  88539. ** If pVector is of type TK_VECTOR, then code for the requested field
  88540. ** is generated. In this case (*pRegFree) may be set to the number of
  88541. ** a temporary register to be freed by the caller before returning.
  88542. **
  88543. ** Before returning, output parameter (*ppExpr) is set to point to the
  88544. ** Expr object corresponding to element iElem of the vector.
  88545. */
  88546. static int exprVectorRegister(
  88547. Parse *pParse, /* Parse context */
  88548. Expr *pVector, /* Vector to extract element from */
  88549. int iField, /* Field to extract from pVector */
  88550. int regSelect, /* First in array of registers */
  88551. Expr **ppExpr, /* OUT: Expression element */
  88552. int *pRegFree /* OUT: Temp register to free */
  88553. ){
  88554. u8 op = pVector->op;
  88555. assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
  88556. if( op==TK_REGISTER ){
  88557. *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
  88558. return pVector->iTable+iField;
  88559. }
  88560. if( op==TK_SELECT ){
  88561. *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
  88562. return regSelect+iField;
  88563. }
  88564. *ppExpr = pVector->x.pList->a[iField].pExpr;
  88565. return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
  88566. }
  88567. /*
  88568. ** Expression pExpr is a comparison between two vector values. Compute
  88569. ** the result of the comparison (1, 0, or NULL) and write that
  88570. ** result into register dest.
  88571. **
  88572. ** The caller must satisfy the following preconditions:
  88573. **
  88574. ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
  88575. ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
  88576. ** otherwise: op==pExpr->op and p5==0
  88577. */
  88578. static void codeVectorCompare(
  88579. Parse *pParse, /* Code generator context */
  88580. Expr *pExpr, /* The comparison operation */
  88581. int dest, /* Write results into this register */
  88582. u8 op, /* Comparison operator */
  88583. u8 p5 /* SQLITE_NULLEQ or zero */
  88584. ){
  88585. Vdbe *v = pParse->pVdbe;
  88586. Expr *pLeft = pExpr->pLeft;
  88587. Expr *pRight = pExpr->pRight;
  88588. int nLeft = sqlite3ExprVectorSize(pLeft);
  88589. int i;
  88590. int regLeft = 0;
  88591. int regRight = 0;
  88592. u8 opx = op;
  88593. int addrDone = sqlite3VdbeMakeLabel(v);
  88594. if( nLeft!=sqlite3ExprVectorSize(pRight) ){
  88595. sqlite3ErrorMsg(pParse, "row value misused");
  88596. return;
  88597. }
  88598. assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
  88599. || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
  88600. || pExpr->op==TK_LT || pExpr->op==TK_GT
  88601. || pExpr->op==TK_LE || pExpr->op==TK_GE
  88602. );
  88603. assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
  88604. || (pExpr->op==TK_ISNOT && op==TK_NE) );
  88605. assert( p5==0 || pExpr->op!=op );
  88606. assert( p5==SQLITE_NULLEQ || pExpr->op==op );
  88607. p5 |= SQLITE_STOREP2;
  88608. if( opx==TK_LE ) opx = TK_LT;
  88609. if( opx==TK_GE ) opx = TK_GT;
  88610. regLeft = exprCodeSubselect(pParse, pLeft);
  88611. regRight = exprCodeSubselect(pParse, pRight);
  88612. for(i=0; 1 /*Loop exits by "break"*/; i++){
  88613. int regFree1 = 0, regFree2 = 0;
  88614. Expr *pL, *pR;
  88615. int r1, r2;
  88616. assert( i>=0 && i<nLeft );
  88617. if( i>0 ) sqlite3ExprCachePush(pParse);
  88618. r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
  88619. r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
  88620. codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
  88621. testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  88622. testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  88623. testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  88624. testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  88625. testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  88626. testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  88627. sqlite3ReleaseTempReg(pParse, regFree1);
  88628. sqlite3ReleaseTempReg(pParse, regFree2);
  88629. if( i>0 ) sqlite3ExprCachePop(pParse);
  88630. if( i==nLeft-1 ){
  88631. break;
  88632. }
  88633. if( opx==TK_EQ ){
  88634. sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
  88635. p5 |= SQLITE_KEEPNULL;
  88636. }else if( opx==TK_NE ){
  88637. sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
  88638. p5 |= SQLITE_KEEPNULL;
  88639. }else{
  88640. assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
  88641. sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
  88642. VdbeCoverageIf(v, op==TK_LT);
  88643. VdbeCoverageIf(v, op==TK_GT);
  88644. VdbeCoverageIf(v, op==TK_LE);
  88645. VdbeCoverageIf(v, op==TK_GE);
  88646. if( i==nLeft-2 ) opx = op;
  88647. }
  88648. }
  88649. sqlite3VdbeResolveLabel(v, addrDone);
  88650. }
  88651. #if SQLITE_MAX_EXPR_DEPTH>0
  88652. /*
  88653. ** Check that argument nHeight is less than or equal to the maximum
  88654. ** expression depth allowed. If it is not, leave an error message in
  88655. ** pParse.
  88656. */
  88657. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  88658. int rc = SQLITE_OK;
  88659. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  88660. if( nHeight>mxHeight ){
  88661. sqlite3ErrorMsg(pParse,
  88662. "Expression tree is too large (maximum depth %d)", mxHeight
  88663. );
  88664. rc = SQLITE_ERROR;
  88665. }
  88666. return rc;
  88667. }
  88668. /* The following three functions, heightOfExpr(), heightOfExprList()
  88669. ** and heightOfSelect(), are used to determine the maximum height
  88670. ** of any expression tree referenced by the structure passed as the
  88671. ** first argument.
  88672. **
  88673. ** If this maximum height is greater than the current value pointed
  88674. ** to by pnHeight, the second parameter, then set *pnHeight to that
  88675. ** value.
  88676. */
  88677. static void heightOfExpr(Expr *p, int *pnHeight){
  88678. if( p ){
  88679. if( p->nHeight>*pnHeight ){
  88680. *pnHeight = p->nHeight;
  88681. }
  88682. }
  88683. }
  88684. static void heightOfExprList(ExprList *p, int *pnHeight){
  88685. if( p ){
  88686. int i;
  88687. for(i=0; i<p->nExpr; i++){
  88688. heightOfExpr(p->a[i].pExpr, pnHeight);
  88689. }
  88690. }
  88691. }
  88692. static void heightOfSelect(Select *pSelect, int *pnHeight){
  88693. Select *p;
  88694. for(p=pSelect; p; p=p->pPrior){
  88695. heightOfExpr(p->pWhere, pnHeight);
  88696. heightOfExpr(p->pHaving, pnHeight);
  88697. heightOfExpr(p->pLimit, pnHeight);
  88698. heightOfExprList(p->pEList, pnHeight);
  88699. heightOfExprList(p->pGroupBy, pnHeight);
  88700. heightOfExprList(p->pOrderBy, pnHeight);
  88701. }
  88702. }
  88703. /*
  88704. ** Set the Expr.nHeight variable in the structure passed as an
  88705. ** argument. An expression with no children, Expr.pList or
  88706. ** Expr.pSelect member has a height of 1. Any other expression
  88707. ** has a height equal to the maximum height of any other
  88708. ** referenced Expr plus one.
  88709. **
  88710. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  88711. ** if appropriate.
  88712. */
  88713. static void exprSetHeight(Expr *p){
  88714. int nHeight = 0;
  88715. heightOfExpr(p->pLeft, &nHeight);
  88716. heightOfExpr(p->pRight, &nHeight);
  88717. if( ExprHasProperty(p, EP_xIsSelect) ){
  88718. heightOfSelect(p->x.pSelect, &nHeight);
  88719. }else if( p->x.pList ){
  88720. heightOfExprList(p->x.pList, &nHeight);
  88721. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  88722. }
  88723. p->nHeight = nHeight + 1;
  88724. }
  88725. /*
  88726. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  88727. ** the height is greater than the maximum allowed expression depth,
  88728. ** leave an error in pParse.
  88729. **
  88730. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  88731. ** Expr.flags.
  88732. */
  88733. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  88734. if( pParse->nErr ) return;
  88735. exprSetHeight(p);
  88736. sqlite3ExprCheckHeight(pParse, p->nHeight);
  88737. }
  88738. /*
  88739. ** Return the maximum height of any expression tree referenced
  88740. ** by the select statement passed as an argument.
  88741. */
  88742. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  88743. int nHeight = 0;
  88744. heightOfSelect(p, &nHeight);
  88745. return nHeight;
  88746. }
  88747. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  88748. /*
  88749. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  88750. ** Expr.flags.
  88751. */
  88752. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  88753. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  88754. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  88755. }
  88756. }
  88757. #define exprSetHeight(y)
  88758. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  88759. /*
  88760. ** This routine is the core allocator for Expr nodes.
  88761. **
  88762. ** Construct a new expression node and return a pointer to it. Memory
  88763. ** for this node and for the pToken argument is a single allocation
  88764. ** obtained from sqlite3DbMalloc(). The calling function
  88765. ** is responsible for making sure the node eventually gets freed.
  88766. **
  88767. ** If dequote is true, then the token (if it exists) is dequoted.
  88768. ** If dequote is false, no dequoting is performed. The deQuote
  88769. ** parameter is ignored if pToken is NULL or if the token does not
  88770. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  88771. ** then the EP_DblQuoted flag is set on the expression node.
  88772. **
  88773. ** Special case: If op==TK_INTEGER and pToken points to a string that
  88774. ** can be translated into a 32-bit integer, then the token is not
  88775. ** stored in u.zToken. Instead, the integer values is written
  88776. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  88777. ** is allocated to hold the integer text and the dequote flag is ignored.
  88778. */
  88779. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  88780. sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
  88781. int op, /* Expression opcode */
  88782. const Token *pToken, /* Token argument. Might be NULL */
  88783. int dequote /* True to dequote */
  88784. ){
  88785. Expr *pNew;
  88786. int nExtra = 0;
  88787. int iValue = 0;
  88788. assert( db!=0 );
  88789. if( pToken ){
  88790. if( op!=TK_INTEGER || pToken->z==0
  88791. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  88792. nExtra = pToken->n+1;
  88793. assert( iValue>=0 );
  88794. }
  88795. }
  88796. pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
  88797. if( pNew ){
  88798. memset(pNew, 0, sizeof(Expr));
  88799. pNew->op = (u8)op;
  88800. pNew->iAgg = -1;
  88801. if( pToken ){
  88802. if( nExtra==0 ){
  88803. pNew->flags |= EP_IntValue|EP_Leaf;
  88804. pNew->u.iValue = iValue;
  88805. }else{
  88806. pNew->u.zToken = (char*)&pNew[1];
  88807. assert( pToken->z!=0 || pToken->n==0 );
  88808. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  88809. pNew->u.zToken[pToken->n] = 0;
  88810. if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
  88811. if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
  88812. sqlite3Dequote(pNew->u.zToken);
  88813. }
  88814. }
  88815. }
  88816. #if SQLITE_MAX_EXPR_DEPTH>0
  88817. pNew->nHeight = 1;
  88818. #endif
  88819. }
  88820. return pNew;
  88821. }
  88822. /*
  88823. ** Allocate a new expression node from a zero-terminated token that has
  88824. ** already been dequoted.
  88825. */
  88826. SQLITE_PRIVATE Expr *sqlite3Expr(
  88827. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  88828. int op, /* Expression opcode */
  88829. const char *zToken /* Token argument. Might be NULL */
  88830. ){
  88831. Token x;
  88832. x.z = zToken;
  88833. x.n = sqlite3Strlen30(zToken);
  88834. return sqlite3ExprAlloc(db, op, &x, 0);
  88835. }
  88836. /*
  88837. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  88838. **
  88839. ** If pRoot==NULL that means that a memory allocation error has occurred.
  88840. ** In that case, delete the subtrees pLeft and pRight.
  88841. */
  88842. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  88843. sqlite3 *db,
  88844. Expr *pRoot,
  88845. Expr *pLeft,
  88846. Expr *pRight
  88847. ){
  88848. if( pRoot==0 ){
  88849. assert( db->mallocFailed );
  88850. sqlite3ExprDelete(db, pLeft);
  88851. sqlite3ExprDelete(db, pRight);
  88852. }else{
  88853. if( pRight ){
  88854. pRoot->pRight = pRight;
  88855. pRoot->flags |= EP_Propagate & pRight->flags;
  88856. }
  88857. if( pLeft ){
  88858. pRoot->pLeft = pLeft;
  88859. pRoot->flags |= EP_Propagate & pLeft->flags;
  88860. }
  88861. exprSetHeight(pRoot);
  88862. }
  88863. }
  88864. /*
  88865. ** Allocate an Expr node which joins as many as two subtrees.
  88866. **
  88867. ** One or both of the subtrees can be NULL. Return a pointer to the new
  88868. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  88869. ** free the subtrees and return NULL.
  88870. */
  88871. SQLITE_PRIVATE Expr *sqlite3PExpr(
  88872. Parse *pParse, /* Parsing context */
  88873. int op, /* Expression opcode */
  88874. Expr *pLeft, /* Left operand */
  88875. Expr *pRight /* Right operand */
  88876. ){
  88877. Expr *p;
  88878. if( op==TK_AND && pParse->nErr==0 ){
  88879. /* Take advantage of short-circuit false optimization for AND */
  88880. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  88881. }else{
  88882. p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
  88883. if( p ){
  88884. memset(p, 0, sizeof(Expr));
  88885. p->op = op & TKFLG_MASK;
  88886. p->iAgg = -1;
  88887. }
  88888. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  88889. }
  88890. if( p ) {
  88891. sqlite3ExprCheckHeight(pParse, p->nHeight);
  88892. }
  88893. return p;
  88894. }
  88895. /*
  88896. ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
  88897. ** do a memory allocation failure) then delete the pSelect object.
  88898. */
  88899. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
  88900. if( pExpr ){
  88901. pExpr->x.pSelect = pSelect;
  88902. ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
  88903. sqlite3ExprSetHeightAndFlags(pParse, pExpr);
  88904. }else{
  88905. assert( pParse->db->mallocFailed );
  88906. sqlite3SelectDelete(pParse->db, pSelect);
  88907. }
  88908. }
  88909. /*
  88910. ** If the expression is always either TRUE or FALSE (respectively),
  88911. ** then return 1. If one cannot determine the truth value of the
  88912. ** expression at compile-time return 0.
  88913. **
  88914. ** This is an optimization. If is OK to return 0 here even if
  88915. ** the expression really is always false or false (a false negative).
  88916. ** But it is a bug to return 1 if the expression might have different
  88917. ** boolean values in different circumstances (a false positive.)
  88918. **
  88919. ** Note that if the expression is part of conditional for a
  88920. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  88921. ** is it true or false, so always return 0.
  88922. */
  88923. static int exprAlwaysTrue(Expr *p){
  88924. int v = 0;
  88925. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  88926. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  88927. return v!=0;
  88928. }
  88929. static int exprAlwaysFalse(Expr *p){
  88930. int v = 0;
  88931. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  88932. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  88933. return v==0;
  88934. }
  88935. /*
  88936. ** Join two expressions using an AND operator. If either expression is
  88937. ** NULL, then just return the other expression.
  88938. **
  88939. ** If one side or the other of the AND is known to be false, then instead
  88940. ** of returning an AND expression, just return a constant expression with
  88941. ** a value of false.
  88942. */
  88943. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  88944. if( pLeft==0 ){
  88945. return pRight;
  88946. }else if( pRight==0 ){
  88947. return pLeft;
  88948. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  88949. sqlite3ExprDelete(db, pLeft);
  88950. sqlite3ExprDelete(db, pRight);
  88951. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  88952. }else{
  88953. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  88954. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  88955. return pNew;
  88956. }
  88957. }
  88958. /*
  88959. ** Construct a new expression node for a function with multiple
  88960. ** arguments.
  88961. */
  88962. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  88963. Expr *pNew;
  88964. sqlite3 *db = pParse->db;
  88965. assert( pToken );
  88966. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  88967. if( pNew==0 ){
  88968. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  88969. return 0;
  88970. }
  88971. pNew->x.pList = pList;
  88972. ExprSetProperty(pNew, EP_HasFunc);
  88973. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  88974. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  88975. return pNew;
  88976. }
  88977. /*
  88978. ** Assign a variable number to an expression that encodes a wildcard
  88979. ** in the original SQL statement.
  88980. **
  88981. ** Wildcards consisting of a single "?" are assigned the next sequential
  88982. ** variable number.
  88983. **
  88984. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  88985. ** sure "nnn" is not too big to avoid a denial of service attack when
  88986. ** the SQL statement comes from an external source.
  88987. **
  88988. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  88989. ** as the previous instance of the same wildcard. Or if this is the first
  88990. ** instance of the wildcard, the next sequential variable number is
  88991. ** assigned.
  88992. */
  88993. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
  88994. sqlite3 *db = pParse->db;
  88995. const char *z;
  88996. ynVar x;
  88997. if( pExpr==0 ) return;
  88998. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  88999. z = pExpr->u.zToken;
  89000. assert( z!=0 );
  89001. assert( z[0]!=0 );
  89002. assert( n==(u32)sqlite3Strlen30(z) );
  89003. if( z[1]==0 ){
  89004. /* Wildcard of the form "?". Assign the next variable number */
  89005. assert( z[0]=='?' );
  89006. x = (ynVar)(++pParse->nVar);
  89007. }else{
  89008. int doAdd = 0;
  89009. if( z[0]=='?' ){
  89010. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  89011. ** use it as the variable number */
  89012. i64 i;
  89013. int bOk;
  89014. if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
  89015. i = z[1]-'0'; /* The common case of ?N for a single digit N */
  89016. bOk = 1;
  89017. }else{
  89018. bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  89019. }
  89020. testcase( i==0 );
  89021. testcase( i==1 );
  89022. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  89023. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  89024. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  89025. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  89026. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  89027. return;
  89028. }
  89029. x = (ynVar)i;
  89030. if( x>pParse->nVar ){
  89031. pParse->nVar = (int)x;
  89032. doAdd = 1;
  89033. }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
  89034. doAdd = 1;
  89035. }
  89036. }else{
  89037. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  89038. ** number as the prior appearance of the same name, or if the name
  89039. ** has never appeared before, reuse the same variable number
  89040. */
  89041. x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
  89042. if( x==0 ){
  89043. x = (ynVar)(++pParse->nVar);
  89044. doAdd = 1;
  89045. }
  89046. }
  89047. if( doAdd ){
  89048. pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
  89049. }
  89050. }
  89051. pExpr->iColumn = x;
  89052. if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  89053. sqlite3ErrorMsg(pParse, "too many SQL variables");
  89054. }
  89055. }
  89056. /*
  89057. ** Recursively delete an expression tree.
  89058. */
  89059. static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  89060. assert( p!=0 );
  89061. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  89062. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  89063. #ifdef SQLITE_DEBUG
  89064. if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
  89065. assert( p->pLeft==0 );
  89066. assert( p->pRight==0 );
  89067. assert( p->x.pSelect==0 );
  89068. }
  89069. #endif
  89070. if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
  89071. /* The Expr.x union is never used at the same time as Expr.pRight */
  89072. assert( p->x.pList==0 || p->pRight==0 );
  89073. if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
  89074. if( p->pRight ){
  89075. sqlite3ExprDeleteNN(db, p->pRight);
  89076. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  89077. sqlite3SelectDelete(db, p->x.pSelect);
  89078. }else{
  89079. sqlite3ExprListDelete(db, p->x.pList);
  89080. }
  89081. }
  89082. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  89083. if( !ExprHasProperty(p, EP_Static) ){
  89084. sqlite3DbFreeNN(db, p);
  89085. }
  89086. }
  89087. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  89088. if( p ) sqlite3ExprDeleteNN(db, p);
  89089. }
  89090. /*
  89091. ** Return the number of bytes allocated for the expression structure
  89092. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  89093. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  89094. */
  89095. static int exprStructSize(Expr *p){
  89096. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  89097. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  89098. return EXPR_FULLSIZE;
  89099. }
  89100. /*
  89101. ** The dupedExpr*Size() routines each return the number of bytes required
  89102. ** to store a copy of an expression or expression tree. They differ in
  89103. ** how much of the tree is measured.
  89104. **
  89105. ** dupedExprStructSize() Size of only the Expr structure
  89106. ** dupedExprNodeSize() Size of Expr + space for token
  89107. ** dupedExprSize() Expr + token + subtree components
  89108. **
  89109. ***************************************************************************
  89110. **
  89111. ** The dupedExprStructSize() function returns two values OR-ed together:
  89112. ** (1) the space required for a copy of the Expr structure only and
  89113. ** (2) the EP_xxx flags that indicate what the structure size should be.
  89114. ** The return values is always one of:
  89115. **
  89116. ** EXPR_FULLSIZE
  89117. ** EXPR_REDUCEDSIZE | EP_Reduced
  89118. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  89119. **
  89120. ** The size of the structure can be found by masking the return value
  89121. ** of this routine with 0xfff. The flags can be found by masking the
  89122. ** return value with EP_Reduced|EP_TokenOnly.
  89123. **
  89124. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  89125. ** (unreduced) Expr objects as they or originally constructed by the parser.
  89126. ** During expression analysis, extra information is computed and moved into
  89127. ** later parts of teh Expr object and that extra information might get chopped
  89128. ** off if the expression is reduced. Note also that it does not work to
  89129. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  89130. ** to reduce a pristine expression tree from the parser. The implementation
  89131. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  89132. ** to enforce this constraint.
  89133. */
  89134. static int dupedExprStructSize(Expr *p, int flags){
  89135. int nSize;
  89136. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  89137. assert( EXPR_FULLSIZE<=0xfff );
  89138. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  89139. if( 0==flags || p->op==TK_SELECT_COLUMN ){
  89140. nSize = EXPR_FULLSIZE;
  89141. }else{
  89142. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  89143. assert( !ExprHasProperty(p, EP_FromJoin) );
  89144. assert( !ExprHasProperty(p, EP_MemToken) );
  89145. assert( !ExprHasProperty(p, EP_NoReduce) );
  89146. if( p->pLeft || p->x.pList ){
  89147. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  89148. }else{
  89149. assert( p->pRight==0 );
  89150. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  89151. }
  89152. }
  89153. return nSize;
  89154. }
  89155. /*
  89156. ** This function returns the space in bytes required to store the copy
  89157. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  89158. ** string is defined.)
  89159. */
  89160. static int dupedExprNodeSize(Expr *p, int flags){
  89161. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  89162. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  89163. nByte += sqlite3Strlen30(p->u.zToken)+1;
  89164. }
  89165. return ROUND8(nByte);
  89166. }
  89167. /*
  89168. ** Return the number of bytes required to create a duplicate of the
  89169. ** expression passed as the first argument. The second argument is a
  89170. ** mask containing EXPRDUP_XXX flags.
  89171. **
  89172. ** The value returned includes space to create a copy of the Expr struct
  89173. ** itself and the buffer referred to by Expr.u.zToken, if any.
  89174. **
  89175. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  89176. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  89177. ** and Expr.pRight variables (but not for any structures pointed to or
  89178. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  89179. */
  89180. static int dupedExprSize(Expr *p, int flags){
  89181. int nByte = 0;
  89182. if( p ){
  89183. nByte = dupedExprNodeSize(p, flags);
  89184. if( flags&EXPRDUP_REDUCE ){
  89185. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  89186. }
  89187. }
  89188. return nByte;
  89189. }
  89190. /*
  89191. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  89192. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  89193. ** to store the copy of expression p, the copies of p->u.zToken
  89194. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  89195. ** if any. Before returning, *pzBuffer is set to the first byte past the
  89196. ** portion of the buffer copied into by this function.
  89197. */
  89198. static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
  89199. Expr *pNew; /* Value to return */
  89200. u8 *zAlloc; /* Memory space from which to build Expr object */
  89201. u32 staticFlag; /* EP_Static if space not obtained from malloc */
  89202. assert( db!=0 );
  89203. assert( p );
  89204. assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
  89205. assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
  89206. /* Figure out where to write the new Expr structure. */
  89207. if( pzBuffer ){
  89208. zAlloc = *pzBuffer;
  89209. staticFlag = EP_Static;
  89210. }else{
  89211. zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
  89212. staticFlag = 0;
  89213. }
  89214. pNew = (Expr *)zAlloc;
  89215. if( pNew ){
  89216. /* Set nNewSize to the size allocated for the structure pointed to
  89217. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  89218. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  89219. ** by the copy of the p->u.zToken string (if any).
  89220. */
  89221. const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
  89222. const int nNewSize = nStructSize & 0xfff;
  89223. int nToken;
  89224. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  89225. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  89226. }else{
  89227. nToken = 0;
  89228. }
  89229. if( dupFlags ){
  89230. assert( ExprHasProperty(p, EP_Reduced)==0 );
  89231. memcpy(zAlloc, p, nNewSize);
  89232. }else{
  89233. u32 nSize = (u32)exprStructSize(p);
  89234. memcpy(zAlloc, p, nSize);
  89235. if( nSize<EXPR_FULLSIZE ){
  89236. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  89237. }
  89238. }
  89239. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  89240. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  89241. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  89242. pNew->flags |= staticFlag;
  89243. /* Copy the p->u.zToken string, if any. */
  89244. if( nToken ){
  89245. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  89246. memcpy(zToken, p->u.zToken, nToken);
  89247. }
  89248. if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
  89249. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  89250. if( ExprHasProperty(p, EP_xIsSelect) ){
  89251. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
  89252. }else{
  89253. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
  89254. }
  89255. }
  89256. /* Fill in pNew->pLeft and pNew->pRight. */
  89257. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  89258. zAlloc += dupedExprNodeSize(p, dupFlags);
  89259. if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
  89260. pNew->pLeft = p->pLeft ?
  89261. exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
  89262. pNew->pRight = p->pRight ?
  89263. exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
  89264. }
  89265. if( pzBuffer ){
  89266. *pzBuffer = zAlloc;
  89267. }
  89268. }else{
  89269. if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  89270. if( pNew->op==TK_SELECT_COLUMN ){
  89271. pNew->pLeft = p->pLeft;
  89272. assert( p->iColumn==0 || p->pRight==0 );
  89273. assert( p->pRight==0 || p->pRight==p->pLeft );
  89274. }else{
  89275. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  89276. }
  89277. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  89278. }
  89279. }
  89280. }
  89281. return pNew;
  89282. }
  89283. /*
  89284. ** Create and return a deep copy of the object passed as the second
  89285. ** argument. If an OOM condition is encountered, NULL is returned
  89286. ** and the db->mallocFailed flag set.
  89287. */
  89288. #ifndef SQLITE_OMIT_CTE
  89289. static With *withDup(sqlite3 *db, With *p){
  89290. With *pRet = 0;
  89291. if( p ){
  89292. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  89293. pRet = sqlite3DbMallocZero(db, nByte);
  89294. if( pRet ){
  89295. int i;
  89296. pRet->nCte = p->nCte;
  89297. for(i=0; i<p->nCte; i++){
  89298. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  89299. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  89300. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  89301. }
  89302. }
  89303. }
  89304. return pRet;
  89305. }
  89306. #else
  89307. # define withDup(x,y) 0
  89308. #endif
  89309. /*
  89310. ** The following group of routines make deep copies of expressions,
  89311. ** expression lists, ID lists, and select statements. The copies can
  89312. ** be deleted (by being passed to their respective ...Delete() routines)
  89313. ** without effecting the originals.
  89314. **
  89315. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  89316. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  89317. ** by subsequent calls to sqlite*ListAppend() routines.
  89318. **
  89319. ** Any tables that the SrcList might point to are not duplicated.
  89320. **
  89321. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  89322. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  89323. ** truncated version of the usual Expr structure that will be stored as
  89324. ** part of the in-memory representation of the database schema.
  89325. */
  89326. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  89327. assert( flags==0 || flags==EXPRDUP_REDUCE );
  89328. return p ? exprDup(db, p, flags, 0) : 0;
  89329. }
  89330. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  89331. ExprList *pNew;
  89332. struct ExprList_item *pItem, *pOldItem;
  89333. int i;
  89334. Expr *pPriorSelectCol = 0;
  89335. assert( db!=0 );
  89336. if( p==0 ) return 0;
  89337. pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
  89338. if( pNew==0 ) return 0;
  89339. pNew->nExpr = p->nExpr;
  89340. pItem = pNew->a;
  89341. pOldItem = p->a;
  89342. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  89343. Expr *pOldExpr = pOldItem->pExpr;
  89344. Expr *pNewExpr;
  89345. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  89346. if( pOldExpr
  89347. && pOldExpr->op==TK_SELECT_COLUMN
  89348. && (pNewExpr = pItem->pExpr)!=0
  89349. ){
  89350. assert( pNewExpr->iColumn==0 || i>0 );
  89351. if( pNewExpr->iColumn==0 ){
  89352. assert( pOldExpr->pLeft==pOldExpr->pRight );
  89353. pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
  89354. }else{
  89355. assert( i>0 );
  89356. assert( pItem[-1].pExpr!=0 );
  89357. assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
  89358. assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
  89359. pNewExpr->pLeft = pPriorSelectCol;
  89360. }
  89361. }
  89362. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  89363. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  89364. pItem->sortOrder = pOldItem->sortOrder;
  89365. pItem->done = 0;
  89366. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  89367. pItem->u = pOldItem->u;
  89368. }
  89369. return pNew;
  89370. }
  89371. /*
  89372. ** If cursors, triggers, views and subqueries are all omitted from
  89373. ** the build, then none of the following routines, except for
  89374. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  89375. ** called with a NULL argument.
  89376. */
  89377. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  89378. || !defined(SQLITE_OMIT_SUBQUERY)
  89379. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  89380. SrcList *pNew;
  89381. int i;
  89382. int nByte;
  89383. assert( db!=0 );
  89384. if( p==0 ) return 0;
  89385. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  89386. pNew = sqlite3DbMallocRawNN(db, nByte );
  89387. if( pNew==0 ) return 0;
  89388. pNew->nSrc = pNew->nAlloc = p->nSrc;
  89389. for(i=0; i<p->nSrc; i++){
  89390. struct SrcList_item *pNewItem = &pNew->a[i];
  89391. struct SrcList_item *pOldItem = &p->a[i];
  89392. Table *pTab;
  89393. pNewItem->pSchema = pOldItem->pSchema;
  89394. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  89395. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  89396. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  89397. pNewItem->fg = pOldItem->fg;
  89398. pNewItem->iCursor = pOldItem->iCursor;
  89399. pNewItem->addrFillSub = pOldItem->addrFillSub;
  89400. pNewItem->regReturn = pOldItem->regReturn;
  89401. if( pNewItem->fg.isIndexedBy ){
  89402. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  89403. }
  89404. pNewItem->pIBIndex = pOldItem->pIBIndex;
  89405. if( pNewItem->fg.isTabFunc ){
  89406. pNewItem->u1.pFuncArg =
  89407. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  89408. }
  89409. pTab = pNewItem->pTab = pOldItem->pTab;
  89410. if( pTab ){
  89411. pTab->nTabRef++;
  89412. }
  89413. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  89414. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  89415. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  89416. pNewItem->colUsed = pOldItem->colUsed;
  89417. }
  89418. return pNew;
  89419. }
  89420. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  89421. IdList *pNew;
  89422. int i;
  89423. assert( db!=0 );
  89424. if( p==0 ) return 0;
  89425. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  89426. if( pNew==0 ) return 0;
  89427. pNew->nId = p->nId;
  89428. pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  89429. if( pNew->a==0 ){
  89430. sqlite3DbFreeNN(db, pNew);
  89431. return 0;
  89432. }
  89433. /* Note that because the size of the allocation for p->a[] is not
  89434. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  89435. ** on the duplicate created by this function. */
  89436. for(i=0; i<p->nId; i++){
  89437. struct IdList_item *pNewItem = &pNew->a[i];
  89438. struct IdList_item *pOldItem = &p->a[i];
  89439. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  89440. pNewItem->idx = pOldItem->idx;
  89441. }
  89442. return pNew;
  89443. }
  89444. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
  89445. Select *pRet = 0;
  89446. Select *pNext = 0;
  89447. Select **pp = &pRet;
  89448. Select *p;
  89449. assert( db!=0 );
  89450. for(p=pDup; p; p=p->pPrior){
  89451. Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  89452. if( pNew==0 ) break;
  89453. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  89454. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  89455. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  89456. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  89457. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  89458. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  89459. pNew->op = p->op;
  89460. pNew->pNext = pNext;
  89461. pNew->pPrior = 0;
  89462. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  89463. pNew->iLimit = 0;
  89464. pNew->iOffset = 0;
  89465. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  89466. pNew->addrOpenEphm[0] = -1;
  89467. pNew->addrOpenEphm[1] = -1;
  89468. pNew->nSelectRow = p->nSelectRow;
  89469. pNew->pWith = withDup(db, p->pWith);
  89470. sqlite3SelectSetName(pNew, p->zSelName);
  89471. *pp = pNew;
  89472. pp = &pNew->pPrior;
  89473. pNext = pNew;
  89474. }
  89475. return pRet;
  89476. }
  89477. #else
  89478. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  89479. assert( p==0 );
  89480. return 0;
  89481. }
  89482. #endif
  89483. /*
  89484. ** Add a new element to the end of an expression list. If pList is
  89485. ** initially NULL, then create a new expression list.
  89486. **
  89487. ** The pList argument must be either NULL or a pointer to an ExprList
  89488. ** obtained from a prior call to sqlite3ExprListAppend(). This routine
  89489. ** may not be used with an ExprList obtained from sqlite3ExprListDup().
  89490. ** Reason: This routine assumes that the number of slots in pList->a[]
  89491. ** is a power of two. That is true for sqlite3ExprListAppend() returns
  89492. ** but is not necessarily true from the return value of sqlite3ExprListDup().
  89493. **
  89494. ** If a memory allocation error occurs, the entire list is freed and
  89495. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  89496. ** that the new entry was successfully appended.
  89497. */
  89498. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  89499. Parse *pParse, /* Parsing context */
  89500. ExprList *pList, /* List to which to append. Might be NULL */
  89501. Expr *pExpr /* Expression to be appended. Might be NULL */
  89502. ){
  89503. struct ExprList_item *pItem;
  89504. sqlite3 *db = pParse->db;
  89505. assert( db!=0 );
  89506. if( pList==0 ){
  89507. pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  89508. if( pList==0 ){
  89509. goto no_mem;
  89510. }
  89511. pList->nExpr = 0;
  89512. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  89513. ExprList *pNew;
  89514. pNew = sqlite3DbRealloc(db, pList,
  89515. sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0]));
  89516. if( pNew==0 ){
  89517. goto no_mem;
  89518. }
  89519. pList = pNew;
  89520. }
  89521. pItem = &pList->a[pList->nExpr++];
  89522. assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
  89523. assert( offsetof(struct ExprList_item,pExpr)==0 );
  89524. memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
  89525. pItem->pExpr = pExpr;
  89526. return pList;
  89527. no_mem:
  89528. /* Avoid leaking memory if malloc has failed. */
  89529. sqlite3ExprDelete(db, pExpr);
  89530. sqlite3ExprListDelete(db, pList);
  89531. return 0;
  89532. }
  89533. /*
  89534. ** pColumns and pExpr form a vector assignment which is part of the SET
  89535. ** clause of an UPDATE statement. Like this:
  89536. **
  89537. ** (a,b,c) = (expr1,expr2,expr3)
  89538. ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
  89539. **
  89540. ** For each term of the vector assignment, append new entries to the
  89541. ** expression list pList. In the case of a subquery on the RHS, append
  89542. ** TK_SELECT_COLUMN expressions.
  89543. */
  89544. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
  89545. Parse *pParse, /* Parsing context */
  89546. ExprList *pList, /* List to which to append. Might be NULL */
  89547. IdList *pColumns, /* List of names of LHS of the assignment */
  89548. Expr *pExpr /* Vector expression to be appended. Might be NULL */
  89549. ){
  89550. sqlite3 *db = pParse->db;
  89551. int n;
  89552. int i;
  89553. int iFirst = pList ? pList->nExpr : 0;
  89554. /* pColumns can only be NULL due to an OOM but an OOM will cause an
  89555. ** exit prior to this routine being invoked */
  89556. if( NEVER(pColumns==0) ) goto vector_append_error;
  89557. if( pExpr==0 ) goto vector_append_error;
  89558. /* If the RHS is a vector, then we can immediately check to see that
  89559. ** the size of the RHS and LHS match. But if the RHS is a SELECT,
  89560. ** wildcards ("*") in the result set of the SELECT must be expanded before
  89561. ** we can do the size check, so defer the size check until code generation.
  89562. */
  89563. if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
  89564. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  89565. pColumns->nId, n);
  89566. goto vector_append_error;
  89567. }
  89568. for(i=0; i<pColumns->nId; i++){
  89569. Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
  89570. pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
  89571. if( pList ){
  89572. assert( pList->nExpr==iFirst+i+1 );
  89573. pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
  89574. pColumns->a[i].zName = 0;
  89575. }
  89576. }
  89577. if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
  89578. Expr *pFirst = pList->a[iFirst].pExpr;
  89579. assert( pFirst!=0 );
  89580. assert( pFirst->op==TK_SELECT_COLUMN );
  89581. /* Store the SELECT statement in pRight so it will be deleted when
  89582. ** sqlite3ExprListDelete() is called */
  89583. pFirst->pRight = pExpr;
  89584. pExpr = 0;
  89585. /* Remember the size of the LHS in iTable so that we can check that
  89586. ** the RHS and LHS sizes match during code generation. */
  89587. pFirst->iTable = pColumns->nId;
  89588. }
  89589. vector_append_error:
  89590. sqlite3ExprDelete(db, pExpr);
  89591. sqlite3IdListDelete(db, pColumns);
  89592. return pList;
  89593. }
  89594. /*
  89595. ** Set the sort order for the last element on the given ExprList.
  89596. */
  89597. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
  89598. if( p==0 ) return;
  89599. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
  89600. assert( p->nExpr>0 );
  89601. if( iSortOrder<0 ){
  89602. assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
  89603. return;
  89604. }
  89605. p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
  89606. }
  89607. /*
  89608. ** Set the ExprList.a[].zName element of the most recently added item
  89609. ** on the expression list.
  89610. **
  89611. ** pList might be NULL following an OOM error. But pName should never be
  89612. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  89613. ** is set.
  89614. */
  89615. SQLITE_PRIVATE void sqlite3ExprListSetName(
  89616. Parse *pParse, /* Parsing context */
  89617. ExprList *pList, /* List to which to add the span. */
  89618. Token *pName, /* Name to be added */
  89619. int dequote /* True to cause the name to be dequoted */
  89620. ){
  89621. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  89622. if( pList ){
  89623. struct ExprList_item *pItem;
  89624. assert( pList->nExpr>0 );
  89625. pItem = &pList->a[pList->nExpr-1];
  89626. assert( pItem->zName==0 );
  89627. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  89628. if( dequote ) sqlite3Dequote(pItem->zName);
  89629. }
  89630. }
  89631. /*
  89632. ** Set the ExprList.a[].zSpan element of the most recently added item
  89633. ** on the expression list.
  89634. **
  89635. ** pList might be NULL following an OOM error. But pSpan should never be
  89636. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  89637. ** is set.
  89638. */
  89639. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  89640. Parse *pParse, /* Parsing context */
  89641. ExprList *pList, /* List to which to add the span. */
  89642. const char *zStart, /* Start of the span */
  89643. const char *zEnd /* End of the span */
  89644. ){
  89645. sqlite3 *db = pParse->db;
  89646. assert( pList!=0 || db->mallocFailed!=0 );
  89647. if( pList ){
  89648. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  89649. assert( pList->nExpr>0 );
  89650. sqlite3DbFree(db, pItem->zSpan);
  89651. pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
  89652. }
  89653. }
  89654. /*
  89655. ** If the expression list pEList contains more than iLimit elements,
  89656. ** leave an error message in pParse.
  89657. */
  89658. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  89659. Parse *pParse,
  89660. ExprList *pEList,
  89661. const char *zObject
  89662. ){
  89663. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  89664. testcase( pEList && pEList->nExpr==mx );
  89665. testcase( pEList && pEList->nExpr==mx+1 );
  89666. if( pEList && pEList->nExpr>mx ){
  89667. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  89668. }
  89669. }
  89670. /*
  89671. ** Delete an entire expression list.
  89672. */
  89673. static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
  89674. int i = pList->nExpr;
  89675. struct ExprList_item *pItem = pList->a;
  89676. assert( pList->nExpr>0 );
  89677. do{
  89678. sqlite3ExprDelete(db, pItem->pExpr);
  89679. sqlite3DbFree(db, pItem->zName);
  89680. sqlite3DbFree(db, pItem->zSpan);
  89681. pItem++;
  89682. }while( --i>0 );
  89683. sqlite3DbFreeNN(db, pList);
  89684. }
  89685. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  89686. if( pList ) exprListDeleteNN(db, pList);
  89687. }
  89688. /*
  89689. ** Return the bitwise-OR of all Expr.flags fields in the given
  89690. ** ExprList.
  89691. */
  89692. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  89693. int i;
  89694. u32 m = 0;
  89695. assert( pList!=0 );
  89696. for(i=0; i<pList->nExpr; i++){
  89697. Expr *pExpr = pList->a[i].pExpr;
  89698. assert( pExpr!=0 );
  89699. m |= pExpr->flags;
  89700. }
  89701. return m;
  89702. }
  89703. /*
  89704. ** This is a SELECT-node callback for the expression walker that
  89705. ** always "fails". By "fail" in this case, we mean set
  89706. ** pWalker->eCode to zero and abort.
  89707. **
  89708. ** This callback is used by multiple expression walkers.
  89709. */
  89710. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
  89711. UNUSED_PARAMETER(NotUsed);
  89712. pWalker->eCode = 0;
  89713. return WRC_Abort;
  89714. }
  89715. /*
  89716. ** If the input expression is an ID with the name "true" or "false"
  89717. ** then convert it into an TK_TRUEFALSE term. Return non-zero if
  89718. ** the conversion happened, and zero if the expression is unaltered.
  89719. */
  89720. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
  89721. assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
  89722. if( sqlite3StrICmp(pExpr->u.zToken, "true")==0
  89723. || sqlite3StrICmp(pExpr->u.zToken, "false")==0
  89724. ){
  89725. pExpr->op = TK_TRUEFALSE;
  89726. return 1;
  89727. }
  89728. return 0;
  89729. }
  89730. /*
  89731. ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
  89732. ** and 0 if it is FALSE.
  89733. */
  89734. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){
  89735. assert( pExpr->op==TK_TRUEFALSE );
  89736. assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
  89737. || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
  89738. return pExpr->u.zToken[4]==0;
  89739. }
  89740. /*
  89741. ** These routines are Walker callbacks used to check expressions to
  89742. ** see if they are "constant" for some definition of constant. The
  89743. ** Walker.eCode value determines the type of "constant" we are looking
  89744. ** for.
  89745. **
  89746. ** These callback routines are used to implement the following:
  89747. **
  89748. ** sqlite3ExprIsConstant() pWalker->eCode==1
  89749. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  89750. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  89751. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  89752. **
  89753. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  89754. ** is found to not be a constant.
  89755. **
  89756. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  89757. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  89758. ** an existing schema and 4 when processing a new statement. A bound
  89759. ** parameter raises an error for new statements, but is silently converted
  89760. ** to NULL for existing schemas. This allows sqlite_master tables that
  89761. ** contain a bound parameter because they were generated by older versions
  89762. ** of SQLite to be parsed by newer versions of SQLite without raising a
  89763. ** malformed schema error.
  89764. */
  89765. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  89766. /* If pWalker->eCode is 2 then any term of the expression that comes from
  89767. ** the ON or USING clauses of a left join disqualifies the expression
  89768. ** from being considered constant. */
  89769. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  89770. pWalker->eCode = 0;
  89771. return WRC_Abort;
  89772. }
  89773. switch( pExpr->op ){
  89774. /* Consider functions to be constant if all their arguments are constant
  89775. ** and either pWalker->eCode==4 or 5 or the function has the
  89776. ** SQLITE_FUNC_CONST flag. */
  89777. case TK_FUNCTION:
  89778. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  89779. return WRC_Continue;
  89780. }else{
  89781. pWalker->eCode = 0;
  89782. return WRC_Abort;
  89783. }
  89784. case TK_ID:
  89785. /* Convert "true" or "false" in a DEFAULT clause into the
  89786. ** appropriate TK_TRUEFALSE operator */
  89787. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  89788. return WRC_Prune;
  89789. }
  89790. /* Fall thru */
  89791. case TK_COLUMN:
  89792. case TK_AGG_FUNCTION:
  89793. case TK_AGG_COLUMN:
  89794. testcase( pExpr->op==TK_ID );
  89795. testcase( pExpr->op==TK_COLUMN );
  89796. testcase( pExpr->op==TK_AGG_FUNCTION );
  89797. testcase( pExpr->op==TK_AGG_COLUMN );
  89798. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  89799. return WRC_Continue;
  89800. }
  89801. /* Fall through */
  89802. case TK_IF_NULL_ROW:
  89803. testcase( pExpr->op==TK_IF_NULL_ROW );
  89804. pWalker->eCode = 0;
  89805. return WRC_Abort;
  89806. case TK_VARIABLE:
  89807. if( pWalker->eCode==5 ){
  89808. /* Silently convert bound parameters that appear inside of CREATE
  89809. ** statements into a NULL when parsing the CREATE statement text out
  89810. ** of the sqlite_master table */
  89811. pExpr->op = TK_NULL;
  89812. }else if( pWalker->eCode==4 ){
  89813. /* A bound parameter in a CREATE statement that originates from
  89814. ** sqlite3_prepare() causes an error */
  89815. pWalker->eCode = 0;
  89816. return WRC_Abort;
  89817. }
  89818. /* Fall through */
  89819. default:
  89820. testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail will disallow */
  89821. testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail will disallow */
  89822. return WRC_Continue;
  89823. }
  89824. }
  89825. static int exprIsConst(Expr *p, int initFlag, int iCur){
  89826. Walker w;
  89827. w.eCode = initFlag;
  89828. w.xExprCallback = exprNodeIsConstant;
  89829. w.xSelectCallback = sqlite3SelectWalkFail;
  89830. #ifdef SQLITE_DEBUG
  89831. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  89832. #endif
  89833. w.u.iCur = iCur;
  89834. sqlite3WalkExpr(&w, p);
  89835. return w.eCode;
  89836. }
  89837. /*
  89838. ** Walk an expression tree. Return non-zero if the expression is constant
  89839. ** and 0 if it involves variables or function calls.
  89840. **
  89841. ** For the purposes of this function, a double-quoted string (ex: "abc")
  89842. ** is considered a variable but a single-quoted string (ex: 'abc') is
  89843. ** a constant.
  89844. */
  89845. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  89846. return exprIsConst(p, 1, 0);
  89847. }
  89848. /*
  89849. ** Walk an expression tree. Return non-zero if the expression is constant
  89850. ** that does no originate from the ON or USING clauses of a join.
  89851. ** Return 0 if it involves variables or function calls or terms from
  89852. ** an ON or USING clause.
  89853. */
  89854. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  89855. return exprIsConst(p, 2, 0);
  89856. }
  89857. /*
  89858. ** Walk an expression tree. Return non-zero if the expression is constant
  89859. ** for any single row of the table with cursor iCur. In other words, the
  89860. ** expression must not refer to any non-deterministic function nor any
  89861. ** table other than iCur.
  89862. */
  89863. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  89864. return exprIsConst(p, 3, iCur);
  89865. }
  89866. /*
  89867. ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
  89868. */
  89869. static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
  89870. ExprList *pGroupBy = pWalker->u.pGroupBy;
  89871. int i;
  89872. /* Check if pExpr is identical to any GROUP BY term. If so, consider
  89873. ** it constant. */
  89874. for(i=0; i<pGroupBy->nExpr; i++){
  89875. Expr *p = pGroupBy->a[i].pExpr;
  89876. if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
  89877. CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
  89878. if( sqlite3_stricmp("BINARY", pColl->zName)==0 ){
  89879. return WRC_Prune;
  89880. }
  89881. }
  89882. }
  89883. /* Check if pExpr is a sub-select. If so, consider it variable. */
  89884. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  89885. pWalker->eCode = 0;
  89886. return WRC_Abort;
  89887. }
  89888. return exprNodeIsConstant(pWalker, pExpr);
  89889. }
  89890. /*
  89891. ** Walk the expression tree passed as the first argument. Return non-zero
  89892. ** if the expression consists entirely of constants or copies of terms
  89893. ** in pGroupBy that sort with the BINARY collation sequence.
  89894. **
  89895. ** This routine is used to determine if a term of the HAVING clause can
  89896. ** be promoted into the WHERE clause. In order for such a promotion to work,
  89897. ** the value of the HAVING clause term must be the same for all members of
  89898. ** a "group". The requirement that the GROUP BY term must be BINARY
  89899. ** assumes that no other collating sequence will have a finer-grained
  89900. ** grouping than binary. In other words (A=B COLLATE binary) implies
  89901. ** A=B in every other collating sequence. The requirement that the
  89902. ** GROUP BY be BINARY is stricter than necessary. It would also work
  89903. ** to promote HAVING clauses that use the same alternative collating
  89904. ** sequence as the GROUP BY term, but that is much harder to check,
  89905. ** alternative collating sequences are uncommon, and this is only an
  89906. ** optimization, so we take the easy way out and simply require the
  89907. ** GROUP BY to use the BINARY collating sequence.
  89908. */
  89909. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
  89910. Walker w;
  89911. w.eCode = 1;
  89912. w.xExprCallback = exprNodeIsConstantOrGroupBy;
  89913. w.xSelectCallback = 0;
  89914. w.u.pGroupBy = pGroupBy;
  89915. w.pParse = pParse;
  89916. sqlite3WalkExpr(&w, p);
  89917. return w.eCode;
  89918. }
  89919. /*
  89920. ** Walk an expression tree. Return non-zero if the expression is constant
  89921. ** or a function call with constant arguments. Return and 0 if there
  89922. ** are any variables.
  89923. **
  89924. ** For the purposes of this function, a double-quoted string (ex: "abc")
  89925. ** is considered a variable but a single-quoted string (ex: 'abc') is
  89926. ** a constant.
  89927. */
  89928. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  89929. assert( isInit==0 || isInit==1 );
  89930. return exprIsConst(p, 4+isInit, 0);
  89931. }
  89932. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  89933. /*
  89934. ** Walk an expression tree. Return 1 if the expression contains a
  89935. ** subquery of some kind. Return 0 if there are no subqueries.
  89936. */
  89937. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  89938. Walker w;
  89939. w.eCode = 1;
  89940. w.xExprCallback = sqlite3ExprWalkNoop;
  89941. w.xSelectCallback = sqlite3SelectWalkFail;
  89942. #ifdef SQLITE_DEBUG
  89943. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  89944. #endif
  89945. sqlite3WalkExpr(&w, p);
  89946. return w.eCode==0;
  89947. }
  89948. #endif
  89949. /*
  89950. ** If the expression p codes a constant integer that is small enough
  89951. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  89952. ** in *pValue. If the expression is not an integer or if it is too big
  89953. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  89954. */
  89955. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  89956. int rc = 0;
  89957. if( p==0 ) return 0; /* Can only happen following on OOM */
  89958. /* If an expression is an integer literal that fits in a signed 32-bit
  89959. ** integer, then the EP_IntValue flag will have already been set */
  89960. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  89961. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  89962. if( p->flags & EP_IntValue ){
  89963. *pValue = p->u.iValue;
  89964. return 1;
  89965. }
  89966. switch( p->op ){
  89967. case TK_UPLUS: {
  89968. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  89969. break;
  89970. }
  89971. case TK_UMINUS: {
  89972. int v;
  89973. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  89974. assert( v!=(-2147483647-1) );
  89975. *pValue = -v;
  89976. rc = 1;
  89977. }
  89978. break;
  89979. }
  89980. default: break;
  89981. }
  89982. return rc;
  89983. }
  89984. /*
  89985. ** Return FALSE if there is no chance that the expression can be NULL.
  89986. **
  89987. ** If the expression might be NULL or if the expression is too complex
  89988. ** to tell return TRUE.
  89989. **
  89990. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  89991. ** when we know that a value cannot be NULL. Hence, a false positive
  89992. ** (returning TRUE when in fact the expression can never be NULL) might
  89993. ** be a small performance hit but is otherwise harmless. On the other
  89994. ** hand, a false negative (returning FALSE when the result could be NULL)
  89995. ** will likely result in an incorrect answer. So when in doubt, return
  89996. ** TRUE.
  89997. */
  89998. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  89999. u8 op;
  90000. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  90001. op = p->op;
  90002. if( op==TK_REGISTER ) op = p->op2;
  90003. switch( op ){
  90004. case TK_INTEGER:
  90005. case TK_STRING:
  90006. case TK_FLOAT:
  90007. case TK_BLOB:
  90008. return 0;
  90009. case TK_COLUMN:
  90010. return ExprHasProperty(p, EP_CanBeNull) ||
  90011. p->pTab==0 || /* Reference to column of index on expression */
  90012. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  90013. default:
  90014. return 1;
  90015. }
  90016. }
  90017. /*
  90018. ** Return TRUE if the given expression is a constant which would be
  90019. ** unchanged by OP_Affinity with the affinity given in the second
  90020. ** argument.
  90021. **
  90022. ** This routine is used to determine if the OP_Affinity operation
  90023. ** can be omitted. When in doubt return FALSE. A false negative
  90024. ** is harmless. A false positive, however, can result in the wrong
  90025. ** answer.
  90026. */
  90027. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  90028. u8 op;
  90029. if( aff==SQLITE_AFF_BLOB ) return 1;
  90030. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  90031. op = p->op;
  90032. if( op==TK_REGISTER ) op = p->op2;
  90033. switch( op ){
  90034. case TK_INTEGER: {
  90035. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  90036. }
  90037. case TK_FLOAT: {
  90038. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  90039. }
  90040. case TK_STRING: {
  90041. return aff==SQLITE_AFF_TEXT;
  90042. }
  90043. case TK_BLOB: {
  90044. return 1;
  90045. }
  90046. case TK_COLUMN: {
  90047. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  90048. return p->iColumn<0
  90049. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  90050. }
  90051. default: {
  90052. return 0;
  90053. }
  90054. }
  90055. }
  90056. /*
  90057. ** Return TRUE if the given string is a row-id column name.
  90058. */
  90059. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  90060. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  90061. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  90062. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  90063. return 0;
  90064. }
  90065. /*
  90066. ** pX is the RHS of an IN operator. If pX is a SELECT statement
  90067. ** that can be simplified to a direct table access, then return
  90068. ** a pointer to the SELECT statement. If pX is not a SELECT statement,
  90069. ** or if the SELECT statement needs to be manifested into a transient
  90070. ** table, then return NULL.
  90071. */
  90072. #ifndef SQLITE_OMIT_SUBQUERY
  90073. static Select *isCandidateForInOpt(Expr *pX){
  90074. Select *p;
  90075. SrcList *pSrc;
  90076. ExprList *pEList;
  90077. Table *pTab;
  90078. int i;
  90079. if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
  90080. if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
  90081. p = pX->x.pSelect;
  90082. if( p->pPrior ) return 0; /* Not a compound SELECT */
  90083. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  90084. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  90085. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  90086. return 0; /* No DISTINCT keyword and no aggregate functions */
  90087. }
  90088. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  90089. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  90090. if( p->pWhere ) return 0; /* Has no WHERE clause */
  90091. pSrc = p->pSrc;
  90092. assert( pSrc!=0 );
  90093. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  90094. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  90095. pTab = pSrc->a[0].pTab;
  90096. assert( pTab!=0 );
  90097. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  90098. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  90099. pEList = p->pEList;
  90100. assert( pEList!=0 );
  90101. /* All SELECT results must be columns. */
  90102. for(i=0; i<pEList->nExpr; i++){
  90103. Expr *pRes = pEList->a[i].pExpr;
  90104. if( pRes->op!=TK_COLUMN ) return 0;
  90105. assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
  90106. }
  90107. return p;
  90108. }
  90109. #endif /* SQLITE_OMIT_SUBQUERY */
  90110. #ifndef SQLITE_OMIT_SUBQUERY
  90111. /*
  90112. ** Generate code that checks the left-most column of index table iCur to see if
  90113. ** it contains any NULL entries. Cause the register at regHasNull to be set
  90114. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  90115. ** to be set to NULL if iCur contains one or more NULL values.
  90116. */
  90117. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  90118. int addr1;
  90119. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  90120. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  90121. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  90122. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  90123. VdbeComment((v, "first_entry_in(%d)", iCur));
  90124. sqlite3VdbeJumpHere(v, addr1);
  90125. }
  90126. #endif
  90127. #ifndef SQLITE_OMIT_SUBQUERY
  90128. /*
  90129. ** The argument is an IN operator with a list (not a subquery) on the
  90130. ** right-hand side. Return TRUE if that list is constant.
  90131. */
  90132. static int sqlite3InRhsIsConstant(Expr *pIn){
  90133. Expr *pLHS;
  90134. int res;
  90135. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  90136. pLHS = pIn->pLeft;
  90137. pIn->pLeft = 0;
  90138. res = sqlite3ExprIsConstant(pIn);
  90139. pIn->pLeft = pLHS;
  90140. return res;
  90141. }
  90142. #endif
  90143. /*
  90144. ** This function is used by the implementation of the IN (...) operator.
  90145. ** The pX parameter is the expression on the RHS of the IN operator, which
  90146. ** might be either a list of expressions or a subquery.
  90147. **
  90148. ** The job of this routine is to find or create a b-tree object that can
  90149. ** be used either to test for membership in the RHS set or to iterate through
  90150. ** all members of the RHS set, skipping duplicates.
  90151. **
  90152. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  90153. ** and pX->iTable is set to the index of that cursor.
  90154. **
  90155. ** The returned value of this function indicates the b-tree type, as follows:
  90156. **
  90157. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  90158. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  90159. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  90160. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  90161. ** populated epheremal table.
  90162. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  90163. ** implemented as a sequence of comparisons.
  90164. **
  90165. ** An existing b-tree might be used if the RHS expression pX is a simple
  90166. ** subquery such as:
  90167. **
  90168. ** SELECT <column1>, <column2>... FROM <table>
  90169. **
  90170. ** If the RHS of the IN operator is a list or a more complex subquery, then
  90171. ** an ephemeral table might need to be generated from the RHS and then
  90172. ** pX->iTable made to point to the ephemeral table instead of an
  90173. ** existing table.
  90174. **
  90175. ** The inFlags parameter must contain, at a minimum, one of the bits
  90176. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
  90177. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
  90178. ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
  90179. ** be used to loop over all values of the RHS of the IN operator.
  90180. **
  90181. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  90182. ** through the set members) then the b-tree must not contain duplicates.
  90183. ** An epheremal table will be created unless the selected columns are guaranteed
  90184. ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
  90185. ** a UNIQUE constraint or index.
  90186. **
  90187. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  90188. ** for fast set membership tests) then an epheremal table must
  90189. ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
  90190. ** index can be found with the specified <columns> as its left-most.
  90191. **
  90192. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  90193. ** if the RHS of the IN operator is a list (not a subquery) then this
  90194. ** routine might decide that creating an ephemeral b-tree for membership
  90195. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  90196. ** calling routine should implement the IN operator using a sequence
  90197. ** of Eq or Ne comparison operations.
  90198. **
  90199. ** When the b-tree is being used for membership tests, the calling function
  90200. ** might need to know whether or not the RHS side of the IN operator
  90201. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  90202. ** if there is any chance that the (...) might contain a NULL value at
  90203. ** runtime, then a register is allocated and the register number written
  90204. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  90205. ** NULL value, then *prRhsHasNull is left unchanged.
  90206. **
  90207. ** If a register is allocated and its location stored in *prRhsHasNull, then
  90208. ** the value in that register will be NULL if the b-tree contains one or more
  90209. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  90210. ** NULL values.
  90211. **
  90212. ** If the aiMap parameter is not NULL, it must point to an array containing
  90213. ** one element for each column returned by the SELECT statement on the RHS
  90214. ** of the IN(...) operator. The i'th entry of the array is populated with the
  90215. ** offset of the index column that matches the i'th column returned by the
  90216. ** SELECT. For example, if the expression and selected index are:
  90217. **
  90218. ** (?,?,?) IN (SELECT a, b, c FROM t1)
  90219. ** CREATE INDEX i1 ON t1(b, c, a);
  90220. **
  90221. ** then aiMap[] is populated with {2, 0, 1}.
  90222. */
  90223. #ifndef SQLITE_OMIT_SUBQUERY
  90224. SQLITE_PRIVATE int sqlite3FindInIndex(
  90225. Parse *pParse, /* Parsing context */
  90226. Expr *pX, /* The right-hand side (RHS) of the IN operator */
  90227. u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
  90228. int *prRhsHasNull, /* Register holding NULL status. See notes */
  90229. int *aiMap /* Mapping from Index fields to RHS fields */
  90230. ){
  90231. Select *p; /* SELECT to the right of IN operator */
  90232. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  90233. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  90234. int mustBeUnique; /* True if RHS must be unique */
  90235. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  90236. assert( pX->op==TK_IN );
  90237. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  90238. /* If the RHS of this IN(...) operator is a SELECT, and if it matters
  90239. ** whether or not the SELECT result contains NULL values, check whether
  90240. ** or not NULL is actually possible (it may not be, for example, due
  90241. ** to NOT NULL constraints in the schema). If no NULL values are possible,
  90242. ** set prRhsHasNull to 0 before continuing. */
  90243. if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
  90244. int i;
  90245. ExprList *pEList = pX->x.pSelect->pEList;
  90246. for(i=0; i<pEList->nExpr; i++){
  90247. if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
  90248. }
  90249. if( i==pEList->nExpr ){
  90250. prRhsHasNull = 0;
  90251. }
  90252. }
  90253. /* Check to see if an existing table or index can be used to
  90254. ** satisfy the query. This is preferable to generating a new
  90255. ** ephemeral table. */
  90256. if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
  90257. sqlite3 *db = pParse->db; /* Database connection */
  90258. Table *pTab; /* Table <table>. */
  90259. i16 iDb; /* Database idx for pTab */
  90260. ExprList *pEList = p->pEList;
  90261. int nExpr = pEList->nExpr;
  90262. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  90263. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  90264. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  90265. pTab = p->pSrc->a[0].pTab;
  90266. /* Code an OP_Transaction and OP_TableLock for <table>. */
  90267. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90268. sqlite3CodeVerifySchema(pParse, iDb);
  90269. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  90270. assert(v); /* sqlite3GetVdbe() has always been previously called */
  90271. if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
  90272. /* The "x IN (SELECT rowid FROM table)" case */
  90273. int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
  90274. VdbeCoverage(v);
  90275. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  90276. eType = IN_INDEX_ROWID;
  90277. sqlite3VdbeJumpHere(v, iAddr);
  90278. }else{
  90279. Index *pIdx; /* Iterator variable */
  90280. int affinity_ok = 1;
  90281. int i;
  90282. /* Check that the affinity that will be used to perform each
  90283. ** comparison is the same as the affinity of each column in table
  90284. ** on the RHS of the IN operator. If it not, it is not possible to
  90285. ** use any index of the RHS table. */
  90286. for(i=0; i<nExpr && affinity_ok; i++){
  90287. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  90288. int iCol = pEList->a[i].pExpr->iColumn;
  90289. char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
  90290. char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
  90291. testcase( cmpaff==SQLITE_AFF_BLOB );
  90292. testcase( cmpaff==SQLITE_AFF_TEXT );
  90293. switch( cmpaff ){
  90294. case SQLITE_AFF_BLOB:
  90295. break;
  90296. case SQLITE_AFF_TEXT:
  90297. /* sqlite3CompareAffinity() only returns TEXT if one side or the
  90298. ** other has no affinity and the other side is TEXT. Hence,
  90299. ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
  90300. ** and for the term on the LHS of the IN to have no affinity. */
  90301. assert( idxaff==SQLITE_AFF_TEXT );
  90302. break;
  90303. default:
  90304. affinity_ok = sqlite3IsNumericAffinity(idxaff);
  90305. }
  90306. }
  90307. if( affinity_ok ){
  90308. /* Search for an existing index that will work for this IN operator */
  90309. for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
  90310. Bitmask colUsed; /* Columns of the index used */
  90311. Bitmask mCol; /* Mask for the current column */
  90312. if( pIdx->nColumn<nExpr ) continue;
  90313. /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
  90314. ** BITMASK(nExpr) without overflowing */
  90315. testcase( pIdx->nColumn==BMS-2 );
  90316. testcase( pIdx->nColumn==BMS-1 );
  90317. if( pIdx->nColumn>=BMS-1 ) continue;
  90318. if( mustBeUnique ){
  90319. if( pIdx->nKeyCol>nExpr
  90320. ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
  90321. ){
  90322. continue; /* This index is not unique over the IN RHS columns */
  90323. }
  90324. }
  90325. colUsed = 0; /* Columns of index used so far */
  90326. for(i=0; i<nExpr; i++){
  90327. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  90328. Expr *pRhs = pEList->a[i].pExpr;
  90329. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  90330. int j;
  90331. assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
  90332. for(j=0; j<nExpr; j++){
  90333. if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
  90334. assert( pIdx->azColl[j] );
  90335. if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
  90336. continue;
  90337. }
  90338. break;
  90339. }
  90340. if( j==nExpr ) break;
  90341. mCol = MASKBIT(j);
  90342. if( mCol & colUsed ) break; /* Each column used only once */
  90343. colUsed |= mCol;
  90344. if( aiMap ) aiMap[i] = j;
  90345. }
  90346. assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
  90347. if( colUsed==(MASKBIT(nExpr)-1) ){
  90348. /* If we reach this point, that means the index pIdx is usable */
  90349. int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  90350. #ifndef SQLITE_OMIT_EXPLAIN
  90351. sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
  90352. sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
  90353. P4_DYNAMIC);
  90354. #endif
  90355. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  90356. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  90357. VdbeComment((v, "%s", pIdx->zName));
  90358. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  90359. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  90360. if( prRhsHasNull ){
  90361. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  90362. i64 mask = (1<<nExpr)-1;
  90363. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
  90364. iTab, 0, 0, (u8*)&mask, P4_INT64);
  90365. #endif
  90366. *prRhsHasNull = ++pParse->nMem;
  90367. if( nExpr==1 ){
  90368. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  90369. }
  90370. }
  90371. sqlite3VdbeJumpHere(v, iAddr);
  90372. }
  90373. } /* End loop over indexes */
  90374. } /* End if( affinity_ok ) */
  90375. } /* End if not an rowid index */
  90376. } /* End attempt to optimize using an index */
  90377. /* If no preexisting index is available for the IN clause
  90378. ** and IN_INDEX_NOOP is an allowed reply
  90379. ** and the RHS of the IN operator is a list, not a subquery
  90380. ** and the RHS is not constant or has two or fewer terms,
  90381. ** then it is not worth creating an ephemeral table to evaluate
  90382. ** the IN operator so return IN_INDEX_NOOP.
  90383. */
  90384. if( eType==0
  90385. && (inFlags & IN_INDEX_NOOP_OK)
  90386. && !ExprHasProperty(pX, EP_xIsSelect)
  90387. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  90388. ){
  90389. eType = IN_INDEX_NOOP;
  90390. }
  90391. if( eType==0 ){
  90392. /* Could not find an existing table or index to use as the RHS b-tree.
  90393. ** We will have to generate an ephemeral table to do the job.
  90394. */
  90395. u32 savedNQueryLoop = pParse->nQueryLoop;
  90396. int rMayHaveNull = 0;
  90397. eType = IN_INDEX_EPH;
  90398. if( inFlags & IN_INDEX_LOOP ){
  90399. pParse->nQueryLoop = 0;
  90400. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  90401. eType = IN_INDEX_ROWID;
  90402. }
  90403. }else if( prRhsHasNull ){
  90404. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  90405. }
  90406. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  90407. pParse->nQueryLoop = savedNQueryLoop;
  90408. }else{
  90409. pX->iTable = iTab;
  90410. }
  90411. if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
  90412. int i, n;
  90413. n = sqlite3ExprVectorSize(pX->pLeft);
  90414. for(i=0; i<n; i++) aiMap[i] = i;
  90415. }
  90416. return eType;
  90417. }
  90418. #endif
  90419. #ifndef SQLITE_OMIT_SUBQUERY
  90420. /*
  90421. ** Argument pExpr is an (?, ?...) IN(...) expression. This
  90422. ** function allocates and returns a nul-terminated string containing
  90423. ** the affinities to be used for each column of the comparison.
  90424. **
  90425. ** It is the responsibility of the caller to ensure that the returned
  90426. ** string is eventually freed using sqlite3DbFree().
  90427. */
  90428. static char *exprINAffinity(Parse *pParse, Expr *pExpr){
  90429. Expr *pLeft = pExpr->pLeft;
  90430. int nVal = sqlite3ExprVectorSize(pLeft);
  90431. Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
  90432. char *zRet;
  90433. assert( pExpr->op==TK_IN );
  90434. zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
  90435. if( zRet ){
  90436. int i;
  90437. for(i=0; i<nVal; i++){
  90438. Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
  90439. char a = sqlite3ExprAffinity(pA);
  90440. if( pSelect ){
  90441. zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
  90442. }else{
  90443. zRet[i] = a;
  90444. }
  90445. }
  90446. zRet[nVal] = '\0';
  90447. }
  90448. return zRet;
  90449. }
  90450. #endif
  90451. #ifndef SQLITE_OMIT_SUBQUERY
  90452. /*
  90453. ** Load the Parse object passed as the first argument with an error
  90454. ** message of the form:
  90455. **
  90456. ** "sub-select returns N columns - expected M"
  90457. */
  90458. SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
  90459. const char *zFmt = "sub-select returns %d columns - expected %d";
  90460. sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
  90461. }
  90462. #endif
  90463. /*
  90464. ** Expression pExpr is a vector that has been used in a context where
  90465. ** it is not permitted. If pExpr is a sub-select vector, this routine
  90466. ** loads the Parse object with a message of the form:
  90467. **
  90468. ** "sub-select returns N columns - expected 1"
  90469. **
  90470. ** Or, if it is a regular scalar vector:
  90471. **
  90472. ** "row value misused"
  90473. */
  90474. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
  90475. #ifndef SQLITE_OMIT_SUBQUERY
  90476. if( pExpr->flags & EP_xIsSelect ){
  90477. sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
  90478. }else
  90479. #endif
  90480. {
  90481. sqlite3ErrorMsg(pParse, "row value misused");
  90482. }
  90483. }
  90484. /*
  90485. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  90486. ** or IN operators. Examples:
  90487. **
  90488. ** (SELECT a FROM b) -- subquery
  90489. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  90490. ** x IN (4,5,11) -- IN operator with list on right-hand side
  90491. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  90492. **
  90493. ** The pExpr parameter describes the expression that contains the IN
  90494. ** operator or subquery.
  90495. **
  90496. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  90497. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  90498. ** to some integer key column of a table B-Tree. In this case, use an
  90499. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  90500. ** (slower) variable length keys B-Tree.
  90501. **
  90502. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  90503. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  90504. ** All this routine does is initialize the register given by rMayHaveNull
  90505. ** to NULL. Calling routines will take care of changing this register
  90506. ** value to non-NULL if the RHS is NULL-free.
  90507. **
  90508. ** For a SELECT or EXISTS operator, return the register that holds the
  90509. ** result. For a multi-column SELECT, the result is stored in a contiguous
  90510. ** array of registers and the return value is the register of the left-most
  90511. ** result column. Return 0 for IN operators or if an error occurs.
  90512. */
  90513. #ifndef SQLITE_OMIT_SUBQUERY
  90514. SQLITE_PRIVATE int sqlite3CodeSubselect(
  90515. Parse *pParse, /* Parsing context */
  90516. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  90517. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  90518. int isRowid /* If true, LHS of IN operator is a rowid */
  90519. ){
  90520. int jmpIfDynamic = -1; /* One-time test address */
  90521. int rReg = 0; /* Register storing resulting */
  90522. Vdbe *v = sqlite3GetVdbe(pParse);
  90523. if( NEVER(v==0) ) return 0;
  90524. sqlite3ExprCachePush(pParse);
  90525. /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
  90526. ** is encountered if any of the following is true:
  90527. **
  90528. ** * The right-hand side is a correlated subquery
  90529. ** * The right-hand side is an expression list containing variables
  90530. ** * We are inside a trigger
  90531. **
  90532. ** If all of the above are false, then we can run this code just once
  90533. ** save the results, and reuse the same result on subsequent invocations.
  90534. */
  90535. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  90536. jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  90537. }
  90538. #ifndef SQLITE_OMIT_EXPLAIN
  90539. if( pParse->explain==2 ){
  90540. char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
  90541. jmpIfDynamic>=0?"":"CORRELATED ",
  90542. pExpr->op==TK_IN?"LIST":"SCALAR",
  90543. pParse->iNextSelectId
  90544. );
  90545. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  90546. }
  90547. #endif
  90548. switch( pExpr->op ){
  90549. case TK_IN: {
  90550. int addr; /* Address of OP_OpenEphemeral instruction */
  90551. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  90552. KeyInfo *pKeyInfo = 0; /* Key information */
  90553. int nVal; /* Size of vector pLeft */
  90554. nVal = sqlite3ExprVectorSize(pLeft);
  90555. assert( !isRowid || nVal==1 );
  90556. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  90557. ** expression it is handled the same way. An ephemeral table is
  90558. ** filled with index keys representing the results from the
  90559. ** SELECT or the <exprlist>.
  90560. **
  90561. ** If the 'x' expression is a column value, or the SELECT...
  90562. ** statement returns a column value, then the affinity of that
  90563. ** column is used to build the index keys. If both 'x' and the
  90564. ** SELECT... statement are columns, then numeric affinity is used
  90565. ** if either column has NUMERIC or INTEGER affinity. If neither
  90566. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  90567. ** is used.
  90568. */
  90569. pExpr->iTable = pParse->nTab++;
  90570. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
  90571. pExpr->iTable, (isRowid?0:nVal));
  90572. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
  90573. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  90574. /* Case 1: expr IN (SELECT ...)
  90575. **
  90576. ** Generate code to write the results of the select into the temporary
  90577. ** table allocated and opened above.
  90578. */
  90579. Select *pSelect = pExpr->x.pSelect;
  90580. ExprList *pEList = pSelect->pEList;
  90581. assert( !isRowid );
  90582. /* If the LHS and RHS of the IN operator do not match, that
  90583. ** error will have been caught long before we reach this point. */
  90584. if( ALWAYS(pEList->nExpr==nVal) ){
  90585. SelectDest dest;
  90586. int i;
  90587. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  90588. dest.zAffSdst = exprINAffinity(pParse, pExpr);
  90589. pSelect->iLimit = 0;
  90590. testcase( pSelect->selFlags & SF_Distinct );
  90591. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  90592. if( sqlite3Select(pParse, pSelect, &dest) ){
  90593. sqlite3DbFree(pParse->db, dest.zAffSdst);
  90594. sqlite3KeyInfoUnref(pKeyInfo);
  90595. return 0;
  90596. }
  90597. sqlite3DbFree(pParse->db, dest.zAffSdst);
  90598. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  90599. assert( pEList!=0 );
  90600. assert( pEList->nExpr>0 );
  90601. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  90602. for(i=0; i<nVal; i++){
  90603. Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
  90604. pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
  90605. pParse, p, pEList->a[i].pExpr
  90606. );
  90607. }
  90608. }
  90609. }else if( ALWAYS(pExpr->x.pList!=0) ){
  90610. /* Case 2: expr IN (exprlist)
  90611. **
  90612. ** For each expression, build an index key from the evaluation and
  90613. ** store it in the temporary table. If <expr> is a column, then use
  90614. ** that columns affinity when building index keys. If <expr> is not
  90615. ** a column, use numeric affinity.
  90616. */
  90617. char affinity; /* Affinity of the LHS of the IN */
  90618. int i;
  90619. ExprList *pList = pExpr->x.pList;
  90620. struct ExprList_item *pItem;
  90621. int r1, r2, r3;
  90622. affinity = sqlite3ExprAffinity(pLeft);
  90623. if( !affinity ){
  90624. affinity = SQLITE_AFF_BLOB;
  90625. }
  90626. if( pKeyInfo ){
  90627. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  90628. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  90629. }
  90630. /* Loop through each expression in <exprlist>. */
  90631. r1 = sqlite3GetTempReg(pParse);
  90632. r2 = sqlite3GetTempReg(pParse);
  90633. if( isRowid ) sqlite3VdbeAddOp4(v, OP_Blob, 0, r2, 0, "", P4_STATIC);
  90634. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  90635. Expr *pE2 = pItem->pExpr;
  90636. int iValToIns;
  90637. /* If the expression is not constant then we will need to
  90638. ** disable the test that was generated above that makes sure
  90639. ** this code only executes once. Because for a non-constant
  90640. ** expression we need to rerun this code each time.
  90641. */
  90642. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  90643. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  90644. jmpIfDynamic = -1;
  90645. }
  90646. /* Evaluate the expression and insert it into the temp table */
  90647. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  90648. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  90649. }else{
  90650. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  90651. if( isRowid ){
  90652. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  90653. sqlite3VdbeCurrentAddr(v)+2);
  90654. VdbeCoverage(v);
  90655. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  90656. }else{
  90657. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  90658. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  90659. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
  90660. }
  90661. }
  90662. }
  90663. sqlite3ReleaseTempReg(pParse, r1);
  90664. sqlite3ReleaseTempReg(pParse, r2);
  90665. }
  90666. if( pKeyInfo ){
  90667. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  90668. }
  90669. break;
  90670. }
  90671. case TK_EXISTS:
  90672. case TK_SELECT:
  90673. default: {
  90674. /* Case 3: (SELECT ... FROM ...)
  90675. ** or: EXISTS(SELECT ... FROM ...)
  90676. **
  90677. ** For a SELECT, generate code to put the values for all columns of
  90678. ** the first row into an array of registers and return the index of
  90679. ** the first register.
  90680. **
  90681. ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
  90682. ** into a register and return that register number.
  90683. **
  90684. ** In both cases, the query is augmented with "LIMIT 1". Any
  90685. ** preexisting limit is discarded in place of the new LIMIT 1.
  90686. */
  90687. Select *pSel; /* SELECT statement to encode */
  90688. SelectDest dest; /* How to deal with SELECT result */
  90689. int nReg; /* Registers to allocate */
  90690. Expr *pLimit; /* New limit expression */
  90691. testcase( pExpr->op==TK_EXISTS );
  90692. testcase( pExpr->op==TK_SELECT );
  90693. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  90694. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  90695. pSel = pExpr->x.pSelect;
  90696. nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
  90697. sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
  90698. pParse->nMem += nReg;
  90699. if( pExpr->op==TK_SELECT ){
  90700. dest.eDest = SRT_Mem;
  90701. dest.iSdst = dest.iSDParm;
  90702. dest.nSdst = nReg;
  90703. sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
  90704. VdbeComment((v, "Init subquery result"));
  90705. }else{
  90706. dest.eDest = SRT_Exists;
  90707. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  90708. VdbeComment((v, "Init EXISTS result"));
  90709. }
  90710. pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0);
  90711. if( pSel->pLimit ){
  90712. sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft);
  90713. pSel->pLimit->pLeft = pLimit;
  90714. }else{
  90715. pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
  90716. }
  90717. pSel->iLimit = 0;
  90718. if( sqlite3Select(pParse, pSel, &dest) ){
  90719. return 0;
  90720. }
  90721. rReg = dest.iSDParm;
  90722. ExprSetVVAProperty(pExpr, EP_NoReduce);
  90723. break;
  90724. }
  90725. }
  90726. if( rHasNullFlag ){
  90727. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  90728. }
  90729. if( jmpIfDynamic>=0 ){
  90730. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  90731. }
  90732. sqlite3ExprCachePop(pParse);
  90733. return rReg;
  90734. }
  90735. #endif /* SQLITE_OMIT_SUBQUERY */
  90736. #ifndef SQLITE_OMIT_SUBQUERY
  90737. /*
  90738. ** Expr pIn is an IN(...) expression. This function checks that the
  90739. ** sub-select on the RHS of the IN() operator has the same number of
  90740. ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
  90741. ** a sub-query, that the LHS is a vector of size 1.
  90742. */
  90743. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
  90744. int nVector = sqlite3ExprVectorSize(pIn->pLeft);
  90745. if( (pIn->flags & EP_xIsSelect) ){
  90746. if( nVector!=pIn->x.pSelect->pEList->nExpr ){
  90747. sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
  90748. return 1;
  90749. }
  90750. }else if( nVector!=1 ){
  90751. sqlite3VectorErrorMsg(pParse, pIn->pLeft);
  90752. return 1;
  90753. }
  90754. return 0;
  90755. }
  90756. #endif
  90757. #ifndef SQLITE_OMIT_SUBQUERY
  90758. /*
  90759. ** Generate code for an IN expression.
  90760. **
  90761. ** x IN (SELECT ...)
  90762. ** x IN (value, value, ...)
  90763. **
  90764. ** The left-hand side (LHS) is a scalar or vector expression. The
  90765. ** right-hand side (RHS) is an array of zero or more scalar values, or a
  90766. ** subquery. If the RHS is a subquery, the number of result columns must
  90767. ** match the number of columns in the vector on the LHS. If the RHS is
  90768. ** a list of values, the LHS must be a scalar.
  90769. **
  90770. ** The IN operator is true if the LHS value is contained within the RHS.
  90771. ** The result is false if the LHS is definitely not in the RHS. The
  90772. ** result is NULL if the presence of the LHS in the RHS cannot be
  90773. ** determined due to NULLs.
  90774. **
  90775. ** This routine generates code that jumps to destIfFalse if the LHS is not
  90776. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  90777. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  90778. ** within the RHS then fall through.
  90779. **
  90780. ** See the separate in-operator.md documentation file in the canonical
  90781. ** SQLite source tree for additional information.
  90782. */
  90783. static void sqlite3ExprCodeIN(
  90784. Parse *pParse, /* Parsing and code generating context */
  90785. Expr *pExpr, /* The IN expression */
  90786. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  90787. int destIfNull /* Jump here if the results are unknown due to NULLs */
  90788. ){
  90789. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  90790. int eType; /* Type of the RHS */
  90791. int rLhs; /* Register(s) holding the LHS values */
  90792. int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
  90793. Vdbe *v; /* Statement under construction */
  90794. int *aiMap = 0; /* Map from vector field to index column */
  90795. char *zAff = 0; /* Affinity string for comparisons */
  90796. int nVector; /* Size of vectors for this IN operator */
  90797. int iDummy; /* Dummy parameter to exprCodeVector() */
  90798. Expr *pLeft; /* The LHS of the IN operator */
  90799. int i; /* loop counter */
  90800. int destStep2; /* Where to jump when NULLs seen in step 2 */
  90801. int destStep6 = 0; /* Start of code for Step 6 */
  90802. int addrTruthOp; /* Address of opcode that determines the IN is true */
  90803. int destNotNull; /* Jump here if a comparison is not true in step 6 */
  90804. int addrTop; /* Top of the step-6 loop */
  90805. pLeft = pExpr->pLeft;
  90806. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  90807. zAff = exprINAffinity(pParse, pExpr);
  90808. nVector = sqlite3ExprVectorSize(pExpr->pLeft);
  90809. aiMap = (int*)sqlite3DbMallocZero(
  90810. pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
  90811. );
  90812. if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
  90813. /* Attempt to compute the RHS. After this step, if anything other than
  90814. ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
  90815. ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
  90816. ** the RHS has not yet been coded. */
  90817. v = pParse->pVdbe;
  90818. assert( v!=0 ); /* OOM detected prior to this routine */
  90819. VdbeNoopComment((v, "begin IN expr"));
  90820. eType = sqlite3FindInIndex(pParse, pExpr,
  90821. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  90822. destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
  90823. assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
  90824. || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
  90825. );
  90826. #ifdef SQLITE_DEBUG
  90827. /* Confirm that aiMap[] contains nVector integer values between 0 and
  90828. ** nVector-1. */
  90829. for(i=0; i<nVector; i++){
  90830. int j, cnt;
  90831. for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
  90832. assert( cnt==1 );
  90833. }
  90834. #endif
  90835. /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
  90836. ** vector, then it is stored in an array of nVector registers starting
  90837. ** at r1.
  90838. **
  90839. ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
  90840. ** so that the fields are in the same order as an existing index. The
  90841. ** aiMap[] array contains a mapping from the original LHS field order to
  90842. ** the field order that matches the RHS index.
  90843. */
  90844. sqlite3ExprCachePush(pParse);
  90845. rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
  90846. for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
  90847. if( i==nVector ){
  90848. /* LHS fields are not reordered */
  90849. rLhs = rLhsOrig;
  90850. }else{
  90851. /* Need to reorder the LHS fields according to aiMap */
  90852. rLhs = sqlite3GetTempRange(pParse, nVector);
  90853. for(i=0; i<nVector; i++){
  90854. sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
  90855. }
  90856. }
  90857. /* If sqlite3FindInIndex() did not find or create an index that is
  90858. ** suitable for evaluating the IN operator, then evaluate using a
  90859. ** sequence of comparisons.
  90860. **
  90861. ** This is step (1) in the in-operator.md optimized algorithm.
  90862. */
  90863. if( eType==IN_INDEX_NOOP ){
  90864. ExprList *pList = pExpr->x.pList;
  90865. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  90866. int labelOk = sqlite3VdbeMakeLabel(v);
  90867. int r2, regToFree;
  90868. int regCkNull = 0;
  90869. int ii;
  90870. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  90871. if( destIfNull!=destIfFalse ){
  90872. regCkNull = sqlite3GetTempReg(pParse);
  90873. sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
  90874. }
  90875. for(ii=0; ii<pList->nExpr; ii++){
  90876. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  90877. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  90878. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  90879. }
  90880. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  90881. sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
  90882. (void*)pColl, P4_COLLSEQ);
  90883. VdbeCoverageIf(v, ii<pList->nExpr-1);
  90884. VdbeCoverageIf(v, ii==pList->nExpr-1);
  90885. sqlite3VdbeChangeP5(v, zAff[0]);
  90886. }else{
  90887. assert( destIfNull==destIfFalse );
  90888. sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
  90889. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  90890. sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
  90891. }
  90892. sqlite3ReleaseTempReg(pParse, regToFree);
  90893. }
  90894. if( regCkNull ){
  90895. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  90896. sqlite3VdbeGoto(v, destIfFalse);
  90897. }
  90898. sqlite3VdbeResolveLabel(v, labelOk);
  90899. sqlite3ReleaseTempReg(pParse, regCkNull);
  90900. goto sqlite3ExprCodeIN_finished;
  90901. }
  90902. /* Step 2: Check to see if the LHS contains any NULL columns. If the
  90903. ** LHS does contain NULLs then the result must be either FALSE or NULL.
  90904. ** We will then skip the binary search of the RHS.
  90905. */
  90906. if( destIfNull==destIfFalse ){
  90907. destStep2 = destIfFalse;
  90908. }else{
  90909. destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
  90910. }
  90911. for(i=0; i<nVector; i++){
  90912. Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
  90913. if( sqlite3ExprCanBeNull(p) ){
  90914. sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
  90915. VdbeCoverage(v);
  90916. }
  90917. }
  90918. /* Step 3. The LHS is now known to be non-NULL. Do the binary search
  90919. ** of the RHS using the LHS as a probe. If found, the result is
  90920. ** true.
  90921. */
  90922. if( eType==IN_INDEX_ROWID ){
  90923. /* In this case, the RHS is the ROWID of table b-tree and so we also
  90924. ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
  90925. ** into a single opcode. */
  90926. sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
  90927. VdbeCoverage(v);
  90928. addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
  90929. }else{
  90930. sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
  90931. if( destIfFalse==destIfNull ){
  90932. /* Combine Step 3 and Step 5 into a single opcode */
  90933. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
  90934. rLhs, nVector); VdbeCoverage(v);
  90935. goto sqlite3ExprCodeIN_finished;
  90936. }
  90937. /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
  90938. addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
  90939. rLhs, nVector); VdbeCoverage(v);
  90940. }
  90941. /* Step 4. If the RHS is known to be non-NULL and we did not find
  90942. ** an match on the search above, then the result must be FALSE.
  90943. */
  90944. if( rRhsHasNull && nVector==1 ){
  90945. sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
  90946. VdbeCoverage(v);
  90947. }
  90948. /* Step 5. If we do not care about the difference between NULL and
  90949. ** FALSE, then just return false.
  90950. */
  90951. if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
  90952. /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
  90953. ** If any comparison is NULL, then the result is NULL. If all
  90954. ** comparisons are FALSE then the final result is FALSE.
  90955. **
  90956. ** For a scalar LHS, it is sufficient to check just the first row
  90957. ** of the RHS.
  90958. */
  90959. if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
  90960. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  90961. VdbeCoverage(v);
  90962. if( nVector>1 ){
  90963. destNotNull = sqlite3VdbeMakeLabel(v);
  90964. }else{
  90965. /* For nVector==1, combine steps 6 and 7 by immediately returning
  90966. ** FALSE if the first comparison is not NULL */
  90967. destNotNull = destIfFalse;
  90968. }
  90969. for(i=0; i<nVector; i++){
  90970. Expr *p;
  90971. CollSeq *pColl;
  90972. int r3 = sqlite3GetTempReg(pParse);
  90973. p = sqlite3VectorFieldSubexpr(pLeft, i);
  90974. pColl = sqlite3ExprCollSeq(pParse, p);
  90975. sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
  90976. sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
  90977. (void*)pColl, P4_COLLSEQ);
  90978. VdbeCoverage(v);
  90979. sqlite3ReleaseTempReg(pParse, r3);
  90980. }
  90981. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  90982. if( nVector>1 ){
  90983. sqlite3VdbeResolveLabel(v, destNotNull);
  90984. sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
  90985. VdbeCoverage(v);
  90986. /* Step 7: If we reach this point, we know that the result must
  90987. ** be false. */
  90988. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  90989. }
  90990. /* Jumps here in order to return true. */
  90991. sqlite3VdbeJumpHere(v, addrTruthOp);
  90992. sqlite3ExprCodeIN_finished:
  90993. if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
  90994. sqlite3ExprCachePop(pParse);
  90995. VdbeComment((v, "end IN expr"));
  90996. sqlite3ExprCodeIN_oom_error:
  90997. sqlite3DbFree(pParse->db, aiMap);
  90998. sqlite3DbFree(pParse->db, zAff);
  90999. }
  91000. #endif /* SQLITE_OMIT_SUBQUERY */
  91001. #ifndef SQLITE_OMIT_FLOATING_POINT
  91002. /*
  91003. ** Generate an instruction that will put the floating point
  91004. ** value described by z[0..n-1] into register iMem.
  91005. **
  91006. ** The z[] string will probably not be zero-terminated. But the
  91007. ** z[n] character is guaranteed to be something that does not look
  91008. ** like the continuation of the number.
  91009. */
  91010. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  91011. if( ALWAYS(z!=0) ){
  91012. double value;
  91013. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  91014. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  91015. if( negateFlag ) value = -value;
  91016. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  91017. }
  91018. }
  91019. #endif
  91020. /*
  91021. ** Generate an instruction that will put the integer describe by
  91022. ** text z[0..n-1] into register iMem.
  91023. **
  91024. ** Expr.u.zToken is always UTF8 and zero-terminated.
  91025. */
  91026. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  91027. Vdbe *v = pParse->pVdbe;
  91028. if( pExpr->flags & EP_IntValue ){
  91029. int i = pExpr->u.iValue;
  91030. assert( i>=0 );
  91031. if( negFlag ) i = -i;
  91032. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  91033. }else{
  91034. int c;
  91035. i64 value;
  91036. const char *z = pExpr->u.zToken;
  91037. assert( z!=0 );
  91038. c = sqlite3DecOrHexToI64(z, &value);
  91039. if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
  91040. #ifdef SQLITE_OMIT_FLOATING_POINT
  91041. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  91042. #else
  91043. #ifndef SQLITE_OMIT_HEX_INTEGER
  91044. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  91045. sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
  91046. }else
  91047. #endif
  91048. {
  91049. codeReal(v, z, negFlag, iMem);
  91050. }
  91051. #endif
  91052. }else{
  91053. if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
  91054. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  91055. }
  91056. }
  91057. }
  91058. /*
  91059. ** Erase column-cache entry number i
  91060. */
  91061. static void cacheEntryClear(Parse *pParse, int i){
  91062. if( pParse->aColCache[i].tempReg ){
  91063. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  91064. pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
  91065. }
  91066. }
  91067. pParse->nColCache--;
  91068. if( i<pParse->nColCache ){
  91069. pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
  91070. }
  91071. }
  91072. /*
  91073. ** Record in the column cache that a particular column from a
  91074. ** particular table is stored in a particular register.
  91075. */
  91076. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  91077. int i;
  91078. int minLru;
  91079. int idxLru;
  91080. struct yColCache *p;
  91081. /* Unless an error has occurred, register numbers are always positive. */
  91082. assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
  91083. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  91084. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  91085. ** for testing only - to verify that SQLite always gets the same answer
  91086. ** with and without the column cache.
  91087. */
  91088. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  91089. /* First replace any existing entry.
  91090. **
  91091. ** Actually, the way the column cache is currently used, we are guaranteed
  91092. ** that the object will never already be in cache. Verify this guarantee.
  91093. */
  91094. #ifndef NDEBUG
  91095. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  91096. assert( p->iTable!=iTab || p->iColumn!=iCol );
  91097. }
  91098. #endif
  91099. /* If the cache is already full, delete the least recently used entry */
  91100. if( pParse->nColCache>=SQLITE_N_COLCACHE ){
  91101. minLru = 0x7fffffff;
  91102. idxLru = -1;
  91103. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  91104. if( p->lru<minLru ){
  91105. idxLru = i;
  91106. minLru = p->lru;
  91107. }
  91108. }
  91109. p = &pParse->aColCache[idxLru];
  91110. }else{
  91111. p = &pParse->aColCache[pParse->nColCache++];
  91112. }
  91113. /* Add the new entry to the end of the cache */
  91114. p->iLevel = pParse->iCacheLevel;
  91115. p->iTable = iTab;
  91116. p->iColumn = iCol;
  91117. p->iReg = iReg;
  91118. p->tempReg = 0;
  91119. p->lru = pParse->iCacheCnt++;
  91120. }
  91121. /*
  91122. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  91123. ** Purge the range of registers from the column cache.
  91124. */
  91125. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  91126. int i = 0;
  91127. while( i<pParse->nColCache ){
  91128. struct yColCache *p = &pParse->aColCache[i];
  91129. if( p->iReg >= iReg && p->iReg < iReg+nReg ){
  91130. cacheEntryClear(pParse, i);
  91131. }else{
  91132. i++;
  91133. }
  91134. }
  91135. }
  91136. /*
  91137. ** Remember the current column cache context. Any new entries added
  91138. ** added to the column cache after this call are removed when the
  91139. ** corresponding pop occurs.
  91140. */
  91141. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  91142. pParse->iCacheLevel++;
  91143. #ifdef SQLITE_DEBUG
  91144. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  91145. printf("PUSH to %d\n", pParse->iCacheLevel);
  91146. }
  91147. #endif
  91148. }
  91149. /*
  91150. ** Remove from the column cache any entries that were added since the
  91151. ** the previous sqlite3ExprCachePush operation. In other words, restore
  91152. ** the cache to the state it was in prior the most recent Push.
  91153. */
  91154. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  91155. int i = 0;
  91156. assert( pParse->iCacheLevel>=1 );
  91157. pParse->iCacheLevel--;
  91158. #ifdef SQLITE_DEBUG
  91159. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  91160. printf("POP to %d\n", pParse->iCacheLevel);
  91161. }
  91162. #endif
  91163. while( i<pParse->nColCache ){
  91164. if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
  91165. cacheEntryClear(pParse, i);
  91166. }else{
  91167. i++;
  91168. }
  91169. }
  91170. }
  91171. /*
  91172. ** When a cached column is reused, make sure that its register is
  91173. ** no longer available as a temp register. ticket #3879: that same
  91174. ** register might be in the cache in multiple places, so be sure to
  91175. ** get them all.
  91176. */
  91177. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  91178. int i;
  91179. struct yColCache *p;
  91180. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  91181. if( p->iReg==iReg ){
  91182. p->tempReg = 0;
  91183. }
  91184. }
  91185. }
  91186. /* Generate code that will load into register regOut a value that is
  91187. ** appropriate for the iIdxCol-th column of index pIdx.
  91188. */
  91189. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  91190. Parse *pParse, /* The parsing context */
  91191. Index *pIdx, /* The index whose column is to be loaded */
  91192. int iTabCur, /* Cursor pointing to a table row */
  91193. int iIdxCol, /* The column of the index to be loaded */
  91194. int regOut /* Store the index column value in this register */
  91195. ){
  91196. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  91197. if( iTabCol==XN_EXPR ){
  91198. assert( pIdx->aColExpr );
  91199. assert( pIdx->aColExpr->nExpr>iIdxCol );
  91200. pParse->iSelfTab = iTabCur + 1;
  91201. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  91202. pParse->iSelfTab = 0;
  91203. }else{
  91204. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  91205. iTabCol, regOut);
  91206. }
  91207. }
  91208. /*
  91209. ** Generate code to extract the value of the iCol-th column of a table.
  91210. */
  91211. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  91212. Vdbe *v, /* The VDBE under construction */
  91213. Table *pTab, /* The table containing the value */
  91214. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  91215. int iCol, /* Index of the column to extract */
  91216. int regOut /* Extract the value into this register */
  91217. ){
  91218. if( pTab==0 ){
  91219. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
  91220. return;
  91221. }
  91222. if( iCol<0 || iCol==pTab->iPKey ){
  91223. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  91224. }else{
  91225. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  91226. int x = iCol;
  91227. if( !HasRowid(pTab) && !IsVirtual(pTab) ){
  91228. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  91229. }
  91230. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  91231. }
  91232. if( iCol>=0 ){
  91233. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  91234. }
  91235. }
  91236. /*
  91237. ** Generate code that will extract the iColumn-th column from
  91238. ** table pTab and store the column value in a register.
  91239. **
  91240. ** An effort is made to store the column value in register iReg. This
  91241. ** is not garanteeed for GetColumn() - the result can be stored in
  91242. ** any register. But the result is guaranteed to land in register iReg
  91243. ** for GetColumnToReg().
  91244. **
  91245. ** There must be an open cursor to pTab in iTable when this routine
  91246. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  91247. */
  91248. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  91249. Parse *pParse, /* Parsing and code generating context */
  91250. Table *pTab, /* Description of the table we are reading from */
  91251. int iColumn, /* Index of the table column */
  91252. int iTable, /* The cursor pointing to the table */
  91253. int iReg, /* Store results here */
  91254. u8 p5 /* P5 value for OP_Column + FLAGS */
  91255. ){
  91256. Vdbe *v = pParse->pVdbe;
  91257. int i;
  91258. struct yColCache *p;
  91259. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  91260. if( p->iTable==iTable && p->iColumn==iColumn ){
  91261. p->lru = pParse->iCacheCnt++;
  91262. sqlite3ExprCachePinRegister(pParse, p->iReg);
  91263. return p->iReg;
  91264. }
  91265. }
  91266. assert( v!=0 );
  91267. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  91268. if( p5 ){
  91269. sqlite3VdbeChangeP5(v, p5);
  91270. }else{
  91271. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  91272. }
  91273. return iReg;
  91274. }
  91275. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(
  91276. Parse *pParse, /* Parsing and code generating context */
  91277. Table *pTab, /* Description of the table we are reading from */
  91278. int iColumn, /* Index of the table column */
  91279. int iTable, /* The cursor pointing to the table */
  91280. int iReg /* Store results here */
  91281. ){
  91282. int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
  91283. if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
  91284. }
  91285. /*
  91286. ** Clear all column cache entries.
  91287. */
  91288. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  91289. int i;
  91290. #ifdef SQLITE_DEBUG
  91291. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  91292. printf("CLEAR\n");
  91293. }
  91294. #endif
  91295. for(i=0; i<pParse->nColCache; i++){
  91296. if( pParse->aColCache[i].tempReg
  91297. && pParse->nTempReg<ArraySize(pParse->aTempReg)
  91298. ){
  91299. pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
  91300. }
  91301. }
  91302. pParse->nColCache = 0;
  91303. }
  91304. /*
  91305. ** Record the fact that an affinity change has occurred on iCount
  91306. ** registers starting with iStart.
  91307. */
  91308. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  91309. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  91310. }
  91311. /*
  91312. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  91313. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  91314. */
  91315. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  91316. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  91317. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  91318. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  91319. }
  91320. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  91321. /*
  91322. ** Return true if any register in the range iFrom..iTo (inclusive)
  91323. ** is used as part of the column cache.
  91324. **
  91325. ** This routine is used within assert() and testcase() macros only
  91326. ** and does not appear in a normal build.
  91327. */
  91328. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  91329. int i;
  91330. struct yColCache *p;
  91331. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  91332. int r = p->iReg;
  91333. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  91334. }
  91335. return 0;
  91336. }
  91337. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  91338. /*
  91339. ** Convert a scalar expression node to a TK_REGISTER referencing
  91340. ** register iReg. The caller must ensure that iReg already contains
  91341. ** the correct value for the expression.
  91342. */
  91343. static void exprToRegister(Expr *p, int iReg){
  91344. p->op2 = p->op;
  91345. p->op = TK_REGISTER;
  91346. p->iTable = iReg;
  91347. ExprClearProperty(p, EP_Skip);
  91348. }
  91349. /*
  91350. ** Evaluate an expression (either a vector or a scalar expression) and store
  91351. ** the result in continguous temporary registers. Return the index of
  91352. ** the first register used to store the result.
  91353. **
  91354. ** If the returned result register is a temporary scalar, then also write
  91355. ** that register number into *piFreeable. If the returned result register
  91356. ** is not a temporary or if the expression is a vector set *piFreeable
  91357. ** to 0.
  91358. */
  91359. static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
  91360. int iResult;
  91361. int nResult = sqlite3ExprVectorSize(p);
  91362. if( nResult==1 ){
  91363. iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
  91364. }else{
  91365. *piFreeable = 0;
  91366. if( p->op==TK_SELECT ){
  91367. #if SQLITE_OMIT_SUBQUERY
  91368. iResult = 0;
  91369. #else
  91370. iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
  91371. #endif
  91372. }else{
  91373. int i;
  91374. iResult = pParse->nMem+1;
  91375. pParse->nMem += nResult;
  91376. for(i=0; i<nResult; i++){
  91377. sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
  91378. }
  91379. }
  91380. }
  91381. return iResult;
  91382. }
  91383. /*
  91384. ** Generate code into the current Vdbe to evaluate the given
  91385. ** expression. Attempt to store the results in register "target".
  91386. ** Return the register where results are stored.
  91387. **
  91388. ** With this routine, there is no guarantee that results will
  91389. ** be stored in target. The result might be stored in some other
  91390. ** register if it is convenient to do so. The calling function
  91391. ** must check the return code and move the results to the desired
  91392. ** register.
  91393. */
  91394. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  91395. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  91396. int op; /* The opcode being coded */
  91397. int inReg = target; /* Results stored in register inReg */
  91398. int regFree1 = 0; /* If non-zero free this temporary register */
  91399. int regFree2 = 0; /* If non-zero free this temporary register */
  91400. int r1, r2; /* Various register numbers */
  91401. Expr tempX; /* Temporary expression node */
  91402. int p5 = 0;
  91403. assert( target>0 && target<=pParse->nMem );
  91404. if( v==0 ){
  91405. assert( pParse->db->mallocFailed );
  91406. return 0;
  91407. }
  91408. if( pExpr==0 ){
  91409. op = TK_NULL;
  91410. }else{
  91411. op = pExpr->op;
  91412. }
  91413. switch( op ){
  91414. case TK_AGG_COLUMN: {
  91415. AggInfo *pAggInfo = pExpr->pAggInfo;
  91416. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  91417. if( !pAggInfo->directMode ){
  91418. assert( pCol->iMem>0 );
  91419. return pCol->iMem;
  91420. }else if( pAggInfo->useSortingIdx ){
  91421. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  91422. pCol->iSorterColumn, target);
  91423. return target;
  91424. }
  91425. /* Otherwise, fall thru into the TK_COLUMN case */
  91426. }
  91427. case TK_COLUMN: {
  91428. int iTab = pExpr->iTable;
  91429. if( iTab<0 ){
  91430. if( pParse->iSelfTab<0 ){
  91431. /* Generating CHECK constraints or inserting into partial index */
  91432. return pExpr->iColumn - pParse->iSelfTab;
  91433. }else{
  91434. /* Coding an expression that is part of an index where column names
  91435. ** in the index refer to the table to which the index belongs */
  91436. iTab = pParse->iSelfTab - 1;
  91437. }
  91438. }
  91439. return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  91440. pExpr->iColumn, iTab, target,
  91441. pExpr->op2);
  91442. }
  91443. case TK_INTEGER: {
  91444. codeInteger(pParse, pExpr, 0, target);
  91445. return target;
  91446. }
  91447. case TK_TRUEFALSE: {
  91448. sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
  91449. return target;
  91450. }
  91451. #ifndef SQLITE_OMIT_FLOATING_POINT
  91452. case TK_FLOAT: {
  91453. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  91454. codeReal(v, pExpr->u.zToken, 0, target);
  91455. return target;
  91456. }
  91457. #endif
  91458. case TK_STRING: {
  91459. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  91460. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  91461. return target;
  91462. }
  91463. case TK_NULL: {
  91464. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  91465. return target;
  91466. }
  91467. #ifndef SQLITE_OMIT_BLOB_LITERAL
  91468. case TK_BLOB: {
  91469. int n;
  91470. const char *z;
  91471. char *zBlob;
  91472. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  91473. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  91474. assert( pExpr->u.zToken[1]=='\'' );
  91475. z = &pExpr->u.zToken[2];
  91476. n = sqlite3Strlen30(z) - 1;
  91477. assert( z[n]=='\'' );
  91478. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  91479. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  91480. return target;
  91481. }
  91482. #endif
  91483. case TK_VARIABLE: {
  91484. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  91485. assert( pExpr->u.zToken!=0 );
  91486. assert( pExpr->u.zToken[0]!=0 );
  91487. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  91488. if( pExpr->u.zToken[1]!=0 ){
  91489. const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
  91490. assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
  91491. pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
  91492. sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
  91493. }
  91494. return target;
  91495. }
  91496. case TK_REGISTER: {
  91497. return pExpr->iTable;
  91498. }
  91499. #ifndef SQLITE_OMIT_CAST
  91500. case TK_CAST: {
  91501. /* Expressions of the form: CAST(pLeft AS token) */
  91502. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  91503. if( inReg!=target ){
  91504. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  91505. inReg = target;
  91506. }
  91507. sqlite3VdbeAddOp2(v, OP_Cast, target,
  91508. sqlite3AffinityType(pExpr->u.zToken, 0));
  91509. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  91510. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  91511. return inReg;
  91512. }
  91513. #endif /* SQLITE_OMIT_CAST */
  91514. case TK_IS:
  91515. case TK_ISNOT:
  91516. op = (op==TK_IS) ? TK_EQ : TK_NE;
  91517. p5 = SQLITE_NULLEQ;
  91518. /* fall-through */
  91519. case TK_LT:
  91520. case TK_LE:
  91521. case TK_GT:
  91522. case TK_GE:
  91523. case TK_NE:
  91524. case TK_EQ: {
  91525. Expr *pLeft = pExpr->pLeft;
  91526. if( sqlite3ExprIsVector(pLeft) ){
  91527. codeVectorCompare(pParse, pExpr, target, op, p5);
  91528. }else{
  91529. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  91530. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  91531. codeCompare(pParse, pLeft, pExpr->pRight, op,
  91532. r1, r2, inReg, SQLITE_STOREP2 | p5);
  91533. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  91534. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  91535. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  91536. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  91537. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  91538. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  91539. testcase( regFree1==0 );
  91540. testcase( regFree2==0 );
  91541. }
  91542. break;
  91543. }
  91544. case TK_AND:
  91545. case TK_OR:
  91546. case TK_PLUS:
  91547. case TK_STAR:
  91548. case TK_MINUS:
  91549. case TK_REM:
  91550. case TK_BITAND:
  91551. case TK_BITOR:
  91552. case TK_SLASH:
  91553. case TK_LSHIFT:
  91554. case TK_RSHIFT:
  91555. case TK_CONCAT: {
  91556. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  91557. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  91558. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  91559. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  91560. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  91561. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  91562. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  91563. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  91564. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  91565. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  91566. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  91567. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  91568. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  91569. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  91570. testcase( regFree1==0 );
  91571. testcase( regFree2==0 );
  91572. break;
  91573. }
  91574. case TK_UMINUS: {
  91575. Expr *pLeft = pExpr->pLeft;
  91576. assert( pLeft );
  91577. if( pLeft->op==TK_INTEGER ){
  91578. codeInteger(pParse, pLeft, 1, target);
  91579. return target;
  91580. #ifndef SQLITE_OMIT_FLOATING_POINT
  91581. }else if( pLeft->op==TK_FLOAT ){
  91582. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  91583. codeReal(v, pLeft->u.zToken, 1, target);
  91584. return target;
  91585. #endif
  91586. }else{
  91587. tempX.op = TK_INTEGER;
  91588. tempX.flags = EP_IntValue|EP_TokenOnly;
  91589. tempX.u.iValue = 0;
  91590. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  91591. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  91592. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  91593. testcase( regFree2==0 );
  91594. }
  91595. break;
  91596. }
  91597. case TK_BITNOT:
  91598. case TK_NOT: {
  91599. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  91600. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  91601. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  91602. testcase( regFree1==0 );
  91603. sqlite3VdbeAddOp2(v, op, r1, inReg);
  91604. break;
  91605. }
  91606. case TK_TRUTH: {
  91607. int isTrue; /* IS TRUE or IS NOT TRUE */
  91608. int bNormal; /* IS TRUE or IS FALSE */
  91609. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  91610. testcase( regFree1==0 );
  91611. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  91612. bNormal = pExpr->op2==TK_IS;
  91613. testcase( isTrue && bNormal);
  91614. testcase( !isTrue && bNormal);
  91615. sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
  91616. break;
  91617. }
  91618. case TK_ISNULL:
  91619. case TK_NOTNULL: {
  91620. int addr;
  91621. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  91622. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  91623. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  91624. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  91625. testcase( regFree1==0 );
  91626. addr = sqlite3VdbeAddOp1(v, op, r1);
  91627. VdbeCoverageIf(v, op==TK_ISNULL);
  91628. VdbeCoverageIf(v, op==TK_NOTNULL);
  91629. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  91630. sqlite3VdbeJumpHere(v, addr);
  91631. break;
  91632. }
  91633. case TK_AGG_FUNCTION: {
  91634. AggInfo *pInfo = pExpr->pAggInfo;
  91635. if( pInfo==0 ){
  91636. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  91637. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  91638. }else{
  91639. return pInfo->aFunc[pExpr->iAgg].iMem;
  91640. }
  91641. break;
  91642. }
  91643. case TK_FUNCTION: {
  91644. ExprList *pFarg; /* List of function arguments */
  91645. int nFarg; /* Number of function arguments */
  91646. FuncDef *pDef; /* The function definition object */
  91647. const char *zId; /* The function name */
  91648. u32 constMask = 0; /* Mask of function arguments that are constant */
  91649. int i; /* Loop counter */
  91650. sqlite3 *db = pParse->db; /* The database connection */
  91651. u8 enc = ENC(db); /* The text encoding used by this database */
  91652. CollSeq *pColl = 0; /* A collating sequence */
  91653. if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
  91654. /* SQL functions can be expensive. So try to move constant functions
  91655. ** out of the inner loop, even if that means an extra OP_Copy. */
  91656. return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  91657. }
  91658. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  91659. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  91660. pFarg = 0;
  91661. }else{
  91662. pFarg = pExpr->x.pList;
  91663. }
  91664. nFarg = pFarg ? pFarg->nExpr : 0;
  91665. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  91666. zId = pExpr->u.zToken;
  91667. pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
  91668. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  91669. if( pDef==0 && pParse->explain ){
  91670. pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
  91671. }
  91672. #endif
  91673. if( pDef==0 || pDef->xFinalize!=0 ){
  91674. sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
  91675. break;
  91676. }
  91677. /* Attempt a direct implementation of the built-in COALESCE() and
  91678. ** IFNULL() functions. This avoids unnecessary evaluation of
  91679. ** arguments past the first non-NULL argument.
  91680. */
  91681. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  91682. int endCoalesce = sqlite3VdbeMakeLabel(v);
  91683. assert( nFarg>=2 );
  91684. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  91685. for(i=1; i<nFarg; i++){
  91686. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  91687. VdbeCoverage(v);
  91688. sqlite3ExprCacheRemove(pParse, target, 1);
  91689. sqlite3ExprCachePush(pParse);
  91690. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  91691. sqlite3ExprCachePop(pParse);
  91692. }
  91693. sqlite3VdbeResolveLabel(v, endCoalesce);
  91694. break;
  91695. }
  91696. /* The UNLIKELY() function is a no-op. The result is the value
  91697. ** of the first argument.
  91698. */
  91699. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  91700. assert( nFarg>=1 );
  91701. return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  91702. }
  91703. #ifdef SQLITE_DEBUG
  91704. /* The AFFINITY() function evaluates to a string that describes
  91705. ** the type affinity of the argument. This is used for testing of
  91706. ** the SQLite type logic.
  91707. */
  91708. if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
  91709. const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
  91710. char aff;
  91711. assert( nFarg==1 );
  91712. aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
  91713. sqlite3VdbeLoadString(v, target,
  91714. aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
  91715. return target;
  91716. }
  91717. #endif
  91718. for(i=0; i<nFarg; i++){
  91719. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  91720. testcase( i==31 );
  91721. constMask |= MASKBIT32(i);
  91722. }
  91723. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  91724. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  91725. }
  91726. }
  91727. if( pFarg ){
  91728. if( constMask ){
  91729. r1 = pParse->nMem+1;
  91730. pParse->nMem += nFarg;
  91731. }else{
  91732. r1 = sqlite3GetTempRange(pParse, nFarg);
  91733. }
  91734. /* For length() and typeof() functions with a column argument,
  91735. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  91736. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  91737. ** loading.
  91738. */
  91739. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  91740. u8 exprOp;
  91741. assert( nFarg==1 );
  91742. assert( pFarg->a[0].pExpr!=0 );
  91743. exprOp = pFarg->a[0].pExpr->op;
  91744. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  91745. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  91746. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  91747. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  91748. pFarg->a[0].pExpr->op2 =
  91749. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  91750. }
  91751. }
  91752. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  91753. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  91754. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  91755. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  91756. }else{
  91757. r1 = 0;
  91758. }
  91759. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91760. /* Possibly overload the function if the first argument is
  91761. ** a virtual table column.
  91762. **
  91763. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  91764. ** second argument, not the first, as the argument to test to
  91765. ** see if it is a column in a virtual table. This is done because
  91766. ** the left operand of infix functions (the operand we want to
  91767. ** control overloading) ends up as the second argument to the
  91768. ** function. The expression "A glob B" is equivalent to
  91769. ** "glob(B,A). We want to use the A in "A glob B" to test
  91770. ** for function overloading. But we use the B term in "glob(B,A)".
  91771. */
  91772. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  91773. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  91774. }else if( nFarg>0 ){
  91775. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  91776. }
  91777. #endif
  91778. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  91779. if( !pColl ) pColl = db->pDfltColl;
  91780. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  91781. }
  91782. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  91783. if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
  91784. Expr *pArg = pFarg->a[0].pExpr;
  91785. if( pArg->op==TK_COLUMN ){
  91786. sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
  91787. }else{
  91788. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  91789. }
  91790. }else
  91791. #endif
  91792. {
  91793. sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
  91794. constMask, r1, target, (char*)pDef, P4_FUNCDEF);
  91795. sqlite3VdbeChangeP5(v, (u8)nFarg);
  91796. }
  91797. if( nFarg && constMask==0 ){
  91798. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  91799. }
  91800. return target;
  91801. }
  91802. #ifndef SQLITE_OMIT_SUBQUERY
  91803. case TK_EXISTS:
  91804. case TK_SELECT: {
  91805. int nCol;
  91806. testcase( op==TK_EXISTS );
  91807. testcase( op==TK_SELECT );
  91808. if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
  91809. sqlite3SubselectError(pParse, nCol, 1);
  91810. }else{
  91811. return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  91812. }
  91813. break;
  91814. }
  91815. case TK_SELECT_COLUMN: {
  91816. int n;
  91817. if( pExpr->pLeft->iTable==0 ){
  91818. pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
  91819. }
  91820. assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
  91821. if( pExpr->iTable
  91822. && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
  91823. ){
  91824. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  91825. pExpr->iTable, n);
  91826. }
  91827. return pExpr->pLeft->iTable + pExpr->iColumn;
  91828. }
  91829. case TK_IN: {
  91830. int destIfFalse = sqlite3VdbeMakeLabel(v);
  91831. int destIfNull = sqlite3VdbeMakeLabel(v);
  91832. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  91833. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  91834. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  91835. sqlite3VdbeResolveLabel(v, destIfFalse);
  91836. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  91837. sqlite3VdbeResolveLabel(v, destIfNull);
  91838. return target;
  91839. }
  91840. #endif /* SQLITE_OMIT_SUBQUERY */
  91841. /*
  91842. ** x BETWEEN y AND z
  91843. **
  91844. ** This is equivalent to
  91845. **
  91846. ** x>=y AND x<=z
  91847. **
  91848. ** X is stored in pExpr->pLeft.
  91849. ** Y is stored in pExpr->pList->a[0].pExpr.
  91850. ** Z is stored in pExpr->pList->a[1].pExpr.
  91851. */
  91852. case TK_BETWEEN: {
  91853. exprCodeBetween(pParse, pExpr, target, 0, 0);
  91854. return target;
  91855. }
  91856. case TK_SPAN:
  91857. case TK_COLLATE:
  91858. case TK_UPLUS: {
  91859. return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  91860. }
  91861. case TK_TRIGGER: {
  91862. /* If the opcode is TK_TRIGGER, then the expression is a reference
  91863. ** to a column in the new.* or old.* pseudo-tables available to
  91864. ** trigger programs. In this case Expr.iTable is set to 1 for the
  91865. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  91866. ** is set to the column of the pseudo-table to read, or to -1 to
  91867. ** read the rowid field.
  91868. **
  91869. ** The expression is implemented using an OP_Param opcode. The p1
  91870. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  91871. ** to reference another column of the old.* pseudo-table, where
  91872. ** i is the index of the column. For a new.rowid reference, p1 is
  91873. ** set to (n+1), where n is the number of columns in each pseudo-table.
  91874. ** For a reference to any other column in the new.* pseudo-table, p1
  91875. ** is set to (n+2+i), where n and i are as defined previously. For
  91876. ** example, if the table on which triggers are being fired is
  91877. ** declared as:
  91878. **
  91879. ** CREATE TABLE t1(a, b);
  91880. **
  91881. ** Then p1 is interpreted as follows:
  91882. **
  91883. ** p1==0 -> old.rowid p1==3 -> new.rowid
  91884. ** p1==1 -> old.a p1==4 -> new.a
  91885. ** p1==2 -> old.b p1==5 -> new.b
  91886. */
  91887. Table *pTab = pExpr->pTab;
  91888. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  91889. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  91890. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  91891. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  91892. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  91893. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  91894. VdbeComment((v, "%s.%s -> $%d",
  91895. (pExpr->iTable ? "new" : "old"),
  91896. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  91897. target
  91898. ));
  91899. #ifndef SQLITE_OMIT_FLOATING_POINT
  91900. /* If the column has REAL affinity, it may currently be stored as an
  91901. ** integer. Use OP_RealAffinity to make sure it is really real.
  91902. **
  91903. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  91904. ** floating point when extracting it from the record. */
  91905. if( pExpr->iColumn>=0
  91906. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  91907. ){
  91908. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  91909. }
  91910. #endif
  91911. break;
  91912. }
  91913. case TK_VECTOR: {
  91914. sqlite3ErrorMsg(pParse, "row value misused");
  91915. break;
  91916. }
  91917. case TK_IF_NULL_ROW: {
  91918. int addrINR;
  91919. addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
  91920. sqlite3ExprCachePush(pParse);
  91921. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  91922. sqlite3ExprCachePop(pParse);
  91923. sqlite3VdbeJumpHere(v, addrINR);
  91924. sqlite3VdbeChangeP3(v, addrINR, inReg);
  91925. break;
  91926. }
  91927. /*
  91928. ** Form A:
  91929. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  91930. **
  91931. ** Form B:
  91932. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  91933. **
  91934. ** Form A is can be transformed into the equivalent form B as follows:
  91935. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  91936. ** WHEN x=eN THEN rN ELSE y END
  91937. **
  91938. ** X (if it exists) is in pExpr->pLeft.
  91939. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  91940. ** odd. The Y is also optional. If the number of elements in x.pList
  91941. ** is even, then Y is omitted and the "otherwise" result is NULL.
  91942. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  91943. **
  91944. ** The result of the expression is the Ri for the first matching Ei,
  91945. ** or if there is no matching Ei, the ELSE term Y, or if there is
  91946. ** no ELSE term, NULL.
  91947. */
  91948. default: assert( op==TK_CASE ); {
  91949. int endLabel; /* GOTO label for end of CASE stmt */
  91950. int nextCase; /* GOTO label for next WHEN clause */
  91951. int nExpr; /* 2x number of WHEN terms */
  91952. int i; /* Loop counter */
  91953. ExprList *pEList; /* List of WHEN terms */
  91954. struct ExprList_item *aListelem; /* Array of WHEN terms */
  91955. Expr opCompare; /* The X==Ei expression */
  91956. Expr *pX; /* The X expression */
  91957. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  91958. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  91959. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  91960. assert(pExpr->x.pList->nExpr > 0);
  91961. pEList = pExpr->x.pList;
  91962. aListelem = pEList->a;
  91963. nExpr = pEList->nExpr;
  91964. endLabel = sqlite3VdbeMakeLabel(v);
  91965. if( (pX = pExpr->pLeft)!=0 ){
  91966. tempX = *pX;
  91967. testcase( pX->op==TK_COLUMN );
  91968. exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
  91969. testcase( regFree1==0 );
  91970. memset(&opCompare, 0, sizeof(opCompare));
  91971. opCompare.op = TK_EQ;
  91972. opCompare.pLeft = &tempX;
  91973. pTest = &opCompare;
  91974. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  91975. ** The value in regFree1 might get SCopy-ed into the file result.
  91976. ** So make sure that the regFree1 register is not reused for other
  91977. ** purposes and possibly overwritten. */
  91978. regFree1 = 0;
  91979. }
  91980. for(i=0; i<nExpr-1; i=i+2){
  91981. sqlite3ExprCachePush(pParse);
  91982. if( pX ){
  91983. assert( pTest!=0 );
  91984. opCompare.pRight = aListelem[i].pExpr;
  91985. }else{
  91986. pTest = aListelem[i].pExpr;
  91987. }
  91988. nextCase = sqlite3VdbeMakeLabel(v);
  91989. testcase( pTest->op==TK_COLUMN );
  91990. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  91991. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  91992. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  91993. sqlite3VdbeGoto(v, endLabel);
  91994. sqlite3ExprCachePop(pParse);
  91995. sqlite3VdbeResolveLabel(v, nextCase);
  91996. }
  91997. if( (nExpr&1)!=0 ){
  91998. sqlite3ExprCachePush(pParse);
  91999. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  92000. sqlite3ExprCachePop(pParse);
  92001. }else{
  92002. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  92003. }
  92004. assert( pParse->db->mallocFailed || pParse->nErr>0
  92005. || pParse->iCacheLevel==iCacheLevel );
  92006. sqlite3VdbeResolveLabel(v, endLabel);
  92007. break;
  92008. }
  92009. #ifndef SQLITE_OMIT_TRIGGER
  92010. case TK_RAISE: {
  92011. assert( pExpr->affinity==OE_Rollback
  92012. || pExpr->affinity==OE_Abort
  92013. || pExpr->affinity==OE_Fail
  92014. || pExpr->affinity==OE_Ignore
  92015. );
  92016. if( !pParse->pTriggerTab ){
  92017. sqlite3ErrorMsg(pParse,
  92018. "RAISE() may only be used within a trigger-program");
  92019. return 0;
  92020. }
  92021. if( pExpr->affinity==OE_Abort ){
  92022. sqlite3MayAbort(pParse);
  92023. }
  92024. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  92025. if( pExpr->affinity==OE_Ignore ){
  92026. sqlite3VdbeAddOp4(
  92027. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  92028. VdbeCoverage(v);
  92029. }else{
  92030. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  92031. pExpr->affinity, pExpr->u.zToken, 0, 0);
  92032. }
  92033. break;
  92034. }
  92035. #endif
  92036. }
  92037. sqlite3ReleaseTempReg(pParse, regFree1);
  92038. sqlite3ReleaseTempReg(pParse, regFree2);
  92039. return inReg;
  92040. }
  92041. /*
  92042. ** Factor out the code of the given expression to initialization time.
  92043. **
  92044. ** If regDest>=0 then the result is always stored in that register and the
  92045. ** result is not reusable. If regDest<0 then this routine is free to
  92046. ** store the value whereever it wants. The register where the expression
  92047. ** is stored is returned. When regDest<0, two identical expressions will
  92048. ** code to the same register.
  92049. */
  92050. SQLITE_PRIVATE int sqlite3ExprCodeAtInit(
  92051. Parse *pParse, /* Parsing context */
  92052. Expr *pExpr, /* The expression to code when the VDBE initializes */
  92053. int regDest /* Store the value in this register */
  92054. ){
  92055. ExprList *p;
  92056. assert( ConstFactorOk(pParse) );
  92057. p = pParse->pConstExpr;
  92058. if( regDest<0 && p ){
  92059. struct ExprList_item *pItem;
  92060. int i;
  92061. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  92062. if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
  92063. return pItem->u.iConstExprReg;
  92064. }
  92065. }
  92066. }
  92067. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  92068. p = sqlite3ExprListAppend(pParse, p, pExpr);
  92069. if( p ){
  92070. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  92071. pItem->reusable = regDest<0;
  92072. if( regDest<0 ) regDest = ++pParse->nMem;
  92073. pItem->u.iConstExprReg = regDest;
  92074. }
  92075. pParse->pConstExpr = p;
  92076. return regDest;
  92077. }
  92078. /*
  92079. ** Generate code to evaluate an expression and store the results
  92080. ** into a register. Return the register number where the results
  92081. ** are stored.
  92082. **
  92083. ** If the register is a temporary register that can be deallocated,
  92084. ** then write its number into *pReg. If the result register is not
  92085. ** a temporary, then set *pReg to zero.
  92086. **
  92087. ** If pExpr is a constant, then this routine might generate this
  92088. ** code to fill the register in the initialization section of the
  92089. ** VDBE program, in order to factor it out of the evaluation loop.
  92090. */
  92091. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  92092. int r2;
  92093. pExpr = sqlite3ExprSkipCollate(pExpr);
  92094. if( ConstFactorOk(pParse)
  92095. && pExpr->op!=TK_REGISTER
  92096. && sqlite3ExprIsConstantNotJoin(pExpr)
  92097. ){
  92098. *pReg = 0;
  92099. r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
  92100. }else{
  92101. int r1 = sqlite3GetTempReg(pParse);
  92102. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  92103. if( r2==r1 ){
  92104. *pReg = r1;
  92105. }else{
  92106. sqlite3ReleaseTempReg(pParse, r1);
  92107. *pReg = 0;
  92108. }
  92109. }
  92110. return r2;
  92111. }
  92112. /*
  92113. ** Generate code that will evaluate expression pExpr and store the
  92114. ** results in register target. The results are guaranteed to appear
  92115. ** in register target.
  92116. */
  92117. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  92118. int inReg;
  92119. assert( target>0 && target<=pParse->nMem );
  92120. if( pExpr && pExpr->op==TK_REGISTER ){
  92121. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  92122. }else{
  92123. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  92124. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  92125. if( inReg!=target && pParse->pVdbe ){
  92126. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  92127. }
  92128. }
  92129. }
  92130. /*
  92131. ** Make a transient copy of expression pExpr and then code it using
  92132. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  92133. ** except that the input expression is guaranteed to be unchanged.
  92134. */
  92135. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  92136. sqlite3 *db = pParse->db;
  92137. pExpr = sqlite3ExprDup(db, pExpr, 0);
  92138. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  92139. sqlite3ExprDelete(db, pExpr);
  92140. }
  92141. /*
  92142. ** Generate code that will evaluate expression pExpr and store the
  92143. ** results in register target. The results are guaranteed to appear
  92144. ** in register target. If the expression is constant, then this routine
  92145. ** might choose to code the expression at initialization time.
  92146. */
  92147. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  92148. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  92149. sqlite3ExprCodeAtInit(pParse, pExpr, target);
  92150. }else{
  92151. sqlite3ExprCode(pParse, pExpr, target);
  92152. }
  92153. }
  92154. /*
  92155. ** Generate code that evaluates the given expression and puts the result
  92156. ** in register target.
  92157. **
  92158. ** Also make a copy of the expression results into another "cache" register
  92159. ** and modify the expression so that the next time it is evaluated,
  92160. ** the result is a copy of the cache register.
  92161. **
  92162. ** This routine is used for expressions that are used multiple
  92163. ** times. They are evaluated once and the results of the expression
  92164. ** are reused.
  92165. */
  92166. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  92167. Vdbe *v = pParse->pVdbe;
  92168. int iMem;
  92169. assert( target>0 );
  92170. assert( pExpr->op!=TK_REGISTER );
  92171. sqlite3ExprCode(pParse, pExpr, target);
  92172. iMem = ++pParse->nMem;
  92173. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  92174. exprToRegister(pExpr, iMem);
  92175. }
  92176. /*
  92177. ** Generate code that pushes the value of every element of the given
  92178. ** expression list into a sequence of registers beginning at target.
  92179. **
  92180. ** Return the number of elements evaluated. The number returned will
  92181. ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
  92182. ** is defined.
  92183. **
  92184. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  92185. ** filled using OP_SCopy. OP_Copy must be used instead.
  92186. **
  92187. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  92188. ** factored out into initialization code.
  92189. **
  92190. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  92191. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  92192. ** in registers at srcReg, and so the value can be copied from there.
  92193. ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
  92194. ** are simply omitted rather than being copied from srcReg.
  92195. */
  92196. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  92197. Parse *pParse, /* Parsing context */
  92198. ExprList *pList, /* The expression list to be coded */
  92199. int target, /* Where to write results */
  92200. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  92201. u8 flags /* SQLITE_ECEL_* flags */
  92202. ){
  92203. struct ExprList_item *pItem;
  92204. int i, j, n;
  92205. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  92206. Vdbe *v = pParse->pVdbe;
  92207. assert( pList!=0 );
  92208. assert( target>0 );
  92209. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  92210. n = pList->nExpr;
  92211. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  92212. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  92213. Expr *pExpr = pItem->pExpr;
  92214. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
  92215. if( flags & SQLITE_ECEL_OMITREF ){
  92216. i--;
  92217. n--;
  92218. }else{
  92219. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  92220. }
  92221. }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  92222. sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
  92223. }else{
  92224. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  92225. if( inReg!=target+i ){
  92226. VdbeOp *pOp;
  92227. if( copyOp==OP_Copy
  92228. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  92229. && pOp->p1+pOp->p3+1==inReg
  92230. && pOp->p2+pOp->p3+1==target+i
  92231. ){
  92232. pOp->p3++;
  92233. }else{
  92234. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  92235. }
  92236. }
  92237. }
  92238. }
  92239. return n;
  92240. }
  92241. /*
  92242. ** Generate code for a BETWEEN operator.
  92243. **
  92244. ** x BETWEEN y AND z
  92245. **
  92246. ** The above is equivalent to
  92247. **
  92248. ** x>=y AND x<=z
  92249. **
  92250. ** Code it as such, taking care to do the common subexpression
  92251. ** elimination of x.
  92252. **
  92253. ** The xJumpIf parameter determines details:
  92254. **
  92255. ** NULL: Store the boolean result in reg[dest]
  92256. ** sqlite3ExprIfTrue: Jump to dest if true
  92257. ** sqlite3ExprIfFalse: Jump to dest if false
  92258. **
  92259. ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
  92260. */
  92261. static void exprCodeBetween(
  92262. Parse *pParse, /* Parsing and code generating context */
  92263. Expr *pExpr, /* The BETWEEN expression */
  92264. int dest, /* Jump destination or storage location */
  92265. void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
  92266. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  92267. ){
  92268. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  92269. Expr compLeft; /* The x>=y term */
  92270. Expr compRight; /* The x<=z term */
  92271. Expr exprX; /* The x subexpression */
  92272. int regFree1 = 0; /* Temporary use register */
  92273. memset(&compLeft, 0, sizeof(Expr));
  92274. memset(&compRight, 0, sizeof(Expr));
  92275. memset(&exprAnd, 0, sizeof(Expr));
  92276. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  92277. exprX = *pExpr->pLeft;
  92278. exprAnd.op = TK_AND;
  92279. exprAnd.pLeft = &compLeft;
  92280. exprAnd.pRight = &compRight;
  92281. compLeft.op = TK_GE;
  92282. compLeft.pLeft = &exprX;
  92283. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  92284. compRight.op = TK_LE;
  92285. compRight.pLeft = &exprX;
  92286. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  92287. exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
  92288. if( xJump ){
  92289. xJump(pParse, &exprAnd, dest, jumpIfNull);
  92290. }else{
  92291. /* Mark the expression is being from the ON or USING clause of a join
  92292. ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
  92293. ** it into the Parse.pConstExpr list. We should use a new bit for this,
  92294. ** for clarity, but we are out of bits in the Expr.flags field so we
  92295. ** have to reuse the EP_FromJoin bit. Bummer. */
  92296. exprX.flags |= EP_FromJoin;
  92297. sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
  92298. }
  92299. sqlite3ReleaseTempReg(pParse, regFree1);
  92300. /* Ensure adequate test coverage */
  92301. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
  92302. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
  92303. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
  92304. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
  92305. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
  92306. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
  92307. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
  92308. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
  92309. testcase( xJump==0 );
  92310. }
  92311. /*
  92312. ** Generate code for a boolean expression such that a jump is made
  92313. ** to the label "dest" if the expression is true but execution
  92314. ** continues straight thru if the expression is false.
  92315. **
  92316. ** If the expression evaluates to NULL (neither true nor false), then
  92317. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  92318. **
  92319. ** This code depends on the fact that certain token values (ex: TK_EQ)
  92320. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  92321. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  92322. ** the make process cause these values to align. Assert()s in the code
  92323. ** below verify that the numbers are aligned correctly.
  92324. */
  92325. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  92326. Vdbe *v = pParse->pVdbe;
  92327. int op = 0;
  92328. int regFree1 = 0;
  92329. int regFree2 = 0;
  92330. int r1, r2;
  92331. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  92332. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  92333. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  92334. op = pExpr->op;
  92335. switch( op ){
  92336. case TK_AND: {
  92337. int d2 = sqlite3VdbeMakeLabel(v);
  92338. testcase( jumpIfNull==0 );
  92339. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  92340. sqlite3ExprCachePush(pParse);
  92341. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  92342. sqlite3VdbeResolveLabel(v, d2);
  92343. sqlite3ExprCachePop(pParse);
  92344. break;
  92345. }
  92346. case TK_OR: {
  92347. testcase( jumpIfNull==0 );
  92348. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  92349. sqlite3ExprCachePush(pParse);
  92350. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  92351. sqlite3ExprCachePop(pParse);
  92352. break;
  92353. }
  92354. case TK_NOT: {
  92355. testcase( jumpIfNull==0 );
  92356. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  92357. break;
  92358. }
  92359. case TK_TRUTH: {
  92360. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  92361. int isTrue; /* IS TRUE or IS NOT TRUE */
  92362. testcase( jumpIfNull==0 );
  92363. isNot = pExpr->op2==TK_ISNOT;
  92364. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  92365. testcase( isTrue && isNot );
  92366. testcase( !isTrue && isNot );
  92367. if( isTrue ^ isNot ){
  92368. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  92369. isNot ? SQLITE_JUMPIFNULL : 0);
  92370. }else{
  92371. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  92372. isNot ? SQLITE_JUMPIFNULL : 0);
  92373. }
  92374. break;
  92375. }
  92376. case TK_IS:
  92377. case TK_ISNOT:
  92378. testcase( op==TK_IS );
  92379. testcase( op==TK_ISNOT );
  92380. op = (op==TK_IS) ? TK_EQ : TK_NE;
  92381. jumpIfNull = SQLITE_NULLEQ;
  92382. /* Fall thru */
  92383. case TK_LT:
  92384. case TK_LE:
  92385. case TK_GT:
  92386. case TK_GE:
  92387. case TK_NE:
  92388. case TK_EQ: {
  92389. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  92390. testcase( jumpIfNull==0 );
  92391. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  92392. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  92393. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  92394. r1, r2, dest, jumpIfNull);
  92395. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  92396. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  92397. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  92398. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  92399. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  92400. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  92401. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  92402. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  92403. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  92404. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  92405. testcase( regFree1==0 );
  92406. testcase( regFree2==0 );
  92407. break;
  92408. }
  92409. case TK_ISNULL:
  92410. case TK_NOTNULL: {
  92411. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  92412. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  92413. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  92414. sqlite3VdbeAddOp2(v, op, r1, dest);
  92415. VdbeCoverageIf(v, op==TK_ISNULL);
  92416. VdbeCoverageIf(v, op==TK_NOTNULL);
  92417. testcase( regFree1==0 );
  92418. break;
  92419. }
  92420. case TK_BETWEEN: {
  92421. testcase( jumpIfNull==0 );
  92422. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
  92423. break;
  92424. }
  92425. #ifndef SQLITE_OMIT_SUBQUERY
  92426. case TK_IN: {
  92427. int destIfFalse = sqlite3VdbeMakeLabel(v);
  92428. int destIfNull = jumpIfNull ? dest : destIfFalse;
  92429. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  92430. sqlite3VdbeGoto(v, dest);
  92431. sqlite3VdbeResolveLabel(v, destIfFalse);
  92432. break;
  92433. }
  92434. #endif
  92435. default: {
  92436. default_expr:
  92437. if( exprAlwaysTrue(pExpr) ){
  92438. sqlite3VdbeGoto(v, dest);
  92439. }else if( exprAlwaysFalse(pExpr) ){
  92440. /* No-op */
  92441. }else{
  92442. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  92443. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  92444. VdbeCoverage(v);
  92445. testcase( regFree1==0 );
  92446. testcase( jumpIfNull==0 );
  92447. }
  92448. break;
  92449. }
  92450. }
  92451. sqlite3ReleaseTempReg(pParse, regFree1);
  92452. sqlite3ReleaseTempReg(pParse, regFree2);
  92453. }
  92454. /*
  92455. ** Generate code for a boolean expression such that a jump is made
  92456. ** to the label "dest" if the expression is false but execution
  92457. ** continues straight thru if the expression is true.
  92458. **
  92459. ** If the expression evaluates to NULL (neither true nor false) then
  92460. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  92461. ** is 0.
  92462. */
  92463. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  92464. Vdbe *v = pParse->pVdbe;
  92465. int op = 0;
  92466. int regFree1 = 0;
  92467. int regFree2 = 0;
  92468. int r1, r2;
  92469. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  92470. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  92471. if( pExpr==0 ) return;
  92472. /* The value of pExpr->op and op are related as follows:
  92473. **
  92474. ** pExpr->op op
  92475. ** --------- ----------
  92476. ** TK_ISNULL OP_NotNull
  92477. ** TK_NOTNULL OP_IsNull
  92478. ** TK_NE OP_Eq
  92479. ** TK_EQ OP_Ne
  92480. ** TK_GT OP_Le
  92481. ** TK_LE OP_Gt
  92482. ** TK_GE OP_Lt
  92483. ** TK_LT OP_Ge
  92484. **
  92485. ** For other values of pExpr->op, op is undefined and unused.
  92486. ** The value of TK_ and OP_ constants are arranged such that we
  92487. ** can compute the mapping above using the following expression.
  92488. ** Assert()s verify that the computation is correct.
  92489. */
  92490. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  92491. /* Verify correct alignment of TK_ and OP_ constants
  92492. */
  92493. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  92494. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  92495. assert( pExpr->op!=TK_NE || op==OP_Eq );
  92496. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  92497. assert( pExpr->op!=TK_LT || op==OP_Ge );
  92498. assert( pExpr->op!=TK_LE || op==OP_Gt );
  92499. assert( pExpr->op!=TK_GT || op==OP_Le );
  92500. assert( pExpr->op!=TK_GE || op==OP_Lt );
  92501. switch( pExpr->op ){
  92502. case TK_AND: {
  92503. testcase( jumpIfNull==0 );
  92504. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  92505. sqlite3ExprCachePush(pParse);
  92506. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  92507. sqlite3ExprCachePop(pParse);
  92508. break;
  92509. }
  92510. case TK_OR: {
  92511. int d2 = sqlite3VdbeMakeLabel(v);
  92512. testcase( jumpIfNull==0 );
  92513. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  92514. sqlite3ExprCachePush(pParse);
  92515. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  92516. sqlite3VdbeResolveLabel(v, d2);
  92517. sqlite3ExprCachePop(pParse);
  92518. break;
  92519. }
  92520. case TK_NOT: {
  92521. testcase( jumpIfNull==0 );
  92522. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  92523. break;
  92524. }
  92525. case TK_TRUTH: {
  92526. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  92527. int isTrue; /* IS TRUE or IS NOT TRUE */
  92528. testcase( jumpIfNull==0 );
  92529. isNot = pExpr->op2==TK_ISNOT;
  92530. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  92531. testcase( isTrue && isNot );
  92532. testcase( !isTrue && isNot );
  92533. if( isTrue ^ isNot ){
  92534. /* IS TRUE and IS NOT FALSE */
  92535. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  92536. isNot ? 0 : SQLITE_JUMPIFNULL);
  92537. }else{
  92538. /* IS FALSE and IS NOT TRUE */
  92539. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  92540. isNot ? 0 : SQLITE_JUMPIFNULL);
  92541. }
  92542. break;
  92543. }
  92544. case TK_IS:
  92545. case TK_ISNOT:
  92546. testcase( pExpr->op==TK_IS );
  92547. testcase( pExpr->op==TK_ISNOT );
  92548. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  92549. jumpIfNull = SQLITE_NULLEQ;
  92550. /* Fall thru */
  92551. case TK_LT:
  92552. case TK_LE:
  92553. case TK_GT:
  92554. case TK_GE:
  92555. case TK_NE:
  92556. case TK_EQ: {
  92557. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  92558. testcase( jumpIfNull==0 );
  92559. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  92560. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  92561. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  92562. r1, r2, dest, jumpIfNull);
  92563. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  92564. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  92565. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  92566. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  92567. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  92568. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  92569. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  92570. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  92571. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  92572. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  92573. testcase( regFree1==0 );
  92574. testcase( regFree2==0 );
  92575. break;
  92576. }
  92577. case TK_ISNULL:
  92578. case TK_NOTNULL: {
  92579. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  92580. sqlite3VdbeAddOp2(v, op, r1, dest);
  92581. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  92582. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  92583. testcase( regFree1==0 );
  92584. break;
  92585. }
  92586. case TK_BETWEEN: {
  92587. testcase( jumpIfNull==0 );
  92588. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
  92589. break;
  92590. }
  92591. #ifndef SQLITE_OMIT_SUBQUERY
  92592. case TK_IN: {
  92593. if( jumpIfNull ){
  92594. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  92595. }else{
  92596. int destIfNull = sqlite3VdbeMakeLabel(v);
  92597. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  92598. sqlite3VdbeResolveLabel(v, destIfNull);
  92599. }
  92600. break;
  92601. }
  92602. #endif
  92603. default: {
  92604. default_expr:
  92605. if( exprAlwaysFalse(pExpr) ){
  92606. sqlite3VdbeGoto(v, dest);
  92607. }else if( exprAlwaysTrue(pExpr) ){
  92608. /* no-op */
  92609. }else{
  92610. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  92611. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  92612. VdbeCoverage(v);
  92613. testcase( regFree1==0 );
  92614. testcase( jumpIfNull==0 );
  92615. }
  92616. break;
  92617. }
  92618. }
  92619. sqlite3ReleaseTempReg(pParse, regFree1);
  92620. sqlite3ReleaseTempReg(pParse, regFree2);
  92621. }
  92622. /*
  92623. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  92624. ** code generation, and that copy is deleted after code generation. This
  92625. ** ensures that the original pExpr is unchanged.
  92626. */
  92627. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  92628. sqlite3 *db = pParse->db;
  92629. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  92630. if( db->mallocFailed==0 ){
  92631. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  92632. }
  92633. sqlite3ExprDelete(db, pCopy);
  92634. }
  92635. /*
  92636. ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
  92637. ** type of expression.
  92638. **
  92639. ** If pExpr is a simple SQL value - an integer, real, string, blob
  92640. ** or NULL value - then the VDBE currently being prepared is configured
  92641. ** to re-prepare each time a new value is bound to variable pVar.
  92642. **
  92643. ** Additionally, if pExpr is a simple SQL value and the value is the
  92644. ** same as that currently bound to variable pVar, non-zero is returned.
  92645. ** Otherwise, if the values are not the same or if pExpr is not a simple
  92646. ** SQL value, zero is returned.
  92647. */
  92648. static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
  92649. int res = 0;
  92650. int iVar;
  92651. sqlite3_value *pL, *pR = 0;
  92652. sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
  92653. if( pR ){
  92654. iVar = pVar->iColumn;
  92655. sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
  92656. pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
  92657. if( pL ){
  92658. if( sqlite3_value_type(pL)==SQLITE_TEXT ){
  92659. sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
  92660. }
  92661. res = 0==sqlite3MemCompare(pL, pR, 0);
  92662. }
  92663. sqlite3ValueFree(pR);
  92664. sqlite3ValueFree(pL);
  92665. }
  92666. return res;
  92667. }
  92668. /*
  92669. ** Do a deep comparison of two expression trees. Return 0 if the two
  92670. ** expressions are completely identical. Return 1 if they differ only
  92671. ** by a COLLATE operator at the top level. Return 2 if there are differences
  92672. ** other than the top-level COLLATE operator.
  92673. **
  92674. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  92675. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  92676. **
  92677. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  92678. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  92679. **
  92680. ** Sometimes this routine will return 2 even if the two expressions
  92681. ** really are equivalent. If we cannot prove that the expressions are
  92682. ** identical, we return 2 just to be safe. So if this routine
  92683. ** returns 2, then you do not really know for certain if the two
  92684. ** expressions are the same. But if you get a 0 or 1 return, then you
  92685. ** can be sure the expressions are the same. In the places where
  92686. ** this routine is used, it does not hurt to get an extra 2 - that
  92687. ** just might result in some slightly slower code. But returning
  92688. ** an incorrect 0 or 1 could lead to a malfunction.
  92689. **
  92690. ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
  92691. ** pParse->pReprepare can be matched against literals in pB. The
  92692. ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
  92693. ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
  92694. ** Argument pParse should normally be NULL. If it is not NULL and pA or
  92695. ** pB causes a return value of 2.
  92696. */
  92697. SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
  92698. u32 combinedFlags;
  92699. if( pA==0 || pB==0 ){
  92700. return pB==pA ? 0 : 2;
  92701. }
  92702. if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
  92703. return 0;
  92704. }
  92705. combinedFlags = pA->flags | pB->flags;
  92706. if( combinedFlags & EP_IntValue ){
  92707. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  92708. return 0;
  92709. }
  92710. return 2;
  92711. }
  92712. if( pA->op!=pB->op ){
  92713. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
  92714. return 1;
  92715. }
  92716. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
  92717. return 1;
  92718. }
  92719. return 2;
  92720. }
  92721. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  92722. if( pA->op==TK_FUNCTION ){
  92723. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  92724. }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  92725. return pA->op==TK_COLLATE ? 1 : 2;
  92726. }
  92727. }
  92728. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  92729. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  92730. if( combinedFlags & EP_xIsSelect ) return 2;
  92731. if( sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
  92732. if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
  92733. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  92734. if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
  92735. if( pA->iColumn!=pB->iColumn ) return 2;
  92736. if( pA->iTable!=pB->iTable
  92737. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  92738. }
  92739. }
  92740. return 0;
  92741. }
  92742. /*
  92743. ** Compare two ExprList objects. Return 0 if they are identical and
  92744. ** non-zero if they differ in any way.
  92745. **
  92746. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  92747. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  92748. **
  92749. ** This routine might return non-zero for equivalent ExprLists. The
  92750. ** only consequence will be disabled optimizations. But this routine
  92751. ** must never return 0 if the two ExprList objects are different, or
  92752. ** a malfunction will result.
  92753. **
  92754. ** Two NULL pointers are considered to be the same. But a NULL pointer
  92755. ** always differs from a non-NULL pointer.
  92756. */
  92757. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  92758. int i;
  92759. if( pA==0 && pB==0 ) return 0;
  92760. if( pA==0 || pB==0 ) return 1;
  92761. if( pA->nExpr!=pB->nExpr ) return 1;
  92762. for(i=0; i<pA->nExpr; i++){
  92763. Expr *pExprA = pA->a[i].pExpr;
  92764. Expr *pExprB = pB->a[i].pExpr;
  92765. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  92766. if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
  92767. }
  92768. return 0;
  92769. }
  92770. /*
  92771. ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
  92772. ** are ignored.
  92773. */
  92774. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
  92775. return sqlite3ExprCompare(0,
  92776. sqlite3ExprSkipCollate(pA),
  92777. sqlite3ExprSkipCollate(pB),
  92778. iTab);
  92779. }
  92780. /*
  92781. ** Return true if we can prove the pE2 will always be true if pE1 is
  92782. ** true. Return false if we cannot complete the proof or if pE2 might
  92783. ** be false. Examples:
  92784. **
  92785. ** pE1: x==5 pE2: x==5 Result: true
  92786. ** pE1: x>0 pE2: x==5 Result: false
  92787. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  92788. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  92789. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  92790. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  92791. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  92792. **
  92793. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  92794. ** Expr.iTable<0 then assume a table number given by iTab.
  92795. **
  92796. ** If pParse is not NULL, then the values of bound variables in pE1 are
  92797. ** compared against literal values in pE2 and pParse->pVdbe->expmask is
  92798. ** modified to record which bound variables are referenced. If pParse
  92799. ** is NULL, then false will be returned if pE1 contains any bound variables.
  92800. **
  92801. ** When in doubt, return false. Returning true might give a performance
  92802. ** improvement. Returning false might cause a performance reduction, but
  92803. ** it will always give the correct answer and is hence always safe.
  92804. */
  92805. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
  92806. if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
  92807. return 1;
  92808. }
  92809. if( pE2->op==TK_OR
  92810. && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
  92811. || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
  92812. ){
  92813. return 1;
  92814. }
  92815. if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
  92816. Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
  92817. testcase( pX!=pE1->pLeft );
  92818. if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
  92819. }
  92820. return 0;
  92821. }
  92822. /*
  92823. ** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
  92824. ** If the expression node requires that the table at pWalker->iCur
  92825. ** have a non-NULL column, then set pWalker->eCode to 1 and abort.
  92826. */
  92827. static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
  92828. /* This routine is only called for WHERE clause expressions and so it
  92829. ** cannot have any TK_AGG_COLUMN entries because those are only found
  92830. ** in HAVING clauses. We can get a TK_AGG_FUNCTION in a WHERE clause,
  92831. ** but that is an illegal construct and the query will be rejected at
  92832. ** a later stage of processing, so the TK_AGG_FUNCTION case does not
  92833. ** need to be considered here. */
  92834. assert( pExpr->op!=TK_AGG_COLUMN );
  92835. testcase( pExpr->op==TK_AGG_FUNCTION );
  92836. if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
  92837. switch( pExpr->op ){
  92838. case TK_ISNOT:
  92839. case TK_NOT:
  92840. case TK_ISNULL:
  92841. case TK_IS:
  92842. case TK_OR:
  92843. case TK_CASE:
  92844. case TK_IN:
  92845. case TK_FUNCTION:
  92846. testcase( pExpr->op==TK_ISNOT );
  92847. testcase( pExpr->op==TK_NOT );
  92848. testcase( pExpr->op==TK_ISNULL );
  92849. testcase( pExpr->op==TK_IS );
  92850. testcase( pExpr->op==TK_OR );
  92851. testcase( pExpr->op==TK_CASE );
  92852. testcase( pExpr->op==TK_IN );
  92853. testcase( pExpr->op==TK_FUNCTION );
  92854. return WRC_Prune;
  92855. case TK_COLUMN:
  92856. if( pWalker->u.iCur==pExpr->iTable ){
  92857. pWalker->eCode = 1;
  92858. return WRC_Abort;
  92859. }
  92860. return WRC_Prune;
  92861. /* Virtual tables are allowed to use constraints like x=NULL. So
  92862. ** a term of the form x=y does not prove that y is not null if x
  92863. ** is the column of a virtual table */
  92864. case TK_EQ:
  92865. case TK_NE:
  92866. case TK_LT:
  92867. case TK_LE:
  92868. case TK_GT:
  92869. case TK_GE:
  92870. testcase( pExpr->op==TK_EQ );
  92871. testcase( pExpr->op==TK_NE );
  92872. testcase( pExpr->op==TK_LT );
  92873. testcase( pExpr->op==TK_LE );
  92874. testcase( pExpr->op==TK_GT );
  92875. testcase( pExpr->op==TK_GE );
  92876. if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->pTab))
  92877. || (pExpr->pRight->op==TK_COLUMN && IsVirtual(pExpr->pRight->pTab))
  92878. ){
  92879. return WRC_Prune;
  92880. }
  92881. default:
  92882. return WRC_Continue;
  92883. }
  92884. }
  92885. /*
  92886. ** Return true (non-zero) if expression p can only be true if at least
  92887. ** one column of table iTab is non-null. In other words, return true
  92888. ** if expression p will always be NULL or false if every column of iTab
  92889. ** is NULL.
  92890. **
  92891. ** False negatives are acceptable. In other words, it is ok to return
  92892. ** zero even if expression p will never be true of every column of iTab
  92893. ** is NULL. A false negative is merely a missed optimization opportunity.
  92894. **
  92895. ** False positives are not allowed, however. A false positive may result
  92896. ** in an incorrect answer.
  92897. **
  92898. ** Terms of p that are marked with EP_FromJoin (and hence that come from
  92899. ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
  92900. **
  92901. ** This routine is used to check if a LEFT JOIN can be converted into
  92902. ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
  92903. ** clause requires that some column of the right table of the LEFT JOIN
  92904. ** be non-NULL, then the LEFT JOIN can be safely converted into an
  92905. ** ordinary join.
  92906. */
  92907. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
  92908. Walker w;
  92909. w.xExprCallback = impliesNotNullRow;
  92910. w.xSelectCallback = 0;
  92911. w.xSelectCallback2 = 0;
  92912. w.eCode = 0;
  92913. w.u.iCur = iTab;
  92914. sqlite3WalkExpr(&w, p);
  92915. return w.eCode;
  92916. }
  92917. /*
  92918. ** An instance of the following structure is used by the tree walker
  92919. ** to determine if an expression can be evaluated by reference to the
  92920. ** index only, without having to do a search for the corresponding
  92921. ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
  92922. ** is the cursor for the table.
  92923. */
  92924. struct IdxCover {
  92925. Index *pIdx; /* The index to be tested for coverage */
  92926. int iCur; /* Cursor number for the table corresponding to the index */
  92927. };
  92928. /*
  92929. ** Check to see if there are references to columns in table
  92930. ** pWalker->u.pIdxCover->iCur can be satisfied using the index
  92931. ** pWalker->u.pIdxCover->pIdx.
  92932. */
  92933. static int exprIdxCover(Walker *pWalker, Expr *pExpr){
  92934. if( pExpr->op==TK_COLUMN
  92935. && pExpr->iTable==pWalker->u.pIdxCover->iCur
  92936. && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
  92937. ){
  92938. pWalker->eCode = 1;
  92939. return WRC_Abort;
  92940. }
  92941. return WRC_Continue;
  92942. }
  92943. /*
  92944. ** Determine if an index pIdx on table with cursor iCur contains will
  92945. ** the expression pExpr. Return true if the index does cover the
  92946. ** expression and false if the pExpr expression references table columns
  92947. ** that are not found in the index pIdx.
  92948. **
  92949. ** An index covering an expression means that the expression can be
  92950. ** evaluated using only the index and without having to lookup the
  92951. ** corresponding table entry.
  92952. */
  92953. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
  92954. Expr *pExpr, /* The index to be tested */
  92955. int iCur, /* The cursor number for the corresponding table */
  92956. Index *pIdx /* The index that might be used for coverage */
  92957. ){
  92958. Walker w;
  92959. struct IdxCover xcov;
  92960. memset(&w, 0, sizeof(w));
  92961. xcov.iCur = iCur;
  92962. xcov.pIdx = pIdx;
  92963. w.xExprCallback = exprIdxCover;
  92964. w.u.pIdxCover = &xcov;
  92965. sqlite3WalkExpr(&w, pExpr);
  92966. return !w.eCode;
  92967. }
  92968. /*
  92969. ** An instance of the following structure is used by the tree walker
  92970. ** to count references to table columns in the arguments of an
  92971. ** aggregate function, in order to implement the
  92972. ** sqlite3FunctionThisSrc() routine.
  92973. */
  92974. struct SrcCount {
  92975. SrcList *pSrc; /* One particular FROM clause in a nested query */
  92976. int nThis; /* Number of references to columns in pSrcList */
  92977. int nOther; /* Number of references to columns in other FROM clauses */
  92978. };
  92979. /*
  92980. ** Count the number of references to columns.
  92981. */
  92982. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  92983. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  92984. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  92985. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  92986. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  92987. ** NEVER() will need to be removed. */
  92988. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  92989. int i;
  92990. struct SrcCount *p = pWalker->u.pSrcCount;
  92991. SrcList *pSrc = p->pSrc;
  92992. int nSrc = pSrc ? pSrc->nSrc : 0;
  92993. for(i=0; i<nSrc; i++){
  92994. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  92995. }
  92996. if( i<nSrc ){
  92997. p->nThis++;
  92998. }else{
  92999. p->nOther++;
  93000. }
  93001. }
  93002. return WRC_Continue;
  93003. }
  93004. /*
  93005. ** Determine if any of the arguments to the pExpr Function reference
  93006. ** pSrcList. Return true if they do. Also return true if the function
  93007. ** has no arguments or has only constant arguments. Return false if pExpr
  93008. ** references columns but not columns of tables found in pSrcList.
  93009. */
  93010. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  93011. Walker w;
  93012. struct SrcCount cnt;
  93013. assert( pExpr->op==TK_AGG_FUNCTION );
  93014. w.xExprCallback = exprSrcCount;
  93015. w.xSelectCallback = 0;
  93016. w.u.pSrcCount = &cnt;
  93017. cnt.pSrc = pSrcList;
  93018. cnt.nThis = 0;
  93019. cnt.nOther = 0;
  93020. sqlite3WalkExprList(&w, pExpr->x.pList);
  93021. return cnt.nThis>0 || cnt.nOther==0;
  93022. }
  93023. /*
  93024. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  93025. ** the new element. Return a negative number if malloc fails.
  93026. */
  93027. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  93028. int i;
  93029. pInfo->aCol = sqlite3ArrayAllocate(
  93030. db,
  93031. pInfo->aCol,
  93032. sizeof(pInfo->aCol[0]),
  93033. &pInfo->nColumn,
  93034. &i
  93035. );
  93036. return i;
  93037. }
  93038. /*
  93039. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  93040. ** the new element. Return a negative number if malloc fails.
  93041. */
  93042. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  93043. int i;
  93044. pInfo->aFunc = sqlite3ArrayAllocate(
  93045. db,
  93046. pInfo->aFunc,
  93047. sizeof(pInfo->aFunc[0]),
  93048. &pInfo->nFunc,
  93049. &i
  93050. );
  93051. return i;
  93052. }
  93053. /*
  93054. ** This is the xExprCallback for a tree walker. It is used to
  93055. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  93056. ** for additional information.
  93057. */
  93058. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  93059. int i;
  93060. NameContext *pNC = pWalker->u.pNC;
  93061. Parse *pParse = pNC->pParse;
  93062. SrcList *pSrcList = pNC->pSrcList;
  93063. AggInfo *pAggInfo = pNC->pAggInfo;
  93064. switch( pExpr->op ){
  93065. case TK_AGG_COLUMN:
  93066. case TK_COLUMN: {
  93067. testcase( pExpr->op==TK_AGG_COLUMN );
  93068. testcase( pExpr->op==TK_COLUMN );
  93069. /* Check to see if the column is in one of the tables in the FROM
  93070. ** clause of the aggregate query */
  93071. if( ALWAYS(pSrcList!=0) ){
  93072. struct SrcList_item *pItem = pSrcList->a;
  93073. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  93074. struct AggInfo_col *pCol;
  93075. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  93076. if( pExpr->iTable==pItem->iCursor ){
  93077. /* If we reach this point, it means that pExpr refers to a table
  93078. ** that is in the FROM clause of the aggregate query.
  93079. **
  93080. ** Make an entry for the column in pAggInfo->aCol[] if there
  93081. ** is not an entry there already.
  93082. */
  93083. int k;
  93084. pCol = pAggInfo->aCol;
  93085. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  93086. if( pCol->iTable==pExpr->iTable &&
  93087. pCol->iColumn==pExpr->iColumn ){
  93088. break;
  93089. }
  93090. }
  93091. if( (k>=pAggInfo->nColumn)
  93092. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  93093. ){
  93094. pCol = &pAggInfo->aCol[k];
  93095. pCol->pTab = pExpr->pTab;
  93096. pCol->iTable = pExpr->iTable;
  93097. pCol->iColumn = pExpr->iColumn;
  93098. pCol->iMem = ++pParse->nMem;
  93099. pCol->iSorterColumn = -1;
  93100. pCol->pExpr = pExpr;
  93101. if( pAggInfo->pGroupBy ){
  93102. int j, n;
  93103. ExprList *pGB = pAggInfo->pGroupBy;
  93104. struct ExprList_item *pTerm = pGB->a;
  93105. n = pGB->nExpr;
  93106. for(j=0; j<n; j++, pTerm++){
  93107. Expr *pE = pTerm->pExpr;
  93108. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  93109. pE->iColumn==pExpr->iColumn ){
  93110. pCol->iSorterColumn = j;
  93111. break;
  93112. }
  93113. }
  93114. }
  93115. if( pCol->iSorterColumn<0 ){
  93116. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  93117. }
  93118. }
  93119. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  93120. ** because it was there before or because we just created it).
  93121. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  93122. ** pAggInfo->aCol[] entry.
  93123. */
  93124. ExprSetVVAProperty(pExpr, EP_NoReduce);
  93125. pExpr->pAggInfo = pAggInfo;
  93126. pExpr->op = TK_AGG_COLUMN;
  93127. pExpr->iAgg = (i16)k;
  93128. break;
  93129. } /* endif pExpr->iTable==pItem->iCursor */
  93130. } /* end loop over pSrcList */
  93131. }
  93132. return WRC_Prune;
  93133. }
  93134. case TK_AGG_FUNCTION: {
  93135. if( (pNC->ncFlags & NC_InAggFunc)==0
  93136. && pWalker->walkerDepth==pExpr->op2
  93137. ){
  93138. /* Check to see if pExpr is a duplicate of another aggregate
  93139. ** function that is already in the pAggInfo structure
  93140. */
  93141. struct AggInfo_func *pItem = pAggInfo->aFunc;
  93142. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  93143. if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
  93144. break;
  93145. }
  93146. }
  93147. if( i>=pAggInfo->nFunc ){
  93148. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  93149. */
  93150. u8 enc = ENC(pParse->db);
  93151. i = addAggInfoFunc(pParse->db, pAggInfo);
  93152. if( i>=0 ){
  93153. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  93154. pItem = &pAggInfo->aFunc[i];
  93155. pItem->pExpr = pExpr;
  93156. pItem->iMem = ++pParse->nMem;
  93157. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93158. pItem->pFunc = sqlite3FindFunction(pParse->db,
  93159. pExpr->u.zToken,
  93160. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  93161. if( pExpr->flags & EP_Distinct ){
  93162. pItem->iDistinct = pParse->nTab++;
  93163. }else{
  93164. pItem->iDistinct = -1;
  93165. }
  93166. }
  93167. }
  93168. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  93169. */
  93170. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  93171. ExprSetVVAProperty(pExpr, EP_NoReduce);
  93172. pExpr->iAgg = (i16)i;
  93173. pExpr->pAggInfo = pAggInfo;
  93174. return WRC_Prune;
  93175. }else{
  93176. return WRC_Continue;
  93177. }
  93178. }
  93179. }
  93180. return WRC_Continue;
  93181. }
  93182. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  93183. UNUSED_PARAMETER(pSelect);
  93184. pWalker->walkerDepth++;
  93185. return WRC_Continue;
  93186. }
  93187. static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
  93188. UNUSED_PARAMETER(pSelect);
  93189. pWalker->walkerDepth--;
  93190. }
  93191. /*
  93192. ** Analyze the pExpr expression looking for aggregate functions and
  93193. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  93194. ** points to. Additional entries are made on the AggInfo object as
  93195. ** necessary.
  93196. **
  93197. ** This routine should only be called after the expression has been
  93198. ** analyzed by sqlite3ResolveExprNames().
  93199. */
  93200. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  93201. Walker w;
  93202. w.xExprCallback = analyzeAggregate;
  93203. w.xSelectCallback = analyzeAggregatesInSelect;
  93204. w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
  93205. w.walkerDepth = 0;
  93206. w.u.pNC = pNC;
  93207. assert( pNC->pSrcList!=0 );
  93208. sqlite3WalkExpr(&w, pExpr);
  93209. }
  93210. /*
  93211. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  93212. ** expression list. Return the number of errors.
  93213. **
  93214. ** If an error is found, the analysis is cut short.
  93215. */
  93216. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  93217. struct ExprList_item *pItem;
  93218. int i;
  93219. if( pList ){
  93220. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  93221. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  93222. }
  93223. }
  93224. }
  93225. /*
  93226. ** Allocate a single new register for use to hold some intermediate result.
  93227. */
  93228. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  93229. if( pParse->nTempReg==0 ){
  93230. return ++pParse->nMem;
  93231. }
  93232. return pParse->aTempReg[--pParse->nTempReg];
  93233. }
  93234. /*
  93235. ** Deallocate a register, making available for reuse for some other
  93236. ** purpose.
  93237. **
  93238. ** If a register is currently being used by the column cache, then
  93239. ** the deallocation is deferred until the column cache line that uses
  93240. ** the register becomes stale.
  93241. */
  93242. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  93243. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  93244. int i;
  93245. struct yColCache *p;
  93246. for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
  93247. if( p->iReg==iReg ){
  93248. p->tempReg = 1;
  93249. return;
  93250. }
  93251. }
  93252. pParse->aTempReg[pParse->nTempReg++] = iReg;
  93253. }
  93254. }
  93255. /*
  93256. ** Allocate or deallocate a block of nReg consecutive registers.
  93257. */
  93258. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  93259. int i, n;
  93260. if( nReg==1 ) return sqlite3GetTempReg(pParse);
  93261. i = pParse->iRangeReg;
  93262. n = pParse->nRangeReg;
  93263. if( nReg<=n ){
  93264. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  93265. pParse->iRangeReg += nReg;
  93266. pParse->nRangeReg -= nReg;
  93267. }else{
  93268. i = pParse->nMem+1;
  93269. pParse->nMem += nReg;
  93270. }
  93271. return i;
  93272. }
  93273. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  93274. if( nReg==1 ){
  93275. sqlite3ReleaseTempReg(pParse, iReg);
  93276. return;
  93277. }
  93278. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  93279. if( nReg>pParse->nRangeReg ){
  93280. pParse->nRangeReg = nReg;
  93281. pParse->iRangeReg = iReg;
  93282. }
  93283. }
  93284. /*
  93285. ** Mark all temporary registers as being unavailable for reuse.
  93286. */
  93287. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  93288. pParse->nTempReg = 0;
  93289. pParse->nRangeReg = 0;
  93290. }
  93291. /*
  93292. ** Validate that no temporary register falls within the range of
  93293. ** iFirst..iLast, inclusive. This routine is only call from within assert()
  93294. ** statements.
  93295. */
  93296. #ifdef SQLITE_DEBUG
  93297. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  93298. int i;
  93299. if( pParse->nRangeReg>0
  93300. && pParse->iRangeReg+pParse->nRangeReg > iFirst
  93301. && pParse->iRangeReg <= iLast
  93302. ){
  93303. return 0;
  93304. }
  93305. for(i=0; i<pParse->nTempReg; i++){
  93306. if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
  93307. return 0;
  93308. }
  93309. }
  93310. return 1;
  93311. }
  93312. #endif /* SQLITE_DEBUG */
  93313. /************** End of expr.c ************************************************/
  93314. /************** Begin file alter.c *******************************************/
  93315. /*
  93316. ** 2005 February 15
  93317. **
  93318. ** The author disclaims copyright to this source code. In place of
  93319. ** a legal notice, here is a blessing:
  93320. **
  93321. ** May you do good and not evil.
  93322. ** May you find forgiveness for yourself and forgive others.
  93323. ** May you share freely, never taking more than you give.
  93324. **
  93325. *************************************************************************
  93326. ** This file contains C code routines that used to generate VDBE code
  93327. ** that implements the ALTER TABLE command.
  93328. */
  93329. /* #include "sqliteInt.h" */
  93330. /*
  93331. ** The code in this file only exists if we are not omitting the
  93332. ** ALTER TABLE logic from the build.
  93333. */
  93334. #ifndef SQLITE_OMIT_ALTERTABLE
  93335. /*
  93336. ** This function is used by SQL generated to implement the
  93337. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  93338. ** CREATE INDEX command. The second is a table name. The table name in
  93339. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  93340. ** argument and the result returned. Examples:
  93341. **
  93342. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  93343. ** -> 'CREATE TABLE def(a, b, c)'
  93344. **
  93345. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  93346. ** -> 'CREATE INDEX i ON def(a, b, c)'
  93347. */
  93348. static void renameTableFunc(
  93349. sqlite3_context *context,
  93350. int NotUsed,
  93351. sqlite3_value **argv
  93352. ){
  93353. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  93354. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  93355. int token;
  93356. Token tname;
  93357. unsigned char const *zCsr = zSql;
  93358. int len = 0;
  93359. char *zRet;
  93360. sqlite3 *db = sqlite3_context_db_handle(context);
  93361. UNUSED_PARAMETER(NotUsed);
  93362. /* The principle used to locate the table name in the CREATE TABLE
  93363. ** statement is that the table name is the first non-space token that
  93364. ** is immediately followed by a TK_LP or TK_USING token.
  93365. */
  93366. if( zSql ){
  93367. do {
  93368. if( !*zCsr ){
  93369. /* Ran out of input before finding an opening bracket. Return NULL. */
  93370. return;
  93371. }
  93372. /* Store the token that zCsr points to in tname. */
  93373. tname.z = (char*)zCsr;
  93374. tname.n = len;
  93375. /* Advance zCsr to the next token. Store that token type in 'token',
  93376. ** and its length in 'len' (to be used next iteration of this loop).
  93377. */
  93378. do {
  93379. zCsr += len;
  93380. len = sqlite3GetToken(zCsr, &token);
  93381. } while( token==TK_SPACE );
  93382. assert( len>0 );
  93383. } while( token!=TK_LP && token!=TK_USING );
  93384. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  93385. zSql, zTableName, tname.z+tname.n);
  93386. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  93387. }
  93388. }
  93389. /*
  93390. ** This C function implements an SQL user function that is used by SQL code
  93391. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  93392. ** of any foreign key constraints that use the table being renamed as the
  93393. ** parent table. It is passed three arguments:
  93394. **
  93395. ** 1) The complete text of the CREATE TABLE statement being modified,
  93396. ** 2) The old name of the table being renamed, and
  93397. ** 3) The new name of the table being renamed.
  93398. **
  93399. ** It returns the new CREATE TABLE statement. For example:
  93400. **
  93401. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  93402. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  93403. */
  93404. #ifndef SQLITE_OMIT_FOREIGN_KEY
  93405. static void renameParentFunc(
  93406. sqlite3_context *context,
  93407. int NotUsed,
  93408. sqlite3_value **argv
  93409. ){
  93410. sqlite3 *db = sqlite3_context_db_handle(context);
  93411. char *zOutput = 0;
  93412. char *zResult;
  93413. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  93414. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  93415. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  93416. unsigned const char *z; /* Pointer to token */
  93417. int n; /* Length of token z */
  93418. int token; /* Type of token */
  93419. UNUSED_PARAMETER(NotUsed);
  93420. if( zInput==0 || zOld==0 ) return;
  93421. for(z=zInput; *z; z=z+n){
  93422. n = sqlite3GetToken(z, &token);
  93423. if( token==TK_REFERENCES ){
  93424. char *zParent;
  93425. do {
  93426. z += n;
  93427. n = sqlite3GetToken(z, &token);
  93428. }while( token==TK_SPACE );
  93429. if( token==TK_ILLEGAL ) break;
  93430. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  93431. if( zParent==0 ) break;
  93432. sqlite3Dequote(zParent);
  93433. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  93434. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  93435. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  93436. );
  93437. sqlite3DbFree(db, zOutput);
  93438. zOutput = zOut;
  93439. zInput = &z[n];
  93440. }
  93441. sqlite3DbFree(db, zParent);
  93442. }
  93443. }
  93444. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  93445. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  93446. sqlite3DbFree(db, zOutput);
  93447. }
  93448. #endif
  93449. #ifndef SQLITE_OMIT_TRIGGER
  93450. /* This function is used by SQL generated to implement the
  93451. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  93452. ** statement. The second is a table name. The table name in the CREATE
  93453. ** TRIGGER statement is replaced with the third argument and the result
  93454. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  93455. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  93456. */
  93457. static void renameTriggerFunc(
  93458. sqlite3_context *context,
  93459. int NotUsed,
  93460. sqlite3_value **argv
  93461. ){
  93462. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  93463. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  93464. int token;
  93465. Token tname;
  93466. int dist = 3;
  93467. unsigned char const *zCsr = zSql;
  93468. int len = 0;
  93469. char *zRet;
  93470. sqlite3 *db = sqlite3_context_db_handle(context);
  93471. UNUSED_PARAMETER(NotUsed);
  93472. /* The principle used to locate the table name in the CREATE TRIGGER
  93473. ** statement is that the table name is the first token that is immediately
  93474. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  93475. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  93476. */
  93477. if( zSql ){
  93478. do {
  93479. if( !*zCsr ){
  93480. /* Ran out of input before finding the table name. Return NULL. */
  93481. return;
  93482. }
  93483. /* Store the token that zCsr points to in tname. */
  93484. tname.z = (char*)zCsr;
  93485. tname.n = len;
  93486. /* Advance zCsr to the next token. Store that token type in 'token',
  93487. ** and its length in 'len' (to be used next iteration of this loop).
  93488. */
  93489. do {
  93490. zCsr += len;
  93491. len = sqlite3GetToken(zCsr, &token);
  93492. }while( token==TK_SPACE );
  93493. assert( len>0 );
  93494. /* Variable 'dist' stores the number of tokens read since the most
  93495. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  93496. ** token is read and 'dist' equals 2, the condition stated above
  93497. ** to be met.
  93498. **
  93499. ** Note that ON cannot be a database, table or column name, so
  93500. ** there is no need to worry about syntax like
  93501. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  93502. */
  93503. dist++;
  93504. if( token==TK_DOT || token==TK_ON ){
  93505. dist = 0;
  93506. }
  93507. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  93508. /* Variable tname now contains the token that is the old table-name
  93509. ** in the CREATE TRIGGER statement.
  93510. */
  93511. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  93512. zSql, zTableName, tname.z+tname.n);
  93513. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  93514. }
  93515. }
  93516. #endif /* !SQLITE_OMIT_TRIGGER */
  93517. /*
  93518. ** Register built-in functions used to help implement ALTER TABLE
  93519. */
  93520. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  93521. static FuncDef aAlterTableFuncs[] = {
  93522. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  93523. #ifndef SQLITE_OMIT_TRIGGER
  93524. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  93525. #endif
  93526. #ifndef SQLITE_OMIT_FOREIGN_KEY
  93527. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  93528. #endif
  93529. };
  93530. sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
  93531. }
  93532. /*
  93533. ** This function is used to create the text of expressions of the form:
  93534. **
  93535. ** name=<constant1> OR name=<constant2> OR ...
  93536. **
  93537. ** If argument zWhere is NULL, then a pointer string containing the text
  93538. ** "name=<constant>" is returned, where <constant> is the quoted version
  93539. ** of the string passed as argument zConstant. The returned buffer is
  93540. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  93541. ** caller to ensure that it is eventually freed.
  93542. **
  93543. ** If argument zWhere is not NULL, then the string returned is
  93544. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  93545. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  93546. **
  93547. */
  93548. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  93549. char *zNew;
  93550. if( !zWhere ){
  93551. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  93552. }else{
  93553. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  93554. sqlite3DbFree(db, zWhere);
  93555. }
  93556. return zNew;
  93557. }
  93558. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  93559. /*
  93560. ** Generate the text of a WHERE expression which can be used to select all
  93561. ** tables that have foreign key constraints that refer to table pTab (i.e.
  93562. ** constraints for which pTab is the parent table) from the sqlite_master
  93563. ** table.
  93564. */
  93565. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  93566. FKey *p;
  93567. char *zWhere = 0;
  93568. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  93569. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  93570. }
  93571. return zWhere;
  93572. }
  93573. #endif
  93574. /*
  93575. ** Generate the text of a WHERE expression which can be used to select all
  93576. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  93577. ** table pTab has no temporary triggers, or is itself stored in the
  93578. ** temporary database, NULL is returned.
  93579. */
  93580. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  93581. Trigger *pTrig;
  93582. char *zWhere = 0;
  93583. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  93584. /* If the table is not located in the temp-db (in which case NULL is
  93585. ** returned, loop through the tables list of triggers. For each trigger
  93586. ** that is not part of the temp-db schema, add a clause to the WHERE
  93587. ** expression being built up in zWhere.
  93588. */
  93589. if( pTab->pSchema!=pTempSchema ){
  93590. sqlite3 *db = pParse->db;
  93591. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  93592. if( pTrig->pSchema==pTempSchema ){
  93593. zWhere = whereOrName(db, zWhere, pTrig->zName);
  93594. }
  93595. }
  93596. }
  93597. if( zWhere ){
  93598. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  93599. sqlite3DbFree(pParse->db, zWhere);
  93600. zWhere = zNew;
  93601. }
  93602. return zWhere;
  93603. }
  93604. /*
  93605. ** Generate code to drop and reload the internal representation of table
  93606. ** pTab from the database, including triggers and temporary triggers.
  93607. ** Argument zName is the name of the table in the database schema at
  93608. ** the time the generated code is executed. This can be different from
  93609. ** pTab->zName if this function is being called to code part of an
  93610. ** "ALTER TABLE RENAME TO" statement.
  93611. */
  93612. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  93613. Vdbe *v;
  93614. char *zWhere;
  93615. int iDb; /* Index of database containing pTab */
  93616. #ifndef SQLITE_OMIT_TRIGGER
  93617. Trigger *pTrig;
  93618. #endif
  93619. v = sqlite3GetVdbe(pParse);
  93620. if( NEVER(v==0) ) return;
  93621. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  93622. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  93623. assert( iDb>=0 );
  93624. #ifndef SQLITE_OMIT_TRIGGER
  93625. /* Drop any table triggers from the internal schema. */
  93626. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  93627. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  93628. assert( iTrigDb==iDb || iTrigDb==1 );
  93629. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  93630. }
  93631. #endif
  93632. /* Drop the table and index from the internal schema. */
  93633. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  93634. /* Reload the table, index and permanent trigger schemas. */
  93635. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  93636. if( !zWhere ) return;
  93637. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  93638. #ifndef SQLITE_OMIT_TRIGGER
  93639. /* Now, if the table is not stored in the temp database, reload any temp
  93640. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  93641. */
  93642. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  93643. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  93644. }
  93645. #endif
  93646. }
  93647. /*
  93648. ** Parameter zName is the name of a table that is about to be altered
  93649. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  93650. ** If the table is a system table, this function leaves an error message
  93651. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  93652. **
  93653. ** Or, if zName is not a system table, zero is returned.
  93654. */
  93655. static int isSystemTable(Parse *pParse, const char *zName){
  93656. if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  93657. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  93658. return 1;
  93659. }
  93660. return 0;
  93661. }
  93662. /*
  93663. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  93664. ** command.
  93665. */
  93666. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  93667. Parse *pParse, /* Parser context. */
  93668. SrcList *pSrc, /* The table to rename. */
  93669. Token *pName /* The new table name. */
  93670. ){
  93671. int iDb; /* Database that contains the table */
  93672. char *zDb; /* Name of database iDb */
  93673. Table *pTab; /* Table being renamed */
  93674. char *zName = 0; /* NULL-terminated version of pName */
  93675. sqlite3 *db = pParse->db; /* Database connection */
  93676. int nTabName; /* Number of UTF-8 characters in zTabName */
  93677. const char *zTabName; /* Original name of the table */
  93678. Vdbe *v;
  93679. #ifndef SQLITE_OMIT_TRIGGER
  93680. char *zWhere = 0; /* Where clause to locate temp triggers */
  93681. #endif
  93682. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  93683. u32 savedDbFlags; /* Saved value of db->mDbFlags */
  93684. savedDbFlags = db->mDbFlags;
  93685. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  93686. assert( pSrc->nSrc==1 );
  93687. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  93688. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  93689. if( !pTab ) goto exit_rename_table;
  93690. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  93691. zDb = db->aDb[iDb].zDbSName;
  93692. db->mDbFlags |= DBFLAG_PreferBuiltin;
  93693. /* Get a NULL terminated version of the new table name. */
  93694. zName = sqlite3NameFromToken(db, pName);
  93695. if( !zName ) goto exit_rename_table;
  93696. /* Check that a table or index named 'zName' does not already exist
  93697. ** in database iDb. If so, this is an error.
  93698. */
  93699. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  93700. sqlite3ErrorMsg(pParse,
  93701. "there is already another table or index with this name: %s", zName);
  93702. goto exit_rename_table;
  93703. }
  93704. /* Make sure it is not a system table being altered, or a reserved name
  93705. ** that the table is being renamed to.
  93706. */
  93707. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  93708. goto exit_rename_table;
  93709. }
  93710. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  93711. exit_rename_table;
  93712. }
  93713. #ifndef SQLITE_OMIT_VIEW
  93714. if( pTab->pSelect ){
  93715. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  93716. goto exit_rename_table;
  93717. }
  93718. #endif
  93719. #ifndef SQLITE_OMIT_AUTHORIZATION
  93720. /* Invoke the authorization callback. */
  93721. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  93722. goto exit_rename_table;
  93723. }
  93724. #endif
  93725. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93726. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  93727. goto exit_rename_table;
  93728. }
  93729. if( IsVirtual(pTab) ){
  93730. pVTab = sqlite3GetVTable(db, pTab);
  93731. if( pVTab->pVtab->pModule->xRename==0 ){
  93732. pVTab = 0;
  93733. }
  93734. }
  93735. #endif
  93736. /* Begin a transaction for database iDb.
  93737. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  93738. ** schema). Open a statement transaction if the table is a virtual
  93739. ** table.
  93740. */
  93741. v = sqlite3GetVdbe(pParse);
  93742. if( v==0 ){
  93743. goto exit_rename_table;
  93744. }
  93745. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  93746. sqlite3ChangeCookie(pParse, iDb);
  93747. /* If this is a virtual table, invoke the xRename() function if
  93748. ** one is defined. The xRename() callback will modify the names
  93749. ** of any resources used by the v-table implementation (including other
  93750. ** SQLite tables) that are identified by the name of the virtual table.
  93751. */
  93752. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93753. if( pVTab ){
  93754. int i = ++pParse->nMem;
  93755. sqlite3VdbeLoadString(v, i, zName);
  93756. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  93757. sqlite3MayAbort(pParse);
  93758. }
  93759. #endif
  93760. /* figure out how many UTF-8 characters are in zName */
  93761. zTabName = pTab->zName;
  93762. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  93763. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  93764. if( db->flags&SQLITE_ForeignKeys ){
  93765. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  93766. ** statements corresponding to all child tables of foreign key constraints
  93767. ** for which the renamed table is the parent table. */
  93768. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  93769. sqlite3NestedParse(pParse,
  93770. "UPDATE \"%w\".%s SET "
  93771. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  93772. "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
  93773. sqlite3DbFree(db, zWhere);
  93774. }
  93775. }
  93776. #endif
  93777. /* Modify the sqlite_master table to use the new table name. */
  93778. sqlite3NestedParse(pParse,
  93779. "UPDATE %Q.%s SET "
  93780. #ifdef SQLITE_OMIT_TRIGGER
  93781. "sql = sqlite_rename_table(sql, %Q), "
  93782. #else
  93783. "sql = CASE "
  93784. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  93785. "ELSE sqlite_rename_table(sql, %Q) END, "
  93786. #endif
  93787. "tbl_name = %Q, "
  93788. "name = CASE "
  93789. "WHEN type='table' THEN %Q "
  93790. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  93791. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  93792. "ELSE name END "
  93793. "WHERE tbl_name=%Q COLLATE nocase AND "
  93794. "(type='table' OR type='index' OR type='trigger');",
  93795. zDb, MASTER_NAME, zName, zName, zName,
  93796. #ifndef SQLITE_OMIT_TRIGGER
  93797. zName,
  93798. #endif
  93799. zName, nTabName, zTabName
  93800. );
  93801. #ifndef SQLITE_OMIT_AUTOINCREMENT
  93802. /* If the sqlite_sequence table exists in this database, then update
  93803. ** it with the new table name.
  93804. */
  93805. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  93806. sqlite3NestedParse(pParse,
  93807. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  93808. zDb, zName, pTab->zName);
  93809. }
  93810. #endif
  93811. #ifndef SQLITE_OMIT_TRIGGER
  93812. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  93813. ** table. Don't do this if the table being ALTERed is itself located in
  93814. ** the temp database.
  93815. */
  93816. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  93817. sqlite3NestedParse(pParse,
  93818. "UPDATE sqlite_temp_master SET "
  93819. "sql = sqlite_rename_trigger(sql, %Q), "
  93820. "tbl_name = %Q "
  93821. "WHERE %s;", zName, zName, zWhere);
  93822. sqlite3DbFree(db, zWhere);
  93823. }
  93824. #endif
  93825. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  93826. if( db->flags&SQLITE_ForeignKeys ){
  93827. FKey *p;
  93828. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  93829. Table *pFrom = p->pFrom;
  93830. if( pFrom!=pTab ){
  93831. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  93832. }
  93833. }
  93834. }
  93835. #endif
  93836. /* Drop and reload the internal table schema. */
  93837. reloadTableSchema(pParse, pTab, zName);
  93838. exit_rename_table:
  93839. sqlite3SrcListDelete(db, pSrc);
  93840. sqlite3DbFree(db, zName);
  93841. db->mDbFlags = savedDbFlags;
  93842. }
  93843. /*
  93844. ** This function is called after an "ALTER TABLE ... ADD" statement
  93845. ** has been parsed. Argument pColDef contains the text of the new
  93846. ** column definition.
  93847. **
  93848. ** The Table structure pParse->pNewTable was extended to include
  93849. ** the new column during parsing.
  93850. */
  93851. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  93852. Table *pNew; /* Copy of pParse->pNewTable */
  93853. Table *pTab; /* Table being altered */
  93854. int iDb; /* Database number */
  93855. const char *zDb; /* Database name */
  93856. const char *zTab; /* Table name */
  93857. char *zCol; /* Null-terminated column definition */
  93858. Column *pCol; /* The new column */
  93859. Expr *pDflt; /* Default value for the new column */
  93860. sqlite3 *db; /* The database connection; */
  93861. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  93862. int r1; /* Temporary registers */
  93863. db = pParse->db;
  93864. if( pParse->nErr || db->mallocFailed ) return;
  93865. assert( v!=0 );
  93866. pNew = pParse->pNewTable;
  93867. assert( pNew );
  93868. assert( sqlite3BtreeHoldsAllMutexes(db) );
  93869. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  93870. zDb = db->aDb[iDb].zDbSName;
  93871. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  93872. pCol = &pNew->aCol[pNew->nCol-1];
  93873. pDflt = pCol->pDflt;
  93874. pTab = sqlite3FindTable(db, zTab, zDb);
  93875. assert( pTab );
  93876. #ifndef SQLITE_OMIT_AUTHORIZATION
  93877. /* Invoke the authorization callback. */
  93878. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  93879. return;
  93880. }
  93881. #endif
  93882. /* If the default value for the new column was specified with a
  93883. ** literal NULL, then set pDflt to 0. This simplifies checking
  93884. ** for an SQL NULL default below.
  93885. */
  93886. assert( pDflt==0 || pDflt->op==TK_SPAN );
  93887. if( pDflt && pDflt->pLeft->op==TK_NULL ){
  93888. pDflt = 0;
  93889. }
  93890. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  93891. ** If there is a NOT NULL constraint, then the default value for the
  93892. ** column must not be NULL.
  93893. */
  93894. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  93895. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  93896. return;
  93897. }
  93898. if( pNew->pIndex ){
  93899. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  93900. return;
  93901. }
  93902. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  93903. sqlite3ErrorMsg(pParse,
  93904. "Cannot add a REFERENCES column with non-NULL default value");
  93905. return;
  93906. }
  93907. if( pCol->notNull && !pDflt ){
  93908. sqlite3ErrorMsg(pParse,
  93909. "Cannot add a NOT NULL column with default value NULL");
  93910. return;
  93911. }
  93912. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  93913. ** can handle (i.e. not CURRENT_TIME etc.)
  93914. */
  93915. if( pDflt ){
  93916. sqlite3_value *pVal = 0;
  93917. int rc;
  93918. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  93919. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  93920. if( rc!=SQLITE_OK ){
  93921. assert( db->mallocFailed == 1 );
  93922. return;
  93923. }
  93924. if( !pVal ){
  93925. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  93926. return;
  93927. }
  93928. sqlite3ValueFree(pVal);
  93929. }
  93930. /* Modify the CREATE TABLE statement. */
  93931. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  93932. if( zCol ){
  93933. char *zEnd = &zCol[pColDef->n-1];
  93934. u32 savedDbFlags = db->mDbFlags;
  93935. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  93936. *zEnd-- = '\0';
  93937. }
  93938. db->mDbFlags |= DBFLAG_PreferBuiltin;
  93939. sqlite3NestedParse(pParse,
  93940. "UPDATE \"%w\".%s SET "
  93941. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  93942. "WHERE type = 'table' AND name = %Q",
  93943. zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
  93944. zTab
  93945. );
  93946. sqlite3DbFree(db, zCol);
  93947. db->mDbFlags = savedDbFlags;
  93948. }
  93949. /* Make sure the schema version is at least 3. But do not upgrade
  93950. ** from less than 3 to 4, as that will corrupt any preexisting DESC
  93951. ** index.
  93952. */
  93953. r1 = sqlite3GetTempReg(pParse);
  93954. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  93955. sqlite3VdbeUsesBtree(v, iDb);
  93956. sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
  93957. sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
  93958. VdbeCoverage(v);
  93959. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
  93960. sqlite3ReleaseTempReg(pParse, r1);
  93961. /* Reload the schema of the modified table. */
  93962. reloadTableSchema(pParse, pTab, pTab->zName);
  93963. }
  93964. /*
  93965. ** This function is called by the parser after the table-name in
  93966. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  93967. ** pSrc is the full-name of the table being altered.
  93968. **
  93969. ** This routine makes a (partial) copy of the Table structure
  93970. ** for the table being altered and sets Parse.pNewTable to point
  93971. ** to it. Routines called by the parser as the column definition
  93972. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  93973. ** the copy. The copy of the Table structure is deleted by tokenize.c
  93974. ** after parsing is finished.
  93975. **
  93976. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  93977. ** coding the "ALTER TABLE ... ADD" statement.
  93978. */
  93979. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  93980. Table *pNew;
  93981. Table *pTab;
  93982. Vdbe *v;
  93983. int iDb;
  93984. int i;
  93985. int nAlloc;
  93986. sqlite3 *db = pParse->db;
  93987. /* Look up the table being altered. */
  93988. assert( pParse->pNewTable==0 );
  93989. assert( sqlite3BtreeHoldsAllMutexes(db) );
  93990. if( db->mallocFailed ) goto exit_begin_add_column;
  93991. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  93992. if( !pTab ) goto exit_begin_add_column;
  93993. #ifndef SQLITE_OMIT_VIRTUALTABLE
  93994. if( IsVirtual(pTab) ){
  93995. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  93996. goto exit_begin_add_column;
  93997. }
  93998. #endif
  93999. /* Make sure this is not an attempt to ALTER a view. */
  94000. if( pTab->pSelect ){
  94001. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  94002. goto exit_begin_add_column;
  94003. }
  94004. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  94005. goto exit_begin_add_column;
  94006. }
  94007. assert( pTab->addColOffset>0 );
  94008. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  94009. /* Put a copy of the Table struct in Parse.pNewTable for the
  94010. ** sqlite3AddColumn() function and friends to modify. But modify
  94011. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  94012. ** prefix, we insure that the name will not collide with an existing
  94013. ** table because user table are not allowed to have the "sqlite_"
  94014. ** prefix on their name.
  94015. */
  94016. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  94017. if( !pNew ) goto exit_begin_add_column;
  94018. pParse->pNewTable = pNew;
  94019. pNew->nTabRef = 1;
  94020. pNew->nCol = pTab->nCol;
  94021. assert( pNew->nCol>0 );
  94022. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  94023. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  94024. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  94025. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  94026. if( !pNew->aCol || !pNew->zName ){
  94027. assert( db->mallocFailed );
  94028. goto exit_begin_add_column;
  94029. }
  94030. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  94031. for(i=0; i<pNew->nCol; i++){
  94032. Column *pCol = &pNew->aCol[i];
  94033. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  94034. pCol->zColl = 0;
  94035. pCol->pDflt = 0;
  94036. }
  94037. pNew->pSchema = db->aDb[iDb].pSchema;
  94038. pNew->addColOffset = pTab->addColOffset;
  94039. pNew->nTabRef = 1;
  94040. /* Begin a transaction and increment the schema cookie. */
  94041. sqlite3BeginWriteOperation(pParse, 0, iDb);
  94042. v = sqlite3GetVdbe(pParse);
  94043. if( !v ) goto exit_begin_add_column;
  94044. sqlite3ChangeCookie(pParse, iDb);
  94045. exit_begin_add_column:
  94046. sqlite3SrcListDelete(db, pSrc);
  94047. return;
  94048. }
  94049. #endif /* SQLITE_ALTER_TABLE */
  94050. /************** End of alter.c ***********************************************/
  94051. /************** Begin file analyze.c *****************************************/
  94052. /*
  94053. ** 2005-07-08
  94054. **
  94055. ** The author disclaims copyright to this source code. In place of
  94056. ** a legal notice, here is a blessing:
  94057. **
  94058. ** May you do good and not evil.
  94059. ** May you find forgiveness for yourself and forgive others.
  94060. ** May you share freely, never taking more than you give.
  94061. **
  94062. *************************************************************************
  94063. ** This file contains code associated with the ANALYZE command.
  94064. **
  94065. ** The ANALYZE command gather statistics about the content of tables
  94066. ** and indices. These statistics are made available to the query planner
  94067. ** to help it make better decisions about how to perform queries.
  94068. **
  94069. ** The following system tables are or have been supported:
  94070. **
  94071. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  94072. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  94073. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  94074. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  94075. **
  94076. ** Additional tables might be added in future releases of SQLite.
  94077. ** The sqlite_stat2 table is not created or used unless the SQLite version
  94078. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  94079. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  94080. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  94081. ** created and used by SQLite versions 3.7.9 and later and with
  94082. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  94083. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  94084. ** version of sqlite_stat3 and is only available when compiled with
  94085. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  94086. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  94087. ** are both enabled, then STAT4 takes precedence.
  94088. **
  94089. ** For most applications, sqlite_stat1 provides all the statistics required
  94090. ** for the query planner to make good choices.
  94091. **
  94092. ** Format of sqlite_stat1:
  94093. **
  94094. ** There is normally one row per index, with the index identified by the
  94095. ** name in the idx column. The tbl column is the name of the table to
  94096. ** which the index belongs. In each such row, the stat column will be
  94097. ** a string consisting of a list of integers. The first integer in this
  94098. ** list is the number of rows in the index. (This is the same as the
  94099. ** number of rows in the table, except for partial indices.) The second
  94100. ** integer is the average number of rows in the index that have the same
  94101. ** value in the first column of the index. The third integer is the average
  94102. ** number of rows in the index that have the same value for the first two
  94103. ** columns. The N-th integer (for N>1) is the average number of rows in
  94104. ** the index which have the same value for the first N-1 columns. For
  94105. ** a K-column index, there will be K+1 integers in the stat column. If
  94106. ** the index is unique, then the last integer will be 1.
  94107. **
  94108. ** The list of integers in the stat column can optionally be followed
  94109. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  94110. ** must be separated from the last integer by a single space. If the
  94111. ** "unordered" keyword is present, then the query planner assumes that
  94112. ** the index is unordered and will not use the index for a range query.
  94113. **
  94114. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  94115. ** column contains a single integer which is the (estimated) number of
  94116. ** rows in the table identified by sqlite_stat1.tbl.
  94117. **
  94118. ** Format of sqlite_stat2:
  94119. **
  94120. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  94121. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  94122. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  94123. ** about the distribution of keys within an index. The index is identified by
  94124. ** the "idx" column and the "tbl" column is the name of the table to which
  94125. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  94126. ** table for each index.
  94127. **
  94128. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  94129. ** inclusive are samples of the left-most key value in the index taken at
  94130. ** evenly spaced points along the index. Let the number of samples be S
  94131. ** (10 in the standard build) and let C be the number of rows in the index.
  94132. ** Then the sampled rows are given by:
  94133. **
  94134. ** rownumber = (i*C*2 + C)/(S*2)
  94135. **
  94136. ** For i between 0 and S-1. Conceptually, the index space is divided into
  94137. ** S uniform buckets and the samples are the middle row from each bucket.
  94138. **
  94139. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  94140. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  94141. ** writes the sqlite_stat2 table. This version of SQLite only supports
  94142. ** sqlite_stat3.
  94143. **
  94144. ** Format for sqlite_stat3:
  94145. **
  94146. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  94147. ** sqlite_stat4 format will be described first. Further information
  94148. ** about sqlite_stat3 follows the sqlite_stat4 description.
  94149. **
  94150. ** Format for sqlite_stat4:
  94151. **
  94152. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  94153. ** to aid the query planner in choosing good indices based on the values
  94154. ** that indexed columns are compared against in the WHERE clauses of
  94155. ** queries.
  94156. **
  94157. ** The sqlite_stat4 table contains multiple entries for each index.
  94158. ** The idx column names the index and the tbl column is the table of the
  94159. ** index. If the idx and tbl columns are the same, then the sample is
  94160. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  94161. ** binary encoding of a key from the index. The nEq column is a
  94162. ** list of integers. The first integer is the approximate number
  94163. ** of entries in the index whose left-most column exactly matches
  94164. ** the left-most column of the sample. The second integer in nEq
  94165. ** is the approximate number of entries in the index where the
  94166. ** first two columns match the first two columns of the sample.
  94167. ** And so forth. nLt is another list of integers that show the approximate
  94168. ** number of entries that are strictly less than the sample. The first
  94169. ** integer in nLt contains the number of entries in the index where the
  94170. ** left-most column is less than the left-most column of the sample.
  94171. ** The K-th integer in the nLt entry is the number of index entries
  94172. ** where the first K columns are less than the first K columns of the
  94173. ** sample. The nDLt column is like nLt except that it contains the
  94174. ** number of distinct entries in the index that are less than the
  94175. ** sample.
  94176. **
  94177. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  94178. ** The ANALYZE command will typically generate sqlite_stat4 tables
  94179. ** that contain between 10 and 40 samples which are distributed across
  94180. ** the key space, though not uniformly, and which include samples with
  94181. ** large nEq values.
  94182. **
  94183. ** Format for sqlite_stat3 redux:
  94184. **
  94185. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  94186. ** looks at the left-most column of the index. The sqlite_stat3.sample
  94187. ** column contains the actual value of the left-most column instead
  94188. ** of a blob encoding of the complete index key as is found in
  94189. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  94190. ** all contain just a single integer which is the same as the first
  94191. ** integer in the equivalent columns in sqlite_stat4.
  94192. */
  94193. #ifndef SQLITE_OMIT_ANALYZE
  94194. /* #include "sqliteInt.h" */
  94195. #if defined(SQLITE_ENABLE_STAT4)
  94196. # define IsStat4 1
  94197. # define IsStat3 0
  94198. #elif defined(SQLITE_ENABLE_STAT3)
  94199. # define IsStat4 0
  94200. # define IsStat3 1
  94201. #else
  94202. # define IsStat4 0
  94203. # define IsStat3 0
  94204. # undef SQLITE_STAT4_SAMPLES
  94205. # define SQLITE_STAT4_SAMPLES 1
  94206. #endif
  94207. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  94208. /*
  94209. ** This routine generates code that opens the sqlite_statN tables.
  94210. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  94211. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  94212. ** appropriate compile-time options are provided.
  94213. **
  94214. ** If the sqlite_statN tables do not previously exist, it is created.
  94215. **
  94216. ** Argument zWhere may be a pointer to a buffer containing a table name,
  94217. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  94218. ** the sqlite_statN tables associated with the named table are deleted.
  94219. ** If zWhere==0, then code is generated to delete all stat table entries.
  94220. */
  94221. static void openStatTable(
  94222. Parse *pParse, /* Parsing context */
  94223. int iDb, /* The database we are looking in */
  94224. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  94225. const char *zWhere, /* Delete entries for this table or index */
  94226. const char *zWhereType /* Either "tbl" or "idx" */
  94227. ){
  94228. static const struct {
  94229. const char *zName;
  94230. const char *zCols;
  94231. } aTable[] = {
  94232. { "sqlite_stat1", "tbl,idx,stat" },
  94233. #if defined(SQLITE_ENABLE_STAT4)
  94234. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  94235. { "sqlite_stat3", 0 },
  94236. #elif defined(SQLITE_ENABLE_STAT3)
  94237. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  94238. { "sqlite_stat4", 0 },
  94239. #else
  94240. { "sqlite_stat3", 0 },
  94241. { "sqlite_stat4", 0 },
  94242. #endif
  94243. };
  94244. int i;
  94245. sqlite3 *db = pParse->db;
  94246. Db *pDb;
  94247. Vdbe *v = sqlite3GetVdbe(pParse);
  94248. int aRoot[ArraySize(aTable)];
  94249. u8 aCreateTbl[ArraySize(aTable)];
  94250. if( v==0 ) return;
  94251. assert( sqlite3BtreeHoldsAllMutexes(db) );
  94252. assert( sqlite3VdbeDb(v)==db );
  94253. pDb = &db->aDb[iDb];
  94254. /* Create new statistic tables if they do not exist, or clear them
  94255. ** if they do already exist.
  94256. */
  94257. for(i=0; i<ArraySize(aTable); i++){
  94258. const char *zTab = aTable[i].zName;
  94259. Table *pStat;
  94260. if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
  94261. if( aTable[i].zCols ){
  94262. /* The sqlite_statN table does not exist. Create it. Note that a
  94263. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  94264. ** of the new table in register pParse->regRoot. This is important
  94265. ** because the OpenWrite opcode below will be needing it. */
  94266. sqlite3NestedParse(pParse,
  94267. "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
  94268. );
  94269. aRoot[i] = pParse->regRoot;
  94270. aCreateTbl[i] = OPFLAG_P2ISREG;
  94271. }
  94272. }else{
  94273. /* The table already exists. If zWhere is not NULL, delete all entries
  94274. ** associated with the table zWhere. If zWhere is NULL, delete the
  94275. ** entire contents of the table. */
  94276. aRoot[i] = pStat->tnum;
  94277. aCreateTbl[i] = 0;
  94278. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  94279. if( zWhere ){
  94280. sqlite3NestedParse(pParse,
  94281. "DELETE FROM %Q.%s WHERE %s=%Q",
  94282. pDb->zDbSName, zTab, zWhereType, zWhere
  94283. );
  94284. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  94285. }else if( db->xPreUpdateCallback ){
  94286. sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
  94287. #endif
  94288. }else{
  94289. /* The sqlite_stat[134] table already exists. Delete all rows. */
  94290. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  94291. }
  94292. }
  94293. }
  94294. /* Open the sqlite_stat[134] tables for writing. */
  94295. for(i=0; aTable[i].zCols; i++){
  94296. assert( i<ArraySize(aTable) );
  94297. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  94298. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  94299. VdbeComment((v, aTable[i].zName));
  94300. }
  94301. }
  94302. /*
  94303. ** Recommended number of samples for sqlite_stat4
  94304. */
  94305. #ifndef SQLITE_STAT4_SAMPLES
  94306. # define SQLITE_STAT4_SAMPLES 24
  94307. #endif
  94308. /*
  94309. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  94310. ** share an instance of the following structure to hold their state
  94311. ** information.
  94312. */
  94313. typedef struct Stat4Accum Stat4Accum;
  94314. typedef struct Stat4Sample Stat4Sample;
  94315. struct Stat4Sample {
  94316. tRowcnt *anEq; /* sqlite_stat4.nEq */
  94317. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  94318. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94319. tRowcnt *anLt; /* sqlite_stat4.nLt */
  94320. union {
  94321. i64 iRowid; /* Rowid in main table of the key */
  94322. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  94323. } u;
  94324. u32 nRowid; /* Sizeof aRowid[] */
  94325. u8 isPSample; /* True if a periodic sample */
  94326. int iCol; /* If !isPSample, the reason for inclusion */
  94327. u32 iHash; /* Tiebreaker hash */
  94328. #endif
  94329. };
  94330. struct Stat4Accum {
  94331. tRowcnt nRow; /* Number of rows in the entire table */
  94332. tRowcnt nPSample; /* How often to do a periodic sample */
  94333. int nCol; /* Number of columns in index + pk/rowid */
  94334. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  94335. int mxSample; /* Maximum number of samples to accumulate */
  94336. Stat4Sample current; /* Current row as a Stat4Sample */
  94337. u32 iPrn; /* Pseudo-random number used for sampling */
  94338. Stat4Sample *aBest; /* Array of nCol best samples */
  94339. int iMin; /* Index in a[] of entry with minimum score */
  94340. int nSample; /* Current number of samples */
  94341. int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
  94342. int iGet; /* Index of current sample accessed by stat_get() */
  94343. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  94344. sqlite3 *db; /* Database connection, for malloc() */
  94345. };
  94346. /* Reclaim memory used by a Stat4Sample
  94347. */
  94348. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94349. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  94350. assert( db!=0 );
  94351. if( p->nRowid ){
  94352. sqlite3DbFree(db, p->u.aRowid);
  94353. p->nRowid = 0;
  94354. }
  94355. }
  94356. #endif
  94357. /* Initialize the BLOB value of a ROWID
  94358. */
  94359. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94360. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  94361. assert( db!=0 );
  94362. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  94363. p->u.aRowid = sqlite3DbMallocRawNN(db, n);
  94364. if( p->u.aRowid ){
  94365. p->nRowid = n;
  94366. memcpy(p->u.aRowid, pData, n);
  94367. }else{
  94368. p->nRowid = 0;
  94369. }
  94370. }
  94371. #endif
  94372. /* Initialize the INTEGER value of a ROWID.
  94373. */
  94374. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94375. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  94376. assert( db!=0 );
  94377. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  94378. p->nRowid = 0;
  94379. p->u.iRowid = iRowid;
  94380. }
  94381. #endif
  94382. /*
  94383. ** Copy the contents of object (*pFrom) into (*pTo).
  94384. */
  94385. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94386. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  94387. pTo->isPSample = pFrom->isPSample;
  94388. pTo->iCol = pFrom->iCol;
  94389. pTo->iHash = pFrom->iHash;
  94390. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  94391. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  94392. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  94393. if( pFrom->nRowid ){
  94394. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  94395. }else{
  94396. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  94397. }
  94398. }
  94399. #endif
  94400. /*
  94401. ** Reclaim all memory of a Stat4Accum structure.
  94402. */
  94403. static void stat4Destructor(void *pOld){
  94404. Stat4Accum *p = (Stat4Accum*)pOld;
  94405. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94406. int i;
  94407. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  94408. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  94409. sampleClear(p->db, &p->current);
  94410. #endif
  94411. sqlite3DbFree(p->db, p);
  94412. }
  94413. /*
  94414. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  94415. ** are:
  94416. ** N: The number of columns in the index including the rowid/pk (note 1)
  94417. ** K: The number of columns in the index excluding the rowid/pk.
  94418. ** C: The number of rows in the index (note 2)
  94419. **
  94420. ** Note 1: In the special case of the covering index that implements a
  94421. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  94422. ** total number of columns in the table.
  94423. **
  94424. ** Note 2: C is only used for STAT3 and STAT4.
  94425. **
  94426. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  94427. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  94428. ** PRIMARY KEY of the table. The covering index that implements the
  94429. ** original WITHOUT ROWID table as N==K as a special case.
  94430. **
  94431. ** This routine allocates the Stat4Accum object in heap memory. The return
  94432. ** value is a pointer to the Stat4Accum object. The datatype of the
  94433. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  94434. ** object.
  94435. */
  94436. static void statInit(
  94437. sqlite3_context *context,
  94438. int argc,
  94439. sqlite3_value **argv
  94440. ){
  94441. Stat4Accum *p;
  94442. int nCol; /* Number of columns in index being sampled */
  94443. int nKeyCol; /* Number of key columns */
  94444. int nColUp; /* nCol rounded up for alignment */
  94445. int n; /* Bytes of space to allocate */
  94446. sqlite3 *db; /* Database connection */
  94447. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94448. int mxSample = SQLITE_STAT4_SAMPLES;
  94449. #endif
  94450. /* Decode the three function arguments */
  94451. UNUSED_PARAMETER(argc);
  94452. nCol = sqlite3_value_int(argv[0]);
  94453. assert( nCol>0 );
  94454. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  94455. nKeyCol = sqlite3_value_int(argv[1]);
  94456. assert( nKeyCol<=nCol );
  94457. assert( nKeyCol>0 );
  94458. /* Allocate the space required for the Stat4Accum object */
  94459. n = sizeof(*p)
  94460. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  94461. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  94462. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94463. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  94464. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  94465. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  94466. #endif
  94467. ;
  94468. db = sqlite3_context_db_handle(context);
  94469. p = sqlite3DbMallocZero(db, n);
  94470. if( p==0 ){
  94471. sqlite3_result_error_nomem(context);
  94472. return;
  94473. }
  94474. p->db = db;
  94475. p->nRow = 0;
  94476. p->nCol = nCol;
  94477. p->nKeyCol = nKeyCol;
  94478. p->current.anDLt = (tRowcnt*)&p[1];
  94479. p->current.anEq = &p->current.anDLt[nColUp];
  94480. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94481. {
  94482. u8 *pSpace; /* Allocated space not yet assigned */
  94483. int i; /* Used to iterate through p->aSample[] */
  94484. p->iGet = -1;
  94485. p->mxSample = mxSample;
  94486. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  94487. p->current.anLt = &p->current.anEq[nColUp];
  94488. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  94489. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  94490. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  94491. p->aBest = &p->a[mxSample];
  94492. pSpace = (u8*)(&p->a[mxSample+nCol]);
  94493. for(i=0; i<(mxSample+nCol); i++){
  94494. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  94495. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  94496. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  94497. }
  94498. assert( (pSpace - (u8*)p)==n );
  94499. for(i=0; i<nCol; i++){
  94500. p->aBest[i].iCol = i;
  94501. }
  94502. }
  94503. #endif
  94504. /* Return a pointer to the allocated object to the caller. Note that
  94505. ** only the pointer (the 2nd parameter) matters. The size of the object
  94506. ** (given by the 3rd parameter) is never used and can be any positive
  94507. ** value. */
  94508. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  94509. }
  94510. static const FuncDef statInitFuncdef = {
  94511. 2+IsStat34, /* nArg */
  94512. SQLITE_UTF8, /* funcFlags */
  94513. 0, /* pUserData */
  94514. 0, /* pNext */
  94515. statInit, /* xSFunc */
  94516. 0, /* xFinalize */
  94517. "stat_init", /* zName */
  94518. {0}
  94519. };
  94520. #ifdef SQLITE_ENABLE_STAT4
  94521. /*
  94522. ** pNew and pOld are both candidate non-periodic samples selected for
  94523. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  94524. ** considering only any trailing columns and the sample hash value, this
  94525. ** function returns true if sample pNew is to be preferred over pOld.
  94526. ** In other words, if we assume that the cardinalities of the selected
  94527. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  94528. **
  94529. ** This function assumes that for each argument sample, the contents of
  94530. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  94531. */
  94532. static int sampleIsBetterPost(
  94533. Stat4Accum *pAccum,
  94534. Stat4Sample *pNew,
  94535. Stat4Sample *pOld
  94536. ){
  94537. int nCol = pAccum->nCol;
  94538. int i;
  94539. assert( pNew->iCol==pOld->iCol );
  94540. for(i=pNew->iCol+1; i<nCol; i++){
  94541. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  94542. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  94543. }
  94544. if( pNew->iHash>pOld->iHash ) return 1;
  94545. return 0;
  94546. }
  94547. #endif
  94548. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94549. /*
  94550. ** Return true if pNew is to be preferred over pOld.
  94551. **
  94552. ** This function assumes that for each argument sample, the contents of
  94553. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  94554. */
  94555. static int sampleIsBetter(
  94556. Stat4Accum *pAccum,
  94557. Stat4Sample *pNew,
  94558. Stat4Sample *pOld
  94559. ){
  94560. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  94561. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  94562. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  94563. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  94564. if( (nEqNew>nEqOld) ) return 1;
  94565. #ifdef SQLITE_ENABLE_STAT4
  94566. if( nEqNew==nEqOld ){
  94567. if( pNew->iCol<pOld->iCol ) return 1;
  94568. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  94569. }
  94570. return 0;
  94571. #else
  94572. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  94573. #endif
  94574. }
  94575. /*
  94576. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  94577. ** remove the least desirable sample from p->a[] to make room.
  94578. */
  94579. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  94580. Stat4Sample *pSample = 0;
  94581. int i;
  94582. assert( IsStat4 || nEqZero==0 );
  94583. #ifdef SQLITE_ENABLE_STAT4
  94584. /* Stat4Accum.nMaxEqZero is set to the maximum number of leading 0
  94585. ** values in the anEq[] array of any sample in Stat4Accum.a[]. In
  94586. ** other words, if nMaxEqZero is n, then it is guaranteed that there
  94587. ** are no samples with Stat4Sample.anEq[m]==0 for (m>=n). */
  94588. if( nEqZero>p->nMaxEqZero ){
  94589. p->nMaxEqZero = nEqZero;
  94590. }
  94591. if( pNew->isPSample==0 ){
  94592. Stat4Sample *pUpgrade = 0;
  94593. assert( pNew->anEq[pNew->iCol]>0 );
  94594. /* This sample is being added because the prefix that ends in column
  94595. ** iCol occurs many times in the table. However, if we have already
  94596. ** added a sample that shares this prefix, there is no need to add
  94597. ** this one. Instead, upgrade the priority of the highest priority
  94598. ** existing sample that shares this prefix. */
  94599. for(i=p->nSample-1; i>=0; i--){
  94600. Stat4Sample *pOld = &p->a[i];
  94601. if( pOld->anEq[pNew->iCol]==0 ){
  94602. if( pOld->isPSample ) return;
  94603. assert( pOld->iCol>pNew->iCol );
  94604. assert( sampleIsBetter(p, pNew, pOld) );
  94605. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  94606. pUpgrade = pOld;
  94607. }
  94608. }
  94609. }
  94610. if( pUpgrade ){
  94611. pUpgrade->iCol = pNew->iCol;
  94612. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  94613. goto find_new_min;
  94614. }
  94615. }
  94616. #endif
  94617. /* If necessary, remove sample iMin to make room for the new sample. */
  94618. if( p->nSample>=p->mxSample ){
  94619. Stat4Sample *pMin = &p->a[p->iMin];
  94620. tRowcnt *anEq = pMin->anEq;
  94621. tRowcnt *anLt = pMin->anLt;
  94622. tRowcnt *anDLt = pMin->anDLt;
  94623. sampleClear(p->db, pMin);
  94624. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  94625. pSample = &p->a[p->nSample-1];
  94626. pSample->nRowid = 0;
  94627. pSample->anEq = anEq;
  94628. pSample->anDLt = anDLt;
  94629. pSample->anLt = anLt;
  94630. p->nSample = p->mxSample-1;
  94631. }
  94632. /* The "rows less-than" for the rowid column must be greater than that
  94633. ** for the last sample in the p->a[] array. Otherwise, the samples would
  94634. ** be out of order. */
  94635. #ifdef SQLITE_ENABLE_STAT4
  94636. assert( p->nSample==0
  94637. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  94638. #endif
  94639. /* Insert the new sample */
  94640. pSample = &p->a[p->nSample];
  94641. sampleCopy(p, pSample, pNew);
  94642. p->nSample++;
  94643. /* Zero the first nEqZero entries in the anEq[] array. */
  94644. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  94645. #ifdef SQLITE_ENABLE_STAT4
  94646. find_new_min:
  94647. #endif
  94648. if( p->nSample>=p->mxSample ){
  94649. int iMin = -1;
  94650. for(i=0; i<p->mxSample; i++){
  94651. if( p->a[i].isPSample ) continue;
  94652. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  94653. iMin = i;
  94654. }
  94655. }
  94656. assert( iMin>=0 );
  94657. p->iMin = iMin;
  94658. }
  94659. }
  94660. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  94661. /*
  94662. ** Field iChng of the index being scanned has changed. So at this point
  94663. ** p->current contains a sample that reflects the previous row of the
  94664. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  94665. ** correct at this point.
  94666. */
  94667. static void samplePushPrevious(Stat4Accum *p, int iChng){
  94668. #ifdef SQLITE_ENABLE_STAT4
  94669. int i;
  94670. /* Check if any samples from the aBest[] array should be pushed
  94671. ** into IndexSample.a[] at this point. */
  94672. for(i=(p->nCol-2); i>=iChng; i--){
  94673. Stat4Sample *pBest = &p->aBest[i];
  94674. pBest->anEq[i] = p->current.anEq[i];
  94675. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  94676. sampleInsert(p, pBest, i);
  94677. }
  94678. }
  94679. /* Check that no sample contains an anEq[] entry with an index of
  94680. ** p->nMaxEqZero or greater set to zero. */
  94681. for(i=p->nSample-1; i>=0; i--){
  94682. int j;
  94683. for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
  94684. }
  94685. /* Update the anEq[] fields of any samples already collected. */
  94686. if( iChng<p->nMaxEqZero ){
  94687. for(i=p->nSample-1; i>=0; i--){
  94688. int j;
  94689. for(j=iChng; j<p->nCol; j++){
  94690. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  94691. }
  94692. }
  94693. p->nMaxEqZero = iChng;
  94694. }
  94695. #endif
  94696. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  94697. if( iChng==0 ){
  94698. tRowcnt nLt = p->current.anLt[0];
  94699. tRowcnt nEq = p->current.anEq[0];
  94700. /* Check if this is to be a periodic sample. If so, add it. */
  94701. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  94702. p->current.isPSample = 1;
  94703. sampleInsert(p, &p->current, 0);
  94704. p->current.isPSample = 0;
  94705. }else
  94706. /* Or if it is a non-periodic sample. Add it in this case too. */
  94707. if( p->nSample<p->mxSample
  94708. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  94709. ){
  94710. sampleInsert(p, &p->current, 0);
  94711. }
  94712. }
  94713. #endif
  94714. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  94715. UNUSED_PARAMETER( p );
  94716. UNUSED_PARAMETER( iChng );
  94717. #endif
  94718. }
  94719. /*
  94720. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  94721. ** Arguments:
  94722. **
  94723. ** P Pointer to the Stat4Accum object created by stat_init()
  94724. ** C Index of left-most column to differ from previous row
  94725. ** R Rowid for the current row. Might be a key record for
  94726. ** WITHOUT ROWID tables.
  94727. **
  94728. ** This SQL function always returns NULL. It's purpose it to accumulate
  94729. ** statistical data and/or samples in the Stat4Accum object about the
  94730. ** index being analyzed. The stat_get() SQL function will later be used to
  94731. ** extract relevant information for constructing the sqlite_statN tables.
  94732. **
  94733. ** The R parameter is only used for STAT3 and STAT4
  94734. */
  94735. static void statPush(
  94736. sqlite3_context *context,
  94737. int argc,
  94738. sqlite3_value **argv
  94739. ){
  94740. int i;
  94741. /* The three function arguments */
  94742. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  94743. int iChng = sqlite3_value_int(argv[1]);
  94744. UNUSED_PARAMETER( argc );
  94745. UNUSED_PARAMETER( context );
  94746. assert( p->nCol>0 );
  94747. assert( iChng<p->nCol );
  94748. if( p->nRow==0 ){
  94749. /* This is the first call to this function. Do initialization. */
  94750. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  94751. }else{
  94752. /* Second and subsequent calls get processed here */
  94753. samplePushPrevious(p, iChng);
  94754. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  94755. ** to the current row of the index. */
  94756. for(i=0; i<iChng; i++){
  94757. p->current.anEq[i]++;
  94758. }
  94759. for(i=iChng; i<p->nCol; i++){
  94760. p->current.anDLt[i]++;
  94761. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94762. p->current.anLt[i] += p->current.anEq[i];
  94763. #endif
  94764. p->current.anEq[i] = 1;
  94765. }
  94766. }
  94767. p->nRow++;
  94768. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94769. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  94770. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  94771. }else{
  94772. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  94773. sqlite3_value_blob(argv[2]));
  94774. }
  94775. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  94776. #endif
  94777. #ifdef SQLITE_ENABLE_STAT4
  94778. {
  94779. tRowcnt nLt = p->current.anLt[p->nCol-1];
  94780. /* Check if this is to be a periodic sample. If so, add it. */
  94781. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  94782. p->current.isPSample = 1;
  94783. p->current.iCol = 0;
  94784. sampleInsert(p, &p->current, p->nCol-1);
  94785. p->current.isPSample = 0;
  94786. }
  94787. /* Update the aBest[] array. */
  94788. for(i=0; i<(p->nCol-1); i++){
  94789. p->current.iCol = i;
  94790. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  94791. sampleCopy(p, &p->aBest[i], &p->current);
  94792. }
  94793. }
  94794. }
  94795. #endif
  94796. }
  94797. static const FuncDef statPushFuncdef = {
  94798. 2+IsStat34, /* nArg */
  94799. SQLITE_UTF8, /* funcFlags */
  94800. 0, /* pUserData */
  94801. 0, /* pNext */
  94802. statPush, /* xSFunc */
  94803. 0, /* xFinalize */
  94804. "stat_push", /* zName */
  94805. {0}
  94806. };
  94807. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  94808. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  94809. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  94810. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  94811. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  94812. /*
  94813. ** Implementation of the stat_get(P,J) SQL function. This routine is
  94814. ** used to query statistical information that has been gathered into
  94815. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  94816. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  94817. ** The content to returned is determined by the parameter J
  94818. ** which is one of the STAT_GET_xxxx values defined above.
  94819. **
  94820. ** The stat_get(P,J) function is not available to generic SQL. It is
  94821. ** inserted as part of a manually constructed bytecode program. (See
  94822. ** the callStatGet() routine below.) It is guaranteed that the P
  94823. ** parameter will always be a poiner to a Stat4Accum object, never a
  94824. ** NULL.
  94825. **
  94826. ** If neither STAT3 nor STAT4 are enabled, then J is always
  94827. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  94828. ** a one-parameter function, stat_get(P), that always returns the
  94829. ** stat1 table entry information.
  94830. */
  94831. static void statGet(
  94832. sqlite3_context *context,
  94833. int argc,
  94834. sqlite3_value **argv
  94835. ){
  94836. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  94837. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94838. /* STAT3 and STAT4 have a parameter on this routine. */
  94839. int eCall = sqlite3_value_int(argv[1]);
  94840. assert( argc==2 );
  94841. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  94842. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  94843. || eCall==STAT_GET_NDLT
  94844. );
  94845. if( eCall==STAT_GET_STAT1 )
  94846. #else
  94847. assert( argc==1 );
  94848. #endif
  94849. {
  94850. /* Return the value to store in the "stat" column of the sqlite_stat1
  94851. ** table for this index.
  94852. **
  94853. ** The value is a string composed of a list of integers describing
  94854. ** the index. The first integer in the list is the total number of
  94855. ** entries in the index. There is one additional integer in the list
  94856. ** for each indexed column. This additional integer is an estimate of
  94857. ** the number of rows matched by a stabbing query on the index using
  94858. ** a key with the corresponding number of fields. In other words,
  94859. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  94860. ** "100 10 2", then SQLite estimates that:
  94861. **
  94862. ** * the index contains 100 rows,
  94863. ** * "WHERE a=?" matches 10 rows, and
  94864. ** * "WHERE a=? AND b=?" matches 2 rows.
  94865. **
  94866. ** If D is the count of distinct values and K is the total number of
  94867. ** rows, then each estimate is computed as:
  94868. **
  94869. ** I = (K+D-1)/D
  94870. */
  94871. char *z;
  94872. int i;
  94873. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  94874. if( zRet==0 ){
  94875. sqlite3_result_error_nomem(context);
  94876. return;
  94877. }
  94878. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  94879. z = zRet + sqlite3Strlen30(zRet);
  94880. for(i=0; i<p->nKeyCol; i++){
  94881. u64 nDistinct = p->current.anDLt[i] + 1;
  94882. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  94883. sqlite3_snprintf(24, z, " %llu", iVal);
  94884. z += sqlite3Strlen30(z);
  94885. assert( p->current.anEq[i] );
  94886. }
  94887. assert( z[0]=='\0' && z>zRet );
  94888. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  94889. }
  94890. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94891. else if( eCall==STAT_GET_ROWID ){
  94892. if( p->iGet<0 ){
  94893. samplePushPrevious(p, 0);
  94894. p->iGet = 0;
  94895. }
  94896. if( p->iGet<p->nSample ){
  94897. Stat4Sample *pS = p->a + p->iGet;
  94898. if( pS->nRowid==0 ){
  94899. sqlite3_result_int64(context, pS->u.iRowid);
  94900. }else{
  94901. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  94902. SQLITE_TRANSIENT);
  94903. }
  94904. }
  94905. }else{
  94906. tRowcnt *aCnt = 0;
  94907. assert( p->iGet<p->nSample );
  94908. switch( eCall ){
  94909. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  94910. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  94911. default: {
  94912. aCnt = p->a[p->iGet].anDLt;
  94913. p->iGet++;
  94914. break;
  94915. }
  94916. }
  94917. if( IsStat3 ){
  94918. sqlite3_result_int64(context, (i64)aCnt[0]);
  94919. }else{
  94920. char *zRet = sqlite3MallocZero(p->nCol * 25);
  94921. if( zRet==0 ){
  94922. sqlite3_result_error_nomem(context);
  94923. }else{
  94924. int i;
  94925. char *z = zRet;
  94926. for(i=0; i<p->nCol; i++){
  94927. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  94928. z += sqlite3Strlen30(z);
  94929. }
  94930. assert( z[0]=='\0' && z>zRet );
  94931. z[-1] = '\0';
  94932. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  94933. }
  94934. }
  94935. }
  94936. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  94937. #ifndef SQLITE_DEBUG
  94938. UNUSED_PARAMETER( argc );
  94939. #endif
  94940. }
  94941. static const FuncDef statGetFuncdef = {
  94942. 1+IsStat34, /* nArg */
  94943. SQLITE_UTF8, /* funcFlags */
  94944. 0, /* pUserData */
  94945. 0, /* pNext */
  94946. statGet, /* xSFunc */
  94947. 0, /* xFinalize */
  94948. "stat_get", /* zName */
  94949. {0}
  94950. };
  94951. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  94952. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  94953. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94954. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  94955. #elif SQLITE_DEBUG
  94956. assert( iParam==STAT_GET_STAT1 );
  94957. #else
  94958. UNUSED_PARAMETER( iParam );
  94959. #endif
  94960. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
  94961. (char*)&statGetFuncdef, P4_FUNCDEF);
  94962. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  94963. }
  94964. /*
  94965. ** Generate code to do an analysis of all indices associated with
  94966. ** a single table.
  94967. */
  94968. static void analyzeOneTable(
  94969. Parse *pParse, /* Parser context */
  94970. Table *pTab, /* Table whose indices are to be analyzed */
  94971. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  94972. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  94973. int iMem, /* Available memory locations begin here */
  94974. int iTab /* Next available cursor */
  94975. ){
  94976. sqlite3 *db = pParse->db; /* Database handle */
  94977. Index *pIdx; /* An index to being analyzed */
  94978. int iIdxCur; /* Cursor open on index being analyzed */
  94979. int iTabCur; /* Table cursor */
  94980. Vdbe *v; /* The virtual machine being built up */
  94981. int i; /* Loop counter */
  94982. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  94983. int iDb; /* Index of database containing pTab */
  94984. u8 needTableCnt = 1; /* True to count the table */
  94985. int regNewRowid = iMem++; /* Rowid for the inserted record */
  94986. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  94987. int regChng = iMem++; /* Index of changed index field */
  94988. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  94989. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  94990. #endif
  94991. int regTemp = iMem++; /* Temporary use register */
  94992. int regTabname = iMem++; /* Register containing table name */
  94993. int regIdxname = iMem++; /* Register containing index name */
  94994. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  94995. int regPrev = iMem; /* MUST BE LAST (see below) */
  94996. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  94997. Table *pStat1 = 0;
  94998. #endif
  94999. pParse->nMem = MAX(pParse->nMem, iMem);
  95000. v = sqlite3GetVdbe(pParse);
  95001. if( v==0 || NEVER(pTab==0) ){
  95002. return;
  95003. }
  95004. if( pTab->tnum==0 ){
  95005. /* Do not gather statistics on views or virtual tables */
  95006. return;
  95007. }
  95008. if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
  95009. /* Do not gather statistics on system tables */
  95010. return;
  95011. }
  95012. assert( sqlite3BtreeHoldsAllMutexes(db) );
  95013. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95014. assert( iDb>=0 );
  95015. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95016. #ifndef SQLITE_OMIT_AUTHORIZATION
  95017. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  95018. db->aDb[iDb].zDbSName ) ){
  95019. return;
  95020. }
  95021. #endif
  95022. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  95023. if( db->xPreUpdateCallback ){
  95024. pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
  95025. if( pStat1==0 ) return;
  95026. pStat1->zName = (char*)&pStat1[1];
  95027. memcpy(pStat1->zName, "sqlite_stat1", 13);
  95028. pStat1->nCol = 3;
  95029. pStat1->iPKey = -1;
  95030. sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
  95031. }
  95032. #endif
  95033. /* Establish a read-lock on the table at the shared-cache level.
  95034. ** Open a read-only cursor on the table. Also allocate a cursor number
  95035. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  95036. ** this time though. */
  95037. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  95038. iTabCur = iTab++;
  95039. iIdxCur = iTab++;
  95040. pParse->nTab = MAX(pParse->nTab, iTab);
  95041. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  95042. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  95043. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95044. int nCol; /* Number of columns in pIdx. "N" */
  95045. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  95046. int addrNextRow; /* Address of "next_row:" */
  95047. const char *zIdxName; /* Name of the index */
  95048. int nColTest; /* Number of columns to test for changes */
  95049. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  95050. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  95051. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  95052. nCol = pIdx->nKeyCol;
  95053. zIdxName = pTab->zName;
  95054. nColTest = nCol - 1;
  95055. }else{
  95056. nCol = pIdx->nColumn;
  95057. zIdxName = pIdx->zName;
  95058. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  95059. }
  95060. /* Populate the register containing the index name. */
  95061. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  95062. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  95063. /*
  95064. ** Pseudo-code for loop that calls stat_push():
  95065. **
  95066. ** Rewind csr
  95067. ** if eof(csr) goto end_of_scan;
  95068. ** regChng = 0
  95069. ** goto chng_addr_0;
  95070. **
  95071. ** next_row:
  95072. ** regChng = 0
  95073. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  95074. ** regChng = 1
  95075. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  95076. ** ...
  95077. ** regChng = N
  95078. ** goto chng_addr_N
  95079. **
  95080. ** chng_addr_0:
  95081. ** regPrev(0) = idx(0)
  95082. ** chng_addr_1:
  95083. ** regPrev(1) = idx(1)
  95084. ** ...
  95085. **
  95086. ** endDistinctTest:
  95087. ** regRowid = idx(rowid)
  95088. ** stat_push(P, regChng, regRowid)
  95089. ** Next csr
  95090. ** if !eof(csr) goto next_row;
  95091. **
  95092. ** end_of_scan:
  95093. */
  95094. /* Make sure there are enough memory cells allocated to accommodate
  95095. ** the regPrev array and a trailing rowid (the rowid slot is required
  95096. ** when building a record to insert into the sample column of
  95097. ** the sqlite_stat4 table. */
  95098. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  95099. /* Open a read-only cursor on the index being analyzed. */
  95100. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  95101. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  95102. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  95103. VdbeComment((v, "%s", pIdx->zName));
  95104. /* Invoke the stat_init() function. The arguments are:
  95105. **
  95106. ** (1) the number of columns in the index including the rowid
  95107. ** (or for a WITHOUT ROWID table, the number of PK columns),
  95108. ** (2) the number of columns in the key without the rowid/pk
  95109. ** (3) the number of rows in the index,
  95110. **
  95111. **
  95112. ** The third argument is only used for STAT3 and STAT4
  95113. */
  95114. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95115. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  95116. #endif
  95117. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  95118. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  95119. sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
  95120. (char*)&statInitFuncdef, P4_FUNCDEF);
  95121. sqlite3VdbeChangeP5(v, 2+IsStat34);
  95122. /* Implementation of the following:
  95123. **
  95124. ** Rewind csr
  95125. ** if eof(csr) goto end_of_scan;
  95126. ** regChng = 0
  95127. ** goto next_push_0;
  95128. **
  95129. */
  95130. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  95131. VdbeCoverage(v);
  95132. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  95133. addrNextRow = sqlite3VdbeCurrentAddr(v);
  95134. if( nColTest>0 ){
  95135. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  95136. int *aGotoChng; /* Array of jump instruction addresses */
  95137. aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  95138. if( aGotoChng==0 ) continue;
  95139. /*
  95140. ** next_row:
  95141. ** regChng = 0
  95142. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  95143. ** regChng = 1
  95144. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  95145. ** ...
  95146. ** regChng = N
  95147. ** goto endDistinctTest
  95148. */
  95149. sqlite3VdbeAddOp0(v, OP_Goto);
  95150. addrNextRow = sqlite3VdbeCurrentAddr(v);
  95151. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  95152. /* For a single-column UNIQUE index, once we have found a non-NULL
  95153. ** row, we know that all the rest will be distinct, so skip
  95154. ** subsequent distinctness tests. */
  95155. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  95156. VdbeCoverage(v);
  95157. }
  95158. for(i=0; i<nColTest; i++){
  95159. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  95160. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  95161. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  95162. aGotoChng[i] =
  95163. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  95164. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  95165. VdbeCoverage(v);
  95166. }
  95167. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  95168. sqlite3VdbeGoto(v, endDistinctTest);
  95169. /*
  95170. ** chng_addr_0:
  95171. ** regPrev(0) = idx(0)
  95172. ** chng_addr_1:
  95173. ** regPrev(1) = idx(1)
  95174. ** ...
  95175. */
  95176. sqlite3VdbeJumpHere(v, addrNextRow-1);
  95177. for(i=0; i<nColTest; i++){
  95178. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  95179. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  95180. }
  95181. sqlite3VdbeResolveLabel(v, endDistinctTest);
  95182. sqlite3DbFree(db, aGotoChng);
  95183. }
  95184. /*
  95185. ** chng_addr_N:
  95186. ** regRowid = idx(rowid) // STAT34 only
  95187. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  95188. ** Next csr
  95189. ** if !eof(csr) goto next_row;
  95190. */
  95191. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95192. assert( regRowid==(regStat4+2) );
  95193. if( HasRowid(pTab) ){
  95194. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  95195. }else{
  95196. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  95197. int j, k, regKey;
  95198. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  95199. for(j=0; j<pPk->nKeyCol; j++){
  95200. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  95201. assert( k>=0 && k<pIdx->nColumn );
  95202. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  95203. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  95204. }
  95205. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  95206. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  95207. }
  95208. #endif
  95209. assert( regChng==(regStat4+1) );
  95210. sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
  95211. (char*)&statPushFuncdef, P4_FUNCDEF);
  95212. sqlite3VdbeChangeP5(v, 2+IsStat34);
  95213. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  95214. /* Add the entry to the stat1 table. */
  95215. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  95216. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  95217. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  95218. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  95219. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  95220. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  95221. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  95222. #endif
  95223. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  95224. /* Add the entries to the stat3 or stat4 table. */
  95225. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95226. {
  95227. int regEq = regStat1;
  95228. int regLt = regStat1+1;
  95229. int regDLt = regStat1+2;
  95230. int regSample = regStat1+3;
  95231. int regCol = regStat1+4;
  95232. int regSampleRowid = regCol + nCol;
  95233. int addrNext;
  95234. int addrIsNull;
  95235. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  95236. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  95237. addrNext = sqlite3VdbeCurrentAddr(v);
  95238. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  95239. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  95240. VdbeCoverage(v);
  95241. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  95242. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  95243. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  95244. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  95245. /* We know that the regSampleRowid row exists because it was read by
  95246. ** the previous loop. Thus the not-found jump of seekOp will never
  95247. ** be taken */
  95248. VdbeCoverageNeverTaken(v);
  95249. #ifdef SQLITE_ENABLE_STAT3
  95250. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
  95251. #else
  95252. for(i=0; i<nCol; i++){
  95253. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  95254. }
  95255. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  95256. #endif
  95257. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  95258. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  95259. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  95260. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  95261. sqlite3VdbeJumpHere(v, addrIsNull);
  95262. }
  95263. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  95264. /* End of analysis */
  95265. sqlite3VdbeJumpHere(v, addrRewind);
  95266. }
  95267. /* Create a single sqlite_stat1 entry containing NULL as the index
  95268. ** name and the row count as the content.
  95269. */
  95270. if( pOnlyIdx==0 && needTableCnt ){
  95271. VdbeComment((v, "%s", pTab->zName));
  95272. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  95273. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  95274. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  95275. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  95276. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  95277. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  95278. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  95279. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  95280. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  95281. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  95282. #endif
  95283. sqlite3VdbeJumpHere(v, jZeroRows);
  95284. }
  95285. }
  95286. /*
  95287. ** Generate code that will cause the most recent index analysis to
  95288. ** be loaded into internal hash tables where is can be used.
  95289. */
  95290. static void loadAnalysis(Parse *pParse, int iDb){
  95291. Vdbe *v = sqlite3GetVdbe(pParse);
  95292. if( v ){
  95293. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  95294. }
  95295. }
  95296. /*
  95297. ** Generate code that will do an analysis of an entire database
  95298. */
  95299. static void analyzeDatabase(Parse *pParse, int iDb){
  95300. sqlite3 *db = pParse->db;
  95301. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  95302. HashElem *k;
  95303. int iStatCur;
  95304. int iMem;
  95305. int iTab;
  95306. sqlite3BeginWriteOperation(pParse, 0, iDb);
  95307. iStatCur = pParse->nTab;
  95308. pParse->nTab += 3;
  95309. openStatTable(pParse, iDb, iStatCur, 0, 0);
  95310. iMem = pParse->nMem+1;
  95311. iTab = pParse->nTab;
  95312. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95313. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  95314. Table *pTab = (Table*)sqliteHashData(k);
  95315. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  95316. }
  95317. loadAnalysis(pParse, iDb);
  95318. }
  95319. /*
  95320. ** Generate code that will do an analysis of a single table in
  95321. ** a database. If pOnlyIdx is not NULL then it is a single index
  95322. ** in pTab that should be analyzed.
  95323. */
  95324. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  95325. int iDb;
  95326. int iStatCur;
  95327. assert( pTab!=0 );
  95328. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  95329. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  95330. sqlite3BeginWriteOperation(pParse, 0, iDb);
  95331. iStatCur = pParse->nTab;
  95332. pParse->nTab += 3;
  95333. if( pOnlyIdx ){
  95334. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  95335. }else{
  95336. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  95337. }
  95338. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  95339. loadAnalysis(pParse, iDb);
  95340. }
  95341. /*
  95342. ** Generate code for the ANALYZE command. The parser calls this routine
  95343. ** when it recognizes an ANALYZE command.
  95344. **
  95345. ** ANALYZE -- 1
  95346. ** ANALYZE <database> -- 2
  95347. ** ANALYZE ?<database>.?<tablename> -- 3
  95348. **
  95349. ** Form 1 causes all indices in all attached databases to be analyzed.
  95350. ** Form 2 analyzes all indices the single database named.
  95351. ** Form 3 analyzes all indices associated with the named table.
  95352. */
  95353. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  95354. sqlite3 *db = pParse->db;
  95355. int iDb;
  95356. int i;
  95357. char *z, *zDb;
  95358. Table *pTab;
  95359. Index *pIdx;
  95360. Token *pTableName;
  95361. Vdbe *v;
  95362. /* Read the database schema. If an error occurs, leave an error message
  95363. ** and code in pParse and return NULL. */
  95364. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  95365. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  95366. return;
  95367. }
  95368. assert( pName2!=0 || pName1==0 );
  95369. if( pName1==0 ){
  95370. /* Form 1: Analyze everything */
  95371. for(i=0; i<db->nDb; i++){
  95372. if( i==1 ) continue; /* Do not analyze the TEMP database */
  95373. analyzeDatabase(pParse, i);
  95374. }
  95375. }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
  95376. /* Analyze the schema named as the argument */
  95377. analyzeDatabase(pParse, iDb);
  95378. }else{
  95379. /* Form 3: Analyze the table or index named as an argument */
  95380. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  95381. if( iDb>=0 ){
  95382. zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
  95383. z = sqlite3NameFromToken(db, pTableName);
  95384. if( z ){
  95385. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  95386. analyzeTable(pParse, pIdx->pTable, pIdx);
  95387. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  95388. analyzeTable(pParse, pTab, 0);
  95389. }
  95390. sqlite3DbFree(db, z);
  95391. }
  95392. }
  95393. }
  95394. if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
  95395. sqlite3VdbeAddOp0(v, OP_Expire);
  95396. }
  95397. }
  95398. /*
  95399. ** Used to pass information from the analyzer reader through to the
  95400. ** callback routine.
  95401. */
  95402. typedef struct analysisInfo analysisInfo;
  95403. struct analysisInfo {
  95404. sqlite3 *db;
  95405. const char *zDatabase;
  95406. };
  95407. /*
  95408. ** The first argument points to a nul-terminated string containing a
  95409. ** list of space separated integers. Read the first nOut of these into
  95410. ** the array aOut[].
  95411. */
  95412. static void decodeIntArray(
  95413. char *zIntArray, /* String containing int array to decode */
  95414. int nOut, /* Number of slots in aOut[] */
  95415. tRowcnt *aOut, /* Store integers here */
  95416. LogEst *aLog, /* Or, if aOut==0, here */
  95417. Index *pIndex /* Handle extra flags for this index, if not NULL */
  95418. ){
  95419. char *z = zIntArray;
  95420. int c;
  95421. int i;
  95422. tRowcnt v;
  95423. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95424. if( z==0 ) z = "";
  95425. #else
  95426. assert( z!=0 );
  95427. #endif
  95428. for(i=0; *z && i<nOut; i++){
  95429. v = 0;
  95430. while( (c=z[0])>='0' && c<='9' ){
  95431. v = v*10 + c - '0';
  95432. z++;
  95433. }
  95434. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95435. if( aOut ) aOut[i] = v;
  95436. if( aLog ) aLog[i] = sqlite3LogEst(v);
  95437. #else
  95438. assert( aOut==0 );
  95439. UNUSED_PARAMETER(aOut);
  95440. assert( aLog!=0 );
  95441. aLog[i] = sqlite3LogEst(v);
  95442. #endif
  95443. if( *z==' ' ) z++;
  95444. }
  95445. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  95446. assert( pIndex!=0 ); {
  95447. #else
  95448. if( pIndex ){
  95449. #endif
  95450. pIndex->bUnordered = 0;
  95451. pIndex->noSkipScan = 0;
  95452. while( z[0] ){
  95453. if( sqlite3_strglob("unordered*", z)==0 ){
  95454. pIndex->bUnordered = 1;
  95455. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  95456. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  95457. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  95458. pIndex->noSkipScan = 1;
  95459. }
  95460. #ifdef SQLITE_ENABLE_COSTMULT
  95461. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  95462. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  95463. }
  95464. #endif
  95465. while( z[0]!=0 && z[0]!=' ' ) z++;
  95466. while( z[0]==' ' ) z++;
  95467. }
  95468. }
  95469. }
  95470. /*
  95471. ** This callback is invoked once for each index when reading the
  95472. ** sqlite_stat1 table.
  95473. **
  95474. ** argv[0] = name of the table
  95475. ** argv[1] = name of the index (might be NULL)
  95476. ** argv[2] = results of analysis - on integer for each column
  95477. **
  95478. ** Entries for which argv[1]==NULL simply record the number of rows in
  95479. ** the table.
  95480. */
  95481. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  95482. analysisInfo *pInfo = (analysisInfo*)pData;
  95483. Index *pIndex;
  95484. Table *pTable;
  95485. const char *z;
  95486. assert( argc==3 );
  95487. UNUSED_PARAMETER2(NotUsed, argc);
  95488. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  95489. return 0;
  95490. }
  95491. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  95492. if( pTable==0 ){
  95493. return 0;
  95494. }
  95495. if( argv[1]==0 ){
  95496. pIndex = 0;
  95497. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  95498. pIndex = sqlite3PrimaryKeyIndex(pTable);
  95499. }else{
  95500. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  95501. }
  95502. z = argv[2];
  95503. if( pIndex ){
  95504. tRowcnt *aiRowEst = 0;
  95505. int nCol = pIndex->nKeyCol+1;
  95506. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95507. /* Index.aiRowEst may already be set here if there are duplicate
  95508. ** sqlite_stat1 entries for this index. In that case just clobber
  95509. ** the old data with the new instead of allocating a new array. */
  95510. if( pIndex->aiRowEst==0 ){
  95511. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  95512. if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  95513. }
  95514. aiRowEst = pIndex->aiRowEst;
  95515. #endif
  95516. pIndex->bUnordered = 0;
  95517. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  95518. pIndex->hasStat1 = 1;
  95519. if( pIndex->pPartIdxWhere==0 ){
  95520. pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  95521. pTable->tabFlags |= TF_HasStat1;
  95522. }
  95523. }else{
  95524. Index fakeIdx;
  95525. fakeIdx.szIdxRow = pTable->szTabRow;
  95526. #ifdef SQLITE_ENABLE_COSTMULT
  95527. fakeIdx.pTable = pTable;
  95528. #endif
  95529. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  95530. pTable->szTabRow = fakeIdx.szIdxRow;
  95531. pTable->tabFlags |= TF_HasStat1;
  95532. }
  95533. return 0;
  95534. }
  95535. /*
  95536. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  95537. ** and its contents.
  95538. */
  95539. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  95540. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95541. if( pIdx->aSample ){
  95542. int j;
  95543. for(j=0; j<pIdx->nSample; j++){
  95544. IndexSample *p = &pIdx->aSample[j];
  95545. sqlite3DbFree(db, p->p);
  95546. }
  95547. sqlite3DbFree(db, pIdx->aSample);
  95548. }
  95549. if( db && db->pnBytesFreed==0 ){
  95550. pIdx->nSample = 0;
  95551. pIdx->aSample = 0;
  95552. }
  95553. #else
  95554. UNUSED_PARAMETER(db);
  95555. UNUSED_PARAMETER(pIdx);
  95556. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  95557. }
  95558. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95559. /*
  95560. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  95561. ** stored in pIdx->aSample[].
  95562. */
  95563. static void initAvgEq(Index *pIdx){
  95564. if( pIdx ){
  95565. IndexSample *aSample = pIdx->aSample;
  95566. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  95567. int iCol;
  95568. int nCol = 1;
  95569. if( pIdx->nSampleCol>1 ){
  95570. /* If this is stat4 data, then calculate aAvgEq[] values for all
  95571. ** sample columns except the last. The last is always set to 1, as
  95572. ** once the trailing PK fields are considered all index keys are
  95573. ** unique. */
  95574. nCol = pIdx->nSampleCol-1;
  95575. pIdx->aAvgEq[nCol] = 1;
  95576. }
  95577. for(iCol=0; iCol<nCol; iCol++){
  95578. int nSample = pIdx->nSample;
  95579. int i; /* Used to iterate through samples */
  95580. tRowcnt sumEq = 0; /* Sum of the nEq values */
  95581. tRowcnt avgEq = 0;
  95582. tRowcnt nRow; /* Number of rows in index */
  95583. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  95584. i64 nDist100; /* Number of distinct values in index */
  95585. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  95586. nRow = pFinal->anLt[iCol];
  95587. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  95588. nSample--;
  95589. }else{
  95590. nRow = pIdx->aiRowEst[0];
  95591. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  95592. }
  95593. pIdx->nRowEst0 = nRow;
  95594. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  95595. ** occur in the stat4 table for this index. Set sumEq to the sum of
  95596. ** the nEq values for column iCol for the same set (adding the value
  95597. ** only once where there exist duplicate prefixes). */
  95598. for(i=0; i<nSample; i++){
  95599. if( i==(pIdx->nSample-1)
  95600. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  95601. ){
  95602. sumEq += aSample[i].anEq[iCol];
  95603. nSum100 += 100;
  95604. }
  95605. }
  95606. if( nDist100>nSum100 && sumEq<nRow ){
  95607. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  95608. }
  95609. if( avgEq==0 ) avgEq = 1;
  95610. pIdx->aAvgEq[iCol] = avgEq;
  95611. }
  95612. }
  95613. }
  95614. /*
  95615. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  95616. ** is supplied instead, find the PRIMARY KEY index for that table.
  95617. */
  95618. static Index *findIndexOrPrimaryKey(
  95619. sqlite3 *db,
  95620. const char *zName,
  95621. const char *zDb
  95622. ){
  95623. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  95624. if( pIdx==0 ){
  95625. Table *pTab = sqlite3FindTable(db, zName, zDb);
  95626. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  95627. }
  95628. return pIdx;
  95629. }
  95630. /*
  95631. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  95632. ** into the relevant Index.aSample[] arrays.
  95633. **
  95634. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  95635. ** data equivalent to the following (statements are different for stat3,
  95636. ** see the caller of this function for details):
  95637. **
  95638. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  95639. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  95640. **
  95641. ** where %Q is replaced with the database name before the SQL is executed.
  95642. */
  95643. static int loadStatTbl(
  95644. sqlite3 *db, /* Database handle */
  95645. int bStat3, /* Assume single column records only */
  95646. const char *zSql1, /* SQL statement 1 (see above) */
  95647. const char *zSql2, /* SQL statement 2 (see above) */
  95648. const char *zDb /* Database name (e.g. "main") */
  95649. ){
  95650. int rc; /* Result codes from subroutines */
  95651. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  95652. char *zSql; /* Text of the SQL statement */
  95653. Index *pPrevIdx = 0; /* Previous index in the loop */
  95654. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  95655. assert( db->lookaside.bDisable );
  95656. zSql = sqlite3MPrintf(db, zSql1, zDb);
  95657. if( !zSql ){
  95658. return SQLITE_NOMEM_BKPT;
  95659. }
  95660. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  95661. sqlite3DbFree(db, zSql);
  95662. if( rc ) return rc;
  95663. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  95664. int nIdxCol = 1; /* Number of columns in stat4 records */
  95665. char *zIndex; /* Index name */
  95666. Index *pIdx; /* Pointer to the index object */
  95667. int nSample; /* Number of samples */
  95668. int nByte; /* Bytes of space required */
  95669. int i; /* Bytes of space required */
  95670. tRowcnt *pSpace;
  95671. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  95672. if( zIndex==0 ) continue;
  95673. nSample = sqlite3_column_int(pStmt, 1);
  95674. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  95675. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  95676. /* Index.nSample is non-zero at this point if data has already been
  95677. ** loaded from the stat4 table. In this case ignore stat3 data. */
  95678. if( pIdx==0 || pIdx->nSample ) continue;
  95679. if( bStat3==0 ){
  95680. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  95681. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  95682. nIdxCol = pIdx->nKeyCol;
  95683. }else{
  95684. nIdxCol = pIdx->nColumn;
  95685. }
  95686. }
  95687. pIdx->nSampleCol = nIdxCol;
  95688. nByte = sizeof(IndexSample) * nSample;
  95689. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  95690. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  95691. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  95692. if( pIdx->aSample==0 ){
  95693. sqlite3_finalize(pStmt);
  95694. return SQLITE_NOMEM_BKPT;
  95695. }
  95696. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  95697. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  95698. for(i=0; i<nSample; i++){
  95699. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  95700. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  95701. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  95702. }
  95703. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  95704. }
  95705. rc = sqlite3_finalize(pStmt);
  95706. if( rc ) return rc;
  95707. zSql = sqlite3MPrintf(db, zSql2, zDb);
  95708. if( !zSql ){
  95709. return SQLITE_NOMEM_BKPT;
  95710. }
  95711. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  95712. sqlite3DbFree(db, zSql);
  95713. if( rc ) return rc;
  95714. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  95715. char *zIndex; /* Index name */
  95716. Index *pIdx; /* Pointer to the index object */
  95717. int nCol = 1; /* Number of columns in index */
  95718. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  95719. if( zIndex==0 ) continue;
  95720. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  95721. if( pIdx==0 ) continue;
  95722. /* This next condition is true if data has already been loaded from
  95723. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  95724. nCol = pIdx->nSampleCol;
  95725. if( bStat3 && nCol>1 ) continue;
  95726. if( pIdx!=pPrevIdx ){
  95727. initAvgEq(pPrevIdx);
  95728. pPrevIdx = pIdx;
  95729. }
  95730. pSample = &pIdx->aSample[pIdx->nSample];
  95731. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  95732. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  95733. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  95734. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  95735. ** This is in case the sample record is corrupted. In that case, the
  95736. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  95737. ** end of the allocated buffer before it realizes it is dealing with
  95738. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  95739. ** a buffer overread. */
  95740. pSample->n = sqlite3_column_bytes(pStmt, 4);
  95741. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  95742. if( pSample->p==0 ){
  95743. sqlite3_finalize(pStmt);
  95744. return SQLITE_NOMEM_BKPT;
  95745. }
  95746. if( pSample->n ){
  95747. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  95748. }
  95749. pIdx->nSample++;
  95750. }
  95751. rc = sqlite3_finalize(pStmt);
  95752. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  95753. return rc;
  95754. }
  95755. /*
  95756. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  95757. ** the Index.aSample[] arrays of all indices.
  95758. */
  95759. static int loadStat4(sqlite3 *db, const char *zDb){
  95760. int rc = SQLITE_OK; /* Result codes from subroutines */
  95761. assert( db->lookaside.bDisable );
  95762. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  95763. rc = loadStatTbl(db, 0,
  95764. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  95765. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  95766. zDb
  95767. );
  95768. }
  95769. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  95770. rc = loadStatTbl(db, 1,
  95771. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  95772. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  95773. zDb
  95774. );
  95775. }
  95776. return rc;
  95777. }
  95778. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  95779. /*
  95780. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  95781. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  95782. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  95783. ** Index.aSample[] arrays.
  95784. **
  95785. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  95786. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  95787. ** during compilation and the sqlite_stat3/4 table is present, no data is
  95788. ** read from it.
  95789. **
  95790. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  95791. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  95792. ** returned. However, in this case, data is read from the sqlite_stat1
  95793. ** table (if it is present) before returning.
  95794. **
  95795. ** If an OOM error occurs, this function always sets db->mallocFailed.
  95796. ** This means if the caller does not care about other errors, the return
  95797. ** code may be ignored.
  95798. */
  95799. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  95800. analysisInfo sInfo;
  95801. HashElem *i;
  95802. char *zSql;
  95803. int rc = SQLITE_OK;
  95804. Schema *pSchema = db->aDb[iDb].pSchema;
  95805. assert( iDb>=0 && iDb<db->nDb );
  95806. assert( db->aDb[iDb].pBt!=0 );
  95807. /* Clear any prior statistics */
  95808. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95809. for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
  95810. Table *pTab = sqliteHashData(i);
  95811. pTab->tabFlags &= ~TF_HasStat1;
  95812. }
  95813. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  95814. Index *pIdx = sqliteHashData(i);
  95815. pIdx->hasStat1 = 0;
  95816. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95817. sqlite3DeleteIndexSamples(db, pIdx);
  95818. pIdx->aSample = 0;
  95819. #endif
  95820. }
  95821. /* Load new statistics out of the sqlite_stat1 table */
  95822. sInfo.db = db;
  95823. sInfo.zDatabase = db->aDb[iDb].zDbSName;
  95824. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
  95825. zSql = sqlite3MPrintf(db,
  95826. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  95827. if( zSql==0 ){
  95828. rc = SQLITE_NOMEM_BKPT;
  95829. }else{
  95830. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  95831. sqlite3DbFree(db, zSql);
  95832. }
  95833. }
  95834. /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
  95835. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95836. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  95837. Index *pIdx = sqliteHashData(i);
  95838. if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
  95839. }
  95840. /* Load the statistics from the sqlite_stat4 table. */
  95841. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  95842. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  95843. db->lookaside.bDisable++;
  95844. rc = loadStat4(db, sInfo.zDatabase);
  95845. db->lookaside.bDisable--;
  95846. }
  95847. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  95848. Index *pIdx = sqliteHashData(i);
  95849. sqlite3_free(pIdx->aiRowEst);
  95850. pIdx->aiRowEst = 0;
  95851. }
  95852. #endif
  95853. if( rc==SQLITE_NOMEM ){
  95854. sqlite3OomFault(db);
  95855. }
  95856. return rc;
  95857. }
  95858. #endif /* SQLITE_OMIT_ANALYZE */
  95859. /************** End of analyze.c *********************************************/
  95860. /************** Begin file attach.c ******************************************/
  95861. /*
  95862. ** 2003 April 6
  95863. **
  95864. ** The author disclaims copyright to this source code. In place of
  95865. ** a legal notice, here is a blessing:
  95866. **
  95867. ** May you do good and not evil.
  95868. ** May you find forgiveness for yourself and forgive others.
  95869. ** May you share freely, never taking more than you give.
  95870. **
  95871. *************************************************************************
  95872. ** This file contains code used to implement the ATTACH and DETACH commands.
  95873. */
  95874. /* #include "sqliteInt.h" */
  95875. #ifndef SQLITE_OMIT_ATTACH
  95876. /*
  95877. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  95878. ** is slightly different from resolving a normal SQL expression, because simple
  95879. ** identifiers are treated as strings, not possible column names or aliases.
  95880. **
  95881. ** i.e. if the parser sees:
  95882. **
  95883. ** ATTACH DATABASE abc AS def
  95884. **
  95885. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  95886. ** looking for columns of the same name.
  95887. **
  95888. ** This only applies to the root node of pExpr, so the statement:
  95889. **
  95890. ** ATTACH DATABASE abc||def AS 'db2'
  95891. **
  95892. ** will fail because neither abc or def can be resolved.
  95893. */
  95894. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  95895. {
  95896. int rc = SQLITE_OK;
  95897. if( pExpr ){
  95898. if( pExpr->op!=TK_ID ){
  95899. rc = sqlite3ResolveExprNames(pName, pExpr);
  95900. }else{
  95901. pExpr->op = TK_STRING;
  95902. }
  95903. }
  95904. return rc;
  95905. }
  95906. /*
  95907. ** An SQL user-function registered to do the work of an ATTACH statement. The
  95908. ** three arguments to the function come directly from an attach statement:
  95909. **
  95910. ** ATTACH DATABASE x AS y KEY z
  95911. **
  95912. ** SELECT sqlite_attach(x, y, z)
  95913. **
  95914. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  95915. ** third argument.
  95916. **
  95917. ** If the db->init.reopenMemdb flags is set, then instead of attaching a
  95918. ** new database, close the database on db->init.iDb and reopen it as an
  95919. ** empty MemDB.
  95920. */
  95921. static void attachFunc(
  95922. sqlite3_context *context,
  95923. int NotUsed,
  95924. sqlite3_value **argv
  95925. ){
  95926. int i;
  95927. int rc = 0;
  95928. sqlite3 *db = sqlite3_context_db_handle(context);
  95929. const char *zName;
  95930. const char *zFile;
  95931. char *zPath = 0;
  95932. char *zErr = 0;
  95933. unsigned int flags;
  95934. Db *aNew; /* New array of Db pointers */
  95935. Db *pNew; /* Db object for the newly attached database */
  95936. char *zErrDyn = 0;
  95937. sqlite3_vfs *pVfs;
  95938. UNUSED_PARAMETER(NotUsed);
  95939. zFile = (const char *)sqlite3_value_text(argv[0]);
  95940. zName = (const char *)sqlite3_value_text(argv[1]);
  95941. if( zFile==0 ) zFile = "";
  95942. if( zName==0 ) zName = "";
  95943. #ifdef SQLITE_ENABLE_DESERIALIZE
  95944. # define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb)
  95945. #else
  95946. # define REOPEN_AS_MEMDB(db) (0)
  95947. #endif
  95948. if( REOPEN_AS_MEMDB(db) ){
  95949. /* This is not a real ATTACH. Instead, this routine is being called
  95950. ** from sqlite3_deserialize() to close database db->init.iDb and
  95951. ** reopen it as a MemDB */
  95952. pVfs = sqlite3_vfs_find("memdb");
  95953. if( pVfs==0 ) return;
  95954. pNew = &db->aDb[db->init.iDb];
  95955. if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
  95956. pNew->pBt = 0;
  95957. pNew->pSchema = 0;
  95958. rc = sqlite3BtreeOpen(pVfs, "x", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
  95959. }else{
  95960. /* This is a real ATTACH
  95961. **
  95962. ** Check for the following errors:
  95963. **
  95964. ** * Too many attached databases,
  95965. ** * Transaction currently open
  95966. ** * Specified database name already being used.
  95967. */
  95968. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  95969. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  95970. db->aLimit[SQLITE_LIMIT_ATTACHED]
  95971. );
  95972. goto attach_error;
  95973. }
  95974. for(i=0; i<db->nDb; i++){
  95975. char *z = db->aDb[i].zDbSName;
  95976. assert( z && zName );
  95977. if( sqlite3StrICmp(z, zName)==0 ){
  95978. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  95979. goto attach_error;
  95980. }
  95981. }
  95982. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  95983. ** hash tables.
  95984. */
  95985. if( db->aDb==db->aDbStatic ){
  95986. aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
  95987. if( aNew==0 ) return;
  95988. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  95989. }else{
  95990. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  95991. if( aNew==0 ) return;
  95992. }
  95993. db->aDb = aNew;
  95994. pNew = &db->aDb[db->nDb];
  95995. memset(pNew, 0, sizeof(*pNew));
  95996. /* Open the database file. If the btree is successfully opened, use
  95997. ** it to obtain the database schema. At this point the schema may
  95998. ** or may not be initialized.
  95999. */
  96000. flags = db->openFlags;
  96001. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  96002. if( rc!=SQLITE_OK ){
  96003. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  96004. sqlite3_result_error(context, zErr, -1);
  96005. sqlite3_free(zErr);
  96006. return;
  96007. }
  96008. assert( pVfs );
  96009. flags |= SQLITE_OPEN_MAIN_DB;
  96010. rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
  96011. sqlite3_free( zPath );
  96012. db->nDb++;
  96013. }
  96014. db->skipBtreeMutex = 0;
  96015. if( rc==SQLITE_CONSTRAINT ){
  96016. rc = SQLITE_ERROR;
  96017. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  96018. }else if( rc==SQLITE_OK ){
  96019. Pager *pPager;
  96020. pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
  96021. if( !pNew->pSchema ){
  96022. rc = SQLITE_NOMEM_BKPT;
  96023. }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
  96024. zErrDyn = sqlite3MPrintf(db,
  96025. "attached databases must use the same text encoding as main database");
  96026. rc = SQLITE_ERROR;
  96027. }
  96028. sqlite3BtreeEnter(pNew->pBt);
  96029. pPager = sqlite3BtreePager(pNew->pBt);
  96030. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  96031. sqlite3BtreeSecureDelete(pNew->pBt,
  96032. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  96033. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  96034. sqlite3BtreeSetPagerFlags(pNew->pBt,
  96035. PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
  96036. #endif
  96037. sqlite3BtreeLeave(pNew->pBt);
  96038. }
  96039. pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  96040. if( !REOPEN_AS_MEMDB(db) ) pNew->zDbSName = sqlite3DbStrDup(db, zName);
  96041. if( rc==SQLITE_OK && pNew->zDbSName==0 ){
  96042. rc = SQLITE_NOMEM_BKPT;
  96043. }
  96044. #ifdef SQLITE_HAS_CODEC
  96045. if( rc==SQLITE_OK ){
  96046. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  96047. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  96048. int nKey;
  96049. char *zKey;
  96050. int t = sqlite3_value_type(argv[2]);
  96051. switch( t ){
  96052. case SQLITE_INTEGER:
  96053. case SQLITE_FLOAT:
  96054. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  96055. rc = SQLITE_ERROR;
  96056. break;
  96057. case SQLITE_TEXT:
  96058. case SQLITE_BLOB:
  96059. nKey = sqlite3_value_bytes(argv[2]);
  96060. zKey = (char *)sqlite3_value_blob(argv[2]);
  96061. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  96062. break;
  96063. case SQLITE_NULL:
  96064. /* No key specified. Use the key from the main database */
  96065. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  96066. if( nKey || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  96067. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  96068. }
  96069. break;
  96070. }
  96071. }
  96072. #endif
  96073. /* If the file was opened successfully, read the schema for the new database.
  96074. ** If this fails, or if opening the file failed, then close the file and
  96075. ** remove the entry from the db->aDb[] array. i.e. put everything back the
  96076. ** way we found it.
  96077. */
  96078. if( rc==SQLITE_OK ){
  96079. sqlite3BtreeEnterAll(db);
  96080. db->init.iDb = 0;
  96081. rc = sqlite3Init(db, &zErrDyn);
  96082. sqlite3BtreeLeaveAll(db);
  96083. assert( zErrDyn==0 || rc!=SQLITE_OK );
  96084. }
  96085. #ifdef SQLITE_USER_AUTHENTICATION
  96086. if( rc==SQLITE_OK ){
  96087. u8 newAuth = 0;
  96088. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  96089. if( newAuth<db->auth.authLevel ){
  96090. rc = SQLITE_AUTH_USER;
  96091. }
  96092. }
  96093. #endif
  96094. if( rc ){
  96095. if( !REOPEN_AS_MEMDB(db) ){
  96096. int iDb = db->nDb - 1;
  96097. assert( iDb>=2 );
  96098. if( db->aDb[iDb].pBt ){
  96099. sqlite3BtreeClose(db->aDb[iDb].pBt);
  96100. db->aDb[iDb].pBt = 0;
  96101. db->aDb[iDb].pSchema = 0;
  96102. }
  96103. sqlite3ResetAllSchemasOfConnection(db);
  96104. db->nDb = iDb;
  96105. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  96106. sqlite3OomFault(db);
  96107. sqlite3DbFree(db, zErrDyn);
  96108. zErrDyn = sqlite3MPrintf(db, "out of memory");
  96109. }else if( zErrDyn==0 ){
  96110. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  96111. }
  96112. }
  96113. goto attach_error;
  96114. }
  96115. return;
  96116. attach_error:
  96117. /* Return an error if we get here */
  96118. if( zErrDyn ){
  96119. sqlite3_result_error(context, zErrDyn, -1);
  96120. sqlite3DbFree(db, zErrDyn);
  96121. }
  96122. if( rc ) sqlite3_result_error_code(context, rc);
  96123. }
  96124. /*
  96125. ** An SQL user-function registered to do the work of an DETACH statement. The
  96126. ** three arguments to the function come directly from a detach statement:
  96127. **
  96128. ** DETACH DATABASE x
  96129. **
  96130. ** SELECT sqlite_detach(x)
  96131. */
  96132. static void detachFunc(
  96133. sqlite3_context *context,
  96134. int NotUsed,
  96135. sqlite3_value **argv
  96136. ){
  96137. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  96138. sqlite3 *db = sqlite3_context_db_handle(context);
  96139. int i;
  96140. Db *pDb = 0;
  96141. char zErr[128];
  96142. UNUSED_PARAMETER(NotUsed);
  96143. if( zName==0 ) zName = "";
  96144. for(i=0; i<db->nDb; i++){
  96145. pDb = &db->aDb[i];
  96146. if( pDb->pBt==0 ) continue;
  96147. if( sqlite3StrICmp(pDb->zDbSName, zName)==0 ) break;
  96148. }
  96149. if( i>=db->nDb ){
  96150. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  96151. goto detach_error;
  96152. }
  96153. if( i<2 ){
  96154. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  96155. goto detach_error;
  96156. }
  96157. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  96158. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  96159. goto detach_error;
  96160. }
  96161. sqlite3BtreeClose(pDb->pBt);
  96162. pDb->pBt = 0;
  96163. pDb->pSchema = 0;
  96164. sqlite3CollapseDatabaseArray(db);
  96165. return;
  96166. detach_error:
  96167. sqlite3_result_error(context, zErr, -1);
  96168. }
  96169. /*
  96170. ** This procedure generates VDBE code for a single invocation of either the
  96171. ** sqlite_detach() or sqlite_attach() SQL user functions.
  96172. */
  96173. static void codeAttach(
  96174. Parse *pParse, /* The parser context */
  96175. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  96176. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  96177. Expr *pAuthArg, /* Expression to pass to authorization callback */
  96178. Expr *pFilename, /* Name of database file */
  96179. Expr *pDbname, /* Name of the database to use internally */
  96180. Expr *pKey /* Database key for encryption extension */
  96181. ){
  96182. int rc;
  96183. NameContext sName;
  96184. Vdbe *v;
  96185. sqlite3* db = pParse->db;
  96186. int regArgs;
  96187. if( pParse->nErr ) goto attach_end;
  96188. memset(&sName, 0, sizeof(NameContext));
  96189. sName.pParse = pParse;
  96190. if(
  96191. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  96192. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  96193. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  96194. ){
  96195. goto attach_end;
  96196. }
  96197. #ifndef SQLITE_OMIT_AUTHORIZATION
  96198. if( pAuthArg ){
  96199. char *zAuthArg;
  96200. if( pAuthArg->op==TK_STRING ){
  96201. zAuthArg = pAuthArg->u.zToken;
  96202. }else{
  96203. zAuthArg = 0;
  96204. }
  96205. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  96206. if(rc!=SQLITE_OK ){
  96207. goto attach_end;
  96208. }
  96209. }
  96210. #endif /* SQLITE_OMIT_AUTHORIZATION */
  96211. v = sqlite3GetVdbe(pParse);
  96212. regArgs = sqlite3GetTempRange(pParse, 4);
  96213. sqlite3ExprCode(pParse, pFilename, regArgs);
  96214. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  96215. sqlite3ExprCode(pParse, pKey, regArgs+2);
  96216. assert( v || db->mallocFailed );
  96217. if( v ){
  96218. sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
  96219. (char *)pFunc, P4_FUNCDEF);
  96220. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  96221. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  96222. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  96223. ** statement only). For DETACH, set it to false (expire all existing
  96224. ** statements).
  96225. */
  96226. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  96227. }
  96228. attach_end:
  96229. sqlite3ExprDelete(db, pFilename);
  96230. sqlite3ExprDelete(db, pDbname);
  96231. sqlite3ExprDelete(db, pKey);
  96232. }
  96233. /*
  96234. ** Called by the parser to compile a DETACH statement.
  96235. **
  96236. ** DETACH pDbname
  96237. */
  96238. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  96239. static const FuncDef detach_func = {
  96240. 1, /* nArg */
  96241. SQLITE_UTF8, /* funcFlags */
  96242. 0, /* pUserData */
  96243. 0, /* pNext */
  96244. detachFunc, /* xSFunc */
  96245. 0, /* xFinalize */
  96246. "sqlite_detach", /* zName */
  96247. {0}
  96248. };
  96249. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  96250. }
  96251. /*
  96252. ** Called by the parser to compile an ATTACH statement.
  96253. **
  96254. ** ATTACH p AS pDbname KEY pKey
  96255. */
  96256. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  96257. static const FuncDef attach_func = {
  96258. 3, /* nArg */
  96259. SQLITE_UTF8, /* funcFlags */
  96260. 0, /* pUserData */
  96261. 0, /* pNext */
  96262. attachFunc, /* xSFunc */
  96263. 0, /* xFinalize */
  96264. "sqlite_attach", /* zName */
  96265. {0}
  96266. };
  96267. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  96268. }
  96269. #endif /* SQLITE_OMIT_ATTACH */
  96270. /*
  96271. ** Initialize a DbFixer structure. This routine must be called prior
  96272. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  96273. */
  96274. SQLITE_PRIVATE void sqlite3FixInit(
  96275. DbFixer *pFix, /* The fixer to be initialized */
  96276. Parse *pParse, /* Error messages will be written here */
  96277. int iDb, /* This is the database that must be used */
  96278. const char *zType, /* "view", "trigger", or "index" */
  96279. const Token *pName /* Name of the view, trigger, or index */
  96280. ){
  96281. sqlite3 *db;
  96282. db = pParse->db;
  96283. assert( db->nDb>iDb );
  96284. pFix->pParse = pParse;
  96285. pFix->zDb = db->aDb[iDb].zDbSName;
  96286. pFix->pSchema = db->aDb[iDb].pSchema;
  96287. pFix->zType = zType;
  96288. pFix->pName = pName;
  96289. pFix->bVarOnly = (iDb==1);
  96290. }
  96291. /*
  96292. ** The following set of routines walk through the parse tree and assign
  96293. ** a specific database to all table references where the database name
  96294. ** was left unspecified in the original SQL statement. The pFix structure
  96295. ** must have been initialized by a prior call to sqlite3FixInit().
  96296. **
  96297. ** These routines are used to make sure that an index, trigger, or
  96298. ** view in one database does not refer to objects in a different database.
  96299. ** (Exception: indices, triggers, and views in the TEMP database are
  96300. ** allowed to refer to anything.) If a reference is explicitly made
  96301. ** to an object in a different database, an error message is added to
  96302. ** pParse->zErrMsg and these routines return non-zero. If everything
  96303. ** checks out, these routines return 0.
  96304. */
  96305. SQLITE_PRIVATE int sqlite3FixSrcList(
  96306. DbFixer *pFix, /* Context of the fixation */
  96307. SrcList *pList /* The Source list to check and modify */
  96308. ){
  96309. int i;
  96310. const char *zDb;
  96311. struct SrcList_item *pItem;
  96312. if( NEVER(pList==0) ) return 0;
  96313. zDb = pFix->zDb;
  96314. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  96315. if( pFix->bVarOnly==0 ){
  96316. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  96317. sqlite3ErrorMsg(pFix->pParse,
  96318. "%s %T cannot reference objects in database %s",
  96319. pFix->zType, pFix->pName, pItem->zDatabase);
  96320. return 1;
  96321. }
  96322. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  96323. pItem->zDatabase = 0;
  96324. pItem->pSchema = pFix->pSchema;
  96325. }
  96326. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  96327. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  96328. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  96329. #endif
  96330. }
  96331. return 0;
  96332. }
  96333. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  96334. SQLITE_PRIVATE int sqlite3FixSelect(
  96335. DbFixer *pFix, /* Context of the fixation */
  96336. Select *pSelect /* The SELECT statement to be fixed to one database */
  96337. ){
  96338. while( pSelect ){
  96339. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  96340. return 1;
  96341. }
  96342. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  96343. return 1;
  96344. }
  96345. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  96346. return 1;
  96347. }
  96348. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  96349. return 1;
  96350. }
  96351. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  96352. return 1;
  96353. }
  96354. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  96355. return 1;
  96356. }
  96357. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  96358. return 1;
  96359. }
  96360. if( pSelect->pWith ){
  96361. int i;
  96362. for(i=0; i<pSelect->pWith->nCte; i++){
  96363. if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
  96364. return 1;
  96365. }
  96366. }
  96367. }
  96368. pSelect = pSelect->pPrior;
  96369. }
  96370. return 0;
  96371. }
  96372. SQLITE_PRIVATE int sqlite3FixExpr(
  96373. DbFixer *pFix, /* Context of the fixation */
  96374. Expr *pExpr /* The expression to be fixed to one database */
  96375. ){
  96376. while( pExpr ){
  96377. if( pExpr->op==TK_VARIABLE ){
  96378. if( pFix->pParse->db->init.busy ){
  96379. pExpr->op = TK_NULL;
  96380. }else{
  96381. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  96382. return 1;
  96383. }
  96384. }
  96385. if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
  96386. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  96387. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  96388. }else{
  96389. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  96390. }
  96391. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  96392. return 1;
  96393. }
  96394. pExpr = pExpr->pLeft;
  96395. }
  96396. return 0;
  96397. }
  96398. SQLITE_PRIVATE int sqlite3FixExprList(
  96399. DbFixer *pFix, /* Context of the fixation */
  96400. ExprList *pList /* The expression to be fixed to one database */
  96401. ){
  96402. int i;
  96403. struct ExprList_item *pItem;
  96404. if( pList==0 ) return 0;
  96405. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  96406. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  96407. return 1;
  96408. }
  96409. }
  96410. return 0;
  96411. }
  96412. #endif
  96413. #ifndef SQLITE_OMIT_TRIGGER
  96414. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  96415. DbFixer *pFix, /* Context of the fixation */
  96416. TriggerStep *pStep /* The trigger step be fixed to one database */
  96417. ){
  96418. while( pStep ){
  96419. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  96420. return 1;
  96421. }
  96422. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  96423. return 1;
  96424. }
  96425. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  96426. return 1;
  96427. }
  96428. pStep = pStep->pNext;
  96429. }
  96430. return 0;
  96431. }
  96432. #endif
  96433. /************** End of attach.c **********************************************/
  96434. /************** Begin file auth.c ********************************************/
  96435. /*
  96436. ** 2003 January 11
  96437. **
  96438. ** The author disclaims copyright to this source code. In place of
  96439. ** a legal notice, here is a blessing:
  96440. **
  96441. ** May you do good and not evil.
  96442. ** May you find forgiveness for yourself and forgive others.
  96443. ** May you share freely, never taking more than you give.
  96444. **
  96445. *************************************************************************
  96446. ** This file contains code used to implement the sqlite3_set_authorizer()
  96447. ** API. This facility is an optional feature of the library. Embedded
  96448. ** systems that do not need this facility may omit it by recompiling
  96449. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  96450. */
  96451. /* #include "sqliteInt.h" */
  96452. /*
  96453. ** All of the code in this file may be omitted by defining a single
  96454. ** macro.
  96455. */
  96456. #ifndef SQLITE_OMIT_AUTHORIZATION
  96457. /*
  96458. ** Set or clear the access authorization function.
  96459. **
  96460. ** The access authorization function is be called during the compilation
  96461. ** phase to verify that the user has read and/or write access permission on
  96462. ** various fields of the database. The first argument to the auth function
  96463. ** is a copy of the 3rd argument to this routine. The second argument
  96464. ** to the auth function is one of these constants:
  96465. **
  96466. ** SQLITE_CREATE_INDEX
  96467. ** SQLITE_CREATE_TABLE
  96468. ** SQLITE_CREATE_TEMP_INDEX
  96469. ** SQLITE_CREATE_TEMP_TABLE
  96470. ** SQLITE_CREATE_TEMP_TRIGGER
  96471. ** SQLITE_CREATE_TEMP_VIEW
  96472. ** SQLITE_CREATE_TRIGGER
  96473. ** SQLITE_CREATE_VIEW
  96474. ** SQLITE_DELETE
  96475. ** SQLITE_DROP_INDEX
  96476. ** SQLITE_DROP_TABLE
  96477. ** SQLITE_DROP_TEMP_INDEX
  96478. ** SQLITE_DROP_TEMP_TABLE
  96479. ** SQLITE_DROP_TEMP_TRIGGER
  96480. ** SQLITE_DROP_TEMP_VIEW
  96481. ** SQLITE_DROP_TRIGGER
  96482. ** SQLITE_DROP_VIEW
  96483. ** SQLITE_INSERT
  96484. ** SQLITE_PRAGMA
  96485. ** SQLITE_READ
  96486. ** SQLITE_SELECT
  96487. ** SQLITE_TRANSACTION
  96488. ** SQLITE_UPDATE
  96489. **
  96490. ** The third and fourth arguments to the auth function are the name of
  96491. ** the table and the column that are being accessed. The auth function
  96492. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  96493. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  96494. ** means that the SQL statement will never-run - the sqlite3_exec() call
  96495. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  96496. ** should run but attempts to read the specified column will return NULL
  96497. ** and attempts to write the column will be ignored.
  96498. **
  96499. ** Setting the auth function to NULL disables this hook. The default
  96500. ** setting of the auth function is NULL.
  96501. */
  96502. SQLITE_API int sqlite3_set_authorizer(
  96503. sqlite3 *db,
  96504. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  96505. void *pArg
  96506. ){
  96507. #ifdef SQLITE_ENABLE_API_ARMOR
  96508. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  96509. #endif
  96510. sqlite3_mutex_enter(db->mutex);
  96511. db->xAuth = (sqlite3_xauth)xAuth;
  96512. db->pAuthArg = pArg;
  96513. sqlite3ExpirePreparedStatements(db);
  96514. sqlite3_mutex_leave(db->mutex);
  96515. return SQLITE_OK;
  96516. }
  96517. /*
  96518. ** Write an error message into pParse->zErrMsg that explains that the
  96519. ** user-supplied authorization function returned an illegal value.
  96520. */
  96521. static void sqliteAuthBadReturnCode(Parse *pParse){
  96522. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  96523. pParse->rc = SQLITE_ERROR;
  96524. }
  96525. /*
  96526. ** Invoke the authorization callback for permission to read column zCol from
  96527. ** table zTab in database zDb. This function assumes that an authorization
  96528. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  96529. **
  96530. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  96531. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  96532. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  96533. */
  96534. SQLITE_PRIVATE int sqlite3AuthReadCol(
  96535. Parse *pParse, /* The parser context */
  96536. const char *zTab, /* Table name */
  96537. const char *zCol, /* Column name */
  96538. int iDb /* Index of containing database. */
  96539. ){
  96540. sqlite3 *db = pParse->db; /* Database handle */
  96541. char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
  96542. int rc; /* Auth callback return code */
  96543. if( db->init.busy ) return SQLITE_OK;
  96544. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  96545. #ifdef SQLITE_USER_AUTHENTICATION
  96546. ,db->auth.zAuthUser
  96547. #endif
  96548. );
  96549. if( rc==SQLITE_DENY ){
  96550. char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
  96551. if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
  96552. sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
  96553. pParse->rc = SQLITE_AUTH;
  96554. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  96555. sqliteAuthBadReturnCode(pParse);
  96556. }
  96557. return rc;
  96558. }
  96559. /*
  96560. ** The pExpr should be a TK_COLUMN expression. The table referred to
  96561. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  96562. ** Check to see if it is OK to read this particular column.
  96563. **
  96564. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  96565. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  96566. ** then generate an error.
  96567. */
  96568. SQLITE_PRIVATE void sqlite3AuthRead(
  96569. Parse *pParse, /* The parser context */
  96570. Expr *pExpr, /* The expression to check authorization on */
  96571. Schema *pSchema, /* The schema of the expression */
  96572. SrcList *pTabList /* All table that pExpr might refer to */
  96573. ){
  96574. sqlite3 *db = pParse->db;
  96575. Table *pTab = 0; /* The table being read */
  96576. const char *zCol; /* Name of the column of the table */
  96577. int iSrc; /* Index in pTabList->a[] of table being read */
  96578. int iDb; /* The index of the database the expression refers to */
  96579. int iCol; /* Index of column in table */
  96580. if( db->xAuth==0 ) return;
  96581. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  96582. if( iDb<0 ){
  96583. /* An attempt to read a column out of a subquery or other
  96584. ** temporary table. */
  96585. return;
  96586. }
  96587. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  96588. if( pExpr->op==TK_TRIGGER ){
  96589. pTab = pParse->pTriggerTab;
  96590. }else{
  96591. assert( pTabList );
  96592. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  96593. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  96594. pTab = pTabList->a[iSrc].pTab;
  96595. break;
  96596. }
  96597. }
  96598. }
  96599. iCol = pExpr->iColumn;
  96600. if( NEVER(pTab==0) ) return;
  96601. if( iCol>=0 ){
  96602. assert( iCol<pTab->nCol );
  96603. zCol = pTab->aCol[iCol].zName;
  96604. }else if( pTab->iPKey>=0 ){
  96605. assert( pTab->iPKey<pTab->nCol );
  96606. zCol = pTab->aCol[pTab->iPKey].zName;
  96607. }else{
  96608. zCol = "ROWID";
  96609. }
  96610. assert( iDb>=0 && iDb<db->nDb );
  96611. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  96612. pExpr->op = TK_NULL;
  96613. }
  96614. }
  96615. /*
  96616. ** Do an authorization check using the code and arguments given. Return
  96617. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  96618. ** is returned, then the error count and error message in pParse are
  96619. ** modified appropriately.
  96620. */
  96621. SQLITE_PRIVATE int sqlite3AuthCheck(
  96622. Parse *pParse,
  96623. int code,
  96624. const char *zArg1,
  96625. const char *zArg2,
  96626. const char *zArg3
  96627. ){
  96628. sqlite3 *db = pParse->db;
  96629. int rc;
  96630. /* Don't do any authorization checks if the database is initialising
  96631. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  96632. */
  96633. if( db->init.busy || IN_DECLARE_VTAB ){
  96634. return SQLITE_OK;
  96635. }
  96636. if( db->xAuth==0 ){
  96637. return SQLITE_OK;
  96638. }
  96639. /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
  96640. ** callback are either NULL pointers or zero-terminated strings that
  96641. ** contain additional details about the action to be authorized.
  96642. **
  96643. ** The following testcase() macros show that any of the 3rd through 6th
  96644. ** parameters can be either NULL or a string. */
  96645. testcase( zArg1==0 );
  96646. testcase( zArg2==0 );
  96647. testcase( zArg3==0 );
  96648. testcase( pParse->zAuthContext==0 );
  96649. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  96650. #ifdef SQLITE_USER_AUTHENTICATION
  96651. ,db->auth.zAuthUser
  96652. #endif
  96653. );
  96654. if( rc==SQLITE_DENY ){
  96655. sqlite3ErrorMsg(pParse, "not authorized");
  96656. pParse->rc = SQLITE_AUTH;
  96657. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  96658. rc = SQLITE_DENY;
  96659. sqliteAuthBadReturnCode(pParse);
  96660. }
  96661. return rc;
  96662. }
  96663. /*
  96664. ** Push an authorization context. After this routine is called, the
  96665. ** zArg3 argument to authorization callbacks will be zContext until
  96666. ** popped. Or if pParse==0, this routine is a no-op.
  96667. */
  96668. SQLITE_PRIVATE void sqlite3AuthContextPush(
  96669. Parse *pParse,
  96670. AuthContext *pContext,
  96671. const char *zContext
  96672. ){
  96673. assert( pParse );
  96674. pContext->pParse = pParse;
  96675. pContext->zAuthContext = pParse->zAuthContext;
  96676. pParse->zAuthContext = zContext;
  96677. }
  96678. /*
  96679. ** Pop an authorization context that was previously pushed
  96680. ** by sqlite3AuthContextPush
  96681. */
  96682. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  96683. if( pContext->pParse ){
  96684. pContext->pParse->zAuthContext = pContext->zAuthContext;
  96685. pContext->pParse = 0;
  96686. }
  96687. }
  96688. #endif /* SQLITE_OMIT_AUTHORIZATION */
  96689. /************** End of auth.c ************************************************/
  96690. /************** Begin file build.c *******************************************/
  96691. /*
  96692. ** 2001 September 15
  96693. **
  96694. ** The author disclaims copyright to this source code. In place of
  96695. ** a legal notice, here is a blessing:
  96696. **
  96697. ** May you do good and not evil.
  96698. ** May you find forgiveness for yourself and forgive others.
  96699. ** May you share freely, never taking more than you give.
  96700. **
  96701. *************************************************************************
  96702. ** This file contains C code routines that are called by the SQLite parser
  96703. ** when syntax rules are reduced. The routines in this file handle the
  96704. ** following kinds of SQL syntax:
  96705. **
  96706. ** CREATE TABLE
  96707. ** DROP TABLE
  96708. ** CREATE INDEX
  96709. ** DROP INDEX
  96710. ** creating ID lists
  96711. ** BEGIN TRANSACTION
  96712. ** COMMIT
  96713. ** ROLLBACK
  96714. */
  96715. /* #include "sqliteInt.h" */
  96716. #ifndef SQLITE_OMIT_SHARED_CACHE
  96717. /*
  96718. ** The TableLock structure is only used by the sqlite3TableLock() and
  96719. ** codeTableLocks() functions.
  96720. */
  96721. struct TableLock {
  96722. int iDb; /* The database containing the table to be locked */
  96723. int iTab; /* The root page of the table to be locked */
  96724. u8 isWriteLock; /* True for write lock. False for a read lock */
  96725. const char *zLockName; /* Name of the table */
  96726. };
  96727. /*
  96728. ** Record the fact that we want to lock a table at run-time.
  96729. **
  96730. ** The table to be locked has root page iTab and is found in database iDb.
  96731. ** A read or a write lock can be taken depending on isWritelock.
  96732. **
  96733. ** This routine just records the fact that the lock is desired. The
  96734. ** code to make the lock occur is generated by a later call to
  96735. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  96736. */
  96737. SQLITE_PRIVATE void sqlite3TableLock(
  96738. Parse *pParse, /* Parsing context */
  96739. int iDb, /* Index of the database containing the table to lock */
  96740. int iTab, /* Root page number of the table to be locked */
  96741. u8 isWriteLock, /* True for a write lock */
  96742. const char *zName /* Name of the table to be locked */
  96743. ){
  96744. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  96745. int i;
  96746. int nBytes;
  96747. TableLock *p;
  96748. assert( iDb>=0 );
  96749. if( iDb==1 ) return;
  96750. if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
  96751. for(i=0; i<pToplevel->nTableLock; i++){
  96752. p = &pToplevel->aTableLock[i];
  96753. if( p->iDb==iDb && p->iTab==iTab ){
  96754. p->isWriteLock = (p->isWriteLock || isWriteLock);
  96755. return;
  96756. }
  96757. }
  96758. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  96759. pToplevel->aTableLock =
  96760. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  96761. if( pToplevel->aTableLock ){
  96762. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  96763. p->iDb = iDb;
  96764. p->iTab = iTab;
  96765. p->isWriteLock = isWriteLock;
  96766. p->zLockName = zName;
  96767. }else{
  96768. pToplevel->nTableLock = 0;
  96769. sqlite3OomFault(pToplevel->db);
  96770. }
  96771. }
  96772. /*
  96773. ** Code an OP_TableLock instruction for each table locked by the
  96774. ** statement (configured by calls to sqlite3TableLock()).
  96775. */
  96776. static void codeTableLocks(Parse *pParse){
  96777. int i;
  96778. Vdbe *pVdbe;
  96779. pVdbe = sqlite3GetVdbe(pParse);
  96780. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  96781. for(i=0; i<pParse->nTableLock; i++){
  96782. TableLock *p = &pParse->aTableLock[i];
  96783. int p1 = p->iDb;
  96784. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  96785. p->zLockName, P4_STATIC);
  96786. }
  96787. }
  96788. #else
  96789. #define codeTableLocks(x)
  96790. #endif
  96791. /*
  96792. ** Return TRUE if the given yDbMask object is empty - if it contains no
  96793. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  96794. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  96795. */
  96796. #if SQLITE_MAX_ATTACHED>30
  96797. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  96798. int i;
  96799. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  96800. return 1;
  96801. }
  96802. #endif
  96803. /*
  96804. ** This routine is called after a single SQL statement has been
  96805. ** parsed and a VDBE program to execute that statement has been
  96806. ** prepared. This routine puts the finishing touches on the
  96807. ** VDBE program and resets the pParse structure for the next
  96808. ** parse.
  96809. **
  96810. ** Note that if an error occurred, it might be the case that
  96811. ** no VDBE code was generated.
  96812. */
  96813. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  96814. sqlite3 *db;
  96815. Vdbe *v;
  96816. assert( pParse->pToplevel==0 );
  96817. db = pParse->db;
  96818. if( pParse->nested ) return;
  96819. if( db->mallocFailed || pParse->nErr ){
  96820. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  96821. return;
  96822. }
  96823. /* Begin by generating some termination code at the end of the
  96824. ** vdbe program
  96825. */
  96826. v = sqlite3GetVdbe(pParse);
  96827. assert( !pParse->isMultiWrite
  96828. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  96829. if( v ){
  96830. sqlite3VdbeAddOp0(v, OP_Halt);
  96831. #if SQLITE_USER_AUTHENTICATION
  96832. if( pParse->nTableLock>0 && db->init.busy==0 ){
  96833. sqlite3UserAuthInit(db);
  96834. if( db->auth.authLevel<UAUTH_User ){
  96835. sqlite3ErrorMsg(pParse, "user not authenticated");
  96836. pParse->rc = SQLITE_AUTH_USER;
  96837. return;
  96838. }
  96839. }
  96840. #endif
  96841. /* The cookie mask contains one bit for each database file open.
  96842. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  96843. ** set for each database that is used. Generate code to start a
  96844. ** transaction on each used database and to verify the schema cookie
  96845. ** on each used database.
  96846. */
  96847. if( db->mallocFailed==0
  96848. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  96849. ){
  96850. int iDb, i;
  96851. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  96852. sqlite3VdbeJumpHere(v, 0);
  96853. for(iDb=0; iDb<db->nDb; iDb++){
  96854. Schema *pSchema;
  96855. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  96856. sqlite3VdbeUsesBtree(v, iDb);
  96857. pSchema = db->aDb[iDb].pSchema;
  96858. sqlite3VdbeAddOp4Int(v,
  96859. OP_Transaction, /* Opcode */
  96860. iDb, /* P1 */
  96861. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  96862. pSchema->schema_cookie, /* P3 */
  96863. pSchema->iGeneration /* P4 */
  96864. );
  96865. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  96866. VdbeComment((v,
  96867. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  96868. }
  96869. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96870. for(i=0; i<pParse->nVtabLock; i++){
  96871. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  96872. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  96873. }
  96874. pParse->nVtabLock = 0;
  96875. #endif
  96876. /* Once all the cookies have been verified and transactions opened,
  96877. ** obtain the required table-locks. This is a no-op unless the
  96878. ** shared-cache feature is enabled.
  96879. */
  96880. codeTableLocks(pParse);
  96881. /* Initialize any AUTOINCREMENT data structures required.
  96882. */
  96883. sqlite3AutoincrementBegin(pParse);
  96884. /* Code constant expressions that where factored out of inner loops */
  96885. if( pParse->pConstExpr ){
  96886. ExprList *pEL = pParse->pConstExpr;
  96887. pParse->okConstFactor = 0;
  96888. for(i=0; i<pEL->nExpr; i++){
  96889. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  96890. }
  96891. }
  96892. /* Finally, jump back to the beginning of the executable code. */
  96893. sqlite3VdbeGoto(v, 1);
  96894. }
  96895. }
  96896. /* Get the VDBE program ready for execution
  96897. */
  96898. if( v && pParse->nErr==0 && !db->mallocFailed ){
  96899. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  96900. /* A minimum of one cursor is required if autoincrement is used
  96901. * See ticket [a696379c1f08866] */
  96902. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  96903. sqlite3VdbeMakeReady(v, pParse);
  96904. pParse->rc = SQLITE_DONE;
  96905. }else{
  96906. pParse->rc = SQLITE_ERROR;
  96907. }
  96908. }
  96909. /*
  96910. ** Run the parser and code generator recursively in order to generate
  96911. ** code for the SQL statement given onto the end of the pParse context
  96912. ** currently under construction. When the parser is run recursively
  96913. ** this way, the final OP_Halt is not appended and other initialization
  96914. ** and finalization steps are omitted because those are handling by the
  96915. ** outermost parser.
  96916. **
  96917. ** Not everything is nestable. This facility is designed to permit
  96918. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  96919. ** care if you decide to try to use this routine for some other purposes.
  96920. */
  96921. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  96922. va_list ap;
  96923. char *zSql;
  96924. char *zErrMsg = 0;
  96925. sqlite3 *db = pParse->db;
  96926. char saveBuf[PARSE_TAIL_SZ];
  96927. if( pParse->nErr ) return;
  96928. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  96929. va_start(ap, zFormat);
  96930. zSql = sqlite3VMPrintf(db, zFormat, ap);
  96931. va_end(ap);
  96932. if( zSql==0 ){
  96933. return; /* A malloc must have failed */
  96934. }
  96935. pParse->nested++;
  96936. memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
  96937. memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
  96938. sqlite3RunParser(pParse, zSql, &zErrMsg);
  96939. sqlite3DbFree(db, zErrMsg);
  96940. sqlite3DbFree(db, zSql);
  96941. memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
  96942. pParse->nested--;
  96943. }
  96944. #if SQLITE_USER_AUTHENTICATION
  96945. /*
  96946. ** Return TRUE if zTable is the name of the system table that stores the
  96947. ** list of users and their access credentials.
  96948. */
  96949. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  96950. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  96951. }
  96952. #endif
  96953. /*
  96954. ** Locate the in-memory structure that describes a particular database
  96955. ** table given the name of that table and (optionally) the name of the
  96956. ** database containing the table. Return NULL if not found.
  96957. **
  96958. ** If zDatabase is 0, all databases are searched for the table and the
  96959. ** first matching table is returned. (No checking for duplicate table
  96960. ** names is done.) The search order is TEMP first, then MAIN, then any
  96961. ** auxiliary databases added using the ATTACH command.
  96962. **
  96963. ** See also sqlite3LocateTable().
  96964. */
  96965. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  96966. Table *p = 0;
  96967. int i;
  96968. /* All mutexes are required for schema access. Make sure we hold them. */
  96969. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  96970. #if SQLITE_USER_AUTHENTICATION
  96971. /* Only the admin user is allowed to know that the sqlite_user table
  96972. ** exists */
  96973. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  96974. return 0;
  96975. }
  96976. #endif
  96977. while(1){
  96978. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  96979. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  96980. if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
  96981. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  96982. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  96983. if( p ) return p;
  96984. }
  96985. }
  96986. /* Not found. If the name we were looking for was temp.sqlite_master
  96987. ** then change the name to sqlite_temp_master and try again. */
  96988. if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
  96989. if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
  96990. zName = TEMP_MASTER_NAME;
  96991. }
  96992. return 0;
  96993. }
  96994. /*
  96995. ** Locate the in-memory structure that describes a particular database
  96996. ** table given the name of that table and (optionally) the name of the
  96997. ** database containing the table. Return NULL if not found. Also leave an
  96998. ** error message in pParse->zErrMsg.
  96999. **
  97000. ** The difference between this routine and sqlite3FindTable() is that this
  97001. ** routine leaves an error message in pParse->zErrMsg where
  97002. ** sqlite3FindTable() does not.
  97003. */
  97004. SQLITE_PRIVATE Table *sqlite3LocateTable(
  97005. Parse *pParse, /* context in which to report errors */
  97006. u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
  97007. const char *zName, /* Name of the table we are looking for */
  97008. const char *zDbase /* Name of the database. Might be NULL */
  97009. ){
  97010. Table *p;
  97011. /* Read the database schema. If an error occurs, leave an error message
  97012. ** and code in pParse and return NULL. */
  97013. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  97014. return 0;
  97015. }
  97016. p = sqlite3FindTable(pParse->db, zName, zDbase);
  97017. if( p==0 ){
  97018. const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
  97019. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97020. if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
  97021. /* If zName is the not the name of a table in the schema created using
  97022. ** CREATE, then check to see if it is the name of an virtual table that
  97023. ** can be an eponymous virtual table. */
  97024. Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
  97025. if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
  97026. pMod = sqlite3PragmaVtabRegister(pParse->db, zName);
  97027. }
  97028. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  97029. return pMod->pEpoTab;
  97030. }
  97031. }
  97032. #endif
  97033. if( (flags & LOCATE_NOERR)==0 ){
  97034. if( zDbase ){
  97035. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  97036. }else{
  97037. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  97038. }
  97039. pParse->checkSchema = 1;
  97040. }
  97041. }
  97042. return p;
  97043. }
  97044. /*
  97045. ** Locate the table identified by *p.
  97046. **
  97047. ** This is a wrapper around sqlite3LocateTable(). The difference between
  97048. ** sqlite3LocateTable() and this function is that this function restricts
  97049. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  97050. ** non-NULL if it is part of a view or trigger program definition. See
  97051. ** sqlite3FixSrcList() for details.
  97052. */
  97053. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  97054. Parse *pParse,
  97055. u32 flags,
  97056. struct SrcList_item *p
  97057. ){
  97058. const char *zDb;
  97059. assert( p->pSchema==0 || p->zDatabase==0 );
  97060. if( p->pSchema ){
  97061. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  97062. zDb = pParse->db->aDb[iDb].zDbSName;
  97063. }else{
  97064. zDb = p->zDatabase;
  97065. }
  97066. return sqlite3LocateTable(pParse, flags, p->zName, zDb);
  97067. }
  97068. /*
  97069. ** Locate the in-memory structure that describes
  97070. ** a particular index given the name of that index
  97071. ** and the name of the database that contains the index.
  97072. ** Return NULL if not found.
  97073. **
  97074. ** If zDatabase is 0, all databases are searched for the
  97075. ** table and the first matching index is returned. (No checking
  97076. ** for duplicate index names is done.) The search order is
  97077. ** TEMP first, then MAIN, then any auxiliary databases added
  97078. ** using the ATTACH command.
  97079. */
  97080. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  97081. Index *p = 0;
  97082. int i;
  97083. /* All mutexes are required for schema access. Make sure we hold them. */
  97084. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  97085. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  97086. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  97087. Schema *pSchema = db->aDb[j].pSchema;
  97088. assert( pSchema );
  97089. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
  97090. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  97091. p = sqlite3HashFind(&pSchema->idxHash, zName);
  97092. if( p ) break;
  97093. }
  97094. return p;
  97095. }
  97096. /*
  97097. ** Reclaim the memory used by an index
  97098. */
  97099. static void freeIndex(sqlite3 *db, Index *p){
  97100. #ifndef SQLITE_OMIT_ANALYZE
  97101. sqlite3DeleteIndexSamples(db, p);
  97102. #endif
  97103. sqlite3ExprDelete(db, p->pPartIdxWhere);
  97104. sqlite3ExprListDelete(db, p->aColExpr);
  97105. sqlite3DbFree(db, p->zColAff);
  97106. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  97107. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  97108. sqlite3_free(p->aiRowEst);
  97109. #endif
  97110. sqlite3DbFree(db, p);
  97111. }
  97112. /*
  97113. ** For the index called zIdxName which is found in the database iDb,
  97114. ** unlike that index from its Table then remove the index from
  97115. ** the index hash table and free all memory structures associated
  97116. ** with the index.
  97117. */
  97118. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  97119. Index *pIndex;
  97120. Hash *pHash;
  97121. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97122. pHash = &db->aDb[iDb].pSchema->idxHash;
  97123. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  97124. if( ALWAYS(pIndex) ){
  97125. if( pIndex->pTable->pIndex==pIndex ){
  97126. pIndex->pTable->pIndex = pIndex->pNext;
  97127. }else{
  97128. Index *p;
  97129. /* Justification of ALWAYS(); The index must be on the list of
  97130. ** indices. */
  97131. p = pIndex->pTable->pIndex;
  97132. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  97133. if( ALWAYS(p && p->pNext==pIndex) ){
  97134. p->pNext = pIndex->pNext;
  97135. }
  97136. }
  97137. freeIndex(db, pIndex);
  97138. }
  97139. db->mDbFlags |= DBFLAG_SchemaChange;
  97140. }
  97141. /*
  97142. ** Look through the list of open database files in db->aDb[] and if
  97143. ** any have been closed, remove them from the list. Reallocate the
  97144. ** db->aDb[] structure to a smaller size, if possible.
  97145. **
  97146. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  97147. ** are never candidates for being collapsed.
  97148. */
  97149. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  97150. int i, j;
  97151. for(i=j=2; i<db->nDb; i++){
  97152. struct Db *pDb = &db->aDb[i];
  97153. if( pDb->pBt==0 ){
  97154. sqlite3DbFree(db, pDb->zDbSName);
  97155. pDb->zDbSName = 0;
  97156. continue;
  97157. }
  97158. if( j<i ){
  97159. db->aDb[j] = db->aDb[i];
  97160. }
  97161. j++;
  97162. }
  97163. db->nDb = j;
  97164. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  97165. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  97166. sqlite3DbFree(db, db->aDb);
  97167. db->aDb = db->aDbStatic;
  97168. }
  97169. }
  97170. /*
  97171. ** Reset the schema for the database at index iDb. Also reset the
  97172. ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
  97173. ** Deferred resets may be run by calling with iDb<0.
  97174. */
  97175. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  97176. int i;
  97177. assert( iDb<db->nDb );
  97178. if( iDb>=0 ){
  97179. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97180. DbSetProperty(db, iDb, DB_ResetWanted);
  97181. DbSetProperty(db, 1, DB_ResetWanted);
  97182. }
  97183. if( db->nSchemaLock==0 ){
  97184. for(i=0; i<db->nDb; i++){
  97185. if( DbHasProperty(db, i, DB_ResetWanted) ){
  97186. sqlite3SchemaClear(db->aDb[i].pSchema);
  97187. }
  97188. }
  97189. }
  97190. }
  97191. /*
  97192. ** Erase all schema information from all attached databases (including
  97193. ** "main" and "temp") for a single database connection.
  97194. */
  97195. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  97196. int i;
  97197. sqlite3BtreeEnterAll(db);
  97198. assert( db->nSchemaLock==0 );
  97199. for(i=0; i<db->nDb; i++){
  97200. Db *pDb = &db->aDb[i];
  97201. if( pDb->pSchema ){
  97202. sqlite3SchemaClear(pDb->pSchema);
  97203. }
  97204. }
  97205. db->mDbFlags &= ~DBFLAG_SchemaChange;
  97206. sqlite3VtabUnlockList(db);
  97207. sqlite3BtreeLeaveAll(db);
  97208. sqlite3CollapseDatabaseArray(db);
  97209. }
  97210. /*
  97211. ** This routine is called when a commit occurs.
  97212. */
  97213. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  97214. db->mDbFlags &= ~DBFLAG_SchemaChange;
  97215. }
  97216. /*
  97217. ** Delete memory allocated for the column names of a table or view (the
  97218. ** Table.aCol[] array).
  97219. */
  97220. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  97221. int i;
  97222. Column *pCol;
  97223. assert( pTable!=0 );
  97224. if( (pCol = pTable->aCol)!=0 ){
  97225. for(i=0; i<pTable->nCol; i++, pCol++){
  97226. sqlite3DbFree(db, pCol->zName);
  97227. sqlite3ExprDelete(db, pCol->pDflt);
  97228. sqlite3DbFree(db, pCol->zColl);
  97229. }
  97230. sqlite3DbFree(db, pTable->aCol);
  97231. }
  97232. }
  97233. /*
  97234. ** Remove the memory data structures associated with the given
  97235. ** Table. No changes are made to disk by this routine.
  97236. **
  97237. ** This routine just deletes the data structure. It does not unlink
  97238. ** the table data structure from the hash table. But it does destroy
  97239. ** memory structures of the indices and foreign keys associated with
  97240. ** the table.
  97241. **
  97242. ** The db parameter is optional. It is needed if the Table object
  97243. ** contains lookaside memory. (Table objects in the schema do not use
  97244. ** lookaside memory, but some ephemeral Table objects do.) Or the
  97245. ** db parameter can be used with db->pnBytesFreed to measure the memory
  97246. ** used by the Table object.
  97247. */
  97248. static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
  97249. Index *pIndex, *pNext;
  97250. #ifdef SQLITE_DEBUG
  97251. /* Record the number of outstanding lookaside allocations in schema Tables
  97252. ** prior to doing any free() operations. Since schema Tables do not use
  97253. ** lookaside, this number should not change. */
  97254. int nLookaside = 0;
  97255. if( db && (pTable->tabFlags & TF_Ephemeral)==0 ){
  97256. nLookaside = sqlite3LookasideUsed(db, 0);
  97257. }
  97258. #endif
  97259. /* Delete all indices associated with this table. */
  97260. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  97261. pNext = pIndex->pNext;
  97262. assert( pIndex->pSchema==pTable->pSchema
  97263. || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
  97264. if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
  97265. char *zName = pIndex->zName;
  97266. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  97267. &pIndex->pSchema->idxHash, zName, 0
  97268. );
  97269. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  97270. assert( pOld==pIndex || pOld==0 );
  97271. }
  97272. freeIndex(db, pIndex);
  97273. }
  97274. /* Delete any foreign keys attached to this table. */
  97275. sqlite3FkDelete(db, pTable);
  97276. /* Delete the Table structure itself.
  97277. */
  97278. sqlite3DeleteColumnNames(db, pTable);
  97279. sqlite3DbFree(db, pTable->zName);
  97280. sqlite3DbFree(db, pTable->zColAff);
  97281. sqlite3SelectDelete(db, pTable->pSelect);
  97282. sqlite3ExprListDelete(db, pTable->pCheck);
  97283. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97284. sqlite3VtabClear(db, pTable);
  97285. #endif
  97286. sqlite3DbFree(db, pTable);
  97287. /* Verify that no lookaside memory was used by schema tables */
  97288. assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
  97289. }
  97290. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  97291. /* Do not delete the table until the reference count reaches zero. */
  97292. if( !pTable ) return;
  97293. if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
  97294. deleteTable(db, pTable);
  97295. }
  97296. /*
  97297. ** Unlink the given table from the hash tables and the delete the
  97298. ** table structure with all its indices and foreign keys.
  97299. */
  97300. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  97301. Table *p;
  97302. Db *pDb;
  97303. assert( db!=0 );
  97304. assert( iDb>=0 && iDb<db->nDb );
  97305. assert( zTabName );
  97306. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97307. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  97308. pDb = &db->aDb[iDb];
  97309. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  97310. sqlite3DeleteTable(db, p);
  97311. db->mDbFlags |= DBFLAG_SchemaChange;
  97312. }
  97313. /*
  97314. ** Given a token, return a string that consists of the text of that
  97315. ** token. Space to hold the returned string
  97316. ** is obtained from sqliteMalloc() and must be freed by the calling
  97317. ** function.
  97318. **
  97319. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  97320. ** surround the body of the token are removed.
  97321. **
  97322. ** Tokens are often just pointers into the original SQL text and so
  97323. ** are not \000 terminated and are not persistent. The returned string
  97324. ** is \000 terminated and is persistent.
  97325. */
  97326. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  97327. char *zName;
  97328. if( pName ){
  97329. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  97330. sqlite3Dequote(zName);
  97331. }else{
  97332. zName = 0;
  97333. }
  97334. return zName;
  97335. }
  97336. /*
  97337. ** Open the sqlite_master table stored in database number iDb for
  97338. ** writing. The table is opened using cursor 0.
  97339. */
  97340. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  97341. Vdbe *v = sqlite3GetVdbe(p);
  97342. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
  97343. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  97344. if( p->nTab==0 ){
  97345. p->nTab = 1;
  97346. }
  97347. }
  97348. /*
  97349. ** Parameter zName points to a nul-terminated buffer containing the name
  97350. ** of a database ("main", "temp" or the name of an attached db). This
  97351. ** function returns the index of the named database in db->aDb[], or
  97352. ** -1 if the named db cannot be found.
  97353. */
  97354. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  97355. int i = -1; /* Database number */
  97356. if( zName ){
  97357. Db *pDb;
  97358. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  97359. if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
  97360. /* "main" is always an acceptable alias for the primary database
  97361. ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
  97362. if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
  97363. }
  97364. }
  97365. return i;
  97366. }
  97367. /*
  97368. ** The token *pName contains the name of a database (either "main" or
  97369. ** "temp" or the name of an attached db). This routine returns the
  97370. ** index of the named database in db->aDb[], or -1 if the named db
  97371. ** does not exist.
  97372. */
  97373. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  97374. int i; /* Database number */
  97375. char *zName; /* Name we are searching for */
  97376. zName = sqlite3NameFromToken(db, pName);
  97377. i = sqlite3FindDbName(db, zName);
  97378. sqlite3DbFree(db, zName);
  97379. return i;
  97380. }
  97381. /* The table or view or trigger name is passed to this routine via tokens
  97382. ** pName1 and pName2. If the table name was fully qualified, for example:
  97383. **
  97384. ** CREATE TABLE xxx.yyy (...);
  97385. **
  97386. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  97387. ** the table name is not fully qualified, i.e.:
  97388. **
  97389. ** CREATE TABLE yyy(...);
  97390. **
  97391. ** Then pName1 is set to "yyy" and pName2 is "".
  97392. **
  97393. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  97394. ** pName2) that stores the unqualified table name. The index of the
  97395. ** database "xxx" is returned.
  97396. */
  97397. SQLITE_PRIVATE int sqlite3TwoPartName(
  97398. Parse *pParse, /* Parsing and code generating context */
  97399. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  97400. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  97401. Token **pUnqual /* Write the unqualified object name here */
  97402. ){
  97403. int iDb; /* Database holding the object */
  97404. sqlite3 *db = pParse->db;
  97405. assert( pName2!=0 );
  97406. if( pName2->n>0 ){
  97407. if( db->init.busy ) {
  97408. sqlite3ErrorMsg(pParse, "corrupt database");
  97409. return -1;
  97410. }
  97411. *pUnqual = pName2;
  97412. iDb = sqlite3FindDb(db, pName1);
  97413. if( iDb<0 ){
  97414. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  97415. return -1;
  97416. }
  97417. }else{
  97418. assert( db->init.iDb==0 || db->init.busy
  97419. || (db->mDbFlags & DBFLAG_Vacuum)!=0);
  97420. iDb = db->init.iDb;
  97421. *pUnqual = pName1;
  97422. }
  97423. return iDb;
  97424. }
  97425. /*
  97426. ** This routine is used to check if the UTF-8 string zName is a legal
  97427. ** unqualified name for a new schema object (table, index, view or
  97428. ** trigger). All names are legal except those that begin with the string
  97429. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  97430. ** is reserved for internal use.
  97431. */
  97432. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  97433. if( !pParse->db->init.busy && pParse->nested==0
  97434. && (pParse->db->flags & SQLITE_WriteSchema)==0
  97435. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  97436. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  97437. return SQLITE_ERROR;
  97438. }
  97439. return SQLITE_OK;
  97440. }
  97441. /*
  97442. ** Return the PRIMARY KEY index of a table
  97443. */
  97444. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  97445. Index *p;
  97446. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  97447. return p;
  97448. }
  97449. /*
  97450. ** Return the column of index pIdx that corresponds to table
  97451. ** column iCol. Return -1 if not found.
  97452. */
  97453. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  97454. int i;
  97455. for(i=0; i<pIdx->nColumn; i++){
  97456. if( iCol==pIdx->aiColumn[i] ) return i;
  97457. }
  97458. return -1;
  97459. }
  97460. /*
  97461. ** Begin constructing a new table representation in memory. This is
  97462. ** the first of several action routines that get called in response
  97463. ** to a CREATE TABLE statement. In particular, this routine is called
  97464. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  97465. ** flag is true if the table should be stored in the auxiliary database
  97466. ** file instead of in the main database file. This is normally the case
  97467. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  97468. ** CREATE and TABLE.
  97469. **
  97470. ** The new table record is initialized and put in pParse->pNewTable.
  97471. ** As more of the CREATE TABLE statement is parsed, additional action
  97472. ** routines will be called to add more information to this record.
  97473. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  97474. ** is called to complete the construction of the new table record.
  97475. */
  97476. SQLITE_PRIVATE void sqlite3StartTable(
  97477. Parse *pParse, /* Parser context */
  97478. Token *pName1, /* First part of the name of the table or view */
  97479. Token *pName2, /* Second part of the name of the table or view */
  97480. int isTemp, /* True if this is a TEMP table */
  97481. int isView, /* True if this is a VIEW */
  97482. int isVirtual, /* True if this is a VIRTUAL table */
  97483. int noErr /* Do nothing if table already exists */
  97484. ){
  97485. Table *pTable;
  97486. char *zName = 0; /* The name of the new table */
  97487. sqlite3 *db = pParse->db;
  97488. Vdbe *v;
  97489. int iDb; /* Database number to create the table in */
  97490. Token *pName; /* Unqualified name of the table to create */
  97491. if( db->init.busy && db->init.newTnum==1 ){
  97492. /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
  97493. iDb = db->init.iDb;
  97494. zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
  97495. pName = pName1;
  97496. }else{
  97497. /* The common case */
  97498. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  97499. if( iDb<0 ) return;
  97500. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  97501. /* If creating a temp table, the name may not be qualified. Unless
  97502. ** the database name is "temp" anyway. */
  97503. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  97504. return;
  97505. }
  97506. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  97507. zName = sqlite3NameFromToken(db, pName);
  97508. }
  97509. pParse->sNameToken = *pName;
  97510. if( zName==0 ) return;
  97511. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  97512. goto begin_table_error;
  97513. }
  97514. if( db->init.iDb==1 ) isTemp = 1;
  97515. #ifndef SQLITE_OMIT_AUTHORIZATION
  97516. assert( isTemp==0 || isTemp==1 );
  97517. assert( isView==0 || isView==1 );
  97518. {
  97519. static const u8 aCode[] = {
  97520. SQLITE_CREATE_TABLE,
  97521. SQLITE_CREATE_TEMP_TABLE,
  97522. SQLITE_CREATE_VIEW,
  97523. SQLITE_CREATE_TEMP_VIEW
  97524. };
  97525. char *zDb = db->aDb[iDb].zDbSName;
  97526. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  97527. goto begin_table_error;
  97528. }
  97529. if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
  97530. zName, 0, zDb) ){
  97531. goto begin_table_error;
  97532. }
  97533. }
  97534. #endif
  97535. /* Make sure the new table name does not collide with an existing
  97536. ** index or table name in the same database. Issue an error message if
  97537. ** it does. The exception is if the statement being parsed was passed
  97538. ** to an sqlite3_declare_vtab() call. In that case only the column names
  97539. ** and types will be used, so there is no need to test for namespace
  97540. ** collisions.
  97541. */
  97542. if( !IN_DECLARE_VTAB ){
  97543. char *zDb = db->aDb[iDb].zDbSName;
  97544. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  97545. goto begin_table_error;
  97546. }
  97547. pTable = sqlite3FindTable(db, zName, zDb);
  97548. if( pTable ){
  97549. if( !noErr ){
  97550. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  97551. }else{
  97552. assert( !db->init.busy || CORRUPT_DB );
  97553. sqlite3CodeVerifySchema(pParse, iDb);
  97554. }
  97555. goto begin_table_error;
  97556. }
  97557. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  97558. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  97559. goto begin_table_error;
  97560. }
  97561. }
  97562. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  97563. if( pTable==0 ){
  97564. assert( db->mallocFailed );
  97565. pParse->rc = SQLITE_NOMEM_BKPT;
  97566. pParse->nErr++;
  97567. goto begin_table_error;
  97568. }
  97569. pTable->zName = zName;
  97570. pTable->iPKey = -1;
  97571. pTable->pSchema = db->aDb[iDb].pSchema;
  97572. pTable->nTabRef = 1;
  97573. #ifdef SQLITE_DEFAULT_ROWEST
  97574. pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
  97575. #else
  97576. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  97577. #endif
  97578. assert( pParse->pNewTable==0 );
  97579. pParse->pNewTable = pTable;
  97580. /* If this is the magic sqlite_sequence table used by autoincrement,
  97581. ** then record a pointer to this table in the main database structure
  97582. ** so that INSERT can find the table easily.
  97583. */
  97584. #ifndef SQLITE_OMIT_AUTOINCREMENT
  97585. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  97586. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97587. pTable->pSchema->pSeqTab = pTable;
  97588. }
  97589. #endif
  97590. /* Begin generating the code that will insert the table record into
  97591. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  97592. ** and allocate the record number for the table entry now. Before any
  97593. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  97594. ** indices to be created and the table record must come before the
  97595. ** indices. Hence, the record number for the table must be allocated
  97596. ** now.
  97597. */
  97598. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  97599. int addr1;
  97600. int fileFormat;
  97601. int reg1, reg2, reg3;
  97602. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  97603. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  97604. sqlite3BeginWriteOperation(pParse, 1, iDb);
  97605. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97606. if( isVirtual ){
  97607. sqlite3VdbeAddOp0(v, OP_VBegin);
  97608. }
  97609. #endif
  97610. /* If the file format and encoding in the database have not been set,
  97611. ** set them now.
  97612. */
  97613. reg1 = pParse->regRowid = ++pParse->nMem;
  97614. reg2 = pParse->regRoot = ++pParse->nMem;
  97615. reg3 = ++pParse->nMem;
  97616. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  97617. sqlite3VdbeUsesBtree(v, iDb);
  97618. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  97619. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  97620. 1 : SQLITE_MAX_FILE_FORMAT;
  97621. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
  97622. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
  97623. sqlite3VdbeJumpHere(v, addr1);
  97624. /* This just creates a place-holder record in the sqlite_master table.
  97625. ** The record created does not contain anything yet. It will be replaced
  97626. ** by the real entry in code generated at sqlite3EndTable().
  97627. **
  97628. ** The rowid for the new entry is left in register pParse->regRowid.
  97629. ** The root page number of the new table is left in reg pParse->regRoot.
  97630. ** The rowid and root page number values are needed by the code that
  97631. ** sqlite3EndTable will generate.
  97632. */
  97633. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  97634. if( isView || isVirtual ){
  97635. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  97636. }else
  97637. #endif
  97638. {
  97639. pParse->addrCrTab =
  97640. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
  97641. }
  97642. sqlite3OpenMasterTable(pParse, iDb);
  97643. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  97644. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  97645. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  97646. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  97647. sqlite3VdbeAddOp0(v, OP_Close);
  97648. }
  97649. /* Normal (non-error) return. */
  97650. return;
  97651. /* If an error occurs, we jump here */
  97652. begin_table_error:
  97653. sqlite3DbFree(db, zName);
  97654. return;
  97655. }
  97656. /* Set properties of a table column based on the (magical)
  97657. ** name of the column.
  97658. */
  97659. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  97660. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  97661. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  97662. pCol->colFlags |= COLFLAG_HIDDEN;
  97663. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  97664. pTab->tabFlags |= TF_OOOHidden;
  97665. }
  97666. }
  97667. #endif
  97668. /*
  97669. ** Add a new column to the table currently being constructed.
  97670. **
  97671. ** The parser calls this routine once for each column declaration
  97672. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  97673. ** first to get things going. Then this routine is called for each
  97674. ** column.
  97675. */
  97676. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
  97677. Table *p;
  97678. int i;
  97679. char *z;
  97680. char *zType;
  97681. Column *pCol;
  97682. sqlite3 *db = pParse->db;
  97683. if( (p = pParse->pNewTable)==0 ) return;
  97684. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  97685. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  97686. return;
  97687. }
  97688. z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
  97689. if( z==0 ) return;
  97690. memcpy(z, pName->z, pName->n);
  97691. z[pName->n] = 0;
  97692. sqlite3Dequote(z);
  97693. for(i=0; i<p->nCol; i++){
  97694. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  97695. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  97696. sqlite3DbFree(db, z);
  97697. return;
  97698. }
  97699. }
  97700. if( (p->nCol & 0x7)==0 ){
  97701. Column *aNew;
  97702. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  97703. if( aNew==0 ){
  97704. sqlite3DbFree(db, z);
  97705. return;
  97706. }
  97707. p->aCol = aNew;
  97708. }
  97709. pCol = &p->aCol[p->nCol];
  97710. memset(pCol, 0, sizeof(p->aCol[0]));
  97711. pCol->zName = z;
  97712. sqlite3ColumnPropertiesFromName(p, pCol);
  97713. if( pType->n==0 ){
  97714. /* If there is no type specified, columns have the default affinity
  97715. ** 'BLOB'. */
  97716. pCol->affinity = SQLITE_AFF_BLOB;
  97717. pCol->szEst = 1;
  97718. }else{
  97719. zType = z + sqlite3Strlen30(z) + 1;
  97720. memcpy(zType, pType->z, pType->n);
  97721. zType[pType->n] = 0;
  97722. sqlite3Dequote(zType);
  97723. pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
  97724. pCol->colFlags |= COLFLAG_HASTYPE;
  97725. }
  97726. p->nCol++;
  97727. pParse->constraintName.n = 0;
  97728. }
  97729. /*
  97730. ** This routine is called by the parser while in the middle of
  97731. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  97732. ** been seen on a column. This routine sets the notNull flag on
  97733. ** the column currently under construction.
  97734. */
  97735. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  97736. Table *p;
  97737. Column *pCol;
  97738. p = pParse->pNewTable;
  97739. if( p==0 || NEVER(p->nCol<1) ) return;
  97740. pCol = &p->aCol[p->nCol-1];
  97741. pCol->notNull = (u8)onError;
  97742. p->tabFlags |= TF_HasNotNull;
  97743. /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
  97744. ** on this column. */
  97745. if( pCol->colFlags & COLFLAG_UNIQUE ){
  97746. Index *pIdx;
  97747. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  97748. assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
  97749. if( pIdx->aiColumn[0]==p->nCol-1 ){
  97750. pIdx->uniqNotNull = 1;
  97751. }
  97752. }
  97753. }
  97754. }
  97755. /*
  97756. ** Scan the column type name zType (length nType) and return the
  97757. ** associated affinity type.
  97758. **
  97759. ** This routine does a case-independent search of zType for the
  97760. ** substrings in the following table. If one of the substrings is
  97761. ** found, the corresponding affinity is returned. If zType contains
  97762. ** more than one of the substrings, entries toward the top of
  97763. ** the table take priority. For example, if zType is 'BLOBINT',
  97764. ** SQLITE_AFF_INTEGER is returned.
  97765. **
  97766. ** Substring | Affinity
  97767. ** --------------------------------
  97768. ** 'INT' | SQLITE_AFF_INTEGER
  97769. ** 'CHAR' | SQLITE_AFF_TEXT
  97770. ** 'CLOB' | SQLITE_AFF_TEXT
  97771. ** 'TEXT' | SQLITE_AFF_TEXT
  97772. ** 'BLOB' | SQLITE_AFF_BLOB
  97773. ** 'REAL' | SQLITE_AFF_REAL
  97774. ** 'FLOA' | SQLITE_AFF_REAL
  97775. ** 'DOUB' | SQLITE_AFF_REAL
  97776. **
  97777. ** If none of the substrings in the above table are found,
  97778. ** SQLITE_AFF_NUMERIC is returned.
  97779. */
  97780. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  97781. u32 h = 0;
  97782. char aff = SQLITE_AFF_NUMERIC;
  97783. const char *zChar = 0;
  97784. assert( zIn!=0 );
  97785. while( zIn[0] ){
  97786. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  97787. zIn++;
  97788. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  97789. aff = SQLITE_AFF_TEXT;
  97790. zChar = zIn;
  97791. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  97792. aff = SQLITE_AFF_TEXT;
  97793. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  97794. aff = SQLITE_AFF_TEXT;
  97795. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  97796. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  97797. aff = SQLITE_AFF_BLOB;
  97798. if( zIn[0]=='(' ) zChar = zIn;
  97799. #ifndef SQLITE_OMIT_FLOATING_POINT
  97800. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  97801. && aff==SQLITE_AFF_NUMERIC ){
  97802. aff = SQLITE_AFF_REAL;
  97803. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  97804. && aff==SQLITE_AFF_NUMERIC ){
  97805. aff = SQLITE_AFF_REAL;
  97806. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  97807. && aff==SQLITE_AFF_NUMERIC ){
  97808. aff = SQLITE_AFF_REAL;
  97809. #endif
  97810. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  97811. aff = SQLITE_AFF_INTEGER;
  97812. break;
  97813. }
  97814. }
  97815. /* If pszEst is not NULL, store an estimate of the field size. The
  97816. ** estimate is scaled so that the size of an integer is 1. */
  97817. if( pszEst ){
  97818. *pszEst = 1; /* default size is approx 4 bytes */
  97819. if( aff<SQLITE_AFF_NUMERIC ){
  97820. if( zChar ){
  97821. while( zChar[0] ){
  97822. if( sqlite3Isdigit(zChar[0]) ){
  97823. int v = 0;
  97824. sqlite3GetInt32(zChar, &v);
  97825. v = v/4 + 1;
  97826. if( v>255 ) v = 255;
  97827. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  97828. break;
  97829. }
  97830. zChar++;
  97831. }
  97832. }else{
  97833. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  97834. }
  97835. }
  97836. }
  97837. return aff;
  97838. }
  97839. /*
  97840. ** The expression is the default value for the most recently added column
  97841. ** of the table currently under construction.
  97842. **
  97843. ** Default value expressions must be constant. Raise an exception if this
  97844. ** is not the case.
  97845. **
  97846. ** This routine is called by the parser while in the middle of
  97847. ** parsing a CREATE TABLE statement.
  97848. */
  97849. SQLITE_PRIVATE void sqlite3AddDefaultValue(
  97850. Parse *pParse, /* Parsing context */
  97851. Expr *pExpr, /* The parsed expression of the default value */
  97852. const char *zStart, /* Start of the default value text */
  97853. const char *zEnd /* First character past end of defaut value text */
  97854. ){
  97855. Table *p;
  97856. Column *pCol;
  97857. sqlite3 *db = pParse->db;
  97858. p = pParse->pNewTable;
  97859. if( p!=0 ){
  97860. pCol = &(p->aCol[p->nCol-1]);
  97861. if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
  97862. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  97863. pCol->zName);
  97864. }else{
  97865. /* A copy of pExpr is used instead of the original, as pExpr contains
  97866. ** tokens that point to volatile memory.
  97867. */
  97868. Expr x;
  97869. sqlite3ExprDelete(db, pCol->pDflt);
  97870. memset(&x, 0, sizeof(x));
  97871. x.op = TK_SPAN;
  97872. x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
  97873. x.pLeft = pExpr;
  97874. x.flags = EP_Skip;
  97875. pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
  97876. sqlite3DbFree(db, x.u.zToken);
  97877. }
  97878. }
  97879. sqlite3ExprDelete(db, pExpr);
  97880. }
  97881. /*
  97882. ** Backwards Compatibility Hack:
  97883. **
  97884. ** Historical versions of SQLite accepted strings as column names in
  97885. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  97886. **
  97887. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  97888. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  97889. **
  97890. ** This is goofy. But to preserve backwards compatibility we continue to
  97891. ** accept it. This routine does the necessary conversion. It converts
  97892. ** the expression given in its argument from a TK_STRING into a TK_ID
  97893. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  97894. ** If the epxression is anything other than TK_STRING, the expression is
  97895. ** unchanged.
  97896. */
  97897. static void sqlite3StringToId(Expr *p){
  97898. if( p->op==TK_STRING ){
  97899. p->op = TK_ID;
  97900. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  97901. p->pLeft->op = TK_ID;
  97902. }
  97903. }
  97904. /*
  97905. ** Designate the PRIMARY KEY for the table. pList is a list of names
  97906. ** of columns that form the primary key. If pList is NULL, then the
  97907. ** most recently added column of the table is the primary key.
  97908. **
  97909. ** A table can have at most one primary key. If the table already has
  97910. ** a primary key (and this is the second primary key) then create an
  97911. ** error.
  97912. **
  97913. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  97914. ** then we will try to use that column as the rowid. Set the Table.iPKey
  97915. ** field of the table under construction to be the index of the
  97916. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  97917. ** no INTEGER PRIMARY KEY.
  97918. **
  97919. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  97920. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  97921. */
  97922. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  97923. Parse *pParse, /* Parsing context */
  97924. ExprList *pList, /* List of field names to be indexed */
  97925. int onError, /* What to do with a uniqueness conflict */
  97926. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  97927. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  97928. ){
  97929. Table *pTab = pParse->pNewTable;
  97930. Column *pCol = 0;
  97931. int iCol = -1, i;
  97932. int nTerm;
  97933. if( pTab==0 ) goto primary_key_exit;
  97934. if( pTab->tabFlags & TF_HasPrimaryKey ){
  97935. sqlite3ErrorMsg(pParse,
  97936. "table \"%s\" has more than one primary key", pTab->zName);
  97937. goto primary_key_exit;
  97938. }
  97939. pTab->tabFlags |= TF_HasPrimaryKey;
  97940. if( pList==0 ){
  97941. iCol = pTab->nCol - 1;
  97942. pCol = &pTab->aCol[iCol];
  97943. pCol->colFlags |= COLFLAG_PRIMKEY;
  97944. nTerm = 1;
  97945. }else{
  97946. nTerm = pList->nExpr;
  97947. for(i=0; i<nTerm; i++){
  97948. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  97949. assert( pCExpr!=0 );
  97950. sqlite3StringToId(pCExpr);
  97951. if( pCExpr->op==TK_ID ){
  97952. const char *zCName = pCExpr->u.zToken;
  97953. for(iCol=0; iCol<pTab->nCol; iCol++){
  97954. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  97955. pCol = &pTab->aCol[iCol];
  97956. pCol->colFlags |= COLFLAG_PRIMKEY;
  97957. break;
  97958. }
  97959. }
  97960. }
  97961. }
  97962. }
  97963. if( nTerm==1
  97964. && pCol
  97965. && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
  97966. && sortOrder!=SQLITE_SO_DESC
  97967. ){
  97968. pTab->iPKey = iCol;
  97969. pTab->keyConf = (u8)onError;
  97970. assert( autoInc==0 || autoInc==1 );
  97971. pTab->tabFlags |= autoInc*TF_Autoincrement;
  97972. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  97973. }else if( autoInc ){
  97974. #ifndef SQLITE_OMIT_AUTOINCREMENT
  97975. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  97976. "INTEGER PRIMARY KEY");
  97977. #endif
  97978. }else{
  97979. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  97980. 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
  97981. pList = 0;
  97982. }
  97983. primary_key_exit:
  97984. sqlite3ExprListDelete(pParse->db, pList);
  97985. return;
  97986. }
  97987. /*
  97988. ** Add a new CHECK constraint to the table currently under construction.
  97989. */
  97990. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  97991. Parse *pParse, /* Parsing context */
  97992. Expr *pCheckExpr /* The check expression */
  97993. ){
  97994. #ifndef SQLITE_OMIT_CHECK
  97995. Table *pTab = pParse->pNewTable;
  97996. sqlite3 *db = pParse->db;
  97997. if( pTab && !IN_DECLARE_VTAB
  97998. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  97999. ){
  98000. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  98001. if( pParse->constraintName.n ){
  98002. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  98003. }
  98004. }else
  98005. #endif
  98006. {
  98007. sqlite3ExprDelete(pParse->db, pCheckExpr);
  98008. }
  98009. }
  98010. /*
  98011. ** Set the collation function of the most recently parsed table column
  98012. ** to the CollSeq given.
  98013. */
  98014. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  98015. Table *p;
  98016. int i;
  98017. char *zColl; /* Dequoted name of collation sequence */
  98018. sqlite3 *db;
  98019. if( (p = pParse->pNewTable)==0 ) return;
  98020. i = p->nCol-1;
  98021. db = pParse->db;
  98022. zColl = sqlite3NameFromToken(db, pToken);
  98023. if( !zColl ) return;
  98024. if( sqlite3LocateCollSeq(pParse, zColl) ){
  98025. Index *pIdx;
  98026. sqlite3DbFree(db, p->aCol[i].zColl);
  98027. p->aCol[i].zColl = zColl;
  98028. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  98029. ** then an index may have been created on this column before the
  98030. ** collation type was added. Correct this if it is the case.
  98031. */
  98032. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  98033. assert( pIdx->nKeyCol==1 );
  98034. if( pIdx->aiColumn[0]==i ){
  98035. pIdx->azColl[0] = p->aCol[i].zColl;
  98036. }
  98037. }
  98038. }else{
  98039. sqlite3DbFree(db, zColl);
  98040. }
  98041. }
  98042. /*
  98043. ** This function returns the collation sequence for database native text
  98044. ** encoding identified by the string zName, length nName.
  98045. **
  98046. ** If the requested collation sequence is not available, or not available
  98047. ** in the database native encoding, the collation factory is invoked to
  98048. ** request it. If the collation factory does not supply such a sequence,
  98049. ** and the sequence is available in another text encoding, then that is
  98050. ** returned instead.
  98051. **
  98052. ** If no versions of the requested collations sequence are available, or
  98053. ** another error occurs, NULL is returned and an error message written into
  98054. ** pParse.
  98055. **
  98056. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  98057. ** invokes the collation factory if the named collation cannot be found
  98058. ** and generates an error message.
  98059. **
  98060. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  98061. */
  98062. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  98063. sqlite3 *db = pParse->db;
  98064. u8 enc = ENC(db);
  98065. u8 initbusy = db->init.busy;
  98066. CollSeq *pColl;
  98067. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  98068. if( !initbusy && (!pColl || !pColl->xCmp) ){
  98069. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  98070. }
  98071. return pColl;
  98072. }
  98073. /*
  98074. ** Generate code that will increment the schema cookie.
  98075. **
  98076. ** The schema cookie is used to determine when the schema for the
  98077. ** database changes. After each schema change, the cookie value
  98078. ** changes. When a process first reads the schema it records the
  98079. ** cookie. Thereafter, whenever it goes to access the database,
  98080. ** it checks the cookie to make sure the schema has not changed
  98081. ** since it was last read.
  98082. **
  98083. ** This plan is not completely bullet-proof. It is possible for
  98084. ** the schema to change multiple times and for the cookie to be
  98085. ** set back to prior value. But schema changes are infrequent
  98086. ** and the probability of hitting the same cookie value is only
  98087. ** 1 chance in 2^32. So we're safe enough.
  98088. **
  98089. ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
  98090. ** the schema-version whenever the schema changes.
  98091. */
  98092. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  98093. sqlite3 *db = pParse->db;
  98094. Vdbe *v = pParse->pVdbe;
  98095. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98096. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
  98097. (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
  98098. }
  98099. /*
  98100. ** Measure the number of characters needed to output the given
  98101. ** identifier. The number returned includes any quotes used
  98102. ** but does not include the null terminator.
  98103. **
  98104. ** The estimate is conservative. It might be larger that what is
  98105. ** really needed.
  98106. */
  98107. static int identLength(const char *z){
  98108. int n;
  98109. for(n=0; *z; n++, z++){
  98110. if( *z=='"' ){ n++; }
  98111. }
  98112. return n + 2;
  98113. }
  98114. /*
  98115. ** The first parameter is a pointer to an output buffer. The second
  98116. ** parameter is a pointer to an integer that contains the offset at
  98117. ** which to write into the output buffer. This function copies the
  98118. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  98119. ** to the specified offset in the buffer and updates *pIdx to refer
  98120. ** to the first byte after the last byte written before returning.
  98121. **
  98122. ** If the string zSignedIdent consists entirely of alpha-numeric
  98123. ** characters, does not begin with a digit and is not an SQL keyword,
  98124. ** then it is copied to the output buffer exactly as it is. Otherwise,
  98125. ** it is quoted using double-quotes.
  98126. */
  98127. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  98128. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  98129. int i, j, needQuote;
  98130. i = *pIdx;
  98131. for(j=0; zIdent[j]; j++){
  98132. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  98133. }
  98134. needQuote = sqlite3Isdigit(zIdent[0])
  98135. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  98136. || zIdent[j]!=0
  98137. || j==0;
  98138. if( needQuote ) z[i++] = '"';
  98139. for(j=0; zIdent[j]; j++){
  98140. z[i++] = zIdent[j];
  98141. if( zIdent[j]=='"' ) z[i++] = '"';
  98142. }
  98143. if( needQuote ) z[i++] = '"';
  98144. z[i] = 0;
  98145. *pIdx = i;
  98146. }
  98147. /*
  98148. ** Generate a CREATE TABLE statement appropriate for the given
  98149. ** table. Memory to hold the text of the statement is obtained
  98150. ** from sqliteMalloc() and must be freed by the calling function.
  98151. */
  98152. static char *createTableStmt(sqlite3 *db, Table *p){
  98153. int i, k, n;
  98154. char *zStmt;
  98155. char *zSep, *zSep2, *zEnd;
  98156. Column *pCol;
  98157. n = 0;
  98158. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  98159. n += identLength(pCol->zName) + 5;
  98160. }
  98161. n += identLength(p->zName);
  98162. if( n<50 ){
  98163. zSep = "";
  98164. zSep2 = ",";
  98165. zEnd = ")";
  98166. }else{
  98167. zSep = "\n ";
  98168. zSep2 = ",\n ";
  98169. zEnd = "\n)";
  98170. }
  98171. n += 35 + 6*p->nCol;
  98172. zStmt = sqlite3DbMallocRaw(0, n);
  98173. if( zStmt==0 ){
  98174. sqlite3OomFault(db);
  98175. return 0;
  98176. }
  98177. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  98178. k = sqlite3Strlen30(zStmt);
  98179. identPut(zStmt, &k, p->zName);
  98180. zStmt[k++] = '(';
  98181. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  98182. static const char * const azType[] = {
  98183. /* SQLITE_AFF_BLOB */ "",
  98184. /* SQLITE_AFF_TEXT */ " TEXT",
  98185. /* SQLITE_AFF_NUMERIC */ " NUM",
  98186. /* SQLITE_AFF_INTEGER */ " INT",
  98187. /* SQLITE_AFF_REAL */ " REAL"
  98188. };
  98189. int len;
  98190. const char *zType;
  98191. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  98192. k += sqlite3Strlen30(&zStmt[k]);
  98193. zSep = zSep2;
  98194. identPut(zStmt, &k, pCol->zName);
  98195. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  98196. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  98197. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  98198. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  98199. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  98200. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  98201. testcase( pCol->affinity==SQLITE_AFF_REAL );
  98202. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  98203. len = sqlite3Strlen30(zType);
  98204. assert( pCol->affinity==SQLITE_AFF_BLOB
  98205. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  98206. memcpy(&zStmt[k], zType, len);
  98207. k += len;
  98208. assert( k<=n );
  98209. }
  98210. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  98211. return zStmt;
  98212. }
  98213. /*
  98214. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  98215. ** on success and SQLITE_NOMEM on an OOM error.
  98216. */
  98217. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  98218. char *zExtra;
  98219. int nByte;
  98220. if( pIdx->nColumn>=N ) return SQLITE_OK;
  98221. assert( pIdx->isResized==0 );
  98222. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  98223. zExtra = sqlite3DbMallocZero(db, nByte);
  98224. if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
  98225. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  98226. pIdx->azColl = (const char**)zExtra;
  98227. zExtra += sizeof(char*)*N;
  98228. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  98229. pIdx->aiColumn = (i16*)zExtra;
  98230. zExtra += sizeof(i16)*N;
  98231. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  98232. pIdx->aSortOrder = (u8*)zExtra;
  98233. pIdx->nColumn = N;
  98234. pIdx->isResized = 1;
  98235. return SQLITE_OK;
  98236. }
  98237. /*
  98238. ** Estimate the total row width for a table.
  98239. */
  98240. static void estimateTableWidth(Table *pTab){
  98241. unsigned wTable = 0;
  98242. const Column *pTabCol;
  98243. int i;
  98244. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  98245. wTable += pTabCol->szEst;
  98246. }
  98247. if( pTab->iPKey<0 ) wTable++;
  98248. pTab->szTabRow = sqlite3LogEst(wTable*4);
  98249. }
  98250. /*
  98251. ** Estimate the average size of a row for an index.
  98252. */
  98253. static void estimateIndexWidth(Index *pIdx){
  98254. unsigned wIndex = 0;
  98255. int i;
  98256. const Column *aCol = pIdx->pTable->aCol;
  98257. for(i=0; i<pIdx->nColumn; i++){
  98258. i16 x = pIdx->aiColumn[i];
  98259. assert( x<pIdx->pTable->nCol );
  98260. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  98261. }
  98262. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  98263. }
  98264. /* Return true if value x is found any of the first nCol entries of aiCol[]
  98265. */
  98266. static int hasColumn(const i16 *aiCol, int nCol, int x){
  98267. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  98268. return 0;
  98269. }
  98270. /*
  98271. ** This routine runs at the end of parsing a CREATE TABLE statement that
  98272. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  98273. ** internal schema data structures and the generated VDBE code so that they
  98274. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  98275. ** Changes include:
  98276. **
  98277. ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  98278. ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
  98279. ** into BTREE_BLOBKEY.
  98280. ** (3) Bypass the creation of the sqlite_master table entry
  98281. ** for the PRIMARY KEY as the primary key index is now
  98282. ** identified by the sqlite_master table entry of the table itself.
  98283. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
  98284. ** schema to the rootpage from the main table.
  98285. ** (5) Add all table columns to the PRIMARY KEY Index object
  98286. ** so that the PRIMARY KEY is a covering index. The surplus
  98287. ** columns are part of KeyInfo.nAllField and are not used for
  98288. ** sorting or lookup or uniqueness checks.
  98289. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  98290. ** indices with the PRIMARY KEY columns.
  98291. **
  98292. ** For virtual tables, only (1) is performed.
  98293. */
  98294. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  98295. Index *pIdx;
  98296. Index *pPk;
  98297. int nPk;
  98298. int i, j;
  98299. sqlite3 *db = pParse->db;
  98300. Vdbe *v = pParse->pVdbe;
  98301. /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
  98302. */
  98303. if( !db->init.imposterTable ){
  98304. for(i=0; i<pTab->nCol; i++){
  98305. if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
  98306. pTab->aCol[i].notNull = OE_Abort;
  98307. }
  98308. }
  98309. }
  98310. /* The remaining transformations only apply to b-tree tables, not to
  98311. ** virtual tables */
  98312. if( IN_DECLARE_VTAB ) return;
  98313. /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
  98314. ** into BTREE_BLOBKEY.
  98315. */
  98316. if( pParse->addrCrTab ){
  98317. assert( v );
  98318. sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
  98319. }
  98320. /* Locate the PRIMARY KEY index. Or, if this table was originally
  98321. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  98322. */
  98323. if( pTab->iPKey>=0 ){
  98324. ExprList *pList;
  98325. Token ipkToken;
  98326. sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
  98327. pList = sqlite3ExprListAppend(pParse, 0,
  98328. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  98329. if( pList==0 ) return;
  98330. pList->a[0].sortOrder = pParse->iPkSortOrder;
  98331. assert( pParse->pNewTable==pTab );
  98332. sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
  98333. SQLITE_IDXTYPE_PRIMARYKEY);
  98334. if( db->mallocFailed ) return;
  98335. pPk = sqlite3PrimaryKeyIndex(pTab);
  98336. pTab->iPKey = -1;
  98337. }else{
  98338. pPk = sqlite3PrimaryKeyIndex(pTab);
  98339. /*
  98340. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  98341. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  98342. ** code assumes the PRIMARY KEY contains no repeated columns.
  98343. */
  98344. for(i=j=1; i<pPk->nKeyCol; i++){
  98345. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  98346. pPk->nColumn--;
  98347. }else{
  98348. pPk->aiColumn[j++] = pPk->aiColumn[i];
  98349. }
  98350. }
  98351. pPk->nKeyCol = j;
  98352. }
  98353. assert( pPk!=0 );
  98354. pPk->isCovering = 1;
  98355. if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
  98356. nPk = pPk->nKeyCol;
  98357. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  98358. ** table entry. This is only required if currently generating VDBE
  98359. ** code for a CREATE TABLE (not when parsing one as part of reading
  98360. ** a database schema). */
  98361. if( v && pPk->tnum>0 ){
  98362. assert( db->init.busy==0 );
  98363. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  98364. }
  98365. /* The root page of the PRIMARY KEY is the table root page */
  98366. pPk->tnum = pTab->tnum;
  98367. /* Update the in-memory representation of all UNIQUE indices by converting
  98368. ** the final rowid column into one or more columns of the PRIMARY KEY.
  98369. */
  98370. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  98371. int n;
  98372. if( IsPrimaryKeyIndex(pIdx) ) continue;
  98373. for(i=n=0; i<nPk; i++){
  98374. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  98375. }
  98376. if( n==0 ){
  98377. /* This index is a superset of the primary key */
  98378. pIdx->nColumn = pIdx->nKeyCol;
  98379. continue;
  98380. }
  98381. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  98382. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  98383. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  98384. pIdx->aiColumn[j] = pPk->aiColumn[i];
  98385. pIdx->azColl[j] = pPk->azColl[i];
  98386. j++;
  98387. }
  98388. }
  98389. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  98390. assert( pIdx->nColumn>=j );
  98391. }
  98392. /* Add all table columns to the PRIMARY KEY index
  98393. */
  98394. if( nPk<pTab->nCol ){
  98395. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  98396. for(i=0, j=nPk; i<pTab->nCol; i++){
  98397. if( !hasColumn(pPk->aiColumn, j, i) ){
  98398. assert( j<pPk->nColumn );
  98399. pPk->aiColumn[j] = i;
  98400. pPk->azColl[j] = sqlite3StrBINARY;
  98401. j++;
  98402. }
  98403. }
  98404. assert( pPk->nColumn==j );
  98405. assert( pTab->nCol==j );
  98406. }else{
  98407. pPk->nColumn = pTab->nCol;
  98408. }
  98409. }
  98410. /*
  98411. ** This routine is called to report the final ")" that terminates
  98412. ** a CREATE TABLE statement.
  98413. **
  98414. ** The table structure that other action routines have been building
  98415. ** is added to the internal hash tables, assuming no errors have
  98416. ** occurred.
  98417. **
  98418. ** An entry for the table is made in the master table on disk, unless
  98419. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  98420. ** it means we are reading the sqlite_master table because we just
  98421. ** connected to the database or because the sqlite_master table has
  98422. ** recently changed, so the entry for this table already exists in
  98423. ** the sqlite_master table. We do not want to create it again.
  98424. **
  98425. ** If the pSelect argument is not NULL, it means that this routine
  98426. ** was called to create a table generated from a
  98427. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  98428. ** the new table will match the result set of the SELECT.
  98429. */
  98430. SQLITE_PRIVATE void sqlite3EndTable(
  98431. Parse *pParse, /* Parse context */
  98432. Token *pCons, /* The ',' token after the last column defn. */
  98433. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  98434. u8 tabOpts, /* Extra table options. Usually 0. */
  98435. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  98436. ){
  98437. Table *p; /* The new table */
  98438. sqlite3 *db = pParse->db; /* The database connection */
  98439. int iDb; /* Database in which the table lives */
  98440. Index *pIdx; /* An implied index of the table */
  98441. if( pEnd==0 && pSelect==0 ){
  98442. return;
  98443. }
  98444. assert( !db->mallocFailed );
  98445. p = pParse->pNewTable;
  98446. if( p==0 ) return;
  98447. /* If the db->init.busy is 1 it means we are reading the SQL off the
  98448. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  98449. ** So do not write to the disk again. Extract the root page number
  98450. ** for the table from the db->init.newTnum field. (The page number
  98451. ** should have been put there by the sqliteOpenCb routine.)
  98452. **
  98453. ** If the root page number is 1, that means this is the sqlite_master
  98454. ** table itself. So mark it read-only.
  98455. */
  98456. if( db->init.busy ){
  98457. if( pSelect ){
  98458. sqlite3ErrorMsg(pParse, "");
  98459. return;
  98460. }
  98461. p->tnum = db->init.newTnum;
  98462. if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
  98463. }
  98464. /* Special processing for WITHOUT ROWID Tables */
  98465. if( tabOpts & TF_WithoutRowid ){
  98466. if( (p->tabFlags & TF_Autoincrement) ){
  98467. sqlite3ErrorMsg(pParse,
  98468. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  98469. return;
  98470. }
  98471. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  98472. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  98473. }else{
  98474. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  98475. convertToWithoutRowidTable(pParse, p);
  98476. }
  98477. }
  98478. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  98479. #ifndef SQLITE_OMIT_CHECK
  98480. /* Resolve names in all CHECK constraint expressions.
  98481. */
  98482. if( p->pCheck ){
  98483. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  98484. }
  98485. #endif /* !defined(SQLITE_OMIT_CHECK) */
  98486. /* Estimate the average row size for the table and for all implied indices */
  98487. estimateTableWidth(p);
  98488. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  98489. estimateIndexWidth(pIdx);
  98490. }
  98491. /* If not initializing, then create a record for the new table
  98492. ** in the SQLITE_MASTER table of the database.
  98493. **
  98494. ** If this is a TEMPORARY table, write the entry into the auxiliary
  98495. ** file instead of into the main database file.
  98496. */
  98497. if( !db->init.busy ){
  98498. int n;
  98499. Vdbe *v;
  98500. char *zType; /* "view" or "table" */
  98501. char *zType2; /* "VIEW" or "TABLE" */
  98502. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  98503. v = sqlite3GetVdbe(pParse);
  98504. if( NEVER(v==0) ) return;
  98505. sqlite3VdbeAddOp1(v, OP_Close, 0);
  98506. /*
  98507. ** Initialize zType for the new view or table.
  98508. */
  98509. if( p->pSelect==0 ){
  98510. /* A regular table */
  98511. zType = "table";
  98512. zType2 = "TABLE";
  98513. #ifndef SQLITE_OMIT_VIEW
  98514. }else{
  98515. /* A view */
  98516. zType = "view";
  98517. zType2 = "VIEW";
  98518. #endif
  98519. }
  98520. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  98521. ** statement to populate the new table. The root-page number for the
  98522. ** new table is in register pParse->regRoot.
  98523. **
  98524. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  98525. ** suitable state to query for the column names and types to be used
  98526. ** by the new table.
  98527. **
  98528. ** A shared-cache write-lock is not required to write to the new table,
  98529. ** as a schema-lock must have already been obtained to create it. Since
  98530. ** a schema-lock excludes all other database users, the write-lock would
  98531. ** be redundant.
  98532. */
  98533. if( pSelect ){
  98534. SelectDest dest; /* Where the SELECT should store results */
  98535. int regYield; /* Register holding co-routine entry-point */
  98536. int addrTop; /* Top of the co-routine */
  98537. int regRec; /* A record to be insert into the new table */
  98538. int regRowid; /* Rowid of the next row to insert */
  98539. int addrInsLoop; /* Top of the loop for inserting rows */
  98540. Table *pSelTab; /* A table that describes the SELECT results */
  98541. regYield = ++pParse->nMem;
  98542. regRec = ++pParse->nMem;
  98543. regRowid = ++pParse->nMem;
  98544. assert(pParse->nTab==1);
  98545. sqlite3MayAbort(pParse);
  98546. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  98547. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  98548. pParse->nTab = 2;
  98549. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  98550. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  98551. if( pParse->nErr ) return;
  98552. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  98553. if( pSelTab==0 ) return;
  98554. assert( p->aCol==0 );
  98555. p->nCol = pSelTab->nCol;
  98556. p->aCol = pSelTab->aCol;
  98557. pSelTab->nCol = 0;
  98558. pSelTab->aCol = 0;
  98559. sqlite3DeleteTable(db, pSelTab);
  98560. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  98561. sqlite3Select(pParse, pSelect, &dest);
  98562. if( pParse->nErr ) return;
  98563. sqlite3VdbeEndCoroutine(v, regYield);
  98564. sqlite3VdbeJumpHere(v, addrTop - 1);
  98565. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  98566. VdbeCoverage(v);
  98567. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  98568. sqlite3TableAffinity(v, p, 0);
  98569. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  98570. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  98571. sqlite3VdbeGoto(v, addrInsLoop);
  98572. sqlite3VdbeJumpHere(v, addrInsLoop);
  98573. sqlite3VdbeAddOp1(v, OP_Close, 1);
  98574. }
  98575. /* Compute the complete text of the CREATE statement */
  98576. if( pSelect ){
  98577. zStmt = createTableStmt(db, p);
  98578. }else{
  98579. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  98580. n = (int)(pEnd2->z - pParse->sNameToken.z);
  98581. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  98582. zStmt = sqlite3MPrintf(db,
  98583. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  98584. );
  98585. }
  98586. /* A slot for the record has already been allocated in the
  98587. ** SQLITE_MASTER table. We just need to update that slot with all
  98588. ** the information we've collected.
  98589. */
  98590. sqlite3NestedParse(pParse,
  98591. "UPDATE %Q.%s "
  98592. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  98593. "WHERE rowid=#%d",
  98594. db->aDb[iDb].zDbSName, MASTER_NAME,
  98595. zType,
  98596. p->zName,
  98597. p->zName,
  98598. pParse->regRoot,
  98599. zStmt,
  98600. pParse->regRowid
  98601. );
  98602. sqlite3DbFree(db, zStmt);
  98603. sqlite3ChangeCookie(pParse, iDb);
  98604. #ifndef SQLITE_OMIT_AUTOINCREMENT
  98605. /* Check to see if we need to create an sqlite_sequence table for
  98606. ** keeping track of autoincrement keys.
  98607. */
  98608. if( (p->tabFlags & TF_Autoincrement)!=0 ){
  98609. Db *pDb = &db->aDb[iDb];
  98610. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98611. if( pDb->pSchema->pSeqTab==0 ){
  98612. sqlite3NestedParse(pParse,
  98613. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  98614. pDb->zDbSName
  98615. );
  98616. }
  98617. }
  98618. #endif
  98619. /* Reparse everything to update our internal data structures */
  98620. sqlite3VdbeAddParseSchemaOp(v, iDb,
  98621. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  98622. }
  98623. /* Add the table to the in-memory representation of the database.
  98624. */
  98625. if( db->init.busy ){
  98626. Table *pOld;
  98627. Schema *pSchema = p->pSchema;
  98628. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98629. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  98630. if( pOld ){
  98631. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  98632. sqlite3OomFault(db);
  98633. return;
  98634. }
  98635. pParse->pNewTable = 0;
  98636. db->mDbFlags |= DBFLAG_SchemaChange;
  98637. #ifndef SQLITE_OMIT_ALTERTABLE
  98638. if( !p->pSelect ){
  98639. const char *zName = (const char *)pParse->sNameToken.z;
  98640. int nName;
  98641. assert( !pSelect && pCons && pEnd );
  98642. if( pCons->z==0 ){
  98643. pCons = pEnd;
  98644. }
  98645. nName = (int)((const char *)pCons->z - zName);
  98646. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  98647. }
  98648. #endif
  98649. }
  98650. }
  98651. #ifndef SQLITE_OMIT_VIEW
  98652. /*
  98653. ** The parser calls this routine in order to create a new VIEW
  98654. */
  98655. SQLITE_PRIVATE void sqlite3CreateView(
  98656. Parse *pParse, /* The parsing context */
  98657. Token *pBegin, /* The CREATE token that begins the statement */
  98658. Token *pName1, /* The token that holds the name of the view */
  98659. Token *pName2, /* The token that holds the name of the view */
  98660. ExprList *pCNames, /* Optional list of view column names */
  98661. Select *pSelect, /* A SELECT statement that will become the new view */
  98662. int isTemp, /* TRUE for a TEMPORARY view */
  98663. int noErr /* Suppress error messages if VIEW already exists */
  98664. ){
  98665. Table *p;
  98666. int n;
  98667. const char *z;
  98668. Token sEnd;
  98669. DbFixer sFix;
  98670. Token *pName = 0;
  98671. int iDb;
  98672. sqlite3 *db = pParse->db;
  98673. if( pParse->nVar>0 ){
  98674. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  98675. goto create_view_fail;
  98676. }
  98677. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  98678. p = pParse->pNewTable;
  98679. if( p==0 || pParse->nErr ) goto create_view_fail;
  98680. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  98681. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  98682. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  98683. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  98684. /* Make a copy of the entire SELECT statement that defines the view.
  98685. ** This will force all the Expr.token.z values to be dynamically
  98686. ** allocated rather than point to the input string - which means that
  98687. ** they will persist after the current sqlite3_exec() call returns.
  98688. */
  98689. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  98690. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  98691. if( db->mallocFailed ) goto create_view_fail;
  98692. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  98693. ** the end.
  98694. */
  98695. sEnd = pParse->sLastToken;
  98696. assert( sEnd.z[0]!=0 || sEnd.n==0 );
  98697. if( sEnd.z[0]!=';' ){
  98698. sEnd.z += sEnd.n;
  98699. }
  98700. sEnd.n = 0;
  98701. n = (int)(sEnd.z - pBegin->z);
  98702. assert( n>0 );
  98703. z = pBegin->z;
  98704. while( sqlite3Isspace(z[n-1]) ){ n--; }
  98705. sEnd.z = &z[n-1];
  98706. sEnd.n = 1;
  98707. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  98708. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  98709. create_view_fail:
  98710. sqlite3SelectDelete(db, pSelect);
  98711. sqlite3ExprListDelete(db, pCNames);
  98712. return;
  98713. }
  98714. #endif /* SQLITE_OMIT_VIEW */
  98715. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  98716. /*
  98717. ** The Table structure pTable is really a VIEW. Fill in the names of
  98718. ** the columns of the view in the pTable structure. Return the number
  98719. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  98720. */
  98721. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  98722. Table *pSelTab; /* A fake table from which we get the result set */
  98723. Select *pSel; /* Copy of the SELECT that implements the view */
  98724. int nErr = 0; /* Number of errors encountered */
  98725. int n; /* Temporarily holds the number of cursors assigned */
  98726. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  98727. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98728. int rc;
  98729. #endif
  98730. #ifndef SQLITE_OMIT_AUTHORIZATION
  98731. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  98732. #endif
  98733. assert( pTable );
  98734. #ifndef SQLITE_OMIT_VIRTUALTABLE
  98735. db->nSchemaLock++;
  98736. rc = sqlite3VtabCallConnect(pParse, pTable);
  98737. db->nSchemaLock--;
  98738. if( rc ){
  98739. return 1;
  98740. }
  98741. if( IsVirtual(pTable) ) return 0;
  98742. #endif
  98743. #ifndef SQLITE_OMIT_VIEW
  98744. /* A positive nCol means the columns names for this view are
  98745. ** already known.
  98746. */
  98747. if( pTable->nCol>0 ) return 0;
  98748. /* A negative nCol is a special marker meaning that we are currently
  98749. ** trying to compute the column names. If we enter this routine with
  98750. ** a negative nCol, it means two or more views form a loop, like this:
  98751. **
  98752. ** CREATE VIEW one AS SELECT * FROM two;
  98753. ** CREATE VIEW two AS SELECT * FROM one;
  98754. **
  98755. ** Actually, the error above is now caught prior to reaching this point.
  98756. ** But the following test is still important as it does come up
  98757. ** in the following:
  98758. **
  98759. ** CREATE TABLE main.ex1(a);
  98760. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  98761. ** SELECT * FROM temp.ex1;
  98762. */
  98763. if( pTable->nCol<0 ){
  98764. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  98765. return 1;
  98766. }
  98767. assert( pTable->nCol>=0 );
  98768. /* If we get this far, it means we need to compute the table names.
  98769. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  98770. ** "*" elements in the results set of the view and will assign cursors
  98771. ** to the elements of the FROM clause. But we do not want these changes
  98772. ** to be permanent. So the computation is done on a copy of the SELECT
  98773. ** statement that defines the view.
  98774. */
  98775. assert( pTable->pSelect );
  98776. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  98777. if( pSel ){
  98778. n = pParse->nTab;
  98779. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  98780. pTable->nCol = -1;
  98781. db->lookaside.bDisable++;
  98782. #ifndef SQLITE_OMIT_AUTHORIZATION
  98783. xAuth = db->xAuth;
  98784. db->xAuth = 0;
  98785. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  98786. db->xAuth = xAuth;
  98787. #else
  98788. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  98789. #endif
  98790. pParse->nTab = n;
  98791. if( pTable->pCheck ){
  98792. /* CREATE VIEW name(arglist) AS ...
  98793. ** The names of the columns in the table are taken from
  98794. ** arglist which is stored in pTable->pCheck. The pCheck field
  98795. ** normally holds CHECK constraints on an ordinary table, but for
  98796. ** a VIEW it holds the list of column names.
  98797. */
  98798. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  98799. &pTable->nCol, &pTable->aCol);
  98800. if( db->mallocFailed==0
  98801. && pParse->nErr==0
  98802. && pTable->nCol==pSel->pEList->nExpr
  98803. ){
  98804. sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
  98805. }
  98806. }else if( pSelTab ){
  98807. /* CREATE VIEW name AS... without an argument list. Construct
  98808. ** the column names from the SELECT statement that defines the view.
  98809. */
  98810. assert( pTable->aCol==0 );
  98811. pTable->nCol = pSelTab->nCol;
  98812. pTable->aCol = pSelTab->aCol;
  98813. pSelTab->nCol = 0;
  98814. pSelTab->aCol = 0;
  98815. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  98816. }else{
  98817. pTable->nCol = 0;
  98818. nErr++;
  98819. }
  98820. sqlite3DeleteTable(db, pSelTab);
  98821. sqlite3SelectDelete(db, pSel);
  98822. db->lookaside.bDisable--;
  98823. } else {
  98824. nErr++;
  98825. }
  98826. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  98827. #endif /* SQLITE_OMIT_VIEW */
  98828. return nErr;
  98829. }
  98830. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  98831. #ifndef SQLITE_OMIT_VIEW
  98832. /*
  98833. ** Clear the column names from every VIEW in database idx.
  98834. */
  98835. static void sqliteViewResetAll(sqlite3 *db, int idx){
  98836. HashElem *i;
  98837. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  98838. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  98839. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  98840. Table *pTab = sqliteHashData(i);
  98841. if( pTab->pSelect ){
  98842. sqlite3DeleteColumnNames(db, pTab);
  98843. pTab->aCol = 0;
  98844. pTab->nCol = 0;
  98845. }
  98846. }
  98847. DbClearProperty(db, idx, DB_UnresetViews);
  98848. }
  98849. #else
  98850. # define sqliteViewResetAll(A,B)
  98851. #endif /* SQLITE_OMIT_VIEW */
  98852. /*
  98853. ** This function is called by the VDBE to adjust the internal schema
  98854. ** used by SQLite when the btree layer moves a table root page. The
  98855. ** root-page of a table or index in database iDb has changed from iFrom
  98856. ** to iTo.
  98857. **
  98858. ** Ticket #1728: The symbol table might still contain information
  98859. ** on tables and/or indices that are the process of being deleted.
  98860. ** If you are unlucky, one of those deleted indices or tables might
  98861. ** have the same rootpage number as the real table or index that is
  98862. ** being moved. So we cannot stop searching after the first match
  98863. ** because the first match might be for one of the deleted indices
  98864. ** or tables and not the table/index that is actually being moved.
  98865. ** We must continue looping until all tables and indices with
  98866. ** rootpage==iFrom have been converted to have a rootpage of iTo
  98867. ** in order to be certain that we got the right one.
  98868. */
  98869. #ifndef SQLITE_OMIT_AUTOVACUUM
  98870. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  98871. HashElem *pElem;
  98872. Hash *pHash;
  98873. Db *pDb;
  98874. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98875. pDb = &db->aDb[iDb];
  98876. pHash = &pDb->pSchema->tblHash;
  98877. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  98878. Table *pTab = sqliteHashData(pElem);
  98879. if( pTab->tnum==iFrom ){
  98880. pTab->tnum = iTo;
  98881. }
  98882. }
  98883. pHash = &pDb->pSchema->idxHash;
  98884. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  98885. Index *pIdx = sqliteHashData(pElem);
  98886. if( pIdx->tnum==iFrom ){
  98887. pIdx->tnum = iTo;
  98888. }
  98889. }
  98890. }
  98891. #endif
  98892. /*
  98893. ** Write code to erase the table with root-page iTable from database iDb.
  98894. ** Also write code to modify the sqlite_master table and internal schema
  98895. ** if a root-page of another table is moved by the btree-layer whilst
  98896. ** erasing iTable (this can happen with an auto-vacuum database).
  98897. */
  98898. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  98899. Vdbe *v = sqlite3GetVdbe(pParse);
  98900. int r1 = sqlite3GetTempReg(pParse);
  98901. assert( iTable>1 );
  98902. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  98903. sqlite3MayAbort(pParse);
  98904. #ifndef SQLITE_OMIT_AUTOVACUUM
  98905. /* OP_Destroy stores an in integer r1. If this integer
  98906. ** is non-zero, then it is the root page number of a table moved to
  98907. ** location iTable. The following code modifies the sqlite_master table to
  98908. ** reflect this.
  98909. **
  98910. ** The "#NNN" in the SQL is a special constant that means whatever value
  98911. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  98912. ** token for additional information.
  98913. */
  98914. sqlite3NestedParse(pParse,
  98915. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  98916. pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
  98917. #endif
  98918. sqlite3ReleaseTempReg(pParse, r1);
  98919. }
  98920. /*
  98921. ** Write VDBE code to erase table pTab and all associated indices on disk.
  98922. ** Code to update the sqlite_master tables and internal schema definitions
  98923. ** in case a root-page belonging to another table is moved by the btree layer
  98924. ** is also added (this can happen with an auto-vacuum database).
  98925. */
  98926. static void destroyTable(Parse *pParse, Table *pTab){
  98927. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  98928. ** is not defined), then it is important to call OP_Destroy on the
  98929. ** table and index root-pages in order, starting with the numerically
  98930. ** largest root-page number. This guarantees that none of the root-pages
  98931. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  98932. ** following were coded:
  98933. **
  98934. ** OP_Destroy 4 0
  98935. ** ...
  98936. ** OP_Destroy 5 0
  98937. **
  98938. ** and root page 5 happened to be the largest root-page number in the
  98939. ** database, then root page 5 would be moved to page 4 by the
  98940. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  98941. ** a free-list page.
  98942. */
  98943. int iTab = pTab->tnum;
  98944. int iDestroyed = 0;
  98945. while( 1 ){
  98946. Index *pIdx;
  98947. int iLargest = 0;
  98948. if( iDestroyed==0 || iTab<iDestroyed ){
  98949. iLargest = iTab;
  98950. }
  98951. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  98952. int iIdx = pIdx->tnum;
  98953. assert( pIdx->pSchema==pTab->pSchema );
  98954. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  98955. iLargest = iIdx;
  98956. }
  98957. }
  98958. if( iLargest==0 ){
  98959. return;
  98960. }else{
  98961. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  98962. assert( iDb>=0 && iDb<pParse->db->nDb );
  98963. destroyRootPage(pParse, iLargest, iDb);
  98964. iDestroyed = iLargest;
  98965. }
  98966. }
  98967. }
  98968. /*
  98969. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  98970. ** after a DROP INDEX or DROP TABLE command.
  98971. */
  98972. static void sqlite3ClearStatTables(
  98973. Parse *pParse, /* The parsing context */
  98974. int iDb, /* The database number */
  98975. const char *zType, /* "idx" or "tbl" */
  98976. const char *zName /* Name of index or table */
  98977. ){
  98978. int i;
  98979. const char *zDbName = pParse->db->aDb[iDb].zDbSName;
  98980. for(i=1; i<=4; i++){
  98981. char zTab[24];
  98982. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  98983. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  98984. sqlite3NestedParse(pParse,
  98985. "DELETE FROM %Q.%s WHERE %s=%Q",
  98986. zDbName, zTab, zType, zName
  98987. );
  98988. }
  98989. }
  98990. }
  98991. /*
  98992. ** Generate code to drop a table.
  98993. */
  98994. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  98995. Vdbe *v;
  98996. sqlite3 *db = pParse->db;
  98997. Trigger *pTrigger;
  98998. Db *pDb = &db->aDb[iDb];
  98999. v = sqlite3GetVdbe(pParse);
  99000. assert( v!=0 );
  99001. sqlite3BeginWriteOperation(pParse, 1, iDb);
  99002. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99003. if( IsVirtual(pTab) ){
  99004. sqlite3VdbeAddOp0(v, OP_VBegin);
  99005. }
  99006. #endif
  99007. /* Drop all triggers associated with the table being dropped. Code
  99008. ** is generated to remove entries from sqlite_master and/or
  99009. ** sqlite_temp_master if required.
  99010. */
  99011. pTrigger = sqlite3TriggerList(pParse, pTab);
  99012. while( pTrigger ){
  99013. assert( pTrigger->pSchema==pTab->pSchema ||
  99014. pTrigger->pSchema==db->aDb[1].pSchema );
  99015. sqlite3DropTriggerPtr(pParse, pTrigger);
  99016. pTrigger = pTrigger->pNext;
  99017. }
  99018. #ifndef SQLITE_OMIT_AUTOINCREMENT
  99019. /* Remove any entries of the sqlite_sequence table associated with
  99020. ** the table being dropped. This is done before the table is dropped
  99021. ** at the btree level, in case the sqlite_sequence table needs to
  99022. ** move as a result of the drop (can happen in auto-vacuum mode).
  99023. */
  99024. if( pTab->tabFlags & TF_Autoincrement ){
  99025. sqlite3NestedParse(pParse,
  99026. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  99027. pDb->zDbSName, pTab->zName
  99028. );
  99029. }
  99030. #endif
  99031. /* Drop all SQLITE_MASTER table and index entries that refer to the
  99032. ** table. The program name loops through the master table and deletes
  99033. ** every row that refers to a table of the same name as the one being
  99034. ** dropped. Triggers are handled separately because a trigger can be
  99035. ** created in the temp database that refers to a table in another
  99036. ** database.
  99037. */
  99038. sqlite3NestedParse(pParse,
  99039. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  99040. pDb->zDbSName, MASTER_NAME, pTab->zName);
  99041. if( !isView && !IsVirtual(pTab) ){
  99042. destroyTable(pParse, pTab);
  99043. }
  99044. /* Remove the table entry from SQLite's internal schema and modify
  99045. ** the schema cookie.
  99046. */
  99047. if( IsVirtual(pTab) ){
  99048. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  99049. }
  99050. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  99051. sqlite3ChangeCookie(pParse, iDb);
  99052. sqliteViewResetAll(db, iDb);
  99053. }
  99054. /*
  99055. ** This routine is called to do the work of a DROP TABLE statement.
  99056. ** pName is the name of the table to be dropped.
  99057. */
  99058. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  99059. Table *pTab;
  99060. Vdbe *v;
  99061. sqlite3 *db = pParse->db;
  99062. int iDb;
  99063. if( db->mallocFailed ){
  99064. goto exit_drop_table;
  99065. }
  99066. assert( pParse->nErr==0 );
  99067. assert( pName->nSrc==1 );
  99068. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  99069. if( noErr ) db->suppressErr++;
  99070. assert( isView==0 || isView==LOCATE_VIEW );
  99071. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  99072. if( noErr ) db->suppressErr--;
  99073. if( pTab==0 ){
  99074. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  99075. goto exit_drop_table;
  99076. }
  99077. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  99078. assert( iDb>=0 && iDb<db->nDb );
  99079. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  99080. ** it is initialized.
  99081. */
  99082. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  99083. goto exit_drop_table;
  99084. }
  99085. #ifndef SQLITE_OMIT_AUTHORIZATION
  99086. {
  99087. int code;
  99088. const char *zTab = SCHEMA_TABLE(iDb);
  99089. const char *zDb = db->aDb[iDb].zDbSName;
  99090. const char *zArg2 = 0;
  99091. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  99092. goto exit_drop_table;
  99093. }
  99094. if( isView ){
  99095. if( !OMIT_TEMPDB && iDb==1 ){
  99096. code = SQLITE_DROP_TEMP_VIEW;
  99097. }else{
  99098. code = SQLITE_DROP_VIEW;
  99099. }
  99100. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99101. }else if( IsVirtual(pTab) ){
  99102. code = SQLITE_DROP_VTABLE;
  99103. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  99104. #endif
  99105. }else{
  99106. if( !OMIT_TEMPDB && iDb==1 ){
  99107. code = SQLITE_DROP_TEMP_TABLE;
  99108. }else{
  99109. code = SQLITE_DROP_TABLE;
  99110. }
  99111. }
  99112. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  99113. goto exit_drop_table;
  99114. }
  99115. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  99116. goto exit_drop_table;
  99117. }
  99118. }
  99119. #endif
  99120. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  99121. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  99122. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  99123. goto exit_drop_table;
  99124. }
  99125. #ifndef SQLITE_OMIT_VIEW
  99126. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  99127. ** on a table.
  99128. */
  99129. if( isView && pTab->pSelect==0 ){
  99130. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  99131. goto exit_drop_table;
  99132. }
  99133. if( !isView && pTab->pSelect ){
  99134. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  99135. goto exit_drop_table;
  99136. }
  99137. #endif
  99138. /* Generate code to remove the table from the master table
  99139. ** on disk.
  99140. */
  99141. v = sqlite3GetVdbe(pParse);
  99142. if( v ){
  99143. sqlite3BeginWriteOperation(pParse, 1, iDb);
  99144. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  99145. sqlite3FkDropTable(pParse, pName, pTab);
  99146. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  99147. }
  99148. exit_drop_table:
  99149. sqlite3SrcListDelete(db, pName);
  99150. }
  99151. /*
  99152. ** This routine is called to create a new foreign key on the table
  99153. ** currently under construction. pFromCol determines which columns
  99154. ** in the current table point to the foreign key. If pFromCol==0 then
  99155. ** connect the key to the last column inserted. pTo is the name of
  99156. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  99157. ** of tables in the parent pTo table. flags contains all
  99158. ** information about the conflict resolution algorithms specified
  99159. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  99160. **
  99161. ** An FKey structure is created and added to the table currently
  99162. ** under construction in the pParse->pNewTable field.
  99163. **
  99164. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  99165. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  99166. */
  99167. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  99168. Parse *pParse, /* Parsing context */
  99169. ExprList *pFromCol, /* Columns in this table that point to other table */
  99170. Token *pTo, /* Name of the other table */
  99171. ExprList *pToCol, /* Columns in the other table */
  99172. int flags /* Conflict resolution algorithms. */
  99173. ){
  99174. sqlite3 *db = pParse->db;
  99175. #ifndef SQLITE_OMIT_FOREIGN_KEY
  99176. FKey *pFKey = 0;
  99177. FKey *pNextTo;
  99178. Table *p = pParse->pNewTable;
  99179. int nByte;
  99180. int i;
  99181. int nCol;
  99182. char *z;
  99183. assert( pTo!=0 );
  99184. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  99185. if( pFromCol==0 ){
  99186. int iCol = p->nCol-1;
  99187. if( NEVER(iCol<0) ) goto fk_end;
  99188. if( pToCol && pToCol->nExpr!=1 ){
  99189. sqlite3ErrorMsg(pParse, "foreign key on %s"
  99190. " should reference only one column of table %T",
  99191. p->aCol[iCol].zName, pTo);
  99192. goto fk_end;
  99193. }
  99194. nCol = 1;
  99195. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  99196. sqlite3ErrorMsg(pParse,
  99197. "number of columns in foreign key does not match the number of "
  99198. "columns in the referenced table");
  99199. goto fk_end;
  99200. }else{
  99201. nCol = pFromCol->nExpr;
  99202. }
  99203. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  99204. if( pToCol ){
  99205. for(i=0; i<pToCol->nExpr; i++){
  99206. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  99207. }
  99208. }
  99209. pFKey = sqlite3DbMallocZero(db, nByte );
  99210. if( pFKey==0 ){
  99211. goto fk_end;
  99212. }
  99213. pFKey->pFrom = p;
  99214. pFKey->pNextFrom = p->pFKey;
  99215. z = (char*)&pFKey->aCol[nCol];
  99216. pFKey->zTo = z;
  99217. memcpy(z, pTo->z, pTo->n);
  99218. z[pTo->n] = 0;
  99219. sqlite3Dequote(z);
  99220. z += pTo->n+1;
  99221. pFKey->nCol = nCol;
  99222. if( pFromCol==0 ){
  99223. pFKey->aCol[0].iFrom = p->nCol-1;
  99224. }else{
  99225. for(i=0; i<nCol; i++){
  99226. int j;
  99227. for(j=0; j<p->nCol; j++){
  99228. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  99229. pFKey->aCol[i].iFrom = j;
  99230. break;
  99231. }
  99232. }
  99233. if( j>=p->nCol ){
  99234. sqlite3ErrorMsg(pParse,
  99235. "unknown column \"%s\" in foreign key definition",
  99236. pFromCol->a[i].zName);
  99237. goto fk_end;
  99238. }
  99239. }
  99240. }
  99241. if( pToCol ){
  99242. for(i=0; i<nCol; i++){
  99243. int n = sqlite3Strlen30(pToCol->a[i].zName);
  99244. pFKey->aCol[i].zCol = z;
  99245. memcpy(z, pToCol->a[i].zName, n);
  99246. z[n] = 0;
  99247. z += n+1;
  99248. }
  99249. }
  99250. pFKey->isDeferred = 0;
  99251. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  99252. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  99253. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  99254. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  99255. pFKey->zTo, (void *)pFKey
  99256. );
  99257. if( pNextTo==pFKey ){
  99258. sqlite3OomFault(db);
  99259. goto fk_end;
  99260. }
  99261. if( pNextTo ){
  99262. assert( pNextTo->pPrevTo==0 );
  99263. pFKey->pNextTo = pNextTo;
  99264. pNextTo->pPrevTo = pFKey;
  99265. }
  99266. /* Link the foreign key to the table as the last step.
  99267. */
  99268. p->pFKey = pFKey;
  99269. pFKey = 0;
  99270. fk_end:
  99271. sqlite3DbFree(db, pFKey);
  99272. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  99273. sqlite3ExprListDelete(db, pFromCol);
  99274. sqlite3ExprListDelete(db, pToCol);
  99275. }
  99276. /*
  99277. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  99278. ** clause is seen as part of a foreign key definition. The isDeferred
  99279. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  99280. ** The behavior of the most recently created foreign key is adjusted
  99281. ** accordingly.
  99282. */
  99283. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  99284. #ifndef SQLITE_OMIT_FOREIGN_KEY
  99285. Table *pTab;
  99286. FKey *pFKey;
  99287. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  99288. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  99289. pFKey->isDeferred = (u8)isDeferred;
  99290. #endif
  99291. }
  99292. /*
  99293. ** Generate code that will erase and refill index *pIdx. This is
  99294. ** used to initialize a newly created index or to recompute the
  99295. ** content of an index in response to a REINDEX command.
  99296. **
  99297. ** if memRootPage is not negative, it means that the index is newly
  99298. ** created. The register specified by memRootPage contains the
  99299. ** root page number of the index. If memRootPage is negative, then
  99300. ** the index already exists and must be cleared before being refilled and
  99301. ** the root page number of the index is taken from pIndex->tnum.
  99302. */
  99303. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  99304. Table *pTab = pIndex->pTable; /* The table that is indexed */
  99305. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  99306. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  99307. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  99308. int addr1; /* Address of top of loop */
  99309. int addr2; /* Address to jump to for next iteration */
  99310. int tnum; /* Root page of index */
  99311. int iPartIdxLabel; /* Jump to this label to skip a row */
  99312. Vdbe *v; /* Generate code into this virtual machine */
  99313. KeyInfo *pKey; /* KeyInfo for index */
  99314. int regRecord; /* Register holding assembled index record */
  99315. sqlite3 *db = pParse->db; /* The database connection */
  99316. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  99317. #ifndef SQLITE_OMIT_AUTHORIZATION
  99318. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  99319. db->aDb[iDb].zDbSName ) ){
  99320. return;
  99321. }
  99322. #endif
  99323. /* Require a write-lock on the table to perform this operation */
  99324. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  99325. v = sqlite3GetVdbe(pParse);
  99326. if( v==0 ) return;
  99327. if( memRootPage>=0 ){
  99328. tnum = memRootPage;
  99329. }else{
  99330. tnum = pIndex->tnum;
  99331. }
  99332. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  99333. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  99334. /* Open the sorter cursor if we are to use one. */
  99335. iSorter = pParse->nTab++;
  99336. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  99337. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  99338. /* Open the table. Loop through all rows of the table, inserting index
  99339. ** records into the sorter. */
  99340. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  99341. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  99342. regRecord = sqlite3GetTempReg(pParse);
  99343. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  99344. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  99345. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  99346. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  99347. sqlite3VdbeJumpHere(v, addr1);
  99348. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  99349. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  99350. (char *)pKey, P4_KEYINFO);
  99351. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  99352. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  99353. if( IsUniqueIndex(pIndex) ){
  99354. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  99355. sqlite3VdbeGoto(v, j2);
  99356. addr2 = sqlite3VdbeCurrentAddr(v);
  99357. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  99358. pIndex->nKeyCol); VdbeCoverage(v);
  99359. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  99360. }else{
  99361. addr2 = sqlite3VdbeCurrentAddr(v);
  99362. }
  99363. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  99364. sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
  99365. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  99366. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  99367. sqlite3ReleaseTempReg(pParse, regRecord);
  99368. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  99369. sqlite3VdbeJumpHere(v, addr1);
  99370. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  99371. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  99372. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  99373. }
  99374. /*
  99375. ** Allocate heap space to hold an Index object with nCol columns.
  99376. **
  99377. ** Increase the allocation size to provide an extra nExtra bytes
  99378. ** of 8-byte aligned space after the Index object and return a
  99379. ** pointer to this extra space in *ppExtra.
  99380. */
  99381. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  99382. sqlite3 *db, /* Database connection */
  99383. i16 nCol, /* Total number of columns in the index */
  99384. int nExtra, /* Number of bytes of extra space to alloc */
  99385. char **ppExtra /* Pointer to the "extra" space */
  99386. ){
  99387. Index *p; /* Allocated index object */
  99388. int nByte; /* Bytes of space for Index object + arrays */
  99389. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  99390. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  99391. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  99392. sizeof(i16)*nCol + /* Index.aiColumn */
  99393. sizeof(u8)*nCol); /* Index.aSortOrder */
  99394. p = sqlite3DbMallocZero(db, nByte + nExtra);
  99395. if( p ){
  99396. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  99397. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  99398. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  99399. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  99400. p->aSortOrder = (u8*)pExtra;
  99401. p->nColumn = nCol;
  99402. p->nKeyCol = nCol - 1;
  99403. *ppExtra = ((char*)p) + nByte;
  99404. }
  99405. return p;
  99406. }
  99407. /*
  99408. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  99409. ** and pTblList is the name of the table that is to be indexed. Both will
  99410. ** be NULL for a primary key or an index that is created to satisfy a
  99411. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  99412. ** as the table to be indexed. pParse->pNewTable is a table that is
  99413. ** currently being constructed by a CREATE TABLE statement.
  99414. **
  99415. ** pList is a list of columns to be indexed. pList will be NULL if this
  99416. ** is a primary key or unique-constraint on the most recent column added
  99417. ** to the table currently under construction.
  99418. */
  99419. SQLITE_PRIVATE void sqlite3CreateIndex(
  99420. Parse *pParse, /* All information about this parse */
  99421. Token *pName1, /* First part of index name. May be NULL */
  99422. Token *pName2, /* Second part of index name. May be NULL */
  99423. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  99424. ExprList *pList, /* A list of columns to be indexed */
  99425. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  99426. Token *pStart, /* The CREATE token that begins this statement */
  99427. Expr *pPIWhere, /* WHERE clause for partial indices */
  99428. int sortOrder, /* Sort order of primary key when pList==NULL */
  99429. int ifNotExist, /* Omit error if index already exists */
  99430. u8 idxType /* The index type */
  99431. ){
  99432. Table *pTab = 0; /* Table to be indexed */
  99433. Index *pIndex = 0; /* The index to be created */
  99434. char *zName = 0; /* Name of the index */
  99435. int nName; /* Number of characters in zName */
  99436. int i, j;
  99437. DbFixer sFix; /* For assigning database names to pTable */
  99438. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  99439. sqlite3 *db = pParse->db;
  99440. Db *pDb; /* The specific table containing the indexed database */
  99441. int iDb; /* Index of the database that is being written */
  99442. Token *pName = 0; /* Unqualified name of the index to create */
  99443. struct ExprList_item *pListItem; /* For looping over pList */
  99444. int nExtra = 0; /* Space allocated for zExtra[] */
  99445. int nExtraCol; /* Number of extra columns needed */
  99446. char *zExtra = 0; /* Extra space after the Index object */
  99447. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  99448. if( db->mallocFailed || pParse->nErr>0 ){
  99449. goto exit_create_index;
  99450. }
  99451. if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
  99452. goto exit_create_index;
  99453. }
  99454. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  99455. goto exit_create_index;
  99456. }
  99457. /*
  99458. ** Find the table that is to be indexed. Return early if not found.
  99459. */
  99460. if( pTblName!=0 ){
  99461. /* Use the two-part index name to determine the database
  99462. ** to search for the table. 'Fix' the table name to this db
  99463. ** before looking up the table.
  99464. */
  99465. assert( pName1 && pName2 );
  99466. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  99467. if( iDb<0 ) goto exit_create_index;
  99468. assert( pName && pName->z );
  99469. #ifndef SQLITE_OMIT_TEMPDB
  99470. /* If the index name was unqualified, check if the table
  99471. ** is a temp table. If so, set the database to 1. Do not do this
  99472. ** if initialising a database schema.
  99473. */
  99474. if( !db->init.busy ){
  99475. pTab = sqlite3SrcListLookup(pParse, pTblName);
  99476. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  99477. iDb = 1;
  99478. }
  99479. }
  99480. #endif
  99481. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  99482. if( sqlite3FixSrcList(&sFix, pTblName) ){
  99483. /* Because the parser constructs pTblName from a single identifier,
  99484. ** sqlite3FixSrcList can never fail. */
  99485. assert(0);
  99486. }
  99487. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  99488. assert( db->mallocFailed==0 || pTab==0 );
  99489. if( pTab==0 ) goto exit_create_index;
  99490. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  99491. sqlite3ErrorMsg(pParse,
  99492. "cannot create a TEMP index on non-TEMP table \"%s\"",
  99493. pTab->zName);
  99494. goto exit_create_index;
  99495. }
  99496. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  99497. }else{
  99498. assert( pName==0 );
  99499. assert( pStart==0 );
  99500. pTab = pParse->pNewTable;
  99501. if( !pTab ) goto exit_create_index;
  99502. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  99503. }
  99504. pDb = &db->aDb[iDb];
  99505. assert( pTab!=0 );
  99506. assert( pParse->nErr==0 );
  99507. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  99508. && db->init.busy==0
  99509. #if SQLITE_USER_AUTHENTICATION
  99510. && sqlite3UserAuthTable(pTab->zName)==0
  99511. #endif
  99512. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  99513. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  99514. goto exit_create_index;
  99515. }
  99516. #ifndef SQLITE_OMIT_VIEW
  99517. if( pTab->pSelect ){
  99518. sqlite3ErrorMsg(pParse, "views may not be indexed");
  99519. goto exit_create_index;
  99520. }
  99521. #endif
  99522. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99523. if( IsVirtual(pTab) ){
  99524. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  99525. goto exit_create_index;
  99526. }
  99527. #endif
  99528. /*
  99529. ** Find the name of the index. Make sure there is not already another
  99530. ** index or table with the same name.
  99531. **
  99532. ** Exception: If we are reading the names of permanent indices from the
  99533. ** sqlite_master table (because some other process changed the schema) and
  99534. ** one of the index names collides with the name of a temporary table or
  99535. ** index, then we will continue to process this index.
  99536. **
  99537. ** If pName==0 it means that we are
  99538. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  99539. ** own name.
  99540. */
  99541. if( pName ){
  99542. zName = sqlite3NameFromToken(db, pName);
  99543. if( zName==0 ) goto exit_create_index;
  99544. assert( pName->z!=0 );
  99545. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  99546. goto exit_create_index;
  99547. }
  99548. if( !db->init.busy ){
  99549. if( sqlite3FindTable(db, zName, 0)!=0 ){
  99550. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  99551. goto exit_create_index;
  99552. }
  99553. }
  99554. if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
  99555. if( !ifNotExist ){
  99556. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  99557. }else{
  99558. assert( !db->init.busy );
  99559. sqlite3CodeVerifySchema(pParse, iDb);
  99560. }
  99561. goto exit_create_index;
  99562. }
  99563. }else{
  99564. int n;
  99565. Index *pLoop;
  99566. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  99567. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  99568. if( zName==0 ){
  99569. goto exit_create_index;
  99570. }
  99571. /* Automatic index names generated from within sqlite3_declare_vtab()
  99572. ** must have names that are distinct from normal automatic index names.
  99573. ** The following statement converts "sqlite3_autoindex..." into
  99574. ** "sqlite3_butoindex..." in order to make the names distinct.
  99575. ** The "vtab_err.test" test demonstrates the need of this statement. */
  99576. if( IN_DECLARE_VTAB ) zName[7]++;
  99577. }
  99578. /* Check for authorization to create an index.
  99579. */
  99580. #ifndef SQLITE_OMIT_AUTHORIZATION
  99581. {
  99582. const char *zDb = pDb->zDbSName;
  99583. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  99584. goto exit_create_index;
  99585. }
  99586. i = SQLITE_CREATE_INDEX;
  99587. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  99588. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  99589. goto exit_create_index;
  99590. }
  99591. }
  99592. #endif
  99593. /* If pList==0, it means this routine was called to make a primary
  99594. ** key out of the last column added to the table under construction.
  99595. ** So create a fake list to simulate this.
  99596. */
  99597. if( pList==0 ){
  99598. Token prevCol;
  99599. Column *pCol = &pTab->aCol[pTab->nCol-1];
  99600. pCol->colFlags |= COLFLAG_UNIQUE;
  99601. sqlite3TokenInit(&prevCol, pCol->zName);
  99602. pList = sqlite3ExprListAppend(pParse, 0,
  99603. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  99604. if( pList==0 ) goto exit_create_index;
  99605. assert( pList->nExpr==1 );
  99606. sqlite3ExprListSetSortOrder(pList, sortOrder);
  99607. }else{
  99608. sqlite3ExprListCheckLength(pParse, pList, "index");
  99609. }
  99610. /* Figure out how many bytes of space are required to store explicitly
  99611. ** specified collation sequence names.
  99612. */
  99613. for(i=0; i<pList->nExpr; i++){
  99614. Expr *pExpr = pList->a[i].pExpr;
  99615. assert( pExpr!=0 );
  99616. if( pExpr->op==TK_COLLATE ){
  99617. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  99618. }
  99619. }
  99620. /*
  99621. ** Allocate the index structure.
  99622. */
  99623. nName = sqlite3Strlen30(zName);
  99624. nExtraCol = pPk ? pPk->nKeyCol : 1;
  99625. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  99626. nName + nExtra + 1, &zExtra);
  99627. if( db->mallocFailed ){
  99628. goto exit_create_index;
  99629. }
  99630. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  99631. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  99632. pIndex->zName = zExtra;
  99633. zExtra += nName + 1;
  99634. memcpy(pIndex->zName, zName, nName+1);
  99635. pIndex->pTable = pTab;
  99636. pIndex->onError = (u8)onError;
  99637. pIndex->uniqNotNull = onError!=OE_None;
  99638. pIndex->idxType = idxType;
  99639. pIndex->pSchema = db->aDb[iDb].pSchema;
  99640. pIndex->nKeyCol = pList->nExpr;
  99641. if( pPIWhere ){
  99642. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  99643. pIndex->pPartIdxWhere = pPIWhere;
  99644. pPIWhere = 0;
  99645. }
  99646. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99647. /* Check to see if we should honor DESC requests on index columns
  99648. */
  99649. if( pDb->pSchema->file_format>=4 ){
  99650. sortOrderMask = -1; /* Honor DESC */
  99651. }else{
  99652. sortOrderMask = 0; /* Ignore DESC */
  99653. }
  99654. /* Analyze the list of expressions that form the terms of the index and
  99655. ** report any errors. In the common case where the expression is exactly
  99656. ** a table column, store that column in aiColumn[]. For general expressions,
  99657. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  99658. **
  99659. ** TODO: Issue a warning if two or more columns of the index are identical.
  99660. ** TODO: Issue a warning if the table primary key is used as part of the
  99661. ** index key.
  99662. */
  99663. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  99664. Expr *pCExpr; /* The i-th index expression */
  99665. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  99666. const char *zColl; /* Collation sequence name */
  99667. sqlite3StringToId(pListItem->pExpr);
  99668. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  99669. if( pParse->nErr ) goto exit_create_index;
  99670. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  99671. if( pCExpr->op!=TK_COLUMN ){
  99672. if( pTab==pParse->pNewTable ){
  99673. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  99674. "UNIQUE constraints");
  99675. goto exit_create_index;
  99676. }
  99677. if( pIndex->aColExpr==0 ){
  99678. ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
  99679. pIndex->aColExpr = pCopy;
  99680. if( !db->mallocFailed ){
  99681. assert( pCopy!=0 );
  99682. pListItem = &pCopy->a[i];
  99683. }
  99684. }
  99685. j = XN_EXPR;
  99686. pIndex->aiColumn[i] = XN_EXPR;
  99687. pIndex->uniqNotNull = 0;
  99688. }else{
  99689. j = pCExpr->iColumn;
  99690. assert( j<=0x7fff );
  99691. if( j<0 ){
  99692. j = pTab->iPKey;
  99693. }else if( pTab->aCol[j].notNull==0 ){
  99694. pIndex->uniqNotNull = 0;
  99695. }
  99696. pIndex->aiColumn[i] = (i16)j;
  99697. }
  99698. zColl = 0;
  99699. if( pListItem->pExpr->op==TK_COLLATE ){
  99700. int nColl;
  99701. zColl = pListItem->pExpr->u.zToken;
  99702. nColl = sqlite3Strlen30(zColl) + 1;
  99703. assert( nExtra>=nColl );
  99704. memcpy(zExtra, zColl, nColl);
  99705. zColl = zExtra;
  99706. zExtra += nColl;
  99707. nExtra -= nColl;
  99708. }else if( j>=0 ){
  99709. zColl = pTab->aCol[j].zColl;
  99710. }
  99711. if( !zColl ) zColl = sqlite3StrBINARY;
  99712. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  99713. goto exit_create_index;
  99714. }
  99715. pIndex->azColl[i] = zColl;
  99716. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  99717. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  99718. }
  99719. /* Append the table key to the end of the index. For WITHOUT ROWID
  99720. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  99721. ** normal tables (when pPk==0) this will be the rowid.
  99722. */
  99723. if( pPk ){
  99724. for(j=0; j<pPk->nKeyCol; j++){
  99725. int x = pPk->aiColumn[j];
  99726. assert( x>=0 );
  99727. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  99728. pIndex->nColumn--;
  99729. }else{
  99730. pIndex->aiColumn[i] = x;
  99731. pIndex->azColl[i] = pPk->azColl[j];
  99732. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  99733. i++;
  99734. }
  99735. }
  99736. assert( i==pIndex->nColumn );
  99737. }else{
  99738. pIndex->aiColumn[i] = XN_ROWID;
  99739. pIndex->azColl[i] = sqlite3StrBINARY;
  99740. }
  99741. sqlite3DefaultRowEst(pIndex);
  99742. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  99743. /* If this index contains every column of its table, then mark
  99744. ** it as a covering index */
  99745. assert( HasRowid(pTab)
  99746. || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
  99747. if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
  99748. pIndex->isCovering = 1;
  99749. for(j=0; j<pTab->nCol; j++){
  99750. if( j==pTab->iPKey ) continue;
  99751. if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
  99752. pIndex->isCovering = 0;
  99753. break;
  99754. }
  99755. }
  99756. if( pTab==pParse->pNewTable ){
  99757. /* This routine has been called to create an automatic index as a
  99758. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  99759. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  99760. ** i.e. one of:
  99761. **
  99762. ** CREATE TABLE t(x PRIMARY KEY, y);
  99763. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  99764. **
  99765. ** Either way, check to see if the table already has such an index. If
  99766. ** so, don't bother creating this one. This only applies to
  99767. ** automatically created indices. Users can do as they wish with
  99768. ** explicit indices.
  99769. **
  99770. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  99771. ** (and thus suppressing the second one) even if they have different
  99772. ** sort orders.
  99773. **
  99774. ** If there are different collating sequences or if the columns of
  99775. ** the constraint occur in different orders, then the constraints are
  99776. ** considered distinct and both result in separate indices.
  99777. */
  99778. Index *pIdx;
  99779. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  99780. int k;
  99781. assert( IsUniqueIndex(pIdx) );
  99782. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  99783. assert( IsUniqueIndex(pIndex) );
  99784. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  99785. for(k=0; k<pIdx->nKeyCol; k++){
  99786. const char *z1;
  99787. const char *z2;
  99788. assert( pIdx->aiColumn[k]>=0 );
  99789. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  99790. z1 = pIdx->azColl[k];
  99791. z2 = pIndex->azColl[k];
  99792. if( sqlite3StrICmp(z1, z2) ) break;
  99793. }
  99794. if( k==pIdx->nKeyCol ){
  99795. if( pIdx->onError!=pIndex->onError ){
  99796. /* This constraint creates the same index as a previous
  99797. ** constraint specified somewhere in the CREATE TABLE statement.
  99798. ** However the ON CONFLICT clauses are different. If both this
  99799. ** constraint and the previous equivalent constraint have explicit
  99800. ** ON CONFLICT clauses this is an error. Otherwise, use the
  99801. ** explicitly specified behavior for the index.
  99802. */
  99803. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  99804. sqlite3ErrorMsg(pParse,
  99805. "conflicting ON CONFLICT clauses specified", 0);
  99806. }
  99807. if( pIdx->onError==OE_Default ){
  99808. pIdx->onError = pIndex->onError;
  99809. }
  99810. }
  99811. if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
  99812. goto exit_create_index;
  99813. }
  99814. }
  99815. }
  99816. /* Link the new Index structure to its table and to the other
  99817. ** in-memory database structures.
  99818. */
  99819. assert( pParse->nErr==0 );
  99820. if( db->init.busy ){
  99821. Index *p;
  99822. assert( !IN_DECLARE_VTAB );
  99823. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  99824. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  99825. pIndex->zName, pIndex);
  99826. if( p ){
  99827. assert( p==pIndex ); /* Malloc must have failed */
  99828. sqlite3OomFault(db);
  99829. goto exit_create_index;
  99830. }
  99831. db->mDbFlags |= DBFLAG_SchemaChange;
  99832. if( pTblName!=0 ){
  99833. pIndex->tnum = db->init.newTnum;
  99834. }
  99835. }
  99836. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  99837. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  99838. ** emit code to allocate the index rootpage on disk and make an entry for
  99839. ** the index in the sqlite_master table and populate the index with
  99840. ** content. But, do not do this if we are simply reading the sqlite_master
  99841. ** table to parse the schema, or if this index is the PRIMARY KEY index
  99842. ** of a WITHOUT ROWID table.
  99843. **
  99844. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  99845. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  99846. ** has just been created, it contains no data and the index initialization
  99847. ** step can be skipped.
  99848. */
  99849. else if( HasRowid(pTab) || pTblName!=0 ){
  99850. Vdbe *v;
  99851. char *zStmt;
  99852. int iMem = ++pParse->nMem;
  99853. v = sqlite3GetVdbe(pParse);
  99854. if( v==0 ) goto exit_create_index;
  99855. sqlite3BeginWriteOperation(pParse, 1, iDb);
  99856. /* Create the rootpage for the index using CreateIndex. But before
  99857. ** doing so, code a Noop instruction and store its address in
  99858. ** Index.tnum. This is required in case this index is actually a
  99859. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  99860. ** that case the convertToWithoutRowidTable() routine will replace
  99861. ** the Noop with a Goto to jump over the VDBE code generated below. */
  99862. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  99863. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
  99864. /* Gather the complete text of the CREATE INDEX statement into
  99865. ** the zStmt variable
  99866. */
  99867. if( pStart ){
  99868. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  99869. if( pName->z[n-1]==';' ) n--;
  99870. /* A named index with an explicit CREATE INDEX statement */
  99871. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  99872. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  99873. }else{
  99874. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  99875. /* zStmt = sqlite3MPrintf(""); */
  99876. zStmt = 0;
  99877. }
  99878. /* Add an entry in sqlite_master for this index
  99879. */
  99880. sqlite3NestedParse(pParse,
  99881. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  99882. db->aDb[iDb].zDbSName, MASTER_NAME,
  99883. pIndex->zName,
  99884. pTab->zName,
  99885. iMem,
  99886. zStmt
  99887. );
  99888. sqlite3DbFree(db, zStmt);
  99889. /* Fill the index with data and reparse the schema. Code an OP_Expire
  99890. ** to invalidate all pre-compiled statements.
  99891. */
  99892. if( pTblName ){
  99893. sqlite3RefillIndex(pParse, pIndex, iMem);
  99894. sqlite3ChangeCookie(pParse, iDb);
  99895. sqlite3VdbeAddParseSchemaOp(v, iDb,
  99896. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  99897. sqlite3VdbeAddOp0(v, OP_Expire);
  99898. }
  99899. sqlite3VdbeJumpHere(v, pIndex->tnum);
  99900. }
  99901. /* When adding an index to the list of indices for a table, make
  99902. ** sure all indices labeled OE_Replace come after all those labeled
  99903. ** OE_Ignore. This is necessary for the correct constraint check
  99904. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  99905. ** UPDATE and INSERT statements.
  99906. */
  99907. if( db->init.busy || pTblName==0 ){
  99908. if( onError!=OE_Replace || pTab->pIndex==0
  99909. || pTab->pIndex->onError==OE_Replace){
  99910. pIndex->pNext = pTab->pIndex;
  99911. pTab->pIndex = pIndex;
  99912. }else{
  99913. Index *pOther = pTab->pIndex;
  99914. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  99915. pOther = pOther->pNext;
  99916. }
  99917. pIndex->pNext = pOther->pNext;
  99918. pOther->pNext = pIndex;
  99919. }
  99920. pIndex = 0;
  99921. }
  99922. /* Clean up before exiting */
  99923. exit_create_index:
  99924. if( pIndex ) freeIndex(db, pIndex);
  99925. sqlite3ExprDelete(db, pPIWhere);
  99926. sqlite3ExprListDelete(db, pList);
  99927. sqlite3SrcListDelete(db, pTblName);
  99928. sqlite3DbFree(db, zName);
  99929. }
  99930. /*
  99931. ** Fill the Index.aiRowEst[] array with default information - information
  99932. ** to be used when we have not run the ANALYZE command.
  99933. **
  99934. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  99935. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  99936. ** number of rows in the table that match any particular value of the
  99937. ** first column of the index. aiRowEst[2] is an estimate of the number
  99938. ** of rows that match any particular combination of the first 2 columns
  99939. ** of the index. And so forth. It must always be the case that
  99940. *
  99941. ** aiRowEst[N]<=aiRowEst[N-1]
  99942. ** aiRowEst[N]>=1
  99943. **
  99944. ** Apart from that, we have little to go on besides intuition as to
  99945. ** how aiRowEst[] should be initialized. The numbers generated here
  99946. ** are based on typical values found in actual indices.
  99947. */
  99948. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  99949. /* 10, 9, 8, 7, 6 */
  99950. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  99951. LogEst *a = pIdx->aiRowLogEst;
  99952. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  99953. int i;
  99954. /* Indexes with default row estimates should not have stat1 data */
  99955. assert( !pIdx->hasStat1 );
  99956. /* Set the first entry (number of rows in the index) to the estimated
  99957. ** number of rows in the table, or half the number of rows in the table
  99958. ** for a partial index. But do not let the estimate drop below 10. */
  99959. a[0] = pIdx->pTable->nRowLogEst;
  99960. if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
  99961. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  99962. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  99963. ** 6 and each subsequent value (if any) is 5. */
  99964. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  99965. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  99966. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  99967. }
  99968. assert( 0==sqlite3LogEst(1) );
  99969. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  99970. }
  99971. /*
  99972. ** This routine will drop an existing named index. This routine
  99973. ** implements the DROP INDEX statement.
  99974. */
  99975. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  99976. Index *pIndex;
  99977. Vdbe *v;
  99978. sqlite3 *db = pParse->db;
  99979. int iDb;
  99980. assert( pParse->nErr==0 ); /* Never called with prior errors */
  99981. if( db->mallocFailed ){
  99982. goto exit_drop_index;
  99983. }
  99984. assert( pName->nSrc==1 );
  99985. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  99986. goto exit_drop_index;
  99987. }
  99988. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  99989. if( pIndex==0 ){
  99990. if( !ifExists ){
  99991. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  99992. }else{
  99993. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  99994. }
  99995. pParse->checkSchema = 1;
  99996. goto exit_drop_index;
  99997. }
  99998. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  99999. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  100000. "or PRIMARY KEY constraint cannot be dropped", 0);
  100001. goto exit_drop_index;
  100002. }
  100003. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  100004. #ifndef SQLITE_OMIT_AUTHORIZATION
  100005. {
  100006. int code = SQLITE_DROP_INDEX;
  100007. Table *pTab = pIndex->pTable;
  100008. const char *zDb = db->aDb[iDb].zDbSName;
  100009. const char *zTab = SCHEMA_TABLE(iDb);
  100010. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  100011. goto exit_drop_index;
  100012. }
  100013. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  100014. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  100015. goto exit_drop_index;
  100016. }
  100017. }
  100018. #endif
  100019. /* Generate code to remove the index and from the master table */
  100020. v = sqlite3GetVdbe(pParse);
  100021. if( v ){
  100022. sqlite3BeginWriteOperation(pParse, 1, iDb);
  100023. sqlite3NestedParse(pParse,
  100024. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  100025. db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
  100026. );
  100027. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  100028. sqlite3ChangeCookie(pParse, iDb);
  100029. destroyRootPage(pParse, pIndex->tnum, iDb);
  100030. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  100031. }
  100032. exit_drop_index:
  100033. sqlite3SrcListDelete(db, pName);
  100034. }
  100035. /*
  100036. ** pArray is a pointer to an array of objects. Each object in the
  100037. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  100038. ** to extend the array so that there is space for a new object at the end.
  100039. **
  100040. ** When this function is called, *pnEntry contains the current size of
  100041. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  100042. ** in total).
  100043. **
  100044. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  100045. ** space allocated for the new object is zeroed, *pnEntry updated to
  100046. ** reflect the new size of the array and a pointer to the new allocation
  100047. ** returned. *pIdx is set to the index of the new array entry in this case.
  100048. **
  100049. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  100050. ** unchanged and a copy of pArray returned.
  100051. */
  100052. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  100053. sqlite3 *db, /* Connection to notify of malloc failures */
  100054. void *pArray, /* Array of objects. Might be reallocated */
  100055. int szEntry, /* Size of each object in the array */
  100056. int *pnEntry, /* Number of objects currently in use */
  100057. int *pIdx /* Write the index of a new slot here */
  100058. ){
  100059. char *z;
  100060. int n = *pnEntry;
  100061. if( (n & (n-1))==0 ){
  100062. int sz = (n==0) ? 1 : 2*n;
  100063. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  100064. if( pNew==0 ){
  100065. *pIdx = -1;
  100066. return pArray;
  100067. }
  100068. pArray = pNew;
  100069. }
  100070. z = (char*)pArray;
  100071. memset(&z[n * szEntry], 0, szEntry);
  100072. *pIdx = n;
  100073. ++*pnEntry;
  100074. return pArray;
  100075. }
  100076. /*
  100077. ** Append a new element to the given IdList. Create a new IdList if
  100078. ** need be.
  100079. **
  100080. ** A new IdList is returned, or NULL if malloc() fails.
  100081. */
  100082. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  100083. int i;
  100084. if( pList==0 ){
  100085. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  100086. if( pList==0 ) return 0;
  100087. }
  100088. pList->a = sqlite3ArrayAllocate(
  100089. db,
  100090. pList->a,
  100091. sizeof(pList->a[0]),
  100092. &pList->nId,
  100093. &i
  100094. );
  100095. if( i<0 ){
  100096. sqlite3IdListDelete(db, pList);
  100097. return 0;
  100098. }
  100099. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  100100. return pList;
  100101. }
  100102. /*
  100103. ** Delete an IdList.
  100104. */
  100105. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  100106. int i;
  100107. if( pList==0 ) return;
  100108. for(i=0; i<pList->nId; i++){
  100109. sqlite3DbFree(db, pList->a[i].zName);
  100110. }
  100111. sqlite3DbFree(db, pList->a);
  100112. sqlite3DbFreeNN(db, pList);
  100113. }
  100114. /*
  100115. ** Return the index in pList of the identifier named zId. Return -1
  100116. ** if not found.
  100117. */
  100118. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  100119. int i;
  100120. if( pList==0 ) return -1;
  100121. for(i=0; i<pList->nId; i++){
  100122. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  100123. }
  100124. return -1;
  100125. }
  100126. /*
  100127. ** Expand the space allocated for the given SrcList object by
  100128. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  100129. ** New slots are zeroed.
  100130. **
  100131. ** For example, suppose a SrcList initially contains two entries: A,B.
  100132. ** To append 3 new entries onto the end, do this:
  100133. **
  100134. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  100135. **
  100136. ** After the call above it would contain: A, B, nil, nil, nil.
  100137. ** If the iStart argument had been 1 instead of 2, then the result
  100138. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  100139. ** the iStart value would be 0. The result then would
  100140. ** be: nil, nil, nil, A, B.
  100141. **
  100142. ** If a memory allocation fails the SrcList is unchanged. The
  100143. ** db->mallocFailed flag will be set to true.
  100144. */
  100145. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  100146. sqlite3 *db, /* Database connection to notify of OOM errors */
  100147. SrcList *pSrc, /* The SrcList to be enlarged */
  100148. int nExtra, /* Number of new slots to add to pSrc->a[] */
  100149. int iStart /* Index in pSrc->a[] of first new slot */
  100150. ){
  100151. int i;
  100152. /* Sanity checking on calling parameters */
  100153. assert( iStart>=0 );
  100154. assert( nExtra>=1 );
  100155. assert( pSrc!=0 );
  100156. assert( iStart<=pSrc->nSrc );
  100157. /* Allocate additional space if needed */
  100158. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  100159. SrcList *pNew;
  100160. int nAlloc = pSrc->nSrc*2+nExtra;
  100161. int nGot;
  100162. pNew = sqlite3DbRealloc(db, pSrc,
  100163. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  100164. if( pNew==0 ){
  100165. assert( db->mallocFailed );
  100166. return pSrc;
  100167. }
  100168. pSrc = pNew;
  100169. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  100170. pSrc->nAlloc = nGot;
  100171. }
  100172. /* Move existing slots that come after the newly inserted slots
  100173. ** out of the way */
  100174. for(i=pSrc->nSrc-1; i>=iStart; i--){
  100175. pSrc->a[i+nExtra] = pSrc->a[i];
  100176. }
  100177. pSrc->nSrc += nExtra;
  100178. /* Zero the newly allocated slots */
  100179. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  100180. for(i=iStart; i<iStart+nExtra; i++){
  100181. pSrc->a[i].iCursor = -1;
  100182. }
  100183. /* Return a pointer to the enlarged SrcList */
  100184. return pSrc;
  100185. }
  100186. /*
  100187. ** Append a new table name to the given SrcList. Create a new SrcList if
  100188. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  100189. **
  100190. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  100191. ** SrcList might be the same as the SrcList that was input or it might be
  100192. ** a new one. If an OOM error does occurs, then the prior value of pList
  100193. ** that is input to this routine is automatically freed.
  100194. **
  100195. ** If pDatabase is not null, it means that the table has an optional
  100196. ** database name prefix. Like this: "database.table". The pDatabase
  100197. ** points to the table name and the pTable points to the database name.
  100198. ** The SrcList.a[].zName field is filled with the table name which might
  100199. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  100200. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  100201. ** or with NULL if no database is specified.
  100202. **
  100203. ** In other words, if call like this:
  100204. **
  100205. ** sqlite3SrcListAppend(D,A,B,0);
  100206. **
  100207. ** Then B is a table name and the database name is unspecified. If called
  100208. ** like this:
  100209. **
  100210. ** sqlite3SrcListAppend(D,A,B,C);
  100211. **
  100212. ** Then C is the table name and B is the database name. If C is defined
  100213. ** then so is B. In other words, we never have a case where:
  100214. **
  100215. ** sqlite3SrcListAppend(D,A,0,C);
  100216. **
  100217. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  100218. ** before being added to the SrcList.
  100219. */
  100220. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  100221. sqlite3 *db, /* Connection to notify of malloc failures */
  100222. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  100223. Token *pTable, /* Table to append */
  100224. Token *pDatabase /* Database of the table */
  100225. ){
  100226. struct SrcList_item *pItem;
  100227. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  100228. assert( db!=0 );
  100229. if( pList==0 ){
  100230. pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
  100231. if( pList==0 ) return 0;
  100232. pList->nAlloc = 1;
  100233. pList->nSrc = 1;
  100234. memset(&pList->a[0], 0, sizeof(pList->a[0]));
  100235. pList->a[0].iCursor = -1;
  100236. }else{
  100237. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  100238. }
  100239. if( db->mallocFailed ){
  100240. sqlite3SrcListDelete(db, pList);
  100241. return 0;
  100242. }
  100243. pItem = &pList->a[pList->nSrc-1];
  100244. if( pDatabase && pDatabase->z==0 ){
  100245. pDatabase = 0;
  100246. }
  100247. if( pDatabase ){
  100248. pItem->zName = sqlite3NameFromToken(db, pDatabase);
  100249. pItem->zDatabase = sqlite3NameFromToken(db, pTable);
  100250. }else{
  100251. pItem->zName = sqlite3NameFromToken(db, pTable);
  100252. pItem->zDatabase = 0;
  100253. }
  100254. return pList;
  100255. }
  100256. /*
  100257. ** Assign VdbeCursor index numbers to all tables in a SrcList
  100258. */
  100259. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  100260. int i;
  100261. struct SrcList_item *pItem;
  100262. assert(pList || pParse->db->mallocFailed );
  100263. if( pList ){
  100264. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  100265. if( pItem->iCursor>=0 ) break;
  100266. pItem->iCursor = pParse->nTab++;
  100267. if( pItem->pSelect ){
  100268. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  100269. }
  100270. }
  100271. }
  100272. }
  100273. /*
  100274. ** Delete an entire SrcList including all its substructure.
  100275. */
  100276. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  100277. int i;
  100278. struct SrcList_item *pItem;
  100279. if( pList==0 ) return;
  100280. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  100281. sqlite3DbFree(db, pItem->zDatabase);
  100282. sqlite3DbFree(db, pItem->zName);
  100283. sqlite3DbFree(db, pItem->zAlias);
  100284. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  100285. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  100286. sqlite3DeleteTable(db, pItem->pTab);
  100287. sqlite3SelectDelete(db, pItem->pSelect);
  100288. sqlite3ExprDelete(db, pItem->pOn);
  100289. sqlite3IdListDelete(db, pItem->pUsing);
  100290. }
  100291. sqlite3DbFreeNN(db, pList);
  100292. }
  100293. /*
  100294. ** This routine is called by the parser to add a new term to the
  100295. ** end of a growing FROM clause. The "p" parameter is the part of
  100296. ** the FROM clause that has already been constructed. "p" is NULL
  100297. ** if this is the first term of the FROM clause. pTable and pDatabase
  100298. ** are the name of the table and database named in the FROM clause term.
  100299. ** pDatabase is NULL if the database name qualifier is missing - the
  100300. ** usual case. If the term has an alias, then pAlias points to the
  100301. ** alias token. If the term is a subquery, then pSubquery is the
  100302. ** SELECT statement that the subquery encodes. The pTable and
  100303. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  100304. ** parameters are the content of the ON and USING clauses.
  100305. **
  100306. ** Return a new SrcList which encodes is the FROM with the new
  100307. ** term added.
  100308. */
  100309. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  100310. Parse *pParse, /* Parsing context */
  100311. SrcList *p, /* The left part of the FROM clause already seen */
  100312. Token *pTable, /* Name of the table to add to the FROM clause */
  100313. Token *pDatabase, /* Name of the database containing pTable */
  100314. Token *pAlias, /* The right-hand side of the AS subexpression */
  100315. Select *pSubquery, /* A subquery used in place of a table name */
  100316. Expr *pOn, /* The ON clause of a join */
  100317. IdList *pUsing /* The USING clause of a join */
  100318. ){
  100319. struct SrcList_item *pItem;
  100320. sqlite3 *db = pParse->db;
  100321. if( !p && (pOn || pUsing) ){
  100322. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  100323. (pOn ? "ON" : "USING")
  100324. );
  100325. goto append_from_error;
  100326. }
  100327. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  100328. if( p==0 ){
  100329. goto append_from_error;
  100330. }
  100331. assert( p->nSrc>0 );
  100332. pItem = &p->a[p->nSrc-1];
  100333. assert( pAlias!=0 );
  100334. if( pAlias->n ){
  100335. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  100336. }
  100337. pItem->pSelect = pSubquery;
  100338. pItem->pOn = pOn;
  100339. pItem->pUsing = pUsing;
  100340. return p;
  100341. append_from_error:
  100342. assert( p==0 );
  100343. sqlite3ExprDelete(db, pOn);
  100344. sqlite3IdListDelete(db, pUsing);
  100345. sqlite3SelectDelete(db, pSubquery);
  100346. return 0;
  100347. }
  100348. /*
  100349. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  100350. ** element of the source-list passed as the second argument.
  100351. */
  100352. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  100353. assert( pIndexedBy!=0 );
  100354. if( p && pIndexedBy->n>0 ){
  100355. struct SrcList_item *pItem;
  100356. assert( p->nSrc>0 );
  100357. pItem = &p->a[p->nSrc-1];
  100358. assert( pItem->fg.notIndexed==0 );
  100359. assert( pItem->fg.isIndexedBy==0 );
  100360. assert( pItem->fg.isTabFunc==0 );
  100361. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  100362. /* A "NOT INDEXED" clause was supplied. See parse.y
  100363. ** construct "indexed_opt" for details. */
  100364. pItem->fg.notIndexed = 1;
  100365. }else{
  100366. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  100367. pItem->fg.isIndexedBy = 1;
  100368. }
  100369. }
  100370. }
  100371. /*
  100372. ** Add the list of function arguments to the SrcList entry for a
  100373. ** table-valued-function.
  100374. */
  100375. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  100376. if( p ){
  100377. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  100378. assert( pItem->fg.notIndexed==0 );
  100379. assert( pItem->fg.isIndexedBy==0 );
  100380. assert( pItem->fg.isTabFunc==0 );
  100381. pItem->u1.pFuncArg = pList;
  100382. pItem->fg.isTabFunc = 1;
  100383. }else{
  100384. sqlite3ExprListDelete(pParse->db, pList);
  100385. }
  100386. }
  100387. /*
  100388. ** When building up a FROM clause in the parser, the join operator
  100389. ** is initially attached to the left operand. But the code generator
  100390. ** expects the join operator to be on the right operand. This routine
  100391. ** Shifts all join operators from left to right for an entire FROM
  100392. ** clause.
  100393. **
  100394. ** Example: Suppose the join is like this:
  100395. **
  100396. ** A natural cross join B
  100397. **
  100398. ** The operator is "natural cross join". The A and B operands are stored
  100399. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  100400. ** operator with A. This routine shifts that operator over to B.
  100401. */
  100402. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  100403. if( p ){
  100404. int i;
  100405. for(i=p->nSrc-1; i>0; i--){
  100406. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  100407. }
  100408. p->a[0].fg.jointype = 0;
  100409. }
  100410. }
  100411. /*
  100412. ** Generate VDBE code for a BEGIN statement.
  100413. */
  100414. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  100415. sqlite3 *db;
  100416. Vdbe *v;
  100417. int i;
  100418. assert( pParse!=0 );
  100419. db = pParse->db;
  100420. assert( db!=0 );
  100421. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  100422. return;
  100423. }
  100424. v = sqlite3GetVdbe(pParse);
  100425. if( !v ) return;
  100426. if( type!=TK_DEFERRED ){
  100427. for(i=0; i<db->nDb; i++){
  100428. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  100429. sqlite3VdbeUsesBtree(v, i);
  100430. }
  100431. }
  100432. sqlite3VdbeAddOp0(v, OP_AutoCommit);
  100433. }
  100434. /*
  100435. ** Generate VDBE code for a COMMIT or ROLLBACK statement.
  100436. ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
  100437. ** code is generated for a COMMIT.
  100438. */
  100439. SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
  100440. Vdbe *v;
  100441. int isRollback;
  100442. assert( pParse!=0 );
  100443. assert( pParse->db!=0 );
  100444. assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
  100445. isRollback = eType==TK_ROLLBACK;
  100446. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
  100447. isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
  100448. return;
  100449. }
  100450. v = sqlite3GetVdbe(pParse);
  100451. if( v ){
  100452. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
  100453. }
  100454. }
  100455. /*
  100456. ** This function is called by the parser when it parses a command to create,
  100457. ** release or rollback an SQL savepoint.
  100458. */
  100459. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  100460. char *zName = sqlite3NameFromToken(pParse->db, pName);
  100461. if( zName ){
  100462. Vdbe *v = sqlite3GetVdbe(pParse);
  100463. #ifndef SQLITE_OMIT_AUTHORIZATION
  100464. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  100465. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  100466. #endif
  100467. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  100468. sqlite3DbFree(pParse->db, zName);
  100469. return;
  100470. }
  100471. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  100472. }
  100473. }
  100474. /*
  100475. ** Make sure the TEMP database is open and available for use. Return
  100476. ** the number of errors. Leave any error messages in the pParse structure.
  100477. */
  100478. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  100479. sqlite3 *db = pParse->db;
  100480. if( db->aDb[1].pBt==0 && !pParse->explain ){
  100481. int rc;
  100482. Btree *pBt;
  100483. static const int flags =
  100484. SQLITE_OPEN_READWRITE |
  100485. SQLITE_OPEN_CREATE |
  100486. SQLITE_OPEN_EXCLUSIVE |
  100487. SQLITE_OPEN_DELETEONCLOSE |
  100488. SQLITE_OPEN_TEMP_DB;
  100489. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  100490. if( rc!=SQLITE_OK ){
  100491. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  100492. "file for storing temporary tables");
  100493. pParse->rc = rc;
  100494. return 1;
  100495. }
  100496. db->aDb[1].pBt = pBt;
  100497. assert( db->aDb[1].pSchema );
  100498. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  100499. sqlite3OomFault(db);
  100500. return 1;
  100501. }
  100502. }
  100503. return 0;
  100504. }
  100505. /*
  100506. ** Record the fact that the schema cookie will need to be verified
  100507. ** for database iDb. The code to actually verify the schema cookie
  100508. ** will occur at the end of the top-level VDBE and will be generated
  100509. ** later, by sqlite3FinishCoding().
  100510. */
  100511. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  100512. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  100513. assert( iDb>=0 && iDb<pParse->db->nDb );
  100514. assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
  100515. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  100516. assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
  100517. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  100518. DbMaskSet(pToplevel->cookieMask, iDb);
  100519. if( !OMIT_TEMPDB && iDb==1 ){
  100520. sqlite3OpenTempDatabase(pToplevel);
  100521. }
  100522. }
  100523. }
  100524. /*
  100525. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  100526. ** attached database. Otherwise, invoke it for the database named zDb only.
  100527. */
  100528. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  100529. sqlite3 *db = pParse->db;
  100530. int i;
  100531. for(i=0; i<db->nDb; i++){
  100532. Db *pDb = &db->aDb[i];
  100533. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
  100534. sqlite3CodeVerifySchema(pParse, i);
  100535. }
  100536. }
  100537. }
  100538. /*
  100539. ** Generate VDBE code that prepares for doing an operation that
  100540. ** might change the database.
  100541. **
  100542. ** This routine starts a new transaction if we are not already within
  100543. ** a transaction. If we are already within a transaction, then a checkpoint
  100544. ** is set if the setStatement parameter is true. A checkpoint should
  100545. ** be set for operations that might fail (due to a constraint) part of
  100546. ** the way through and which will need to undo some writes without having to
  100547. ** rollback the whole transaction. For operations where all constraints
  100548. ** can be checked before any changes are made to the database, it is never
  100549. ** necessary to undo a write and the checkpoint should not be set.
  100550. */
  100551. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  100552. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  100553. sqlite3CodeVerifySchema(pParse, iDb);
  100554. DbMaskSet(pToplevel->writeMask, iDb);
  100555. pToplevel->isMultiWrite |= setStatement;
  100556. }
  100557. /*
  100558. ** Indicate that the statement currently under construction might write
  100559. ** more than one entry (example: deleting one row then inserting another,
  100560. ** inserting multiple rows in a table, or inserting a row and index entries.)
  100561. ** If an abort occurs after some of these writes have completed, then it will
  100562. ** be necessary to undo the completed writes.
  100563. */
  100564. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  100565. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  100566. pToplevel->isMultiWrite = 1;
  100567. }
  100568. /*
  100569. ** The code generator calls this routine if is discovers that it is
  100570. ** possible to abort a statement prior to completion. In order to
  100571. ** perform this abort without corrupting the database, we need to make
  100572. ** sure that the statement is protected by a statement transaction.
  100573. **
  100574. ** Technically, we only need to set the mayAbort flag if the
  100575. ** isMultiWrite flag was previously set. There is a time dependency
  100576. ** such that the abort must occur after the multiwrite. This makes
  100577. ** some statements involving the REPLACE conflict resolution algorithm
  100578. ** go a little faster. But taking advantage of this time dependency
  100579. ** makes it more difficult to prove that the code is correct (in
  100580. ** particular, it prevents us from writing an effective
  100581. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  100582. ** to take the safe route and skip the optimization.
  100583. */
  100584. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  100585. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  100586. pToplevel->mayAbort = 1;
  100587. }
  100588. /*
  100589. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  100590. ** error. The onError parameter determines which (if any) of the statement
  100591. ** and/or current transaction is rolled back.
  100592. */
  100593. SQLITE_PRIVATE void sqlite3HaltConstraint(
  100594. Parse *pParse, /* Parsing context */
  100595. int errCode, /* extended error code */
  100596. int onError, /* Constraint type */
  100597. char *p4, /* Error message */
  100598. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  100599. u8 p5Errmsg /* P5_ErrMsg type */
  100600. ){
  100601. Vdbe *v = sqlite3GetVdbe(pParse);
  100602. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  100603. if( onError==OE_Abort ){
  100604. sqlite3MayAbort(pParse);
  100605. }
  100606. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  100607. sqlite3VdbeChangeP5(v, p5Errmsg);
  100608. }
  100609. /*
  100610. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  100611. */
  100612. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  100613. Parse *pParse, /* Parsing context */
  100614. int onError, /* Constraint type */
  100615. Index *pIdx /* The index that triggers the constraint */
  100616. ){
  100617. char *zErr;
  100618. int j;
  100619. StrAccum errMsg;
  100620. Table *pTab = pIdx->pTable;
  100621. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  100622. if( pIdx->aColExpr ){
  100623. sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
  100624. }else{
  100625. for(j=0; j<pIdx->nKeyCol; j++){
  100626. char *zCol;
  100627. assert( pIdx->aiColumn[j]>=0 );
  100628. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  100629. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  100630. sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
  100631. sqlite3StrAccumAppend(&errMsg, ".", 1);
  100632. sqlite3StrAccumAppendAll(&errMsg, zCol);
  100633. }
  100634. }
  100635. zErr = sqlite3StrAccumFinish(&errMsg);
  100636. sqlite3HaltConstraint(pParse,
  100637. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  100638. : SQLITE_CONSTRAINT_UNIQUE,
  100639. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  100640. }
  100641. /*
  100642. ** Code an OP_Halt due to non-unique rowid.
  100643. */
  100644. SQLITE_PRIVATE void sqlite3RowidConstraint(
  100645. Parse *pParse, /* Parsing context */
  100646. int onError, /* Conflict resolution algorithm */
  100647. Table *pTab /* The table with the non-unique rowid */
  100648. ){
  100649. char *zMsg;
  100650. int rc;
  100651. if( pTab->iPKey>=0 ){
  100652. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  100653. pTab->aCol[pTab->iPKey].zName);
  100654. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  100655. }else{
  100656. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  100657. rc = SQLITE_CONSTRAINT_ROWID;
  100658. }
  100659. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  100660. P5_ConstraintUnique);
  100661. }
  100662. /*
  100663. ** Check to see if pIndex uses the collating sequence pColl. Return
  100664. ** true if it does and false if it does not.
  100665. */
  100666. #ifndef SQLITE_OMIT_REINDEX
  100667. static int collationMatch(const char *zColl, Index *pIndex){
  100668. int i;
  100669. assert( zColl!=0 );
  100670. for(i=0; i<pIndex->nColumn; i++){
  100671. const char *z = pIndex->azColl[i];
  100672. assert( z!=0 || pIndex->aiColumn[i]<0 );
  100673. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  100674. return 1;
  100675. }
  100676. }
  100677. return 0;
  100678. }
  100679. #endif
  100680. /*
  100681. ** Recompute all indices of pTab that use the collating sequence pColl.
  100682. ** If pColl==0 then recompute all indices of pTab.
  100683. */
  100684. #ifndef SQLITE_OMIT_REINDEX
  100685. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  100686. Index *pIndex; /* An index associated with pTab */
  100687. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  100688. if( zColl==0 || collationMatch(zColl, pIndex) ){
  100689. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  100690. sqlite3BeginWriteOperation(pParse, 0, iDb);
  100691. sqlite3RefillIndex(pParse, pIndex, -1);
  100692. }
  100693. }
  100694. }
  100695. #endif
  100696. /*
  100697. ** Recompute all indices of all tables in all databases where the
  100698. ** indices use the collating sequence pColl. If pColl==0 then recompute
  100699. ** all indices everywhere.
  100700. */
  100701. #ifndef SQLITE_OMIT_REINDEX
  100702. static void reindexDatabases(Parse *pParse, char const *zColl){
  100703. Db *pDb; /* A single database */
  100704. int iDb; /* The database index number */
  100705. sqlite3 *db = pParse->db; /* The database connection */
  100706. HashElem *k; /* For looping over tables in pDb */
  100707. Table *pTab; /* A table in the database */
  100708. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  100709. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  100710. assert( pDb!=0 );
  100711. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  100712. pTab = (Table*)sqliteHashData(k);
  100713. reindexTable(pParse, pTab, zColl);
  100714. }
  100715. }
  100716. }
  100717. #endif
  100718. /*
  100719. ** Generate code for the REINDEX command.
  100720. **
  100721. ** REINDEX -- 1
  100722. ** REINDEX <collation> -- 2
  100723. ** REINDEX ?<database>.?<tablename> -- 3
  100724. ** REINDEX ?<database>.?<indexname> -- 4
  100725. **
  100726. ** Form 1 causes all indices in all attached databases to be rebuilt.
  100727. ** Form 2 rebuilds all indices in all databases that use the named
  100728. ** collating function. Forms 3 and 4 rebuild the named index or all
  100729. ** indices associated with the named table.
  100730. */
  100731. #ifndef SQLITE_OMIT_REINDEX
  100732. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  100733. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  100734. char *z; /* Name of a table or index */
  100735. const char *zDb; /* Name of the database */
  100736. Table *pTab; /* A table in the database */
  100737. Index *pIndex; /* An index associated with pTab */
  100738. int iDb; /* The database index number */
  100739. sqlite3 *db = pParse->db; /* The database connection */
  100740. Token *pObjName; /* Name of the table or index to be reindexed */
  100741. /* Read the database schema. If an error occurs, leave an error message
  100742. ** and code in pParse and return NULL. */
  100743. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  100744. return;
  100745. }
  100746. if( pName1==0 ){
  100747. reindexDatabases(pParse, 0);
  100748. return;
  100749. }else if( NEVER(pName2==0) || pName2->z==0 ){
  100750. char *zColl;
  100751. assert( pName1->z );
  100752. zColl = sqlite3NameFromToken(pParse->db, pName1);
  100753. if( !zColl ) return;
  100754. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  100755. if( pColl ){
  100756. reindexDatabases(pParse, zColl);
  100757. sqlite3DbFree(db, zColl);
  100758. return;
  100759. }
  100760. sqlite3DbFree(db, zColl);
  100761. }
  100762. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  100763. if( iDb<0 ) return;
  100764. z = sqlite3NameFromToken(db, pObjName);
  100765. if( z==0 ) return;
  100766. zDb = db->aDb[iDb].zDbSName;
  100767. pTab = sqlite3FindTable(db, z, zDb);
  100768. if( pTab ){
  100769. reindexTable(pParse, pTab, 0);
  100770. sqlite3DbFree(db, z);
  100771. return;
  100772. }
  100773. pIndex = sqlite3FindIndex(db, z, zDb);
  100774. sqlite3DbFree(db, z);
  100775. if( pIndex ){
  100776. sqlite3BeginWriteOperation(pParse, 0, iDb);
  100777. sqlite3RefillIndex(pParse, pIndex, -1);
  100778. return;
  100779. }
  100780. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  100781. }
  100782. #endif
  100783. /*
  100784. ** Return a KeyInfo structure that is appropriate for the given Index.
  100785. **
  100786. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  100787. ** when it has finished using it.
  100788. */
  100789. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  100790. int i;
  100791. int nCol = pIdx->nColumn;
  100792. int nKey = pIdx->nKeyCol;
  100793. KeyInfo *pKey;
  100794. if( pParse->nErr ) return 0;
  100795. if( pIdx->uniqNotNull ){
  100796. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  100797. }else{
  100798. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  100799. }
  100800. if( pKey ){
  100801. assert( sqlite3KeyInfoIsWriteable(pKey) );
  100802. for(i=0; i<nCol; i++){
  100803. const char *zColl = pIdx->azColl[i];
  100804. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  100805. sqlite3LocateCollSeq(pParse, zColl);
  100806. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  100807. }
  100808. if( pParse->nErr ){
  100809. assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
  100810. if( pIdx->bNoQuery==0 ){
  100811. /* Deactivate the index because it contains an unknown collating
  100812. ** sequence. The only way to reactive the index is to reload the
  100813. ** schema. Adding the missing collating sequence later does not
  100814. ** reactive the index. The application had the chance to register
  100815. ** the missing index using the collation-needed callback. For
  100816. ** simplicity, SQLite will not give the application a second chance.
  100817. */
  100818. pIdx->bNoQuery = 1;
  100819. pParse->rc = SQLITE_ERROR_RETRY;
  100820. }
  100821. sqlite3KeyInfoUnref(pKey);
  100822. pKey = 0;
  100823. }
  100824. }
  100825. return pKey;
  100826. }
  100827. #ifndef SQLITE_OMIT_CTE
  100828. /*
  100829. ** This routine is invoked once per CTE by the parser while parsing a
  100830. ** WITH clause.
  100831. */
  100832. SQLITE_PRIVATE With *sqlite3WithAdd(
  100833. Parse *pParse, /* Parsing context */
  100834. With *pWith, /* Existing WITH clause, or NULL */
  100835. Token *pName, /* Name of the common-table */
  100836. ExprList *pArglist, /* Optional column name list for the table */
  100837. Select *pQuery /* Query used to initialize the table */
  100838. ){
  100839. sqlite3 *db = pParse->db;
  100840. With *pNew;
  100841. char *zName;
  100842. /* Check that the CTE name is unique within this WITH clause. If
  100843. ** not, store an error in the Parse structure. */
  100844. zName = sqlite3NameFromToken(pParse->db, pName);
  100845. if( zName && pWith ){
  100846. int i;
  100847. for(i=0; i<pWith->nCte; i++){
  100848. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  100849. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  100850. }
  100851. }
  100852. }
  100853. if( pWith ){
  100854. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  100855. pNew = sqlite3DbRealloc(db, pWith, nByte);
  100856. }else{
  100857. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  100858. }
  100859. assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  100860. if( db->mallocFailed ){
  100861. sqlite3ExprListDelete(db, pArglist);
  100862. sqlite3SelectDelete(db, pQuery);
  100863. sqlite3DbFree(db, zName);
  100864. pNew = pWith;
  100865. }else{
  100866. pNew->a[pNew->nCte].pSelect = pQuery;
  100867. pNew->a[pNew->nCte].pCols = pArglist;
  100868. pNew->a[pNew->nCte].zName = zName;
  100869. pNew->a[pNew->nCte].zCteErr = 0;
  100870. pNew->nCte++;
  100871. }
  100872. return pNew;
  100873. }
  100874. /*
  100875. ** Free the contents of the With object passed as the second argument.
  100876. */
  100877. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  100878. if( pWith ){
  100879. int i;
  100880. for(i=0; i<pWith->nCte; i++){
  100881. struct Cte *pCte = &pWith->a[i];
  100882. sqlite3ExprListDelete(db, pCte->pCols);
  100883. sqlite3SelectDelete(db, pCte->pSelect);
  100884. sqlite3DbFree(db, pCte->zName);
  100885. }
  100886. sqlite3DbFree(db, pWith);
  100887. }
  100888. }
  100889. #endif /* !defined(SQLITE_OMIT_CTE) */
  100890. /************** End of build.c ***********************************************/
  100891. /************** Begin file callback.c ****************************************/
  100892. /*
  100893. ** 2005 May 23
  100894. **
  100895. ** The author disclaims copyright to this source code. In place of
  100896. ** a legal notice, here is a blessing:
  100897. **
  100898. ** May you do good and not evil.
  100899. ** May you find forgiveness for yourself and forgive others.
  100900. ** May you share freely, never taking more than you give.
  100901. **
  100902. *************************************************************************
  100903. **
  100904. ** This file contains functions used to access the internal hash tables
  100905. ** of user defined functions and collation sequences.
  100906. */
  100907. /* #include "sqliteInt.h" */
  100908. /*
  100909. ** Invoke the 'collation needed' callback to request a collation sequence
  100910. ** in the encoding enc of name zName, length nName.
  100911. */
  100912. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  100913. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  100914. if( db->xCollNeeded ){
  100915. char *zExternal = sqlite3DbStrDup(db, zName);
  100916. if( !zExternal ) return;
  100917. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  100918. sqlite3DbFree(db, zExternal);
  100919. }
  100920. #ifndef SQLITE_OMIT_UTF16
  100921. if( db->xCollNeeded16 ){
  100922. char const *zExternal;
  100923. sqlite3_value *pTmp = sqlite3ValueNew(db);
  100924. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  100925. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  100926. if( zExternal ){
  100927. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  100928. }
  100929. sqlite3ValueFree(pTmp);
  100930. }
  100931. #endif
  100932. }
  100933. /*
  100934. ** This routine is called if the collation factory fails to deliver a
  100935. ** collation function in the best encoding but there may be other versions
  100936. ** of this collation function (for other text encodings) available. Use one
  100937. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  100938. ** possible.
  100939. */
  100940. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  100941. CollSeq *pColl2;
  100942. char *z = pColl->zName;
  100943. int i;
  100944. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  100945. for(i=0; i<3; i++){
  100946. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  100947. if( pColl2->xCmp!=0 ){
  100948. memcpy(pColl, pColl2, sizeof(CollSeq));
  100949. pColl->xDel = 0; /* Do not copy the destructor */
  100950. return SQLITE_OK;
  100951. }
  100952. }
  100953. return SQLITE_ERROR;
  100954. }
  100955. /*
  100956. ** This function is responsible for invoking the collation factory callback
  100957. ** or substituting a collation sequence of a different encoding when the
  100958. ** requested collation sequence is not available in the desired encoding.
  100959. **
  100960. ** If it is not NULL, then pColl must point to the database native encoding
  100961. ** collation sequence with name zName, length nName.
  100962. **
  100963. ** The return value is either the collation sequence to be used in database
  100964. ** db for collation type name zName, length nName, or NULL, if no collation
  100965. ** sequence can be found. If no collation is found, leave an error message.
  100966. **
  100967. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  100968. */
  100969. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  100970. Parse *pParse, /* Parsing context */
  100971. u8 enc, /* The desired encoding for the collating sequence */
  100972. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  100973. const char *zName /* Collating sequence name */
  100974. ){
  100975. CollSeq *p;
  100976. sqlite3 *db = pParse->db;
  100977. p = pColl;
  100978. if( !p ){
  100979. p = sqlite3FindCollSeq(db, enc, zName, 0);
  100980. }
  100981. if( !p || !p->xCmp ){
  100982. /* No collation sequence of this type for this encoding is registered.
  100983. ** Call the collation factory to see if it can supply us with one.
  100984. */
  100985. callCollNeeded(db, enc, zName);
  100986. p = sqlite3FindCollSeq(db, enc, zName, 0);
  100987. }
  100988. if( p && !p->xCmp && synthCollSeq(db, p) ){
  100989. p = 0;
  100990. }
  100991. assert( !p || p->xCmp );
  100992. if( p==0 ){
  100993. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  100994. pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
  100995. }
  100996. return p;
  100997. }
  100998. /*
  100999. ** This routine is called on a collation sequence before it is used to
  101000. ** check that it is defined. An undefined collation sequence exists when
  101001. ** a database is loaded that contains references to collation sequences
  101002. ** that have not been defined by sqlite3_create_collation() etc.
  101003. **
  101004. ** If required, this routine calls the 'collation needed' callback to
  101005. ** request a definition of the collating sequence. If this doesn't work,
  101006. ** an equivalent collating sequence that uses a text encoding different
  101007. ** from the main database is substituted, if one is available.
  101008. */
  101009. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  101010. if( pColl && pColl->xCmp==0 ){
  101011. const char *zName = pColl->zName;
  101012. sqlite3 *db = pParse->db;
  101013. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  101014. if( !p ){
  101015. return SQLITE_ERROR;
  101016. }
  101017. assert( p==pColl );
  101018. }
  101019. return SQLITE_OK;
  101020. }
  101021. /*
  101022. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  101023. ** specified by zName and nName is not found and parameter 'create' is
  101024. ** true, then create a new entry. Otherwise return NULL.
  101025. **
  101026. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  101027. ** array of three CollSeq structures. The first is the collation sequence
  101028. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  101029. **
  101030. ** Stored immediately after the three collation sequences is a copy of
  101031. ** the collation sequence name. A pointer to this string is stored in
  101032. ** each collation sequence structure.
  101033. */
  101034. static CollSeq *findCollSeqEntry(
  101035. sqlite3 *db, /* Database connection */
  101036. const char *zName, /* Name of the collating sequence */
  101037. int create /* Create a new entry if true */
  101038. ){
  101039. CollSeq *pColl;
  101040. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  101041. if( 0==pColl && create ){
  101042. int nName = sqlite3Strlen30(zName) + 1;
  101043. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
  101044. if( pColl ){
  101045. CollSeq *pDel = 0;
  101046. pColl[0].zName = (char*)&pColl[3];
  101047. pColl[0].enc = SQLITE_UTF8;
  101048. pColl[1].zName = (char*)&pColl[3];
  101049. pColl[1].enc = SQLITE_UTF16LE;
  101050. pColl[2].zName = (char*)&pColl[3];
  101051. pColl[2].enc = SQLITE_UTF16BE;
  101052. memcpy(pColl[0].zName, zName, nName);
  101053. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  101054. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  101055. ** return the pColl pointer to be deleted (because it wasn't added
  101056. ** to the hash table).
  101057. */
  101058. assert( pDel==0 || pDel==pColl );
  101059. if( pDel!=0 ){
  101060. sqlite3OomFault(db);
  101061. sqlite3DbFree(db, pDel);
  101062. pColl = 0;
  101063. }
  101064. }
  101065. }
  101066. return pColl;
  101067. }
  101068. /*
  101069. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  101070. ** Return the CollSeq* pointer for the collation sequence named zName
  101071. ** for the encoding 'enc' from the database 'db'.
  101072. **
  101073. ** If the entry specified is not found and 'create' is true, then create a
  101074. ** new entry. Otherwise return NULL.
  101075. **
  101076. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  101077. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  101078. ** if necessary and generates an error message if the collating sequence
  101079. ** cannot be found.
  101080. **
  101081. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  101082. */
  101083. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  101084. sqlite3 *db,
  101085. u8 enc,
  101086. const char *zName,
  101087. int create
  101088. ){
  101089. CollSeq *pColl;
  101090. if( zName ){
  101091. pColl = findCollSeqEntry(db, zName, create);
  101092. }else{
  101093. pColl = db->pDfltColl;
  101094. }
  101095. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  101096. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  101097. if( pColl ) pColl += enc-1;
  101098. return pColl;
  101099. }
  101100. /* During the search for the best function definition, this procedure
  101101. ** is called to test how well the function passed as the first argument
  101102. ** matches the request for a function with nArg arguments in a system
  101103. ** that uses encoding enc. The value returned indicates how well the
  101104. ** request is matched. A higher value indicates a better match.
  101105. **
  101106. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  101107. ** is also -1. In other words, we are searching for a function that
  101108. ** takes a variable number of arguments.
  101109. **
  101110. ** If nArg is -2 that means that we are searching for any function
  101111. ** regardless of the number of arguments it uses, so return a positive
  101112. ** match score for any
  101113. **
  101114. ** The returned value is always between 0 and 6, as follows:
  101115. **
  101116. ** 0: Not a match.
  101117. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  101118. ** 2: UTF16 byte order change required and function takes any number of args.
  101119. ** 3: encoding matches and function takes any number of arguments
  101120. ** 4: UTF8/16 conversion required - argument count matches exactly
  101121. ** 5: UTF16 byte order conversion required - argument count matches exactly
  101122. ** 6: Perfect match: encoding and argument count match exactly.
  101123. **
  101124. ** If nArg==(-2) then any function with a non-null xSFunc is
  101125. ** a perfect match and any function with xSFunc NULL is
  101126. ** a non-match.
  101127. */
  101128. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  101129. static int matchQuality(
  101130. FuncDef *p, /* The function we are evaluating for match quality */
  101131. int nArg, /* Desired number of arguments. (-1)==any */
  101132. u8 enc /* Desired text encoding */
  101133. ){
  101134. int match;
  101135. /* nArg of -2 is a special case */
  101136. if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
  101137. /* Wrong number of arguments means "no match" */
  101138. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  101139. /* Give a better score to a function with a specific number of arguments
  101140. ** than to function that accepts any number of arguments. */
  101141. if( p->nArg==nArg ){
  101142. match = 4;
  101143. }else{
  101144. match = 1;
  101145. }
  101146. /* Bonus points if the text encoding matches */
  101147. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  101148. match += 2; /* Exact encoding match */
  101149. }else if( (enc & p->funcFlags & 2)!=0 ){
  101150. match += 1; /* Both are UTF16, but with different byte orders */
  101151. }
  101152. return match;
  101153. }
  101154. /*
  101155. ** Search a FuncDefHash for a function with the given name. Return
  101156. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  101157. */
  101158. static FuncDef *functionSearch(
  101159. int h, /* Hash of the name */
  101160. const char *zFunc /* Name of function */
  101161. ){
  101162. FuncDef *p;
  101163. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  101164. if( sqlite3StrICmp(p->zName, zFunc)==0 ){
  101165. return p;
  101166. }
  101167. }
  101168. return 0;
  101169. }
  101170. /*
  101171. ** Insert a new FuncDef into a FuncDefHash hash table.
  101172. */
  101173. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
  101174. FuncDef *aDef, /* List of global functions to be inserted */
  101175. int nDef /* Length of the apDef[] list */
  101176. ){
  101177. int i;
  101178. for(i=0; i<nDef; i++){
  101179. FuncDef *pOther;
  101180. const char *zName = aDef[i].zName;
  101181. int nName = sqlite3Strlen30(zName);
  101182. int h = (zName[0] + nName) % SQLITE_FUNC_HASH_SZ;
  101183. assert( zName[0]>='a' && zName[0]<='z' );
  101184. pOther = functionSearch(h, zName);
  101185. if( pOther ){
  101186. assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
  101187. aDef[i].pNext = pOther->pNext;
  101188. pOther->pNext = &aDef[i];
  101189. }else{
  101190. aDef[i].pNext = 0;
  101191. aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
  101192. sqlite3BuiltinFunctions.a[h] = &aDef[i];
  101193. }
  101194. }
  101195. }
  101196. /*
  101197. ** Locate a user function given a name, a number of arguments and a flag
  101198. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  101199. ** pointer to the FuncDef structure that defines that function, or return
  101200. ** NULL if the function does not exist.
  101201. **
  101202. ** If the createFlag argument is true, then a new (blank) FuncDef
  101203. ** structure is created and liked into the "db" structure if a
  101204. ** no matching function previously existed.
  101205. **
  101206. ** If nArg is -2, then the first valid function found is returned. A
  101207. ** function is valid if xSFunc is non-zero. The nArg==(-2)
  101208. ** case is used to see if zName is a valid function name for some number
  101209. ** of arguments. If nArg is -2, then createFlag must be 0.
  101210. **
  101211. ** If createFlag is false, then a function with the required name and
  101212. ** number of arguments may be returned even if the eTextRep flag does not
  101213. ** match that requested.
  101214. */
  101215. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  101216. sqlite3 *db, /* An open database */
  101217. const char *zName, /* Name of the function. zero-terminated */
  101218. int nArg, /* Number of arguments. -1 means any number */
  101219. u8 enc, /* Preferred text encoding */
  101220. u8 createFlag /* Create new entry if true and does not otherwise exist */
  101221. ){
  101222. FuncDef *p; /* Iterator variable */
  101223. FuncDef *pBest = 0; /* Best match found so far */
  101224. int bestScore = 0; /* Score of best match */
  101225. int h; /* Hash value */
  101226. int nName; /* Length of the name */
  101227. assert( nArg>=(-2) );
  101228. assert( nArg>=(-1) || createFlag==0 );
  101229. nName = sqlite3Strlen30(zName);
  101230. /* First search for a match amongst the application-defined functions.
  101231. */
  101232. p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
  101233. while( p ){
  101234. int score = matchQuality(p, nArg, enc);
  101235. if( score>bestScore ){
  101236. pBest = p;
  101237. bestScore = score;
  101238. }
  101239. p = p->pNext;
  101240. }
  101241. /* If no match is found, search the built-in functions.
  101242. **
  101243. ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
  101244. ** functions even if a prior app-defined function was found. And give
  101245. ** priority to built-in functions.
  101246. **
  101247. ** Except, if createFlag is true, that means that we are trying to
  101248. ** install a new function. Whatever FuncDef structure is returned it will
  101249. ** have fields overwritten with new information appropriate for the
  101250. ** new function. But the FuncDefs for built-in functions are read-only.
  101251. ** So we must not search for built-ins when creating a new function.
  101252. */
  101253. if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
  101254. bestScore = 0;
  101255. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
  101256. p = functionSearch(h, zName);
  101257. while( p ){
  101258. int score = matchQuality(p, nArg, enc);
  101259. if( score>bestScore ){
  101260. pBest = p;
  101261. bestScore = score;
  101262. }
  101263. p = p->pNext;
  101264. }
  101265. }
  101266. /* If the createFlag parameter is true and the search did not reveal an
  101267. ** exact match for the name, number of arguments and encoding, then add a
  101268. ** new entry to the hash table and return it.
  101269. */
  101270. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  101271. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  101272. FuncDef *pOther;
  101273. pBest->zName = (const char*)&pBest[1];
  101274. pBest->nArg = (u16)nArg;
  101275. pBest->funcFlags = enc;
  101276. memcpy((char*)&pBest[1], zName, nName+1);
  101277. pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
  101278. if( pOther==pBest ){
  101279. sqlite3DbFree(db, pBest);
  101280. sqlite3OomFault(db);
  101281. return 0;
  101282. }else{
  101283. pBest->pNext = pOther;
  101284. }
  101285. }
  101286. if( pBest && (pBest->xSFunc || createFlag) ){
  101287. return pBest;
  101288. }
  101289. return 0;
  101290. }
  101291. /*
  101292. ** Free all resources held by the schema structure. The void* argument points
  101293. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  101294. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  101295. ** of the schema hash tables).
  101296. **
  101297. ** The Schema.cache_size variable is not cleared.
  101298. */
  101299. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  101300. Hash temp1;
  101301. Hash temp2;
  101302. HashElem *pElem;
  101303. Schema *pSchema = (Schema *)p;
  101304. temp1 = pSchema->tblHash;
  101305. temp2 = pSchema->trigHash;
  101306. sqlite3HashInit(&pSchema->trigHash);
  101307. sqlite3HashClear(&pSchema->idxHash);
  101308. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  101309. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  101310. }
  101311. sqlite3HashClear(&temp2);
  101312. sqlite3HashInit(&pSchema->tblHash);
  101313. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  101314. Table *pTab = sqliteHashData(pElem);
  101315. sqlite3DeleteTable(0, pTab);
  101316. }
  101317. sqlite3HashClear(&temp1);
  101318. sqlite3HashClear(&pSchema->fkeyHash);
  101319. pSchema->pSeqTab = 0;
  101320. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  101321. pSchema->iGeneration++;
  101322. }
  101323. pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
  101324. }
  101325. /*
  101326. ** Find and return the schema associated with a BTree. Create
  101327. ** a new one if necessary.
  101328. */
  101329. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  101330. Schema * p;
  101331. if( pBt ){
  101332. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  101333. }else{
  101334. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  101335. }
  101336. if( !p ){
  101337. sqlite3OomFault(db);
  101338. }else if ( 0==p->file_format ){
  101339. sqlite3HashInit(&p->tblHash);
  101340. sqlite3HashInit(&p->idxHash);
  101341. sqlite3HashInit(&p->trigHash);
  101342. sqlite3HashInit(&p->fkeyHash);
  101343. p->enc = SQLITE_UTF8;
  101344. }
  101345. return p;
  101346. }
  101347. /************** End of callback.c ********************************************/
  101348. /************** Begin file delete.c ******************************************/
  101349. /*
  101350. ** 2001 September 15
  101351. **
  101352. ** The author disclaims copyright to this source code. In place of
  101353. ** a legal notice, here is a blessing:
  101354. **
  101355. ** May you do good and not evil.
  101356. ** May you find forgiveness for yourself and forgive others.
  101357. ** May you share freely, never taking more than you give.
  101358. **
  101359. *************************************************************************
  101360. ** This file contains C code routines that are called by the parser
  101361. ** in order to generate code for DELETE FROM statements.
  101362. */
  101363. /* #include "sqliteInt.h" */
  101364. /*
  101365. ** While a SrcList can in general represent multiple tables and subqueries
  101366. ** (as in the FROM clause of a SELECT statement) in this case it contains
  101367. ** the name of a single table, as one might find in an INSERT, DELETE,
  101368. ** or UPDATE statement. Look up that table in the symbol table and
  101369. ** return a pointer. Set an error message and return NULL if the table
  101370. ** name is not found or if any other error occurs.
  101371. **
  101372. ** The following fields are initialized appropriate in pSrc:
  101373. **
  101374. ** pSrc->a[0].pTab Pointer to the Table object
  101375. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  101376. **
  101377. */
  101378. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  101379. struct SrcList_item *pItem = pSrc->a;
  101380. Table *pTab;
  101381. assert( pItem && pSrc->nSrc==1 );
  101382. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  101383. sqlite3DeleteTable(pParse->db, pItem->pTab);
  101384. pItem->pTab = pTab;
  101385. if( pTab ){
  101386. pTab->nTabRef++;
  101387. }
  101388. if( sqlite3IndexedByLookup(pParse, pItem) ){
  101389. pTab = 0;
  101390. }
  101391. return pTab;
  101392. }
  101393. /*
  101394. ** Check to make sure the given table is writable. If it is not
  101395. ** writable, generate an error message and return 1. If it is
  101396. ** writable return 0;
  101397. */
  101398. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  101399. /* A table is not writable under the following circumstances:
  101400. **
  101401. ** 1) It is a virtual table and no implementation of the xUpdate method
  101402. ** has been provided, or
  101403. ** 2) It is a system table (i.e. sqlite_master), this call is not
  101404. ** part of a nested parse and writable_schema pragma has not
  101405. ** been specified.
  101406. **
  101407. ** In either case leave an error message in pParse and return non-zero.
  101408. */
  101409. if( ( IsVirtual(pTab)
  101410. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  101411. || ( (pTab->tabFlags & TF_Readonly)!=0
  101412. && (pParse->db->flags & SQLITE_WriteSchema)==0
  101413. && pParse->nested==0 )
  101414. ){
  101415. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  101416. return 1;
  101417. }
  101418. #ifndef SQLITE_OMIT_VIEW
  101419. if( !viewOk && pTab->pSelect ){
  101420. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  101421. return 1;
  101422. }
  101423. #endif
  101424. return 0;
  101425. }
  101426. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  101427. /*
  101428. ** Evaluate a view and store its result in an ephemeral table. The
  101429. ** pWhere argument is an optional WHERE clause that restricts the
  101430. ** set of rows in the view that are to be added to the ephemeral table.
  101431. */
  101432. SQLITE_PRIVATE void sqlite3MaterializeView(
  101433. Parse *pParse, /* Parsing context */
  101434. Table *pView, /* View definition */
  101435. Expr *pWhere, /* Optional WHERE clause to be added */
  101436. ExprList *pOrderBy, /* Optional ORDER BY clause */
  101437. Expr *pLimit, /* Optional LIMIT clause */
  101438. int iCur /* Cursor number for ephemeral table */
  101439. ){
  101440. SelectDest dest;
  101441. Select *pSel;
  101442. SrcList *pFrom;
  101443. sqlite3 *db = pParse->db;
  101444. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  101445. pWhere = sqlite3ExprDup(db, pWhere, 0);
  101446. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  101447. if( pFrom ){
  101448. assert( pFrom->nSrc==1 );
  101449. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  101450. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
  101451. assert( pFrom->a[0].pOn==0 );
  101452. assert( pFrom->a[0].pUsing==0 );
  101453. }
  101454. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
  101455. SF_IncludeHidden, pLimit);
  101456. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  101457. sqlite3Select(pParse, pSel, &dest);
  101458. sqlite3SelectDelete(db, pSel);
  101459. }
  101460. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  101461. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  101462. /*
  101463. ** Generate an expression tree to implement the WHERE, ORDER BY,
  101464. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  101465. **
  101466. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  101467. ** \__________________________/
  101468. ** pLimitWhere (pInClause)
  101469. */
  101470. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  101471. Parse *pParse, /* The parser context */
  101472. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  101473. Expr *pWhere, /* The WHERE clause. May be null */
  101474. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  101475. Expr *pLimit, /* The LIMIT clause. May be null */
  101476. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  101477. ){
  101478. sqlite3 *db = pParse->db;
  101479. Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */
  101480. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  101481. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  101482. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  101483. Select *pSelect = NULL; /* Complete SELECT tree */
  101484. Table *pTab;
  101485. /* Check that there isn't an ORDER BY without a LIMIT clause.
  101486. */
  101487. if( pOrderBy && pLimit==0 ) {
  101488. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  101489. sqlite3ExprDelete(pParse->db, pWhere);
  101490. sqlite3ExprListDelete(pParse->db, pOrderBy);
  101491. return 0;
  101492. }
  101493. /* We only need to generate a select expression if there
  101494. ** is a limit/offset term to enforce.
  101495. */
  101496. if( pLimit == 0 ) {
  101497. return pWhere;
  101498. }
  101499. /* Generate a select expression tree to enforce the limit/offset
  101500. ** term for the DELETE or UPDATE statement. For example:
  101501. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  101502. ** becomes:
  101503. ** DELETE FROM table_a WHERE rowid IN (
  101504. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  101505. ** );
  101506. */
  101507. pTab = pSrc->a[0].pTab;
  101508. if( HasRowid(pTab) ){
  101509. pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  101510. pEList = sqlite3ExprListAppend(
  101511. pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
  101512. );
  101513. }else{
  101514. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  101515. if( pPk->nKeyCol==1 ){
  101516. const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
  101517. pLhs = sqlite3Expr(db, TK_ID, zName);
  101518. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
  101519. }else{
  101520. int i;
  101521. for(i=0; i<pPk->nKeyCol; i++){
  101522. Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
  101523. pEList = sqlite3ExprListAppend(pParse, pEList, p);
  101524. }
  101525. pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  101526. if( pLhs ){
  101527. pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
  101528. }
  101529. }
  101530. }
  101531. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  101532. ** and the SELECT subtree. */
  101533. pSrc->a[0].pTab = 0;
  101534. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  101535. pSrc->a[0].pTab = pTab;
  101536. pSrc->a[0].pIBIndex = 0;
  101537. /* generate the SELECT expression tree. */
  101538. pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
  101539. pOrderBy,0,pLimit
  101540. );
  101541. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  101542. pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
  101543. sqlite3PExprAddSelect(pParse, pInClause, pSelect);
  101544. return pInClause;
  101545. }
  101546. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  101547. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  101548. /*
  101549. ** Generate code for a DELETE FROM statement.
  101550. **
  101551. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  101552. ** \________/ \________________/
  101553. ** pTabList pWhere
  101554. */
  101555. SQLITE_PRIVATE void sqlite3DeleteFrom(
  101556. Parse *pParse, /* The parser context */
  101557. SrcList *pTabList, /* The table from which we should delete things */
  101558. Expr *pWhere, /* The WHERE clause. May be null */
  101559. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  101560. Expr *pLimit /* LIMIT clause. May be null */
  101561. ){
  101562. Vdbe *v; /* The virtual database engine */
  101563. Table *pTab; /* The table from which records will be deleted */
  101564. int i; /* Loop counter */
  101565. WhereInfo *pWInfo; /* Information about the WHERE clause */
  101566. Index *pIdx; /* For looping over indices of the table */
  101567. int iTabCur; /* Cursor number for the table */
  101568. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  101569. int iIdxCur = 0; /* Cursor number of the first index */
  101570. int nIdx; /* Number of indices */
  101571. sqlite3 *db; /* Main database structure */
  101572. AuthContext sContext; /* Authorization context */
  101573. NameContext sNC; /* Name context to resolve expressions in */
  101574. int iDb; /* Database number */
  101575. int memCnt = -1; /* Memory cell used for change counting */
  101576. int rcauth; /* Value returned by authorization callback */
  101577. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  101578. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  101579. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  101580. Index *pPk; /* The PRIMARY KEY index on the table */
  101581. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  101582. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  101583. int iKey; /* Memory cell holding key of row to be deleted */
  101584. i16 nKey; /* Number of memory cells in the row key */
  101585. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  101586. int iRowSet = 0; /* Register for rowset of rows to delete */
  101587. int addrBypass = 0; /* Address of jump over the delete logic */
  101588. int addrLoop = 0; /* Top of the delete loop */
  101589. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  101590. int bComplex; /* True if there are triggers or FKs or
  101591. ** subqueries in the WHERE clause */
  101592. #ifndef SQLITE_OMIT_TRIGGER
  101593. int isView; /* True if attempting to delete from a view */
  101594. Trigger *pTrigger; /* List of table triggers, if required */
  101595. #endif
  101596. memset(&sContext, 0, sizeof(sContext));
  101597. db = pParse->db;
  101598. if( pParse->nErr || db->mallocFailed ){
  101599. goto delete_from_cleanup;
  101600. }
  101601. assert( pTabList->nSrc==1 );
  101602. /* Locate the table which we want to delete. This table has to be
  101603. ** put in an SrcList structure because some of the subroutines we
  101604. ** will be calling are designed to work with multiple tables and expect
  101605. ** an SrcList* parameter instead of just a Table* parameter.
  101606. */
  101607. pTab = sqlite3SrcListLookup(pParse, pTabList);
  101608. if( pTab==0 ) goto delete_from_cleanup;
  101609. /* Figure out if we have any triggers and if the table being
  101610. ** deleted from is a view
  101611. */
  101612. #ifndef SQLITE_OMIT_TRIGGER
  101613. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  101614. isView = pTab->pSelect!=0;
  101615. #else
  101616. # define pTrigger 0
  101617. # define isView 0
  101618. #endif
  101619. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  101620. #ifdef SQLITE_OMIT_VIEW
  101621. # undef isView
  101622. # define isView 0
  101623. #endif
  101624. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  101625. if( !isView ){
  101626. pWhere = sqlite3LimitWhere(
  101627. pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
  101628. );
  101629. pOrderBy = 0;
  101630. pLimit = 0;
  101631. }
  101632. #endif
  101633. /* If pTab is really a view, make sure it has been initialized.
  101634. */
  101635. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  101636. goto delete_from_cleanup;
  101637. }
  101638. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  101639. goto delete_from_cleanup;
  101640. }
  101641. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  101642. assert( iDb<db->nDb );
  101643. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
  101644. db->aDb[iDb].zDbSName);
  101645. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  101646. if( rcauth==SQLITE_DENY ){
  101647. goto delete_from_cleanup;
  101648. }
  101649. assert(!isView || pTrigger);
  101650. /* Assign cursor numbers to the table and all its indices.
  101651. */
  101652. assert( pTabList->nSrc==1 );
  101653. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  101654. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  101655. pParse->nTab++;
  101656. }
  101657. /* Start the view context
  101658. */
  101659. if( isView ){
  101660. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  101661. }
  101662. /* Begin generating code.
  101663. */
  101664. v = sqlite3GetVdbe(pParse);
  101665. if( v==0 ){
  101666. goto delete_from_cleanup;
  101667. }
  101668. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  101669. sqlite3BeginWriteOperation(pParse, 1, iDb);
  101670. /* If we are trying to delete from a view, realize that view into
  101671. ** an ephemeral table.
  101672. */
  101673. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  101674. if( isView ){
  101675. sqlite3MaterializeView(pParse, pTab,
  101676. pWhere, pOrderBy, pLimit, iTabCur
  101677. );
  101678. iDataCur = iIdxCur = iTabCur;
  101679. pOrderBy = 0;
  101680. pLimit = 0;
  101681. }
  101682. #endif
  101683. /* Resolve the column names in the WHERE clause.
  101684. */
  101685. memset(&sNC, 0, sizeof(sNC));
  101686. sNC.pParse = pParse;
  101687. sNC.pSrcList = pTabList;
  101688. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  101689. goto delete_from_cleanup;
  101690. }
  101691. /* Initialize the counter of the number of rows deleted, if
  101692. ** we are counting rows.
  101693. */
  101694. if( db->flags & SQLITE_CountRows ){
  101695. memCnt = ++pParse->nMem;
  101696. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  101697. }
  101698. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  101699. /* Special case: A DELETE without a WHERE clause deletes everything.
  101700. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  101701. ** this optimization caused the row change count (the value returned by
  101702. ** API function sqlite3_count_changes) to be set incorrectly.
  101703. **
  101704. ** The "rcauth==SQLITE_OK" terms is the
  101705. ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
  101706. ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
  101707. ** the truncate optimization is disabled and all rows are deleted
  101708. ** individually.
  101709. */
  101710. if( rcauth==SQLITE_OK
  101711. && pWhere==0
  101712. && !bComplex
  101713. && !IsVirtual(pTab)
  101714. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  101715. && db->xPreUpdateCallback==0
  101716. #endif
  101717. ){
  101718. assert( !isView );
  101719. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  101720. if( HasRowid(pTab) ){
  101721. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  101722. pTab->zName, P4_STATIC);
  101723. }
  101724. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101725. assert( pIdx->pSchema==pTab->pSchema );
  101726. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  101727. }
  101728. }else
  101729. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  101730. {
  101731. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
  101732. if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
  101733. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  101734. if( HasRowid(pTab) ){
  101735. /* For a rowid table, initialize the RowSet to an empty set */
  101736. pPk = 0;
  101737. nPk = 1;
  101738. iRowSet = ++pParse->nMem;
  101739. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  101740. }else{
  101741. /* For a WITHOUT ROWID table, create an ephemeral table used to
  101742. ** hold all primary keys for rows to be deleted. */
  101743. pPk = sqlite3PrimaryKeyIndex(pTab);
  101744. assert( pPk!=0 );
  101745. nPk = pPk->nKeyCol;
  101746. iPk = pParse->nMem+1;
  101747. pParse->nMem += nPk;
  101748. iEphCur = pParse->nTab++;
  101749. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  101750. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  101751. }
  101752. /* Construct a query to find the rowid or primary key for every row
  101753. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  101754. ** to indicate the strategy used to implement this delete:
  101755. **
  101756. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  101757. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  101758. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  101759. */
  101760. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  101761. if( pWInfo==0 ) goto delete_from_cleanup;
  101762. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  101763. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  101764. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  101765. /* Keep track of the number of rows to be deleted */
  101766. if( db->flags & SQLITE_CountRows ){
  101767. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  101768. }
  101769. /* Extract the rowid or primary key for the current row */
  101770. if( pPk ){
  101771. for(i=0; i<nPk; i++){
  101772. assert( pPk->aiColumn[i]>=0 );
  101773. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  101774. pPk->aiColumn[i], iPk+i);
  101775. }
  101776. iKey = iPk;
  101777. }else{
  101778. iKey = pParse->nMem + 1;
  101779. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  101780. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  101781. }
  101782. if( eOnePass!=ONEPASS_OFF ){
  101783. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  101784. ** one, so just keep it in its register(s) and fall through to the
  101785. ** delete code. */
  101786. nKey = nPk; /* OP_Found will use an unpacked key */
  101787. aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
  101788. if( aToOpen==0 ){
  101789. sqlite3WhereEnd(pWInfo);
  101790. goto delete_from_cleanup;
  101791. }
  101792. memset(aToOpen, 1, nIdx+1);
  101793. aToOpen[nIdx+1] = 0;
  101794. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  101795. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  101796. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  101797. }else{
  101798. if( pPk ){
  101799. /* Add the PK key for this row to the temporary table */
  101800. iKey = ++pParse->nMem;
  101801. nKey = 0; /* Zero tells OP_Found to use a composite key */
  101802. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  101803. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  101804. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
  101805. }else{
  101806. /* Add the rowid of the row to be deleted to the RowSet */
  101807. nKey = 1; /* OP_DeferredSeek always uses a single rowid */
  101808. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  101809. }
  101810. }
  101811. /* If this DELETE cannot use the ONEPASS strategy, this is the
  101812. ** end of the WHERE loop */
  101813. if( eOnePass!=ONEPASS_OFF ){
  101814. addrBypass = sqlite3VdbeMakeLabel(v);
  101815. }else{
  101816. sqlite3WhereEnd(pWInfo);
  101817. }
  101818. /* Unless this is a view, open cursors for the table we are
  101819. ** deleting from and all its indices. If this is a view, then the
  101820. ** only effect this statement has is to fire the INSTEAD OF
  101821. ** triggers.
  101822. */
  101823. if( !isView ){
  101824. int iAddrOnce = 0;
  101825. if( eOnePass==ONEPASS_MULTI ){
  101826. iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  101827. }
  101828. testcase( IsVirtual(pTab) );
  101829. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
  101830. iTabCur, aToOpen, &iDataCur, &iIdxCur);
  101831. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  101832. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  101833. if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
  101834. }
  101835. /* Set up a loop over the rowids/primary-keys that were found in the
  101836. ** where-clause loop above.
  101837. */
  101838. if( eOnePass!=ONEPASS_OFF ){
  101839. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  101840. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  101841. assert( pPk!=0 || pTab->pSelect!=0 );
  101842. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  101843. VdbeCoverage(v);
  101844. }
  101845. }else if( pPk ){
  101846. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  101847. if( IsVirtual(pTab) ){
  101848. sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
  101849. }else{
  101850. sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
  101851. }
  101852. assert( nKey==0 ); /* OP_Found will use a composite key */
  101853. }else{
  101854. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  101855. VdbeCoverage(v);
  101856. assert( nKey==1 );
  101857. }
  101858. /* Delete the row */
  101859. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101860. if( IsVirtual(pTab) ){
  101861. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  101862. sqlite3VtabMakeWritable(pParse, pTab);
  101863. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  101864. sqlite3VdbeChangeP5(v, OE_Abort);
  101865. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  101866. sqlite3MayAbort(pParse);
  101867. if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
  101868. pParse->isMultiWrite = 0;
  101869. }
  101870. }else
  101871. #endif
  101872. {
  101873. int count = (pParse->nested==0); /* True to count changes */
  101874. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  101875. iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
  101876. }
  101877. /* End of the loop over all rowids/primary-keys. */
  101878. if( eOnePass!=ONEPASS_OFF ){
  101879. sqlite3VdbeResolveLabel(v, addrBypass);
  101880. sqlite3WhereEnd(pWInfo);
  101881. }else if( pPk ){
  101882. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  101883. sqlite3VdbeJumpHere(v, addrLoop);
  101884. }else{
  101885. sqlite3VdbeGoto(v, addrLoop);
  101886. sqlite3VdbeJumpHere(v, addrLoop);
  101887. }
  101888. } /* End non-truncate path */
  101889. /* Update the sqlite_sequence table by storing the content of the
  101890. ** maximum rowid counter values recorded while inserting into
  101891. ** autoincrement tables.
  101892. */
  101893. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  101894. sqlite3AutoincrementEnd(pParse);
  101895. }
  101896. /* Return the number of rows that were deleted. If this routine is
  101897. ** generating code because of a call to sqlite3NestedParse(), do not
  101898. ** invoke the callback function.
  101899. */
  101900. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  101901. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  101902. sqlite3VdbeSetNumCols(v, 1);
  101903. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  101904. }
  101905. delete_from_cleanup:
  101906. sqlite3AuthContextPop(&sContext);
  101907. sqlite3SrcListDelete(db, pTabList);
  101908. sqlite3ExprDelete(db, pWhere);
  101909. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  101910. sqlite3ExprListDelete(db, pOrderBy);
  101911. sqlite3ExprDelete(db, pLimit);
  101912. #endif
  101913. sqlite3DbFree(db, aToOpen);
  101914. return;
  101915. }
  101916. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  101917. ** they may interfere with compilation of other functions in this file
  101918. ** (or in another file, if this file becomes part of the amalgamation). */
  101919. #ifdef isView
  101920. #undef isView
  101921. #endif
  101922. #ifdef pTrigger
  101923. #undef pTrigger
  101924. #endif
  101925. /*
  101926. ** This routine generates VDBE code that causes a single row of a
  101927. ** single table to be deleted. Both the original table entry and
  101928. ** all indices are removed.
  101929. **
  101930. ** Preconditions:
  101931. **
  101932. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  101933. ** store for the table. (This will be either the table itself,
  101934. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  101935. ** of a WITHOUT ROWID table.)
  101936. **
  101937. ** 2. Read/write cursors for all indices of pTab must be open as
  101938. ** cursor number iIdxCur+i for the i-th index.
  101939. **
  101940. ** 3. The primary key for the row to be deleted must be stored in a
  101941. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  101942. ** that a search record formed from OP_MakeRecord is contained in the
  101943. ** single memory location iPk.
  101944. **
  101945. ** eMode:
  101946. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  101947. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  101948. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  101949. ** then this function must seek iDataCur to the entry identified by iPk
  101950. ** and nPk before reading from it.
  101951. **
  101952. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  101953. ** of a ONEPASS delete that affects multiple rows. In this case, if
  101954. ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
  101955. ** iDataCur, then its position should be preserved following the delete
  101956. ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
  101957. ** position of iDataCur should be preserved instead.
  101958. **
  101959. ** iIdxNoSeek:
  101960. ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
  101961. ** then it identifies an index cursor (from within array of cursors
  101962. ** starting at iIdxCur) that already points to the index entry to be deleted.
  101963. ** Except, this optimization is disabled if there are BEFORE triggers since
  101964. ** the trigger body might have moved the cursor.
  101965. */
  101966. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  101967. Parse *pParse, /* Parsing context */
  101968. Table *pTab, /* Table containing the row to be deleted */
  101969. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  101970. int iDataCur, /* Cursor from which column data is extracted */
  101971. int iIdxCur, /* First index cursor */
  101972. int iPk, /* First memory cell containing the PRIMARY KEY */
  101973. i16 nPk, /* Number of PRIMARY KEY memory cells */
  101974. u8 count, /* If non-zero, increment the row change counter */
  101975. u8 onconf, /* Default ON CONFLICT policy for triggers */
  101976. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  101977. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  101978. ){
  101979. Vdbe *v = pParse->pVdbe; /* Vdbe */
  101980. int iOld = 0; /* First register in OLD.* array */
  101981. int iLabel; /* Label resolved to end of generated code */
  101982. u8 opSeek; /* Seek opcode */
  101983. /* Vdbe is guaranteed to have been allocated by this stage. */
  101984. assert( v );
  101985. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  101986. iDataCur, iIdxCur, iPk, (int)nPk));
  101987. /* Seek cursor iCur to the row to delete. If this row no longer exists
  101988. ** (this can happen if a trigger program has already deleted it), do
  101989. ** not attempt to delete it or fire any DELETE triggers. */
  101990. iLabel = sqlite3VdbeMakeLabel(v);
  101991. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  101992. if( eMode==ONEPASS_OFF ){
  101993. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  101994. VdbeCoverageIf(v, opSeek==OP_NotExists);
  101995. VdbeCoverageIf(v, opSeek==OP_NotFound);
  101996. }
  101997. /* If there are any triggers to fire, allocate a range of registers to
  101998. ** use for the old.* references in the triggers. */
  101999. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  102000. u32 mask; /* Mask of OLD.* columns in use */
  102001. int iCol; /* Iterator used while populating OLD.* */
  102002. int addrStart; /* Start of BEFORE trigger programs */
  102003. /* TODO: Could use temporary registers here. Also could attempt to
  102004. ** avoid copying the contents of the rowid register. */
  102005. mask = sqlite3TriggerColmask(
  102006. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  102007. );
  102008. mask |= sqlite3FkOldmask(pParse, pTab);
  102009. iOld = pParse->nMem+1;
  102010. pParse->nMem += (1 + pTab->nCol);
  102011. /* Populate the OLD.* pseudo-table register array. These values will be
  102012. ** used by any BEFORE and AFTER triggers that exist. */
  102013. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  102014. for(iCol=0; iCol<pTab->nCol; iCol++){
  102015. testcase( mask!=0xffffffff && iCol==31 );
  102016. testcase( mask!=0xffffffff && iCol==32 );
  102017. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  102018. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  102019. }
  102020. }
  102021. /* Invoke BEFORE DELETE trigger programs. */
  102022. addrStart = sqlite3VdbeCurrentAddr(v);
  102023. sqlite3CodeRowTrigger(pParse, pTrigger,
  102024. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  102025. );
  102026. /* If any BEFORE triggers were coded, then seek the cursor to the
  102027. ** row to be deleted again. It may be that the BEFORE triggers moved
  102028. ** the cursor or already deleted the row that the cursor was
  102029. ** pointing to.
  102030. **
  102031. ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
  102032. ** may have moved that cursor.
  102033. */
  102034. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  102035. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  102036. VdbeCoverageIf(v, opSeek==OP_NotExists);
  102037. VdbeCoverageIf(v, opSeek==OP_NotFound);
  102038. testcase( iIdxNoSeek>=0 );
  102039. iIdxNoSeek = -1;
  102040. }
  102041. /* Do FK processing. This call checks that any FK constraints that
  102042. ** refer to this table (i.e. constraints attached to other tables)
  102043. ** are not violated by deleting this row. */
  102044. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  102045. }
  102046. /* Delete the index and table entries. Skip this step if pTab is really
  102047. ** a view (in which case the only effect of the DELETE statement is to
  102048. ** fire the INSTEAD OF triggers).
  102049. **
  102050. ** If variable 'count' is non-zero, then this OP_Delete instruction should
  102051. ** invoke the update-hook. The pre-update-hook, on the other hand should
  102052. ** be invoked unless table pTab is a system table. The difference is that
  102053. ** the update-hook is not invoked for rows removed by REPLACE, but the
  102054. ** pre-update-hook is.
  102055. */
  102056. if( pTab->pSelect==0 ){
  102057. u8 p5 = 0;
  102058. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  102059. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  102060. if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
  102061. sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
  102062. }
  102063. if( eMode!=ONEPASS_OFF ){
  102064. sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
  102065. }
  102066. if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
  102067. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  102068. }
  102069. if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
  102070. sqlite3VdbeChangeP5(v, p5);
  102071. }
  102072. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  102073. ** handle rows (possibly in other tables) that refer via a foreign key
  102074. ** to the row just deleted. */
  102075. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  102076. /* Invoke AFTER DELETE trigger programs. */
  102077. sqlite3CodeRowTrigger(pParse, pTrigger,
  102078. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  102079. );
  102080. /* Jump here if the row had already been deleted before any BEFORE
  102081. ** trigger programs were invoked. Or if a trigger program throws a
  102082. ** RAISE(IGNORE) exception. */
  102083. sqlite3VdbeResolveLabel(v, iLabel);
  102084. VdbeModuleComment((v, "END: GenRowDel()"));
  102085. }
  102086. /*
  102087. ** This routine generates VDBE code that causes the deletion of all
  102088. ** index entries associated with a single row of a single table, pTab
  102089. **
  102090. ** Preconditions:
  102091. **
  102092. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  102093. ** btree for the table pTab. (This will be either the table itself
  102094. ** for rowid tables or to the primary key index for WITHOUT ROWID
  102095. ** tables.)
  102096. **
  102097. ** 2. Read/write cursors for all indices of pTab must be open as
  102098. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  102099. ** index is the 0-th index.)
  102100. **
  102101. ** 3. The "iDataCur" cursor must be already be positioned on the row
  102102. ** that is to be deleted.
  102103. */
  102104. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  102105. Parse *pParse, /* Parsing and code generating context */
  102106. Table *pTab, /* Table containing the row to be deleted */
  102107. int iDataCur, /* Cursor of table holding data. */
  102108. int iIdxCur, /* First index cursor */
  102109. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  102110. int iIdxNoSeek /* Do not delete from this cursor */
  102111. ){
  102112. int i; /* Index loop counter */
  102113. int r1 = -1; /* Register holding an index key */
  102114. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  102115. Index *pIdx; /* Current index */
  102116. Index *pPrior = 0; /* Prior index */
  102117. Vdbe *v; /* The prepared statement under construction */
  102118. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  102119. v = pParse->pVdbe;
  102120. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  102121. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  102122. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  102123. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  102124. if( pIdx==pPk ) continue;
  102125. if( iIdxCur+i==iIdxNoSeek ) continue;
  102126. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  102127. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  102128. &iPartIdxLabel, pPrior, r1);
  102129. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  102130. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  102131. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  102132. pPrior = pIdx;
  102133. }
  102134. }
  102135. /*
  102136. ** Generate code that will assemble an index key and stores it in register
  102137. ** regOut. The key with be for index pIdx which is an index on pTab.
  102138. ** iCur is the index of a cursor open on the pTab table and pointing to
  102139. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  102140. ** iCur must be the cursor of the PRIMARY KEY index.
  102141. **
  102142. ** Return a register number which is the first in a block of
  102143. ** registers that holds the elements of the index key. The
  102144. ** block of registers has already been deallocated by the time
  102145. ** this routine returns.
  102146. **
  102147. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  102148. ** to that label if pIdx is a partial index that should be skipped.
  102149. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  102150. ** A partial index should be skipped if its WHERE clause evaluates
  102151. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  102152. ** will be set to zero which is an empty label that is ignored by
  102153. ** sqlite3ResolvePartIdxLabel().
  102154. **
  102155. ** The pPrior and regPrior parameters are used to implement a cache to
  102156. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  102157. ** a pointer to a different index for which an index key has just been
  102158. ** computed into register regPrior. If the current pIdx index is generating
  102159. ** its key into the same sequence of registers and if pPrior and pIdx share
  102160. ** a column in common, then the register corresponding to that column already
  102161. ** holds the correct value and the loading of that register is skipped.
  102162. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  102163. ** on a table with multiple indices, and especially with the ROWID or
  102164. ** PRIMARY KEY columns of the index.
  102165. */
  102166. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  102167. Parse *pParse, /* Parsing context */
  102168. Index *pIdx, /* The index for which to generate a key */
  102169. int iDataCur, /* Cursor number from which to take column data */
  102170. int regOut, /* Put the new key into this register if not 0 */
  102171. int prefixOnly, /* Compute only a unique prefix of the key */
  102172. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  102173. Index *pPrior, /* Previously generated index key */
  102174. int regPrior /* Register holding previous generated key */
  102175. ){
  102176. Vdbe *v = pParse->pVdbe;
  102177. int j;
  102178. int regBase;
  102179. int nCol;
  102180. if( piPartIdxLabel ){
  102181. if( pIdx->pPartIdxWhere ){
  102182. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  102183. pParse->iSelfTab = iDataCur + 1;
  102184. sqlite3ExprCachePush(pParse);
  102185. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  102186. SQLITE_JUMPIFNULL);
  102187. pParse->iSelfTab = 0;
  102188. }else{
  102189. *piPartIdxLabel = 0;
  102190. }
  102191. }
  102192. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  102193. regBase = sqlite3GetTempRange(pParse, nCol);
  102194. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  102195. for(j=0; j<nCol; j++){
  102196. if( pPrior
  102197. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  102198. && pPrior->aiColumn[j]!=XN_EXPR
  102199. ){
  102200. /* This column was already computed by the previous index */
  102201. continue;
  102202. }
  102203. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  102204. /* If the column affinity is REAL but the number is an integer, then it
  102205. ** might be stored in the table as an integer (using a compact
  102206. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  102207. ** But we are getting ready to store this value back into an index, where
  102208. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  102209. ** opcode if it is present */
  102210. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  102211. }
  102212. if( regOut ){
  102213. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  102214. if( pIdx->pTable->pSelect ){
  102215. const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
  102216. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  102217. }
  102218. }
  102219. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  102220. return regBase;
  102221. }
  102222. /*
  102223. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  102224. ** because it was a partial index, then this routine should be called to
  102225. ** resolve that label.
  102226. */
  102227. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  102228. if( iLabel ){
  102229. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  102230. sqlite3ExprCachePop(pParse);
  102231. }
  102232. }
  102233. /************** End of delete.c **********************************************/
  102234. /************** Begin file func.c ********************************************/
  102235. /*
  102236. ** 2002 February 23
  102237. **
  102238. ** The author disclaims copyright to this source code. In place of
  102239. ** a legal notice, here is a blessing:
  102240. **
  102241. ** May you do good and not evil.
  102242. ** May you find forgiveness for yourself and forgive others.
  102243. ** May you share freely, never taking more than you give.
  102244. **
  102245. *************************************************************************
  102246. ** This file contains the C-language implementations for many of the SQL
  102247. ** functions of SQLite. (Some function, and in particular the date and
  102248. ** time functions, are implemented separately.)
  102249. */
  102250. /* #include "sqliteInt.h" */
  102251. /* #include <stdlib.h> */
  102252. /* #include <assert.h> */
  102253. /* #include "vdbeInt.h" */
  102254. /*
  102255. ** Return the collating function associated with a function.
  102256. */
  102257. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  102258. VdbeOp *pOp;
  102259. assert( context->pVdbe!=0 );
  102260. pOp = &context->pVdbe->aOp[context->iOp-1];
  102261. assert( pOp->opcode==OP_CollSeq );
  102262. assert( pOp->p4type==P4_COLLSEQ );
  102263. return pOp->p4.pColl;
  102264. }
  102265. /*
  102266. ** Indicate that the accumulator load should be skipped on this
  102267. ** iteration of the aggregate loop.
  102268. */
  102269. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  102270. assert( context->isError<=0 );
  102271. context->isError = -1;
  102272. context->skipFlag = 1;
  102273. }
  102274. /*
  102275. ** Implementation of the non-aggregate min() and max() functions
  102276. */
  102277. static void minmaxFunc(
  102278. sqlite3_context *context,
  102279. int argc,
  102280. sqlite3_value **argv
  102281. ){
  102282. int i;
  102283. int mask; /* 0 for min() or 0xffffffff for max() */
  102284. int iBest;
  102285. CollSeq *pColl;
  102286. assert( argc>1 );
  102287. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  102288. pColl = sqlite3GetFuncCollSeq(context);
  102289. assert( pColl );
  102290. assert( mask==-1 || mask==0 );
  102291. iBest = 0;
  102292. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  102293. for(i=1; i<argc; i++){
  102294. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  102295. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  102296. testcase( mask==0 );
  102297. iBest = i;
  102298. }
  102299. }
  102300. sqlite3_result_value(context, argv[iBest]);
  102301. }
  102302. /*
  102303. ** Return the type of the argument.
  102304. */
  102305. static void typeofFunc(
  102306. sqlite3_context *context,
  102307. int NotUsed,
  102308. sqlite3_value **argv
  102309. ){
  102310. static const char *azType[] = { "integer", "real", "text", "blob", "null" };
  102311. int i = sqlite3_value_type(argv[0]) - 1;
  102312. UNUSED_PARAMETER(NotUsed);
  102313. assert( i>=0 && i<ArraySize(azType) );
  102314. assert( SQLITE_INTEGER==1 );
  102315. assert( SQLITE_FLOAT==2 );
  102316. assert( SQLITE_TEXT==3 );
  102317. assert( SQLITE_BLOB==4 );
  102318. assert( SQLITE_NULL==5 );
  102319. /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
  102320. ** the datatype code for the initial datatype of the sqlite3_value object
  102321. ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
  102322. ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
  102323. sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
  102324. }
  102325. /*
  102326. ** Implementation of the length() function
  102327. */
  102328. static void lengthFunc(
  102329. sqlite3_context *context,
  102330. int argc,
  102331. sqlite3_value **argv
  102332. ){
  102333. assert( argc==1 );
  102334. UNUSED_PARAMETER(argc);
  102335. switch( sqlite3_value_type(argv[0]) ){
  102336. case SQLITE_BLOB:
  102337. case SQLITE_INTEGER:
  102338. case SQLITE_FLOAT: {
  102339. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  102340. break;
  102341. }
  102342. case SQLITE_TEXT: {
  102343. const unsigned char *z = sqlite3_value_text(argv[0]);
  102344. const unsigned char *z0;
  102345. unsigned char c;
  102346. if( z==0 ) return;
  102347. z0 = z;
  102348. while( (c = *z)!=0 ){
  102349. z++;
  102350. if( c>=0xc0 ){
  102351. while( (*z & 0xc0)==0x80 ){ z++; z0++; }
  102352. }
  102353. }
  102354. sqlite3_result_int(context, (int)(z-z0));
  102355. break;
  102356. }
  102357. default: {
  102358. sqlite3_result_null(context);
  102359. break;
  102360. }
  102361. }
  102362. }
  102363. /*
  102364. ** Implementation of the abs() function.
  102365. **
  102366. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  102367. ** the numeric argument X.
  102368. */
  102369. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  102370. assert( argc==1 );
  102371. UNUSED_PARAMETER(argc);
  102372. switch( sqlite3_value_type(argv[0]) ){
  102373. case SQLITE_INTEGER: {
  102374. i64 iVal = sqlite3_value_int64(argv[0]);
  102375. if( iVal<0 ){
  102376. if( iVal==SMALLEST_INT64 ){
  102377. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  102378. ** then abs(X) throws an integer overflow error since there is no
  102379. ** equivalent positive 64-bit two complement value. */
  102380. sqlite3_result_error(context, "integer overflow", -1);
  102381. return;
  102382. }
  102383. iVal = -iVal;
  102384. }
  102385. sqlite3_result_int64(context, iVal);
  102386. break;
  102387. }
  102388. case SQLITE_NULL: {
  102389. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  102390. sqlite3_result_null(context);
  102391. break;
  102392. }
  102393. default: {
  102394. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  102395. ** something that can be converted into a number, we have:
  102396. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  102397. ** that cannot be converted to a numeric value.
  102398. */
  102399. double rVal = sqlite3_value_double(argv[0]);
  102400. if( rVal<0 ) rVal = -rVal;
  102401. sqlite3_result_double(context, rVal);
  102402. break;
  102403. }
  102404. }
  102405. }
  102406. /*
  102407. ** Implementation of the instr() function.
  102408. **
  102409. ** instr(haystack,needle) finds the first occurrence of needle
  102410. ** in haystack and returns the number of previous characters plus 1,
  102411. ** or 0 if needle does not occur within haystack.
  102412. **
  102413. ** If both haystack and needle are BLOBs, then the result is one more than
  102414. ** the number of bytes in haystack prior to the first occurrence of needle,
  102415. ** or 0 if needle never occurs in haystack.
  102416. */
  102417. static void instrFunc(
  102418. sqlite3_context *context,
  102419. int argc,
  102420. sqlite3_value **argv
  102421. ){
  102422. const unsigned char *zHaystack;
  102423. const unsigned char *zNeedle;
  102424. int nHaystack;
  102425. int nNeedle;
  102426. int typeHaystack, typeNeedle;
  102427. int N = 1;
  102428. int isText;
  102429. UNUSED_PARAMETER(argc);
  102430. typeHaystack = sqlite3_value_type(argv[0]);
  102431. typeNeedle = sqlite3_value_type(argv[1]);
  102432. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  102433. nHaystack = sqlite3_value_bytes(argv[0]);
  102434. nNeedle = sqlite3_value_bytes(argv[1]);
  102435. if( nNeedle>0 ){
  102436. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  102437. zHaystack = sqlite3_value_blob(argv[0]);
  102438. zNeedle = sqlite3_value_blob(argv[1]);
  102439. isText = 0;
  102440. }else{
  102441. zHaystack = sqlite3_value_text(argv[0]);
  102442. zNeedle = sqlite3_value_text(argv[1]);
  102443. isText = 1;
  102444. }
  102445. if( zNeedle==0 || (nHaystack && zHaystack==0) ) return;
  102446. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  102447. N++;
  102448. do{
  102449. nHaystack--;
  102450. zHaystack++;
  102451. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  102452. }
  102453. if( nNeedle>nHaystack ) N = 0;
  102454. }
  102455. sqlite3_result_int(context, N);
  102456. }
  102457. /*
  102458. ** Implementation of the printf() function.
  102459. */
  102460. static void printfFunc(
  102461. sqlite3_context *context,
  102462. int argc,
  102463. sqlite3_value **argv
  102464. ){
  102465. PrintfArguments x;
  102466. StrAccum str;
  102467. const char *zFormat;
  102468. int n;
  102469. sqlite3 *db = sqlite3_context_db_handle(context);
  102470. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  102471. x.nArg = argc-1;
  102472. x.nUsed = 0;
  102473. x.apArg = argv+1;
  102474. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  102475. str.printfFlags = SQLITE_PRINTF_SQLFUNC;
  102476. sqlite3XPrintf(&str, zFormat, &x);
  102477. n = str.nChar;
  102478. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  102479. SQLITE_DYNAMIC);
  102480. }
  102481. }
  102482. /*
  102483. ** Implementation of the substr() function.
  102484. **
  102485. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  102486. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  102487. ** of x. If x is text, then we actually count UTF-8 characters.
  102488. ** If x is a blob, then we count bytes.
  102489. **
  102490. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  102491. **
  102492. ** If p2 is negative, return the p2 characters preceding p1.
  102493. */
  102494. static void substrFunc(
  102495. sqlite3_context *context,
  102496. int argc,
  102497. sqlite3_value **argv
  102498. ){
  102499. const unsigned char *z;
  102500. const unsigned char *z2;
  102501. int len;
  102502. int p0type;
  102503. i64 p1, p2;
  102504. int negP2 = 0;
  102505. assert( argc==3 || argc==2 );
  102506. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  102507. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  102508. ){
  102509. return;
  102510. }
  102511. p0type = sqlite3_value_type(argv[0]);
  102512. p1 = sqlite3_value_int(argv[1]);
  102513. if( p0type==SQLITE_BLOB ){
  102514. len = sqlite3_value_bytes(argv[0]);
  102515. z = sqlite3_value_blob(argv[0]);
  102516. if( z==0 ) return;
  102517. assert( len==sqlite3_value_bytes(argv[0]) );
  102518. }else{
  102519. z = sqlite3_value_text(argv[0]);
  102520. if( z==0 ) return;
  102521. len = 0;
  102522. if( p1<0 ){
  102523. for(z2=z; *z2; len++){
  102524. SQLITE_SKIP_UTF8(z2);
  102525. }
  102526. }
  102527. }
  102528. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  102529. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  102530. ** as substr(X,1,N) - it returns the first N characters of X. This
  102531. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  102532. ** from 2009-02-02 for compatibility of applications that exploited the
  102533. ** old buggy behavior. */
  102534. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  102535. #endif
  102536. if( argc==3 ){
  102537. p2 = sqlite3_value_int(argv[2]);
  102538. if( p2<0 ){
  102539. p2 = -p2;
  102540. negP2 = 1;
  102541. }
  102542. }else{
  102543. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  102544. }
  102545. if( p1<0 ){
  102546. p1 += len;
  102547. if( p1<0 ){
  102548. p2 += p1;
  102549. if( p2<0 ) p2 = 0;
  102550. p1 = 0;
  102551. }
  102552. }else if( p1>0 ){
  102553. p1--;
  102554. }else if( p2>0 ){
  102555. p2--;
  102556. }
  102557. if( negP2 ){
  102558. p1 -= p2;
  102559. if( p1<0 ){
  102560. p2 += p1;
  102561. p1 = 0;
  102562. }
  102563. }
  102564. assert( p1>=0 && p2>=0 );
  102565. if( p0type!=SQLITE_BLOB ){
  102566. while( *z && p1 ){
  102567. SQLITE_SKIP_UTF8(z);
  102568. p1--;
  102569. }
  102570. for(z2=z; *z2 && p2; p2--){
  102571. SQLITE_SKIP_UTF8(z2);
  102572. }
  102573. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  102574. SQLITE_UTF8);
  102575. }else{
  102576. if( p1+p2>len ){
  102577. p2 = len-p1;
  102578. if( p2<0 ) p2 = 0;
  102579. }
  102580. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  102581. }
  102582. }
  102583. /*
  102584. ** Implementation of the round() function
  102585. */
  102586. #ifndef SQLITE_OMIT_FLOATING_POINT
  102587. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  102588. int n = 0;
  102589. double r;
  102590. char *zBuf;
  102591. assert( argc==1 || argc==2 );
  102592. if( argc==2 ){
  102593. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  102594. n = sqlite3_value_int(argv[1]);
  102595. if( n>30 ) n = 30;
  102596. if( n<0 ) n = 0;
  102597. }
  102598. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  102599. r = sqlite3_value_double(argv[0]);
  102600. /* If Y==0 and X will fit in a 64-bit int,
  102601. ** handle the rounding directly,
  102602. ** otherwise use printf.
  102603. */
  102604. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  102605. r = (double)((sqlite_int64)(r+0.5));
  102606. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  102607. r = -(double)((sqlite_int64)((-r)+0.5));
  102608. }else{
  102609. zBuf = sqlite3_mprintf("%.*f",n,r);
  102610. if( zBuf==0 ){
  102611. sqlite3_result_error_nomem(context);
  102612. return;
  102613. }
  102614. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  102615. sqlite3_free(zBuf);
  102616. }
  102617. sqlite3_result_double(context, r);
  102618. }
  102619. #endif
  102620. /*
  102621. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  102622. ** allocation fails, call sqlite3_result_error_nomem() to notify
  102623. ** the database handle that malloc() has failed and return NULL.
  102624. ** If nByte is larger than the maximum string or blob length, then
  102625. ** raise an SQLITE_TOOBIG exception and return NULL.
  102626. */
  102627. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  102628. char *z;
  102629. sqlite3 *db = sqlite3_context_db_handle(context);
  102630. assert( nByte>0 );
  102631. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  102632. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  102633. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  102634. sqlite3_result_error_toobig(context);
  102635. z = 0;
  102636. }else{
  102637. z = sqlite3Malloc(nByte);
  102638. if( !z ){
  102639. sqlite3_result_error_nomem(context);
  102640. }
  102641. }
  102642. return z;
  102643. }
  102644. /*
  102645. ** Implementation of the upper() and lower() SQL functions.
  102646. */
  102647. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  102648. char *z1;
  102649. const char *z2;
  102650. int i, n;
  102651. UNUSED_PARAMETER(argc);
  102652. z2 = (char*)sqlite3_value_text(argv[0]);
  102653. n = sqlite3_value_bytes(argv[0]);
  102654. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  102655. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  102656. if( z2 ){
  102657. z1 = contextMalloc(context, ((i64)n)+1);
  102658. if( z1 ){
  102659. for(i=0; i<n; i++){
  102660. z1[i] = (char)sqlite3Toupper(z2[i]);
  102661. }
  102662. sqlite3_result_text(context, z1, n, sqlite3_free);
  102663. }
  102664. }
  102665. }
  102666. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  102667. char *z1;
  102668. const char *z2;
  102669. int i, n;
  102670. UNUSED_PARAMETER(argc);
  102671. z2 = (char*)sqlite3_value_text(argv[0]);
  102672. n = sqlite3_value_bytes(argv[0]);
  102673. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  102674. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  102675. if( z2 ){
  102676. z1 = contextMalloc(context, ((i64)n)+1);
  102677. if( z1 ){
  102678. for(i=0; i<n; i++){
  102679. z1[i] = sqlite3Tolower(z2[i]);
  102680. }
  102681. sqlite3_result_text(context, z1, n, sqlite3_free);
  102682. }
  102683. }
  102684. }
  102685. /*
  102686. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  102687. ** as VDBE code so that unused argument values do not have to be computed.
  102688. ** However, we still need some kind of function implementation for this
  102689. ** routines in the function table. The noopFunc macro provides this.
  102690. ** noopFunc will never be called so it doesn't matter what the implementation
  102691. ** is. We might as well use the "version()" function as a substitute.
  102692. */
  102693. #define noopFunc versionFunc /* Substitute function - never called */
  102694. /*
  102695. ** Implementation of random(). Return a random integer.
  102696. */
  102697. static void randomFunc(
  102698. sqlite3_context *context,
  102699. int NotUsed,
  102700. sqlite3_value **NotUsed2
  102701. ){
  102702. sqlite_int64 r;
  102703. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  102704. sqlite3_randomness(sizeof(r), &r);
  102705. if( r<0 ){
  102706. /* We need to prevent a random number of 0x8000000000000000
  102707. ** (or -9223372036854775808) since when you do abs() of that
  102708. ** number of you get the same value back again. To do this
  102709. ** in a way that is testable, mask the sign bit off of negative
  102710. ** values, resulting in a positive value. Then take the
  102711. ** 2s complement of that positive value. The end result can
  102712. ** therefore be no less than -9223372036854775807.
  102713. */
  102714. r = -(r & LARGEST_INT64);
  102715. }
  102716. sqlite3_result_int64(context, r);
  102717. }
  102718. /*
  102719. ** Implementation of randomblob(N). Return a random blob
  102720. ** that is N bytes long.
  102721. */
  102722. static void randomBlob(
  102723. sqlite3_context *context,
  102724. int argc,
  102725. sqlite3_value **argv
  102726. ){
  102727. int n;
  102728. unsigned char *p;
  102729. assert( argc==1 );
  102730. UNUSED_PARAMETER(argc);
  102731. n = sqlite3_value_int(argv[0]);
  102732. if( n<1 ){
  102733. n = 1;
  102734. }
  102735. p = contextMalloc(context, n);
  102736. if( p ){
  102737. sqlite3_randomness(n, p);
  102738. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  102739. }
  102740. }
  102741. /*
  102742. ** Implementation of the last_insert_rowid() SQL function. The return
  102743. ** value is the same as the sqlite3_last_insert_rowid() API function.
  102744. */
  102745. static void last_insert_rowid(
  102746. sqlite3_context *context,
  102747. int NotUsed,
  102748. sqlite3_value **NotUsed2
  102749. ){
  102750. sqlite3 *db = sqlite3_context_db_handle(context);
  102751. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  102752. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  102753. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  102754. ** function. */
  102755. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  102756. }
  102757. /*
  102758. ** Implementation of the changes() SQL function.
  102759. **
  102760. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  102761. ** around the sqlite3_changes() C/C++ function and hence follows the same
  102762. ** rules for counting changes.
  102763. */
  102764. static void changes(
  102765. sqlite3_context *context,
  102766. int NotUsed,
  102767. sqlite3_value **NotUsed2
  102768. ){
  102769. sqlite3 *db = sqlite3_context_db_handle(context);
  102770. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  102771. sqlite3_result_int(context, sqlite3_changes(db));
  102772. }
  102773. /*
  102774. ** Implementation of the total_changes() SQL function. The return value is
  102775. ** the same as the sqlite3_total_changes() API function.
  102776. */
  102777. static void total_changes(
  102778. sqlite3_context *context,
  102779. int NotUsed,
  102780. sqlite3_value **NotUsed2
  102781. ){
  102782. sqlite3 *db = sqlite3_context_db_handle(context);
  102783. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  102784. /* IMP: R-52756-41993 This function is a wrapper around the
  102785. ** sqlite3_total_changes() C/C++ interface. */
  102786. sqlite3_result_int(context, sqlite3_total_changes(db));
  102787. }
  102788. /*
  102789. ** A structure defining how to do GLOB-style comparisons.
  102790. */
  102791. struct compareInfo {
  102792. u8 matchAll; /* "*" or "%" */
  102793. u8 matchOne; /* "?" or "_" */
  102794. u8 matchSet; /* "[" or 0 */
  102795. u8 noCase; /* true to ignore case differences */
  102796. };
  102797. /*
  102798. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  102799. ** character is exactly one byte in size. Also, provde the Utf8Read()
  102800. ** macro for fast reading of the next character in the common case where
  102801. ** the next character is ASCII.
  102802. */
  102803. #if defined(SQLITE_EBCDIC)
  102804. # define sqlite3Utf8Read(A) (*((*A)++))
  102805. # define Utf8Read(A) (*(A++))
  102806. #else
  102807. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  102808. #endif
  102809. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  102810. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  102811. ** case. Thus 'a' LIKE 'A' would be true. */
  102812. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  102813. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  102814. ** is case sensitive causing 'a' LIKE 'A' to be false */
  102815. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  102816. /*
  102817. ** Possible error returns from patternMatch()
  102818. */
  102819. #define SQLITE_MATCH 0
  102820. #define SQLITE_NOMATCH 1
  102821. #define SQLITE_NOWILDCARDMATCH 2
  102822. /*
  102823. ** Compare two UTF-8 strings for equality where the first string is
  102824. ** a GLOB or LIKE expression. Return values:
  102825. **
  102826. ** SQLITE_MATCH: Match
  102827. ** SQLITE_NOMATCH: No match
  102828. ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
  102829. **
  102830. ** Globbing rules:
  102831. **
  102832. ** '*' Matches any sequence of zero or more characters.
  102833. **
  102834. ** '?' Matches exactly one character.
  102835. **
  102836. ** [...] Matches one character from the enclosed list of
  102837. ** characters.
  102838. **
  102839. ** [^...] Matches one character not in the enclosed list.
  102840. **
  102841. ** With the [...] and [^...] matching, a ']' character can be included
  102842. ** in the list by making it the first character after '[' or '^'. A
  102843. ** range of characters can be specified using '-'. Example:
  102844. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  102845. ** it the last character in the list.
  102846. **
  102847. ** Like matching rules:
  102848. **
  102849. ** '%' Matches any sequence of zero or more characters
  102850. **
  102851. *** '_' Matches any one character
  102852. **
  102853. ** Ec Where E is the "esc" character and c is any other
  102854. ** character, including '%', '_', and esc, match exactly c.
  102855. **
  102856. ** The comments within this routine usually assume glob matching.
  102857. **
  102858. ** This routine is usually quick, but can be N**2 in the worst case.
  102859. */
  102860. static int patternCompare(
  102861. const u8 *zPattern, /* The glob pattern */
  102862. const u8 *zString, /* The string to compare against the glob */
  102863. const struct compareInfo *pInfo, /* Information about how to do the compare */
  102864. u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
  102865. ){
  102866. u32 c, c2; /* Next pattern and input string chars */
  102867. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  102868. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  102869. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  102870. const u8 *zEscaped = 0; /* One past the last escaped input char */
  102871. while( (c = Utf8Read(zPattern))!=0 ){
  102872. if( c==matchAll ){ /* Match "*" */
  102873. /* Skip over multiple "*" characters in the pattern. If there
  102874. ** are also "?" characters, skip those as well, but consume a
  102875. ** single character of the input string for each "?" skipped */
  102876. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  102877. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  102878. return SQLITE_NOWILDCARDMATCH;
  102879. }
  102880. }
  102881. if( c==0 ){
  102882. return SQLITE_MATCH; /* "*" at the end of the pattern matches */
  102883. }else if( c==matchOther ){
  102884. if( pInfo->matchSet==0 ){
  102885. c = sqlite3Utf8Read(&zPattern);
  102886. if( c==0 ) return SQLITE_NOWILDCARDMATCH;
  102887. }else{
  102888. /* "[...]" immediately follows the "*". We have to do a slow
  102889. ** recursive search in this case, but it is an unusual case. */
  102890. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  102891. while( *zString ){
  102892. int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
  102893. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  102894. SQLITE_SKIP_UTF8(zString);
  102895. }
  102896. return SQLITE_NOWILDCARDMATCH;
  102897. }
  102898. }
  102899. /* At this point variable c contains the first character of the
  102900. ** pattern string past the "*". Search in the input string for the
  102901. ** first matching character and recursively continue the match from
  102902. ** that point.
  102903. **
  102904. ** For a case-insensitive search, set variable cx to be the same as
  102905. ** c but in the other case and search the input string for either
  102906. ** c or cx.
  102907. */
  102908. if( c<=0x80 ){
  102909. char zStop[3];
  102910. int bMatch;
  102911. if( noCase ){
  102912. zStop[0] = sqlite3Toupper(c);
  102913. zStop[1] = sqlite3Tolower(c);
  102914. zStop[2] = 0;
  102915. }else{
  102916. zStop[0] = c;
  102917. zStop[1] = 0;
  102918. }
  102919. while(1){
  102920. zString += strcspn((const char*)zString, zStop);
  102921. if( zString[0]==0 ) break;
  102922. zString++;
  102923. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  102924. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  102925. }
  102926. }else{
  102927. int bMatch;
  102928. while( (c2 = Utf8Read(zString))!=0 ){
  102929. if( c2!=c ) continue;
  102930. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  102931. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  102932. }
  102933. }
  102934. return SQLITE_NOWILDCARDMATCH;
  102935. }
  102936. if( c==matchOther ){
  102937. if( pInfo->matchSet==0 ){
  102938. c = sqlite3Utf8Read(&zPattern);
  102939. if( c==0 ) return SQLITE_NOMATCH;
  102940. zEscaped = zPattern;
  102941. }else{
  102942. u32 prior_c = 0;
  102943. int seen = 0;
  102944. int invert = 0;
  102945. c = sqlite3Utf8Read(&zString);
  102946. if( c==0 ) return SQLITE_NOMATCH;
  102947. c2 = sqlite3Utf8Read(&zPattern);
  102948. if( c2=='^' ){
  102949. invert = 1;
  102950. c2 = sqlite3Utf8Read(&zPattern);
  102951. }
  102952. if( c2==']' ){
  102953. if( c==']' ) seen = 1;
  102954. c2 = sqlite3Utf8Read(&zPattern);
  102955. }
  102956. while( c2 && c2!=']' ){
  102957. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  102958. c2 = sqlite3Utf8Read(&zPattern);
  102959. if( c>=prior_c && c<=c2 ) seen = 1;
  102960. prior_c = 0;
  102961. }else{
  102962. if( c==c2 ){
  102963. seen = 1;
  102964. }
  102965. prior_c = c2;
  102966. }
  102967. c2 = sqlite3Utf8Read(&zPattern);
  102968. }
  102969. if( c2==0 || (seen ^ invert)==0 ){
  102970. return SQLITE_NOMATCH;
  102971. }
  102972. continue;
  102973. }
  102974. }
  102975. c2 = Utf8Read(zString);
  102976. if( c==c2 ) continue;
  102977. if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
  102978. continue;
  102979. }
  102980. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  102981. return SQLITE_NOMATCH;
  102982. }
  102983. return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
  102984. }
  102985. /*
  102986. ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
  102987. ** non-zero if there is no match.
  102988. */
  102989. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  102990. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
  102991. }
  102992. /*
  102993. ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
  102994. ** a miss - like strcmp().
  102995. */
  102996. SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  102997. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
  102998. }
  102999. /*
  103000. ** Count the number of times that the LIKE operator (or GLOB which is
  103001. ** just a variation of LIKE) gets called. This is used for testing
  103002. ** only.
  103003. */
  103004. #ifdef SQLITE_TEST
  103005. SQLITE_API int sqlite3_like_count = 0;
  103006. #endif
  103007. /*
  103008. ** Implementation of the like() SQL function. This function implements
  103009. ** the build-in LIKE operator. The first argument to the function is the
  103010. ** pattern and the second argument is the string. So, the SQL statements:
  103011. **
  103012. ** A LIKE B
  103013. **
  103014. ** is implemented as like(B,A).
  103015. **
  103016. ** This same function (with a different compareInfo structure) computes
  103017. ** the GLOB operator.
  103018. */
  103019. static void likeFunc(
  103020. sqlite3_context *context,
  103021. int argc,
  103022. sqlite3_value **argv
  103023. ){
  103024. const unsigned char *zA, *zB;
  103025. u32 escape;
  103026. int nPat;
  103027. sqlite3 *db = sqlite3_context_db_handle(context);
  103028. struct compareInfo *pInfo = sqlite3_user_data(context);
  103029. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  103030. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  103031. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  103032. ){
  103033. #ifdef SQLITE_TEST
  103034. sqlite3_like_count++;
  103035. #endif
  103036. sqlite3_result_int(context, 0);
  103037. return;
  103038. }
  103039. #endif
  103040. zB = sqlite3_value_text(argv[0]);
  103041. zA = sqlite3_value_text(argv[1]);
  103042. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  103043. ** of deep recursion and N*N behavior in patternCompare().
  103044. */
  103045. nPat = sqlite3_value_bytes(argv[0]);
  103046. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  103047. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  103048. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  103049. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  103050. return;
  103051. }
  103052. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  103053. if( argc==3 ){
  103054. /* The escape character string must consist of a single UTF-8 character.
  103055. ** Otherwise, return an error.
  103056. */
  103057. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  103058. if( zEsc==0 ) return;
  103059. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  103060. sqlite3_result_error(context,
  103061. "ESCAPE expression must be a single character", -1);
  103062. return;
  103063. }
  103064. escape = sqlite3Utf8Read(&zEsc);
  103065. }else{
  103066. escape = pInfo->matchSet;
  103067. }
  103068. if( zA && zB ){
  103069. #ifdef SQLITE_TEST
  103070. sqlite3_like_count++;
  103071. #endif
  103072. sqlite3_result_int(context,
  103073. patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
  103074. }
  103075. }
  103076. /*
  103077. ** Implementation of the NULLIF(x,y) function. The result is the first
  103078. ** argument if the arguments are different. The result is NULL if the
  103079. ** arguments are equal to each other.
  103080. */
  103081. static void nullifFunc(
  103082. sqlite3_context *context,
  103083. int NotUsed,
  103084. sqlite3_value **argv
  103085. ){
  103086. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  103087. UNUSED_PARAMETER(NotUsed);
  103088. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  103089. sqlite3_result_value(context, argv[0]);
  103090. }
  103091. }
  103092. /*
  103093. ** Implementation of the sqlite_version() function. The result is the version
  103094. ** of the SQLite library that is running.
  103095. */
  103096. static void versionFunc(
  103097. sqlite3_context *context,
  103098. int NotUsed,
  103099. sqlite3_value **NotUsed2
  103100. ){
  103101. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  103102. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  103103. ** sqlite3_libversion() C-interface. */
  103104. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  103105. }
  103106. /*
  103107. ** Implementation of the sqlite_source_id() function. The result is a string
  103108. ** that identifies the particular version of the source code used to build
  103109. ** SQLite.
  103110. */
  103111. static void sourceidFunc(
  103112. sqlite3_context *context,
  103113. int NotUsed,
  103114. sqlite3_value **NotUsed2
  103115. ){
  103116. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  103117. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  103118. ** sqlite3_sourceid() C interface. */
  103119. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  103120. }
  103121. /*
  103122. ** Implementation of the sqlite_log() function. This is a wrapper around
  103123. ** sqlite3_log(). The return value is NULL. The function exists purely for
  103124. ** its side-effects.
  103125. */
  103126. static void errlogFunc(
  103127. sqlite3_context *context,
  103128. int argc,
  103129. sqlite3_value **argv
  103130. ){
  103131. UNUSED_PARAMETER(argc);
  103132. UNUSED_PARAMETER(context);
  103133. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  103134. }
  103135. /*
  103136. ** Implementation of the sqlite_compileoption_used() function.
  103137. ** The result is an integer that identifies if the compiler option
  103138. ** was used to build SQLite.
  103139. */
  103140. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  103141. static void compileoptionusedFunc(
  103142. sqlite3_context *context,
  103143. int argc,
  103144. sqlite3_value **argv
  103145. ){
  103146. const char *zOptName;
  103147. assert( argc==1 );
  103148. UNUSED_PARAMETER(argc);
  103149. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  103150. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  103151. ** function.
  103152. */
  103153. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  103154. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  103155. }
  103156. }
  103157. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  103158. /*
  103159. ** Implementation of the sqlite_compileoption_get() function.
  103160. ** The result is a string that identifies the compiler options
  103161. ** used to build SQLite.
  103162. */
  103163. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  103164. static void compileoptiongetFunc(
  103165. sqlite3_context *context,
  103166. int argc,
  103167. sqlite3_value **argv
  103168. ){
  103169. int n;
  103170. assert( argc==1 );
  103171. UNUSED_PARAMETER(argc);
  103172. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  103173. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  103174. */
  103175. n = sqlite3_value_int(argv[0]);
  103176. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  103177. }
  103178. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  103179. /* Array for converting from half-bytes (nybbles) into ASCII hex
  103180. ** digits. */
  103181. static const char hexdigits[] = {
  103182. '0', '1', '2', '3', '4', '5', '6', '7',
  103183. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  103184. };
  103185. /*
  103186. ** Implementation of the QUOTE() function. This function takes a single
  103187. ** argument. If the argument is numeric, the return value is the same as
  103188. ** the argument. If the argument is NULL, the return value is the string
  103189. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  103190. ** single-quote escapes.
  103191. */
  103192. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  103193. assert( argc==1 );
  103194. UNUSED_PARAMETER(argc);
  103195. switch( sqlite3_value_type(argv[0]) ){
  103196. case SQLITE_FLOAT: {
  103197. double r1, r2;
  103198. char zBuf[50];
  103199. r1 = sqlite3_value_double(argv[0]);
  103200. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  103201. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  103202. if( r1!=r2 ){
  103203. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  103204. }
  103205. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  103206. break;
  103207. }
  103208. case SQLITE_INTEGER: {
  103209. sqlite3_result_value(context, argv[0]);
  103210. break;
  103211. }
  103212. case SQLITE_BLOB: {
  103213. char *zText = 0;
  103214. char const *zBlob = sqlite3_value_blob(argv[0]);
  103215. int nBlob = sqlite3_value_bytes(argv[0]);
  103216. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  103217. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  103218. if( zText ){
  103219. int i;
  103220. for(i=0; i<nBlob; i++){
  103221. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  103222. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  103223. }
  103224. zText[(nBlob*2)+2] = '\'';
  103225. zText[(nBlob*2)+3] = '\0';
  103226. zText[0] = 'X';
  103227. zText[1] = '\'';
  103228. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  103229. sqlite3_free(zText);
  103230. }
  103231. break;
  103232. }
  103233. case SQLITE_TEXT: {
  103234. int i,j;
  103235. u64 n;
  103236. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  103237. char *z;
  103238. if( zArg==0 ) return;
  103239. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  103240. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  103241. if( z ){
  103242. z[0] = '\'';
  103243. for(i=0, j=1; zArg[i]; i++){
  103244. z[j++] = zArg[i];
  103245. if( zArg[i]=='\'' ){
  103246. z[j++] = '\'';
  103247. }
  103248. }
  103249. z[j++] = '\'';
  103250. z[j] = 0;
  103251. sqlite3_result_text(context, z, j, sqlite3_free);
  103252. }
  103253. break;
  103254. }
  103255. default: {
  103256. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  103257. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  103258. break;
  103259. }
  103260. }
  103261. }
  103262. /*
  103263. ** The unicode() function. Return the integer unicode code-point value
  103264. ** for the first character of the input string.
  103265. */
  103266. static void unicodeFunc(
  103267. sqlite3_context *context,
  103268. int argc,
  103269. sqlite3_value **argv
  103270. ){
  103271. const unsigned char *z = sqlite3_value_text(argv[0]);
  103272. (void)argc;
  103273. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  103274. }
  103275. /*
  103276. ** The char() function takes zero or more arguments, each of which is
  103277. ** an integer. It constructs a string where each character of the string
  103278. ** is the unicode character for the corresponding integer argument.
  103279. */
  103280. static void charFunc(
  103281. sqlite3_context *context,
  103282. int argc,
  103283. sqlite3_value **argv
  103284. ){
  103285. unsigned char *z, *zOut;
  103286. int i;
  103287. zOut = z = sqlite3_malloc64( argc*4+1 );
  103288. if( z==0 ){
  103289. sqlite3_result_error_nomem(context);
  103290. return;
  103291. }
  103292. for(i=0; i<argc; i++){
  103293. sqlite3_int64 x;
  103294. unsigned c;
  103295. x = sqlite3_value_int64(argv[i]);
  103296. if( x<0 || x>0x10ffff ) x = 0xfffd;
  103297. c = (unsigned)(x & 0x1fffff);
  103298. if( c<0x00080 ){
  103299. *zOut++ = (u8)(c&0xFF);
  103300. }else if( c<0x00800 ){
  103301. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  103302. *zOut++ = 0x80 + (u8)(c & 0x3F);
  103303. }else if( c<0x10000 ){
  103304. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  103305. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  103306. *zOut++ = 0x80 + (u8)(c & 0x3F);
  103307. }else{
  103308. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  103309. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  103310. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  103311. *zOut++ = 0x80 + (u8)(c & 0x3F);
  103312. } \
  103313. }
  103314. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  103315. }
  103316. /*
  103317. ** The hex() function. Interpret the argument as a blob. Return
  103318. ** a hexadecimal rendering as text.
  103319. */
  103320. static void hexFunc(
  103321. sqlite3_context *context,
  103322. int argc,
  103323. sqlite3_value **argv
  103324. ){
  103325. int i, n;
  103326. const unsigned char *pBlob;
  103327. char *zHex, *z;
  103328. assert( argc==1 );
  103329. UNUSED_PARAMETER(argc);
  103330. pBlob = sqlite3_value_blob(argv[0]);
  103331. n = sqlite3_value_bytes(argv[0]);
  103332. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  103333. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  103334. if( zHex ){
  103335. for(i=0; i<n; i++, pBlob++){
  103336. unsigned char c = *pBlob;
  103337. *(z++) = hexdigits[(c>>4)&0xf];
  103338. *(z++) = hexdigits[c&0xf];
  103339. }
  103340. *z = 0;
  103341. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  103342. }
  103343. }
  103344. /*
  103345. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  103346. */
  103347. static void zeroblobFunc(
  103348. sqlite3_context *context,
  103349. int argc,
  103350. sqlite3_value **argv
  103351. ){
  103352. i64 n;
  103353. int rc;
  103354. assert( argc==1 );
  103355. UNUSED_PARAMETER(argc);
  103356. n = sqlite3_value_int64(argv[0]);
  103357. if( n<0 ) n = 0;
  103358. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  103359. if( rc ){
  103360. sqlite3_result_error_code(context, rc);
  103361. }
  103362. }
  103363. /*
  103364. ** The replace() function. Three arguments are all strings: call
  103365. ** them A, B, and C. The result is also a string which is derived
  103366. ** from A by replacing every occurrence of B with C. The match
  103367. ** must be exact. Collating sequences are not used.
  103368. */
  103369. static void replaceFunc(
  103370. sqlite3_context *context,
  103371. int argc,
  103372. sqlite3_value **argv
  103373. ){
  103374. const unsigned char *zStr; /* The input string A */
  103375. const unsigned char *zPattern; /* The pattern string B */
  103376. const unsigned char *zRep; /* The replacement string C */
  103377. unsigned char *zOut; /* The output */
  103378. int nStr; /* Size of zStr */
  103379. int nPattern; /* Size of zPattern */
  103380. int nRep; /* Size of zRep */
  103381. i64 nOut; /* Maximum size of zOut */
  103382. int loopLimit; /* Last zStr[] that might match zPattern[] */
  103383. int i, j; /* Loop counters */
  103384. unsigned cntExpand; /* Number zOut expansions */
  103385. sqlite3 *db = sqlite3_context_db_handle(context);
  103386. assert( argc==3 );
  103387. UNUSED_PARAMETER(argc);
  103388. zStr = sqlite3_value_text(argv[0]);
  103389. if( zStr==0 ) return;
  103390. nStr = sqlite3_value_bytes(argv[0]);
  103391. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  103392. zPattern = sqlite3_value_text(argv[1]);
  103393. if( zPattern==0 ){
  103394. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  103395. || sqlite3_context_db_handle(context)->mallocFailed );
  103396. return;
  103397. }
  103398. if( zPattern[0]==0 ){
  103399. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  103400. sqlite3_result_value(context, argv[0]);
  103401. return;
  103402. }
  103403. nPattern = sqlite3_value_bytes(argv[1]);
  103404. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  103405. zRep = sqlite3_value_text(argv[2]);
  103406. if( zRep==0 ) return;
  103407. nRep = sqlite3_value_bytes(argv[2]);
  103408. assert( zRep==sqlite3_value_text(argv[2]) );
  103409. nOut = nStr + 1;
  103410. assert( nOut<SQLITE_MAX_LENGTH );
  103411. zOut = contextMalloc(context, (i64)nOut);
  103412. if( zOut==0 ){
  103413. return;
  103414. }
  103415. loopLimit = nStr - nPattern;
  103416. cntExpand = 0;
  103417. for(i=j=0; i<=loopLimit; i++){
  103418. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  103419. zOut[j++] = zStr[i];
  103420. }else{
  103421. if( nRep>nPattern ){
  103422. nOut += nRep - nPattern;
  103423. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  103424. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  103425. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  103426. sqlite3_result_error_toobig(context);
  103427. sqlite3_free(zOut);
  103428. return;
  103429. }
  103430. cntExpand++;
  103431. if( (cntExpand&(cntExpand-1))==0 ){
  103432. /* Grow the size of the output buffer only on substitutions
  103433. ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
  103434. u8 *zOld;
  103435. zOld = zOut;
  103436. zOut = sqlite3_realloc64(zOut, (int)nOut + (nOut - nStr - 1));
  103437. if( zOut==0 ){
  103438. sqlite3_result_error_nomem(context);
  103439. sqlite3_free(zOld);
  103440. return;
  103441. }
  103442. }
  103443. }
  103444. memcpy(&zOut[j], zRep, nRep);
  103445. j += nRep;
  103446. i += nPattern-1;
  103447. }
  103448. }
  103449. assert( j+nStr-i+1<=nOut );
  103450. memcpy(&zOut[j], &zStr[i], nStr-i);
  103451. j += nStr - i;
  103452. assert( j<=nOut );
  103453. zOut[j] = 0;
  103454. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  103455. }
  103456. /*
  103457. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  103458. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  103459. */
  103460. static void trimFunc(
  103461. sqlite3_context *context,
  103462. int argc,
  103463. sqlite3_value **argv
  103464. ){
  103465. const unsigned char *zIn; /* Input string */
  103466. const unsigned char *zCharSet; /* Set of characters to trim */
  103467. int nIn; /* Number of bytes in input */
  103468. int flags; /* 1: trimleft 2: trimright 3: trim */
  103469. int i; /* Loop counter */
  103470. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  103471. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  103472. int nChar; /* Number of characters in zCharSet */
  103473. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  103474. return;
  103475. }
  103476. zIn = sqlite3_value_text(argv[0]);
  103477. if( zIn==0 ) return;
  103478. nIn = sqlite3_value_bytes(argv[0]);
  103479. assert( zIn==sqlite3_value_text(argv[0]) );
  103480. if( argc==1 ){
  103481. static const unsigned char lenOne[] = { 1 };
  103482. static unsigned char * const azOne[] = { (u8*)" " };
  103483. nChar = 1;
  103484. aLen = (u8*)lenOne;
  103485. azChar = (unsigned char **)azOne;
  103486. zCharSet = 0;
  103487. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  103488. return;
  103489. }else{
  103490. const unsigned char *z;
  103491. for(z=zCharSet, nChar=0; *z; nChar++){
  103492. SQLITE_SKIP_UTF8(z);
  103493. }
  103494. if( nChar>0 ){
  103495. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  103496. if( azChar==0 ){
  103497. return;
  103498. }
  103499. aLen = (unsigned char*)&azChar[nChar];
  103500. for(z=zCharSet, nChar=0; *z; nChar++){
  103501. azChar[nChar] = (unsigned char *)z;
  103502. SQLITE_SKIP_UTF8(z);
  103503. aLen[nChar] = (u8)(z - azChar[nChar]);
  103504. }
  103505. }
  103506. }
  103507. if( nChar>0 ){
  103508. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  103509. if( flags & 1 ){
  103510. while( nIn>0 ){
  103511. int len = 0;
  103512. for(i=0; i<nChar; i++){
  103513. len = aLen[i];
  103514. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  103515. }
  103516. if( i>=nChar ) break;
  103517. zIn += len;
  103518. nIn -= len;
  103519. }
  103520. }
  103521. if( flags & 2 ){
  103522. while( nIn>0 ){
  103523. int len = 0;
  103524. for(i=0; i<nChar; i++){
  103525. len = aLen[i];
  103526. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  103527. }
  103528. if( i>=nChar ) break;
  103529. nIn -= len;
  103530. }
  103531. }
  103532. if( zCharSet ){
  103533. sqlite3_free(azChar);
  103534. }
  103535. }
  103536. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  103537. }
  103538. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  103539. /*
  103540. ** The "unknown" function is automatically substituted in place of
  103541. ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
  103542. ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
  103543. ** When the "sqlite3" command-line shell is built using this functionality,
  103544. ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
  103545. ** involving application-defined functions to be examined in a generic
  103546. ** sqlite3 shell.
  103547. */
  103548. static void unknownFunc(
  103549. sqlite3_context *context,
  103550. int argc,
  103551. sqlite3_value **argv
  103552. ){
  103553. /* no-op */
  103554. }
  103555. #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
  103556. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  103557. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  103558. ** when SQLite is built.
  103559. */
  103560. #ifdef SQLITE_SOUNDEX
  103561. /*
  103562. ** Compute the soundex encoding of a word.
  103563. **
  103564. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  103565. ** soundex encoding of the string X.
  103566. */
  103567. static void soundexFunc(
  103568. sqlite3_context *context,
  103569. int argc,
  103570. sqlite3_value **argv
  103571. ){
  103572. char zResult[8];
  103573. const u8 *zIn;
  103574. int i, j;
  103575. static const unsigned char iCode[] = {
  103576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  103577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  103578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  103579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  103580. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  103581. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  103582. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  103583. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  103584. };
  103585. assert( argc==1 );
  103586. zIn = (u8*)sqlite3_value_text(argv[0]);
  103587. if( zIn==0 ) zIn = (u8*)"";
  103588. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  103589. if( zIn[i] ){
  103590. u8 prevcode = iCode[zIn[i]&0x7f];
  103591. zResult[0] = sqlite3Toupper(zIn[i]);
  103592. for(j=1; j<4 && zIn[i]; i++){
  103593. int code = iCode[zIn[i]&0x7f];
  103594. if( code>0 ){
  103595. if( code!=prevcode ){
  103596. prevcode = code;
  103597. zResult[j++] = code + '0';
  103598. }
  103599. }else{
  103600. prevcode = 0;
  103601. }
  103602. }
  103603. while( j<4 ){
  103604. zResult[j++] = '0';
  103605. }
  103606. zResult[j] = 0;
  103607. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  103608. }else{
  103609. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  103610. ** is NULL or contains no ASCII alphabetic characters. */
  103611. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  103612. }
  103613. }
  103614. #endif /* SQLITE_SOUNDEX */
  103615. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  103616. /*
  103617. ** A function that loads a shared-library extension then returns NULL.
  103618. */
  103619. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  103620. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  103621. const char *zProc;
  103622. sqlite3 *db = sqlite3_context_db_handle(context);
  103623. char *zErrMsg = 0;
  103624. /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
  103625. ** flag is set. See the sqlite3_enable_load_extension() API.
  103626. */
  103627. if( (db->flags & SQLITE_LoadExtFunc)==0 ){
  103628. sqlite3_result_error(context, "not authorized", -1);
  103629. return;
  103630. }
  103631. if( argc==2 ){
  103632. zProc = (const char *)sqlite3_value_text(argv[1]);
  103633. }else{
  103634. zProc = 0;
  103635. }
  103636. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  103637. sqlite3_result_error(context, zErrMsg, -1);
  103638. sqlite3_free(zErrMsg);
  103639. }
  103640. }
  103641. #endif
  103642. /*
  103643. ** An instance of the following structure holds the context of a
  103644. ** sum() or avg() aggregate computation.
  103645. */
  103646. typedef struct SumCtx SumCtx;
  103647. struct SumCtx {
  103648. double rSum; /* Floating point sum */
  103649. i64 iSum; /* Integer sum */
  103650. i64 cnt; /* Number of elements summed */
  103651. u8 overflow; /* True if integer overflow seen */
  103652. u8 approx; /* True if non-integer value was input to the sum */
  103653. };
  103654. /*
  103655. ** Routines used to compute the sum, average, and total.
  103656. **
  103657. ** The SUM() function follows the (broken) SQL standard which means
  103658. ** that it returns NULL if it sums over no inputs. TOTAL returns
  103659. ** 0.0 in that case. In addition, TOTAL always returns a float where
  103660. ** SUM might return an integer if it never encounters a floating point
  103661. ** value. TOTAL never fails, but SUM might through an exception if
  103662. ** it overflows an integer.
  103663. */
  103664. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  103665. SumCtx *p;
  103666. int type;
  103667. assert( argc==1 );
  103668. UNUSED_PARAMETER(argc);
  103669. p = sqlite3_aggregate_context(context, sizeof(*p));
  103670. type = sqlite3_value_numeric_type(argv[0]);
  103671. if( p && type!=SQLITE_NULL ){
  103672. p->cnt++;
  103673. if( type==SQLITE_INTEGER ){
  103674. i64 v = sqlite3_value_int64(argv[0]);
  103675. p->rSum += v;
  103676. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  103677. p->overflow = 1;
  103678. }
  103679. }else{
  103680. p->rSum += sqlite3_value_double(argv[0]);
  103681. p->approx = 1;
  103682. }
  103683. }
  103684. }
  103685. static void sumFinalize(sqlite3_context *context){
  103686. SumCtx *p;
  103687. p = sqlite3_aggregate_context(context, 0);
  103688. if( p && p->cnt>0 ){
  103689. if( p->overflow ){
  103690. sqlite3_result_error(context,"integer overflow",-1);
  103691. }else if( p->approx ){
  103692. sqlite3_result_double(context, p->rSum);
  103693. }else{
  103694. sqlite3_result_int64(context, p->iSum);
  103695. }
  103696. }
  103697. }
  103698. static void avgFinalize(sqlite3_context *context){
  103699. SumCtx *p;
  103700. p = sqlite3_aggregate_context(context, 0);
  103701. if( p && p->cnt>0 ){
  103702. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  103703. }
  103704. }
  103705. static void totalFinalize(sqlite3_context *context){
  103706. SumCtx *p;
  103707. p = sqlite3_aggregate_context(context, 0);
  103708. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  103709. sqlite3_result_double(context, p ? p->rSum : (double)0);
  103710. }
  103711. /*
  103712. ** The following structure keeps track of state information for the
  103713. ** count() aggregate function.
  103714. */
  103715. typedef struct CountCtx CountCtx;
  103716. struct CountCtx {
  103717. i64 n;
  103718. };
  103719. /*
  103720. ** Routines to implement the count() aggregate function.
  103721. */
  103722. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  103723. CountCtx *p;
  103724. p = sqlite3_aggregate_context(context, sizeof(*p));
  103725. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  103726. p->n++;
  103727. }
  103728. #ifndef SQLITE_OMIT_DEPRECATED
  103729. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  103730. ** sure it still operates correctly, verify that its count agrees with our
  103731. ** internal count when using count(*) and when the total count can be
  103732. ** expressed as a 32-bit integer. */
  103733. assert( argc==1 || p==0 || p->n>0x7fffffff
  103734. || p->n==sqlite3_aggregate_count(context) );
  103735. #endif
  103736. }
  103737. static void countFinalize(sqlite3_context *context){
  103738. CountCtx *p;
  103739. p = sqlite3_aggregate_context(context, 0);
  103740. sqlite3_result_int64(context, p ? p->n : 0);
  103741. }
  103742. /*
  103743. ** Routines to implement min() and max() aggregate functions.
  103744. */
  103745. static void minmaxStep(
  103746. sqlite3_context *context,
  103747. int NotUsed,
  103748. sqlite3_value **argv
  103749. ){
  103750. Mem *pArg = (Mem *)argv[0];
  103751. Mem *pBest;
  103752. UNUSED_PARAMETER(NotUsed);
  103753. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  103754. if( !pBest ) return;
  103755. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  103756. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  103757. }else if( pBest->flags ){
  103758. int max;
  103759. int cmp;
  103760. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  103761. /* This step function is used for both the min() and max() aggregates,
  103762. ** the only difference between the two being that the sense of the
  103763. ** comparison is inverted. For the max() aggregate, the
  103764. ** sqlite3_user_data() function returns (void *)-1. For min() it
  103765. ** returns (void *)db, where db is the sqlite3* database pointer.
  103766. ** Therefore the next statement sets variable 'max' to 1 for the max()
  103767. ** aggregate, or 0 for min().
  103768. */
  103769. max = sqlite3_user_data(context)!=0;
  103770. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  103771. if( (max && cmp<0) || (!max && cmp>0) ){
  103772. sqlite3VdbeMemCopy(pBest, pArg);
  103773. }else{
  103774. sqlite3SkipAccumulatorLoad(context);
  103775. }
  103776. }else{
  103777. pBest->db = sqlite3_context_db_handle(context);
  103778. sqlite3VdbeMemCopy(pBest, pArg);
  103779. }
  103780. }
  103781. static void minMaxFinalize(sqlite3_context *context){
  103782. sqlite3_value *pRes;
  103783. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  103784. if( pRes ){
  103785. if( pRes->flags ){
  103786. sqlite3_result_value(context, pRes);
  103787. }
  103788. sqlite3VdbeMemRelease(pRes);
  103789. }
  103790. }
  103791. /*
  103792. ** group_concat(EXPR, ?SEPARATOR?)
  103793. */
  103794. static void groupConcatStep(
  103795. sqlite3_context *context,
  103796. int argc,
  103797. sqlite3_value **argv
  103798. ){
  103799. const char *zVal;
  103800. StrAccum *pAccum;
  103801. const char *zSep;
  103802. int nVal, nSep;
  103803. assert( argc==1 || argc==2 );
  103804. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  103805. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  103806. if( pAccum ){
  103807. sqlite3 *db = sqlite3_context_db_handle(context);
  103808. int firstTerm = pAccum->mxAlloc==0;
  103809. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  103810. if( !firstTerm ){
  103811. if( argc==2 ){
  103812. zSep = (char*)sqlite3_value_text(argv[1]);
  103813. nSep = sqlite3_value_bytes(argv[1]);
  103814. }else{
  103815. zSep = ",";
  103816. nSep = 1;
  103817. }
  103818. if( zSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  103819. }
  103820. zVal = (char*)sqlite3_value_text(argv[0]);
  103821. nVal = sqlite3_value_bytes(argv[0]);
  103822. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  103823. }
  103824. }
  103825. static void groupConcatFinalize(sqlite3_context *context){
  103826. StrAccum *pAccum;
  103827. pAccum = sqlite3_aggregate_context(context, 0);
  103828. if( pAccum ){
  103829. if( pAccum->accError==STRACCUM_TOOBIG ){
  103830. sqlite3_result_error_toobig(context);
  103831. }else if( pAccum->accError==STRACCUM_NOMEM ){
  103832. sqlite3_result_error_nomem(context);
  103833. }else{
  103834. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  103835. sqlite3_free);
  103836. }
  103837. }
  103838. }
  103839. /*
  103840. ** This routine does per-connection function registration. Most
  103841. ** of the built-in functions above are part of the global function set.
  103842. ** This routine only deals with those that are not global.
  103843. */
  103844. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
  103845. int rc = sqlite3_overload_function(db, "MATCH", 2);
  103846. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  103847. if( rc==SQLITE_NOMEM ){
  103848. sqlite3OomFault(db);
  103849. }
  103850. }
  103851. /*
  103852. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  103853. */
  103854. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  103855. FuncDef *pDef;
  103856. pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
  103857. if( ALWAYS(pDef) ){
  103858. pDef->funcFlags |= flagVal;
  103859. }
  103860. }
  103861. /*
  103862. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  103863. ** parameter determines whether or not the LIKE operator is case
  103864. ** sensitive. GLOB is always case sensitive.
  103865. */
  103866. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  103867. struct compareInfo *pInfo;
  103868. if( caseSensitive ){
  103869. pInfo = (struct compareInfo*)&likeInfoAlt;
  103870. }else{
  103871. pInfo = (struct compareInfo*)&likeInfoNorm;
  103872. }
  103873. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  103874. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  103875. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  103876. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  103877. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  103878. setLikeOptFlag(db, "like",
  103879. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  103880. }
  103881. /*
  103882. ** pExpr points to an expression which implements a function. If
  103883. ** it is appropriate to apply the LIKE optimization to that function
  103884. ** then set aWc[0] through aWc[2] to the wildcard characters and the
  103885. ** escape character and then return TRUE. If the function is not a
  103886. ** LIKE-style function then return FALSE.
  103887. **
  103888. ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
  103889. ** operator if c is a string literal that is exactly one byte in length.
  103890. ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
  103891. ** no ESCAPE clause.
  103892. **
  103893. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  103894. ** the function (default for LIKE). If the function makes the distinction
  103895. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  103896. ** false.
  103897. */
  103898. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  103899. FuncDef *pDef;
  103900. int nExpr;
  103901. if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
  103902. return 0;
  103903. }
  103904. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  103905. nExpr = pExpr->x.pList->nExpr;
  103906. pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
  103907. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  103908. return 0;
  103909. }
  103910. if( nExpr<3 ){
  103911. aWc[3] = 0;
  103912. }else{
  103913. Expr *pEscape = pExpr->x.pList->a[2].pExpr;
  103914. char *zEscape;
  103915. if( pEscape->op!=TK_STRING ) return 0;
  103916. zEscape = pEscape->u.zToken;
  103917. if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
  103918. aWc[3] = zEscape[0];
  103919. }
  103920. /* The memcpy() statement assumes that the wildcard characters are
  103921. ** the first three statements in the compareInfo structure. The
  103922. ** asserts() that follow verify that assumption
  103923. */
  103924. memcpy(aWc, pDef->pUserData, 3);
  103925. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  103926. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  103927. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  103928. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  103929. return 1;
  103930. }
  103931. /*
  103932. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  103933. ** to the global function hash table. This occurs at start-time (as
  103934. ** a consequence of calling sqlite3_initialize()).
  103935. **
  103936. ** After this routine runs
  103937. */
  103938. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
  103939. /*
  103940. ** The following array holds FuncDef structures for all of the functions
  103941. ** defined in this file.
  103942. **
  103943. ** The array cannot be constant since changes are made to the
  103944. ** FuncDef.pHash elements at start-time. The elements of this array
  103945. ** are read-only after initialization is complete.
  103946. **
  103947. ** For peak efficiency, put the most frequently used function last.
  103948. */
  103949. static FuncDef aBuiltinFunc[] = {
  103950. #ifdef SQLITE_SOUNDEX
  103951. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  103952. #endif
  103953. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  103954. VFUNCTION(load_extension, 1, 0, 0, loadExt ),
  103955. VFUNCTION(load_extension, 2, 0, 0, loadExt ),
  103956. #endif
  103957. #if SQLITE_USER_AUTHENTICATION
  103958. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  103959. #endif
  103960. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  103961. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  103962. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  103963. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  103964. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  103965. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  103966. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  103967. #ifdef SQLITE_DEBUG
  103968. FUNCTION2(affinity, 1, 0, 0, noopFunc, SQLITE_FUNC_AFFINITY),
  103969. #endif
  103970. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  103971. FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET|
  103972. SQLITE_FUNC_TYPEOF),
  103973. #endif
  103974. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  103975. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  103976. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  103977. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  103978. FUNCTION(trim, 1, 3, 0, trimFunc ),
  103979. FUNCTION(trim, 2, 3, 0, trimFunc ),
  103980. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  103981. FUNCTION(min, 0, 0, 1, 0 ),
  103982. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  103983. SQLITE_FUNC_MINMAX ),
  103984. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  103985. FUNCTION(max, 0, 1, 1, 0 ),
  103986. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  103987. SQLITE_FUNC_MINMAX ),
  103988. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  103989. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  103990. FUNCTION(instr, 2, 0, 0, instrFunc ),
  103991. FUNCTION(printf, -1, 0, 0, printfFunc ),
  103992. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  103993. FUNCTION(char, -1, 0, 0, charFunc ),
  103994. FUNCTION(abs, 1, 0, 0, absFunc ),
  103995. #ifndef SQLITE_OMIT_FLOATING_POINT
  103996. FUNCTION(round, 1, 0, 0, roundFunc ),
  103997. FUNCTION(round, 2, 0, 0, roundFunc ),
  103998. #endif
  103999. FUNCTION(upper, 1, 0, 0, upperFunc ),
  104000. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  104001. FUNCTION(hex, 1, 0, 0, hexFunc ),
  104002. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  104003. VFUNCTION(random, 0, 0, 0, randomFunc ),
  104004. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  104005. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  104006. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  104007. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  104008. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  104009. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  104010. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  104011. VFUNCTION(changes, 0, 0, 0, changes ),
  104012. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  104013. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  104014. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  104015. FUNCTION(substr, 2, 0, 0, substrFunc ),
  104016. FUNCTION(substr, 3, 0, 0, substrFunc ),
  104017. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  104018. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  104019. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  104020. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  104021. SQLITE_FUNC_COUNT ),
  104022. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  104023. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  104024. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  104025. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  104026. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  104027. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  104028. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  104029. #else
  104030. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  104031. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  104032. #endif
  104033. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  104034. FUNCTION(unknown, -1, 0, 0, unknownFunc ),
  104035. #endif
  104036. FUNCTION(coalesce, 1, 0, 0, 0 ),
  104037. FUNCTION(coalesce, 0, 0, 0, 0 ),
  104038. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  104039. };
  104040. #ifndef SQLITE_OMIT_ALTERTABLE
  104041. sqlite3AlterFunctions();
  104042. #endif
  104043. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  104044. sqlite3AnalyzeFunctions();
  104045. #endif
  104046. sqlite3RegisterDateTimeFunctions();
  104047. sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
  104048. #if 0 /* Enable to print out how the built-in functions are hashed */
  104049. {
  104050. int i;
  104051. FuncDef *p;
  104052. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  104053. printf("FUNC-HASH %02d:", i);
  104054. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
  104055. int n = sqlite3Strlen30(p->zName);
  104056. int h = p->zName[0] + n;
  104057. printf(" %s(%d)", p->zName, h);
  104058. }
  104059. printf("\n");
  104060. }
  104061. }
  104062. #endif
  104063. }
  104064. /************** End of func.c ************************************************/
  104065. /************** Begin file fkey.c ********************************************/
  104066. /*
  104067. **
  104068. ** The author disclaims copyright to this source code. In place of
  104069. ** a legal notice, here is a blessing:
  104070. **
  104071. ** May you do good and not evil.
  104072. ** May you find forgiveness for yourself and forgive others.
  104073. ** May you share freely, never taking more than you give.
  104074. **
  104075. *************************************************************************
  104076. ** This file contains code used by the compiler to add foreign key
  104077. ** support to compiled SQL statements.
  104078. */
  104079. /* #include "sqliteInt.h" */
  104080. #ifndef SQLITE_OMIT_FOREIGN_KEY
  104081. #ifndef SQLITE_OMIT_TRIGGER
  104082. /*
  104083. ** Deferred and Immediate FKs
  104084. ** --------------------------
  104085. **
  104086. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  104087. ** If an immediate foreign key constraint is violated,
  104088. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  104089. ** statement transaction rolled back. If a
  104090. ** deferred foreign key constraint is violated, no action is taken
  104091. ** immediately. However if the application attempts to commit the
  104092. ** transaction before fixing the constraint violation, the attempt fails.
  104093. **
  104094. ** Deferred constraints are implemented using a simple counter associated
  104095. ** with the database handle. The counter is set to zero each time a
  104096. ** database transaction is opened. Each time a statement is executed
  104097. ** that causes a foreign key violation, the counter is incremented. Each
  104098. ** time a statement is executed that removes an existing violation from
  104099. ** the database, the counter is decremented. When the transaction is
  104100. ** committed, the commit fails if the current value of the counter is
  104101. ** greater than zero. This scheme has two big drawbacks:
  104102. **
  104103. ** * When a commit fails due to a deferred foreign key constraint,
  104104. ** there is no way to tell which foreign constraint is not satisfied,
  104105. ** or which row it is not satisfied for.
  104106. **
  104107. ** * If the database contains foreign key violations when the
  104108. ** transaction is opened, this may cause the mechanism to malfunction.
  104109. **
  104110. ** Despite these problems, this approach is adopted as it seems simpler
  104111. ** than the alternatives.
  104112. **
  104113. ** INSERT operations:
  104114. **
  104115. ** I.1) For each FK for which the table is the child table, search
  104116. ** the parent table for a match. If none is found increment the
  104117. ** constraint counter.
  104118. **
  104119. ** I.2) For each FK for which the table is the parent table,
  104120. ** search the child table for rows that correspond to the new
  104121. ** row in the parent table. Decrement the counter for each row
  104122. ** found (as the constraint is now satisfied).
  104123. **
  104124. ** DELETE operations:
  104125. **
  104126. ** D.1) For each FK for which the table is the child table,
  104127. ** search the parent table for a row that corresponds to the
  104128. ** deleted row in the child table. If such a row is not found,
  104129. ** decrement the counter.
  104130. **
  104131. ** D.2) For each FK for which the table is the parent table, search
  104132. ** the child table for rows that correspond to the deleted row
  104133. ** in the parent table. For each found increment the counter.
  104134. **
  104135. ** UPDATE operations:
  104136. **
  104137. ** An UPDATE command requires that all 4 steps above are taken, but only
  104138. ** for FK constraints for which the affected columns are actually
  104139. ** modified (values must be compared at runtime).
  104140. **
  104141. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  104142. ** This simplifies the implementation a bit.
  104143. **
  104144. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  104145. ** resolution is considered to delete rows before the new row is inserted.
  104146. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  104147. ** is thrown, even if the FK constraint would be satisfied after the new
  104148. ** row is inserted.
  104149. **
  104150. ** Immediate constraints are usually handled similarly. The only difference
  104151. ** is that the counter used is stored as part of each individual statement
  104152. ** object (struct Vdbe). If, after the statement has run, its immediate
  104153. ** constraint counter is greater than zero,
  104154. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  104155. ** and the statement transaction is rolled back. An exception is an INSERT
  104156. ** statement that inserts a single row only (no triggers). In this case,
  104157. ** instead of using a counter, an exception is thrown immediately if the
  104158. ** INSERT violates a foreign key constraint. This is necessary as such
  104159. ** an INSERT does not open a statement transaction.
  104160. **
  104161. ** TODO: How should dropping a table be handled? How should renaming a
  104162. ** table be handled?
  104163. **
  104164. **
  104165. ** Query API Notes
  104166. ** ---------------
  104167. **
  104168. ** Before coding an UPDATE or DELETE row operation, the code-generator
  104169. ** for those two operations needs to know whether or not the operation
  104170. ** requires any FK processing and, if so, which columns of the original
  104171. ** row are required by the FK processing VDBE code (i.e. if FKs were
  104172. ** implemented using triggers, which of the old.* columns would be
  104173. ** accessed). No information is required by the code-generator before
  104174. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  104175. ** generation code to query for this information are:
  104176. **
  104177. ** sqlite3FkRequired() - Test to see if FK processing is required.
  104178. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  104179. **
  104180. **
  104181. ** Externally accessible module functions
  104182. ** --------------------------------------
  104183. **
  104184. ** sqlite3FkCheck() - Check for foreign key violations.
  104185. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  104186. ** sqlite3FkDelete() - Delete an FKey structure.
  104187. */
  104188. /*
  104189. ** VDBE Calling Convention
  104190. ** -----------------------
  104191. **
  104192. ** Example:
  104193. **
  104194. ** For the following INSERT statement:
  104195. **
  104196. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  104197. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  104198. **
  104199. ** Register (x): 2 (type integer)
  104200. ** Register (x+1): 1 (type integer)
  104201. ** Register (x+2): NULL (type NULL)
  104202. ** Register (x+3): 3.1 (type real)
  104203. */
  104204. /*
  104205. ** A foreign key constraint requires that the key columns in the parent
  104206. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  104207. ** Given that pParent is the parent table for foreign key constraint pFKey,
  104208. ** search the schema for a unique index on the parent key columns.
  104209. **
  104210. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  104211. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  104212. ** is set to point to the unique index.
  104213. **
  104214. ** If the parent key consists of a single column (the foreign key constraint
  104215. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  104216. ** Otherwise, it is set to point to an allocated array of size N, where
  104217. ** N is the number of columns in the parent key. The first element of the
  104218. ** array is the index of the child table column that is mapped by the FK
  104219. ** constraint to the parent table column stored in the left-most column
  104220. ** of index *ppIdx. The second element of the array is the index of the
  104221. ** child table column that corresponds to the second left-most column of
  104222. ** *ppIdx, and so on.
  104223. **
  104224. ** If the required index cannot be found, either because:
  104225. **
  104226. ** 1) The named parent key columns do not exist, or
  104227. **
  104228. ** 2) The named parent key columns do exist, but are not subject to a
  104229. ** UNIQUE or PRIMARY KEY constraint, or
  104230. **
  104231. ** 3) No parent key columns were provided explicitly as part of the
  104232. ** foreign key definition, and the parent table does not have a
  104233. ** PRIMARY KEY, or
  104234. **
  104235. ** 4) No parent key columns were provided explicitly as part of the
  104236. ** foreign key definition, and the PRIMARY KEY of the parent table
  104237. ** consists of a different number of columns to the child key in
  104238. ** the child table.
  104239. **
  104240. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  104241. ** into pParse. If an OOM error occurs, non-zero is returned and the
  104242. ** pParse->db->mallocFailed flag is set.
  104243. */
  104244. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  104245. Parse *pParse, /* Parse context to store any error in */
  104246. Table *pParent, /* Parent table of FK constraint pFKey */
  104247. FKey *pFKey, /* Foreign key to find index for */
  104248. Index **ppIdx, /* OUT: Unique index on parent table */
  104249. int **paiCol /* OUT: Map of index columns in pFKey */
  104250. ){
  104251. Index *pIdx = 0; /* Value to return via *ppIdx */
  104252. int *aiCol = 0; /* Value to return via *paiCol */
  104253. int nCol = pFKey->nCol; /* Number of columns in parent key */
  104254. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  104255. /* The caller is responsible for zeroing output parameters. */
  104256. assert( ppIdx && *ppIdx==0 );
  104257. assert( !paiCol || *paiCol==0 );
  104258. assert( pParse );
  104259. /* If this is a non-composite (single column) foreign key, check if it
  104260. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  104261. ** and *paiCol set to zero and return early.
  104262. **
  104263. ** Otherwise, for a composite foreign key (more than one column), allocate
  104264. ** space for the aiCol array (returned via output parameter *paiCol).
  104265. ** Non-composite foreign keys do not require the aiCol array.
  104266. */
  104267. if( nCol==1 ){
  104268. /* The FK maps to the IPK if any of the following are true:
  104269. **
  104270. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  104271. ** mapped to the primary key of table pParent, or
  104272. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  104273. ** PRIMARY KEY.
  104274. */
  104275. if( pParent->iPKey>=0 ){
  104276. if( !zKey ) return 0;
  104277. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  104278. }
  104279. }else if( paiCol ){
  104280. assert( nCol>1 );
  104281. aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
  104282. if( !aiCol ) return 1;
  104283. *paiCol = aiCol;
  104284. }
  104285. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  104286. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
  104287. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  104288. ** of columns. If each indexed column corresponds to a foreign key
  104289. ** column of pFKey, then this index is a winner. */
  104290. if( zKey==0 ){
  104291. /* If zKey is NULL, then this foreign key is implicitly mapped to
  104292. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  104293. ** identified by the test. */
  104294. if( IsPrimaryKeyIndex(pIdx) ){
  104295. if( aiCol ){
  104296. int i;
  104297. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  104298. }
  104299. break;
  104300. }
  104301. }else{
  104302. /* If zKey is non-NULL, then this foreign key was declared to
  104303. ** map to an explicit list of columns in table pParent. Check if this
  104304. ** index matches those columns. Also, check that the index uses
  104305. ** the default collation sequences for each column. */
  104306. int i, j;
  104307. for(i=0; i<nCol; i++){
  104308. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  104309. const char *zDfltColl; /* Def. collation for column */
  104310. char *zIdxCol; /* Name of indexed column */
  104311. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  104312. /* If the index uses a collation sequence that is different from
  104313. ** the default collation sequence for the column, this index is
  104314. ** unusable. Bail out early in this case. */
  104315. zDfltColl = pParent->aCol[iCol].zColl;
  104316. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  104317. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  104318. zIdxCol = pParent->aCol[iCol].zName;
  104319. for(j=0; j<nCol; j++){
  104320. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  104321. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  104322. break;
  104323. }
  104324. }
  104325. if( j==nCol ) break;
  104326. }
  104327. if( i==nCol ) break; /* pIdx is usable */
  104328. }
  104329. }
  104330. }
  104331. if( !pIdx ){
  104332. if( !pParse->disableTriggers ){
  104333. sqlite3ErrorMsg(pParse,
  104334. "foreign key mismatch - \"%w\" referencing \"%w\"",
  104335. pFKey->pFrom->zName, pFKey->zTo);
  104336. }
  104337. sqlite3DbFree(pParse->db, aiCol);
  104338. return 1;
  104339. }
  104340. *ppIdx = pIdx;
  104341. return 0;
  104342. }
  104343. /*
  104344. ** This function is called when a row is inserted into or deleted from the
  104345. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  104346. ** on the child table of pFKey, this function is invoked twice for each row
  104347. ** affected - once to "delete" the old row, and then again to "insert" the
  104348. ** new row.
  104349. **
  104350. ** Each time it is called, this function generates VDBE code to locate the
  104351. ** row in the parent table that corresponds to the row being inserted into
  104352. ** or deleted from the child table. If the parent row can be found, no
  104353. ** special action is taken. Otherwise, if the parent row can *not* be
  104354. ** found in the parent table:
  104355. **
  104356. ** Operation | FK type | Action taken
  104357. ** --------------------------------------------------------------------------
  104358. ** INSERT immediate Increment the "immediate constraint counter".
  104359. **
  104360. ** DELETE immediate Decrement the "immediate constraint counter".
  104361. **
  104362. ** INSERT deferred Increment the "deferred constraint counter".
  104363. **
  104364. ** DELETE deferred Decrement the "deferred constraint counter".
  104365. **
  104366. ** These operations are identified in the comment at the top of this file
  104367. ** (fkey.c) as "I.1" and "D.1".
  104368. */
  104369. static void fkLookupParent(
  104370. Parse *pParse, /* Parse context */
  104371. int iDb, /* Index of database housing pTab */
  104372. Table *pTab, /* Parent table of FK pFKey */
  104373. Index *pIdx, /* Unique index on parent key columns in pTab */
  104374. FKey *pFKey, /* Foreign key constraint */
  104375. int *aiCol, /* Map from parent key columns to child table columns */
  104376. int regData, /* Address of array containing child table row */
  104377. int nIncr, /* Increment constraint counter by this */
  104378. int isIgnore /* If true, pretend pTab contains all NULL values */
  104379. ){
  104380. int i; /* Iterator variable */
  104381. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  104382. int iCur = pParse->nTab - 1; /* Cursor number to use */
  104383. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  104384. /* If nIncr is less than zero, then check at runtime if there are any
  104385. ** outstanding constraints to resolve. If there are not, there is no need
  104386. ** to check if deleting this row resolves any outstanding violations.
  104387. **
  104388. ** Check if any of the key columns in the child table row are NULL. If
  104389. ** any are, then the constraint is considered satisfied. No need to
  104390. ** search for a matching row in the parent table. */
  104391. if( nIncr<0 ){
  104392. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  104393. VdbeCoverage(v);
  104394. }
  104395. for(i=0; i<pFKey->nCol; i++){
  104396. int iReg = aiCol[i] + regData + 1;
  104397. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  104398. }
  104399. if( isIgnore==0 ){
  104400. if( pIdx==0 ){
  104401. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  104402. ** column of the parent table (table pTab). */
  104403. int iMustBeInt; /* Address of MustBeInt instruction */
  104404. int regTemp = sqlite3GetTempReg(pParse);
  104405. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  104406. ** apply the affinity of the parent key). If this fails, then there
  104407. ** is no matching parent key. Before using MustBeInt, make a copy of
  104408. ** the value. Otherwise, the value inserted into the child key column
  104409. ** will have INTEGER affinity applied to it, which may not be correct. */
  104410. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  104411. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  104412. VdbeCoverage(v);
  104413. /* If the parent table is the same as the child table, and we are about
  104414. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  104415. ** then check if the row being inserted matches itself. If so, do not
  104416. ** increment the constraint-counter. */
  104417. if( pTab==pFKey->pFrom && nIncr==1 ){
  104418. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  104419. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  104420. }
  104421. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  104422. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  104423. sqlite3VdbeGoto(v, iOk);
  104424. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  104425. sqlite3VdbeJumpHere(v, iMustBeInt);
  104426. sqlite3ReleaseTempReg(pParse, regTemp);
  104427. }else{
  104428. int nCol = pFKey->nCol;
  104429. int regTemp = sqlite3GetTempRange(pParse, nCol);
  104430. int regRec = sqlite3GetTempReg(pParse);
  104431. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  104432. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  104433. for(i=0; i<nCol; i++){
  104434. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  104435. }
  104436. /* If the parent table is the same as the child table, and we are about
  104437. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  104438. ** then check if the row being inserted matches itself. If so, do not
  104439. ** increment the constraint-counter.
  104440. **
  104441. ** If any of the parent-key values are NULL, then the row cannot match
  104442. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  104443. ** of the parent-key values are NULL (at this point it is known that
  104444. ** none of the child key values are).
  104445. */
  104446. if( pTab==pFKey->pFrom && nIncr==1 ){
  104447. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  104448. for(i=0; i<nCol; i++){
  104449. int iChild = aiCol[i]+1+regData;
  104450. int iParent = pIdx->aiColumn[i]+1+regData;
  104451. assert( pIdx->aiColumn[i]>=0 );
  104452. assert( aiCol[i]!=pTab->iPKey );
  104453. if( pIdx->aiColumn[i]==pTab->iPKey ){
  104454. /* The parent key is a composite key that includes the IPK column */
  104455. iParent = regData;
  104456. }
  104457. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  104458. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  104459. }
  104460. sqlite3VdbeGoto(v, iOk);
  104461. }
  104462. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  104463. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  104464. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  104465. sqlite3ReleaseTempReg(pParse, regRec);
  104466. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  104467. }
  104468. }
  104469. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  104470. && !pParse->pToplevel
  104471. && !pParse->isMultiWrite
  104472. ){
  104473. /* Special case: If this is an INSERT statement that will insert exactly
  104474. ** one row into the table, raise a constraint immediately instead of
  104475. ** incrementing a counter. This is necessary as the VM code is being
  104476. ** generated for will not open a statement transaction. */
  104477. assert( nIncr==1 );
  104478. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  104479. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  104480. }else{
  104481. if( nIncr>0 && pFKey->isDeferred==0 ){
  104482. sqlite3MayAbort(pParse);
  104483. }
  104484. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  104485. }
  104486. sqlite3VdbeResolveLabel(v, iOk);
  104487. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  104488. }
  104489. /*
  104490. ** Return an Expr object that refers to a memory register corresponding
  104491. ** to column iCol of table pTab.
  104492. **
  104493. ** regBase is the first of an array of register that contains the data
  104494. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  104495. ** column. regBase+2 holds the second column, and so forth.
  104496. */
  104497. static Expr *exprTableRegister(
  104498. Parse *pParse, /* Parsing and code generating context */
  104499. Table *pTab, /* The table whose content is at r[regBase]... */
  104500. int regBase, /* Contents of table pTab */
  104501. i16 iCol /* Which column of pTab is desired */
  104502. ){
  104503. Expr *pExpr;
  104504. Column *pCol;
  104505. const char *zColl;
  104506. sqlite3 *db = pParse->db;
  104507. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  104508. if( pExpr ){
  104509. if( iCol>=0 && iCol!=pTab->iPKey ){
  104510. pCol = &pTab->aCol[iCol];
  104511. pExpr->iTable = regBase + iCol + 1;
  104512. pExpr->affinity = pCol->affinity;
  104513. zColl = pCol->zColl;
  104514. if( zColl==0 ) zColl = db->pDfltColl->zName;
  104515. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  104516. }else{
  104517. pExpr->iTable = regBase;
  104518. pExpr->affinity = SQLITE_AFF_INTEGER;
  104519. }
  104520. }
  104521. return pExpr;
  104522. }
  104523. /*
  104524. ** Return an Expr object that refers to column iCol of table pTab which
  104525. ** has cursor iCur.
  104526. */
  104527. static Expr *exprTableColumn(
  104528. sqlite3 *db, /* The database connection */
  104529. Table *pTab, /* The table whose column is desired */
  104530. int iCursor, /* The open cursor on the table */
  104531. i16 iCol /* The column that is wanted */
  104532. ){
  104533. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  104534. if( pExpr ){
  104535. pExpr->pTab = pTab;
  104536. pExpr->iTable = iCursor;
  104537. pExpr->iColumn = iCol;
  104538. }
  104539. return pExpr;
  104540. }
  104541. /*
  104542. ** This function is called to generate code executed when a row is deleted
  104543. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  104544. ** deferred, when a row is inserted into the same table. When generating
  104545. ** code for an SQL UPDATE operation, this function may be called twice -
  104546. ** once to "delete" the old row and once to "insert" the new row.
  104547. **
  104548. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  104549. ** the number of FK violations in the db) or +1 when deleting one (as this
  104550. ** may increase the number of FK constraint problems).
  104551. **
  104552. ** The code generated by this function scans through the rows in the child
  104553. ** table that correspond to the parent table row being deleted or inserted.
  104554. ** For each child row found, one of the following actions is taken:
  104555. **
  104556. ** Operation | FK type | Action taken
  104557. ** --------------------------------------------------------------------------
  104558. ** DELETE immediate Increment the "immediate constraint counter".
  104559. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  104560. ** throw a "FOREIGN KEY constraint failed" exception.
  104561. **
  104562. ** INSERT immediate Decrement the "immediate constraint counter".
  104563. **
  104564. ** DELETE deferred Increment the "deferred constraint counter".
  104565. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  104566. ** throw a "FOREIGN KEY constraint failed" exception.
  104567. **
  104568. ** INSERT deferred Decrement the "deferred constraint counter".
  104569. **
  104570. ** These operations are identified in the comment at the top of this file
  104571. ** (fkey.c) as "I.2" and "D.2".
  104572. */
  104573. static void fkScanChildren(
  104574. Parse *pParse, /* Parse context */
  104575. SrcList *pSrc, /* The child table to be scanned */
  104576. Table *pTab, /* The parent table */
  104577. Index *pIdx, /* Index on parent covering the foreign key */
  104578. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  104579. int *aiCol, /* Map from pIdx cols to child table cols */
  104580. int regData, /* Parent row data starts here */
  104581. int nIncr /* Amount to increment deferred counter by */
  104582. ){
  104583. sqlite3 *db = pParse->db; /* Database handle */
  104584. int i; /* Iterator variable */
  104585. Expr *pWhere = 0; /* WHERE clause to scan with */
  104586. NameContext sNameContext; /* Context used to resolve WHERE clause */
  104587. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  104588. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  104589. Vdbe *v = sqlite3GetVdbe(pParse);
  104590. assert( pIdx==0 || pIdx->pTable==pTab );
  104591. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  104592. assert( pIdx!=0 || pFKey->nCol==1 );
  104593. assert( pIdx!=0 || HasRowid(pTab) );
  104594. if( nIncr<0 ){
  104595. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  104596. VdbeCoverage(v);
  104597. }
  104598. /* Create an Expr object representing an SQL expression like:
  104599. **
  104600. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  104601. **
  104602. ** The collation sequence used for the comparison should be that of
  104603. ** the parent key columns. The affinity of the parent key column should
  104604. ** be applied to each child key value before the comparison takes place.
  104605. */
  104606. for(i=0; i<pFKey->nCol; i++){
  104607. Expr *pLeft; /* Value from parent table row */
  104608. Expr *pRight; /* Column ref to child table */
  104609. Expr *pEq; /* Expression (pLeft = pRight) */
  104610. i16 iCol; /* Index of column in child table */
  104611. const char *zCol; /* Name of column in child table */
  104612. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  104613. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  104614. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  104615. assert( iCol>=0 );
  104616. zCol = pFKey->pFrom->aCol[iCol].zName;
  104617. pRight = sqlite3Expr(db, TK_ID, zCol);
  104618. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  104619. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  104620. }
  104621. /* If the child table is the same as the parent table, then add terms
  104622. ** to the WHERE clause that prevent this entry from being scanned.
  104623. ** The added WHERE clause terms are like this:
  104624. **
  104625. ** $current_rowid!=rowid
  104626. ** NOT( $current_a==a AND $current_b==b AND ... )
  104627. **
  104628. ** The first form is used for rowid tables. The second form is used
  104629. ** for WITHOUT ROWID tables. In the second form, the primary key is
  104630. ** (a,b,...)
  104631. */
  104632. if( pTab==pFKey->pFrom && nIncr>0 ){
  104633. Expr *pNe; /* Expression (pLeft != pRight) */
  104634. Expr *pLeft; /* Value from parent table row */
  104635. Expr *pRight; /* Column ref to child table */
  104636. if( HasRowid(pTab) ){
  104637. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  104638. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  104639. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
  104640. }else{
  104641. Expr *pEq, *pAll = 0;
  104642. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  104643. assert( pIdx!=0 );
  104644. for(i=0; i<pPk->nKeyCol; i++){
  104645. i16 iCol = pIdx->aiColumn[i];
  104646. assert( iCol>=0 );
  104647. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  104648. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  104649. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  104650. pAll = sqlite3ExprAnd(db, pAll, pEq);
  104651. }
  104652. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
  104653. }
  104654. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  104655. }
  104656. /* Resolve the references in the WHERE clause. */
  104657. memset(&sNameContext, 0, sizeof(NameContext));
  104658. sNameContext.pSrcList = pSrc;
  104659. sNameContext.pParse = pParse;
  104660. sqlite3ResolveExprNames(&sNameContext, pWhere);
  104661. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  104662. ** clause. For each row found, increment either the deferred or immediate
  104663. ** foreign key constraint counter. */
  104664. if( pParse->nErr==0 ){
  104665. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  104666. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  104667. if( pWInfo ){
  104668. sqlite3WhereEnd(pWInfo);
  104669. }
  104670. }
  104671. /* Clean up the WHERE clause constructed above. */
  104672. sqlite3ExprDelete(db, pWhere);
  104673. if( iFkIfZero ){
  104674. sqlite3VdbeJumpHere(v, iFkIfZero);
  104675. }
  104676. }
  104677. /*
  104678. ** This function returns a linked list of FKey objects (connected by
  104679. ** FKey.pNextTo) holding all children of table pTab. For example,
  104680. ** given the following schema:
  104681. **
  104682. ** CREATE TABLE t1(a PRIMARY KEY);
  104683. ** CREATE TABLE t2(b REFERENCES t1(a);
  104684. **
  104685. ** Calling this function with table "t1" as an argument returns a pointer
  104686. ** to the FKey structure representing the foreign key constraint on table
  104687. ** "t2". Calling this function with "t2" as the argument would return a
  104688. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  104689. ** table).
  104690. */
  104691. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  104692. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  104693. }
  104694. /*
  104695. ** The second argument is a Trigger structure allocated by the
  104696. ** fkActionTrigger() routine. This function deletes the Trigger structure
  104697. ** and all of its sub-components.
  104698. **
  104699. ** The Trigger structure or any of its sub-components may be allocated from
  104700. ** the lookaside buffer belonging to database handle dbMem.
  104701. */
  104702. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  104703. if( p ){
  104704. TriggerStep *pStep = p->step_list;
  104705. sqlite3ExprDelete(dbMem, pStep->pWhere);
  104706. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  104707. sqlite3SelectDelete(dbMem, pStep->pSelect);
  104708. sqlite3ExprDelete(dbMem, p->pWhen);
  104709. sqlite3DbFree(dbMem, p);
  104710. }
  104711. }
  104712. /*
  104713. ** This function is called to generate code that runs when table pTab is
  104714. ** being dropped from the database. The SrcList passed as the second argument
  104715. ** to this function contains a single entry guaranteed to resolve to
  104716. ** table pTab.
  104717. **
  104718. ** Normally, no code is required. However, if either
  104719. **
  104720. ** (a) The table is the parent table of a FK constraint, or
  104721. ** (b) The table is the child table of a deferred FK constraint and it is
  104722. ** determined at runtime that there are outstanding deferred FK
  104723. ** constraint violations in the database,
  104724. **
  104725. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  104726. ** the table from the database. Triggers are disabled while running this
  104727. ** DELETE, but foreign key actions are not.
  104728. */
  104729. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  104730. sqlite3 *db = pParse->db;
  104731. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  104732. int iSkip = 0;
  104733. Vdbe *v = sqlite3GetVdbe(pParse);
  104734. assert( v ); /* VDBE has already been allocated */
  104735. if( sqlite3FkReferences(pTab)==0 ){
  104736. /* Search for a deferred foreign key constraint for which this table
  104737. ** is the child table. If one cannot be found, return without
  104738. ** generating any VDBE code. If one can be found, then jump over
  104739. ** the entire DELETE if there are no outstanding deferred constraints
  104740. ** when this statement is run. */
  104741. FKey *p;
  104742. for(p=pTab->pFKey; p; p=p->pNextFrom){
  104743. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  104744. }
  104745. if( !p ) return;
  104746. iSkip = sqlite3VdbeMakeLabel(v);
  104747. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  104748. }
  104749. pParse->disableTriggers = 1;
  104750. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
  104751. pParse->disableTriggers = 0;
  104752. /* If the DELETE has generated immediate foreign key constraint
  104753. ** violations, halt the VDBE and return an error at this point, before
  104754. ** any modifications to the schema are made. This is because statement
  104755. ** transactions are not able to rollback schema changes.
  104756. **
  104757. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  104758. ** the statement transaction will not be rolled back even if FK
  104759. ** constraints are violated.
  104760. */
  104761. if( (db->flags & SQLITE_DeferFKs)==0 ){
  104762. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  104763. VdbeCoverage(v);
  104764. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  104765. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  104766. }
  104767. if( iSkip ){
  104768. sqlite3VdbeResolveLabel(v, iSkip);
  104769. }
  104770. }
  104771. }
  104772. /*
  104773. ** The second argument points to an FKey object representing a foreign key
  104774. ** for which pTab is the child table. An UPDATE statement against pTab
  104775. ** is currently being processed. For each column of the table that is
  104776. ** actually updated, the corresponding element in the aChange[] array
  104777. ** is zero or greater (if a column is unmodified the corresponding element
  104778. ** is set to -1). If the rowid column is modified by the UPDATE statement
  104779. ** the bChngRowid argument is non-zero.
  104780. **
  104781. ** This function returns true if any of the columns that are part of the
  104782. ** child key for FK constraint *p are modified.
  104783. */
  104784. static int fkChildIsModified(
  104785. Table *pTab, /* Table being updated */
  104786. FKey *p, /* Foreign key for which pTab is the child */
  104787. int *aChange, /* Array indicating modified columns */
  104788. int bChngRowid /* True if rowid is modified by this update */
  104789. ){
  104790. int i;
  104791. for(i=0; i<p->nCol; i++){
  104792. int iChildKey = p->aCol[i].iFrom;
  104793. if( aChange[iChildKey]>=0 ) return 1;
  104794. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  104795. }
  104796. return 0;
  104797. }
  104798. /*
  104799. ** The second argument points to an FKey object representing a foreign key
  104800. ** for which pTab is the parent table. An UPDATE statement against pTab
  104801. ** is currently being processed. For each column of the table that is
  104802. ** actually updated, the corresponding element in the aChange[] array
  104803. ** is zero or greater (if a column is unmodified the corresponding element
  104804. ** is set to -1). If the rowid column is modified by the UPDATE statement
  104805. ** the bChngRowid argument is non-zero.
  104806. **
  104807. ** This function returns true if any of the columns that are part of the
  104808. ** parent key for FK constraint *p are modified.
  104809. */
  104810. static int fkParentIsModified(
  104811. Table *pTab,
  104812. FKey *p,
  104813. int *aChange,
  104814. int bChngRowid
  104815. ){
  104816. int i;
  104817. for(i=0; i<p->nCol; i++){
  104818. char *zKey = p->aCol[i].zCol;
  104819. int iKey;
  104820. for(iKey=0; iKey<pTab->nCol; iKey++){
  104821. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  104822. Column *pCol = &pTab->aCol[iKey];
  104823. if( zKey ){
  104824. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  104825. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  104826. return 1;
  104827. }
  104828. }
  104829. }
  104830. }
  104831. return 0;
  104832. }
  104833. /*
  104834. ** Return true if the parser passed as the first argument is being
  104835. ** used to code a trigger that is really a "SET NULL" action belonging
  104836. ** to trigger pFKey.
  104837. */
  104838. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  104839. Parse *pTop = sqlite3ParseToplevel(pParse);
  104840. if( pTop->pTriggerPrg ){
  104841. Trigger *p = pTop->pTriggerPrg->pTrigger;
  104842. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  104843. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  104844. ){
  104845. return 1;
  104846. }
  104847. }
  104848. return 0;
  104849. }
  104850. /*
  104851. ** This function is called when inserting, deleting or updating a row of
  104852. ** table pTab to generate VDBE code to perform foreign key constraint
  104853. ** processing for the operation.
  104854. **
  104855. ** For a DELETE operation, parameter regOld is passed the index of the
  104856. ** first register in an array of (pTab->nCol+1) registers containing the
  104857. ** rowid of the row being deleted, followed by each of the column values
  104858. ** of the row being deleted, from left to right. Parameter regNew is passed
  104859. ** zero in this case.
  104860. **
  104861. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  104862. ** first register of an array of (pTab->nCol+1) registers containing the new
  104863. ** row data.
  104864. **
  104865. ** For an UPDATE operation, this function is called twice. Once before
  104866. ** the original record is deleted from the table using the calling convention
  104867. ** described for DELETE. Then again after the original record is deleted
  104868. ** but before the new record is inserted using the INSERT convention.
  104869. */
  104870. SQLITE_PRIVATE void sqlite3FkCheck(
  104871. Parse *pParse, /* Parse context */
  104872. Table *pTab, /* Row is being deleted from this table */
  104873. int regOld, /* Previous row data is stored here */
  104874. int regNew, /* New row data is stored here */
  104875. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  104876. int bChngRowid /* True if rowid is UPDATEd */
  104877. ){
  104878. sqlite3 *db = pParse->db; /* Database handle */
  104879. FKey *pFKey; /* Used to iterate through FKs */
  104880. int iDb; /* Index of database containing pTab */
  104881. const char *zDb; /* Name of database containing pTab */
  104882. int isIgnoreErrors = pParse->disableTriggers;
  104883. /* Exactly one of regOld and regNew should be non-zero. */
  104884. assert( (regOld==0)!=(regNew==0) );
  104885. /* If foreign-keys are disabled, this function is a no-op. */
  104886. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  104887. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  104888. zDb = db->aDb[iDb].zDbSName;
  104889. /* Loop through all the foreign key constraints for which pTab is the
  104890. ** child table (the table that the foreign key definition is part of). */
  104891. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  104892. Table *pTo; /* Parent table of foreign key pFKey */
  104893. Index *pIdx = 0; /* Index on key columns in pTo */
  104894. int *aiFree = 0;
  104895. int *aiCol;
  104896. int iCol;
  104897. int i;
  104898. int bIgnore = 0;
  104899. if( aChange
  104900. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  104901. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  104902. ){
  104903. continue;
  104904. }
  104905. /* Find the parent table of this foreign key. Also find a unique index
  104906. ** on the parent key columns in the parent table. If either of these
  104907. ** schema items cannot be located, set an error in pParse and return
  104908. ** early. */
  104909. if( pParse->disableTriggers ){
  104910. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  104911. }else{
  104912. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  104913. }
  104914. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  104915. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  104916. if( !isIgnoreErrors || db->mallocFailed ) return;
  104917. if( pTo==0 ){
  104918. /* If isIgnoreErrors is true, then a table is being dropped. In this
  104919. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  104920. ** before actually dropping it in order to check FK constraints.
  104921. ** If the parent table of an FK constraint on the current table is
  104922. ** missing, behave as if it is empty. i.e. decrement the relevant
  104923. ** FK counter for each row of the current table with non-NULL keys.
  104924. */
  104925. Vdbe *v = sqlite3GetVdbe(pParse);
  104926. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  104927. for(i=0; i<pFKey->nCol; i++){
  104928. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  104929. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  104930. }
  104931. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  104932. }
  104933. continue;
  104934. }
  104935. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  104936. if( aiFree ){
  104937. aiCol = aiFree;
  104938. }else{
  104939. iCol = pFKey->aCol[0].iFrom;
  104940. aiCol = &iCol;
  104941. }
  104942. for(i=0; i<pFKey->nCol; i++){
  104943. if( aiCol[i]==pTab->iPKey ){
  104944. aiCol[i] = -1;
  104945. }
  104946. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  104947. #ifndef SQLITE_OMIT_AUTHORIZATION
  104948. /* Request permission to read the parent key columns. If the
  104949. ** authorization callback returns SQLITE_IGNORE, behave as if any
  104950. ** values read from the parent table are NULL. */
  104951. if( db->xAuth ){
  104952. int rcauth;
  104953. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  104954. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  104955. bIgnore = (rcauth==SQLITE_IGNORE);
  104956. }
  104957. #endif
  104958. }
  104959. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  104960. ** a cursor to use to search the unique index on the parent key columns
  104961. ** in the parent table. */
  104962. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  104963. pParse->nTab++;
  104964. if( regOld!=0 ){
  104965. /* A row is being removed from the child table. Search for the parent.
  104966. ** If the parent does not exist, removing the child row resolves an
  104967. ** outstanding foreign key constraint violation. */
  104968. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  104969. }
  104970. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  104971. /* A row is being added to the child table. If a parent row cannot
  104972. ** be found, adding the child row has violated the FK constraint.
  104973. **
  104974. ** If this operation is being performed as part of a trigger program
  104975. ** that is actually a "SET NULL" action belonging to this very
  104976. ** foreign key, then omit this scan altogether. As all child key
  104977. ** values are guaranteed to be NULL, it is not possible for adding
  104978. ** this row to cause an FK violation. */
  104979. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  104980. }
  104981. sqlite3DbFree(db, aiFree);
  104982. }
  104983. /* Loop through all the foreign key constraints that refer to this table.
  104984. ** (the "child" constraints) */
  104985. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  104986. Index *pIdx = 0; /* Foreign key index for pFKey */
  104987. SrcList *pSrc;
  104988. int *aiCol = 0;
  104989. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  104990. continue;
  104991. }
  104992. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  104993. && !pParse->pToplevel && !pParse->isMultiWrite
  104994. ){
  104995. assert( regOld==0 && regNew!=0 );
  104996. /* Inserting a single row into a parent table cannot cause (or fix)
  104997. ** an immediate foreign key violation. So do nothing in this case. */
  104998. continue;
  104999. }
  105000. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  105001. if( !isIgnoreErrors || db->mallocFailed ) return;
  105002. continue;
  105003. }
  105004. assert( aiCol || pFKey->nCol==1 );
  105005. /* Create a SrcList structure containing the child table. We need the
  105006. ** child table as a SrcList for sqlite3WhereBegin() */
  105007. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  105008. if( pSrc ){
  105009. struct SrcList_item *pItem = pSrc->a;
  105010. pItem->pTab = pFKey->pFrom;
  105011. pItem->zName = pFKey->pFrom->zName;
  105012. pItem->pTab->nTabRef++;
  105013. pItem->iCursor = pParse->nTab++;
  105014. if( regNew!=0 ){
  105015. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  105016. }
  105017. if( regOld!=0 ){
  105018. int eAction = pFKey->aAction[aChange!=0];
  105019. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  105020. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  105021. ** action applies, then any foreign key violations caused by
  105022. ** removing the parent key will be rectified by the action trigger.
  105023. ** So do not set the "may-abort" flag in this case.
  105024. **
  105025. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  105026. ** may-abort flag will eventually be set on this statement anyway
  105027. ** (when this function is called as part of processing the UPDATE
  105028. ** within the action trigger).
  105029. **
  105030. ** Note 2: At first glance it may seem like SQLite could simply omit
  105031. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  105032. ** applies. The trouble starts if the CASCADE or SET NULL action
  105033. ** trigger causes other triggers or action rules attached to the
  105034. ** child table to fire. In these cases the fk constraint counters
  105035. ** might be set incorrectly if any OP_FkCounter related scans are
  105036. ** omitted. */
  105037. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  105038. sqlite3MayAbort(pParse);
  105039. }
  105040. }
  105041. pItem->zName = 0;
  105042. sqlite3SrcListDelete(db, pSrc);
  105043. }
  105044. sqlite3DbFree(db, aiCol);
  105045. }
  105046. }
  105047. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  105048. /*
  105049. ** This function is called before generating code to update or delete a
  105050. ** row contained in table pTab.
  105051. */
  105052. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  105053. Parse *pParse, /* Parse context */
  105054. Table *pTab /* Table being modified */
  105055. ){
  105056. u32 mask = 0;
  105057. if( pParse->db->flags&SQLITE_ForeignKeys ){
  105058. FKey *p;
  105059. int i;
  105060. for(p=pTab->pFKey; p; p=p->pNextFrom){
  105061. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  105062. }
  105063. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  105064. Index *pIdx = 0;
  105065. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  105066. if( pIdx ){
  105067. for(i=0; i<pIdx->nKeyCol; i++){
  105068. assert( pIdx->aiColumn[i]>=0 );
  105069. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  105070. }
  105071. }
  105072. }
  105073. }
  105074. return mask;
  105075. }
  105076. /*
  105077. ** This function is called before generating code to update or delete a
  105078. ** row contained in table pTab. If the operation is a DELETE, then
  105079. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  105080. ** to an array of size N, where N is the number of columns in table pTab.
  105081. ** If the i'th column is not modified by the UPDATE, then the corresponding
  105082. ** entry in the aChange[] array is set to -1. If the column is modified,
  105083. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  105084. ** UPDATE statement modifies the rowid fields of the table.
  105085. **
  105086. ** If any foreign key processing will be required, this function returns
  105087. ** non-zero. If there is no foreign key related processing, this function
  105088. ** returns zero.
  105089. **
  105090. ** For an UPDATE, this function returns 2 if:
  105091. **
  105092. ** * There are any FKs for which pTab is the child and the parent table, or
  105093. ** * the UPDATE modifies one or more parent keys for which the action is
  105094. ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
  105095. **
  105096. ** Or, assuming some other foreign key processing is required, 1.
  105097. */
  105098. SQLITE_PRIVATE int sqlite3FkRequired(
  105099. Parse *pParse, /* Parse context */
  105100. Table *pTab, /* Table being modified */
  105101. int *aChange, /* Non-NULL for UPDATE operations */
  105102. int chngRowid /* True for UPDATE that affects rowid */
  105103. ){
  105104. int eRet = 0;
  105105. if( pParse->db->flags&SQLITE_ForeignKeys ){
  105106. if( !aChange ){
  105107. /* A DELETE operation. Foreign key processing is required if the
  105108. ** table in question is either the child or parent table for any
  105109. ** foreign key constraint. */
  105110. eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
  105111. }else{
  105112. /* This is an UPDATE. Foreign key processing is only required if the
  105113. ** operation modifies one or more child or parent key columns. */
  105114. FKey *p;
  105115. /* Check if any child key columns are being modified. */
  105116. for(p=pTab->pFKey; p; p=p->pNextFrom){
  105117. if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
  105118. if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
  105119. eRet = 1;
  105120. }
  105121. }
  105122. /* Check if any parent key columns are being modified. */
  105123. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  105124. if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
  105125. if( p->aAction[1]!=OE_None ) return 2;
  105126. eRet = 1;
  105127. }
  105128. }
  105129. }
  105130. }
  105131. return eRet;
  105132. }
  105133. /*
  105134. ** This function is called when an UPDATE or DELETE operation is being
  105135. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  105136. ** If the current operation is an UPDATE, then the pChanges parameter is
  105137. ** passed a pointer to the list of columns being modified. If it is a
  105138. ** DELETE, pChanges is passed a NULL pointer.
  105139. **
  105140. ** It returns a pointer to a Trigger structure containing a trigger
  105141. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  105142. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  105143. ** returned (these actions require no special handling by the triggers
  105144. ** sub-system, code for them is created by fkScanChildren()).
  105145. **
  105146. ** For example, if pFKey is the foreign key and pTab is table "p" in
  105147. ** the following schema:
  105148. **
  105149. ** CREATE TABLE p(pk PRIMARY KEY);
  105150. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  105151. **
  105152. ** then the returned trigger structure is equivalent to:
  105153. **
  105154. ** CREATE TRIGGER ... DELETE ON p BEGIN
  105155. ** DELETE FROM c WHERE ck = old.pk;
  105156. ** END;
  105157. **
  105158. ** The returned pointer is cached as part of the foreign key object. It
  105159. ** is eventually freed along with the rest of the foreign key object by
  105160. ** sqlite3FkDelete().
  105161. */
  105162. static Trigger *fkActionTrigger(
  105163. Parse *pParse, /* Parse context */
  105164. Table *pTab, /* Table being updated or deleted from */
  105165. FKey *pFKey, /* Foreign key to get action for */
  105166. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  105167. ){
  105168. sqlite3 *db = pParse->db; /* Database handle */
  105169. int action; /* One of OE_None, OE_Cascade etc. */
  105170. Trigger *pTrigger; /* Trigger definition to return */
  105171. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  105172. action = pFKey->aAction[iAction];
  105173. if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
  105174. return 0;
  105175. }
  105176. pTrigger = pFKey->apTrigger[iAction];
  105177. if( action!=OE_None && !pTrigger ){
  105178. char const *zFrom; /* Name of child table */
  105179. int nFrom; /* Length in bytes of zFrom */
  105180. Index *pIdx = 0; /* Parent key index for this FK */
  105181. int *aiCol = 0; /* child table cols -> parent key cols */
  105182. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  105183. Expr *pWhere = 0; /* WHERE clause of trigger step */
  105184. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  105185. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  105186. int i; /* Iterator variable */
  105187. Expr *pWhen = 0; /* WHEN clause for the trigger */
  105188. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  105189. assert( aiCol || pFKey->nCol==1 );
  105190. for(i=0; i<pFKey->nCol; i++){
  105191. Token tOld = { "old", 3 }; /* Literal "old" token */
  105192. Token tNew = { "new", 3 }; /* Literal "new" token */
  105193. Token tFromCol; /* Name of column in child table */
  105194. Token tToCol; /* Name of column in parent table */
  105195. int iFromCol; /* Idx of column in child table */
  105196. Expr *pEq; /* tFromCol = OLD.tToCol */
  105197. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  105198. assert( iFromCol>=0 );
  105199. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  105200. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  105201. sqlite3TokenInit(&tToCol,
  105202. pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
  105203. sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
  105204. /* Create the expression "OLD.zToCol = zFromCol". It is important
  105205. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  105206. ** that the affinity and collation sequence associated with the
  105207. ** parent table are used for the comparison. */
  105208. pEq = sqlite3PExpr(pParse, TK_EQ,
  105209. sqlite3PExpr(pParse, TK_DOT,
  105210. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  105211. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  105212. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  105213. );
  105214. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  105215. /* For ON UPDATE, construct the next term of the WHEN clause.
  105216. ** The final WHEN clause will be like this:
  105217. **
  105218. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  105219. */
  105220. if( pChanges ){
  105221. pEq = sqlite3PExpr(pParse, TK_IS,
  105222. sqlite3PExpr(pParse, TK_DOT,
  105223. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  105224. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  105225. sqlite3PExpr(pParse, TK_DOT,
  105226. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  105227. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
  105228. );
  105229. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  105230. }
  105231. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  105232. Expr *pNew;
  105233. if( action==OE_Cascade ){
  105234. pNew = sqlite3PExpr(pParse, TK_DOT,
  105235. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  105236. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
  105237. }else if( action==OE_SetDflt ){
  105238. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  105239. if( pDflt ){
  105240. pNew = sqlite3ExprDup(db, pDflt, 0);
  105241. }else{
  105242. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  105243. }
  105244. }else{
  105245. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  105246. }
  105247. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  105248. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  105249. }
  105250. }
  105251. sqlite3DbFree(db, aiCol);
  105252. zFrom = pFKey->pFrom->zName;
  105253. nFrom = sqlite3Strlen30(zFrom);
  105254. if( action==OE_Restrict ){
  105255. Token tFrom;
  105256. Expr *pRaise;
  105257. tFrom.z = zFrom;
  105258. tFrom.n = nFrom;
  105259. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  105260. if( pRaise ){
  105261. pRaise->affinity = OE_Abort;
  105262. }
  105263. pSelect = sqlite3SelectNew(pParse,
  105264. sqlite3ExprListAppend(pParse, 0, pRaise),
  105265. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  105266. pWhere,
  105267. 0, 0, 0, 0, 0
  105268. );
  105269. pWhere = 0;
  105270. }
  105271. /* Disable lookaside memory allocation */
  105272. db->lookaside.bDisable++;
  105273. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  105274. sizeof(Trigger) + /* struct Trigger */
  105275. sizeof(TriggerStep) + /* Single step in trigger program */
  105276. nFrom + 1 /* Space for pStep->zTarget */
  105277. );
  105278. if( pTrigger ){
  105279. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  105280. pStep->zTarget = (char *)&pStep[1];
  105281. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  105282. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  105283. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  105284. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  105285. if( pWhen ){
  105286. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
  105287. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  105288. }
  105289. }
  105290. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  105291. db->lookaside.bDisable--;
  105292. sqlite3ExprDelete(db, pWhere);
  105293. sqlite3ExprDelete(db, pWhen);
  105294. sqlite3ExprListDelete(db, pList);
  105295. sqlite3SelectDelete(db, pSelect);
  105296. if( db->mallocFailed==1 ){
  105297. fkTriggerDelete(db, pTrigger);
  105298. return 0;
  105299. }
  105300. assert( pStep!=0 );
  105301. switch( action ){
  105302. case OE_Restrict:
  105303. pStep->op = TK_SELECT;
  105304. break;
  105305. case OE_Cascade:
  105306. if( !pChanges ){
  105307. pStep->op = TK_DELETE;
  105308. break;
  105309. }
  105310. default:
  105311. pStep->op = TK_UPDATE;
  105312. }
  105313. pStep->pTrig = pTrigger;
  105314. pTrigger->pSchema = pTab->pSchema;
  105315. pTrigger->pTabSchema = pTab->pSchema;
  105316. pFKey->apTrigger[iAction] = pTrigger;
  105317. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  105318. }
  105319. return pTrigger;
  105320. }
  105321. /*
  105322. ** This function is called when deleting or updating a row to implement
  105323. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  105324. */
  105325. SQLITE_PRIVATE void sqlite3FkActions(
  105326. Parse *pParse, /* Parse context */
  105327. Table *pTab, /* Table being updated or deleted from */
  105328. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  105329. int regOld, /* Address of array containing old row */
  105330. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  105331. int bChngRowid /* True if rowid is UPDATEd */
  105332. ){
  105333. /* If foreign-key support is enabled, iterate through all FKs that
  105334. ** refer to table pTab. If there is an action associated with the FK
  105335. ** for this operation (either update or delete), invoke the associated
  105336. ** trigger sub-program. */
  105337. if( pParse->db->flags&SQLITE_ForeignKeys ){
  105338. FKey *pFKey; /* Iterator variable */
  105339. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  105340. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  105341. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  105342. if( pAct ){
  105343. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  105344. }
  105345. }
  105346. }
  105347. }
  105348. }
  105349. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  105350. /*
  105351. ** Free all memory associated with foreign key definitions attached to
  105352. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  105353. ** hash table.
  105354. */
  105355. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  105356. FKey *pFKey; /* Iterator variable */
  105357. FKey *pNext; /* Copy of pFKey->pNextFrom */
  105358. assert( db==0 || IsVirtual(pTab)
  105359. || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  105360. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  105361. /* Remove the FK from the fkeyHash hash table. */
  105362. if( !db || db->pnBytesFreed==0 ){
  105363. if( pFKey->pPrevTo ){
  105364. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  105365. }else{
  105366. void *p = (void *)pFKey->pNextTo;
  105367. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  105368. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  105369. }
  105370. if( pFKey->pNextTo ){
  105371. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  105372. }
  105373. }
  105374. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  105375. ** classified as either immediate or deferred.
  105376. */
  105377. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  105378. /* Delete any triggers created to implement actions for this FK. */
  105379. #ifndef SQLITE_OMIT_TRIGGER
  105380. fkTriggerDelete(db, pFKey->apTrigger[0]);
  105381. fkTriggerDelete(db, pFKey->apTrigger[1]);
  105382. #endif
  105383. pNext = pFKey->pNextFrom;
  105384. sqlite3DbFree(db, pFKey);
  105385. }
  105386. }
  105387. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  105388. /************** End of fkey.c ************************************************/
  105389. /************** Begin file insert.c ******************************************/
  105390. /*
  105391. ** 2001 September 15
  105392. **
  105393. ** The author disclaims copyright to this source code. In place of
  105394. ** a legal notice, here is a blessing:
  105395. **
  105396. ** May you do good and not evil.
  105397. ** May you find forgiveness for yourself and forgive others.
  105398. ** May you share freely, never taking more than you give.
  105399. **
  105400. *************************************************************************
  105401. ** This file contains C code routines that are called by the parser
  105402. ** to handle INSERT statements in SQLite.
  105403. */
  105404. /* #include "sqliteInt.h" */
  105405. /*
  105406. ** Generate code that will
  105407. **
  105408. ** (1) acquire a lock for table pTab then
  105409. ** (2) open pTab as cursor iCur.
  105410. **
  105411. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  105412. ** for that table that is actually opened.
  105413. */
  105414. SQLITE_PRIVATE void sqlite3OpenTable(
  105415. Parse *pParse, /* Generate code into this VDBE */
  105416. int iCur, /* The cursor number of the table */
  105417. int iDb, /* The database index in sqlite3.aDb[] */
  105418. Table *pTab, /* The table to be opened */
  105419. int opcode /* OP_OpenRead or OP_OpenWrite */
  105420. ){
  105421. Vdbe *v;
  105422. assert( !IsVirtual(pTab) );
  105423. v = sqlite3GetVdbe(pParse);
  105424. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  105425. sqlite3TableLock(pParse, iDb, pTab->tnum,
  105426. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  105427. if( HasRowid(pTab) ){
  105428. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  105429. VdbeComment((v, "%s", pTab->zName));
  105430. }else{
  105431. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  105432. assert( pPk!=0 );
  105433. assert( pPk->tnum==pTab->tnum );
  105434. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  105435. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  105436. VdbeComment((v, "%s", pTab->zName));
  105437. }
  105438. }
  105439. /*
  105440. ** Return a pointer to the column affinity string associated with index
  105441. ** pIdx. A column affinity string has one character for each column in
  105442. ** the table, according to the affinity of the column:
  105443. **
  105444. ** Character Column affinity
  105445. ** ------------------------------
  105446. ** 'A' BLOB
  105447. ** 'B' TEXT
  105448. ** 'C' NUMERIC
  105449. ** 'D' INTEGER
  105450. ** 'F' REAL
  105451. **
  105452. ** An extra 'D' is appended to the end of the string to cover the
  105453. ** rowid that appears as the last column in every index.
  105454. **
  105455. ** Memory for the buffer containing the column index affinity string
  105456. ** is managed along with the rest of the Index structure. It will be
  105457. ** released when sqlite3DeleteIndex() is called.
  105458. */
  105459. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  105460. if( !pIdx->zColAff ){
  105461. /* The first time a column affinity string for a particular index is
  105462. ** required, it is allocated and populated here. It is then stored as
  105463. ** a member of the Index structure for subsequent use.
  105464. **
  105465. ** The column affinity string will eventually be deleted by
  105466. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  105467. ** up.
  105468. */
  105469. int n;
  105470. Table *pTab = pIdx->pTable;
  105471. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  105472. if( !pIdx->zColAff ){
  105473. sqlite3OomFault(db);
  105474. return 0;
  105475. }
  105476. for(n=0; n<pIdx->nColumn; n++){
  105477. i16 x = pIdx->aiColumn[n];
  105478. if( x>=0 ){
  105479. pIdx->zColAff[n] = pTab->aCol[x].affinity;
  105480. }else if( x==XN_ROWID ){
  105481. pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
  105482. }else{
  105483. char aff;
  105484. assert( x==XN_EXPR );
  105485. assert( pIdx->aColExpr!=0 );
  105486. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  105487. if( aff==0 ) aff = SQLITE_AFF_BLOB;
  105488. pIdx->zColAff[n] = aff;
  105489. }
  105490. }
  105491. pIdx->zColAff[n] = 0;
  105492. }
  105493. return pIdx->zColAff;
  105494. }
  105495. /*
  105496. ** Compute the affinity string for table pTab, if it has not already been
  105497. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  105498. **
  105499. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  105500. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  105501. ** for register iReg and following. Or if affinities exists and iReg==0,
  105502. ** then just set the P4 operand of the previous opcode (which should be
  105503. ** an OP_MakeRecord) to the affinity string.
  105504. **
  105505. ** A column affinity string has one character per column:
  105506. **
  105507. ** Character Column affinity
  105508. ** ------------------------------
  105509. ** 'A' BLOB
  105510. ** 'B' TEXT
  105511. ** 'C' NUMERIC
  105512. ** 'D' INTEGER
  105513. ** 'E' REAL
  105514. */
  105515. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  105516. int i;
  105517. char *zColAff = pTab->zColAff;
  105518. if( zColAff==0 ){
  105519. sqlite3 *db = sqlite3VdbeDb(v);
  105520. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  105521. if( !zColAff ){
  105522. sqlite3OomFault(db);
  105523. return;
  105524. }
  105525. for(i=0; i<pTab->nCol; i++){
  105526. zColAff[i] = pTab->aCol[i].affinity;
  105527. }
  105528. do{
  105529. zColAff[i--] = 0;
  105530. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  105531. pTab->zColAff = zColAff;
  105532. }
  105533. i = sqlite3Strlen30(zColAff);
  105534. if( i ){
  105535. if( iReg ){
  105536. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  105537. }else{
  105538. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  105539. }
  105540. }
  105541. }
  105542. /*
  105543. ** Return non-zero if the table pTab in database iDb or any of its indices
  105544. ** have been opened at any point in the VDBE program. This is used to see if
  105545. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  105546. ** run without using a temporary table for the results of the SELECT.
  105547. */
  105548. static int readsTable(Parse *p, int iDb, Table *pTab){
  105549. Vdbe *v = sqlite3GetVdbe(p);
  105550. int i;
  105551. int iEnd = sqlite3VdbeCurrentAddr(v);
  105552. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105553. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  105554. #endif
  105555. for(i=1; i<iEnd; i++){
  105556. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  105557. assert( pOp!=0 );
  105558. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  105559. Index *pIndex;
  105560. int tnum = pOp->p2;
  105561. if( tnum==pTab->tnum ){
  105562. return 1;
  105563. }
  105564. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  105565. if( tnum==pIndex->tnum ){
  105566. return 1;
  105567. }
  105568. }
  105569. }
  105570. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105571. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  105572. assert( pOp->p4.pVtab!=0 );
  105573. assert( pOp->p4type==P4_VTAB );
  105574. return 1;
  105575. }
  105576. #endif
  105577. }
  105578. return 0;
  105579. }
  105580. #ifndef SQLITE_OMIT_AUTOINCREMENT
  105581. /*
  105582. ** Locate or create an AutoincInfo structure associated with table pTab
  105583. ** which is in database iDb. Return the register number for the register
  105584. ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
  105585. ** table. (Also return zero when doing a VACUUM since we do not want to
  105586. ** update the AUTOINCREMENT counters during a VACUUM.)
  105587. **
  105588. ** There is at most one AutoincInfo structure per table even if the
  105589. ** same table is autoincremented multiple times due to inserts within
  105590. ** triggers. A new AutoincInfo structure is created if this is the
  105591. ** first use of table pTab. On 2nd and subsequent uses, the original
  105592. ** AutoincInfo structure is used.
  105593. **
  105594. ** Four consecutive registers are allocated:
  105595. **
  105596. ** (1) The name of the pTab table.
  105597. ** (2) The maximum ROWID of pTab.
  105598. ** (3) The rowid in sqlite_sequence of pTab
  105599. ** (4) The original value of the max ROWID in pTab, or NULL if none
  105600. **
  105601. ** The 2nd register is the one that is returned. That is all the
  105602. ** insert routine needs to know about.
  105603. */
  105604. static int autoIncBegin(
  105605. Parse *pParse, /* Parsing context */
  105606. int iDb, /* Index of the database holding pTab */
  105607. Table *pTab /* The table we are writing to */
  105608. ){
  105609. int memId = 0; /* Register holding maximum rowid */
  105610. if( (pTab->tabFlags & TF_Autoincrement)!=0
  105611. && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
  105612. ){
  105613. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  105614. AutoincInfo *pInfo;
  105615. pInfo = pToplevel->pAinc;
  105616. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  105617. if( pInfo==0 ){
  105618. pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
  105619. if( pInfo==0 ) return 0;
  105620. pInfo->pNext = pToplevel->pAinc;
  105621. pToplevel->pAinc = pInfo;
  105622. pInfo->pTab = pTab;
  105623. pInfo->iDb = iDb;
  105624. pToplevel->nMem++; /* Register to hold name of table */
  105625. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  105626. pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
  105627. }
  105628. memId = pInfo->regCtr;
  105629. }
  105630. return memId;
  105631. }
  105632. /*
  105633. ** This routine generates code that will initialize all of the
  105634. ** register used by the autoincrement tracker.
  105635. */
  105636. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  105637. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  105638. sqlite3 *db = pParse->db; /* The database connection */
  105639. Db *pDb; /* Database only autoinc table */
  105640. int memId; /* Register holding max rowid */
  105641. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  105642. /* This routine is never called during trigger-generation. It is
  105643. ** only called from the top-level */
  105644. assert( pParse->pTriggerTab==0 );
  105645. assert( sqlite3IsToplevel(pParse) );
  105646. assert( v ); /* We failed long ago if this is not so */
  105647. for(p = pParse->pAinc; p; p = p->pNext){
  105648. static const int iLn = VDBE_OFFSET_LINENO(2);
  105649. static const VdbeOpList autoInc[] = {
  105650. /* 0 */ {OP_Null, 0, 0, 0},
  105651. /* 1 */ {OP_Rewind, 0, 10, 0},
  105652. /* 2 */ {OP_Column, 0, 0, 0},
  105653. /* 3 */ {OP_Ne, 0, 9, 0},
  105654. /* 4 */ {OP_Rowid, 0, 0, 0},
  105655. /* 5 */ {OP_Column, 0, 1, 0},
  105656. /* 6 */ {OP_AddImm, 0, 0, 0},
  105657. /* 7 */ {OP_Copy, 0, 0, 0},
  105658. /* 8 */ {OP_Goto, 0, 11, 0},
  105659. /* 9 */ {OP_Next, 0, 2, 0},
  105660. /* 10 */ {OP_Integer, 0, 0, 0},
  105661. /* 11 */ {OP_Close, 0, 0, 0}
  105662. };
  105663. VdbeOp *aOp;
  105664. pDb = &db->aDb[p->iDb];
  105665. memId = p->regCtr;
  105666. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  105667. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  105668. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  105669. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
  105670. if( aOp==0 ) break;
  105671. aOp[0].p2 = memId;
  105672. aOp[0].p3 = memId+2;
  105673. aOp[2].p3 = memId;
  105674. aOp[3].p1 = memId-1;
  105675. aOp[3].p3 = memId;
  105676. aOp[3].p5 = SQLITE_JUMPIFNULL;
  105677. aOp[4].p2 = memId+1;
  105678. aOp[5].p3 = memId;
  105679. aOp[6].p1 = memId;
  105680. aOp[7].p2 = memId+2;
  105681. aOp[7].p1 = memId;
  105682. aOp[10].p2 = memId;
  105683. }
  105684. }
  105685. /*
  105686. ** Update the maximum rowid for an autoincrement calculation.
  105687. **
  105688. ** This routine should be called when the regRowid register holds a
  105689. ** new rowid that is about to be inserted. If that new rowid is
  105690. ** larger than the maximum rowid in the memId memory cell, then the
  105691. ** memory cell is updated.
  105692. */
  105693. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  105694. if( memId>0 ){
  105695. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  105696. }
  105697. }
  105698. /*
  105699. ** This routine generates the code needed to write autoincrement
  105700. ** maximum rowid values back into the sqlite_sequence register.
  105701. ** Every statement that might do an INSERT into an autoincrement
  105702. ** table (either directly or through triggers) needs to call this
  105703. ** routine just before the "exit" code.
  105704. */
  105705. static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
  105706. AutoincInfo *p;
  105707. Vdbe *v = pParse->pVdbe;
  105708. sqlite3 *db = pParse->db;
  105709. assert( v );
  105710. for(p = pParse->pAinc; p; p = p->pNext){
  105711. static const int iLn = VDBE_OFFSET_LINENO(2);
  105712. static const VdbeOpList autoIncEnd[] = {
  105713. /* 0 */ {OP_NotNull, 0, 2, 0},
  105714. /* 1 */ {OP_NewRowid, 0, 0, 0},
  105715. /* 2 */ {OP_MakeRecord, 0, 2, 0},
  105716. /* 3 */ {OP_Insert, 0, 0, 0},
  105717. /* 4 */ {OP_Close, 0, 0, 0}
  105718. };
  105719. VdbeOp *aOp;
  105720. Db *pDb = &db->aDb[p->iDb];
  105721. int iRec;
  105722. int memId = p->regCtr;
  105723. iRec = sqlite3GetTempReg(pParse);
  105724. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  105725. sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
  105726. VdbeCoverage(v);
  105727. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  105728. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
  105729. if( aOp==0 ) break;
  105730. aOp[0].p1 = memId+1;
  105731. aOp[1].p2 = memId+1;
  105732. aOp[2].p1 = memId-1;
  105733. aOp[2].p3 = iRec;
  105734. aOp[3].p2 = iRec;
  105735. aOp[3].p3 = memId+1;
  105736. aOp[3].p5 = OPFLAG_APPEND;
  105737. sqlite3ReleaseTempReg(pParse, iRec);
  105738. }
  105739. }
  105740. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  105741. if( pParse->pAinc ) autoIncrementEnd(pParse);
  105742. }
  105743. #else
  105744. /*
  105745. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  105746. ** above are all no-ops
  105747. */
  105748. # define autoIncBegin(A,B,C) (0)
  105749. # define autoIncStep(A,B,C)
  105750. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  105751. /* Forward declaration */
  105752. static int xferOptimization(
  105753. Parse *pParse, /* Parser context */
  105754. Table *pDest, /* The table we are inserting into */
  105755. Select *pSelect, /* A SELECT statement to use as the data source */
  105756. int onError, /* How to handle constraint errors */
  105757. int iDbDest /* The database of pDest */
  105758. );
  105759. /*
  105760. ** This routine is called to handle SQL of the following forms:
  105761. **
  105762. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  105763. ** insert into TABLE (IDLIST) select
  105764. ** insert into TABLE (IDLIST) default values
  105765. **
  105766. ** The IDLIST following the table name is always optional. If omitted,
  105767. ** then a list of all (non-hidden) columns for the table is substituted.
  105768. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  105769. ** is omitted.
  105770. **
  105771. ** For the pSelect parameter holds the values to be inserted for the
  105772. ** first two forms shown above. A VALUES clause is really just short-hand
  105773. ** for a SELECT statement that omits the FROM clause and everything else
  105774. ** that follows. If the pSelect parameter is NULL, that means that the
  105775. ** DEFAULT VALUES form of the INSERT statement is intended.
  105776. **
  105777. ** The code generated follows one of four templates. For a simple
  105778. ** insert with data coming from a single-row VALUES clause, the code executes
  105779. ** once straight down through. Pseudo-code follows (we call this
  105780. ** the "1st template"):
  105781. **
  105782. ** open write cursor to <table> and its indices
  105783. ** put VALUES clause expressions into registers
  105784. ** write the resulting record into <table>
  105785. ** cleanup
  105786. **
  105787. ** The three remaining templates assume the statement is of the form
  105788. **
  105789. ** INSERT INTO <table> SELECT ...
  105790. **
  105791. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  105792. ** in other words if the SELECT pulls all columns from a single table
  105793. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  105794. ** if <table2> and <table1> are distinct tables but have identical
  105795. ** schemas, including all the same indices, then a special optimization
  105796. ** is invoked that copies raw records from <table2> over to <table1>.
  105797. ** See the xferOptimization() function for the implementation of this
  105798. ** template. This is the 2nd template.
  105799. **
  105800. ** open a write cursor to <table>
  105801. ** open read cursor on <table2>
  105802. ** transfer all records in <table2> over to <table>
  105803. ** close cursors
  105804. ** foreach index on <table>
  105805. ** open a write cursor on the <table> index
  105806. ** open a read cursor on the corresponding <table2> index
  105807. ** transfer all records from the read to the write cursors
  105808. ** close cursors
  105809. ** end foreach
  105810. **
  105811. ** The 3rd template is for when the second template does not apply
  105812. ** and the SELECT clause does not read from <table> at any time.
  105813. ** The generated code follows this template:
  105814. **
  105815. ** X <- A
  105816. ** goto B
  105817. ** A: setup for the SELECT
  105818. ** loop over the rows in the SELECT
  105819. ** load values into registers R..R+n
  105820. ** yield X
  105821. ** end loop
  105822. ** cleanup after the SELECT
  105823. ** end-coroutine X
  105824. ** B: open write cursor to <table> and its indices
  105825. ** C: yield X, at EOF goto D
  105826. ** insert the select result into <table> from R..R+n
  105827. ** goto C
  105828. ** D: cleanup
  105829. **
  105830. ** The 4th template is used if the insert statement takes its
  105831. ** values from a SELECT but the data is being inserted into a table
  105832. ** that is also read as part of the SELECT. In the third form,
  105833. ** we have to use an intermediate table to store the results of
  105834. ** the select. The template is like this:
  105835. **
  105836. ** X <- A
  105837. ** goto B
  105838. ** A: setup for the SELECT
  105839. ** loop over the tables in the SELECT
  105840. ** load value into register R..R+n
  105841. ** yield X
  105842. ** end loop
  105843. ** cleanup after the SELECT
  105844. ** end co-routine R
  105845. ** B: open temp table
  105846. ** L: yield X, at EOF goto M
  105847. ** insert row from R..R+n into temp table
  105848. ** goto L
  105849. ** M: open write cursor to <table> and its indices
  105850. ** rewind temp table
  105851. ** C: loop over rows of intermediate table
  105852. ** transfer values form intermediate table into <table>
  105853. ** end loop
  105854. ** D: cleanup
  105855. */
  105856. SQLITE_PRIVATE void sqlite3Insert(
  105857. Parse *pParse, /* Parser context */
  105858. SrcList *pTabList, /* Name of table into which we are inserting */
  105859. Select *pSelect, /* A SELECT statement to use as the data source */
  105860. IdList *pColumn, /* Column names corresponding to IDLIST. */
  105861. int onError /* How to handle constraint errors */
  105862. ){
  105863. sqlite3 *db; /* The main database structure */
  105864. Table *pTab; /* The table to insert into. aka TABLE */
  105865. int i, j; /* Loop counters */
  105866. Vdbe *v; /* Generate code into this virtual machine */
  105867. Index *pIdx; /* For looping over indices of the table */
  105868. int nColumn; /* Number of columns in the data */
  105869. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  105870. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  105871. int iIdxCur = 0; /* First index cursor */
  105872. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  105873. int endOfLoop; /* Label for the end of the insertion loop */
  105874. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  105875. int addrInsTop = 0; /* Jump to label "D" */
  105876. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  105877. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  105878. int iDb; /* Index of database holding TABLE */
  105879. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  105880. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  105881. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  105882. u8 bIdListInOrder; /* True if IDLIST is in table order */
  105883. ExprList *pList = 0; /* List of VALUES() to be inserted */
  105884. /* Register allocations */
  105885. int regFromSelect = 0;/* Base register for data coming from SELECT */
  105886. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  105887. int regRowCount = 0; /* Memory cell used for the row counter */
  105888. int regIns; /* Block of regs holding rowid+data being inserted */
  105889. int regRowid; /* registers holding insert rowid */
  105890. int regData; /* register holding first column to insert */
  105891. int *aRegIdx = 0; /* One register allocated to each index */
  105892. #ifndef SQLITE_OMIT_TRIGGER
  105893. int isView; /* True if attempting to insert into a view */
  105894. Trigger *pTrigger; /* List of triggers on pTab, if required */
  105895. int tmask; /* Mask of trigger times */
  105896. #endif
  105897. db = pParse->db;
  105898. if( pParse->nErr || db->mallocFailed ){
  105899. goto insert_cleanup;
  105900. }
  105901. dest.iSDParm = 0; /* Suppress a harmless compiler warning */
  105902. /* If the Select object is really just a simple VALUES() list with a
  105903. ** single row (the common case) then keep that one row of values
  105904. ** and discard the other (unused) parts of the pSelect object
  105905. */
  105906. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  105907. pList = pSelect->pEList;
  105908. pSelect->pEList = 0;
  105909. sqlite3SelectDelete(db, pSelect);
  105910. pSelect = 0;
  105911. }
  105912. /* Locate the table into which we will be inserting new information.
  105913. */
  105914. assert( pTabList->nSrc==1 );
  105915. pTab = sqlite3SrcListLookup(pParse, pTabList);
  105916. if( pTab==0 ){
  105917. goto insert_cleanup;
  105918. }
  105919. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105920. assert( iDb<db->nDb );
  105921. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
  105922. db->aDb[iDb].zDbSName) ){
  105923. goto insert_cleanup;
  105924. }
  105925. withoutRowid = !HasRowid(pTab);
  105926. /* Figure out if we have any triggers and if the table being
  105927. ** inserted into is a view
  105928. */
  105929. #ifndef SQLITE_OMIT_TRIGGER
  105930. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  105931. isView = pTab->pSelect!=0;
  105932. #else
  105933. # define pTrigger 0
  105934. # define tmask 0
  105935. # define isView 0
  105936. #endif
  105937. #ifdef SQLITE_OMIT_VIEW
  105938. # undef isView
  105939. # define isView 0
  105940. #endif
  105941. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  105942. /* If pTab is really a view, make sure it has been initialized.
  105943. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  105944. */
  105945. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  105946. goto insert_cleanup;
  105947. }
  105948. /* Cannot insert into a read-only table.
  105949. */
  105950. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  105951. goto insert_cleanup;
  105952. }
  105953. /* Allocate a VDBE
  105954. */
  105955. v = sqlite3GetVdbe(pParse);
  105956. if( v==0 ) goto insert_cleanup;
  105957. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  105958. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  105959. #ifndef SQLITE_OMIT_XFER_OPT
  105960. /* If the statement is of the form
  105961. **
  105962. ** INSERT INTO <table1> SELECT * FROM <table2>;
  105963. **
  105964. ** Then special optimizations can be applied that make the transfer
  105965. ** very fast and which reduce fragmentation of indices.
  105966. **
  105967. ** This is the 2nd template.
  105968. */
  105969. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  105970. assert( !pTrigger );
  105971. assert( pList==0 );
  105972. goto insert_end;
  105973. }
  105974. #endif /* SQLITE_OMIT_XFER_OPT */
  105975. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  105976. ** sqlite_sequence table and store it in memory cell regAutoinc.
  105977. */
  105978. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  105979. /* Allocate registers for holding the rowid of the new row,
  105980. ** the content of the new row, and the assembled row record.
  105981. */
  105982. regRowid = regIns = pParse->nMem+1;
  105983. pParse->nMem += pTab->nCol + 1;
  105984. if( IsVirtual(pTab) ){
  105985. regRowid++;
  105986. pParse->nMem++;
  105987. }
  105988. regData = regRowid+1;
  105989. /* If the INSERT statement included an IDLIST term, then make sure
  105990. ** all elements of the IDLIST really are columns of the table and
  105991. ** remember the column indices.
  105992. **
  105993. ** If the table has an INTEGER PRIMARY KEY column and that column
  105994. ** is named in the IDLIST, then record in the ipkColumn variable
  105995. ** the index into IDLIST of the primary key column. ipkColumn is
  105996. ** the index of the primary key as it appears in IDLIST, not as
  105997. ** is appears in the original table. (The index of the INTEGER
  105998. ** PRIMARY KEY in the original table is pTab->iPKey.)
  105999. */
  106000. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  106001. if( pColumn ){
  106002. for(i=0; i<pColumn->nId; i++){
  106003. pColumn->a[i].idx = -1;
  106004. }
  106005. for(i=0; i<pColumn->nId; i++){
  106006. for(j=0; j<pTab->nCol; j++){
  106007. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  106008. pColumn->a[i].idx = j;
  106009. if( i!=j ) bIdListInOrder = 0;
  106010. if( j==pTab->iPKey ){
  106011. ipkColumn = i; assert( !withoutRowid );
  106012. }
  106013. break;
  106014. }
  106015. }
  106016. if( j>=pTab->nCol ){
  106017. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  106018. ipkColumn = i;
  106019. bIdListInOrder = 0;
  106020. }else{
  106021. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  106022. pTabList, 0, pColumn->a[i].zName);
  106023. pParse->checkSchema = 1;
  106024. goto insert_cleanup;
  106025. }
  106026. }
  106027. }
  106028. }
  106029. /* Figure out how many columns of data are supplied. If the data
  106030. ** is coming from a SELECT statement, then generate a co-routine that
  106031. ** produces a single row of the SELECT on each invocation. The
  106032. ** co-routine is the common header to the 3rd and 4th templates.
  106033. */
  106034. if( pSelect ){
  106035. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  106036. ** Generate a co-routine to run the SELECT. */
  106037. int regYield; /* Register holding co-routine entry-point */
  106038. int addrTop; /* Top of the co-routine */
  106039. int rc; /* Result code */
  106040. regYield = ++pParse->nMem;
  106041. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  106042. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  106043. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  106044. dest.iSdst = bIdListInOrder ? regData : 0;
  106045. dest.nSdst = pTab->nCol;
  106046. rc = sqlite3Select(pParse, pSelect, &dest);
  106047. regFromSelect = dest.iSdst;
  106048. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  106049. sqlite3VdbeEndCoroutine(v, regYield);
  106050. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  106051. assert( pSelect->pEList );
  106052. nColumn = pSelect->pEList->nExpr;
  106053. /* Set useTempTable to TRUE if the result of the SELECT statement
  106054. ** should be written into a temporary table (template 4). Set to
  106055. ** FALSE if each output row of the SELECT can be written directly into
  106056. ** the destination table (template 3).
  106057. **
  106058. ** A temp table must be used if the table being updated is also one
  106059. ** of the tables being read by the SELECT statement. Also use a
  106060. ** temp table in the case of row triggers.
  106061. */
  106062. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  106063. useTempTable = 1;
  106064. }
  106065. if( useTempTable ){
  106066. /* Invoke the coroutine to extract information from the SELECT
  106067. ** and add it to a transient table srcTab. The code generated
  106068. ** here is from the 4th template:
  106069. **
  106070. ** B: open temp table
  106071. ** L: yield X, goto M at EOF
  106072. ** insert row from R..R+n into temp table
  106073. ** goto L
  106074. ** M: ...
  106075. */
  106076. int regRec; /* Register to hold packed record */
  106077. int regTempRowid; /* Register to hold temp table ROWID */
  106078. int addrL; /* Label "L" */
  106079. srcTab = pParse->nTab++;
  106080. regRec = sqlite3GetTempReg(pParse);
  106081. regTempRowid = sqlite3GetTempReg(pParse);
  106082. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  106083. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  106084. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  106085. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  106086. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  106087. sqlite3VdbeGoto(v, addrL);
  106088. sqlite3VdbeJumpHere(v, addrL);
  106089. sqlite3ReleaseTempReg(pParse, regRec);
  106090. sqlite3ReleaseTempReg(pParse, regTempRowid);
  106091. }
  106092. }else{
  106093. /* This is the case if the data for the INSERT is coming from a
  106094. ** single-row VALUES clause
  106095. */
  106096. NameContext sNC;
  106097. memset(&sNC, 0, sizeof(sNC));
  106098. sNC.pParse = pParse;
  106099. srcTab = -1;
  106100. assert( useTempTable==0 );
  106101. if( pList ){
  106102. nColumn = pList->nExpr;
  106103. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  106104. goto insert_cleanup;
  106105. }
  106106. }else{
  106107. nColumn = 0;
  106108. }
  106109. }
  106110. /* If there is no IDLIST term but the table has an integer primary
  106111. ** key, the set the ipkColumn variable to the integer primary key
  106112. ** column index in the original table definition.
  106113. */
  106114. if( pColumn==0 && nColumn>0 ){
  106115. ipkColumn = pTab->iPKey;
  106116. }
  106117. /* Make sure the number of columns in the source data matches the number
  106118. ** of columns to be inserted into the table.
  106119. */
  106120. for(i=0; i<pTab->nCol; i++){
  106121. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  106122. }
  106123. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  106124. sqlite3ErrorMsg(pParse,
  106125. "table %S has %d columns but %d values were supplied",
  106126. pTabList, 0, pTab->nCol-nHidden, nColumn);
  106127. goto insert_cleanup;
  106128. }
  106129. if( pColumn!=0 && nColumn!=pColumn->nId ){
  106130. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  106131. goto insert_cleanup;
  106132. }
  106133. /* Initialize the count of rows to be inserted
  106134. */
  106135. if( db->flags & SQLITE_CountRows ){
  106136. regRowCount = ++pParse->nMem;
  106137. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  106138. }
  106139. /* If this is not a view, open the table and and all indices */
  106140. if( !isView ){
  106141. int nIdx;
  106142. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  106143. &iDataCur, &iIdxCur);
  106144. aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
  106145. if( aRegIdx==0 ){
  106146. goto insert_cleanup;
  106147. }
  106148. for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
  106149. assert( pIdx );
  106150. aRegIdx[i] = ++pParse->nMem;
  106151. pParse->nMem += pIdx->nColumn;
  106152. }
  106153. }
  106154. /* This is the top of the main insertion loop */
  106155. if( useTempTable ){
  106156. /* This block codes the top of loop only. The complete loop is the
  106157. ** following pseudocode (template 4):
  106158. **
  106159. ** rewind temp table, if empty goto D
  106160. ** C: loop over rows of intermediate table
  106161. ** transfer values form intermediate table into <table>
  106162. ** end loop
  106163. ** D: ...
  106164. */
  106165. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  106166. addrCont = sqlite3VdbeCurrentAddr(v);
  106167. }else if( pSelect ){
  106168. /* This block codes the top of loop only. The complete loop is the
  106169. ** following pseudocode (template 3):
  106170. **
  106171. ** C: yield X, at EOF goto D
  106172. ** insert the select result into <table> from R..R+n
  106173. ** goto C
  106174. ** D: ...
  106175. */
  106176. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  106177. VdbeCoverage(v);
  106178. }
  106179. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  106180. */
  106181. endOfLoop = sqlite3VdbeMakeLabel(v);
  106182. if( tmask & TRIGGER_BEFORE ){
  106183. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  106184. /* build the NEW.* reference row. Note that if there is an INTEGER
  106185. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  106186. ** translated into a unique ID for the row. But on a BEFORE trigger,
  106187. ** we do not know what the unique ID will be (because the insert has
  106188. ** not happened yet) so we substitute a rowid of -1
  106189. */
  106190. if( ipkColumn<0 ){
  106191. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  106192. }else{
  106193. int addr1;
  106194. assert( !withoutRowid );
  106195. if( useTempTable ){
  106196. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  106197. }else{
  106198. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  106199. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  106200. }
  106201. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  106202. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  106203. sqlite3VdbeJumpHere(v, addr1);
  106204. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  106205. }
  106206. /* Cannot have triggers on a virtual table. If it were possible,
  106207. ** this block would have to account for hidden column.
  106208. */
  106209. assert( !IsVirtual(pTab) );
  106210. /* Create the new column data
  106211. */
  106212. for(i=j=0; i<pTab->nCol; i++){
  106213. if( pColumn ){
  106214. for(j=0; j<pColumn->nId; j++){
  106215. if( pColumn->a[j].idx==i ) break;
  106216. }
  106217. }
  106218. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
  106219. || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
  106220. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  106221. }else if( useTempTable ){
  106222. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  106223. }else{
  106224. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  106225. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  106226. }
  106227. if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
  106228. }
  106229. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  106230. ** do not attempt any conversions before assembling the record.
  106231. ** If this is a real table, attempt conversions as required by the
  106232. ** table column affinities.
  106233. */
  106234. if( !isView ){
  106235. sqlite3TableAffinity(v, pTab, regCols+1);
  106236. }
  106237. /* Fire BEFORE or INSTEAD OF triggers */
  106238. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  106239. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  106240. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  106241. }
  106242. /* Compute the content of the next row to insert into a range of
  106243. ** registers beginning at regIns.
  106244. */
  106245. if( !isView ){
  106246. if( IsVirtual(pTab) ){
  106247. /* The row that the VUpdate opcode will delete: none */
  106248. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  106249. }
  106250. if( ipkColumn>=0 ){
  106251. if( useTempTable ){
  106252. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  106253. }else if( pSelect ){
  106254. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  106255. }else{
  106256. VdbeOp *pOp;
  106257. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  106258. pOp = sqlite3VdbeGetOp(v, -1);
  106259. assert( pOp!=0 );
  106260. if( pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  106261. appendFlag = 1;
  106262. pOp->opcode = OP_NewRowid;
  106263. pOp->p1 = iDataCur;
  106264. pOp->p2 = regRowid;
  106265. pOp->p3 = regAutoinc;
  106266. }
  106267. }
  106268. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  106269. ** to generate a unique primary key value.
  106270. */
  106271. if( !appendFlag ){
  106272. int addr1;
  106273. if( !IsVirtual(pTab) ){
  106274. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  106275. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  106276. sqlite3VdbeJumpHere(v, addr1);
  106277. }else{
  106278. addr1 = sqlite3VdbeCurrentAddr(v);
  106279. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  106280. }
  106281. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  106282. }
  106283. }else if( IsVirtual(pTab) || withoutRowid ){
  106284. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  106285. }else{
  106286. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  106287. appendFlag = 1;
  106288. }
  106289. autoIncStep(pParse, regAutoinc, regRowid);
  106290. /* Compute data for all columns of the new entry, beginning
  106291. ** with the first column.
  106292. */
  106293. nHidden = 0;
  106294. for(i=0; i<pTab->nCol; i++){
  106295. int iRegStore = regRowid+1+i;
  106296. if( i==pTab->iPKey ){
  106297. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  106298. ** Whenever this column is read, the rowid will be substituted
  106299. ** in its place. Hence, fill this column with a NULL to avoid
  106300. ** taking up data space with information that will never be used.
  106301. ** As there may be shallow copies of this value, make it a soft-NULL */
  106302. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  106303. continue;
  106304. }
  106305. if( pColumn==0 ){
  106306. if( IsHiddenColumn(&pTab->aCol[i]) ){
  106307. j = -1;
  106308. nHidden++;
  106309. }else{
  106310. j = i - nHidden;
  106311. }
  106312. }else{
  106313. for(j=0; j<pColumn->nId; j++){
  106314. if( pColumn->a[j].idx==i ) break;
  106315. }
  106316. }
  106317. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  106318. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  106319. }else if( useTempTable ){
  106320. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  106321. }else if( pSelect ){
  106322. if( regFromSelect!=regData ){
  106323. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  106324. }
  106325. }else{
  106326. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  106327. }
  106328. }
  106329. /* Generate code to check constraints and generate index keys and
  106330. ** do the insertion.
  106331. */
  106332. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106333. if( IsVirtual(pTab) ){
  106334. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  106335. sqlite3VtabMakeWritable(pParse, pTab);
  106336. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  106337. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  106338. sqlite3MayAbort(pParse);
  106339. }else
  106340. #endif
  106341. {
  106342. int isReplace; /* Set to true if constraints may cause a replace */
  106343. int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
  106344. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  106345. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
  106346. );
  106347. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  106348. /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
  106349. ** constraints or (b) there are no triggers and this table is not a
  106350. ** parent table in a foreign key constraint. It is safe to set the
  106351. ** flag in the second case as if any REPLACE constraint is hit, an
  106352. ** OP_Delete or OP_IdxDelete instruction will be executed on each
  106353. ** cursor that is disturbed. And these instructions both clear the
  106354. ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
  106355. ** functionality. */
  106356. bUseSeek = (isReplace==0 || (pTrigger==0 &&
  106357. ((db->flags & SQLITE_ForeignKeys)==0 || sqlite3FkReferences(pTab)==0)
  106358. ));
  106359. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  106360. regIns, aRegIdx, 0, appendFlag, bUseSeek
  106361. );
  106362. }
  106363. }
  106364. /* Update the count of rows that are inserted
  106365. */
  106366. if( (db->flags & SQLITE_CountRows)!=0 ){
  106367. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  106368. }
  106369. if( pTrigger ){
  106370. /* Code AFTER triggers */
  106371. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  106372. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  106373. }
  106374. /* The bottom of the main insertion loop, if the data source
  106375. ** is a SELECT statement.
  106376. */
  106377. sqlite3VdbeResolveLabel(v, endOfLoop);
  106378. if( useTempTable ){
  106379. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  106380. sqlite3VdbeJumpHere(v, addrInsTop);
  106381. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  106382. }else if( pSelect ){
  106383. sqlite3VdbeGoto(v, addrCont);
  106384. sqlite3VdbeJumpHere(v, addrInsTop);
  106385. }
  106386. insert_end:
  106387. /* Update the sqlite_sequence table by storing the content of the
  106388. ** maximum rowid counter values recorded while inserting into
  106389. ** autoincrement tables.
  106390. */
  106391. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  106392. sqlite3AutoincrementEnd(pParse);
  106393. }
  106394. /*
  106395. ** Return the number of rows inserted. If this routine is
  106396. ** generating code because of a call to sqlite3NestedParse(), do not
  106397. ** invoke the callback function.
  106398. */
  106399. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  106400. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  106401. sqlite3VdbeSetNumCols(v, 1);
  106402. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  106403. }
  106404. insert_cleanup:
  106405. sqlite3SrcListDelete(db, pTabList);
  106406. sqlite3ExprListDelete(db, pList);
  106407. sqlite3SelectDelete(db, pSelect);
  106408. sqlite3IdListDelete(db, pColumn);
  106409. sqlite3DbFree(db, aRegIdx);
  106410. }
  106411. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  106412. ** they may interfere with compilation of other functions in this file
  106413. ** (or in another file, if this file becomes part of the amalgamation). */
  106414. #ifdef isView
  106415. #undef isView
  106416. #endif
  106417. #ifdef pTrigger
  106418. #undef pTrigger
  106419. #endif
  106420. #ifdef tmask
  106421. #undef tmask
  106422. #endif
  106423. /*
  106424. ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
  106425. */
  106426. #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
  106427. #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
  106428. /* This is the Walker callback from checkConstraintUnchanged(). Set
  106429. ** bit 0x01 of pWalker->eCode if
  106430. ** pWalker->eCode to 0 if this expression node references any of the
  106431. ** columns that are being modifed by an UPDATE statement.
  106432. */
  106433. static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  106434. if( pExpr->op==TK_COLUMN ){
  106435. assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  106436. if( pExpr->iColumn>=0 ){
  106437. if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  106438. pWalker->eCode |= CKCNSTRNT_COLUMN;
  106439. }
  106440. }else{
  106441. pWalker->eCode |= CKCNSTRNT_ROWID;
  106442. }
  106443. }
  106444. return WRC_Continue;
  106445. }
  106446. /*
  106447. ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
  106448. ** only columns that are modified by the UPDATE are those for which
  106449. ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  106450. **
  106451. ** Return true if CHECK constraint pExpr does not use any of the
  106452. ** changing columns (or the rowid if it is changing). In other words,
  106453. ** return true if this CHECK constraint can be skipped when validating
  106454. ** the new row in the UPDATE statement.
  106455. */
  106456. static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
  106457. Walker w;
  106458. memset(&w, 0, sizeof(w));
  106459. w.eCode = 0;
  106460. w.xExprCallback = checkConstraintExprNode;
  106461. w.u.aiCol = aiChng;
  106462. sqlite3WalkExpr(&w, pExpr);
  106463. if( !chngRowid ){
  106464. testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  106465. w.eCode &= ~CKCNSTRNT_ROWID;
  106466. }
  106467. testcase( w.eCode==0 );
  106468. testcase( w.eCode==CKCNSTRNT_COLUMN );
  106469. testcase( w.eCode==CKCNSTRNT_ROWID );
  106470. testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  106471. return !w.eCode;
  106472. }
  106473. /*
  106474. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  106475. ** on table pTab.
  106476. **
  106477. ** The regNewData parameter is the first register in a range that contains
  106478. ** the data to be inserted or the data after the update. There will be
  106479. ** pTab->nCol+1 registers in this range. The first register (the one
  106480. ** that regNewData points to) will contain the new rowid, or NULL in the
  106481. ** case of a WITHOUT ROWID table. The second register in the range will
  106482. ** contain the content of the first table column. The third register will
  106483. ** contain the content of the second table column. And so forth.
  106484. **
  106485. ** The regOldData parameter is similar to regNewData except that it contains
  106486. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  106487. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  106488. ** checking regOldData for zero.
  106489. **
  106490. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  106491. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  106492. ** might be modified by the UPDATE. If pkChng is false, then the key of
  106493. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  106494. **
  106495. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  106496. ** was explicitly specified as part of the INSERT statement. If pkChng
  106497. ** is zero, it means that the either rowid is computed automatically or
  106498. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  106499. ** pkChng will only be true if the INSERT statement provides an integer
  106500. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  106501. **
  106502. ** The code generated by this routine will store new index entries into
  106503. ** registers identified by aRegIdx[]. No index entry is created for
  106504. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  106505. ** the same as the order of indices on the linked list of indices
  106506. ** at pTab->pIndex.
  106507. **
  106508. ** The caller must have already opened writeable cursors on the main
  106509. ** table and all applicable indices (that is to say, all indices for which
  106510. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  106511. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  106512. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  106513. ** for the first index in the pTab->pIndex list. Cursors for other indices
  106514. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  106515. **
  106516. ** This routine also generates code to check constraints. NOT NULL,
  106517. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  106518. ** then the appropriate action is performed. There are five possible
  106519. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  106520. **
  106521. ** Constraint type Action What Happens
  106522. ** --------------- ---------- ----------------------------------------
  106523. ** any ROLLBACK The current transaction is rolled back and
  106524. ** sqlite3_step() returns immediately with a
  106525. ** return code of SQLITE_CONSTRAINT.
  106526. **
  106527. ** any ABORT Back out changes from the current command
  106528. ** only (do not do a complete rollback) then
  106529. ** cause sqlite3_step() to return immediately
  106530. ** with SQLITE_CONSTRAINT.
  106531. **
  106532. ** any FAIL Sqlite3_step() returns immediately with a
  106533. ** return code of SQLITE_CONSTRAINT. The
  106534. ** transaction is not rolled back and any
  106535. ** changes to prior rows are retained.
  106536. **
  106537. ** any IGNORE The attempt in insert or update the current
  106538. ** row is skipped, without throwing an error.
  106539. ** Processing continues with the next row.
  106540. ** (There is an immediate jump to ignoreDest.)
  106541. **
  106542. ** NOT NULL REPLACE The NULL value is replace by the default
  106543. ** value for that column. If the default value
  106544. ** is NULL, the action is the same as ABORT.
  106545. **
  106546. ** UNIQUE REPLACE The other row that conflicts with the row
  106547. ** being inserted is removed.
  106548. **
  106549. ** CHECK REPLACE Illegal. The results in an exception.
  106550. **
  106551. ** Which action to take is determined by the overrideError parameter.
  106552. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  106553. ** is used. Or if pParse->onError==OE_Default then the onError value
  106554. ** for the constraint is used.
  106555. */
  106556. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  106557. Parse *pParse, /* The parser context */
  106558. Table *pTab, /* The table being inserted or updated */
  106559. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  106560. int iDataCur, /* Canonical data cursor (main table or PK index) */
  106561. int iIdxCur, /* First index cursor */
  106562. int regNewData, /* First register in a range holding values to insert */
  106563. int regOldData, /* Previous content. 0 for INSERTs */
  106564. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  106565. u8 overrideError, /* Override onError to this if not OE_Default */
  106566. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  106567. int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
  106568. int *aiChng /* column i is unchanged if aiChng[i]<0 */
  106569. ){
  106570. Vdbe *v; /* VDBE under constrution */
  106571. Index *pIdx; /* Pointer to one of the indices */
  106572. Index *pPk = 0; /* The PRIMARY KEY index */
  106573. sqlite3 *db; /* Database connection */
  106574. int i; /* loop counter */
  106575. int ix; /* Index loop counter */
  106576. int nCol; /* Number of columns */
  106577. int onError; /* Conflict resolution strategy */
  106578. int addr1; /* Address of jump instruction */
  106579. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  106580. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  106581. int ipkTop = 0; /* Top of the rowid change constraint check */
  106582. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  106583. u8 isUpdate; /* True if this is an UPDATE operation */
  106584. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  106585. isUpdate = regOldData!=0;
  106586. db = pParse->db;
  106587. v = sqlite3GetVdbe(pParse);
  106588. assert( v!=0 );
  106589. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  106590. nCol = pTab->nCol;
  106591. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  106592. ** normal rowid tables. nPkField is the number of key fields in the
  106593. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  106594. ** number of fields in the true primary key of the table. */
  106595. if( HasRowid(pTab) ){
  106596. pPk = 0;
  106597. nPkField = 1;
  106598. }else{
  106599. pPk = sqlite3PrimaryKeyIndex(pTab);
  106600. nPkField = pPk->nKeyCol;
  106601. }
  106602. /* Record that this module has started */
  106603. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  106604. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  106605. /* Test all NOT NULL constraints.
  106606. */
  106607. for(i=0; i<nCol; i++){
  106608. if( i==pTab->iPKey ){
  106609. continue; /* ROWID is never NULL */
  106610. }
  106611. if( aiChng && aiChng[i]<0 ){
  106612. /* Don't bother checking for NOT NULL on columns that do not change */
  106613. continue;
  106614. }
  106615. onError = pTab->aCol[i].notNull;
  106616. if( onError==OE_None ) continue; /* This column is allowed to be NULL */
  106617. if( overrideError!=OE_Default ){
  106618. onError = overrideError;
  106619. }else if( onError==OE_Default ){
  106620. onError = OE_Abort;
  106621. }
  106622. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  106623. onError = OE_Abort;
  106624. }
  106625. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  106626. || onError==OE_Ignore || onError==OE_Replace );
  106627. switch( onError ){
  106628. case OE_Abort:
  106629. sqlite3MayAbort(pParse);
  106630. /* Fall through */
  106631. case OE_Rollback:
  106632. case OE_Fail: {
  106633. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  106634. pTab->aCol[i].zName);
  106635. sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  106636. regNewData+1+i);
  106637. sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
  106638. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  106639. VdbeCoverage(v);
  106640. break;
  106641. }
  106642. case OE_Ignore: {
  106643. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  106644. VdbeCoverage(v);
  106645. break;
  106646. }
  106647. default: {
  106648. assert( onError==OE_Replace );
  106649. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
  106650. VdbeCoverage(v);
  106651. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  106652. sqlite3VdbeJumpHere(v, addr1);
  106653. break;
  106654. }
  106655. }
  106656. }
  106657. /* Test all CHECK constraints
  106658. */
  106659. #ifndef SQLITE_OMIT_CHECK
  106660. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  106661. ExprList *pCheck = pTab->pCheck;
  106662. pParse->iSelfTab = -(regNewData+1);
  106663. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  106664. for(i=0; i<pCheck->nExpr; i++){
  106665. int allOk;
  106666. Expr *pExpr = pCheck->a[i].pExpr;
  106667. if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
  106668. allOk = sqlite3VdbeMakeLabel(v);
  106669. sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
  106670. if( onError==OE_Ignore ){
  106671. sqlite3VdbeGoto(v, ignoreDest);
  106672. }else{
  106673. char *zName = pCheck->a[i].zName;
  106674. if( zName==0 ) zName = pTab->zName;
  106675. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  106676. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  106677. onError, zName, P4_TRANSIENT,
  106678. P5_ConstraintCheck);
  106679. }
  106680. sqlite3VdbeResolveLabel(v, allOk);
  106681. }
  106682. pParse->iSelfTab = 0;
  106683. }
  106684. #endif /* !defined(SQLITE_OMIT_CHECK) */
  106685. /* If rowid is changing, make sure the new rowid does not previously
  106686. ** exist in the table.
  106687. */
  106688. if( pkChng && pPk==0 ){
  106689. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  106690. /* Figure out what action to take in case of a rowid collision */
  106691. onError = pTab->keyConf;
  106692. if( overrideError!=OE_Default ){
  106693. onError = overrideError;
  106694. }else if( onError==OE_Default ){
  106695. onError = OE_Abort;
  106696. }
  106697. if( isUpdate ){
  106698. /* pkChng!=0 does not mean that the rowid has changed, only that
  106699. ** it might have changed. Skip the conflict logic below if the rowid
  106700. ** is unchanged. */
  106701. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  106702. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  106703. VdbeCoverage(v);
  106704. }
  106705. /* If the response to a rowid conflict is REPLACE but the response
  106706. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  106707. ** to defer the running of the rowid conflict checking until after
  106708. ** the UNIQUE constraints have run.
  106709. */
  106710. if( onError==OE_Replace && overrideError!=OE_Replace ){
  106711. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  106712. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  106713. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  106714. break;
  106715. }
  106716. }
  106717. }
  106718. /* Check to see if the new rowid already exists in the table. Skip
  106719. ** the following conflict logic if it does not. */
  106720. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  106721. VdbeCoverage(v);
  106722. /* Generate code that deals with a rowid collision */
  106723. switch( onError ){
  106724. default: {
  106725. onError = OE_Abort;
  106726. /* Fall thru into the next case */
  106727. }
  106728. case OE_Rollback:
  106729. case OE_Abort:
  106730. case OE_Fail: {
  106731. sqlite3RowidConstraint(pParse, onError, pTab);
  106732. break;
  106733. }
  106734. case OE_Replace: {
  106735. /* If there are DELETE triggers on this table and the
  106736. ** recursive-triggers flag is set, call GenerateRowDelete() to
  106737. ** remove the conflicting row from the table. This will fire
  106738. ** the triggers and remove both the table and index b-tree entries.
  106739. **
  106740. ** Otherwise, if there are no triggers or the recursive-triggers
  106741. ** flag is not set, but the table has one or more indexes, call
  106742. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  106743. ** only. The table b-tree entry will be replaced by the new entry
  106744. ** when it is inserted.
  106745. **
  106746. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  106747. ** also invoke MultiWrite() to indicate that this VDBE may require
  106748. ** statement rollback (if the statement is aborted after the delete
  106749. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  106750. ** but being more selective here allows statements like:
  106751. **
  106752. ** REPLACE INTO t(rowid) VALUES($newrowid)
  106753. **
  106754. ** to run without a statement journal if there are no indexes on the
  106755. ** table.
  106756. */
  106757. Trigger *pTrigger = 0;
  106758. if( db->flags&SQLITE_RecTriggers ){
  106759. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  106760. }
  106761. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  106762. sqlite3MultiWrite(pParse);
  106763. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  106764. regNewData, 1, 0, OE_Replace, 1, -1);
  106765. }else{
  106766. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  106767. if( HasRowid(pTab) ){
  106768. /* This OP_Delete opcode fires the pre-update-hook only. It does
  106769. ** not modify the b-tree. It is more efficient to let the coming
  106770. ** OP_Insert replace the existing entry than it is to delete the
  106771. ** existing entry and then insert a new one. */
  106772. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
  106773. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  106774. }
  106775. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  106776. if( pTab->pIndex ){
  106777. sqlite3MultiWrite(pParse);
  106778. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  106779. }
  106780. }
  106781. seenReplace = 1;
  106782. break;
  106783. }
  106784. case OE_Ignore: {
  106785. /*assert( seenReplace==0 );*/
  106786. sqlite3VdbeGoto(v, ignoreDest);
  106787. break;
  106788. }
  106789. }
  106790. sqlite3VdbeResolveLabel(v, addrRowidOk);
  106791. if( ipkTop ){
  106792. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  106793. sqlite3VdbeJumpHere(v, ipkTop);
  106794. }
  106795. }
  106796. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  106797. ** index and making sure that duplicate entries do not already exist.
  106798. ** Compute the revised record entries for indices as we go.
  106799. **
  106800. ** This loop also handles the case of the PRIMARY KEY index for a
  106801. ** WITHOUT ROWID table.
  106802. */
  106803. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  106804. int regIdx; /* Range of registers hold conent for pIdx */
  106805. int regR; /* Range of registers holding conflicting PK */
  106806. int iThisCur; /* Cursor for this UNIQUE index */
  106807. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  106808. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  106809. if( bAffinityDone==0 ){
  106810. sqlite3TableAffinity(v, pTab, regNewData+1);
  106811. bAffinityDone = 1;
  106812. }
  106813. iThisCur = iIdxCur+ix;
  106814. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  106815. /* Skip partial indices for which the WHERE clause is not true */
  106816. if( pIdx->pPartIdxWhere ){
  106817. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  106818. pParse->iSelfTab = -(regNewData+1);
  106819. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  106820. SQLITE_JUMPIFNULL);
  106821. pParse->iSelfTab = 0;
  106822. }
  106823. /* Create a record for this index entry as it should appear after
  106824. ** the insert or update. Store that record in the aRegIdx[ix] register
  106825. */
  106826. regIdx = aRegIdx[ix]+1;
  106827. for(i=0; i<pIdx->nColumn; i++){
  106828. int iField = pIdx->aiColumn[i];
  106829. int x;
  106830. if( iField==XN_EXPR ){
  106831. pParse->iSelfTab = -(regNewData+1);
  106832. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  106833. pParse->iSelfTab = 0;
  106834. VdbeComment((v, "%s column %d", pIdx->zName, i));
  106835. }else{
  106836. if( iField==XN_ROWID || iField==pTab->iPKey ){
  106837. x = regNewData;
  106838. }else{
  106839. x = iField + regNewData + 1;
  106840. }
  106841. sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
  106842. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  106843. }
  106844. }
  106845. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  106846. VdbeComment((v, "for %s", pIdx->zName));
  106847. #ifdef SQLITE_ENABLE_NULL_TRIM
  106848. if( pIdx->idxType==2 ) sqlite3SetMakeRecordP5(v, pIdx->pTable);
  106849. #endif
  106850. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  106851. ** of a WITHOUT ROWID table and there has been no change the
  106852. ** primary key, then no collision is possible. The collision detection
  106853. ** logic below can all be skipped. */
  106854. if( isUpdate && pPk==pIdx && pkChng==0 ){
  106855. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  106856. continue;
  106857. }
  106858. /* Find out what action to take in case there is a uniqueness conflict */
  106859. onError = pIdx->onError;
  106860. if( onError==OE_None ){
  106861. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  106862. continue; /* pIdx is not a UNIQUE index */
  106863. }
  106864. if( overrideError!=OE_Default ){
  106865. onError = overrideError;
  106866. }else if( onError==OE_Default ){
  106867. onError = OE_Abort;
  106868. }
  106869. /* Collision detection may be omitted if all of the following are true:
  106870. ** (1) The conflict resolution algorithm is REPLACE
  106871. ** (2) The table is a WITHOUT ROWID table
  106872. ** (3) There are no secondary indexes on the table
  106873. ** (4) No delete triggers need to be fired if there is a conflict
  106874. ** (5) No FK constraint counters need to be updated if a conflict occurs.
  106875. */
  106876. if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
  106877. && pPk==pIdx /* Condition 2 */
  106878. && onError==OE_Replace /* Condition 1 */
  106879. && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
  106880. 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
  106881. && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
  106882. (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
  106883. ){
  106884. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  106885. continue;
  106886. }
  106887. /* Check to see if the new index entry will be unique */
  106888. sqlite3ExprCachePush(pParse);
  106889. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  106890. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  106891. /* Generate code to handle collisions */
  106892. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  106893. if( isUpdate || onError==OE_Replace ){
  106894. if( HasRowid(pTab) ){
  106895. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  106896. /* Conflict only if the rowid of the existing index entry
  106897. ** is different from old-rowid */
  106898. if( isUpdate ){
  106899. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  106900. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  106901. VdbeCoverage(v);
  106902. }
  106903. }else{
  106904. int x;
  106905. /* Extract the PRIMARY KEY from the end of the index entry and
  106906. ** store it in registers regR..regR+nPk-1 */
  106907. if( pIdx!=pPk ){
  106908. for(i=0; i<pPk->nKeyCol; i++){
  106909. assert( pPk->aiColumn[i]>=0 );
  106910. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  106911. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  106912. VdbeComment((v, "%s.%s", pTab->zName,
  106913. pTab->aCol[pPk->aiColumn[i]].zName));
  106914. }
  106915. }
  106916. if( isUpdate ){
  106917. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  106918. ** table, only conflict if the new PRIMARY KEY values are actually
  106919. ** different from the old.
  106920. **
  106921. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  106922. ** of the matched index row are different from the original PRIMARY
  106923. ** KEY values of this row before the update. */
  106924. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  106925. int op = OP_Ne;
  106926. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  106927. for(i=0; i<pPk->nKeyCol; i++){
  106928. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  106929. x = pPk->aiColumn[i];
  106930. assert( x>=0 );
  106931. if( i==(pPk->nKeyCol-1) ){
  106932. addrJump = addrUniqueOk;
  106933. op = OP_Eq;
  106934. }
  106935. sqlite3VdbeAddOp4(v, op,
  106936. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  106937. );
  106938. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  106939. VdbeCoverageIf(v, op==OP_Eq);
  106940. VdbeCoverageIf(v, op==OP_Ne);
  106941. }
  106942. }
  106943. }
  106944. }
  106945. /* Generate code that executes if the new index entry is not unique */
  106946. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  106947. || onError==OE_Ignore || onError==OE_Replace );
  106948. switch( onError ){
  106949. case OE_Rollback:
  106950. case OE_Abort:
  106951. case OE_Fail: {
  106952. sqlite3UniqueConstraint(pParse, onError, pIdx);
  106953. break;
  106954. }
  106955. case OE_Ignore: {
  106956. sqlite3VdbeGoto(v, ignoreDest);
  106957. break;
  106958. }
  106959. default: {
  106960. Trigger *pTrigger = 0;
  106961. assert( onError==OE_Replace );
  106962. sqlite3MultiWrite(pParse);
  106963. if( db->flags&SQLITE_RecTriggers ){
  106964. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  106965. }
  106966. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  106967. regR, nPkField, 0, OE_Replace,
  106968. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
  106969. seenReplace = 1;
  106970. break;
  106971. }
  106972. }
  106973. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  106974. sqlite3ExprCachePop(pParse);
  106975. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  106976. }
  106977. if( ipkTop ){
  106978. sqlite3VdbeGoto(v, ipkTop+1);
  106979. sqlite3VdbeJumpHere(v, ipkBottom);
  106980. }
  106981. *pbMayReplace = seenReplace;
  106982. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  106983. }
  106984. #ifdef SQLITE_ENABLE_NULL_TRIM
  106985. /*
  106986. ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
  106987. ** to be the number of columns in table pTab that must not be NULL-trimmed.
  106988. **
  106989. ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
  106990. */
  106991. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
  106992. u16 i;
  106993. /* Records with omitted columns are only allowed for schema format
  106994. ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
  106995. if( pTab->pSchema->file_format<2 ) return;
  106996. for(i=pTab->nCol-1; i>0; i--){
  106997. if( pTab->aCol[i].pDflt!=0 ) break;
  106998. if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
  106999. }
  107000. sqlite3VdbeChangeP5(v, i+1);
  107001. }
  107002. #endif
  107003. /*
  107004. ** This routine generates code to finish the INSERT or UPDATE operation
  107005. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  107006. ** A consecutive range of registers starting at regNewData contains the
  107007. ** rowid and the content to be inserted.
  107008. **
  107009. ** The arguments to this routine should be the same as the first six
  107010. ** arguments to sqlite3GenerateConstraintChecks.
  107011. */
  107012. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  107013. Parse *pParse, /* The parser context */
  107014. Table *pTab, /* the table into which we are inserting */
  107015. int iDataCur, /* Cursor of the canonical data source */
  107016. int iIdxCur, /* First index cursor */
  107017. int regNewData, /* Range of content */
  107018. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  107019. int update_flags, /* True for UPDATE, False for INSERT */
  107020. int appendBias, /* True if this is likely to be an append */
  107021. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  107022. ){
  107023. Vdbe *v; /* Prepared statements under construction */
  107024. Index *pIdx; /* An index being inserted or updated */
  107025. u8 pik_flags; /* flag values passed to the btree insert */
  107026. int regData; /* Content registers (after the rowid) */
  107027. int regRec; /* Register holding assembled record for the table */
  107028. int i; /* Loop counter */
  107029. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  107030. assert( update_flags==0
  107031. || update_flags==OPFLAG_ISUPDATE
  107032. || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
  107033. );
  107034. v = sqlite3GetVdbe(pParse);
  107035. assert( v!=0 );
  107036. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  107037. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  107038. if( aRegIdx[i]==0 ) continue;
  107039. bAffinityDone = 1;
  107040. if( pIdx->pPartIdxWhere ){
  107041. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  107042. VdbeCoverage(v);
  107043. }
  107044. pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
  107045. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  107046. assert( pParse->nested==0 );
  107047. pik_flags |= OPFLAG_NCHANGE;
  107048. pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
  107049. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  107050. if( update_flags==0 ){
  107051. sqlite3VdbeAddOp4(v, OP_InsertInt,
  107052. iIdxCur+i, aRegIdx[i], 0, (char*)pTab, P4_TABLE
  107053. );
  107054. sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
  107055. }
  107056. #endif
  107057. }
  107058. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
  107059. aRegIdx[i]+1,
  107060. pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
  107061. sqlite3VdbeChangeP5(v, pik_flags);
  107062. }
  107063. if( !HasRowid(pTab) ) return;
  107064. regData = regNewData + 1;
  107065. regRec = sqlite3GetTempReg(pParse);
  107066. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  107067. sqlite3SetMakeRecordP5(v, pTab);
  107068. if( !bAffinityDone ){
  107069. sqlite3TableAffinity(v, pTab, 0);
  107070. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  107071. }
  107072. if( pParse->nested ){
  107073. pik_flags = 0;
  107074. }else{
  107075. pik_flags = OPFLAG_NCHANGE;
  107076. pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
  107077. }
  107078. if( appendBias ){
  107079. pik_flags |= OPFLAG_APPEND;
  107080. }
  107081. if( useSeekResult ){
  107082. pik_flags |= OPFLAG_USESEEKRESULT;
  107083. }
  107084. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  107085. if( !pParse->nested ){
  107086. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  107087. }
  107088. sqlite3VdbeChangeP5(v, pik_flags);
  107089. }
  107090. /*
  107091. ** Allocate cursors for the pTab table and all its indices and generate
  107092. ** code to open and initialized those cursors.
  107093. **
  107094. ** The cursor for the object that contains the complete data (normally
  107095. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  107096. ** ROWID table) is returned in *piDataCur. The first index cursor is
  107097. ** returned in *piIdxCur. The number of indices is returned.
  107098. **
  107099. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  107100. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  107101. ** If iBase is negative, then allocate the next available cursor.
  107102. **
  107103. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  107104. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  107105. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  107106. ** pTab->pIndex list.
  107107. **
  107108. ** If pTab is a virtual table, then this routine is a no-op and the
  107109. ** *piDataCur and *piIdxCur values are left uninitialized.
  107110. */
  107111. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  107112. Parse *pParse, /* Parsing context */
  107113. Table *pTab, /* Table to be opened */
  107114. int op, /* OP_OpenRead or OP_OpenWrite */
  107115. u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
  107116. int iBase, /* Use this for the table cursor, if there is one */
  107117. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  107118. int *piDataCur, /* Write the database source cursor number here */
  107119. int *piIdxCur /* Write the first index cursor number here */
  107120. ){
  107121. int i;
  107122. int iDb;
  107123. int iDataCur;
  107124. Index *pIdx;
  107125. Vdbe *v;
  107126. assert( op==OP_OpenRead || op==OP_OpenWrite );
  107127. assert( op==OP_OpenWrite || p5==0 );
  107128. if( IsVirtual(pTab) ){
  107129. /* This routine is a no-op for virtual tables. Leave the output
  107130. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  107131. ** can detect if they are used by mistake in the caller. */
  107132. return 0;
  107133. }
  107134. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  107135. v = sqlite3GetVdbe(pParse);
  107136. assert( v!=0 );
  107137. if( iBase<0 ) iBase = pParse->nTab;
  107138. iDataCur = iBase++;
  107139. if( piDataCur ) *piDataCur = iDataCur;
  107140. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  107141. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  107142. }else{
  107143. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  107144. }
  107145. if( piIdxCur ) *piIdxCur = iBase;
  107146. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  107147. int iIdxCur = iBase++;
  107148. assert( pIdx->pSchema==pTab->pSchema );
  107149. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  107150. if( piDataCur ) *piDataCur = iIdxCur;
  107151. p5 = 0;
  107152. }
  107153. if( aToOpen==0 || aToOpen[i+1] ){
  107154. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  107155. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  107156. sqlite3VdbeChangeP5(v, p5);
  107157. VdbeComment((v, "%s", pIdx->zName));
  107158. }
  107159. }
  107160. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  107161. return i;
  107162. }
  107163. #ifdef SQLITE_TEST
  107164. /*
  107165. ** The following global variable is incremented whenever the
  107166. ** transfer optimization is used. This is used for testing
  107167. ** purposes only - to make sure the transfer optimization really
  107168. ** is happening when it is supposed to.
  107169. */
  107170. SQLITE_API int sqlite3_xferopt_count;
  107171. #endif /* SQLITE_TEST */
  107172. #ifndef SQLITE_OMIT_XFER_OPT
  107173. /*
  107174. ** Check to see if index pSrc is compatible as a source of data
  107175. ** for index pDest in an insert transfer optimization. The rules
  107176. ** for a compatible index:
  107177. **
  107178. ** * The index is over the same set of columns
  107179. ** * The same DESC and ASC markings occurs on all columns
  107180. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  107181. ** * The same collating sequence on each column
  107182. ** * The index has the exact same WHERE clause
  107183. */
  107184. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  107185. int i;
  107186. assert( pDest && pSrc );
  107187. assert( pDest->pTable!=pSrc->pTable );
  107188. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  107189. return 0; /* Different number of columns */
  107190. }
  107191. if( pDest->onError!=pSrc->onError ){
  107192. return 0; /* Different conflict resolution strategies */
  107193. }
  107194. for(i=0; i<pSrc->nKeyCol; i++){
  107195. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  107196. return 0; /* Different columns indexed */
  107197. }
  107198. if( pSrc->aiColumn[i]==XN_EXPR ){
  107199. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  107200. if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
  107201. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  107202. return 0; /* Different expressions in the index */
  107203. }
  107204. }
  107205. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  107206. return 0; /* Different sort orders */
  107207. }
  107208. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  107209. return 0; /* Different collating sequences */
  107210. }
  107211. }
  107212. if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  107213. return 0; /* Different WHERE clauses */
  107214. }
  107215. /* If no test above fails then the indices must be compatible */
  107216. return 1;
  107217. }
  107218. /*
  107219. ** Attempt the transfer optimization on INSERTs of the form
  107220. **
  107221. ** INSERT INTO tab1 SELECT * FROM tab2;
  107222. **
  107223. ** The xfer optimization transfers raw records from tab2 over to tab1.
  107224. ** Columns are not decoded and reassembled, which greatly improves
  107225. ** performance. Raw index records are transferred in the same way.
  107226. **
  107227. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  107228. ** There are lots of rules for determining compatibility - see comments
  107229. ** embedded in the code for details.
  107230. **
  107231. ** This routine returns TRUE if the optimization is guaranteed to be used.
  107232. ** Sometimes the xfer optimization will only work if the destination table
  107233. ** is empty - a factor that can only be determined at run-time. In that
  107234. ** case, this routine generates code for the xfer optimization but also
  107235. ** does a test to see if the destination table is empty and jumps over the
  107236. ** xfer optimization code if the test fails. In that case, this routine
  107237. ** returns FALSE so that the caller will know to go ahead and generate
  107238. ** an unoptimized transfer. This routine also returns FALSE if there
  107239. ** is no chance that the xfer optimization can be applied.
  107240. **
  107241. ** This optimization is particularly useful at making VACUUM run faster.
  107242. */
  107243. static int xferOptimization(
  107244. Parse *pParse, /* Parser context */
  107245. Table *pDest, /* The table we are inserting into */
  107246. Select *pSelect, /* A SELECT statement to use as the data source */
  107247. int onError, /* How to handle constraint errors */
  107248. int iDbDest /* The database of pDest */
  107249. ){
  107250. sqlite3 *db = pParse->db;
  107251. ExprList *pEList; /* The result set of the SELECT */
  107252. Table *pSrc; /* The table in the FROM clause of SELECT */
  107253. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  107254. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  107255. int i; /* Loop counter */
  107256. int iDbSrc; /* The database of pSrc */
  107257. int iSrc, iDest; /* Cursors from source and destination */
  107258. int addr1, addr2; /* Loop addresses */
  107259. int emptyDestTest = 0; /* Address of test for empty pDest */
  107260. int emptySrcTest = 0; /* Address of test for empty pSrc */
  107261. Vdbe *v; /* The VDBE we are building */
  107262. int regAutoinc; /* Memory register used by AUTOINC */
  107263. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  107264. int regData, regRowid; /* Registers holding data and rowid */
  107265. if( pSelect==0 ){
  107266. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  107267. }
  107268. if( pParse->pWith || pSelect->pWith ){
  107269. /* Do not attempt to process this query if there are an WITH clauses
  107270. ** attached to it. Proceeding may generate a false "no such table: xxx"
  107271. ** error if pSelect reads from a CTE named "xxx". */
  107272. return 0;
  107273. }
  107274. if( sqlite3TriggerList(pParse, pDest) ){
  107275. return 0; /* tab1 must not have triggers */
  107276. }
  107277. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107278. if( IsVirtual(pDest) ){
  107279. return 0; /* tab1 must not be a virtual table */
  107280. }
  107281. #endif
  107282. if( onError==OE_Default ){
  107283. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  107284. if( onError==OE_Default ) onError = OE_Abort;
  107285. }
  107286. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  107287. if( pSelect->pSrc->nSrc!=1 ){
  107288. return 0; /* FROM clause must have exactly one term */
  107289. }
  107290. if( pSelect->pSrc->a[0].pSelect ){
  107291. return 0; /* FROM clause cannot contain a subquery */
  107292. }
  107293. if( pSelect->pWhere ){
  107294. return 0; /* SELECT may not have a WHERE clause */
  107295. }
  107296. if( pSelect->pOrderBy ){
  107297. return 0; /* SELECT may not have an ORDER BY clause */
  107298. }
  107299. /* Do not need to test for a HAVING clause. If HAVING is present but
  107300. ** there is no ORDER BY, we will get an error. */
  107301. if( pSelect->pGroupBy ){
  107302. return 0; /* SELECT may not have a GROUP BY clause */
  107303. }
  107304. if( pSelect->pLimit ){
  107305. return 0; /* SELECT may not have a LIMIT clause */
  107306. }
  107307. if( pSelect->pPrior ){
  107308. return 0; /* SELECT may not be a compound query */
  107309. }
  107310. if( pSelect->selFlags & SF_Distinct ){
  107311. return 0; /* SELECT may not be DISTINCT */
  107312. }
  107313. pEList = pSelect->pEList;
  107314. assert( pEList!=0 );
  107315. if( pEList->nExpr!=1 ){
  107316. return 0; /* The result set must have exactly one column */
  107317. }
  107318. assert( pEList->a[0].pExpr );
  107319. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  107320. return 0; /* The result set must be the special operator "*" */
  107321. }
  107322. /* At this point we have established that the statement is of the
  107323. ** correct syntactic form to participate in this optimization. Now
  107324. ** we have to check the semantics.
  107325. */
  107326. pItem = pSelect->pSrc->a;
  107327. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  107328. if( pSrc==0 ){
  107329. return 0; /* FROM clause does not contain a real table */
  107330. }
  107331. if( pSrc==pDest ){
  107332. return 0; /* tab1 and tab2 may not be the same table */
  107333. }
  107334. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  107335. return 0; /* source and destination must both be WITHOUT ROWID or not */
  107336. }
  107337. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107338. if( IsVirtual(pSrc) ){
  107339. return 0; /* tab2 must not be a virtual table */
  107340. }
  107341. #endif
  107342. if( pSrc->pSelect ){
  107343. return 0; /* tab2 may not be a view */
  107344. }
  107345. if( pDest->nCol!=pSrc->nCol ){
  107346. return 0; /* Number of columns must be the same in tab1 and tab2 */
  107347. }
  107348. if( pDest->iPKey!=pSrc->iPKey ){
  107349. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  107350. }
  107351. for(i=0; i<pDest->nCol; i++){
  107352. Column *pDestCol = &pDest->aCol[i];
  107353. Column *pSrcCol = &pSrc->aCol[i];
  107354. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  107355. if( (db->mDbFlags & DBFLAG_Vacuum)==0
  107356. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  107357. ){
  107358. return 0; /* Neither table may have __hidden__ columns */
  107359. }
  107360. #endif
  107361. if( pDestCol->affinity!=pSrcCol->affinity ){
  107362. return 0; /* Affinity must be the same on all columns */
  107363. }
  107364. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  107365. return 0; /* Collating sequence must be the same on all columns */
  107366. }
  107367. if( pDestCol->notNull && !pSrcCol->notNull ){
  107368. return 0; /* tab2 must be NOT NULL if tab1 is */
  107369. }
  107370. /* Default values for second and subsequent columns need to match. */
  107371. if( i>0 ){
  107372. assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
  107373. assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
  107374. if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
  107375. || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
  107376. pSrcCol->pDflt->u.zToken)!=0)
  107377. ){
  107378. return 0; /* Default values must be the same for all columns */
  107379. }
  107380. }
  107381. }
  107382. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  107383. if( IsUniqueIndex(pDestIdx) ){
  107384. destHasUniqueIdx = 1;
  107385. }
  107386. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  107387. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  107388. }
  107389. if( pSrcIdx==0 ){
  107390. return 0; /* pDestIdx has no corresponding index in pSrc */
  107391. }
  107392. }
  107393. #ifndef SQLITE_OMIT_CHECK
  107394. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  107395. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  107396. }
  107397. #endif
  107398. #ifndef SQLITE_OMIT_FOREIGN_KEY
  107399. /* Disallow the transfer optimization if the destination table constains
  107400. ** any foreign key constraints. This is more restrictive than necessary.
  107401. ** But the main beneficiary of the transfer optimization is the VACUUM
  107402. ** command, and the VACUUM command disables foreign key constraints. So
  107403. ** the extra complication to make this rule less restrictive is probably
  107404. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  107405. */
  107406. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  107407. return 0;
  107408. }
  107409. #endif
  107410. if( (db->flags & SQLITE_CountRows)!=0 ){
  107411. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  107412. }
  107413. /* If we get this far, it means that the xfer optimization is at
  107414. ** least a possibility, though it might only work if the destination
  107415. ** table (tab1) is initially empty.
  107416. */
  107417. #ifdef SQLITE_TEST
  107418. sqlite3_xferopt_count++;
  107419. #endif
  107420. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  107421. v = sqlite3GetVdbe(pParse);
  107422. sqlite3CodeVerifySchema(pParse, iDbSrc);
  107423. iSrc = pParse->nTab++;
  107424. iDest = pParse->nTab++;
  107425. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  107426. regData = sqlite3GetTempReg(pParse);
  107427. regRowid = sqlite3GetTempReg(pParse);
  107428. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  107429. assert( HasRowid(pDest) || destHasUniqueIdx );
  107430. if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
  107431. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  107432. || destHasUniqueIdx /* (2) */
  107433. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  107434. )){
  107435. /* In some circumstances, we are able to run the xfer optimization
  107436. ** only if the destination table is initially empty. Unless the
  107437. ** DBFLAG_Vacuum flag is set, this block generates code to make
  107438. ** that determination. If DBFLAG_Vacuum is set, then the destination
  107439. ** table is always empty.
  107440. **
  107441. ** Conditions under which the destination must be empty:
  107442. **
  107443. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  107444. ** (If the destination is not initially empty, the rowid fields
  107445. ** of index entries might need to change.)
  107446. **
  107447. ** (2) The destination has a unique index. (The xfer optimization
  107448. ** is unable to test uniqueness.)
  107449. **
  107450. ** (3) onError is something other than OE_Abort and OE_Rollback.
  107451. */
  107452. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  107453. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  107454. sqlite3VdbeJumpHere(v, addr1);
  107455. }
  107456. if( HasRowid(pSrc) ){
  107457. u8 insFlags;
  107458. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  107459. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  107460. if( pDest->iPKey>=0 ){
  107461. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  107462. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  107463. VdbeCoverage(v);
  107464. sqlite3RowidConstraint(pParse, onError, pDest);
  107465. sqlite3VdbeJumpHere(v, addr2);
  107466. autoIncStep(pParse, regAutoinc, regRowid);
  107467. }else if( pDest->pIndex==0 ){
  107468. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  107469. }else{
  107470. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  107471. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  107472. }
  107473. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  107474. if( db->mDbFlags & DBFLAG_Vacuum ){
  107475. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  107476. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|
  107477. OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
  107478. }else{
  107479. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
  107480. }
  107481. sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
  107482. (char*)pDest, P4_TABLE);
  107483. sqlite3VdbeChangeP5(v, insFlags);
  107484. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  107485. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  107486. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  107487. }else{
  107488. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  107489. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  107490. }
  107491. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  107492. u8 idxInsFlags = 0;
  107493. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  107494. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  107495. }
  107496. assert( pSrcIdx );
  107497. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  107498. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  107499. VdbeComment((v, "%s", pSrcIdx->zName));
  107500. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  107501. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  107502. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  107503. VdbeComment((v, "%s", pDestIdx->zName));
  107504. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  107505. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  107506. if( db->mDbFlags & DBFLAG_Vacuum ){
  107507. /* This INSERT command is part of a VACUUM operation, which guarantees
  107508. ** that the destination table is empty. If all indexed columns use
  107509. ** collation sequence BINARY, then it can also be assumed that the
  107510. ** index will be populated by inserting keys in strictly sorted
  107511. ** order. In this case, instead of seeking within the b-tree as part
  107512. ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
  107513. ** OP_IdxInsert to seek to the point within the b-tree where each key
  107514. ** should be inserted. This is faster.
  107515. **
  107516. ** If any of the indexed columns use a collation sequence other than
  107517. ** BINARY, this optimization is disabled. This is because the user
  107518. ** might change the definition of a collation sequence and then run
  107519. ** a VACUUM command. In that case keys may not be written in strictly
  107520. ** sorted order. */
  107521. for(i=0; i<pSrcIdx->nColumn; i++){
  107522. const char *zColl = pSrcIdx->azColl[i];
  107523. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  107524. }
  107525. if( i==pSrcIdx->nColumn ){
  107526. idxInsFlags = OPFLAG_USESEEKRESULT;
  107527. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  107528. }
  107529. }
  107530. if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
  107531. idxInsFlags |= OPFLAG_NCHANGE;
  107532. }
  107533. sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
  107534. sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
  107535. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  107536. sqlite3VdbeJumpHere(v, addr1);
  107537. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  107538. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  107539. }
  107540. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  107541. sqlite3ReleaseTempReg(pParse, regRowid);
  107542. sqlite3ReleaseTempReg(pParse, regData);
  107543. if( emptyDestTest ){
  107544. sqlite3AutoincrementEnd(pParse);
  107545. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  107546. sqlite3VdbeJumpHere(v, emptyDestTest);
  107547. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  107548. return 0;
  107549. }else{
  107550. return 1;
  107551. }
  107552. }
  107553. #endif /* SQLITE_OMIT_XFER_OPT */
  107554. /************** End of insert.c **********************************************/
  107555. /************** Begin file legacy.c ******************************************/
  107556. /*
  107557. ** 2001 September 15
  107558. **
  107559. ** The author disclaims copyright to this source code. In place of
  107560. ** a legal notice, here is a blessing:
  107561. **
  107562. ** May you do good and not evil.
  107563. ** May you find forgiveness for yourself and forgive others.
  107564. ** May you share freely, never taking more than you give.
  107565. **
  107566. *************************************************************************
  107567. ** Main file for the SQLite library. The routines in this file
  107568. ** implement the programmer interface to the library. Routines in
  107569. ** other files are for internal use by SQLite and should not be
  107570. ** accessed by users of the library.
  107571. */
  107572. /* #include "sqliteInt.h" */
  107573. /*
  107574. ** Execute SQL code. Return one of the SQLITE_ success/failure
  107575. ** codes. Also write an error message into memory obtained from
  107576. ** malloc() and make *pzErrMsg point to that message.
  107577. **
  107578. ** If the SQL is a query, then for each row in the query result
  107579. ** the xCallback() function is called. pArg becomes the first
  107580. ** argument to xCallback(). If xCallback=NULL then no callback
  107581. ** is invoked, even for queries.
  107582. */
  107583. SQLITE_API int sqlite3_exec(
  107584. sqlite3 *db, /* The database on which the SQL executes */
  107585. const char *zSql, /* The SQL to be executed */
  107586. sqlite3_callback xCallback, /* Invoke this callback routine */
  107587. void *pArg, /* First argument to xCallback() */
  107588. char **pzErrMsg /* Write error messages here */
  107589. ){
  107590. int rc = SQLITE_OK; /* Return code */
  107591. const char *zLeftover; /* Tail of unprocessed SQL */
  107592. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  107593. char **azCols = 0; /* Names of result columns */
  107594. int callbackIsInit; /* True if callback data is initialized */
  107595. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  107596. if( zSql==0 ) zSql = "";
  107597. sqlite3_mutex_enter(db->mutex);
  107598. sqlite3Error(db, SQLITE_OK);
  107599. while( rc==SQLITE_OK && zSql[0] ){
  107600. int nCol;
  107601. char **azVals = 0;
  107602. pStmt = 0;
  107603. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  107604. assert( rc==SQLITE_OK || pStmt==0 );
  107605. if( rc!=SQLITE_OK ){
  107606. continue;
  107607. }
  107608. if( !pStmt ){
  107609. /* this happens for a comment or white-space */
  107610. zSql = zLeftover;
  107611. continue;
  107612. }
  107613. callbackIsInit = 0;
  107614. nCol = sqlite3_column_count(pStmt);
  107615. while( 1 ){
  107616. int i;
  107617. rc = sqlite3_step(pStmt);
  107618. /* Invoke the callback function if required */
  107619. if( xCallback && (SQLITE_ROW==rc ||
  107620. (SQLITE_DONE==rc && !callbackIsInit
  107621. && db->flags&SQLITE_NullCallback)) ){
  107622. if( !callbackIsInit ){
  107623. azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
  107624. if( azCols==0 ){
  107625. goto exec_out;
  107626. }
  107627. for(i=0; i<nCol; i++){
  107628. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  107629. /* sqlite3VdbeSetColName() installs column names as UTF8
  107630. ** strings so there is no way for sqlite3_column_name() to fail. */
  107631. assert( azCols[i]!=0 );
  107632. }
  107633. callbackIsInit = 1;
  107634. }
  107635. if( rc==SQLITE_ROW ){
  107636. azVals = &azCols[nCol];
  107637. for(i=0; i<nCol; i++){
  107638. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  107639. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  107640. sqlite3OomFault(db);
  107641. goto exec_out;
  107642. }
  107643. }
  107644. azVals[i] = 0;
  107645. }
  107646. if( xCallback(pArg, nCol, azVals, azCols) ){
  107647. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  107648. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  107649. ** return SQLITE_ABORT. */
  107650. rc = SQLITE_ABORT;
  107651. sqlite3VdbeFinalize((Vdbe *)pStmt);
  107652. pStmt = 0;
  107653. sqlite3Error(db, SQLITE_ABORT);
  107654. goto exec_out;
  107655. }
  107656. }
  107657. if( rc!=SQLITE_ROW ){
  107658. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  107659. pStmt = 0;
  107660. zSql = zLeftover;
  107661. while( sqlite3Isspace(zSql[0]) ) zSql++;
  107662. break;
  107663. }
  107664. }
  107665. sqlite3DbFree(db, azCols);
  107666. azCols = 0;
  107667. }
  107668. exec_out:
  107669. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  107670. sqlite3DbFree(db, azCols);
  107671. rc = sqlite3ApiExit(db, rc);
  107672. if( rc!=SQLITE_OK && pzErrMsg ){
  107673. *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
  107674. if( *pzErrMsg==0 ){
  107675. rc = SQLITE_NOMEM_BKPT;
  107676. sqlite3Error(db, SQLITE_NOMEM);
  107677. }
  107678. }else if( pzErrMsg ){
  107679. *pzErrMsg = 0;
  107680. }
  107681. assert( (rc&db->errMask)==rc );
  107682. sqlite3_mutex_leave(db->mutex);
  107683. return rc;
  107684. }
  107685. /************** End of legacy.c **********************************************/
  107686. /************** Begin file loadext.c *****************************************/
  107687. /*
  107688. ** 2006 June 7
  107689. **
  107690. ** The author disclaims copyright to this source code. In place of
  107691. ** a legal notice, here is a blessing:
  107692. **
  107693. ** May you do good and not evil.
  107694. ** May you find forgiveness for yourself and forgive others.
  107695. ** May you share freely, never taking more than you give.
  107696. **
  107697. *************************************************************************
  107698. ** This file contains code used to dynamically load extensions into
  107699. ** the SQLite library.
  107700. */
  107701. #ifndef SQLITE_CORE
  107702. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  107703. #endif
  107704. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  107705. /************** Begin file sqlite3ext.h **************************************/
  107706. /*
  107707. ** 2006 June 7
  107708. **
  107709. ** The author disclaims copyright to this source code. In place of
  107710. ** a legal notice, here is a blessing:
  107711. **
  107712. ** May you do good and not evil.
  107713. ** May you find forgiveness for yourself and forgive others.
  107714. ** May you share freely, never taking more than you give.
  107715. **
  107716. *************************************************************************
  107717. ** This header file defines the SQLite interface for use by
  107718. ** shared libraries that want to be imported as extensions into
  107719. ** an SQLite instance. Shared libraries that intend to be loaded
  107720. ** as extensions by SQLite should #include this file instead of
  107721. ** sqlite3.h.
  107722. */
  107723. #ifndef SQLITE3EXT_H
  107724. #define SQLITE3EXT_H
  107725. /* #include "sqlite3.h" */
  107726. /*
  107727. ** The following structure holds pointers to all of the SQLite API
  107728. ** routines.
  107729. **
  107730. ** WARNING: In order to maintain backwards compatibility, add new
  107731. ** interfaces to the end of this structure only. If you insert new
  107732. ** interfaces in the middle of this structure, then older different
  107733. ** versions of SQLite will not be able to load each other's shared
  107734. ** libraries!
  107735. */
  107736. struct sqlite3_api_routines {
  107737. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  107738. int (*aggregate_count)(sqlite3_context*);
  107739. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  107740. int (*bind_double)(sqlite3_stmt*,int,double);
  107741. int (*bind_int)(sqlite3_stmt*,int,int);
  107742. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  107743. int (*bind_null)(sqlite3_stmt*,int);
  107744. int (*bind_parameter_count)(sqlite3_stmt*);
  107745. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  107746. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  107747. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  107748. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  107749. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  107750. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  107751. int (*busy_timeout)(sqlite3*,int ms);
  107752. int (*changes)(sqlite3*);
  107753. int (*close)(sqlite3*);
  107754. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  107755. int eTextRep,const char*));
  107756. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  107757. int eTextRep,const void*));
  107758. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  107759. int (*column_bytes)(sqlite3_stmt*,int iCol);
  107760. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  107761. int (*column_count)(sqlite3_stmt*pStmt);
  107762. const char * (*column_database_name)(sqlite3_stmt*,int);
  107763. const void * (*column_database_name16)(sqlite3_stmt*,int);
  107764. const char * (*column_decltype)(sqlite3_stmt*,int i);
  107765. const void * (*column_decltype16)(sqlite3_stmt*,int);
  107766. double (*column_double)(sqlite3_stmt*,int iCol);
  107767. int (*column_int)(sqlite3_stmt*,int iCol);
  107768. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  107769. const char * (*column_name)(sqlite3_stmt*,int);
  107770. const void * (*column_name16)(sqlite3_stmt*,int);
  107771. const char * (*column_origin_name)(sqlite3_stmt*,int);
  107772. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  107773. const char * (*column_table_name)(sqlite3_stmt*,int);
  107774. const void * (*column_table_name16)(sqlite3_stmt*,int);
  107775. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  107776. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  107777. int (*column_type)(sqlite3_stmt*,int iCol);
  107778. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  107779. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  107780. int (*complete)(const char*sql);
  107781. int (*complete16)(const void*sql);
  107782. int (*create_collation)(sqlite3*,const char*,int,void*,
  107783. int(*)(void*,int,const void*,int,const void*));
  107784. int (*create_collation16)(sqlite3*,const void*,int,void*,
  107785. int(*)(void*,int,const void*,int,const void*));
  107786. int (*create_function)(sqlite3*,const char*,int,int,void*,
  107787. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  107788. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  107789. void (*xFinal)(sqlite3_context*));
  107790. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  107791. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  107792. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  107793. void (*xFinal)(sqlite3_context*));
  107794. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  107795. int (*data_count)(sqlite3_stmt*pStmt);
  107796. sqlite3 * (*db_handle)(sqlite3_stmt*);
  107797. int (*declare_vtab)(sqlite3*,const char*);
  107798. int (*enable_shared_cache)(int);
  107799. int (*errcode)(sqlite3*db);
  107800. const char * (*errmsg)(sqlite3*);
  107801. const void * (*errmsg16)(sqlite3*);
  107802. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  107803. int (*expired)(sqlite3_stmt*);
  107804. int (*finalize)(sqlite3_stmt*pStmt);
  107805. void (*free)(void*);
  107806. void (*free_table)(char**result);
  107807. int (*get_autocommit)(sqlite3*);
  107808. void * (*get_auxdata)(sqlite3_context*,int);
  107809. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  107810. int (*global_recover)(void);
  107811. void (*interruptx)(sqlite3*);
  107812. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  107813. const char * (*libversion)(void);
  107814. int (*libversion_number)(void);
  107815. void *(*malloc)(int);
  107816. char * (*mprintf)(const char*,...);
  107817. int (*open)(const char*,sqlite3**);
  107818. int (*open16)(const void*,sqlite3**);
  107819. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  107820. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  107821. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  107822. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  107823. void *(*realloc)(void*,int);
  107824. int (*reset)(sqlite3_stmt*pStmt);
  107825. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  107826. void (*result_double)(sqlite3_context*,double);
  107827. void (*result_error)(sqlite3_context*,const char*,int);
  107828. void (*result_error16)(sqlite3_context*,const void*,int);
  107829. void (*result_int)(sqlite3_context*,int);
  107830. void (*result_int64)(sqlite3_context*,sqlite_int64);
  107831. void (*result_null)(sqlite3_context*);
  107832. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  107833. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  107834. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  107835. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  107836. void (*result_value)(sqlite3_context*,sqlite3_value*);
  107837. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  107838. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  107839. const char*,const char*),void*);
  107840. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  107841. char * (*xsnprintf)(int,char*,const char*,...);
  107842. int (*step)(sqlite3_stmt*);
  107843. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  107844. char const**,char const**,int*,int*,int*);
  107845. void (*thread_cleanup)(void);
  107846. int (*total_changes)(sqlite3*);
  107847. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  107848. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  107849. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  107850. sqlite_int64),void*);
  107851. void * (*user_data)(sqlite3_context*);
  107852. const void * (*value_blob)(sqlite3_value*);
  107853. int (*value_bytes)(sqlite3_value*);
  107854. int (*value_bytes16)(sqlite3_value*);
  107855. double (*value_double)(sqlite3_value*);
  107856. int (*value_int)(sqlite3_value*);
  107857. sqlite_int64 (*value_int64)(sqlite3_value*);
  107858. int (*value_numeric_type)(sqlite3_value*);
  107859. const unsigned char * (*value_text)(sqlite3_value*);
  107860. const void * (*value_text16)(sqlite3_value*);
  107861. const void * (*value_text16be)(sqlite3_value*);
  107862. const void * (*value_text16le)(sqlite3_value*);
  107863. int (*value_type)(sqlite3_value*);
  107864. char *(*vmprintf)(const char*,va_list);
  107865. /* Added ??? */
  107866. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  107867. /* Added by 3.3.13 */
  107868. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  107869. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  107870. int (*clear_bindings)(sqlite3_stmt*);
  107871. /* Added by 3.4.1 */
  107872. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  107873. void (*xDestroy)(void *));
  107874. /* Added by 3.5.0 */
  107875. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  107876. int (*blob_bytes)(sqlite3_blob*);
  107877. int (*blob_close)(sqlite3_blob*);
  107878. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  107879. int,sqlite3_blob**);
  107880. int (*blob_read)(sqlite3_blob*,void*,int,int);
  107881. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  107882. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  107883. int(*)(void*,int,const void*,int,const void*),
  107884. void(*)(void*));
  107885. int (*file_control)(sqlite3*,const char*,int,void*);
  107886. sqlite3_int64 (*memory_highwater)(int);
  107887. sqlite3_int64 (*memory_used)(void);
  107888. sqlite3_mutex *(*mutex_alloc)(int);
  107889. void (*mutex_enter)(sqlite3_mutex*);
  107890. void (*mutex_free)(sqlite3_mutex*);
  107891. void (*mutex_leave)(sqlite3_mutex*);
  107892. int (*mutex_try)(sqlite3_mutex*);
  107893. int (*open_v2)(const char*,sqlite3**,int,const char*);
  107894. int (*release_memory)(int);
  107895. void (*result_error_nomem)(sqlite3_context*);
  107896. void (*result_error_toobig)(sqlite3_context*);
  107897. int (*sleep)(int);
  107898. void (*soft_heap_limit)(int);
  107899. sqlite3_vfs *(*vfs_find)(const char*);
  107900. int (*vfs_register)(sqlite3_vfs*,int);
  107901. int (*vfs_unregister)(sqlite3_vfs*);
  107902. int (*xthreadsafe)(void);
  107903. void (*result_zeroblob)(sqlite3_context*,int);
  107904. void (*result_error_code)(sqlite3_context*,int);
  107905. int (*test_control)(int, ...);
  107906. void (*randomness)(int,void*);
  107907. sqlite3 *(*context_db_handle)(sqlite3_context*);
  107908. int (*extended_result_codes)(sqlite3*,int);
  107909. int (*limit)(sqlite3*,int,int);
  107910. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  107911. const char *(*sql)(sqlite3_stmt*);
  107912. int (*status)(int,int*,int*,int);
  107913. int (*backup_finish)(sqlite3_backup*);
  107914. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  107915. int (*backup_pagecount)(sqlite3_backup*);
  107916. int (*backup_remaining)(sqlite3_backup*);
  107917. int (*backup_step)(sqlite3_backup*,int);
  107918. const char *(*compileoption_get)(int);
  107919. int (*compileoption_used)(const char*);
  107920. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  107921. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  107922. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  107923. void (*xFinal)(sqlite3_context*),
  107924. void(*xDestroy)(void*));
  107925. int (*db_config)(sqlite3*,int,...);
  107926. sqlite3_mutex *(*db_mutex)(sqlite3*);
  107927. int (*db_status)(sqlite3*,int,int*,int*,int);
  107928. int (*extended_errcode)(sqlite3*);
  107929. void (*log)(int,const char*,...);
  107930. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  107931. const char *(*sourceid)(void);
  107932. int (*stmt_status)(sqlite3_stmt*,int,int);
  107933. int (*strnicmp)(const char*,const char*,int);
  107934. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  107935. int (*wal_autocheckpoint)(sqlite3*,int);
  107936. int (*wal_checkpoint)(sqlite3*,const char*);
  107937. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  107938. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  107939. int (*vtab_config)(sqlite3*,int op,...);
  107940. int (*vtab_on_conflict)(sqlite3*);
  107941. /* Version 3.7.16 and later */
  107942. int (*close_v2)(sqlite3*);
  107943. const char *(*db_filename)(sqlite3*,const char*);
  107944. int (*db_readonly)(sqlite3*,const char*);
  107945. int (*db_release_memory)(sqlite3*);
  107946. const char *(*errstr)(int);
  107947. int (*stmt_busy)(sqlite3_stmt*);
  107948. int (*stmt_readonly)(sqlite3_stmt*);
  107949. int (*stricmp)(const char*,const char*);
  107950. int (*uri_boolean)(const char*,const char*,int);
  107951. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  107952. const char *(*uri_parameter)(const char*,const char*);
  107953. char *(*xvsnprintf)(int,char*,const char*,va_list);
  107954. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  107955. /* Version 3.8.7 and later */
  107956. int (*auto_extension)(void(*)(void));
  107957. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  107958. void(*)(void*));
  107959. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  107960. void(*)(void*),unsigned char);
  107961. int (*cancel_auto_extension)(void(*)(void));
  107962. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  107963. void *(*malloc64)(sqlite3_uint64);
  107964. sqlite3_uint64 (*msize)(void*);
  107965. void *(*realloc64)(void*,sqlite3_uint64);
  107966. void (*reset_auto_extension)(void);
  107967. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  107968. void(*)(void*));
  107969. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  107970. void(*)(void*), unsigned char);
  107971. int (*strglob)(const char*,const char*);
  107972. /* Version 3.8.11 and later */
  107973. sqlite3_value *(*value_dup)(const sqlite3_value*);
  107974. void (*value_free)(sqlite3_value*);
  107975. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  107976. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  107977. /* Version 3.9.0 and later */
  107978. unsigned int (*value_subtype)(sqlite3_value*);
  107979. void (*result_subtype)(sqlite3_context*,unsigned int);
  107980. /* Version 3.10.0 and later */
  107981. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  107982. int (*strlike)(const char*,const char*,unsigned int);
  107983. int (*db_cacheflush)(sqlite3*);
  107984. /* Version 3.12.0 and later */
  107985. int (*system_errno)(sqlite3*);
  107986. /* Version 3.14.0 and later */
  107987. int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  107988. char *(*expanded_sql)(sqlite3_stmt*);
  107989. /* Version 3.18.0 and later */
  107990. void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  107991. /* Version 3.20.0 and later */
  107992. int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
  107993. sqlite3_stmt**,const char**);
  107994. int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
  107995. sqlite3_stmt**,const void**);
  107996. int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
  107997. void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
  107998. void *(*value_pointer)(sqlite3_value*,const char*);
  107999. int (*vtab_nochange)(sqlite3_context*);
  108000. int (*value_nochange)(sqlite3_value*);
  108001. const char *(*vtab_collation)(sqlite3_index_info*,int);
  108002. };
  108003. /*
  108004. ** This is the function signature used for all extension entry points. It
  108005. ** is also defined in the file "loadext.c".
  108006. */
  108007. typedef int (*sqlite3_loadext_entry)(
  108008. sqlite3 *db, /* Handle to the database. */
  108009. char **pzErrMsg, /* Used to set error string on failure. */
  108010. const sqlite3_api_routines *pThunk /* Extension API function pointers. */
  108011. );
  108012. /*
  108013. ** The following macros redefine the API routines so that they are
  108014. ** redirected through the global sqlite3_api structure.
  108015. **
  108016. ** This header file is also used by the loadext.c source file
  108017. ** (part of the main SQLite library - not an extension) so that
  108018. ** it can get access to the sqlite3_api_routines structure
  108019. ** definition. But the main library does not want to redefine
  108020. ** the API. So the redefinition macros are only valid if the
  108021. ** SQLITE_CORE macros is undefined.
  108022. */
  108023. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  108024. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  108025. #ifndef SQLITE_OMIT_DEPRECATED
  108026. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  108027. #endif
  108028. #define sqlite3_bind_blob sqlite3_api->bind_blob
  108029. #define sqlite3_bind_double sqlite3_api->bind_double
  108030. #define sqlite3_bind_int sqlite3_api->bind_int
  108031. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  108032. #define sqlite3_bind_null sqlite3_api->bind_null
  108033. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  108034. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  108035. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  108036. #define sqlite3_bind_text sqlite3_api->bind_text
  108037. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  108038. #define sqlite3_bind_value sqlite3_api->bind_value
  108039. #define sqlite3_busy_handler sqlite3_api->busy_handler
  108040. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  108041. #define sqlite3_changes sqlite3_api->changes
  108042. #define sqlite3_close sqlite3_api->close
  108043. #define sqlite3_collation_needed sqlite3_api->collation_needed
  108044. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  108045. #define sqlite3_column_blob sqlite3_api->column_blob
  108046. #define sqlite3_column_bytes sqlite3_api->column_bytes
  108047. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  108048. #define sqlite3_column_count sqlite3_api->column_count
  108049. #define sqlite3_column_database_name sqlite3_api->column_database_name
  108050. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  108051. #define sqlite3_column_decltype sqlite3_api->column_decltype
  108052. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  108053. #define sqlite3_column_double sqlite3_api->column_double
  108054. #define sqlite3_column_int sqlite3_api->column_int
  108055. #define sqlite3_column_int64 sqlite3_api->column_int64
  108056. #define sqlite3_column_name sqlite3_api->column_name
  108057. #define sqlite3_column_name16 sqlite3_api->column_name16
  108058. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  108059. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  108060. #define sqlite3_column_table_name sqlite3_api->column_table_name
  108061. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  108062. #define sqlite3_column_text sqlite3_api->column_text
  108063. #define sqlite3_column_text16 sqlite3_api->column_text16
  108064. #define sqlite3_column_type sqlite3_api->column_type
  108065. #define sqlite3_column_value sqlite3_api->column_value
  108066. #define sqlite3_commit_hook sqlite3_api->commit_hook
  108067. #define sqlite3_complete sqlite3_api->complete
  108068. #define sqlite3_complete16 sqlite3_api->complete16
  108069. #define sqlite3_create_collation sqlite3_api->create_collation
  108070. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  108071. #define sqlite3_create_function sqlite3_api->create_function
  108072. #define sqlite3_create_function16 sqlite3_api->create_function16
  108073. #define sqlite3_create_module sqlite3_api->create_module
  108074. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  108075. #define sqlite3_data_count sqlite3_api->data_count
  108076. #define sqlite3_db_handle sqlite3_api->db_handle
  108077. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  108078. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  108079. #define sqlite3_errcode sqlite3_api->errcode
  108080. #define sqlite3_errmsg sqlite3_api->errmsg
  108081. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  108082. #define sqlite3_exec sqlite3_api->exec
  108083. #ifndef SQLITE_OMIT_DEPRECATED
  108084. #define sqlite3_expired sqlite3_api->expired
  108085. #endif
  108086. #define sqlite3_finalize sqlite3_api->finalize
  108087. #define sqlite3_free sqlite3_api->free
  108088. #define sqlite3_free_table sqlite3_api->free_table
  108089. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  108090. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  108091. #define sqlite3_get_table sqlite3_api->get_table
  108092. #ifndef SQLITE_OMIT_DEPRECATED
  108093. #define sqlite3_global_recover sqlite3_api->global_recover
  108094. #endif
  108095. #define sqlite3_interrupt sqlite3_api->interruptx
  108096. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  108097. #define sqlite3_libversion sqlite3_api->libversion
  108098. #define sqlite3_libversion_number sqlite3_api->libversion_number
  108099. #define sqlite3_malloc sqlite3_api->malloc
  108100. #define sqlite3_mprintf sqlite3_api->mprintf
  108101. #define sqlite3_open sqlite3_api->open
  108102. #define sqlite3_open16 sqlite3_api->open16
  108103. #define sqlite3_prepare sqlite3_api->prepare
  108104. #define sqlite3_prepare16 sqlite3_api->prepare16
  108105. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  108106. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  108107. #define sqlite3_profile sqlite3_api->profile
  108108. #define sqlite3_progress_handler sqlite3_api->progress_handler
  108109. #define sqlite3_realloc sqlite3_api->realloc
  108110. #define sqlite3_reset sqlite3_api->reset
  108111. #define sqlite3_result_blob sqlite3_api->result_blob
  108112. #define sqlite3_result_double sqlite3_api->result_double
  108113. #define sqlite3_result_error sqlite3_api->result_error
  108114. #define sqlite3_result_error16 sqlite3_api->result_error16
  108115. #define sqlite3_result_int sqlite3_api->result_int
  108116. #define sqlite3_result_int64 sqlite3_api->result_int64
  108117. #define sqlite3_result_null sqlite3_api->result_null
  108118. #define sqlite3_result_text sqlite3_api->result_text
  108119. #define sqlite3_result_text16 sqlite3_api->result_text16
  108120. #define sqlite3_result_text16be sqlite3_api->result_text16be
  108121. #define sqlite3_result_text16le sqlite3_api->result_text16le
  108122. #define sqlite3_result_value sqlite3_api->result_value
  108123. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  108124. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  108125. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  108126. #define sqlite3_snprintf sqlite3_api->xsnprintf
  108127. #define sqlite3_step sqlite3_api->step
  108128. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  108129. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  108130. #define sqlite3_total_changes sqlite3_api->total_changes
  108131. #define sqlite3_trace sqlite3_api->trace
  108132. #ifndef SQLITE_OMIT_DEPRECATED
  108133. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  108134. #endif
  108135. #define sqlite3_update_hook sqlite3_api->update_hook
  108136. #define sqlite3_user_data sqlite3_api->user_data
  108137. #define sqlite3_value_blob sqlite3_api->value_blob
  108138. #define sqlite3_value_bytes sqlite3_api->value_bytes
  108139. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  108140. #define sqlite3_value_double sqlite3_api->value_double
  108141. #define sqlite3_value_int sqlite3_api->value_int
  108142. #define sqlite3_value_int64 sqlite3_api->value_int64
  108143. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  108144. #define sqlite3_value_text sqlite3_api->value_text
  108145. #define sqlite3_value_text16 sqlite3_api->value_text16
  108146. #define sqlite3_value_text16be sqlite3_api->value_text16be
  108147. #define sqlite3_value_text16le sqlite3_api->value_text16le
  108148. #define sqlite3_value_type sqlite3_api->value_type
  108149. #define sqlite3_vmprintf sqlite3_api->vmprintf
  108150. #define sqlite3_vsnprintf sqlite3_api->xvsnprintf
  108151. #define sqlite3_overload_function sqlite3_api->overload_function
  108152. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  108153. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  108154. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  108155. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  108156. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  108157. #define sqlite3_blob_close sqlite3_api->blob_close
  108158. #define sqlite3_blob_open sqlite3_api->blob_open
  108159. #define sqlite3_blob_read sqlite3_api->blob_read
  108160. #define sqlite3_blob_write sqlite3_api->blob_write
  108161. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  108162. #define sqlite3_file_control sqlite3_api->file_control
  108163. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  108164. #define sqlite3_memory_used sqlite3_api->memory_used
  108165. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  108166. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  108167. #define sqlite3_mutex_free sqlite3_api->mutex_free
  108168. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  108169. #define sqlite3_mutex_try sqlite3_api->mutex_try
  108170. #define sqlite3_open_v2 sqlite3_api->open_v2
  108171. #define sqlite3_release_memory sqlite3_api->release_memory
  108172. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  108173. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  108174. #define sqlite3_sleep sqlite3_api->sleep
  108175. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  108176. #define sqlite3_vfs_find sqlite3_api->vfs_find
  108177. #define sqlite3_vfs_register sqlite3_api->vfs_register
  108178. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  108179. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  108180. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  108181. #define sqlite3_result_error_code sqlite3_api->result_error_code
  108182. #define sqlite3_test_control sqlite3_api->test_control
  108183. #define sqlite3_randomness sqlite3_api->randomness
  108184. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  108185. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  108186. #define sqlite3_limit sqlite3_api->limit
  108187. #define sqlite3_next_stmt sqlite3_api->next_stmt
  108188. #define sqlite3_sql sqlite3_api->sql
  108189. #define sqlite3_status sqlite3_api->status
  108190. #define sqlite3_backup_finish sqlite3_api->backup_finish
  108191. #define sqlite3_backup_init sqlite3_api->backup_init
  108192. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  108193. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  108194. #define sqlite3_backup_step sqlite3_api->backup_step
  108195. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  108196. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  108197. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  108198. #define sqlite3_db_config sqlite3_api->db_config
  108199. #define sqlite3_db_mutex sqlite3_api->db_mutex
  108200. #define sqlite3_db_status sqlite3_api->db_status
  108201. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  108202. #define sqlite3_log sqlite3_api->log
  108203. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  108204. #define sqlite3_sourceid sqlite3_api->sourceid
  108205. #define sqlite3_stmt_status sqlite3_api->stmt_status
  108206. #define sqlite3_strnicmp sqlite3_api->strnicmp
  108207. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  108208. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  108209. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  108210. #define sqlite3_wal_hook sqlite3_api->wal_hook
  108211. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  108212. #define sqlite3_vtab_config sqlite3_api->vtab_config
  108213. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  108214. /* Version 3.7.16 and later */
  108215. #define sqlite3_close_v2 sqlite3_api->close_v2
  108216. #define sqlite3_db_filename sqlite3_api->db_filename
  108217. #define sqlite3_db_readonly sqlite3_api->db_readonly
  108218. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  108219. #define sqlite3_errstr sqlite3_api->errstr
  108220. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  108221. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  108222. #define sqlite3_stricmp sqlite3_api->stricmp
  108223. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  108224. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  108225. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  108226. #define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
  108227. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  108228. /* Version 3.8.7 and later */
  108229. #define sqlite3_auto_extension sqlite3_api->auto_extension
  108230. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  108231. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  108232. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  108233. #define sqlite3_load_extension sqlite3_api->load_extension
  108234. #define sqlite3_malloc64 sqlite3_api->malloc64
  108235. #define sqlite3_msize sqlite3_api->msize
  108236. #define sqlite3_realloc64 sqlite3_api->realloc64
  108237. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  108238. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  108239. #define sqlite3_result_text64 sqlite3_api->result_text64
  108240. #define sqlite3_strglob sqlite3_api->strglob
  108241. /* Version 3.8.11 and later */
  108242. #define sqlite3_value_dup sqlite3_api->value_dup
  108243. #define sqlite3_value_free sqlite3_api->value_free
  108244. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  108245. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  108246. /* Version 3.9.0 and later */
  108247. #define sqlite3_value_subtype sqlite3_api->value_subtype
  108248. #define sqlite3_result_subtype sqlite3_api->result_subtype
  108249. /* Version 3.10.0 and later */
  108250. #define sqlite3_status64 sqlite3_api->status64
  108251. #define sqlite3_strlike sqlite3_api->strlike
  108252. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  108253. /* Version 3.12.0 and later */
  108254. #define sqlite3_system_errno sqlite3_api->system_errno
  108255. /* Version 3.14.0 and later */
  108256. #define sqlite3_trace_v2 sqlite3_api->trace_v2
  108257. #define sqlite3_expanded_sql sqlite3_api->expanded_sql
  108258. /* Version 3.18.0 and later */
  108259. #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
  108260. /* Version 3.20.0 and later */
  108261. #define sqlite3_prepare_v3 sqlite3_api->prepare_v3
  108262. #define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
  108263. #define sqlite3_bind_pointer sqlite3_api->bind_pointer
  108264. #define sqlite3_result_pointer sqlite3_api->result_pointer
  108265. #define sqlite3_value_pointer sqlite3_api->value_pointer
  108266. /* Version 3.22.0 and later */
  108267. #define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
  108268. #define sqlite3_value_nochange sqlite3_api->value_nochange
  108269. #define sqlite3_vtab_collation sqlite3_api->vtab_collation
  108270. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  108271. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  108272. /* This case when the file really is being compiled as a loadable
  108273. ** extension */
  108274. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  108275. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  108276. # define SQLITE_EXTENSION_INIT3 \
  108277. extern const sqlite3_api_routines *sqlite3_api;
  108278. #else
  108279. /* This case when the file is being statically linked into the
  108280. ** application */
  108281. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  108282. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  108283. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  108284. #endif
  108285. #endif /* SQLITE3EXT_H */
  108286. /************** End of sqlite3ext.h ******************************************/
  108287. /************** Continuing where we left off in loadext.c ********************/
  108288. /* #include "sqliteInt.h" */
  108289. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  108290. /*
  108291. ** Some API routines are omitted when various features are
  108292. ** excluded from a build of SQLite. Substitute a NULL pointer
  108293. ** for any missing APIs.
  108294. */
  108295. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  108296. # define sqlite3_column_database_name 0
  108297. # define sqlite3_column_database_name16 0
  108298. # define sqlite3_column_table_name 0
  108299. # define sqlite3_column_table_name16 0
  108300. # define sqlite3_column_origin_name 0
  108301. # define sqlite3_column_origin_name16 0
  108302. #endif
  108303. #ifdef SQLITE_OMIT_AUTHORIZATION
  108304. # define sqlite3_set_authorizer 0
  108305. #endif
  108306. #ifdef SQLITE_OMIT_UTF16
  108307. # define sqlite3_bind_text16 0
  108308. # define sqlite3_collation_needed16 0
  108309. # define sqlite3_column_decltype16 0
  108310. # define sqlite3_column_name16 0
  108311. # define sqlite3_column_text16 0
  108312. # define sqlite3_complete16 0
  108313. # define sqlite3_create_collation16 0
  108314. # define sqlite3_create_function16 0
  108315. # define sqlite3_errmsg16 0
  108316. # define sqlite3_open16 0
  108317. # define sqlite3_prepare16 0
  108318. # define sqlite3_prepare16_v2 0
  108319. # define sqlite3_prepare16_v3 0
  108320. # define sqlite3_result_error16 0
  108321. # define sqlite3_result_text16 0
  108322. # define sqlite3_result_text16be 0
  108323. # define sqlite3_result_text16le 0
  108324. # define sqlite3_value_text16 0
  108325. # define sqlite3_value_text16be 0
  108326. # define sqlite3_value_text16le 0
  108327. # define sqlite3_column_database_name16 0
  108328. # define sqlite3_column_table_name16 0
  108329. # define sqlite3_column_origin_name16 0
  108330. #endif
  108331. #ifdef SQLITE_OMIT_COMPLETE
  108332. # define sqlite3_complete 0
  108333. # define sqlite3_complete16 0
  108334. #endif
  108335. #ifdef SQLITE_OMIT_DECLTYPE
  108336. # define sqlite3_column_decltype16 0
  108337. # define sqlite3_column_decltype 0
  108338. #endif
  108339. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  108340. # define sqlite3_progress_handler 0
  108341. #endif
  108342. #ifdef SQLITE_OMIT_VIRTUALTABLE
  108343. # define sqlite3_create_module 0
  108344. # define sqlite3_create_module_v2 0
  108345. # define sqlite3_declare_vtab 0
  108346. # define sqlite3_vtab_config 0
  108347. # define sqlite3_vtab_on_conflict 0
  108348. #endif
  108349. #ifdef SQLITE_OMIT_SHARED_CACHE
  108350. # define sqlite3_enable_shared_cache 0
  108351. #endif
  108352. #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
  108353. # define sqlite3_profile 0
  108354. # define sqlite3_trace 0
  108355. #endif
  108356. #ifdef SQLITE_OMIT_GET_TABLE
  108357. # define sqlite3_free_table 0
  108358. # define sqlite3_get_table 0
  108359. #endif
  108360. #ifdef SQLITE_OMIT_INCRBLOB
  108361. #define sqlite3_bind_zeroblob 0
  108362. #define sqlite3_blob_bytes 0
  108363. #define sqlite3_blob_close 0
  108364. #define sqlite3_blob_open 0
  108365. #define sqlite3_blob_read 0
  108366. #define sqlite3_blob_write 0
  108367. #define sqlite3_blob_reopen 0
  108368. #endif
  108369. #if defined(SQLITE_OMIT_TRACE)
  108370. # define sqlite3_trace_v2 0
  108371. #endif
  108372. /*
  108373. ** The following structure contains pointers to all SQLite API routines.
  108374. ** A pointer to this structure is passed into extensions when they are
  108375. ** loaded so that the extension can make calls back into the SQLite
  108376. ** library.
  108377. **
  108378. ** When adding new APIs, add them to the bottom of this structure
  108379. ** in order to preserve backwards compatibility.
  108380. **
  108381. ** Extensions that use newer APIs should first call the
  108382. ** sqlite3_libversion_number() to make sure that the API they
  108383. ** intend to use is supported by the library. Extensions should
  108384. ** also check to make sure that the pointer to the function is
  108385. ** not NULL before calling it.
  108386. */
  108387. static const sqlite3_api_routines sqlite3Apis = {
  108388. sqlite3_aggregate_context,
  108389. #ifndef SQLITE_OMIT_DEPRECATED
  108390. sqlite3_aggregate_count,
  108391. #else
  108392. 0,
  108393. #endif
  108394. sqlite3_bind_blob,
  108395. sqlite3_bind_double,
  108396. sqlite3_bind_int,
  108397. sqlite3_bind_int64,
  108398. sqlite3_bind_null,
  108399. sqlite3_bind_parameter_count,
  108400. sqlite3_bind_parameter_index,
  108401. sqlite3_bind_parameter_name,
  108402. sqlite3_bind_text,
  108403. sqlite3_bind_text16,
  108404. sqlite3_bind_value,
  108405. sqlite3_busy_handler,
  108406. sqlite3_busy_timeout,
  108407. sqlite3_changes,
  108408. sqlite3_close,
  108409. sqlite3_collation_needed,
  108410. sqlite3_collation_needed16,
  108411. sqlite3_column_blob,
  108412. sqlite3_column_bytes,
  108413. sqlite3_column_bytes16,
  108414. sqlite3_column_count,
  108415. sqlite3_column_database_name,
  108416. sqlite3_column_database_name16,
  108417. sqlite3_column_decltype,
  108418. sqlite3_column_decltype16,
  108419. sqlite3_column_double,
  108420. sqlite3_column_int,
  108421. sqlite3_column_int64,
  108422. sqlite3_column_name,
  108423. sqlite3_column_name16,
  108424. sqlite3_column_origin_name,
  108425. sqlite3_column_origin_name16,
  108426. sqlite3_column_table_name,
  108427. sqlite3_column_table_name16,
  108428. sqlite3_column_text,
  108429. sqlite3_column_text16,
  108430. sqlite3_column_type,
  108431. sqlite3_column_value,
  108432. sqlite3_commit_hook,
  108433. sqlite3_complete,
  108434. sqlite3_complete16,
  108435. sqlite3_create_collation,
  108436. sqlite3_create_collation16,
  108437. sqlite3_create_function,
  108438. sqlite3_create_function16,
  108439. sqlite3_create_module,
  108440. sqlite3_data_count,
  108441. sqlite3_db_handle,
  108442. sqlite3_declare_vtab,
  108443. sqlite3_enable_shared_cache,
  108444. sqlite3_errcode,
  108445. sqlite3_errmsg,
  108446. sqlite3_errmsg16,
  108447. sqlite3_exec,
  108448. #ifndef SQLITE_OMIT_DEPRECATED
  108449. sqlite3_expired,
  108450. #else
  108451. 0,
  108452. #endif
  108453. sqlite3_finalize,
  108454. sqlite3_free,
  108455. sqlite3_free_table,
  108456. sqlite3_get_autocommit,
  108457. sqlite3_get_auxdata,
  108458. sqlite3_get_table,
  108459. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  108460. sqlite3_interrupt,
  108461. sqlite3_last_insert_rowid,
  108462. sqlite3_libversion,
  108463. sqlite3_libversion_number,
  108464. sqlite3_malloc,
  108465. sqlite3_mprintf,
  108466. sqlite3_open,
  108467. sqlite3_open16,
  108468. sqlite3_prepare,
  108469. sqlite3_prepare16,
  108470. sqlite3_profile,
  108471. sqlite3_progress_handler,
  108472. sqlite3_realloc,
  108473. sqlite3_reset,
  108474. sqlite3_result_blob,
  108475. sqlite3_result_double,
  108476. sqlite3_result_error,
  108477. sqlite3_result_error16,
  108478. sqlite3_result_int,
  108479. sqlite3_result_int64,
  108480. sqlite3_result_null,
  108481. sqlite3_result_text,
  108482. sqlite3_result_text16,
  108483. sqlite3_result_text16be,
  108484. sqlite3_result_text16le,
  108485. sqlite3_result_value,
  108486. sqlite3_rollback_hook,
  108487. sqlite3_set_authorizer,
  108488. sqlite3_set_auxdata,
  108489. sqlite3_snprintf,
  108490. sqlite3_step,
  108491. sqlite3_table_column_metadata,
  108492. #ifndef SQLITE_OMIT_DEPRECATED
  108493. sqlite3_thread_cleanup,
  108494. #else
  108495. 0,
  108496. #endif
  108497. sqlite3_total_changes,
  108498. sqlite3_trace,
  108499. #ifndef SQLITE_OMIT_DEPRECATED
  108500. sqlite3_transfer_bindings,
  108501. #else
  108502. 0,
  108503. #endif
  108504. sqlite3_update_hook,
  108505. sqlite3_user_data,
  108506. sqlite3_value_blob,
  108507. sqlite3_value_bytes,
  108508. sqlite3_value_bytes16,
  108509. sqlite3_value_double,
  108510. sqlite3_value_int,
  108511. sqlite3_value_int64,
  108512. sqlite3_value_numeric_type,
  108513. sqlite3_value_text,
  108514. sqlite3_value_text16,
  108515. sqlite3_value_text16be,
  108516. sqlite3_value_text16le,
  108517. sqlite3_value_type,
  108518. sqlite3_vmprintf,
  108519. /*
  108520. ** The original API set ends here. All extensions can call any
  108521. ** of the APIs above provided that the pointer is not NULL. But
  108522. ** before calling APIs that follow, extension should check the
  108523. ** sqlite3_libversion_number() to make sure they are dealing with
  108524. ** a library that is new enough to support that API.
  108525. *************************************************************************
  108526. */
  108527. sqlite3_overload_function,
  108528. /*
  108529. ** Added after 3.3.13
  108530. */
  108531. sqlite3_prepare_v2,
  108532. sqlite3_prepare16_v2,
  108533. sqlite3_clear_bindings,
  108534. /*
  108535. ** Added for 3.4.1
  108536. */
  108537. sqlite3_create_module_v2,
  108538. /*
  108539. ** Added for 3.5.0
  108540. */
  108541. sqlite3_bind_zeroblob,
  108542. sqlite3_blob_bytes,
  108543. sqlite3_blob_close,
  108544. sqlite3_blob_open,
  108545. sqlite3_blob_read,
  108546. sqlite3_blob_write,
  108547. sqlite3_create_collation_v2,
  108548. sqlite3_file_control,
  108549. sqlite3_memory_highwater,
  108550. sqlite3_memory_used,
  108551. #ifdef SQLITE_MUTEX_OMIT
  108552. 0,
  108553. 0,
  108554. 0,
  108555. 0,
  108556. 0,
  108557. #else
  108558. sqlite3_mutex_alloc,
  108559. sqlite3_mutex_enter,
  108560. sqlite3_mutex_free,
  108561. sqlite3_mutex_leave,
  108562. sqlite3_mutex_try,
  108563. #endif
  108564. sqlite3_open_v2,
  108565. sqlite3_release_memory,
  108566. sqlite3_result_error_nomem,
  108567. sqlite3_result_error_toobig,
  108568. sqlite3_sleep,
  108569. sqlite3_soft_heap_limit,
  108570. sqlite3_vfs_find,
  108571. sqlite3_vfs_register,
  108572. sqlite3_vfs_unregister,
  108573. /*
  108574. ** Added for 3.5.8
  108575. */
  108576. sqlite3_threadsafe,
  108577. sqlite3_result_zeroblob,
  108578. sqlite3_result_error_code,
  108579. sqlite3_test_control,
  108580. sqlite3_randomness,
  108581. sqlite3_context_db_handle,
  108582. /*
  108583. ** Added for 3.6.0
  108584. */
  108585. sqlite3_extended_result_codes,
  108586. sqlite3_limit,
  108587. sqlite3_next_stmt,
  108588. sqlite3_sql,
  108589. sqlite3_status,
  108590. /*
  108591. ** Added for 3.7.4
  108592. */
  108593. sqlite3_backup_finish,
  108594. sqlite3_backup_init,
  108595. sqlite3_backup_pagecount,
  108596. sqlite3_backup_remaining,
  108597. sqlite3_backup_step,
  108598. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  108599. sqlite3_compileoption_get,
  108600. sqlite3_compileoption_used,
  108601. #else
  108602. 0,
  108603. 0,
  108604. #endif
  108605. sqlite3_create_function_v2,
  108606. sqlite3_db_config,
  108607. sqlite3_db_mutex,
  108608. sqlite3_db_status,
  108609. sqlite3_extended_errcode,
  108610. sqlite3_log,
  108611. sqlite3_soft_heap_limit64,
  108612. sqlite3_sourceid,
  108613. sqlite3_stmt_status,
  108614. sqlite3_strnicmp,
  108615. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  108616. sqlite3_unlock_notify,
  108617. #else
  108618. 0,
  108619. #endif
  108620. #ifndef SQLITE_OMIT_WAL
  108621. sqlite3_wal_autocheckpoint,
  108622. sqlite3_wal_checkpoint,
  108623. sqlite3_wal_hook,
  108624. #else
  108625. 0,
  108626. 0,
  108627. 0,
  108628. #endif
  108629. sqlite3_blob_reopen,
  108630. sqlite3_vtab_config,
  108631. sqlite3_vtab_on_conflict,
  108632. sqlite3_close_v2,
  108633. sqlite3_db_filename,
  108634. sqlite3_db_readonly,
  108635. sqlite3_db_release_memory,
  108636. sqlite3_errstr,
  108637. sqlite3_stmt_busy,
  108638. sqlite3_stmt_readonly,
  108639. sqlite3_stricmp,
  108640. sqlite3_uri_boolean,
  108641. sqlite3_uri_int64,
  108642. sqlite3_uri_parameter,
  108643. sqlite3_vsnprintf,
  108644. sqlite3_wal_checkpoint_v2,
  108645. /* Version 3.8.7 and later */
  108646. sqlite3_auto_extension,
  108647. sqlite3_bind_blob64,
  108648. sqlite3_bind_text64,
  108649. sqlite3_cancel_auto_extension,
  108650. sqlite3_load_extension,
  108651. sqlite3_malloc64,
  108652. sqlite3_msize,
  108653. sqlite3_realloc64,
  108654. sqlite3_reset_auto_extension,
  108655. sqlite3_result_blob64,
  108656. sqlite3_result_text64,
  108657. sqlite3_strglob,
  108658. /* Version 3.8.11 and later */
  108659. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  108660. sqlite3_value_free,
  108661. sqlite3_result_zeroblob64,
  108662. sqlite3_bind_zeroblob64,
  108663. /* Version 3.9.0 and later */
  108664. sqlite3_value_subtype,
  108665. sqlite3_result_subtype,
  108666. /* Version 3.10.0 and later */
  108667. sqlite3_status64,
  108668. sqlite3_strlike,
  108669. sqlite3_db_cacheflush,
  108670. /* Version 3.12.0 and later */
  108671. sqlite3_system_errno,
  108672. /* Version 3.14.0 and later */
  108673. sqlite3_trace_v2,
  108674. sqlite3_expanded_sql,
  108675. /* Version 3.18.0 and later */
  108676. sqlite3_set_last_insert_rowid,
  108677. /* Version 3.20.0 and later */
  108678. sqlite3_prepare_v3,
  108679. sqlite3_prepare16_v3,
  108680. sqlite3_bind_pointer,
  108681. sqlite3_result_pointer,
  108682. sqlite3_value_pointer,
  108683. /* Version 3.22.0 and later */
  108684. sqlite3_vtab_nochange,
  108685. sqlite3_value_nochange,
  108686. sqlite3_vtab_collation
  108687. };
  108688. /*
  108689. ** Attempt to load an SQLite extension library contained in the file
  108690. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  108691. ** default entry point name (sqlite3_extension_init) is used. Use
  108692. ** of the default name is recommended.
  108693. **
  108694. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  108695. **
  108696. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  108697. ** error message text. The calling function should free this memory
  108698. ** by calling sqlite3DbFree(db, ).
  108699. */
  108700. static int sqlite3LoadExtension(
  108701. sqlite3 *db, /* Load the extension into this database connection */
  108702. const char *zFile, /* Name of the shared library containing extension */
  108703. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  108704. char **pzErrMsg /* Put error message here if not 0 */
  108705. ){
  108706. sqlite3_vfs *pVfs = db->pVfs;
  108707. void *handle;
  108708. sqlite3_loadext_entry xInit;
  108709. char *zErrmsg = 0;
  108710. const char *zEntry;
  108711. char *zAltEntry = 0;
  108712. void **aHandle;
  108713. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  108714. int ii;
  108715. int rc;
  108716. /* Shared library endings to try if zFile cannot be loaded as written */
  108717. static const char *azEndings[] = {
  108718. #if SQLITE_OS_WIN
  108719. "dll"
  108720. #elif defined(__APPLE__)
  108721. "dylib"
  108722. #else
  108723. "so"
  108724. #endif
  108725. };
  108726. if( pzErrMsg ) *pzErrMsg = 0;
  108727. /* Ticket #1863. To avoid a creating security problems for older
  108728. ** applications that relink against newer versions of SQLite, the
  108729. ** ability to run load_extension is turned off by default. One
  108730. ** must call either sqlite3_enable_load_extension(db) or
  108731. ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
  108732. ** to turn on extension loading.
  108733. */
  108734. if( (db->flags & SQLITE_LoadExtension)==0 ){
  108735. if( pzErrMsg ){
  108736. *pzErrMsg = sqlite3_mprintf("not authorized");
  108737. }
  108738. return SQLITE_ERROR;
  108739. }
  108740. zEntry = zProc ? zProc : "sqlite3_extension_init";
  108741. handle = sqlite3OsDlOpen(pVfs, zFile);
  108742. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  108743. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  108744. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  108745. int bExists = 0;
  108746. if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
  108747. sqlite3OsAccess(pVfs, zAltFile, SQLITE_ACCESS_EXISTS, &bExists);
  108748. if( bExists ) handle = sqlite3OsDlOpen(pVfs, zAltFile);
  108749. sqlite3_free(zAltFile);
  108750. }
  108751. #endif
  108752. if( handle==0 ){
  108753. if( pzErrMsg ){
  108754. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  108755. if( zErrmsg ){
  108756. sqlite3_snprintf(nMsg, zErrmsg,
  108757. "unable to open shared library [%s]", zFile);
  108758. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  108759. }
  108760. }
  108761. return SQLITE_ERROR;
  108762. }
  108763. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  108764. /* If no entry point was specified and the default legacy
  108765. ** entry point name "sqlite3_extension_init" was not found, then
  108766. ** construct an entry point name "sqlite3_X_init" where the X is
  108767. ** replaced by the lowercase value of every ASCII alphabetic
  108768. ** character in the filename after the last "/" upto the first ".",
  108769. ** and eliding the first three characters if they are "lib".
  108770. ** Examples:
  108771. **
  108772. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  108773. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  108774. */
  108775. if( xInit==0 && zProc==0 ){
  108776. int iFile, iEntry, c;
  108777. int ncFile = sqlite3Strlen30(zFile);
  108778. zAltEntry = sqlite3_malloc64(ncFile+30);
  108779. if( zAltEntry==0 ){
  108780. sqlite3OsDlClose(pVfs, handle);
  108781. return SQLITE_NOMEM_BKPT;
  108782. }
  108783. memcpy(zAltEntry, "sqlite3_", 8);
  108784. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  108785. iFile++;
  108786. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  108787. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  108788. if( sqlite3Isalpha(c) ){
  108789. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  108790. }
  108791. }
  108792. memcpy(zAltEntry+iEntry, "_init", 6);
  108793. zEntry = zAltEntry;
  108794. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  108795. }
  108796. if( xInit==0 ){
  108797. if( pzErrMsg ){
  108798. nMsg += sqlite3Strlen30(zEntry);
  108799. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  108800. if( zErrmsg ){
  108801. sqlite3_snprintf(nMsg, zErrmsg,
  108802. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  108803. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  108804. }
  108805. }
  108806. sqlite3OsDlClose(pVfs, handle);
  108807. sqlite3_free(zAltEntry);
  108808. return SQLITE_ERROR;
  108809. }
  108810. sqlite3_free(zAltEntry);
  108811. rc = xInit(db, &zErrmsg, &sqlite3Apis);
  108812. if( rc ){
  108813. if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
  108814. if( pzErrMsg ){
  108815. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  108816. }
  108817. sqlite3_free(zErrmsg);
  108818. sqlite3OsDlClose(pVfs, handle);
  108819. return SQLITE_ERROR;
  108820. }
  108821. /* Append the new shared library handle to the db->aExtension array. */
  108822. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  108823. if( aHandle==0 ){
  108824. return SQLITE_NOMEM_BKPT;
  108825. }
  108826. if( db->nExtension>0 ){
  108827. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  108828. }
  108829. sqlite3DbFree(db, db->aExtension);
  108830. db->aExtension = aHandle;
  108831. db->aExtension[db->nExtension++] = handle;
  108832. return SQLITE_OK;
  108833. }
  108834. SQLITE_API int sqlite3_load_extension(
  108835. sqlite3 *db, /* Load the extension into this database connection */
  108836. const char *zFile, /* Name of the shared library containing extension */
  108837. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  108838. char **pzErrMsg /* Put error message here if not 0 */
  108839. ){
  108840. int rc;
  108841. sqlite3_mutex_enter(db->mutex);
  108842. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  108843. rc = sqlite3ApiExit(db, rc);
  108844. sqlite3_mutex_leave(db->mutex);
  108845. return rc;
  108846. }
  108847. /*
  108848. ** Call this routine when the database connection is closing in order
  108849. ** to clean up loaded extensions
  108850. */
  108851. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  108852. int i;
  108853. assert( sqlite3_mutex_held(db->mutex) );
  108854. for(i=0; i<db->nExtension; i++){
  108855. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  108856. }
  108857. sqlite3DbFree(db, db->aExtension);
  108858. }
  108859. /*
  108860. ** Enable or disable extension loading. Extension loading is disabled by
  108861. ** default so as not to open security holes in older applications.
  108862. */
  108863. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  108864. sqlite3_mutex_enter(db->mutex);
  108865. if( onoff ){
  108866. db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
  108867. }else{
  108868. db->flags &= ~(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
  108869. }
  108870. sqlite3_mutex_leave(db->mutex);
  108871. return SQLITE_OK;
  108872. }
  108873. #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  108874. /*
  108875. ** The following object holds the list of automatically loaded
  108876. ** extensions.
  108877. **
  108878. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  108879. ** mutex must be held while accessing this list.
  108880. */
  108881. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  108882. static SQLITE_WSD struct sqlite3AutoExtList {
  108883. u32 nExt; /* Number of entries in aExt[] */
  108884. void (**aExt)(void); /* Pointers to the extension init functions */
  108885. } sqlite3Autoext = { 0, 0 };
  108886. /* The "wsdAutoext" macro will resolve to the autoextension
  108887. ** state vector. If writable static data is unsupported on the target,
  108888. ** we have to locate the state vector at run-time. In the more common
  108889. ** case where writable static data is supported, wsdStat can refer directly
  108890. ** to the "sqlite3Autoext" state vector declared above.
  108891. */
  108892. #ifdef SQLITE_OMIT_WSD
  108893. # define wsdAutoextInit \
  108894. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  108895. # define wsdAutoext x[0]
  108896. #else
  108897. # define wsdAutoextInit
  108898. # define wsdAutoext sqlite3Autoext
  108899. #endif
  108900. /*
  108901. ** Register a statically linked extension that is automatically
  108902. ** loaded by every new database connection.
  108903. */
  108904. SQLITE_API int sqlite3_auto_extension(
  108905. void (*xInit)(void)
  108906. ){
  108907. int rc = SQLITE_OK;
  108908. #ifndef SQLITE_OMIT_AUTOINIT
  108909. rc = sqlite3_initialize();
  108910. if( rc ){
  108911. return rc;
  108912. }else
  108913. #endif
  108914. {
  108915. u32 i;
  108916. #if SQLITE_THREADSAFE
  108917. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  108918. #endif
  108919. wsdAutoextInit;
  108920. sqlite3_mutex_enter(mutex);
  108921. for(i=0; i<wsdAutoext.nExt; i++){
  108922. if( wsdAutoext.aExt[i]==xInit ) break;
  108923. }
  108924. if( i==wsdAutoext.nExt ){
  108925. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  108926. void (**aNew)(void);
  108927. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  108928. if( aNew==0 ){
  108929. rc = SQLITE_NOMEM_BKPT;
  108930. }else{
  108931. wsdAutoext.aExt = aNew;
  108932. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  108933. wsdAutoext.nExt++;
  108934. }
  108935. }
  108936. sqlite3_mutex_leave(mutex);
  108937. assert( (rc&0xff)==rc );
  108938. return rc;
  108939. }
  108940. }
  108941. /*
  108942. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  108943. ** set of routines that is invoked for each new database connection, if it
  108944. ** is currently on the list. If xInit is not on the list, then this
  108945. ** routine is a no-op.
  108946. **
  108947. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  108948. ** was not on the list.
  108949. */
  108950. SQLITE_API int sqlite3_cancel_auto_extension(
  108951. void (*xInit)(void)
  108952. ){
  108953. #if SQLITE_THREADSAFE
  108954. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  108955. #endif
  108956. int i;
  108957. int n = 0;
  108958. wsdAutoextInit;
  108959. sqlite3_mutex_enter(mutex);
  108960. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  108961. if( wsdAutoext.aExt[i]==xInit ){
  108962. wsdAutoext.nExt--;
  108963. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  108964. n++;
  108965. break;
  108966. }
  108967. }
  108968. sqlite3_mutex_leave(mutex);
  108969. return n;
  108970. }
  108971. /*
  108972. ** Reset the automatic extension loading mechanism.
  108973. */
  108974. SQLITE_API void sqlite3_reset_auto_extension(void){
  108975. #ifndef SQLITE_OMIT_AUTOINIT
  108976. if( sqlite3_initialize()==SQLITE_OK )
  108977. #endif
  108978. {
  108979. #if SQLITE_THREADSAFE
  108980. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  108981. #endif
  108982. wsdAutoextInit;
  108983. sqlite3_mutex_enter(mutex);
  108984. sqlite3_free(wsdAutoext.aExt);
  108985. wsdAutoext.aExt = 0;
  108986. wsdAutoext.nExt = 0;
  108987. sqlite3_mutex_leave(mutex);
  108988. }
  108989. }
  108990. /*
  108991. ** Load all automatic extensions.
  108992. **
  108993. ** If anything goes wrong, set an error in the database connection.
  108994. */
  108995. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  108996. u32 i;
  108997. int go = 1;
  108998. int rc;
  108999. sqlite3_loadext_entry xInit;
  109000. wsdAutoextInit;
  109001. if( wsdAutoext.nExt==0 ){
  109002. /* Common case: early out without every having to acquire a mutex */
  109003. return;
  109004. }
  109005. for(i=0; go; i++){
  109006. char *zErrmsg;
  109007. #if SQLITE_THREADSAFE
  109008. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  109009. #endif
  109010. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  109011. const sqlite3_api_routines *pThunk = 0;
  109012. #else
  109013. const sqlite3_api_routines *pThunk = &sqlite3Apis;
  109014. #endif
  109015. sqlite3_mutex_enter(mutex);
  109016. if( i>=wsdAutoext.nExt ){
  109017. xInit = 0;
  109018. go = 0;
  109019. }else{
  109020. xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
  109021. }
  109022. sqlite3_mutex_leave(mutex);
  109023. zErrmsg = 0;
  109024. if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
  109025. sqlite3ErrorWithMsg(db, rc,
  109026. "automatic extension loading failed: %s", zErrmsg);
  109027. go = 0;
  109028. }
  109029. sqlite3_free(zErrmsg);
  109030. }
  109031. }
  109032. /************** End of loadext.c *********************************************/
  109033. /************** Begin file pragma.c ******************************************/
  109034. /*
  109035. ** 2003 April 6
  109036. **
  109037. ** The author disclaims copyright to this source code. In place of
  109038. ** a legal notice, here is a blessing:
  109039. **
  109040. ** May you do good and not evil.
  109041. ** May you find forgiveness for yourself and forgive others.
  109042. ** May you share freely, never taking more than you give.
  109043. **
  109044. *************************************************************************
  109045. ** This file contains code used to implement the PRAGMA command.
  109046. */
  109047. /* #include "sqliteInt.h" */
  109048. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  109049. # if defined(__APPLE__)
  109050. # define SQLITE_ENABLE_LOCKING_STYLE 1
  109051. # else
  109052. # define SQLITE_ENABLE_LOCKING_STYLE 0
  109053. # endif
  109054. #endif
  109055. /***************************************************************************
  109056. ** The "pragma.h" include file is an automatically generated file that
  109057. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  109058. ** object. This ensures that the aPragmaName[] table is arranged in
  109059. ** lexicographical order to facility a binary search of the pragma name.
  109060. ** Do not edit pragma.h directly. Edit and rerun the script in at
  109061. ** ../tool/mkpragmatab.tcl. */
  109062. /************** Include pragma.h in the middle of pragma.c *******************/
  109063. /************** Begin file pragma.h ******************************************/
  109064. /* DO NOT EDIT!
  109065. ** This file is automatically generated by the script at
  109066. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  109067. ** that script and rerun it.
  109068. */
  109069. /* The various pragma types */
  109070. #define PragTyp_HEADER_VALUE 0
  109071. #define PragTyp_AUTO_VACUUM 1
  109072. #define PragTyp_FLAG 2
  109073. #define PragTyp_BUSY_TIMEOUT 3
  109074. #define PragTyp_CACHE_SIZE 4
  109075. #define PragTyp_CACHE_SPILL 5
  109076. #define PragTyp_CASE_SENSITIVE_LIKE 6
  109077. #define PragTyp_COLLATION_LIST 7
  109078. #define PragTyp_COMPILE_OPTIONS 8
  109079. #define PragTyp_DATA_STORE_DIRECTORY 9
  109080. #define PragTyp_DATABASE_LIST 10
  109081. #define PragTyp_DEFAULT_CACHE_SIZE 11
  109082. #define PragTyp_ENCODING 12
  109083. #define PragTyp_FOREIGN_KEY_CHECK 13
  109084. #define PragTyp_FOREIGN_KEY_LIST 14
  109085. #define PragTyp_FUNCTION_LIST 15
  109086. #define PragTyp_INCREMENTAL_VACUUM 16
  109087. #define PragTyp_INDEX_INFO 17
  109088. #define PragTyp_INDEX_LIST 18
  109089. #define PragTyp_INTEGRITY_CHECK 19
  109090. #define PragTyp_JOURNAL_MODE 20
  109091. #define PragTyp_JOURNAL_SIZE_LIMIT 21
  109092. #define PragTyp_LOCK_PROXY_FILE 22
  109093. #define PragTyp_LOCKING_MODE 23
  109094. #define PragTyp_PAGE_COUNT 24
  109095. #define PragTyp_MMAP_SIZE 25
  109096. #define PragTyp_MODULE_LIST 26
  109097. #define PragTyp_OPTIMIZE 27
  109098. #define PragTyp_PAGE_SIZE 28
  109099. #define PragTyp_PRAGMA_LIST 29
  109100. #define PragTyp_SECURE_DELETE 30
  109101. #define PragTyp_SHRINK_MEMORY 31
  109102. #define PragTyp_SOFT_HEAP_LIMIT 32
  109103. #define PragTyp_SYNCHRONOUS 33
  109104. #define PragTyp_TABLE_INFO 34
  109105. #define PragTyp_TEMP_STORE 35
  109106. #define PragTyp_TEMP_STORE_DIRECTORY 36
  109107. #define PragTyp_THREADS 37
  109108. #define PragTyp_WAL_AUTOCHECKPOINT 38
  109109. #define PragTyp_WAL_CHECKPOINT 39
  109110. #define PragTyp_ACTIVATE_EXTENSIONS 40
  109111. #define PragTyp_HEXKEY 41
  109112. #define PragTyp_KEY 42
  109113. #define PragTyp_REKEY 43
  109114. #define PragTyp_LOCK_STATUS 44
  109115. #define PragTyp_PARSER_TRACE 45
  109116. #define PragTyp_STATS 46
  109117. /* Property flags associated with various pragma. */
  109118. #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
  109119. #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
  109120. #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
  109121. #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
  109122. #define PragFlg_Result0 0x10 /* Acts as query when no argument */
  109123. #define PragFlg_Result1 0x20 /* Acts as query when has one argument */
  109124. #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
  109125. #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
  109126. /* Names of columns for pragmas that return multi-column result
  109127. ** or that return single-column results where the name of the
  109128. ** result column is different from the name of the pragma
  109129. */
  109130. static const char *const pragCName[] = {
  109131. /* 0 */ "cache_size", /* Used by: default_cache_size */
  109132. /* 1 */ "cid", /* Used by: table_info */
  109133. /* 2 */ "name",
  109134. /* 3 */ "type",
  109135. /* 4 */ "notnull",
  109136. /* 5 */ "dflt_value",
  109137. /* 6 */ "pk",
  109138. /* 7 */ "tbl", /* Used by: stats */
  109139. /* 8 */ "idx",
  109140. /* 9 */ "wdth",
  109141. /* 10 */ "hght",
  109142. /* 11 */ "flgs",
  109143. /* 12 */ "seqno", /* Used by: index_info */
  109144. /* 13 */ "cid",
  109145. /* 14 */ "name",
  109146. /* 15 */ "seqno", /* Used by: index_xinfo */
  109147. /* 16 */ "cid",
  109148. /* 17 */ "name",
  109149. /* 18 */ "desc",
  109150. /* 19 */ "coll",
  109151. /* 20 */ "key",
  109152. /* 21 */ "seq", /* Used by: index_list */
  109153. /* 22 */ "name",
  109154. /* 23 */ "unique",
  109155. /* 24 */ "origin",
  109156. /* 25 */ "partial",
  109157. /* 26 */ "seq", /* Used by: database_list */
  109158. /* 27 */ "name",
  109159. /* 28 */ "file",
  109160. /* 29 */ "name", /* Used by: function_list */
  109161. /* 30 */ "builtin",
  109162. /* 31 */ "name", /* Used by: module_list pragma_list */
  109163. /* 32 */ "seq", /* Used by: collation_list */
  109164. /* 33 */ "name",
  109165. /* 34 */ "id", /* Used by: foreign_key_list */
  109166. /* 35 */ "seq",
  109167. /* 36 */ "table",
  109168. /* 37 */ "from",
  109169. /* 38 */ "to",
  109170. /* 39 */ "on_update",
  109171. /* 40 */ "on_delete",
  109172. /* 41 */ "match",
  109173. /* 42 */ "table", /* Used by: foreign_key_check */
  109174. /* 43 */ "rowid",
  109175. /* 44 */ "parent",
  109176. /* 45 */ "fkid",
  109177. /* 46 */ "busy", /* Used by: wal_checkpoint */
  109178. /* 47 */ "log",
  109179. /* 48 */ "checkpointed",
  109180. /* 49 */ "timeout", /* Used by: busy_timeout */
  109181. /* 50 */ "database", /* Used by: lock_status */
  109182. /* 51 */ "status",
  109183. };
  109184. /* Definitions of all built-in pragmas */
  109185. typedef struct PragmaName {
  109186. const char *const zName; /* Name of pragma */
  109187. u8 ePragTyp; /* PragTyp_XXX value */
  109188. u8 mPragFlg; /* Zero or more PragFlg_XXX values */
  109189. u8 iPragCName; /* Start of column names in pragCName[] */
  109190. u8 nPragCName; /* Num of col names. 0 means use pragma name */
  109191. u32 iArg; /* Extra argument */
  109192. } PragmaName;
  109193. static const PragmaName aPragmaName[] = {
  109194. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  109195. {/* zName: */ "activate_extensions",
  109196. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  109197. /* ePragFlg: */ 0,
  109198. /* ColNames: */ 0, 0,
  109199. /* iArg: */ 0 },
  109200. #endif
  109201. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  109202. {/* zName: */ "application_id",
  109203. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  109204. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  109205. /* ColNames: */ 0, 0,
  109206. /* iArg: */ BTREE_APPLICATION_ID },
  109207. #endif
  109208. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  109209. {/* zName: */ "auto_vacuum",
  109210. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  109211. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  109212. /* ColNames: */ 0, 0,
  109213. /* iArg: */ 0 },
  109214. #endif
  109215. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109216. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  109217. {/* zName: */ "automatic_index",
  109218. /* ePragTyp: */ PragTyp_FLAG,
  109219. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109220. /* ColNames: */ 0, 0,
  109221. /* iArg: */ SQLITE_AutoIndex },
  109222. #endif
  109223. #endif
  109224. {/* zName: */ "busy_timeout",
  109225. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  109226. /* ePragFlg: */ PragFlg_Result0,
  109227. /* ColNames: */ 49, 1,
  109228. /* iArg: */ 0 },
  109229. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  109230. {/* zName: */ "cache_size",
  109231. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  109232. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  109233. /* ColNames: */ 0, 0,
  109234. /* iArg: */ 0 },
  109235. #endif
  109236. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109237. {/* zName: */ "cache_spill",
  109238. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  109239. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  109240. /* ColNames: */ 0, 0,
  109241. /* iArg: */ 0 },
  109242. #endif
  109243. {/* zName: */ "case_sensitive_like",
  109244. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  109245. /* ePragFlg: */ PragFlg_NoColumns,
  109246. /* ColNames: */ 0, 0,
  109247. /* iArg: */ 0 },
  109248. {/* zName: */ "cell_size_check",
  109249. /* ePragTyp: */ PragTyp_FLAG,
  109250. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109251. /* ColNames: */ 0, 0,
  109252. /* iArg: */ SQLITE_CellSizeCk },
  109253. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109254. {/* zName: */ "checkpoint_fullfsync",
  109255. /* ePragTyp: */ PragTyp_FLAG,
  109256. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109257. /* ColNames: */ 0, 0,
  109258. /* iArg: */ SQLITE_CkptFullFSync },
  109259. #endif
  109260. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  109261. {/* zName: */ "collation_list",
  109262. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  109263. /* ePragFlg: */ PragFlg_Result0,
  109264. /* ColNames: */ 32, 2,
  109265. /* iArg: */ 0 },
  109266. #endif
  109267. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  109268. {/* zName: */ "compile_options",
  109269. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  109270. /* ePragFlg: */ PragFlg_Result0,
  109271. /* ColNames: */ 0, 0,
  109272. /* iArg: */ 0 },
  109273. #endif
  109274. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109275. {/* zName: */ "count_changes",
  109276. /* ePragTyp: */ PragTyp_FLAG,
  109277. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109278. /* ColNames: */ 0, 0,
  109279. /* iArg: */ SQLITE_CountRows },
  109280. #endif
  109281. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  109282. {/* zName: */ "data_store_directory",
  109283. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  109284. /* ePragFlg: */ PragFlg_NoColumns1,
  109285. /* ColNames: */ 0, 0,
  109286. /* iArg: */ 0 },
  109287. #endif
  109288. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  109289. {/* zName: */ "data_version",
  109290. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  109291. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  109292. /* ColNames: */ 0, 0,
  109293. /* iArg: */ BTREE_DATA_VERSION },
  109294. #endif
  109295. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  109296. {/* zName: */ "database_list",
  109297. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  109298. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  109299. /* ColNames: */ 26, 3,
  109300. /* iArg: */ 0 },
  109301. #endif
  109302. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  109303. {/* zName: */ "default_cache_size",
  109304. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  109305. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  109306. /* ColNames: */ 0, 1,
  109307. /* iArg: */ 0 },
  109308. #endif
  109309. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109310. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  109311. {/* zName: */ "defer_foreign_keys",
  109312. /* ePragTyp: */ PragTyp_FLAG,
  109313. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109314. /* ColNames: */ 0, 0,
  109315. /* iArg: */ SQLITE_DeferFKs },
  109316. #endif
  109317. #endif
  109318. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109319. {/* zName: */ "empty_result_callbacks",
  109320. /* ePragTyp: */ PragTyp_FLAG,
  109321. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109322. /* ColNames: */ 0, 0,
  109323. /* iArg: */ SQLITE_NullCallback },
  109324. #endif
  109325. #if !defined(SQLITE_OMIT_UTF16)
  109326. {/* zName: */ "encoding",
  109327. /* ePragTyp: */ PragTyp_ENCODING,
  109328. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109329. /* ColNames: */ 0, 0,
  109330. /* iArg: */ 0 },
  109331. #endif
  109332. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  109333. {/* zName: */ "foreign_key_check",
  109334. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  109335. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  109336. /* ColNames: */ 42, 4,
  109337. /* iArg: */ 0 },
  109338. #endif
  109339. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  109340. {/* zName: */ "foreign_key_list",
  109341. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  109342. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  109343. /* ColNames: */ 34, 8,
  109344. /* iArg: */ 0 },
  109345. #endif
  109346. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109347. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  109348. {/* zName: */ "foreign_keys",
  109349. /* ePragTyp: */ PragTyp_FLAG,
  109350. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109351. /* ColNames: */ 0, 0,
  109352. /* iArg: */ SQLITE_ForeignKeys },
  109353. #endif
  109354. #endif
  109355. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  109356. {/* zName: */ "freelist_count",
  109357. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  109358. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  109359. /* ColNames: */ 0, 0,
  109360. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  109361. #endif
  109362. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109363. {/* zName: */ "full_column_names",
  109364. /* ePragTyp: */ PragTyp_FLAG,
  109365. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109366. /* ColNames: */ 0, 0,
  109367. /* iArg: */ SQLITE_FullColNames },
  109368. {/* zName: */ "fullfsync",
  109369. /* ePragTyp: */ PragTyp_FLAG,
  109370. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109371. /* ColNames: */ 0, 0,
  109372. /* iArg: */ SQLITE_FullFSync },
  109373. #endif
  109374. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  109375. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  109376. {/* zName: */ "function_list",
  109377. /* ePragTyp: */ PragTyp_FUNCTION_LIST,
  109378. /* ePragFlg: */ PragFlg_Result0,
  109379. /* ColNames: */ 29, 2,
  109380. /* iArg: */ 0 },
  109381. #endif
  109382. #endif
  109383. #if defined(SQLITE_HAS_CODEC)
  109384. {/* zName: */ "hexkey",
  109385. /* ePragTyp: */ PragTyp_HEXKEY,
  109386. /* ePragFlg: */ 0,
  109387. /* ColNames: */ 0, 0,
  109388. /* iArg: */ 0 },
  109389. {/* zName: */ "hexrekey",
  109390. /* ePragTyp: */ PragTyp_HEXKEY,
  109391. /* ePragFlg: */ 0,
  109392. /* ColNames: */ 0, 0,
  109393. /* iArg: */ 0 },
  109394. #endif
  109395. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109396. #if !defined(SQLITE_OMIT_CHECK)
  109397. {/* zName: */ "ignore_check_constraints",
  109398. /* ePragTyp: */ PragTyp_FLAG,
  109399. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109400. /* ColNames: */ 0, 0,
  109401. /* iArg: */ SQLITE_IgnoreChecks },
  109402. #endif
  109403. #endif
  109404. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  109405. {/* zName: */ "incremental_vacuum",
  109406. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  109407. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
  109408. /* ColNames: */ 0, 0,
  109409. /* iArg: */ 0 },
  109410. #endif
  109411. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  109412. {/* zName: */ "index_info",
  109413. /* ePragTyp: */ PragTyp_INDEX_INFO,
  109414. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  109415. /* ColNames: */ 12, 3,
  109416. /* iArg: */ 0 },
  109417. {/* zName: */ "index_list",
  109418. /* ePragTyp: */ PragTyp_INDEX_LIST,
  109419. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  109420. /* ColNames: */ 21, 5,
  109421. /* iArg: */ 0 },
  109422. {/* zName: */ "index_xinfo",
  109423. /* ePragTyp: */ PragTyp_INDEX_INFO,
  109424. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  109425. /* ColNames: */ 15, 6,
  109426. /* iArg: */ 1 },
  109427. #endif
  109428. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  109429. {/* zName: */ "integrity_check",
  109430. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  109431. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  109432. /* ColNames: */ 0, 0,
  109433. /* iArg: */ 0 },
  109434. #endif
  109435. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  109436. {/* zName: */ "journal_mode",
  109437. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  109438. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  109439. /* ColNames: */ 0, 0,
  109440. /* iArg: */ 0 },
  109441. {/* zName: */ "journal_size_limit",
  109442. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  109443. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  109444. /* ColNames: */ 0, 0,
  109445. /* iArg: */ 0 },
  109446. #endif
  109447. #if defined(SQLITE_HAS_CODEC)
  109448. {/* zName: */ "key",
  109449. /* ePragTyp: */ PragTyp_KEY,
  109450. /* ePragFlg: */ 0,
  109451. /* ColNames: */ 0, 0,
  109452. /* iArg: */ 0 },
  109453. #endif
  109454. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109455. {/* zName: */ "legacy_file_format",
  109456. /* ePragTyp: */ PragTyp_FLAG,
  109457. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109458. /* ColNames: */ 0, 0,
  109459. /* iArg: */ SQLITE_LegacyFileFmt },
  109460. #endif
  109461. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  109462. {/* zName: */ "lock_proxy_file",
  109463. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  109464. /* ePragFlg: */ PragFlg_NoColumns1,
  109465. /* ColNames: */ 0, 0,
  109466. /* iArg: */ 0 },
  109467. #endif
  109468. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  109469. {/* zName: */ "lock_status",
  109470. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  109471. /* ePragFlg: */ PragFlg_Result0,
  109472. /* ColNames: */ 50, 2,
  109473. /* iArg: */ 0 },
  109474. #endif
  109475. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  109476. {/* zName: */ "locking_mode",
  109477. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  109478. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  109479. /* ColNames: */ 0, 0,
  109480. /* iArg: */ 0 },
  109481. {/* zName: */ "max_page_count",
  109482. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  109483. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  109484. /* ColNames: */ 0, 0,
  109485. /* iArg: */ 0 },
  109486. {/* zName: */ "mmap_size",
  109487. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  109488. /* ePragFlg: */ 0,
  109489. /* ColNames: */ 0, 0,
  109490. /* iArg: */ 0 },
  109491. #endif
  109492. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  109493. #if !defined(SQLITE_OMIT_VIRTUALTABLE)
  109494. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  109495. {/* zName: */ "module_list",
  109496. /* ePragTyp: */ PragTyp_MODULE_LIST,
  109497. /* ePragFlg: */ PragFlg_Result0,
  109498. /* ColNames: */ 31, 1,
  109499. /* iArg: */ 0 },
  109500. #endif
  109501. #endif
  109502. #endif
  109503. {/* zName: */ "optimize",
  109504. /* ePragTyp: */ PragTyp_OPTIMIZE,
  109505. /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
  109506. /* ColNames: */ 0, 0,
  109507. /* iArg: */ 0 },
  109508. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  109509. {/* zName: */ "page_count",
  109510. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  109511. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  109512. /* ColNames: */ 0, 0,
  109513. /* iArg: */ 0 },
  109514. {/* zName: */ "page_size",
  109515. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  109516. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  109517. /* ColNames: */ 0, 0,
  109518. /* iArg: */ 0 },
  109519. #endif
  109520. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
  109521. {/* zName: */ "parser_trace",
  109522. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  109523. /* ePragFlg: */ 0,
  109524. /* ColNames: */ 0, 0,
  109525. /* iArg: */ 0 },
  109526. #endif
  109527. #if defined(SQLITE_INTROSPECTION_PRAGMAS)
  109528. {/* zName: */ "pragma_list",
  109529. /* ePragTyp: */ PragTyp_PRAGMA_LIST,
  109530. /* ePragFlg: */ PragFlg_Result0,
  109531. /* ColNames: */ 31, 1,
  109532. /* iArg: */ 0 },
  109533. #endif
  109534. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109535. {/* zName: */ "query_only",
  109536. /* ePragTyp: */ PragTyp_FLAG,
  109537. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109538. /* ColNames: */ 0, 0,
  109539. /* iArg: */ SQLITE_QueryOnly },
  109540. #endif
  109541. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  109542. {/* zName: */ "quick_check",
  109543. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  109544. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  109545. /* ColNames: */ 0, 0,
  109546. /* iArg: */ 0 },
  109547. #endif
  109548. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109549. {/* zName: */ "read_uncommitted",
  109550. /* ePragTyp: */ PragTyp_FLAG,
  109551. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109552. /* ColNames: */ 0, 0,
  109553. /* iArg: */ SQLITE_ReadUncommit },
  109554. {/* zName: */ "recursive_triggers",
  109555. /* ePragTyp: */ PragTyp_FLAG,
  109556. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109557. /* ColNames: */ 0, 0,
  109558. /* iArg: */ SQLITE_RecTriggers },
  109559. #endif
  109560. #if defined(SQLITE_HAS_CODEC)
  109561. {/* zName: */ "rekey",
  109562. /* ePragTyp: */ PragTyp_REKEY,
  109563. /* ePragFlg: */ 0,
  109564. /* ColNames: */ 0, 0,
  109565. /* iArg: */ 0 },
  109566. #endif
  109567. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109568. {/* zName: */ "reverse_unordered_selects",
  109569. /* ePragTyp: */ PragTyp_FLAG,
  109570. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109571. /* ColNames: */ 0, 0,
  109572. /* iArg: */ SQLITE_ReverseOrder },
  109573. #endif
  109574. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  109575. {/* zName: */ "schema_version",
  109576. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  109577. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  109578. /* ColNames: */ 0, 0,
  109579. /* iArg: */ BTREE_SCHEMA_VERSION },
  109580. #endif
  109581. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  109582. {/* zName: */ "secure_delete",
  109583. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  109584. /* ePragFlg: */ PragFlg_Result0,
  109585. /* ColNames: */ 0, 0,
  109586. /* iArg: */ 0 },
  109587. #endif
  109588. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109589. {/* zName: */ "short_column_names",
  109590. /* ePragTyp: */ PragTyp_FLAG,
  109591. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109592. /* ColNames: */ 0, 0,
  109593. /* iArg: */ SQLITE_ShortColNames },
  109594. #endif
  109595. {/* zName: */ "shrink_memory",
  109596. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  109597. /* ePragFlg: */ PragFlg_NoColumns,
  109598. /* ColNames: */ 0, 0,
  109599. /* iArg: */ 0 },
  109600. {/* zName: */ "soft_heap_limit",
  109601. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  109602. /* ePragFlg: */ PragFlg_Result0,
  109603. /* ColNames: */ 0, 0,
  109604. /* iArg: */ 0 },
  109605. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109606. #if defined(SQLITE_DEBUG)
  109607. {/* zName: */ "sql_trace",
  109608. /* ePragTyp: */ PragTyp_FLAG,
  109609. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109610. /* ColNames: */ 0, 0,
  109611. /* iArg: */ SQLITE_SqlTrace },
  109612. #endif
  109613. #endif
  109614. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
  109615. {/* zName: */ "stats",
  109616. /* ePragTyp: */ PragTyp_STATS,
  109617. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  109618. /* ColNames: */ 7, 5,
  109619. /* iArg: */ 0 },
  109620. #endif
  109621. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  109622. {/* zName: */ "synchronous",
  109623. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  109624. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  109625. /* ColNames: */ 0, 0,
  109626. /* iArg: */ 0 },
  109627. #endif
  109628. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  109629. {/* zName: */ "table_info",
  109630. /* ePragTyp: */ PragTyp_TABLE_INFO,
  109631. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  109632. /* ColNames: */ 1, 6,
  109633. /* iArg: */ 0 },
  109634. #endif
  109635. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  109636. {/* zName: */ "temp_store",
  109637. /* ePragTyp: */ PragTyp_TEMP_STORE,
  109638. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109639. /* ColNames: */ 0, 0,
  109640. /* iArg: */ 0 },
  109641. {/* zName: */ "temp_store_directory",
  109642. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  109643. /* ePragFlg: */ PragFlg_NoColumns1,
  109644. /* ColNames: */ 0, 0,
  109645. /* iArg: */ 0 },
  109646. #endif
  109647. {/* zName: */ "threads",
  109648. /* ePragTyp: */ PragTyp_THREADS,
  109649. /* ePragFlg: */ PragFlg_Result0,
  109650. /* ColNames: */ 0, 0,
  109651. /* iArg: */ 0 },
  109652. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  109653. {/* zName: */ "user_version",
  109654. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  109655. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  109656. /* ColNames: */ 0, 0,
  109657. /* iArg: */ BTREE_USER_VERSION },
  109658. #endif
  109659. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109660. #if defined(SQLITE_DEBUG)
  109661. {/* zName: */ "vdbe_addoptrace",
  109662. /* ePragTyp: */ PragTyp_FLAG,
  109663. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109664. /* ColNames: */ 0, 0,
  109665. /* iArg: */ SQLITE_VdbeAddopTrace },
  109666. {/* zName: */ "vdbe_debug",
  109667. /* ePragTyp: */ PragTyp_FLAG,
  109668. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109669. /* ColNames: */ 0, 0,
  109670. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  109671. {/* zName: */ "vdbe_eqp",
  109672. /* ePragTyp: */ PragTyp_FLAG,
  109673. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109674. /* ColNames: */ 0, 0,
  109675. /* iArg: */ SQLITE_VdbeEQP },
  109676. {/* zName: */ "vdbe_listing",
  109677. /* ePragTyp: */ PragTyp_FLAG,
  109678. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109679. /* ColNames: */ 0, 0,
  109680. /* iArg: */ SQLITE_VdbeListing },
  109681. {/* zName: */ "vdbe_trace",
  109682. /* ePragTyp: */ PragTyp_FLAG,
  109683. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109684. /* ColNames: */ 0, 0,
  109685. /* iArg: */ SQLITE_VdbeTrace },
  109686. #endif
  109687. #endif
  109688. #if !defined(SQLITE_OMIT_WAL)
  109689. {/* zName: */ "wal_autocheckpoint",
  109690. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  109691. /* ePragFlg: */ 0,
  109692. /* ColNames: */ 0, 0,
  109693. /* iArg: */ 0 },
  109694. {/* zName: */ "wal_checkpoint",
  109695. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  109696. /* ePragFlg: */ PragFlg_NeedSchema,
  109697. /* ColNames: */ 46, 3,
  109698. /* iArg: */ 0 },
  109699. #endif
  109700. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  109701. {/* zName: */ "writable_schema",
  109702. /* ePragTyp: */ PragTyp_FLAG,
  109703. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  109704. /* ColNames: */ 0, 0,
  109705. /* iArg: */ SQLITE_WriteSchema },
  109706. #endif
  109707. };
  109708. /* Number of pragmas: 60 on by default, 77 total. */
  109709. /************** End of pragma.h **********************************************/
  109710. /************** Continuing where we left off in pragma.c *********************/
  109711. /*
  109712. ** Interpret the given string as a safety level. Return 0 for OFF,
  109713. ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
  109714. ** unrecognized string argument. The FULL and EXTRA option is disallowed
  109715. ** if the omitFull parameter it 1.
  109716. **
  109717. ** Note that the values returned are one less that the values that
  109718. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  109719. ** to support legacy SQL code. The safety level used to be boolean
  109720. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  109721. */
  109722. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  109723. /* 123456789 123456789 123 */
  109724. static const char zText[] = "onoffalseyestruextrafull";
  109725. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
  109726. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
  109727. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
  109728. /* on no off false yes true extra full */
  109729. int i, n;
  109730. if( sqlite3Isdigit(*z) ){
  109731. return (u8)sqlite3Atoi(z);
  109732. }
  109733. n = sqlite3Strlen30(z);
  109734. for(i=0; i<ArraySize(iLength); i++){
  109735. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
  109736. && (!omitFull || iValue[i]<=1)
  109737. ){
  109738. return iValue[i];
  109739. }
  109740. }
  109741. return dflt;
  109742. }
  109743. /*
  109744. ** Interpret the given string as a boolean value.
  109745. */
  109746. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  109747. return getSafetyLevel(z,1,dflt)!=0;
  109748. }
  109749. /* The sqlite3GetBoolean() function is used by other modules but the
  109750. ** remainder of this file is specific to PRAGMA processing. So omit
  109751. ** the rest of the file if PRAGMAs are omitted from the build.
  109752. */
  109753. #if !defined(SQLITE_OMIT_PRAGMA)
  109754. /*
  109755. ** Interpret the given string as a locking mode value.
  109756. */
  109757. static int getLockingMode(const char *z){
  109758. if( z ){
  109759. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  109760. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  109761. }
  109762. return PAGER_LOCKINGMODE_QUERY;
  109763. }
  109764. #ifndef SQLITE_OMIT_AUTOVACUUM
  109765. /*
  109766. ** Interpret the given string as an auto-vacuum mode value.
  109767. **
  109768. ** The following strings, "none", "full" and "incremental" are
  109769. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  109770. */
  109771. static int getAutoVacuum(const char *z){
  109772. int i;
  109773. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  109774. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  109775. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  109776. i = sqlite3Atoi(z);
  109777. return (u8)((i>=0&&i<=2)?i:0);
  109778. }
  109779. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  109780. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  109781. /*
  109782. ** Interpret the given string as a temp db location. Return 1 for file
  109783. ** backed temporary databases, 2 for the Red-Black tree in memory database
  109784. ** and 0 to use the compile-time default.
  109785. */
  109786. static int getTempStore(const char *z){
  109787. if( z[0]>='0' && z[0]<='2' ){
  109788. return z[0] - '0';
  109789. }else if( sqlite3StrICmp(z, "file")==0 ){
  109790. return 1;
  109791. }else if( sqlite3StrICmp(z, "memory")==0 ){
  109792. return 2;
  109793. }else{
  109794. return 0;
  109795. }
  109796. }
  109797. #endif /* SQLITE_PAGER_PRAGMAS */
  109798. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  109799. /*
  109800. ** Invalidate temp storage, either when the temp storage is changed
  109801. ** from default, or when 'file' and the temp_store_directory has changed
  109802. */
  109803. static int invalidateTempStorage(Parse *pParse){
  109804. sqlite3 *db = pParse->db;
  109805. if( db->aDb[1].pBt!=0 ){
  109806. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  109807. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  109808. "from within a transaction");
  109809. return SQLITE_ERROR;
  109810. }
  109811. sqlite3BtreeClose(db->aDb[1].pBt);
  109812. db->aDb[1].pBt = 0;
  109813. sqlite3ResetAllSchemasOfConnection(db);
  109814. }
  109815. return SQLITE_OK;
  109816. }
  109817. #endif /* SQLITE_PAGER_PRAGMAS */
  109818. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  109819. /*
  109820. ** If the TEMP database is open, close it and mark the database schema
  109821. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  109822. ** or DEFAULT_TEMP_STORE pragmas.
  109823. */
  109824. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  109825. int ts = getTempStore(zStorageType);
  109826. sqlite3 *db = pParse->db;
  109827. if( db->temp_store==ts ) return SQLITE_OK;
  109828. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  109829. return SQLITE_ERROR;
  109830. }
  109831. db->temp_store = (u8)ts;
  109832. return SQLITE_OK;
  109833. }
  109834. #endif /* SQLITE_PAGER_PRAGMAS */
  109835. /*
  109836. ** Set result column names for a pragma.
  109837. */
  109838. static void setPragmaResultColumnNames(
  109839. Vdbe *v, /* The query under construction */
  109840. const PragmaName *pPragma /* The pragma */
  109841. ){
  109842. u8 n = pPragma->nPragCName;
  109843. sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
  109844. if( n==0 ){
  109845. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
  109846. }else{
  109847. int i, j;
  109848. for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
  109849. sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
  109850. }
  109851. }
  109852. }
  109853. /*
  109854. ** Generate code to return a single integer value.
  109855. */
  109856. static void returnSingleInt(Vdbe *v, i64 value){
  109857. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  109858. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  109859. }
  109860. /*
  109861. ** Generate code to return a single text value.
  109862. */
  109863. static void returnSingleText(
  109864. Vdbe *v, /* Prepared statement under construction */
  109865. const char *zValue /* Value to be returned */
  109866. ){
  109867. if( zValue ){
  109868. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  109869. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  109870. }
  109871. }
  109872. /*
  109873. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  109874. ** set these values for all pagers.
  109875. */
  109876. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  109877. static void setAllPagerFlags(sqlite3 *db){
  109878. if( db->autoCommit ){
  109879. Db *pDb = db->aDb;
  109880. int n = db->nDb;
  109881. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  109882. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  109883. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  109884. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  109885. == PAGER_FLAGS_MASK );
  109886. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  109887. while( (n--) > 0 ){
  109888. if( pDb->pBt ){
  109889. sqlite3BtreeSetPagerFlags(pDb->pBt,
  109890. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  109891. }
  109892. pDb++;
  109893. }
  109894. }
  109895. }
  109896. #else
  109897. # define setAllPagerFlags(X) /* no-op */
  109898. #endif
  109899. /*
  109900. ** Return a human-readable name for a constraint resolution action.
  109901. */
  109902. #ifndef SQLITE_OMIT_FOREIGN_KEY
  109903. static const char *actionName(u8 action){
  109904. const char *zName;
  109905. switch( action ){
  109906. case OE_SetNull: zName = "SET NULL"; break;
  109907. case OE_SetDflt: zName = "SET DEFAULT"; break;
  109908. case OE_Cascade: zName = "CASCADE"; break;
  109909. case OE_Restrict: zName = "RESTRICT"; break;
  109910. default: zName = "NO ACTION";
  109911. assert( action==OE_None ); break;
  109912. }
  109913. return zName;
  109914. }
  109915. #endif
  109916. /*
  109917. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  109918. ** defined in pager.h. This function returns the associated lowercase
  109919. ** journal-mode name.
  109920. */
  109921. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  109922. static char * const azModeName[] = {
  109923. "delete", "persist", "off", "truncate", "memory"
  109924. #ifndef SQLITE_OMIT_WAL
  109925. , "wal"
  109926. #endif
  109927. };
  109928. assert( PAGER_JOURNALMODE_DELETE==0 );
  109929. assert( PAGER_JOURNALMODE_PERSIST==1 );
  109930. assert( PAGER_JOURNALMODE_OFF==2 );
  109931. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  109932. assert( PAGER_JOURNALMODE_MEMORY==4 );
  109933. assert( PAGER_JOURNALMODE_WAL==5 );
  109934. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  109935. if( eMode==ArraySize(azModeName) ) return 0;
  109936. return azModeName[eMode];
  109937. }
  109938. /*
  109939. ** Locate a pragma in the aPragmaName[] array.
  109940. */
  109941. static const PragmaName *pragmaLocate(const char *zName){
  109942. int upr, lwr, mid = 0, rc;
  109943. lwr = 0;
  109944. upr = ArraySize(aPragmaName)-1;
  109945. while( lwr<=upr ){
  109946. mid = (lwr+upr)/2;
  109947. rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
  109948. if( rc==0 ) break;
  109949. if( rc<0 ){
  109950. upr = mid - 1;
  109951. }else{
  109952. lwr = mid + 1;
  109953. }
  109954. }
  109955. return lwr>upr ? 0 : &aPragmaName[mid];
  109956. }
  109957. /*
  109958. ** Helper subroutine for PRAGMA integrity_check:
  109959. **
  109960. ** Generate code to output a single-column result row with a value of the
  109961. ** string held in register 3. Decrement the result count in register 1
  109962. ** and halt if the maximum number of result rows have been issued.
  109963. */
  109964. static int integrityCheckResultRow(Vdbe *v){
  109965. int addr;
  109966. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  109967. addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
  109968. VdbeCoverage(v);
  109969. sqlite3VdbeAddOp0(v, OP_Halt);
  109970. return addr;
  109971. }
  109972. /*
  109973. ** Process a pragma statement.
  109974. **
  109975. ** Pragmas are of this form:
  109976. **
  109977. ** PRAGMA [schema.]id [= value]
  109978. **
  109979. ** The identifier might also be a string. The value is a string, and
  109980. ** identifier, or a number. If minusFlag is true, then the value is
  109981. ** a number that was preceded by a minus sign.
  109982. **
  109983. ** If the left side is "database.id" then pId1 is the database name
  109984. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  109985. ** id and pId2 is any empty string.
  109986. */
  109987. SQLITE_PRIVATE void sqlite3Pragma(
  109988. Parse *pParse,
  109989. Token *pId1, /* First part of [schema.]id field */
  109990. Token *pId2, /* Second part of [schema.]id field, or NULL */
  109991. Token *pValue, /* Token for <value>, or NULL */
  109992. int minusFlag /* True if a '-' sign preceded <value> */
  109993. ){
  109994. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  109995. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  109996. const char *zDb = 0; /* The database name */
  109997. Token *pId; /* Pointer to <id> token */
  109998. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  109999. int iDb; /* Database index for <database> */
  110000. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  110001. sqlite3 *db = pParse->db; /* The database connection */
  110002. Db *pDb; /* The specific database being pragmaed */
  110003. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  110004. const PragmaName *pPragma; /* The pragma */
  110005. if( v==0 ) return;
  110006. sqlite3VdbeRunOnlyOnce(v);
  110007. pParse->nMem = 2;
  110008. /* Interpret the [schema.] part of the pragma statement. iDb is the
  110009. ** index of the database this pragma is being applied to in db.aDb[]. */
  110010. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  110011. if( iDb<0 ) return;
  110012. pDb = &db->aDb[iDb];
  110013. /* If the temp database has been explicitly named as part of the
  110014. ** pragma, make sure it is open.
  110015. */
  110016. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  110017. return;
  110018. }
  110019. zLeft = sqlite3NameFromToken(db, pId);
  110020. if( !zLeft ) return;
  110021. if( minusFlag ){
  110022. zRight = sqlite3MPrintf(db, "-%T", pValue);
  110023. }else{
  110024. zRight = sqlite3NameFromToken(db, pValue);
  110025. }
  110026. assert( pId2 );
  110027. zDb = pId2->n>0 ? pDb->zDbSName : 0;
  110028. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  110029. goto pragma_out;
  110030. }
  110031. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  110032. ** connection. If it returns SQLITE_OK, then assume that the VFS
  110033. ** handled the pragma and generate a no-op prepared statement.
  110034. **
  110035. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  110036. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  110037. ** object corresponding to the database file to which the pragma
  110038. ** statement refers.
  110039. **
  110040. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  110041. ** file control is an array of pointers to strings (char**) in which the
  110042. ** second element of the array is the name of the pragma and the third
  110043. ** element is the argument to the pragma or NULL if the pragma has no
  110044. ** argument.
  110045. */
  110046. aFcntl[0] = 0;
  110047. aFcntl[1] = zLeft;
  110048. aFcntl[2] = zRight;
  110049. aFcntl[3] = 0;
  110050. db->busyHandler.nBusy = 0;
  110051. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  110052. if( rc==SQLITE_OK ){
  110053. sqlite3VdbeSetNumCols(v, 1);
  110054. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
  110055. returnSingleText(v, aFcntl[0]);
  110056. sqlite3_free(aFcntl[0]);
  110057. goto pragma_out;
  110058. }
  110059. if( rc!=SQLITE_NOTFOUND ){
  110060. if( aFcntl[0] ){
  110061. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  110062. sqlite3_free(aFcntl[0]);
  110063. }
  110064. pParse->nErr++;
  110065. pParse->rc = rc;
  110066. goto pragma_out;
  110067. }
  110068. /* Locate the pragma in the lookup table */
  110069. pPragma = pragmaLocate(zLeft);
  110070. if( pPragma==0 ) goto pragma_out;
  110071. /* Make sure the database schema is loaded if the pragma requires that */
  110072. if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
  110073. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  110074. }
  110075. /* Register the result column names for pragmas that return results */
  110076. if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
  110077. && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
  110078. ){
  110079. setPragmaResultColumnNames(v, pPragma);
  110080. }
  110081. /* Jump to the appropriate pragma handler */
  110082. switch( pPragma->ePragTyp ){
  110083. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  110084. /*
  110085. ** PRAGMA [schema.]default_cache_size
  110086. ** PRAGMA [schema.]default_cache_size=N
  110087. **
  110088. ** The first form reports the current persistent setting for the
  110089. ** page cache size. The value returned is the maximum number of
  110090. ** pages in the page cache. The second form sets both the current
  110091. ** page cache size value and the persistent page cache size value
  110092. ** stored in the database file.
  110093. **
  110094. ** Older versions of SQLite would set the default cache size to a
  110095. ** negative number to indicate synchronous=OFF. These days, synchronous
  110096. ** is always on by default regardless of the sign of the default cache
  110097. ** size. But continue to take the absolute value of the default cache
  110098. ** size of historical compatibility.
  110099. */
  110100. case PragTyp_DEFAULT_CACHE_SIZE: {
  110101. static const int iLn = VDBE_OFFSET_LINENO(2);
  110102. static const VdbeOpList getCacheSize[] = {
  110103. { OP_Transaction, 0, 0, 0}, /* 0 */
  110104. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  110105. { OP_IfPos, 1, 8, 0},
  110106. { OP_Integer, 0, 2, 0},
  110107. { OP_Subtract, 1, 2, 1},
  110108. { OP_IfPos, 1, 8, 0},
  110109. { OP_Integer, 0, 1, 0}, /* 6 */
  110110. { OP_Noop, 0, 0, 0},
  110111. { OP_ResultRow, 1, 1, 0},
  110112. };
  110113. VdbeOp *aOp;
  110114. sqlite3VdbeUsesBtree(v, iDb);
  110115. if( !zRight ){
  110116. pParse->nMem += 2;
  110117. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
  110118. aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
  110119. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  110120. aOp[0].p1 = iDb;
  110121. aOp[1].p1 = iDb;
  110122. aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
  110123. }else{
  110124. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  110125. sqlite3BeginWriteOperation(pParse, 0, iDb);
  110126. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
  110127. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  110128. pDb->pSchema->cache_size = size;
  110129. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  110130. }
  110131. break;
  110132. }
  110133. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  110134. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  110135. /*
  110136. ** PRAGMA [schema.]page_size
  110137. ** PRAGMA [schema.]page_size=N
  110138. **
  110139. ** The first form reports the current setting for the
  110140. ** database page size in bytes. The second form sets the
  110141. ** database page size value. The value can only be set if
  110142. ** the database has not yet been created.
  110143. */
  110144. case PragTyp_PAGE_SIZE: {
  110145. Btree *pBt = pDb->pBt;
  110146. assert( pBt!=0 );
  110147. if( !zRight ){
  110148. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  110149. returnSingleInt(v, size);
  110150. }else{
  110151. /* Malloc may fail when setting the page-size, as there is an internal
  110152. ** buffer that the pager module resizes using sqlite3_realloc().
  110153. */
  110154. db->nextPagesize = sqlite3Atoi(zRight);
  110155. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  110156. sqlite3OomFault(db);
  110157. }
  110158. }
  110159. break;
  110160. }
  110161. /*
  110162. ** PRAGMA [schema.]secure_delete
  110163. ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
  110164. **
  110165. ** The first form reports the current setting for the
  110166. ** secure_delete flag. The second form changes the secure_delete
  110167. ** flag setting and reports the new value.
  110168. */
  110169. case PragTyp_SECURE_DELETE: {
  110170. Btree *pBt = pDb->pBt;
  110171. int b = -1;
  110172. assert( pBt!=0 );
  110173. if( zRight ){
  110174. if( sqlite3_stricmp(zRight, "fast")==0 ){
  110175. b = 2;
  110176. }else{
  110177. b = sqlite3GetBoolean(zRight, 0);
  110178. }
  110179. }
  110180. if( pId2->n==0 && b>=0 ){
  110181. int ii;
  110182. for(ii=0; ii<db->nDb; ii++){
  110183. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  110184. }
  110185. }
  110186. b = sqlite3BtreeSecureDelete(pBt, b);
  110187. returnSingleInt(v, b);
  110188. break;
  110189. }
  110190. /*
  110191. ** PRAGMA [schema.]max_page_count
  110192. ** PRAGMA [schema.]max_page_count=N
  110193. **
  110194. ** The first form reports the current setting for the
  110195. ** maximum number of pages in the database file. The
  110196. ** second form attempts to change this setting. Both
  110197. ** forms return the current setting.
  110198. **
  110199. ** The absolute value of N is used. This is undocumented and might
  110200. ** change. The only purpose is to provide an easy way to test
  110201. ** the sqlite3AbsInt32() function.
  110202. **
  110203. ** PRAGMA [schema.]page_count
  110204. **
  110205. ** Return the number of pages in the specified database.
  110206. */
  110207. case PragTyp_PAGE_COUNT: {
  110208. int iReg;
  110209. sqlite3CodeVerifySchema(pParse, iDb);
  110210. iReg = ++pParse->nMem;
  110211. if( sqlite3Tolower(zLeft[0])=='p' ){
  110212. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  110213. }else{
  110214. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  110215. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  110216. }
  110217. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  110218. break;
  110219. }
  110220. /*
  110221. ** PRAGMA [schema.]locking_mode
  110222. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  110223. */
  110224. case PragTyp_LOCKING_MODE: {
  110225. const char *zRet = "normal";
  110226. int eMode = getLockingMode(zRight);
  110227. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  110228. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  110229. ** the current default locking mode (which may be different to
  110230. ** the locking-mode of the main database).
  110231. */
  110232. eMode = db->dfltLockMode;
  110233. }else{
  110234. Pager *pPager;
  110235. if( pId2->n==0 ){
  110236. /* This indicates that no database name was specified as part
  110237. ** of the PRAGMA command. In this case the locking-mode must be
  110238. ** set on all attached databases, as well as the main db file.
  110239. **
  110240. ** Also, the sqlite3.dfltLockMode variable is set so that
  110241. ** any subsequently attached databases also use the specified
  110242. ** locking mode.
  110243. */
  110244. int ii;
  110245. assert(pDb==&db->aDb[0]);
  110246. for(ii=2; ii<db->nDb; ii++){
  110247. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  110248. sqlite3PagerLockingMode(pPager, eMode);
  110249. }
  110250. db->dfltLockMode = (u8)eMode;
  110251. }
  110252. pPager = sqlite3BtreePager(pDb->pBt);
  110253. eMode = sqlite3PagerLockingMode(pPager, eMode);
  110254. }
  110255. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  110256. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  110257. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  110258. zRet = "exclusive";
  110259. }
  110260. returnSingleText(v, zRet);
  110261. break;
  110262. }
  110263. /*
  110264. ** PRAGMA [schema.]journal_mode
  110265. ** PRAGMA [schema.]journal_mode =
  110266. ** (delete|persist|off|truncate|memory|wal|off)
  110267. */
  110268. case PragTyp_JOURNAL_MODE: {
  110269. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  110270. int ii; /* Loop counter */
  110271. if( zRight==0 ){
  110272. /* If there is no "=MODE" part of the pragma, do a query for the
  110273. ** current mode */
  110274. eMode = PAGER_JOURNALMODE_QUERY;
  110275. }else{
  110276. const char *zMode;
  110277. int n = sqlite3Strlen30(zRight);
  110278. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  110279. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  110280. }
  110281. if( !zMode ){
  110282. /* If the "=MODE" part does not match any known journal mode,
  110283. ** then do a query */
  110284. eMode = PAGER_JOURNALMODE_QUERY;
  110285. }
  110286. }
  110287. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  110288. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  110289. iDb = 0;
  110290. pId2->n = 1;
  110291. }
  110292. for(ii=db->nDb-1; ii>=0; ii--){
  110293. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  110294. sqlite3VdbeUsesBtree(v, ii);
  110295. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  110296. }
  110297. }
  110298. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  110299. break;
  110300. }
  110301. /*
  110302. ** PRAGMA [schema.]journal_size_limit
  110303. ** PRAGMA [schema.]journal_size_limit=N
  110304. **
  110305. ** Get or set the size limit on rollback journal files.
  110306. */
  110307. case PragTyp_JOURNAL_SIZE_LIMIT: {
  110308. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  110309. i64 iLimit = -2;
  110310. if( zRight ){
  110311. sqlite3DecOrHexToI64(zRight, &iLimit);
  110312. if( iLimit<-1 ) iLimit = -1;
  110313. }
  110314. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  110315. returnSingleInt(v, iLimit);
  110316. break;
  110317. }
  110318. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  110319. /*
  110320. ** PRAGMA [schema.]auto_vacuum
  110321. ** PRAGMA [schema.]auto_vacuum=N
  110322. **
  110323. ** Get or set the value of the database 'auto-vacuum' parameter.
  110324. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  110325. */
  110326. #ifndef SQLITE_OMIT_AUTOVACUUM
  110327. case PragTyp_AUTO_VACUUM: {
  110328. Btree *pBt = pDb->pBt;
  110329. assert( pBt!=0 );
  110330. if( !zRight ){
  110331. returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
  110332. }else{
  110333. int eAuto = getAutoVacuum(zRight);
  110334. assert( eAuto>=0 && eAuto<=2 );
  110335. db->nextAutovac = (u8)eAuto;
  110336. /* Call SetAutoVacuum() to set initialize the internal auto and
  110337. ** incr-vacuum flags. This is required in case this connection
  110338. ** creates the database file. It is important that it is created
  110339. ** as an auto-vacuum capable db.
  110340. */
  110341. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  110342. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  110343. /* When setting the auto_vacuum mode to either "full" or
  110344. ** "incremental", write the value of meta[6] in the database
  110345. ** file. Before writing to meta[6], check that meta[3] indicates
  110346. ** that this really is an auto-vacuum capable database.
  110347. */
  110348. static const int iLn = VDBE_OFFSET_LINENO(2);
  110349. static const VdbeOpList setMeta6[] = {
  110350. { OP_Transaction, 0, 1, 0}, /* 0 */
  110351. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  110352. { OP_If, 1, 0, 0}, /* 2 */
  110353. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  110354. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
  110355. };
  110356. VdbeOp *aOp;
  110357. int iAddr = sqlite3VdbeCurrentAddr(v);
  110358. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
  110359. aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  110360. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  110361. aOp[0].p1 = iDb;
  110362. aOp[1].p1 = iDb;
  110363. aOp[2].p2 = iAddr+4;
  110364. aOp[4].p1 = iDb;
  110365. aOp[4].p3 = eAuto - 1;
  110366. sqlite3VdbeUsesBtree(v, iDb);
  110367. }
  110368. }
  110369. break;
  110370. }
  110371. #endif
  110372. /*
  110373. ** PRAGMA [schema.]incremental_vacuum(N)
  110374. **
  110375. ** Do N steps of incremental vacuuming on a database.
  110376. */
  110377. #ifndef SQLITE_OMIT_AUTOVACUUM
  110378. case PragTyp_INCREMENTAL_VACUUM: {
  110379. int iLimit, addr;
  110380. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  110381. iLimit = 0x7fffffff;
  110382. }
  110383. sqlite3BeginWriteOperation(pParse, 0, iDb);
  110384. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  110385. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  110386. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  110387. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  110388. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  110389. sqlite3VdbeJumpHere(v, addr);
  110390. break;
  110391. }
  110392. #endif
  110393. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  110394. /*
  110395. ** PRAGMA [schema.]cache_size
  110396. ** PRAGMA [schema.]cache_size=N
  110397. **
  110398. ** The first form reports the current local setting for the
  110399. ** page cache size. The second form sets the local
  110400. ** page cache size value. If N is positive then that is the
  110401. ** number of pages in the cache. If N is negative, then the
  110402. ** number of pages is adjusted so that the cache uses -N kibibytes
  110403. ** of memory.
  110404. */
  110405. case PragTyp_CACHE_SIZE: {
  110406. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  110407. if( !zRight ){
  110408. returnSingleInt(v, pDb->pSchema->cache_size);
  110409. }else{
  110410. int size = sqlite3Atoi(zRight);
  110411. pDb->pSchema->cache_size = size;
  110412. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  110413. }
  110414. break;
  110415. }
  110416. /*
  110417. ** PRAGMA [schema.]cache_spill
  110418. ** PRAGMA cache_spill=BOOLEAN
  110419. ** PRAGMA [schema.]cache_spill=N
  110420. **
  110421. ** The first form reports the current local setting for the
  110422. ** page cache spill size. The second form turns cache spill on
  110423. ** or off. When turnning cache spill on, the size is set to the
  110424. ** current cache_size. The third form sets a spill size that
  110425. ** may be different form the cache size.
  110426. ** If N is positive then that is the
  110427. ** number of pages in the cache. If N is negative, then the
  110428. ** number of pages is adjusted so that the cache uses -N kibibytes
  110429. ** of memory.
  110430. **
  110431. ** If the number of cache_spill pages is less then the number of
  110432. ** cache_size pages, no spilling occurs until the page count exceeds
  110433. ** the number of cache_size pages.
  110434. **
  110435. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  110436. ** not just the schema specified.
  110437. */
  110438. case PragTyp_CACHE_SPILL: {
  110439. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  110440. if( !zRight ){
  110441. returnSingleInt(v,
  110442. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  110443. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  110444. }else{
  110445. int size = 1;
  110446. if( sqlite3GetInt32(zRight, &size) ){
  110447. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  110448. }
  110449. if( sqlite3GetBoolean(zRight, size!=0) ){
  110450. db->flags |= SQLITE_CacheSpill;
  110451. }else{
  110452. db->flags &= ~SQLITE_CacheSpill;
  110453. }
  110454. setAllPagerFlags(db);
  110455. }
  110456. break;
  110457. }
  110458. /*
  110459. ** PRAGMA [schema.]mmap_size(N)
  110460. **
  110461. ** Used to set mapping size limit. The mapping size limit is
  110462. ** used to limit the aggregate size of all memory mapped regions of the
  110463. ** database file. If this parameter is set to zero, then memory mapping
  110464. ** is not used at all. If N is negative, then the default memory map
  110465. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  110466. ** The parameter N is measured in bytes.
  110467. **
  110468. ** This value is advisory. The underlying VFS is free to memory map
  110469. ** as little or as much as it wants. Except, if N is set to 0 then the
  110470. ** upper layers will never invoke the xFetch interfaces to the VFS.
  110471. */
  110472. case PragTyp_MMAP_SIZE: {
  110473. sqlite3_int64 sz;
  110474. #if SQLITE_MAX_MMAP_SIZE>0
  110475. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  110476. if( zRight ){
  110477. int ii;
  110478. sqlite3DecOrHexToI64(zRight, &sz);
  110479. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  110480. if( pId2->n==0 ) db->szMmap = sz;
  110481. for(ii=db->nDb-1; ii>=0; ii--){
  110482. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  110483. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  110484. }
  110485. }
  110486. }
  110487. sz = -1;
  110488. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  110489. #else
  110490. sz = 0;
  110491. rc = SQLITE_OK;
  110492. #endif
  110493. if( rc==SQLITE_OK ){
  110494. returnSingleInt(v, sz);
  110495. }else if( rc!=SQLITE_NOTFOUND ){
  110496. pParse->nErr++;
  110497. pParse->rc = rc;
  110498. }
  110499. break;
  110500. }
  110501. /*
  110502. ** PRAGMA temp_store
  110503. ** PRAGMA temp_store = "default"|"memory"|"file"
  110504. **
  110505. ** Return or set the local value of the temp_store flag. Changing
  110506. ** the local value does not make changes to the disk file and the default
  110507. ** value will be restored the next time the database is opened.
  110508. **
  110509. ** Note that it is possible for the library compile-time options to
  110510. ** override this setting
  110511. */
  110512. case PragTyp_TEMP_STORE: {
  110513. if( !zRight ){
  110514. returnSingleInt(v, db->temp_store);
  110515. }else{
  110516. changeTempStorage(pParse, zRight);
  110517. }
  110518. break;
  110519. }
  110520. /*
  110521. ** PRAGMA temp_store_directory
  110522. ** PRAGMA temp_store_directory = ""|"directory_name"
  110523. **
  110524. ** Return or set the local value of the temp_store_directory flag. Changing
  110525. ** the value sets a specific directory to be used for temporary files.
  110526. ** Setting to a null string reverts to the default temporary directory search.
  110527. ** If temporary directory is changed, then invalidateTempStorage.
  110528. **
  110529. */
  110530. case PragTyp_TEMP_STORE_DIRECTORY: {
  110531. if( !zRight ){
  110532. returnSingleText(v, sqlite3_temp_directory);
  110533. }else{
  110534. #ifndef SQLITE_OMIT_WSD
  110535. if( zRight[0] ){
  110536. int res;
  110537. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  110538. if( rc!=SQLITE_OK || res==0 ){
  110539. sqlite3ErrorMsg(pParse, "not a writable directory");
  110540. goto pragma_out;
  110541. }
  110542. }
  110543. if( SQLITE_TEMP_STORE==0
  110544. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  110545. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  110546. ){
  110547. invalidateTempStorage(pParse);
  110548. }
  110549. sqlite3_free(sqlite3_temp_directory);
  110550. if( zRight[0] ){
  110551. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  110552. }else{
  110553. sqlite3_temp_directory = 0;
  110554. }
  110555. #endif /* SQLITE_OMIT_WSD */
  110556. }
  110557. break;
  110558. }
  110559. #if SQLITE_OS_WIN
  110560. /*
  110561. ** PRAGMA data_store_directory
  110562. ** PRAGMA data_store_directory = ""|"directory_name"
  110563. **
  110564. ** Return or set the local value of the data_store_directory flag. Changing
  110565. ** the value sets a specific directory to be used for database files that
  110566. ** were specified with a relative pathname. Setting to a null string reverts
  110567. ** to the default database directory, which for database files specified with
  110568. ** a relative path will probably be based on the current directory for the
  110569. ** process. Database file specified with an absolute path are not impacted
  110570. ** by this setting, regardless of its value.
  110571. **
  110572. */
  110573. case PragTyp_DATA_STORE_DIRECTORY: {
  110574. if( !zRight ){
  110575. returnSingleText(v, sqlite3_data_directory);
  110576. }else{
  110577. #ifndef SQLITE_OMIT_WSD
  110578. if( zRight[0] ){
  110579. int res;
  110580. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  110581. if( rc!=SQLITE_OK || res==0 ){
  110582. sqlite3ErrorMsg(pParse, "not a writable directory");
  110583. goto pragma_out;
  110584. }
  110585. }
  110586. sqlite3_free(sqlite3_data_directory);
  110587. if( zRight[0] ){
  110588. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  110589. }else{
  110590. sqlite3_data_directory = 0;
  110591. }
  110592. #endif /* SQLITE_OMIT_WSD */
  110593. }
  110594. break;
  110595. }
  110596. #endif
  110597. #if SQLITE_ENABLE_LOCKING_STYLE
  110598. /*
  110599. ** PRAGMA [schema.]lock_proxy_file
  110600. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  110601. **
  110602. ** Return or set the value of the lock_proxy_file flag. Changing
  110603. ** the value sets a specific file to be used for database access locks.
  110604. **
  110605. */
  110606. case PragTyp_LOCK_PROXY_FILE: {
  110607. if( !zRight ){
  110608. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  110609. char *proxy_file_path = NULL;
  110610. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  110611. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  110612. &proxy_file_path);
  110613. returnSingleText(v, proxy_file_path);
  110614. }else{
  110615. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  110616. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  110617. int res;
  110618. if( zRight[0] ){
  110619. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  110620. zRight);
  110621. } else {
  110622. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  110623. NULL);
  110624. }
  110625. if( res!=SQLITE_OK ){
  110626. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  110627. goto pragma_out;
  110628. }
  110629. }
  110630. break;
  110631. }
  110632. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  110633. /*
  110634. ** PRAGMA [schema.]synchronous
  110635. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
  110636. **
  110637. ** Return or set the local value of the synchronous flag. Changing
  110638. ** the local value does not make changes to the disk file and the
  110639. ** default value will be restored the next time the database is
  110640. ** opened.
  110641. */
  110642. case PragTyp_SYNCHRONOUS: {
  110643. if( !zRight ){
  110644. returnSingleInt(v, pDb->safety_level-1);
  110645. }else{
  110646. if( !db->autoCommit ){
  110647. sqlite3ErrorMsg(pParse,
  110648. "Safety level may not be changed inside a transaction");
  110649. }else if( iDb!=1 ){
  110650. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  110651. if( iLevel==0 ) iLevel = 1;
  110652. pDb->safety_level = iLevel;
  110653. pDb->bSyncSet = 1;
  110654. setAllPagerFlags(db);
  110655. }
  110656. }
  110657. break;
  110658. }
  110659. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  110660. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  110661. case PragTyp_FLAG: {
  110662. if( zRight==0 ){
  110663. setPragmaResultColumnNames(v, pPragma);
  110664. returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
  110665. }else{
  110666. int mask = pPragma->iArg; /* Mask of bits to set or clear. */
  110667. if( db->autoCommit==0 ){
  110668. /* Foreign key support may not be enabled or disabled while not
  110669. ** in auto-commit mode. */
  110670. mask &= ~(SQLITE_ForeignKeys);
  110671. }
  110672. #if SQLITE_USER_AUTHENTICATION
  110673. if( db->auth.authLevel==UAUTH_User ){
  110674. /* Do not allow non-admin users to modify the schema arbitrarily */
  110675. mask &= ~(SQLITE_WriteSchema);
  110676. }
  110677. #endif
  110678. if( sqlite3GetBoolean(zRight, 0) ){
  110679. db->flags |= mask;
  110680. }else{
  110681. db->flags &= ~mask;
  110682. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  110683. }
  110684. /* Many of the flag-pragmas modify the code generated by the SQL
  110685. ** compiler (eg. count_changes). So add an opcode to expire all
  110686. ** compiled SQL statements after modifying a pragma value.
  110687. */
  110688. sqlite3VdbeAddOp0(v, OP_Expire);
  110689. setAllPagerFlags(db);
  110690. }
  110691. break;
  110692. }
  110693. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  110694. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  110695. /*
  110696. ** PRAGMA table_info(<table>)
  110697. **
  110698. ** Return a single row for each column of the named table. The columns of
  110699. ** the returned data set are:
  110700. **
  110701. ** cid: Column id (numbered from left to right, starting at 0)
  110702. ** name: Column name
  110703. ** type: Column declaration type.
  110704. ** notnull: True if 'NOT NULL' is part of column declaration
  110705. ** dflt_value: The default value for the column, if any.
  110706. ** pk: Non-zero for PK fields.
  110707. */
  110708. case PragTyp_TABLE_INFO: if( zRight ){
  110709. Table *pTab;
  110710. pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
  110711. if( pTab ){
  110712. int i, k;
  110713. int nHidden = 0;
  110714. Column *pCol;
  110715. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  110716. pParse->nMem = 6;
  110717. sqlite3CodeVerifySchema(pParse, iDb);
  110718. sqlite3ViewGetColumnNames(pParse, pTab);
  110719. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  110720. if( IsHiddenColumn(pCol) ){
  110721. nHidden++;
  110722. continue;
  110723. }
  110724. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  110725. k = 0;
  110726. }else if( pPk==0 ){
  110727. k = 1;
  110728. }else{
  110729. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  110730. }
  110731. assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
  110732. sqlite3VdbeMultiLoad(v, 1, "issisi",
  110733. i-nHidden,
  110734. pCol->zName,
  110735. sqlite3ColumnType(pCol,""),
  110736. pCol->notNull ? 1 : 0,
  110737. pCol->pDflt ? pCol->pDflt->u.zToken : 0,
  110738. k);
  110739. }
  110740. }
  110741. }
  110742. break;
  110743. #ifdef SQLITE_DEBUG
  110744. case PragTyp_STATS: {
  110745. Index *pIdx;
  110746. HashElem *i;
  110747. pParse->nMem = 5;
  110748. sqlite3CodeVerifySchema(pParse, iDb);
  110749. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  110750. Table *pTab = sqliteHashData(i);
  110751. sqlite3VdbeMultiLoad(v, 1, "ssiii",
  110752. pTab->zName,
  110753. 0,
  110754. pTab->szTabRow,
  110755. pTab->nRowLogEst,
  110756. pTab->tabFlags);
  110757. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  110758. sqlite3VdbeMultiLoad(v, 2, "siiiX",
  110759. pIdx->zName,
  110760. pIdx->szIdxRow,
  110761. pIdx->aiRowLogEst[0],
  110762. pIdx->hasStat1);
  110763. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  110764. }
  110765. }
  110766. }
  110767. break;
  110768. #endif
  110769. case PragTyp_INDEX_INFO: if( zRight ){
  110770. Index *pIdx;
  110771. Table *pTab;
  110772. pIdx = sqlite3FindIndex(db, zRight, zDb);
  110773. if( pIdx ){
  110774. int i;
  110775. int mx;
  110776. if( pPragma->iArg ){
  110777. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  110778. mx = pIdx->nColumn;
  110779. pParse->nMem = 6;
  110780. }else{
  110781. /* PRAGMA index_info (legacy version) */
  110782. mx = pIdx->nKeyCol;
  110783. pParse->nMem = 3;
  110784. }
  110785. pTab = pIdx->pTable;
  110786. sqlite3CodeVerifySchema(pParse, iDb);
  110787. assert( pParse->nMem<=pPragma->nPragCName );
  110788. for(i=0; i<mx; i++){
  110789. i16 cnum = pIdx->aiColumn[i];
  110790. sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
  110791. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  110792. if( pPragma->iArg ){
  110793. sqlite3VdbeMultiLoad(v, 4, "isiX",
  110794. pIdx->aSortOrder[i],
  110795. pIdx->azColl[i],
  110796. i<pIdx->nKeyCol);
  110797. }
  110798. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  110799. }
  110800. }
  110801. }
  110802. break;
  110803. case PragTyp_INDEX_LIST: if( zRight ){
  110804. Index *pIdx;
  110805. Table *pTab;
  110806. int i;
  110807. pTab = sqlite3FindTable(db, zRight, zDb);
  110808. if( pTab ){
  110809. pParse->nMem = 5;
  110810. sqlite3CodeVerifySchema(pParse, iDb);
  110811. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  110812. const char *azOrigin[] = { "c", "u", "pk" };
  110813. sqlite3VdbeMultiLoad(v, 1, "isisi",
  110814. i,
  110815. pIdx->zName,
  110816. IsUniqueIndex(pIdx),
  110817. azOrigin[pIdx->idxType],
  110818. pIdx->pPartIdxWhere!=0);
  110819. }
  110820. }
  110821. }
  110822. break;
  110823. case PragTyp_DATABASE_LIST: {
  110824. int i;
  110825. pParse->nMem = 3;
  110826. for(i=0; i<db->nDb; i++){
  110827. if( db->aDb[i].pBt==0 ) continue;
  110828. assert( db->aDb[i].zDbSName!=0 );
  110829. sqlite3VdbeMultiLoad(v, 1, "iss",
  110830. i,
  110831. db->aDb[i].zDbSName,
  110832. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  110833. }
  110834. }
  110835. break;
  110836. case PragTyp_COLLATION_LIST: {
  110837. int i = 0;
  110838. HashElem *p;
  110839. pParse->nMem = 2;
  110840. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  110841. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  110842. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  110843. }
  110844. }
  110845. break;
  110846. #ifdef SQLITE_INTROSPECTION_PRAGMAS
  110847. case PragTyp_FUNCTION_LIST: {
  110848. int i;
  110849. HashElem *j;
  110850. FuncDef *p;
  110851. pParse->nMem = 2;
  110852. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  110853. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
  110854. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1);
  110855. }
  110856. }
  110857. for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
  110858. p = (FuncDef*)sqliteHashData(j);
  110859. sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0);
  110860. }
  110861. }
  110862. break;
  110863. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110864. case PragTyp_MODULE_LIST: {
  110865. HashElem *j;
  110866. pParse->nMem = 1;
  110867. for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
  110868. Module *pMod = (Module*)sqliteHashData(j);
  110869. sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
  110870. }
  110871. }
  110872. break;
  110873. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  110874. case PragTyp_PRAGMA_LIST: {
  110875. int i;
  110876. for(i=0; i<ArraySize(aPragmaName); i++){
  110877. sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
  110878. }
  110879. }
  110880. break;
  110881. #endif /* SQLITE_INTROSPECTION_PRAGMAS */
  110882. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  110883. #ifndef SQLITE_OMIT_FOREIGN_KEY
  110884. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  110885. FKey *pFK;
  110886. Table *pTab;
  110887. pTab = sqlite3FindTable(db, zRight, zDb);
  110888. if( pTab ){
  110889. pFK = pTab->pFKey;
  110890. if( pFK ){
  110891. int i = 0;
  110892. pParse->nMem = 8;
  110893. sqlite3CodeVerifySchema(pParse, iDb);
  110894. while(pFK){
  110895. int j;
  110896. for(j=0; j<pFK->nCol; j++){
  110897. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  110898. i,
  110899. j,
  110900. pFK->zTo,
  110901. pTab->aCol[pFK->aCol[j].iFrom].zName,
  110902. pFK->aCol[j].zCol,
  110903. actionName(pFK->aAction[1]), /* ON UPDATE */
  110904. actionName(pFK->aAction[0]), /* ON DELETE */
  110905. "NONE");
  110906. }
  110907. ++i;
  110908. pFK = pFK->pNextFrom;
  110909. }
  110910. }
  110911. }
  110912. }
  110913. break;
  110914. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  110915. #ifndef SQLITE_OMIT_FOREIGN_KEY
  110916. #ifndef SQLITE_OMIT_TRIGGER
  110917. case PragTyp_FOREIGN_KEY_CHECK: {
  110918. FKey *pFK; /* A foreign key constraint */
  110919. Table *pTab; /* Child table contain "REFERENCES" keyword */
  110920. Table *pParent; /* Parent table that child points to */
  110921. Index *pIdx; /* Index in the parent table */
  110922. int i; /* Loop counter: Foreign key number for pTab */
  110923. int j; /* Loop counter: Field of the foreign key */
  110924. HashElem *k; /* Loop counter: Next table in schema */
  110925. int x; /* result variable */
  110926. int regResult; /* 3 registers to hold a result row */
  110927. int regKey; /* Register to hold key for checking the FK */
  110928. int regRow; /* Registers to hold a row from pTab */
  110929. int addrTop; /* Top of a loop checking foreign keys */
  110930. int addrOk; /* Jump here if the key is OK */
  110931. int *aiCols; /* child to parent column mapping */
  110932. regResult = pParse->nMem+1;
  110933. pParse->nMem += 4;
  110934. regKey = ++pParse->nMem;
  110935. regRow = ++pParse->nMem;
  110936. sqlite3CodeVerifySchema(pParse, iDb);
  110937. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  110938. while( k ){
  110939. if( zRight ){
  110940. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  110941. k = 0;
  110942. }else{
  110943. pTab = (Table*)sqliteHashData(k);
  110944. k = sqliteHashNext(k);
  110945. }
  110946. if( pTab==0 || pTab->pFKey==0 ) continue;
  110947. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  110948. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  110949. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  110950. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  110951. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  110952. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  110953. if( pParent==0 ) continue;
  110954. pIdx = 0;
  110955. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  110956. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  110957. if( x==0 ){
  110958. if( pIdx==0 ){
  110959. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  110960. }else{
  110961. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  110962. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  110963. }
  110964. }else{
  110965. k = 0;
  110966. break;
  110967. }
  110968. }
  110969. assert( pParse->nErr>0 || pFK==0 );
  110970. if( pFK ) break;
  110971. if( pParse->nTab<i ) pParse->nTab = i;
  110972. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  110973. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  110974. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  110975. pIdx = 0;
  110976. aiCols = 0;
  110977. if( pParent ){
  110978. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  110979. assert( x==0 );
  110980. }
  110981. addrOk = sqlite3VdbeMakeLabel(v);
  110982. /* Generate code to read the child key values into registers
  110983. ** regRow..regRow+n. If any of the child key values are NULL, this
  110984. ** row cannot cause an FK violation. Jump directly to addrOk in
  110985. ** this case. */
  110986. for(j=0; j<pFK->nCol; j++){
  110987. int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
  110988. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
  110989. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  110990. }
  110991. /* Generate code to query the parent index for a matching parent
  110992. ** key. If a match is found, jump to addrOk. */
  110993. if( pIdx ){
  110994. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  110995. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  110996. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  110997. VdbeCoverage(v);
  110998. }else if( pParent ){
  110999. int jmp = sqlite3VdbeCurrentAddr(v)+2;
  111000. sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
  111001. sqlite3VdbeGoto(v, addrOk);
  111002. assert( pFK->nCol==1 );
  111003. }
  111004. /* Generate code to report an FK violation to the caller. */
  111005. if( HasRowid(pTab) ){
  111006. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  111007. }else{
  111008. sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
  111009. }
  111010. sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
  111011. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  111012. sqlite3VdbeResolveLabel(v, addrOk);
  111013. sqlite3DbFree(db, aiCols);
  111014. }
  111015. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  111016. sqlite3VdbeJumpHere(v, addrTop);
  111017. }
  111018. }
  111019. break;
  111020. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  111021. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  111022. #ifndef NDEBUG
  111023. case PragTyp_PARSER_TRACE: {
  111024. if( zRight ){
  111025. if( sqlite3GetBoolean(zRight, 0) ){
  111026. sqlite3ParserTrace(stdout, "parser: ");
  111027. }else{
  111028. sqlite3ParserTrace(0, 0);
  111029. }
  111030. }
  111031. }
  111032. break;
  111033. #endif
  111034. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  111035. ** used will be case sensitive or not depending on the RHS.
  111036. */
  111037. case PragTyp_CASE_SENSITIVE_LIKE: {
  111038. if( zRight ){
  111039. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  111040. }
  111041. }
  111042. break;
  111043. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  111044. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  111045. #endif
  111046. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  111047. /* PRAGMA integrity_check
  111048. ** PRAGMA integrity_check(N)
  111049. ** PRAGMA quick_check
  111050. ** PRAGMA quick_check(N)
  111051. **
  111052. ** Verify the integrity of the database.
  111053. **
  111054. ** The "quick_check" is reduced version of
  111055. ** integrity_check designed to detect most database corruption
  111056. ** without the overhead of cross-checking indexes. Quick_check
  111057. ** is linear time wherease integrity_check is O(NlogN).
  111058. */
  111059. case PragTyp_INTEGRITY_CHECK: {
  111060. int i, j, addr, mxErr;
  111061. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  111062. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  111063. ** then iDb is set to the index of the database identified by <db>.
  111064. ** In this case, the integrity of database iDb only is verified by
  111065. ** the VDBE created below.
  111066. **
  111067. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  111068. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  111069. ** to -1 here, to indicate that the VDBE should verify the integrity
  111070. ** of all attached databases. */
  111071. assert( iDb>=0 );
  111072. assert( iDb==0 || pId2->z );
  111073. if( pId2->z==0 ) iDb = -1;
  111074. /* Initialize the VDBE program */
  111075. pParse->nMem = 6;
  111076. /* Set the maximum error count */
  111077. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  111078. if( zRight ){
  111079. sqlite3GetInt32(zRight, &mxErr);
  111080. if( mxErr<=0 ){
  111081. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  111082. }
  111083. }
  111084. sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
  111085. /* Do an integrity check on each database file */
  111086. for(i=0; i<db->nDb; i++){
  111087. HashElem *x; /* For looping over tables in the schema */
  111088. Hash *pTbls; /* Set of all tables in the schema */
  111089. int *aRoot; /* Array of root page numbers of all btrees */
  111090. int cnt = 0; /* Number of entries in aRoot[] */
  111091. int mxIdx = 0; /* Maximum number of indexes for any table */
  111092. if( OMIT_TEMPDB && i==1 ) continue;
  111093. if( iDb>=0 && i!=iDb ) continue;
  111094. sqlite3CodeVerifySchema(pParse, i);
  111095. /* Do an integrity check of the B-Tree
  111096. **
  111097. ** Begin by finding the root pages numbers
  111098. ** for all tables and indices in the database.
  111099. */
  111100. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  111101. pTbls = &db->aDb[i].pSchema->tblHash;
  111102. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  111103. Table *pTab = sqliteHashData(x); /* Current table */
  111104. Index *pIdx; /* An index on pTab */
  111105. int nIdx; /* Number of indexes on pTab */
  111106. if( HasRowid(pTab) ) cnt++;
  111107. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
  111108. if( nIdx>mxIdx ) mxIdx = nIdx;
  111109. }
  111110. aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
  111111. if( aRoot==0 ) break;
  111112. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  111113. Table *pTab = sqliteHashData(x);
  111114. Index *pIdx;
  111115. if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
  111116. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  111117. aRoot[++cnt] = pIdx->tnum;
  111118. }
  111119. }
  111120. aRoot[0] = cnt;
  111121. /* Make sure sufficient number of registers have been allocated */
  111122. pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  111123. sqlite3ClearTempRegCache(pParse);
  111124. /* Do the b-tree integrity checks */
  111125. sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  111126. sqlite3VdbeChangeP5(v, (u8)i);
  111127. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  111128. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  111129. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
  111130. P4_DYNAMIC);
  111131. sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
  111132. integrityCheckResultRow(v);
  111133. sqlite3VdbeJumpHere(v, addr);
  111134. /* Make sure all the indices are constructed correctly.
  111135. */
  111136. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  111137. Table *pTab = sqliteHashData(x);
  111138. Index *pIdx, *pPk;
  111139. Index *pPrior = 0;
  111140. int loopTop;
  111141. int iDataCur, iIdxCur;
  111142. int r1 = -1;
  111143. if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
  111144. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  111145. sqlite3ExprCacheClear(pParse);
  111146. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  111147. 1, 0, &iDataCur, &iIdxCur);
  111148. /* reg[7] counts the number of entries in the table.
  111149. ** reg[8+i] counts the number of entries in the i-th index
  111150. */
  111151. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  111152. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  111153. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  111154. }
  111155. assert( pParse->nMem>=8+j );
  111156. assert( sqlite3NoTempsInRange(pParse,1,7+j) );
  111157. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  111158. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  111159. /* Verify that all NOT NULL columns really are NOT NULL */
  111160. for(j=0; j<pTab->nCol; j++){
  111161. char *zErr;
  111162. int jmp2;
  111163. if( j==pTab->iPKey ) continue;
  111164. if( pTab->aCol[j].notNull==0 ) continue;
  111165. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  111166. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  111167. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  111168. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  111169. pTab->aCol[j].zName);
  111170. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  111171. integrityCheckResultRow(v);
  111172. sqlite3VdbeJumpHere(v, jmp2);
  111173. }
  111174. /* Verify CHECK constraints */
  111175. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  111176. ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
  111177. if( db->mallocFailed==0 ){
  111178. int addrCkFault = sqlite3VdbeMakeLabel(v);
  111179. int addrCkOk = sqlite3VdbeMakeLabel(v);
  111180. char *zErr;
  111181. int k;
  111182. pParse->iSelfTab = iDataCur + 1;
  111183. sqlite3ExprCachePush(pParse);
  111184. for(k=pCheck->nExpr-1; k>0; k--){
  111185. sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
  111186. }
  111187. sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
  111188. SQLITE_JUMPIFNULL);
  111189. sqlite3VdbeResolveLabel(v, addrCkFault);
  111190. pParse->iSelfTab = 0;
  111191. zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
  111192. pTab->zName);
  111193. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  111194. integrityCheckResultRow(v);
  111195. sqlite3VdbeResolveLabel(v, addrCkOk);
  111196. sqlite3ExprCachePop(pParse);
  111197. }
  111198. sqlite3ExprListDelete(db, pCheck);
  111199. }
  111200. if( !isQuick ){ /* Omit the remaining tests for quick_check */
  111201. /* Sanity check on record header decoding */
  111202. sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nCol-1, 3);
  111203. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  111204. /* Validate index entries for the current row */
  111205. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  111206. int jmp2, jmp3, jmp4, jmp5;
  111207. int ckUniq = sqlite3VdbeMakeLabel(v);
  111208. if( pPk==pIdx ) continue;
  111209. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  111210. pPrior, r1);
  111211. pPrior = pIdx;
  111212. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
  111213. /* Verify that an index entry exists for the current table row */
  111214. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  111215. pIdx->nColumn); VdbeCoverage(v);
  111216. sqlite3VdbeLoadString(v, 3, "row ");
  111217. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  111218. sqlite3VdbeLoadString(v, 4, " missing from index ");
  111219. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  111220. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  111221. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  111222. jmp4 = integrityCheckResultRow(v);
  111223. sqlite3VdbeJumpHere(v, jmp2);
  111224. /* For UNIQUE indexes, verify that only one entry exists with the
  111225. ** current key. The entry is unique if (1) any column is NULL
  111226. ** or (2) the next entry has a different key */
  111227. if( IsUniqueIndex(pIdx) ){
  111228. int uniqOk = sqlite3VdbeMakeLabel(v);
  111229. int jmp6;
  111230. int kk;
  111231. for(kk=0; kk<pIdx->nKeyCol; kk++){
  111232. int iCol = pIdx->aiColumn[kk];
  111233. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  111234. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  111235. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  111236. VdbeCoverage(v);
  111237. }
  111238. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  111239. sqlite3VdbeGoto(v, uniqOk);
  111240. sqlite3VdbeJumpHere(v, jmp6);
  111241. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  111242. pIdx->nKeyCol); VdbeCoverage(v);
  111243. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  111244. sqlite3VdbeGoto(v, jmp5);
  111245. sqlite3VdbeResolveLabel(v, uniqOk);
  111246. }
  111247. sqlite3VdbeJumpHere(v, jmp4);
  111248. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  111249. }
  111250. }
  111251. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  111252. sqlite3VdbeJumpHere(v, loopTop-1);
  111253. #ifndef SQLITE_OMIT_BTREECOUNT
  111254. if( !isQuick ){
  111255. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  111256. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  111257. if( pPk==pIdx ) continue;
  111258. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  111259. addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
  111260. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  111261. sqlite3VdbeLoadString(v, 4, pIdx->zName);
  111262. sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
  111263. integrityCheckResultRow(v);
  111264. sqlite3VdbeJumpHere(v, addr);
  111265. }
  111266. }
  111267. #endif /* SQLITE_OMIT_BTREECOUNT */
  111268. }
  111269. }
  111270. {
  111271. static const int iLn = VDBE_OFFSET_LINENO(2);
  111272. static const VdbeOpList endCode[] = {
  111273. { OP_AddImm, 1, 0, 0}, /* 0 */
  111274. { OP_IfNotZero, 1, 4, 0}, /* 1 */
  111275. { OP_String8, 0, 3, 0}, /* 2 */
  111276. { OP_ResultRow, 3, 1, 0}, /* 3 */
  111277. { OP_Halt, 0, 0, 0}, /* 4 */
  111278. { OP_String8, 0, 3, 0}, /* 5 */
  111279. { OP_Goto, 0, 3, 0}, /* 6 */
  111280. };
  111281. VdbeOp *aOp;
  111282. aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  111283. if( aOp ){
  111284. aOp[0].p2 = 1-mxErr;
  111285. aOp[2].p4type = P4_STATIC;
  111286. aOp[2].p4.z = "ok";
  111287. aOp[5].p4type = P4_STATIC;
  111288. aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
  111289. }
  111290. sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
  111291. }
  111292. }
  111293. break;
  111294. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  111295. #ifndef SQLITE_OMIT_UTF16
  111296. /*
  111297. ** PRAGMA encoding
  111298. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  111299. **
  111300. ** In its first form, this pragma returns the encoding of the main
  111301. ** database. If the database is not initialized, it is initialized now.
  111302. **
  111303. ** The second form of this pragma is a no-op if the main database file
  111304. ** has not already been initialized. In this case it sets the default
  111305. ** encoding that will be used for the main database file if a new file
  111306. ** is created. If an existing main database file is opened, then the
  111307. ** default text encoding for the existing database is used.
  111308. **
  111309. ** In all cases new databases created using the ATTACH command are
  111310. ** created to use the same default text encoding as the main database. If
  111311. ** the main database has not been initialized and/or created when ATTACH
  111312. ** is executed, this is done before the ATTACH operation.
  111313. **
  111314. ** In the second form this pragma sets the text encoding to be used in
  111315. ** new database files created using this database handle. It is only
  111316. ** useful if invoked immediately after the main database i
  111317. */
  111318. case PragTyp_ENCODING: {
  111319. static const struct EncName {
  111320. char *zName;
  111321. u8 enc;
  111322. } encnames[] = {
  111323. { "UTF8", SQLITE_UTF8 },
  111324. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  111325. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  111326. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  111327. { "UTF16le", SQLITE_UTF16LE },
  111328. { "UTF16be", SQLITE_UTF16BE },
  111329. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  111330. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  111331. { 0, 0 }
  111332. };
  111333. const struct EncName *pEnc;
  111334. if( !zRight ){ /* "PRAGMA encoding" */
  111335. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  111336. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  111337. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  111338. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  111339. returnSingleText(v, encnames[ENC(pParse->db)].zName);
  111340. }else{ /* "PRAGMA encoding = XXX" */
  111341. /* Only change the value of sqlite.enc if the database handle is not
  111342. ** initialized. If the main database exists, the new sqlite.enc value
  111343. ** will be overwritten when the schema is next loaded. If it does not
  111344. ** already exists, it will be created to use the new encoding value.
  111345. */
  111346. if(
  111347. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  111348. DbHasProperty(db, 0, DB_Empty)
  111349. ){
  111350. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  111351. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  111352. SCHEMA_ENC(db) = ENC(db) =
  111353. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  111354. break;
  111355. }
  111356. }
  111357. if( !pEnc->zName ){
  111358. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  111359. }
  111360. }
  111361. }
  111362. }
  111363. break;
  111364. #endif /* SQLITE_OMIT_UTF16 */
  111365. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  111366. /*
  111367. ** PRAGMA [schema.]schema_version
  111368. ** PRAGMA [schema.]schema_version = <integer>
  111369. **
  111370. ** PRAGMA [schema.]user_version
  111371. ** PRAGMA [schema.]user_version = <integer>
  111372. **
  111373. ** PRAGMA [schema.]freelist_count
  111374. **
  111375. ** PRAGMA [schema.]data_version
  111376. **
  111377. ** PRAGMA [schema.]application_id
  111378. ** PRAGMA [schema.]application_id = <integer>
  111379. **
  111380. ** The pragma's schema_version and user_version are used to set or get
  111381. ** the value of the schema-version and user-version, respectively. Both
  111382. ** the schema-version and the user-version are 32-bit signed integers
  111383. ** stored in the database header.
  111384. **
  111385. ** The schema-cookie is usually only manipulated internally by SQLite. It
  111386. ** is incremented by SQLite whenever the database schema is modified (by
  111387. ** creating or dropping a table or index). The schema version is used by
  111388. ** SQLite each time a query is executed to ensure that the internal cache
  111389. ** of the schema used when compiling the SQL query matches the schema of
  111390. ** the database against which the compiled query is actually executed.
  111391. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  111392. ** the schema-version is potentially dangerous and may lead to program
  111393. ** crashes or database corruption. Use with caution!
  111394. **
  111395. ** The user-version is not used internally by SQLite. It may be used by
  111396. ** applications for any purpose.
  111397. */
  111398. case PragTyp_HEADER_VALUE: {
  111399. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  111400. sqlite3VdbeUsesBtree(v, iDb);
  111401. if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
  111402. /* Write the specified cookie value */
  111403. static const VdbeOpList setCookie[] = {
  111404. { OP_Transaction, 0, 1, 0}, /* 0 */
  111405. { OP_SetCookie, 0, 0, 0}, /* 1 */
  111406. };
  111407. VdbeOp *aOp;
  111408. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
  111409. aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  111410. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  111411. aOp[0].p1 = iDb;
  111412. aOp[1].p1 = iDb;
  111413. aOp[1].p2 = iCookie;
  111414. aOp[1].p3 = sqlite3Atoi(zRight);
  111415. }else{
  111416. /* Read the specified cookie value */
  111417. static const VdbeOpList readCookie[] = {
  111418. { OP_Transaction, 0, 0, 0}, /* 0 */
  111419. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  111420. { OP_ResultRow, 1, 1, 0}
  111421. };
  111422. VdbeOp *aOp;
  111423. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
  111424. aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
  111425. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  111426. aOp[0].p1 = iDb;
  111427. aOp[1].p1 = iDb;
  111428. aOp[1].p3 = iCookie;
  111429. sqlite3VdbeReusable(v);
  111430. }
  111431. }
  111432. break;
  111433. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  111434. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  111435. /*
  111436. ** PRAGMA compile_options
  111437. **
  111438. ** Return the names of all compile-time options used in this build,
  111439. ** one option per row.
  111440. */
  111441. case PragTyp_COMPILE_OPTIONS: {
  111442. int i = 0;
  111443. const char *zOpt;
  111444. pParse->nMem = 1;
  111445. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  111446. sqlite3VdbeLoadString(v, 1, zOpt);
  111447. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  111448. }
  111449. sqlite3VdbeReusable(v);
  111450. }
  111451. break;
  111452. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  111453. #ifndef SQLITE_OMIT_WAL
  111454. /*
  111455. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  111456. **
  111457. ** Checkpoint the database.
  111458. */
  111459. case PragTyp_WAL_CHECKPOINT: {
  111460. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  111461. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  111462. if( zRight ){
  111463. if( sqlite3StrICmp(zRight, "full")==0 ){
  111464. eMode = SQLITE_CHECKPOINT_FULL;
  111465. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  111466. eMode = SQLITE_CHECKPOINT_RESTART;
  111467. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  111468. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  111469. }
  111470. }
  111471. pParse->nMem = 3;
  111472. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  111473. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  111474. }
  111475. break;
  111476. /*
  111477. ** PRAGMA wal_autocheckpoint
  111478. ** PRAGMA wal_autocheckpoint = N
  111479. **
  111480. ** Configure a database connection to automatically checkpoint a database
  111481. ** after accumulating N frames in the log. Or query for the current value
  111482. ** of N.
  111483. */
  111484. case PragTyp_WAL_AUTOCHECKPOINT: {
  111485. if( zRight ){
  111486. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  111487. }
  111488. returnSingleInt(v,
  111489. db->xWalCallback==sqlite3WalDefaultHook ?
  111490. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  111491. }
  111492. break;
  111493. #endif
  111494. /*
  111495. ** PRAGMA shrink_memory
  111496. **
  111497. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  111498. ** connection on which it is invoked to free up as much memory as it
  111499. ** can, by calling sqlite3_db_release_memory().
  111500. */
  111501. case PragTyp_SHRINK_MEMORY: {
  111502. sqlite3_db_release_memory(db);
  111503. break;
  111504. }
  111505. /*
  111506. ** PRAGMA optimize
  111507. ** PRAGMA optimize(MASK)
  111508. ** PRAGMA schema.optimize
  111509. ** PRAGMA schema.optimize(MASK)
  111510. **
  111511. ** Attempt to optimize the database. All schemas are optimized in the first
  111512. ** two forms, and only the specified schema is optimized in the latter two.
  111513. **
  111514. ** The details of optimizations performed by this pragma are expected
  111515. ** to change and improve over time. Applications should anticipate that
  111516. ** this pragma will perform new optimizations in future releases.
  111517. **
  111518. ** The optional argument is a bitmask of optimizations to perform:
  111519. **
  111520. ** 0x0001 Debugging mode. Do not actually perform any optimizations
  111521. ** but instead return one line of text for each optimization
  111522. ** that would have been done. Off by default.
  111523. **
  111524. ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
  111525. ** See below for additional information.
  111526. **
  111527. ** 0x0004 (Not yet implemented) Record usage and performance
  111528. ** information from the current session in the
  111529. ** database file so that it will be available to "optimize"
  111530. ** pragmas run by future database connections.
  111531. **
  111532. ** 0x0008 (Not yet implemented) Create indexes that might have
  111533. ** been helpful to recent queries
  111534. **
  111535. ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
  111536. ** of the optimizations listed above except Debug Mode, including new
  111537. ** optimizations that have not yet been invented. If new optimizations are
  111538. ** ever added that should be off by default, those off-by-default
  111539. ** optimizations will have bitmasks of 0x10000 or larger.
  111540. **
  111541. ** DETERMINATION OF WHEN TO RUN ANALYZE
  111542. **
  111543. ** In the current implementation, a table is analyzed if only if all of
  111544. ** the following are true:
  111545. **
  111546. ** (1) MASK bit 0x02 is set.
  111547. **
  111548. ** (2) The query planner used sqlite_stat1-style statistics for one or
  111549. ** more indexes of the table at some point during the lifetime of
  111550. ** the current connection.
  111551. **
  111552. ** (3) One or more indexes of the table are currently unanalyzed OR
  111553. ** the number of rows in the table has increased by 25 times or more
  111554. ** since the last time ANALYZE was run.
  111555. **
  111556. ** The rules for when tables are analyzed are likely to change in
  111557. ** future releases.
  111558. */
  111559. case PragTyp_OPTIMIZE: {
  111560. int iDbLast; /* Loop termination point for the schema loop */
  111561. int iTabCur; /* Cursor for a table whose size needs checking */
  111562. HashElem *k; /* Loop over tables of a schema */
  111563. Schema *pSchema; /* The current schema */
  111564. Table *pTab; /* A table in the schema */
  111565. Index *pIdx; /* An index of the table */
  111566. LogEst szThreshold; /* Size threshold above which reanalysis is needd */
  111567. char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
  111568. u32 opMask; /* Mask of operations to perform */
  111569. if( zRight ){
  111570. opMask = (u32)sqlite3Atoi(zRight);
  111571. if( (opMask & 0x02)==0 ) break;
  111572. }else{
  111573. opMask = 0xfffe;
  111574. }
  111575. iTabCur = pParse->nTab++;
  111576. for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
  111577. if( iDb==1 ) continue;
  111578. sqlite3CodeVerifySchema(pParse, iDb);
  111579. pSchema = db->aDb[iDb].pSchema;
  111580. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  111581. pTab = (Table*)sqliteHashData(k);
  111582. /* If table pTab has not been used in a way that would benefit from
  111583. ** having analysis statistics during the current session, then skip it.
  111584. ** This also has the effect of skipping virtual tables and views */
  111585. if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
  111586. /* Reanalyze if the table is 25 times larger than the last analysis */
  111587. szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
  111588. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  111589. if( !pIdx->hasStat1 ){
  111590. szThreshold = 0; /* Always analyze if any index lacks statistics */
  111591. break;
  111592. }
  111593. }
  111594. if( szThreshold ){
  111595. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  111596. sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
  111597. sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
  111598. VdbeCoverage(v);
  111599. }
  111600. zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
  111601. db->aDb[iDb].zDbSName, pTab->zName);
  111602. if( opMask & 0x01 ){
  111603. int r1 = sqlite3GetTempReg(pParse);
  111604. sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
  111605. sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
  111606. }else{
  111607. sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
  111608. }
  111609. }
  111610. }
  111611. sqlite3VdbeAddOp0(v, OP_Expire);
  111612. break;
  111613. }
  111614. /*
  111615. ** PRAGMA busy_timeout
  111616. ** PRAGMA busy_timeout = N
  111617. **
  111618. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  111619. ** if one is set. If no busy handler or a different busy handler is set
  111620. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  111621. ** disables the timeout.
  111622. */
  111623. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  111624. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  111625. if( zRight ){
  111626. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  111627. }
  111628. returnSingleInt(v, db->busyTimeout);
  111629. break;
  111630. }
  111631. /*
  111632. ** PRAGMA soft_heap_limit
  111633. ** PRAGMA soft_heap_limit = N
  111634. **
  111635. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  111636. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  111637. ** specified and is a non-negative integer.
  111638. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  111639. ** returns the same integer that would be returned by the
  111640. ** sqlite3_soft_heap_limit64(-1) C-language function.
  111641. */
  111642. case PragTyp_SOFT_HEAP_LIMIT: {
  111643. sqlite3_int64 N;
  111644. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  111645. sqlite3_soft_heap_limit64(N);
  111646. }
  111647. returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
  111648. break;
  111649. }
  111650. /*
  111651. ** PRAGMA threads
  111652. ** PRAGMA threads = N
  111653. **
  111654. ** Configure the maximum number of worker threads. Return the new
  111655. ** maximum, which might be less than requested.
  111656. */
  111657. case PragTyp_THREADS: {
  111658. sqlite3_int64 N;
  111659. if( zRight
  111660. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  111661. && N>=0
  111662. ){
  111663. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  111664. }
  111665. returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  111666. break;
  111667. }
  111668. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  111669. /*
  111670. ** Report the current state of file logs for all databases
  111671. */
  111672. case PragTyp_LOCK_STATUS: {
  111673. static const char *const azLockName[] = {
  111674. "unlocked", "shared", "reserved", "pending", "exclusive"
  111675. };
  111676. int i;
  111677. pParse->nMem = 2;
  111678. for(i=0; i<db->nDb; i++){
  111679. Btree *pBt;
  111680. const char *zState = "unknown";
  111681. int j;
  111682. if( db->aDb[i].zDbSName==0 ) continue;
  111683. pBt = db->aDb[i].pBt;
  111684. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  111685. zState = "closed";
  111686. }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
  111687. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  111688. zState = azLockName[j];
  111689. }
  111690. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
  111691. }
  111692. break;
  111693. }
  111694. #endif
  111695. #ifdef SQLITE_HAS_CODEC
  111696. case PragTyp_KEY: {
  111697. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  111698. break;
  111699. }
  111700. case PragTyp_REKEY: {
  111701. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  111702. break;
  111703. }
  111704. case PragTyp_HEXKEY: {
  111705. if( zRight ){
  111706. u8 iByte;
  111707. int i;
  111708. char zKey[40];
  111709. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  111710. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  111711. if( (i&1)!=0 ) zKey[i/2] = iByte;
  111712. }
  111713. if( (zLeft[3] & 0xf)==0xb ){
  111714. sqlite3_key_v2(db, zDb, zKey, i/2);
  111715. }else{
  111716. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  111717. }
  111718. }
  111719. break;
  111720. }
  111721. #endif
  111722. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  111723. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  111724. #ifdef SQLITE_HAS_CODEC
  111725. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  111726. sqlite3_activate_see(&zRight[4]);
  111727. }
  111728. #endif
  111729. #ifdef SQLITE_ENABLE_CEROD
  111730. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  111731. sqlite3_activate_cerod(&zRight[6]);
  111732. }
  111733. #endif
  111734. }
  111735. break;
  111736. #endif
  111737. } /* End of the PRAGMA switch */
  111738. /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
  111739. ** purpose is to execute assert() statements to verify that if the
  111740. ** PragFlg_NoColumns1 flag is set and the caller specified an argument
  111741. ** to the PRAGMA, the implementation has not added any OP_ResultRow
  111742. ** instructions to the VM. */
  111743. if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
  111744. sqlite3VdbeVerifyNoResultRow(v);
  111745. }
  111746. pragma_out:
  111747. sqlite3DbFree(db, zLeft);
  111748. sqlite3DbFree(db, zRight);
  111749. }
  111750. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111751. /*****************************************************************************
  111752. ** Implementation of an eponymous virtual table that runs a pragma.
  111753. **
  111754. */
  111755. typedef struct PragmaVtab PragmaVtab;
  111756. typedef struct PragmaVtabCursor PragmaVtabCursor;
  111757. struct PragmaVtab {
  111758. sqlite3_vtab base; /* Base class. Must be first */
  111759. sqlite3 *db; /* The database connection to which it belongs */
  111760. const PragmaName *pName; /* Name of the pragma */
  111761. u8 nHidden; /* Number of hidden columns */
  111762. u8 iHidden; /* Index of the first hidden column */
  111763. };
  111764. struct PragmaVtabCursor {
  111765. sqlite3_vtab_cursor base; /* Base class. Must be first */
  111766. sqlite3_stmt *pPragma; /* The pragma statement to run */
  111767. sqlite_int64 iRowid; /* Current rowid */
  111768. char *azArg[2]; /* Value of the argument and schema */
  111769. };
  111770. /*
  111771. ** Pragma virtual table module xConnect method.
  111772. */
  111773. static int pragmaVtabConnect(
  111774. sqlite3 *db,
  111775. void *pAux,
  111776. int argc, const char *const*argv,
  111777. sqlite3_vtab **ppVtab,
  111778. char **pzErr
  111779. ){
  111780. const PragmaName *pPragma = (const PragmaName*)pAux;
  111781. PragmaVtab *pTab = 0;
  111782. int rc;
  111783. int i, j;
  111784. char cSep = '(';
  111785. StrAccum acc;
  111786. char zBuf[200];
  111787. UNUSED_PARAMETER(argc);
  111788. UNUSED_PARAMETER(argv);
  111789. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  111790. sqlite3StrAccumAppendAll(&acc, "CREATE TABLE x");
  111791. for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
  111792. sqlite3XPrintf(&acc, "%c\"%s\"", cSep, pragCName[j]);
  111793. cSep = ',';
  111794. }
  111795. if( i==0 ){
  111796. sqlite3XPrintf(&acc, "(\"%s\"", pPragma->zName);
  111797. cSep = ',';
  111798. i++;
  111799. }
  111800. j = 0;
  111801. if( pPragma->mPragFlg & PragFlg_Result1 ){
  111802. sqlite3StrAccumAppendAll(&acc, ",arg HIDDEN");
  111803. j++;
  111804. }
  111805. if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
  111806. sqlite3StrAccumAppendAll(&acc, ",schema HIDDEN");
  111807. j++;
  111808. }
  111809. sqlite3StrAccumAppend(&acc, ")", 1);
  111810. sqlite3StrAccumFinish(&acc);
  111811. assert( strlen(zBuf) < sizeof(zBuf)-1 );
  111812. rc = sqlite3_declare_vtab(db, zBuf);
  111813. if( rc==SQLITE_OK ){
  111814. pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
  111815. if( pTab==0 ){
  111816. rc = SQLITE_NOMEM;
  111817. }else{
  111818. memset(pTab, 0, sizeof(PragmaVtab));
  111819. pTab->pName = pPragma;
  111820. pTab->db = db;
  111821. pTab->iHidden = i;
  111822. pTab->nHidden = j;
  111823. }
  111824. }else{
  111825. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  111826. }
  111827. *ppVtab = (sqlite3_vtab*)pTab;
  111828. return rc;
  111829. }
  111830. /*
  111831. ** Pragma virtual table module xDisconnect method.
  111832. */
  111833. static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
  111834. PragmaVtab *pTab = (PragmaVtab*)pVtab;
  111835. sqlite3_free(pTab);
  111836. return SQLITE_OK;
  111837. }
  111838. /* Figure out the best index to use to search a pragma virtual table.
  111839. **
  111840. ** There are not really any index choices. But we want to encourage the
  111841. ** query planner to give == constraints on as many hidden parameters as
  111842. ** possible, and especially on the first hidden parameter. So return a
  111843. ** high cost if hidden parameters are unconstrained.
  111844. */
  111845. static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  111846. PragmaVtab *pTab = (PragmaVtab*)tab;
  111847. const struct sqlite3_index_constraint *pConstraint;
  111848. int i, j;
  111849. int seen[2];
  111850. pIdxInfo->estimatedCost = (double)1;
  111851. if( pTab->nHidden==0 ){ return SQLITE_OK; }
  111852. pConstraint = pIdxInfo->aConstraint;
  111853. seen[0] = 0;
  111854. seen[1] = 0;
  111855. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  111856. if( pConstraint->usable==0 ) continue;
  111857. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  111858. if( pConstraint->iColumn < pTab->iHidden ) continue;
  111859. j = pConstraint->iColumn - pTab->iHidden;
  111860. assert( j < 2 );
  111861. seen[j] = i+1;
  111862. }
  111863. if( seen[0]==0 ){
  111864. pIdxInfo->estimatedCost = (double)2147483647;
  111865. pIdxInfo->estimatedRows = 2147483647;
  111866. return SQLITE_OK;
  111867. }
  111868. j = seen[0]-1;
  111869. pIdxInfo->aConstraintUsage[j].argvIndex = 1;
  111870. pIdxInfo->aConstraintUsage[j].omit = 1;
  111871. if( seen[1]==0 ) return SQLITE_OK;
  111872. pIdxInfo->estimatedCost = (double)20;
  111873. pIdxInfo->estimatedRows = 20;
  111874. j = seen[1]-1;
  111875. pIdxInfo->aConstraintUsage[j].argvIndex = 2;
  111876. pIdxInfo->aConstraintUsage[j].omit = 1;
  111877. return SQLITE_OK;
  111878. }
  111879. /* Create a new cursor for the pragma virtual table */
  111880. static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
  111881. PragmaVtabCursor *pCsr;
  111882. pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
  111883. if( pCsr==0 ) return SQLITE_NOMEM;
  111884. memset(pCsr, 0, sizeof(PragmaVtabCursor));
  111885. pCsr->base.pVtab = pVtab;
  111886. *ppCursor = &pCsr->base;
  111887. return SQLITE_OK;
  111888. }
  111889. /* Clear all content from pragma virtual table cursor. */
  111890. static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  111891. int i;
  111892. sqlite3_finalize(pCsr->pPragma);
  111893. pCsr->pPragma = 0;
  111894. for(i=0; i<ArraySize(pCsr->azArg); i++){
  111895. sqlite3_free(pCsr->azArg[i]);
  111896. pCsr->azArg[i] = 0;
  111897. }
  111898. }
  111899. /* Close a pragma virtual table cursor */
  111900. static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
  111901. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
  111902. pragmaVtabCursorClear(pCsr);
  111903. sqlite3_free(pCsr);
  111904. return SQLITE_OK;
  111905. }
  111906. /* Advance the pragma virtual table cursor to the next row */
  111907. static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
  111908. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  111909. int rc = SQLITE_OK;
  111910. /* Increment the xRowid value */
  111911. pCsr->iRowid++;
  111912. assert( pCsr->pPragma );
  111913. if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
  111914. rc = sqlite3_finalize(pCsr->pPragma);
  111915. pCsr->pPragma = 0;
  111916. pragmaVtabCursorClear(pCsr);
  111917. }
  111918. return rc;
  111919. }
  111920. /*
  111921. ** Pragma virtual table module xFilter method.
  111922. */
  111923. static int pragmaVtabFilter(
  111924. sqlite3_vtab_cursor *pVtabCursor,
  111925. int idxNum, const char *idxStr,
  111926. int argc, sqlite3_value **argv
  111927. ){
  111928. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  111929. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  111930. int rc;
  111931. int i, j;
  111932. StrAccum acc;
  111933. char *zSql;
  111934. UNUSED_PARAMETER(idxNum);
  111935. UNUSED_PARAMETER(idxStr);
  111936. pragmaVtabCursorClear(pCsr);
  111937. j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
  111938. for(i=0; i<argc; i++, j++){
  111939. const char *zText = (const char*)sqlite3_value_text(argv[i]);
  111940. assert( j<ArraySize(pCsr->azArg) );
  111941. assert( pCsr->azArg[j]==0 );
  111942. if( zText ){
  111943. pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
  111944. if( pCsr->azArg[j]==0 ){
  111945. return SQLITE_NOMEM;
  111946. }
  111947. }
  111948. }
  111949. sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
  111950. sqlite3StrAccumAppendAll(&acc, "PRAGMA ");
  111951. if( pCsr->azArg[1] ){
  111952. sqlite3XPrintf(&acc, "%Q.", pCsr->azArg[1]);
  111953. }
  111954. sqlite3StrAccumAppendAll(&acc, pTab->pName->zName);
  111955. if( pCsr->azArg[0] ){
  111956. sqlite3XPrintf(&acc, "=%Q", pCsr->azArg[0]);
  111957. }
  111958. zSql = sqlite3StrAccumFinish(&acc);
  111959. if( zSql==0 ) return SQLITE_NOMEM;
  111960. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
  111961. sqlite3_free(zSql);
  111962. if( rc!=SQLITE_OK ){
  111963. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  111964. return rc;
  111965. }
  111966. return pragmaVtabNext(pVtabCursor);
  111967. }
  111968. /*
  111969. ** Pragma virtual table module xEof method.
  111970. */
  111971. static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
  111972. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  111973. return (pCsr->pPragma==0);
  111974. }
  111975. /* The xColumn method simply returns the corresponding column from
  111976. ** the PRAGMA.
  111977. */
  111978. static int pragmaVtabColumn(
  111979. sqlite3_vtab_cursor *pVtabCursor,
  111980. sqlite3_context *ctx,
  111981. int i
  111982. ){
  111983. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  111984. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  111985. if( i<pTab->iHidden ){
  111986. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
  111987. }else{
  111988. sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
  111989. }
  111990. return SQLITE_OK;
  111991. }
  111992. /*
  111993. ** Pragma virtual table module xRowid method.
  111994. */
  111995. static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
  111996. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  111997. *p = pCsr->iRowid;
  111998. return SQLITE_OK;
  111999. }
  112000. /* The pragma virtual table object */
  112001. static const sqlite3_module pragmaVtabModule = {
  112002. 0, /* iVersion */
  112003. 0, /* xCreate - create a table */
  112004. pragmaVtabConnect, /* xConnect - connect to an existing table */
  112005. pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
  112006. pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
  112007. 0, /* xDestroy - Drop a table */
  112008. pragmaVtabOpen, /* xOpen - open a cursor */
  112009. pragmaVtabClose, /* xClose - close a cursor */
  112010. pragmaVtabFilter, /* xFilter - configure scan constraints */
  112011. pragmaVtabNext, /* xNext - advance a cursor */
  112012. pragmaVtabEof, /* xEof */
  112013. pragmaVtabColumn, /* xColumn - read data */
  112014. pragmaVtabRowid, /* xRowid - read data */
  112015. 0, /* xUpdate - write data */
  112016. 0, /* xBegin - begin transaction */
  112017. 0, /* xSync - sync transaction */
  112018. 0, /* xCommit - commit transaction */
  112019. 0, /* xRollback - rollback transaction */
  112020. 0, /* xFindFunction - function overloading */
  112021. 0, /* xRename - rename the table */
  112022. 0, /* xSavepoint */
  112023. 0, /* xRelease */
  112024. 0 /* xRollbackTo */
  112025. };
  112026. /*
  112027. ** Check to see if zTabName is really the name of a pragma. If it is,
  112028. ** then register an eponymous virtual table for that pragma and return
  112029. ** a pointer to the Module object for the new virtual table.
  112030. */
  112031. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
  112032. const PragmaName *pName;
  112033. assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
  112034. pName = pragmaLocate(zName+7);
  112035. if( pName==0 ) return 0;
  112036. if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
  112037. assert( sqlite3HashFind(&db->aModule, zName)==0 );
  112038. return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
  112039. }
  112040. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  112041. #endif /* SQLITE_OMIT_PRAGMA */
  112042. /************** End of pragma.c **********************************************/
  112043. /************** Begin file prepare.c *****************************************/
  112044. /*
  112045. ** 2005 May 25
  112046. **
  112047. ** The author disclaims copyright to this source code. In place of
  112048. ** a legal notice, here is a blessing:
  112049. **
  112050. ** May you do good and not evil.
  112051. ** May you find forgiveness for yourself and forgive others.
  112052. ** May you share freely, never taking more than you give.
  112053. **
  112054. *************************************************************************
  112055. ** This file contains the implementation of the sqlite3_prepare()
  112056. ** interface, and routines that contribute to loading the database schema
  112057. ** from disk.
  112058. */
  112059. /* #include "sqliteInt.h" */
  112060. /*
  112061. ** Fill the InitData structure with an error message that indicates
  112062. ** that the database is corrupt.
  112063. */
  112064. static void corruptSchema(
  112065. InitData *pData, /* Initialization context */
  112066. const char *zObj, /* Object being parsed at the point of error */
  112067. const char *zExtra /* Error information */
  112068. ){
  112069. sqlite3 *db = pData->db;
  112070. if( !db->mallocFailed && (db->flags & SQLITE_WriteSchema)==0 ){
  112071. char *z;
  112072. if( zObj==0 ) zObj = "?";
  112073. z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
  112074. if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
  112075. sqlite3DbFree(db, *pData->pzErrMsg);
  112076. *pData->pzErrMsg = z;
  112077. }
  112078. pData->rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_CORRUPT_BKPT;
  112079. }
  112080. /*
  112081. ** This is the callback routine for the code that initializes the
  112082. ** database. See sqlite3Init() below for additional information.
  112083. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  112084. **
  112085. ** Each callback contains the following information:
  112086. **
  112087. ** argv[0] = name of thing being created
  112088. ** argv[1] = root page number for table or index. 0 for trigger or view.
  112089. ** argv[2] = SQL text for the CREATE statement.
  112090. **
  112091. */
  112092. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  112093. InitData *pData = (InitData*)pInit;
  112094. sqlite3 *db = pData->db;
  112095. int iDb = pData->iDb;
  112096. assert( argc==3 );
  112097. UNUSED_PARAMETER2(NotUsed, argc);
  112098. assert( sqlite3_mutex_held(db->mutex) );
  112099. DbClearProperty(db, iDb, DB_Empty);
  112100. if( db->mallocFailed ){
  112101. corruptSchema(pData, argv[0], 0);
  112102. return 1;
  112103. }
  112104. assert( iDb>=0 && iDb<db->nDb );
  112105. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  112106. if( argv[1]==0 ){
  112107. corruptSchema(pData, argv[0], 0);
  112108. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  112109. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  112110. ** But because db->init.busy is set to 1, no VDBE code is generated
  112111. ** or executed. All the parser does is build the internal data
  112112. ** structures that describe the table, index, or view.
  112113. */
  112114. int rc;
  112115. u8 saved_iDb = db->init.iDb;
  112116. sqlite3_stmt *pStmt;
  112117. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  112118. assert( db->init.busy );
  112119. db->init.iDb = iDb;
  112120. db->init.newTnum = sqlite3Atoi(argv[1]);
  112121. db->init.orphanTrigger = 0;
  112122. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  112123. rc = db->errCode;
  112124. assert( (rc&0xFF)==(rcp&0xFF) );
  112125. db->init.iDb = saved_iDb;
  112126. assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 );
  112127. if( SQLITE_OK!=rc ){
  112128. if( db->init.orphanTrigger ){
  112129. assert( iDb==1 );
  112130. }else{
  112131. pData->rc = rc;
  112132. if( rc==SQLITE_NOMEM ){
  112133. sqlite3OomFault(db);
  112134. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  112135. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  112136. }
  112137. }
  112138. }
  112139. sqlite3_finalize(pStmt);
  112140. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  112141. corruptSchema(pData, argv[0], 0);
  112142. }else{
  112143. /* If the SQL column is blank it means this is an index that
  112144. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  112145. ** constraint for a CREATE TABLE. The index should have already
  112146. ** been created when we processed the CREATE TABLE. All we have
  112147. ** to do here is record the root page number for that index.
  112148. */
  112149. Index *pIndex;
  112150. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zDbSName);
  112151. if( pIndex==0 ){
  112152. /* This can occur if there exists an index on a TEMP table which
  112153. ** has the same name as another index on a permanent index. Since
  112154. ** the permanent table is hidden by the TEMP table, we can also
  112155. ** safely ignore the index on the permanent table.
  112156. */
  112157. /* Do Nothing */;
  112158. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  112159. corruptSchema(pData, argv[0], "invalid rootpage");
  112160. }
  112161. }
  112162. return 0;
  112163. }
  112164. /*
  112165. ** Attempt to read the database schema and initialize internal
  112166. ** data structures for a single database file. The index of the
  112167. ** database file is given by iDb. iDb==0 is used for the main
  112168. ** database. iDb==1 should never be used. iDb>=2 is used for
  112169. ** auxiliary databases. Return one of the SQLITE_ error codes to
  112170. ** indicate success or failure.
  112171. */
  112172. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  112173. int rc;
  112174. int i;
  112175. #ifndef SQLITE_OMIT_DEPRECATED
  112176. int size;
  112177. #endif
  112178. Db *pDb;
  112179. char const *azArg[4];
  112180. int meta[5];
  112181. InitData initData;
  112182. const char *zMasterName;
  112183. int openedTransaction = 0;
  112184. assert( iDb>=0 && iDb<db->nDb );
  112185. assert( db->aDb[iDb].pSchema );
  112186. assert( sqlite3_mutex_held(db->mutex) );
  112187. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  112188. db->init.busy = 1;
  112189. /* Construct the in-memory representation schema tables (sqlite_master or
  112190. ** sqlite_temp_master) by invoking the parser directly. The appropriate
  112191. ** table name will be inserted automatically by the parser so we can just
  112192. ** use the abbreviation "x" here. The parser will also automatically tag
  112193. ** the schema table as read-only. */
  112194. azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
  112195. azArg[1] = "1";
  112196. azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
  112197. "rootpage int,sql text)";
  112198. azArg[3] = 0;
  112199. initData.db = db;
  112200. initData.iDb = iDb;
  112201. initData.rc = SQLITE_OK;
  112202. initData.pzErrMsg = pzErrMsg;
  112203. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  112204. if( initData.rc ){
  112205. rc = initData.rc;
  112206. goto error_out;
  112207. }
  112208. /* Create a cursor to hold the database open
  112209. */
  112210. pDb = &db->aDb[iDb];
  112211. if( pDb->pBt==0 ){
  112212. assert( iDb==1 );
  112213. DbSetProperty(db, 1, DB_SchemaLoaded);
  112214. rc = SQLITE_OK;
  112215. goto error_out;
  112216. }
  112217. /* If there is not already a read-only (or read-write) transaction opened
  112218. ** on the b-tree database, open one now. If a transaction is opened, it
  112219. ** will be closed before this function returns. */
  112220. sqlite3BtreeEnter(pDb->pBt);
  112221. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  112222. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  112223. if( rc!=SQLITE_OK ){
  112224. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  112225. goto initone_error_out;
  112226. }
  112227. openedTransaction = 1;
  112228. }
  112229. /* Get the database meta information.
  112230. **
  112231. ** Meta values are as follows:
  112232. ** meta[0] Schema cookie. Changes with each schema change.
  112233. ** meta[1] File format of schema layer.
  112234. ** meta[2] Size of the page cache.
  112235. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  112236. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  112237. ** meta[5] User version
  112238. ** meta[6] Incremental vacuum mode
  112239. ** meta[7] unused
  112240. ** meta[8] unused
  112241. ** meta[9] unused
  112242. **
  112243. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  112244. ** the possible values of meta[4].
  112245. */
  112246. for(i=0; i<ArraySize(meta); i++){
  112247. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  112248. }
  112249. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  112250. /* If opening a non-empty database, check the text encoding. For the
  112251. ** main database, set sqlite3.enc to the encoding of the main database.
  112252. ** For an attached db, it is an error if the encoding is not the same
  112253. ** as sqlite3.enc.
  112254. */
  112255. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  112256. if( iDb==0 ){
  112257. #ifndef SQLITE_OMIT_UTF16
  112258. u8 encoding;
  112259. /* If opening the main database, set ENC(db). */
  112260. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  112261. if( encoding==0 ) encoding = SQLITE_UTF8;
  112262. ENC(db) = encoding;
  112263. #else
  112264. ENC(db) = SQLITE_UTF8;
  112265. #endif
  112266. }else{
  112267. /* If opening an attached database, the encoding much match ENC(db) */
  112268. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  112269. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  112270. " text encoding as main database");
  112271. rc = SQLITE_ERROR;
  112272. goto initone_error_out;
  112273. }
  112274. }
  112275. }else{
  112276. DbSetProperty(db, iDb, DB_Empty);
  112277. }
  112278. pDb->pSchema->enc = ENC(db);
  112279. if( pDb->pSchema->cache_size==0 ){
  112280. #ifndef SQLITE_OMIT_DEPRECATED
  112281. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  112282. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  112283. pDb->pSchema->cache_size = size;
  112284. #else
  112285. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  112286. #endif
  112287. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  112288. }
  112289. /*
  112290. ** file_format==1 Version 3.0.0.
  112291. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  112292. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  112293. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  112294. */
  112295. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  112296. if( pDb->pSchema->file_format==0 ){
  112297. pDb->pSchema->file_format = 1;
  112298. }
  112299. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  112300. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  112301. rc = SQLITE_ERROR;
  112302. goto initone_error_out;
  112303. }
  112304. /* Ticket #2804: When we open a database in the newer file format,
  112305. ** clear the legacy_file_format pragma flag so that a VACUUM will
  112306. ** not downgrade the database and thus invalidate any descending
  112307. ** indices that the user might have created.
  112308. */
  112309. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  112310. db->flags &= ~SQLITE_LegacyFileFmt;
  112311. }
  112312. /* Read the schema information out of the schema tables
  112313. */
  112314. assert( db->init.busy );
  112315. {
  112316. char *zSql;
  112317. zSql = sqlite3MPrintf(db,
  112318. "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
  112319. db->aDb[iDb].zDbSName, zMasterName);
  112320. #ifndef SQLITE_OMIT_AUTHORIZATION
  112321. {
  112322. sqlite3_xauth xAuth;
  112323. xAuth = db->xAuth;
  112324. db->xAuth = 0;
  112325. #endif
  112326. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  112327. #ifndef SQLITE_OMIT_AUTHORIZATION
  112328. db->xAuth = xAuth;
  112329. }
  112330. #endif
  112331. if( rc==SQLITE_OK ) rc = initData.rc;
  112332. sqlite3DbFree(db, zSql);
  112333. #ifndef SQLITE_OMIT_ANALYZE
  112334. if( rc==SQLITE_OK ){
  112335. sqlite3AnalysisLoad(db, iDb);
  112336. }
  112337. #endif
  112338. }
  112339. if( db->mallocFailed ){
  112340. rc = SQLITE_NOMEM_BKPT;
  112341. sqlite3ResetAllSchemasOfConnection(db);
  112342. }
  112343. if( rc==SQLITE_OK || (db->flags&SQLITE_WriteSchema)){
  112344. /* Black magic: If the SQLITE_WriteSchema flag is set, then consider
  112345. ** the schema loaded, even if errors occurred. In this situation the
  112346. ** current sqlite3_prepare() operation will fail, but the following one
  112347. ** will attempt to compile the supplied statement against whatever subset
  112348. ** of the schema was loaded before the error occurred. The primary
  112349. ** purpose of this is to allow access to the sqlite_master table
  112350. ** even when its contents have been corrupted.
  112351. */
  112352. DbSetProperty(db, iDb, DB_SchemaLoaded);
  112353. rc = SQLITE_OK;
  112354. }
  112355. /* Jump here for an error that occurs after successfully allocating
  112356. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  112357. ** before that point, jump to error_out.
  112358. */
  112359. initone_error_out:
  112360. if( openedTransaction ){
  112361. sqlite3BtreeCommit(pDb->pBt);
  112362. }
  112363. sqlite3BtreeLeave(pDb->pBt);
  112364. error_out:
  112365. if( rc ){
  112366. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  112367. sqlite3OomFault(db);
  112368. }
  112369. sqlite3ResetOneSchema(db, iDb);
  112370. }
  112371. db->init.busy = 0;
  112372. return rc;
  112373. }
  112374. /*
  112375. ** Initialize all database files - the main database file, the file
  112376. ** used to store temporary tables, and any additional database files
  112377. ** created using ATTACH statements. Return a success code. If an
  112378. ** error occurs, write an error message into *pzErrMsg.
  112379. **
  112380. ** After a database is initialized, the DB_SchemaLoaded bit is set
  112381. ** bit is set in the flags field of the Db structure. If the database
  112382. ** file was of zero-length, then the DB_Empty flag is also set.
  112383. */
  112384. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  112385. int i, rc;
  112386. int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
  112387. assert( sqlite3_mutex_held(db->mutex) );
  112388. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  112389. assert( db->init.busy==0 );
  112390. ENC(db) = SCHEMA_ENC(db);
  112391. assert( db->nDb>0 );
  112392. /* Do the main schema first */
  112393. if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
  112394. rc = sqlite3InitOne(db, 0, pzErrMsg);
  112395. if( rc ) return rc;
  112396. }
  112397. /* All other schemas after the main schema. The "temp" schema must be last */
  112398. for(i=db->nDb-1; i>0; i--){
  112399. if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
  112400. rc = sqlite3InitOne(db, i, pzErrMsg);
  112401. if( rc ) return rc;
  112402. }
  112403. }
  112404. if( commit_internal ){
  112405. sqlite3CommitInternalChanges(db);
  112406. }
  112407. return SQLITE_OK;
  112408. }
  112409. /*
  112410. ** This routine is a no-op if the database schema is already initialized.
  112411. ** Otherwise, the schema is loaded. An error code is returned.
  112412. */
  112413. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  112414. int rc = SQLITE_OK;
  112415. sqlite3 *db = pParse->db;
  112416. assert( sqlite3_mutex_held(db->mutex) );
  112417. if( !db->init.busy ){
  112418. rc = sqlite3Init(db, &pParse->zErrMsg);
  112419. }
  112420. if( rc!=SQLITE_OK ){
  112421. pParse->rc = rc;
  112422. pParse->nErr++;
  112423. }
  112424. return rc;
  112425. }
  112426. /*
  112427. ** Check schema cookies in all databases. If any cookie is out
  112428. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  112429. ** make no changes to pParse->rc.
  112430. */
  112431. static void schemaIsValid(Parse *pParse){
  112432. sqlite3 *db = pParse->db;
  112433. int iDb;
  112434. int rc;
  112435. int cookie;
  112436. assert( pParse->checkSchema );
  112437. assert( sqlite3_mutex_held(db->mutex) );
  112438. for(iDb=0; iDb<db->nDb; iDb++){
  112439. int openedTransaction = 0; /* True if a transaction is opened */
  112440. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  112441. if( pBt==0 ) continue;
  112442. /* If there is not already a read-only (or read-write) transaction opened
  112443. ** on the b-tree database, open one now. If a transaction is opened, it
  112444. ** will be closed immediately after reading the meta-value. */
  112445. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  112446. rc = sqlite3BtreeBeginTrans(pBt, 0);
  112447. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  112448. sqlite3OomFault(db);
  112449. }
  112450. if( rc!=SQLITE_OK ) return;
  112451. openedTransaction = 1;
  112452. }
  112453. /* Read the schema cookie from the database. If it does not match the
  112454. ** value stored as part of the in-memory schema representation,
  112455. ** set Parse.rc to SQLITE_SCHEMA. */
  112456. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  112457. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  112458. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  112459. sqlite3ResetOneSchema(db, iDb);
  112460. pParse->rc = SQLITE_SCHEMA;
  112461. }
  112462. /* Close the transaction, if one was opened. */
  112463. if( openedTransaction ){
  112464. sqlite3BtreeCommit(pBt);
  112465. }
  112466. }
  112467. }
  112468. /*
  112469. ** Convert a schema pointer into the iDb index that indicates
  112470. ** which database file in db->aDb[] the schema refers to.
  112471. **
  112472. ** If the same database is attached more than once, the first
  112473. ** attached database is returned.
  112474. */
  112475. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  112476. int i = -1000000;
  112477. /* If pSchema is NULL, then return -1000000. This happens when code in
  112478. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  112479. ** created by a sub-select). In this case the return value of this
  112480. ** function should never be used.
  112481. **
  112482. ** We return -1000000 instead of the more usual -1 simply because using
  112483. ** -1000000 as the incorrect index into db->aDb[] is much
  112484. ** more likely to cause a segfault than -1 (of course there are assert()
  112485. ** statements too, but it never hurts to play the odds).
  112486. */
  112487. assert( sqlite3_mutex_held(db->mutex) );
  112488. if( pSchema ){
  112489. for(i=0; 1; i++){
  112490. assert( i<db->nDb );
  112491. if( db->aDb[i].pSchema==pSchema ){
  112492. break;
  112493. }
  112494. }
  112495. assert( i>=0 && i<db->nDb );
  112496. }
  112497. return i;
  112498. }
  112499. /*
  112500. ** Free all memory allocations in the pParse object
  112501. */
  112502. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  112503. sqlite3 *db = pParse->db;
  112504. sqlite3DbFree(db, pParse->aLabel);
  112505. sqlite3ExprListDelete(db, pParse->pConstExpr);
  112506. if( db ){
  112507. assert( db->lookaside.bDisable >= pParse->disableLookaside );
  112508. db->lookaside.bDisable -= pParse->disableLookaside;
  112509. }
  112510. pParse->disableLookaside = 0;
  112511. }
  112512. /*
  112513. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  112514. */
  112515. static int sqlite3Prepare(
  112516. sqlite3 *db, /* Database handle. */
  112517. const char *zSql, /* UTF-8 encoded SQL statement. */
  112518. int nBytes, /* Length of zSql in bytes. */
  112519. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  112520. Vdbe *pReprepare, /* VM being reprepared */
  112521. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  112522. const char **pzTail /* OUT: End of parsed string */
  112523. ){
  112524. char *zErrMsg = 0; /* Error message */
  112525. int rc = SQLITE_OK; /* Result code */
  112526. int i; /* Loop counter */
  112527. Parse sParse; /* Parsing context */
  112528. memset(&sParse, 0, PARSE_HDR_SZ);
  112529. memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  112530. sParse.pReprepare = pReprepare;
  112531. assert( ppStmt && *ppStmt==0 );
  112532. /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
  112533. assert( sqlite3_mutex_held(db->mutex) );
  112534. /* For a long-term use prepared statement avoid the use of
  112535. ** lookaside memory.
  112536. */
  112537. if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
  112538. sParse.disableLookaside++;
  112539. db->lookaside.bDisable++;
  112540. }
  112541. /* Check to verify that it is possible to get a read lock on all
  112542. ** database schemas. The inability to get a read lock indicates that
  112543. ** some other database connection is holding a write-lock, which in
  112544. ** turn means that the other connection has made uncommitted changes
  112545. ** to the schema.
  112546. **
  112547. ** Were we to proceed and prepare the statement against the uncommitted
  112548. ** schema changes and if those schema changes are subsequently rolled
  112549. ** back and different changes are made in their place, then when this
  112550. ** prepared statement goes to run the schema cookie would fail to detect
  112551. ** the schema change. Disaster would follow.
  112552. **
  112553. ** This thread is currently holding mutexes on all Btrees (because
  112554. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  112555. ** is not possible for another thread to start a new schema change
  112556. ** while this routine is running. Hence, we do not need to hold
  112557. ** locks on the schema, we just need to make sure nobody else is
  112558. ** holding them.
  112559. **
  112560. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  112561. ** but it does *not* override schema lock detection, so this all still
  112562. ** works even if READ_UNCOMMITTED is set.
  112563. */
  112564. for(i=0; i<db->nDb; i++) {
  112565. Btree *pBt = db->aDb[i].pBt;
  112566. if( pBt ){
  112567. assert( sqlite3BtreeHoldsMutex(pBt) );
  112568. rc = sqlite3BtreeSchemaLocked(pBt);
  112569. if( rc ){
  112570. const char *zDb = db->aDb[i].zDbSName;
  112571. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  112572. testcase( db->flags & SQLITE_ReadUncommit );
  112573. goto end_prepare;
  112574. }
  112575. }
  112576. }
  112577. sqlite3VtabUnlockList(db);
  112578. sParse.db = db;
  112579. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  112580. char *zSqlCopy;
  112581. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  112582. testcase( nBytes==mxLen );
  112583. testcase( nBytes==mxLen+1 );
  112584. if( nBytes>mxLen ){
  112585. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  112586. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  112587. goto end_prepare;
  112588. }
  112589. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  112590. if( zSqlCopy ){
  112591. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  112592. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  112593. sqlite3DbFree(db, zSqlCopy);
  112594. }else{
  112595. sParse.zTail = &zSql[nBytes];
  112596. }
  112597. }else{
  112598. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  112599. }
  112600. assert( 0==sParse.nQueryLoop );
  112601. if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  112602. if( sParse.checkSchema ){
  112603. schemaIsValid(&sParse);
  112604. }
  112605. if( db->mallocFailed ){
  112606. sParse.rc = SQLITE_NOMEM_BKPT;
  112607. }
  112608. if( pzTail ){
  112609. *pzTail = sParse.zTail;
  112610. }
  112611. rc = sParse.rc;
  112612. #ifndef SQLITE_OMIT_EXPLAIN
  112613. if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){
  112614. static const char * const azColName[] = {
  112615. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  112616. "selectid", "order", "from", "detail"
  112617. };
  112618. int iFirst, mx;
  112619. if( sParse.explain==2 ){
  112620. sqlite3VdbeSetNumCols(sParse.pVdbe, 4);
  112621. iFirst = 8;
  112622. mx = 12;
  112623. }else{
  112624. sqlite3VdbeSetNumCols(sParse.pVdbe, 8);
  112625. iFirst = 0;
  112626. mx = 8;
  112627. }
  112628. for(i=iFirst; i<mx; i++){
  112629. sqlite3VdbeSetColName(sParse.pVdbe, i-iFirst, COLNAME_NAME,
  112630. azColName[i], SQLITE_STATIC);
  112631. }
  112632. }
  112633. #endif
  112634. if( db->init.busy==0 ){
  112635. sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
  112636. }
  112637. if( sParse.pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  112638. sqlite3VdbeFinalize(sParse.pVdbe);
  112639. assert(!(*ppStmt));
  112640. }else{
  112641. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  112642. }
  112643. if( zErrMsg ){
  112644. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  112645. sqlite3DbFree(db, zErrMsg);
  112646. }else{
  112647. sqlite3Error(db, rc);
  112648. }
  112649. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  112650. while( sParse.pTriggerPrg ){
  112651. TriggerPrg *pT = sParse.pTriggerPrg;
  112652. sParse.pTriggerPrg = pT->pNext;
  112653. sqlite3DbFree(db, pT);
  112654. }
  112655. end_prepare:
  112656. sqlite3ParserReset(&sParse);
  112657. return rc;
  112658. }
  112659. static int sqlite3LockAndPrepare(
  112660. sqlite3 *db, /* Database handle. */
  112661. const char *zSql, /* UTF-8 encoded SQL statement. */
  112662. int nBytes, /* Length of zSql in bytes. */
  112663. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  112664. Vdbe *pOld, /* VM being reprepared */
  112665. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  112666. const char **pzTail /* OUT: End of parsed string */
  112667. ){
  112668. int rc;
  112669. int cnt = 0;
  112670. #ifdef SQLITE_ENABLE_API_ARMOR
  112671. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  112672. #endif
  112673. *ppStmt = 0;
  112674. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  112675. return SQLITE_MISUSE_BKPT;
  112676. }
  112677. sqlite3_mutex_enter(db->mutex);
  112678. sqlite3BtreeEnterAll(db);
  112679. do{
  112680. /* Make multiple attempts to compile the SQL, until it either succeeds
  112681. ** or encounters a permanent error. A schema problem after one schema
  112682. ** reset is considered a permanent error. */
  112683. rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
  112684. assert( rc==SQLITE_OK || *ppStmt==0 );
  112685. }while( rc==SQLITE_ERROR_RETRY
  112686. || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
  112687. sqlite3BtreeLeaveAll(db);
  112688. rc = sqlite3ApiExit(db, rc);
  112689. assert( (rc&db->errMask)==rc );
  112690. sqlite3_mutex_leave(db->mutex);
  112691. return rc;
  112692. }
  112693. /*
  112694. ** Rerun the compilation of a statement after a schema change.
  112695. **
  112696. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  112697. ** if the statement cannot be recompiled because another connection has
  112698. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  112699. ** occurs, return SQLITE_SCHEMA.
  112700. */
  112701. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  112702. int rc;
  112703. sqlite3_stmt *pNew;
  112704. const char *zSql;
  112705. sqlite3 *db;
  112706. u8 prepFlags;
  112707. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  112708. zSql = sqlite3_sql((sqlite3_stmt *)p);
  112709. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  112710. db = sqlite3VdbeDb(p);
  112711. assert( sqlite3_mutex_held(db->mutex) );
  112712. prepFlags = sqlite3VdbePrepareFlags(p);
  112713. rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
  112714. if( rc ){
  112715. if( rc==SQLITE_NOMEM ){
  112716. sqlite3OomFault(db);
  112717. }
  112718. assert( pNew==0 );
  112719. return rc;
  112720. }else{
  112721. assert( pNew!=0 );
  112722. }
  112723. sqlite3VdbeSwap((Vdbe*)pNew, p);
  112724. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  112725. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  112726. sqlite3VdbeFinalize((Vdbe*)pNew);
  112727. return SQLITE_OK;
  112728. }
  112729. /*
  112730. ** Two versions of the official API. Legacy and new use. In the legacy
  112731. ** version, the original SQL text is not saved in the prepared statement
  112732. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  112733. ** sqlite3_step(). In the new version, the original SQL text is retained
  112734. ** and the statement is automatically recompiled if an schema change
  112735. ** occurs.
  112736. */
  112737. SQLITE_API int sqlite3_prepare(
  112738. sqlite3 *db, /* Database handle. */
  112739. const char *zSql, /* UTF-8 encoded SQL statement. */
  112740. int nBytes, /* Length of zSql in bytes. */
  112741. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  112742. const char **pzTail /* OUT: End of parsed string */
  112743. ){
  112744. int rc;
  112745. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  112746. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  112747. return rc;
  112748. }
  112749. SQLITE_API int sqlite3_prepare_v2(
  112750. sqlite3 *db, /* Database handle. */
  112751. const char *zSql, /* UTF-8 encoded SQL statement. */
  112752. int nBytes, /* Length of zSql in bytes. */
  112753. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  112754. const char **pzTail /* OUT: End of parsed string */
  112755. ){
  112756. int rc;
  112757. /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
  112758. ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
  112759. ** parameter.
  112760. **
  112761. ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
  112762. rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
  112763. ppStmt,pzTail);
  112764. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  112765. return rc;
  112766. }
  112767. SQLITE_API int sqlite3_prepare_v3(
  112768. sqlite3 *db, /* Database handle. */
  112769. const char *zSql, /* UTF-8 encoded SQL statement. */
  112770. int nBytes, /* Length of zSql in bytes. */
  112771. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  112772. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  112773. const char **pzTail /* OUT: End of parsed string */
  112774. ){
  112775. int rc;
  112776. /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
  112777. ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
  112778. ** which is a bit array consisting of zero or more of the
  112779. ** SQLITE_PREPARE_* flags.
  112780. **
  112781. ** Proof by comparison to the implementation of sqlite3_prepare_v2()
  112782. ** directly above. */
  112783. rc = sqlite3LockAndPrepare(db,zSql,nBytes,
  112784. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  112785. 0,ppStmt,pzTail);
  112786. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  112787. return rc;
  112788. }
  112789. #ifndef SQLITE_OMIT_UTF16
  112790. /*
  112791. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  112792. */
  112793. static int sqlite3Prepare16(
  112794. sqlite3 *db, /* Database handle. */
  112795. const void *zSql, /* UTF-16 encoded SQL statement. */
  112796. int nBytes, /* Length of zSql in bytes. */
  112797. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  112798. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  112799. const void **pzTail /* OUT: End of parsed string */
  112800. ){
  112801. /* This function currently works by first transforming the UTF-16
  112802. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  112803. ** tricky bit is figuring out the pointer to return in *pzTail.
  112804. */
  112805. char *zSql8;
  112806. const char *zTail8 = 0;
  112807. int rc = SQLITE_OK;
  112808. #ifdef SQLITE_ENABLE_API_ARMOR
  112809. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  112810. #endif
  112811. *ppStmt = 0;
  112812. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  112813. return SQLITE_MISUSE_BKPT;
  112814. }
  112815. if( nBytes>=0 ){
  112816. int sz;
  112817. const char *z = (const char*)zSql;
  112818. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  112819. nBytes = sz;
  112820. }
  112821. sqlite3_mutex_enter(db->mutex);
  112822. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  112823. if( zSql8 ){
  112824. rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
  112825. }
  112826. if( zTail8 && pzTail ){
  112827. /* If sqlite3_prepare returns a tail pointer, we calculate the
  112828. ** equivalent pointer into the UTF-16 string by counting the unicode
  112829. ** characters between zSql8 and zTail8, and then returning a pointer
  112830. ** the same number of characters into the UTF-16 string.
  112831. */
  112832. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  112833. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  112834. }
  112835. sqlite3DbFree(db, zSql8);
  112836. rc = sqlite3ApiExit(db, rc);
  112837. sqlite3_mutex_leave(db->mutex);
  112838. return rc;
  112839. }
  112840. /*
  112841. ** Two versions of the official API. Legacy and new use. In the legacy
  112842. ** version, the original SQL text is not saved in the prepared statement
  112843. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  112844. ** sqlite3_step(). In the new version, the original SQL text is retained
  112845. ** and the statement is automatically recompiled if an schema change
  112846. ** occurs.
  112847. */
  112848. SQLITE_API int sqlite3_prepare16(
  112849. sqlite3 *db, /* Database handle. */
  112850. const void *zSql, /* UTF-16 encoded SQL statement. */
  112851. int nBytes, /* Length of zSql in bytes. */
  112852. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  112853. const void **pzTail /* OUT: End of parsed string */
  112854. ){
  112855. int rc;
  112856. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  112857. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  112858. return rc;
  112859. }
  112860. SQLITE_API int sqlite3_prepare16_v2(
  112861. sqlite3 *db, /* Database handle. */
  112862. const void *zSql, /* UTF-16 encoded SQL statement. */
  112863. int nBytes, /* Length of zSql in bytes. */
  112864. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  112865. const void **pzTail /* OUT: End of parsed string */
  112866. ){
  112867. int rc;
  112868. rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
  112869. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  112870. return rc;
  112871. }
  112872. SQLITE_API int sqlite3_prepare16_v3(
  112873. sqlite3 *db, /* Database handle. */
  112874. const void *zSql, /* UTF-16 encoded SQL statement. */
  112875. int nBytes, /* Length of zSql in bytes. */
  112876. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  112877. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  112878. const void **pzTail /* OUT: End of parsed string */
  112879. ){
  112880. int rc;
  112881. rc = sqlite3Prepare16(db,zSql,nBytes,
  112882. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  112883. ppStmt,pzTail);
  112884. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  112885. return rc;
  112886. }
  112887. #endif /* SQLITE_OMIT_UTF16 */
  112888. /************** End of prepare.c *********************************************/
  112889. /************** Begin file select.c ******************************************/
  112890. /*
  112891. ** 2001 September 15
  112892. **
  112893. ** The author disclaims copyright to this source code. In place of
  112894. ** a legal notice, here is a blessing:
  112895. **
  112896. ** May you do good and not evil.
  112897. ** May you find forgiveness for yourself and forgive others.
  112898. ** May you share freely, never taking more than you give.
  112899. **
  112900. *************************************************************************
  112901. ** This file contains C code routines that are called by the parser
  112902. ** to handle SELECT statements in SQLite.
  112903. */
  112904. /* #include "sqliteInt.h" */
  112905. /*
  112906. ** Trace output macros
  112907. */
  112908. #if SELECTTRACE_ENABLED
  112909. /***/ int sqlite3SelectTrace = 0;
  112910. # define SELECTTRACE(K,P,S,X) \
  112911. if(sqlite3SelectTrace&(K)) \
  112912. sqlite3DebugPrintf("%s/%p: ",(S)->zSelName,(S)),\
  112913. sqlite3DebugPrintf X
  112914. #else
  112915. # define SELECTTRACE(K,P,S,X)
  112916. #endif
  112917. /*
  112918. ** An instance of the following object is used to record information about
  112919. ** how to process the DISTINCT keyword, to simplify passing that information
  112920. ** into the selectInnerLoop() routine.
  112921. */
  112922. typedef struct DistinctCtx DistinctCtx;
  112923. struct DistinctCtx {
  112924. u8 isTnct; /* True if the DISTINCT keyword is present */
  112925. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  112926. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  112927. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  112928. };
  112929. /*
  112930. ** An instance of the following object is used to record information about
  112931. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  112932. */
  112933. typedef struct SortCtx SortCtx;
  112934. struct SortCtx {
  112935. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  112936. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  112937. int iECursor; /* Cursor number for the sorter */
  112938. int regReturn; /* Register holding block-output return address */
  112939. int labelBkOut; /* Start label for the block-output subroutine */
  112940. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  112941. int labelDone; /* Jump here when done, ex: LIMIT reached */
  112942. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  112943. u8 bOrderedInnerLoop; /* ORDER BY correctly sorts the inner loop */
  112944. };
  112945. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  112946. /*
  112947. ** Delete all the content of a Select structure. Deallocate the structure
  112948. ** itself only if bFree is true.
  112949. */
  112950. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  112951. while( p ){
  112952. Select *pPrior = p->pPrior;
  112953. sqlite3ExprListDelete(db, p->pEList);
  112954. sqlite3SrcListDelete(db, p->pSrc);
  112955. sqlite3ExprDelete(db, p->pWhere);
  112956. sqlite3ExprListDelete(db, p->pGroupBy);
  112957. sqlite3ExprDelete(db, p->pHaving);
  112958. sqlite3ExprListDelete(db, p->pOrderBy);
  112959. sqlite3ExprDelete(db, p->pLimit);
  112960. if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
  112961. if( bFree ) sqlite3DbFreeNN(db, p);
  112962. p = pPrior;
  112963. bFree = 1;
  112964. }
  112965. }
  112966. /*
  112967. ** Initialize a SelectDest structure.
  112968. */
  112969. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  112970. pDest->eDest = (u8)eDest;
  112971. pDest->iSDParm = iParm;
  112972. pDest->zAffSdst = 0;
  112973. pDest->iSdst = 0;
  112974. pDest->nSdst = 0;
  112975. }
  112976. /*
  112977. ** Allocate a new Select structure and return a pointer to that
  112978. ** structure.
  112979. */
  112980. SQLITE_PRIVATE Select *sqlite3SelectNew(
  112981. Parse *pParse, /* Parsing context */
  112982. ExprList *pEList, /* which columns to include in the result */
  112983. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  112984. Expr *pWhere, /* the WHERE clause */
  112985. ExprList *pGroupBy, /* the GROUP BY clause */
  112986. Expr *pHaving, /* the HAVING clause */
  112987. ExprList *pOrderBy, /* the ORDER BY clause */
  112988. u32 selFlags, /* Flag parameters, such as SF_Distinct */
  112989. Expr *pLimit /* LIMIT value. NULL means not used */
  112990. ){
  112991. Select *pNew;
  112992. Select standin;
  112993. pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
  112994. if( pNew==0 ){
  112995. assert( pParse->db->mallocFailed );
  112996. pNew = &standin;
  112997. }
  112998. if( pEList==0 ){
  112999. pEList = sqlite3ExprListAppend(pParse, 0,
  113000. sqlite3Expr(pParse->db,TK_ASTERISK,0));
  113001. }
  113002. pNew->pEList = pEList;
  113003. pNew->op = TK_SELECT;
  113004. pNew->selFlags = selFlags;
  113005. pNew->iLimit = 0;
  113006. pNew->iOffset = 0;
  113007. #if SELECTTRACE_ENABLED
  113008. pNew->zSelName[0] = 0;
  113009. #endif
  113010. pNew->addrOpenEphm[0] = -1;
  113011. pNew->addrOpenEphm[1] = -1;
  113012. pNew->nSelectRow = 0;
  113013. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
  113014. pNew->pSrc = pSrc;
  113015. pNew->pWhere = pWhere;
  113016. pNew->pGroupBy = pGroupBy;
  113017. pNew->pHaving = pHaving;
  113018. pNew->pOrderBy = pOrderBy;
  113019. pNew->pPrior = 0;
  113020. pNew->pNext = 0;
  113021. pNew->pLimit = pLimit;
  113022. pNew->pWith = 0;
  113023. if( pParse->db->mallocFailed ) {
  113024. clearSelect(pParse->db, pNew, pNew!=&standin);
  113025. pNew = 0;
  113026. }else{
  113027. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  113028. }
  113029. assert( pNew!=&standin );
  113030. return pNew;
  113031. }
  113032. #if SELECTTRACE_ENABLED
  113033. /*
  113034. ** Set the name of a Select object
  113035. */
  113036. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  113037. if( p && zName ){
  113038. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  113039. }
  113040. }
  113041. #endif
  113042. /*
  113043. ** Delete the given Select structure and all of its substructures.
  113044. */
  113045. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  113046. if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
  113047. }
  113048. /*
  113049. ** Return a pointer to the right-most SELECT statement in a compound.
  113050. */
  113051. static Select *findRightmost(Select *p){
  113052. while( p->pNext ) p = p->pNext;
  113053. return p;
  113054. }
  113055. /*
  113056. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  113057. ** type of join. Return an integer constant that expresses that type
  113058. ** in terms of the following bit values:
  113059. **
  113060. ** JT_INNER
  113061. ** JT_CROSS
  113062. ** JT_OUTER
  113063. ** JT_NATURAL
  113064. ** JT_LEFT
  113065. ** JT_RIGHT
  113066. **
  113067. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  113068. **
  113069. ** If an illegal or unsupported join type is seen, then still return
  113070. ** a join type, but put an error in the pParse structure.
  113071. */
  113072. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  113073. int jointype = 0;
  113074. Token *apAll[3];
  113075. Token *p;
  113076. /* 0123456789 123456789 123456789 123 */
  113077. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  113078. static const struct {
  113079. u8 i; /* Beginning of keyword text in zKeyText[] */
  113080. u8 nChar; /* Length of the keyword in characters */
  113081. u8 code; /* Join type mask */
  113082. } aKeyword[] = {
  113083. /* natural */ { 0, 7, JT_NATURAL },
  113084. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  113085. /* outer */ { 10, 5, JT_OUTER },
  113086. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  113087. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  113088. /* inner */ { 23, 5, JT_INNER },
  113089. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  113090. };
  113091. int i, j;
  113092. apAll[0] = pA;
  113093. apAll[1] = pB;
  113094. apAll[2] = pC;
  113095. for(i=0; i<3 && apAll[i]; i++){
  113096. p = apAll[i];
  113097. for(j=0; j<ArraySize(aKeyword); j++){
  113098. if( p->n==aKeyword[j].nChar
  113099. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  113100. jointype |= aKeyword[j].code;
  113101. break;
  113102. }
  113103. }
  113104. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  113105. if( j>=ArraySize(aKeyword) ){
  113106. jointype |= JT_ERROR;
  113107. break;
  113108. }
  113109. }
  113110. if(
  113111. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  113112. (jointype & JT_ERROR)!=0
  113113. ){
  113114. const char *zSp = " ";
  113115. assert( pB!=0 );
  113116. if( pC==0 ){ zSp++; }
  113117. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  113118. "%T %T%s%T", pA, pB, zSp, pC);
  113119. jointype = JT_INNER;
  113120. }else if( (jointype & JT_OUTER)!=0
  113121. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  113122. sqlite3ErrorMsg(pParse,
  113123. "RIGHT and FULL OUTER JOINs are not currently supported");
  113124. jointype = JT_INNER;
  113125. }
  113126. return jointype;
  113127. }
  113128. /*
  113129. ** Return the index of a column in a table. Return -1 if the column
  113130. ** is not contained in the table.
  113131. */
  113132. static int columnIndex(Table *pTab, const char *zCol){
  113133. int i;
  113134. for(i=0; i<pTab->nCol; i++){
  113135. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  113136. }
  113137. return -1;
  113138. }
  113139. /*
  113140. ** Search the first N tables in pSrc, from left to right, looking for a
  113141. ** table that has a column named zCol.
  113142. **
  113143. ** When found, set *piTab and *piCol to the table index and column index
  113144. ** of the matching column and return TRUE.
  113145. **
  113146. ** If not found, return FALSE.
  113147. */
  113148. static int tableAndColumnIndex(
  113149. SrcList *pSrc, /* Array of tables to search */
  113150. int N, /* Number of tables in pSrc->a[] to search */
  113151. const char *zCol, /* Name of the column we are looking for */
  113152. int *piTab, /* Write index of pSrc->a[] here */
  113153. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  113154. ){
  113155. int i; /* For looping over tables in pSrc */
  113156. int iCol; /* Index of column matching zCol */
  113157. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  113158. for(i=0; i<N; i++){
  113159. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  113160. if( iCol>=0 ){
  113161. if( piTab ){
  113162. *piTab = i;
  113163. *piCol = iCol;
  113164. }
  113165. return 1;
  113166. }
  113167. }
  113168. return 0;
  113169. }
  113170. /*
  113171. ** This function is used to add terms implied by JOIN syntax to the
  113172. ** WHERE clause expression of a SELECT statement. The new term, which
  113173. ** is ANDed with the existing WHERE clause, is of the form:
  113174. **
  113175. ** (tab1.col1 = tab2.col2)
  113176. **
  113177. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  113178. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  113179. ** column iColRight of tab2.
  113180. */
  113181. static void addWhereTerm(
  113182. Parse *pParse, /* Parsing context */
  113183. SrcList *pSrc, /* List of tables in FROM clause */
  113184. int iLeft, /* Index of first table to join in pSrc */
  113185. int iColLeft, /* Index of column in first table */
  113186. int iRight, /* Index of second table in pSrc */
  113187. int iColRight, /* Index of column in second table */
  113188. int isOuterJoin, /* True if this is an OUTER join */
  113189. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  113190. ){
  113191. sqlite3 *db = pParse->db;
  113192. Expr *pE1;
  113193. Expr *pE2;
  113194. Expr *pEq;
  113195. assert( iLeft<iRight );
  113196. assert( pSrc->nSrc>iRight );
  113197. assert( pSrc->a[iLeft].pTab );
  113198. assert( pSrc->a[iRight].pTab );
  113199. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  113200. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  113201. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
  113202. if( pEq && isOuterJoin ){
  113203. ExprSetProperty(pEq, EP_FromJoin);
  113204. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  113205. ExprSetVVAProperty(pEq, EP_NoReduce);
  113206. pEq->iRightJoinTable = (i16)pE2->iTable;
  113207. }
  113208. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  113209. }
  113210. /*
  113211. ** Set the EP_FromJoin property on all terms of the given expression.
  113212. ** And set the Expr.iRightJoinTable to iTable for every term in the
  113213. ** expression.
  113214. **
  113215. ** The EP_FromJoin property is used on terms of an expression to tell
  113216. ** the LEFT OUTER JOIN processing logic that this term is part of the
  113217. ** join restriction specified in the ON or USING clause and not a part
  113218. ** of the more general WHERE clause. These terms are moved over to the
  113219. ** WHERE clause during join processing but we need to remember that they
  113220. ** originated in the ON or USING clause.
  113221. **
  113222. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  113223. ** expression depends on table iRightJoinTable even if that table is not
  113224. ** explicitly mentioned in the expression. That information is needed
  113225. ** for cases like this:
  113226. **
  113227. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  113228. **
  113229. ** The where clause needs to defer the handling of the t1.x=5
  113230. ** term until after the t2 loop of the join. In that way, a
  113231. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  113232. ** defer the handling of t1.x=5, it will be processed immediately
  113233. ** after the t1 loop and rows with t1.x!=5 will never appear in
  113234. ** the output, which is incorrect.
  113235. */
  113236. static void setJoinExpr(Expr *p, int iTable){
  113237. while( p ){
  113238. ExprSetProperty(p, EP_FromJoin);
  113239. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  113240. ExprSetVVAProperty(p, EP_NoReduce);
  113241. p->iRightJoinTable = (i16)iTable;
  113242. if( p->op==TK_FUNCTION && p->x.pList ){
  113243. int i;
  113244. for(i=0; i<p->x.pList->nExpr; i++){
  113245. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  113246. }
  113247. }
  113248. setJoinExpr(p->pLeft, iTable);
  113249. p = p->pRight;
  113250. }
  113251. }
  113252. /* Undo the work of setJoinExpr(). In the expression tree p, convert every
  113253. ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
  113254. ** an ordinary term that omits the EP_FromJoin mark.
  113255. **
  113256. ** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
  113257. */
  113258. static void unsetJoinExpr(Expr *p, int iTable){
  113259. while( p ){
  113260. if( ExprHasProperty(p, EP_FromJoin)
  113261. && (iTable<0 || p->iRightJoinTable==iTable) ){
  113262. ExprClearProperty(p, EP_FromJoin);
  113263. }
  113264. if( p->op==TK_FUNCTION && p->x.pList ){
  113265. int i;
  113266. for(i=0; i<p->x.pList->nExpr; i++){
  113267. unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
  113268. }
  113269. }
  113270. unsetJoinExpr(p->pLeft, iTable);
  113271. p = p->pRight;
  113272. }
  113273. }
  113274. /*
  113275. ** This routine processes the join information for a SELECT statement.
  113276. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  113277. ** NATURAL joins also create extra WHERE clause terms.
  113278. **
  113279. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  113280. ** The left most table is the first entry in Select.pSrc. The right-most
  113281. ** table is the last entry. The join operator is held in the entry to
  113282. ** the left. Thus entry 0 contains the join operator for the join between
  113283. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  113284. ** also attached to the left entry.
  113285. **
  113286. ** This routine returns the number of errors encountered.
  113287. */
  113288. static int sqliteProcessJoin(Parse *pParse, Select *p){
  113289. SrcList *pSrc; /* All tables in the FROM clause */
  113290. int i, j; /* Loop counters */
  113291. struct SrcList_item *pLeft; /* Left table being joined */
  113292. struct SrcList_item *pRight; /* Right table being joined */
  113293. pSrc = p->pSrc;
  113294. pLeft = &pSrc->a[0];
  113295. pRight = &pLeft[1];
  113296. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  113297. Table *pRightTab = pRight->pTab;
  113298. int isOuter;
  113299. if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
  113300. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  113301. /* When the NATURAL keyword is present, add WHERE clause terms for
  113302. ** every column that the two tables have in common.
  113303. */
  113304. if( pRight->fg.jointype & JT_NATURAL ){
  113305. if( pRight->pOn || pRight->pUsing ){
  113306. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  113307. "an ON or USING clause", 0);
  113308. return 1;
  113309. }
  113310. for(j=0; j<pRightTab->nCol; j++){
  113311. char *zName; /* Name of column in the right table */
  113312. int iLeft; /* Matching left table */
  113313. int iLeftCol; /* Matching column in the left table */
  113314. zName = pRightTab->aCol[j].zName;
  113315. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  113316. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  113317. isOuter, &p->pWhere);
  113318. }
  113319. }
  113320. }
  113321. /* Disallow both ON and USING clauses in the same join
  113322. */
  113323. if( pRight->pOn && pRight->pUsing ){
  113324. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  113325. "clauses in the same join");
  113326. return 1;
  113327. }
  113328. /* Add the ON clause to the end of the WHERE clause, connected by
  113329. ** an AND operator.
  113330. */
  113331. if( pRight->pOn ){
  113332. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  113333. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  113334. pRight->pOn = 0;
  113335. }
  113336. /* Create extra terms on the WHERE clause for each column named
  113337. ** in the USING clause. Example: If the two tables to be joined are
  113338. ** A and B and the USING clause names X, Y, and Z, then add this
  113339. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  113340. ** Report an error if any column mentioned in the USING clause is
  113341. ** not contained in both tables to be joined.
  113342. */
  113343. if( pRight->pUsing ){
  113344. IdList *pList = pRight->pUsing;
  113345. for(j=0; j<pList->nId; j++){
  113346. char *zName; /* Name of the term in the USING clause */
  113347. int iLeft; /* Table on the left with matching column name */
  113348. int iLeftCol; /* Column number of matching column on the left */
  113349. int iRightCol; /* Column number of matching column on the right */
  113350. zName = pList->a[j].zName;
  113351. iRightCol = columnIndex(pRightTab, zName);
  113352. if( iRightCol<0
  113353. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  113354. ){
  113355. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  113356. "not present in both tables", zName);
  113357. return 1;
  113358. }
  113359. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  113360. isOuter, &p->pWhere);
  113361. }
  113362. }
  113363. }
  113364. return 0;
  113365. }
  113366. /* Forward reference */
  113367. static KeyInfo *keyInfoFromExprList(
  113368. Parse *pParse, /* Parsing context */
  113369. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  113370. int iStart, /* Begin with this column of pList */
  113371. int nExtra /* Add this many extra columns to the end */
  113372. );
  113373. /*
  113374. ** Generate code that will push the record in registers regData
  113375. ** through regData+nData-1 onto the sorter.
  113376. */
  113377. static void pushOntoSorter(
  113378. Parse *pParse, /* Parser context */
  113379. SortCtx *pSort, /* Information about the ORDER BY clause */
  113380. Select *pSelect, /* The whole SELECT statement */
  113381. int regData, /* First register holding data to be sorted */
  113382. int regOrigData, /* First register holding data before packing */
  113383. int nData, /* Number of elements in the data array */
  113384. int nPrefixReg /* No. of reg prior to regData available for use */
  113385. ){
  113386. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  113387. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  113388. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  113389. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  113390. int regBase; /* Regs for sorter record */
  113391. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  113392. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  113393. int op; /* Opcode to add sorter record to sorter */
  113394. int iLimit; /* LIMIT counter */
  113395. assert( bSeq==0 || bSeq==1 );
  113396. assert( nData==1 || regData==regOrigData || regOrigData==0 );
  113397. if( nPrefixReg ){
  113398. assert( nPrefixReg==nExpr+bSeq );
  113399. regBase = regData - nExpr - bSeq;
  113400. }else{
  113401. regBase = pParse->nMem + 1;
  113402. pParse->nMem += nBase;
  113403. }
  113404. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  113405. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  113406. pSort->labelDone = sqlite3VdbeMakeLabel(v);
  113407. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  113408. SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
  113409. if( bSeq ){
  113410. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  113411. }
  113412. if( nPrefixReg==0 && nData>0 ){
  113413. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  113414. }
  113415. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  113416. if( nOBSat>0 ){
  113417. int regPrevKey; /* The first nOBSat columns of the previous row */
  113418. int addrFirst; /* Address of the OP_IfNot opcode */
  113419. int addrJmp; /* Address of the OP_Jump opcode */
  113420. VdbeOp *pOp; /* Opcode that opens the sorter */
  113421. int nKey; /* Number of sorting key columns, including OP_Sequence */
  113422. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  113423. regPrevKey = pParse->nMem+1;
  113424. pParse->nMem += pSort->nOBSat;
  113425. nKey = nExpr - pSort->nOBSat + bSeq;
  113426. if( bSeq ){
  113427. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  113428. }else{
  113429. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  113430. }
  113431. VdbeCoverage(v);
  113432. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  113433. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  113434. if( pParse->db->mallocFailed ) return;
  113435. pOp->p2 = nKey + nData;
  113436. pKI = pOp->p4.pKeyInfo;
  113437. memset(pKI->aSortOrder, 0, pKI->nKeyField); /* Makes OP_Jump testable */
  113438. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  113439. testcase( pKI->nAllField > pKI->nKeyField+2 );
  113440. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
  113441. pKI->nAllField-pKI->nKeyField-1);
  113442. addrJmp = sqlite3VdbeCurrentAddr(v);
  113443. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  113444. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  113445. pSort->regReturn = ++pParse->nMem;
  113446. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  113447. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  113448. if( iLimit ){
  113449. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  113450. VdbeCoverage(v);
  113451. }
  113452. sqlite3VdbeJumpHere(v, addrFirst);
  113453. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  113454. sqlite3VdbeJumpHere(v, addrJmp);
  113455. }
  113456. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  113457. op = OP_SorterInsert;
  113458. }else{
  113459. op = OP_IdxInsert;
  113460. }
  113461. sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
  113462. regBase+nOBSat, nBase-nOBSat);
  113463. if( iLimit ){
  113464. int addr;
  113465. int r1 = 0;
  113466. /* Fill the sorter until it contains LIMIT+OFFSET entries. (The iLimit
  113467. ** register is initialized with value of LIMIT+OFFSET.) After the sorter
  113468. ** fills up, delete the least entry in the sorter after each insert.
  113469. ** Thus we never hold more than the LIMIT+OFFSET rows in memory at once */
  113470. addr = sqlite3VdbeAddOp1(v, OP_IfNotZero, iLimit); VdbeCoverage(v);
  113471. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  113472. if( pSort->bOrderedInnerLoop ){
  113473. r1 = ++pParse->nMem;
  113474. sqlite3VdbeAddOp3(v, OP_Column, pSort->iECursor, nExpr, r1);
  113475. VdbeComment((v, "seq"));
  113476. }
  113477. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  113478. if( pSort->bOrderedInnerLoop ){
  113479. /* If the inner loop is driven by an index such that values from
  113480. ** the same iteration of the inner loop are in sorted order, then
  113481. ** immediately jump to the next iteration of an inner loop if the
  113482. ** entry from the current iteration does not fit into the top
  113483. ** LIMIT+OFFSET entries of the sorter. */
  113484. int iBrk = sqlite3VdbeCurrentAddr(v) + 2;
  113485. sqlite3VdbeAddOp3(v, OP_Eq, regBase+nExpr, iBrk, r1);
  113486. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  113487. VdbeCoverage(v);
  113488. }
  113489. sqlite3VdbeJumpHere(v, addr);
  113490. }
  113491. }
  113492. /*
  113493. ** Add code to implement the OFFSET
  113494. */
  113495. static void codeOffset(
  113496. Vdbe *v, /* Generate code into this VM */
  113497. int iOffset, /* Register holding the offset counter */
  113498. int iContinue /* Jump here to skip the current record */
  113499. ){
  113500. if( iOffset>0 ){
  113501. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  113502. VdbeComment((v, "OFFSET"));
  113503. }
  113504. }
  113505. /*
  113506. ** Add code that will check to make sure the N registers starting at iMem
  113507. ** form a distinct entry. iTab is a sorting index that holds previously
  113508. ** seen combinations of the N values. A new entry is made in iTab
  113509. ** if the current N values are new.
  113510. **
  113511. ** A jump to addrRepeat is made and the N+1 values are popped from the
  113512. ** stack if the top N elements are not distinct.
  113513. */
  113514. static void codeDistinct(
  113515. Parse *pParse, /* Parsing and code generating context */
  113516. int iTab, /* A sorting index used to test for distinctness */
  113517. int addrRepeat, /* Jump to here if not distinct */
  113518. int N, /* Number of elements */
  113519. int iMem /* First element */
  113520. ){
  113521. Vdbe *v;
  113522. int r1;
  113523. v = pParse->pVdbe;
  113524. r1 = sqlite3GetTempReg(pParse);
  113525. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  113526. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  113527. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
  113528. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  113529. sqlite3ReleaseTempReg(pParse, r1);
  113530. }
  113531. /*
  113532. ** This routine generates the code for the inside of the inner loop
  113533. ** of a SELECT.
  113534. **
  113535. ** If srcTab is negative, then the p->pEList expressions
  113536. ** are evaluated in order to get the data for this row. If srcTab is
  113537. ** zero or more, then data is pulled from srcTab and p->pEList is used only
  113538. ** to get the number of columns and the collation sequence for each column.
  113539. */
  113540. static void selectInnerLoop(
  113541. Parse *pParse, /* The parser context */
  113542. Select *p, /* The complete select statement being coded */
  113543. int srcTab, /* Pull data from this table if non-negative */
  113544. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  113545. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  113546. SelectDest *pDest, /* How to dispose of the results */
  113547. int iContinue, /* Jump here to continue with next row */
  113548. int iBreak /* Jump here to break out of the inner loop */
  113549. ){
  113550. Vdbe *v = pParse->pVdbe;
  113551. int i;
  113552. int hasDistinct; /* True if the DISTINCT keyword is present */
  113553. int eDest = pDest->eDest; /* How to dispose of results */
  113554. int iParm = pDest->iSDParm; /* First argument to disposal method */
  113555. int nResultCol; /* Number of result columns */
  113556. int nPrefixReg = 0; /* Number of extra registers before regResult */
  113557. /* Usually, regResult is the first cell in an array of memory cells
  113558. ** containing the current result row. In this case regOrig is set to the
  113559. ** same value. However, if the results are being sent to the sorter, the
  113560. ** values for any expressions that are also part of the sort-key are omitted
  113561. ** from this array. In this case regOrig is set to zero. */
  113562. int regResult; /* Start of memory holding current results */
  113563. int regOrig; /* Start of memory holding full result (or 0) */
  113564. assert( v );
  113565. assert( p->pEList!=0 );
  113566. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  113567. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  113568. if( pSort==0 && !hasDistinct ){
  113569. assert( iContinue!=0 );
  113570. codeOffset(v, p->iOffset, iContinue);
  113571. }
  113572. /* Pull the requested columns.
  113573. */
  113574. nResultCol = p->pEList->nExpr;
  113575. if( pDest->iSdst==0 ){
  113576. if( pSort ){
  113577. nPrefixReg = pSort->pOrderBy->nExpr;
  113578. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  113579. pParse->nMem += nPrefixReg;
  113580. }
  113581. pDest->iSdst = pParse->nMem+1;
  113582. pParse->nMem += nResultCol;
  113583. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  113584. /* This is an error condition that can result, for example, when a SELECT
  113585. ** on the right-hand side of an INSERT contains more result columns than
  113586. ** there are columns in the table on the left. The error will be caught
  113587. ** and reported later. But we need to make sure enough memory is allocated
  113588. ** to avoid other spurious errors in the meantime. */
  113589. pParse->nMem += nResultCol;
  113590. }
  113591. pDest->nSdst = nResultCol;
  113592. regOrig = regResult = pDest->iSdst;
  113593. if( srcTab>=0 ){
  113594. for(i=0; i<nResultCol; i++){
  113595. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  113596. VdbeComment((v, "%s", p->pEList->a[i].zName));
  113597. }
  113598. }else if( eDest!=SRT_Exists ){
  113599. /* If the destination is an EXISTS(...) expression, the actual
  113600. ** values returned by the SELECT are not required.
  113601. */
  113602. u8 ecelFlags;
  113603. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  113604. ecelFlags = SQLITE_ECEL_DUP;
  113605. }else{
  113606. ecelFlags = 0;
  113607. }
  113608. if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
  113609. /* For each expression in p->pEList that is a copy of an expression in
  113610. ** the ORDER BY clause (pSort->pOrderBy), set the associated
  113611. ** iOrderByCol value to one more than the index of the ORDER BY
  113612. ** expression within the sort-key that pushOntoSorter() will generate.
  113613. ** This allows the p->pEList field to be omitted from the sorted record,
  113614. ** saving space and CPU cycles. */
  113615. ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
  113616. for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
  113617. int j;
  113618. if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
  113619. p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
  113620. }
  113621. }
  113622. regOrig = 0;
  113623. assert( eDest==SRT_Set || eDest==SRT_Mem
  113624. || eDest==SRT_Coroutine || eDest==SRT_Output );
  113625. }
  113626. nResultCol = sqlite3ExprCodeExprList(pParse,p->pEList,regResult,
  113627. 0,ecelFlags);
  113628. }
  113629. /* If the DISTINCT keyword was present on the SELECT statement
  113630. ** and this row has been seen before, then do not make this row
  113631. ** part of the result.
  113632. */
  113633. if( hasDistinct ){
  113634. switch( pDistinct->eTnctType ){
  113635. case WHERE_DISTINCT_ORDERED: {
  113636. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  113637. int iJump; /* Jump destination */
  113638. int regPrev; /* Previous row content */
  113639. /* Allocate space for the previous row */
  113640. regPrev = pParse->nMem+1;
  113641. pParse->nMem += nResultCol;
  113642. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  113643. ** sets the MEM_Cleared bit on the first register of the
  113644. ** previous value. This will cause the OP_Ne below to always
  113645. ** fail on the first iteration of the loop even if the first
  113646. ** row is all NULLs.
  113647. */
  113648. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  113649. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  113650. pOp->opcode = OP_Null;
  113651. pOp->p1 = 1;
  113652. pOp->p2 = regPrev;
  113653. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  113654. for(i=0; i<nResultCol; i++){
  113655. CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
  113656. if( i<nResultCol-1 ){
  113657. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  113658. VdbeCoverage(v);
  113659. }else{
  113660. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  113661. VdbeCoverage(v);
  113662. }
  113663. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  113664. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  113665. }
  113666. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  113667. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  113668. break;
  113669. }
  113670. case WHERE_DISTINCT_UNIQUE: {
  113671. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  113672. break;
  113673. }
  113674. default: {
  113675. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  113676. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  113677. regResult);
  113678. break;
  113679. }
  113680. }
  113681. if( pSort==0 ){
  113682. codeOffset(v, p->iOffset, iContinue);
  113683. }
  113684. }
  113685. switch( eDest ){
  113686. /* In this mode, write each query result to the key of the temporary
  113687. ** table iParm.
  113688. */
  113689. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  113690. case SRT_Union: {
  113691. int r1;
  113692. r1 = sqlite3GetTempReg(pParse);
  113693. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  113694. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  113695. sqlite3ReleaseTempReg(pParse, r1);
  113696. break;
  113697. }
  113698. /* Construct a record from the query result, but instead of
  113699. ** saving that record, use it as a key to delete elements from
  113700. ** the temporary table iParm.
  113701. */
  113702. case SRT_Except: {
  113703. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  113704. break;
  113705. }
  113706. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  113707. /* Store the result as data using a unique key.
  113708. */
  113709. case SRT_Fifo:
  113710. case SRT_DistFifo:
  113711. case SRT_Table:
  113712. case SRT_EphemTab: {
  113713. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  113714. testcase( eDest==SRT_Table );
  113715. testcase( eDest==SRT_EphemTab );
  113716. testcase( eDest==SRT_Fifo );
  113717. testcase( eDest==SRT_DistFifo );
  113718. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  113719. #ifndef SQLITE_OMIT_CTE
  113720. if( eDest==SRT_DistFifo ){
  113721. /* If the destination is DistFifo, then cursor (iParm+1) is open
  113722. ** on an ephemeral index. If the current row is already present
  113723. ** in the index, do not write it to the output. If not, add the
  113724. ** current row to the index and proceed with writing it to the
  113725. ** output table as well. */
  113726. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  113727. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  113728. VdbeCoverage(v);
  113729. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
  113730. assert( pSort==0 );
  113731. }
  113732. #endif
  113733. if( pSort ){
  113734. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
  113735. }else{
  113736. int r2 = sqlite3GetTempReg(pParse);
  113737. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  113738. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  113739. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  113740. sqlite3ReleaseTempReg(pParse, r2);
  113741. }
  113742. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  113743. break;
  113744. }
  113745. #ifndef SQLITE_OMIT_SUBQUERY
  113746. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  113747. ** then there should be a single item on the stack. Write this
  113748. ** item into the set table with bogus data.
  113749. */
  113750. case SRT_Set: {
  113751. if( pSort ){
  113752. /* At first glance you would think we could optimize out the
  113753. ** ORDER BY in this case since the order of entries in the set
  113754. ** does not matter. But there might be a LIMIT clause, in which
  113755. ** case the order does matter */
  113756. pushOntoSorter(
  113757. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  113758. }else{
  113759. int r1 = sqlite3GetTempReg(pParse);
  113760. assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
  113761. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
  113762. r1, pDest->zAffSdst, nResultCol);
  113763. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  113764. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  113765. sqlite3ReleaseTempReg(pParse, r1);
  113766. }
  113767. break;
  113768. }
  113769. /* If any row exist in the result set, record that fact and abort.
  113770. */
  113771. case SRT_Exists: {
  113772. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  113773. /* The LIMIT clause will terminate the loop for us */
  113774. break;
  113775. }
  113776. /* If this is a scalar select that is part of an expression, then
  113777. ** store the results in the appropriate memory cell or array of
  113778. ** memory cells and break out of the scan loop.
  113779. */
  113780. case SRT_Mem: {
  113781. if( pSort ){
  113782. assert( nResultCol<=pDest->nSdst );
  113783. pushOntoSorter(
  113784. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  113785. }else{
  113786. assert( nResultCol==pDest->nSdst );
  113787. assert( regResult==iParm );
  113788. /* The LIMIT clause will jump out of the loop for us */
  113789. }
  113790. break;
  113791. }
  113792. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  113793. case SRT_Coroutine: /* Send data to a co-routine */
  113794. case SRT_Output: { /* Return the results */
  113795. testcase( eDest==SRT_Coroutine );
  113796. testcase( eDest==SRT_Output );
  113797. if( pSort ){
  113798. pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
  113799. nPrefixReg);
  113800. }else if( eDest==SRT_Coroutine ){
  113801. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  113802. }else{
  113803. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  113804. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  113805. }
  113806. break;
  113807. }
  113808. #ifndef SQLITE_OMIT_CTE
  113809. /* Write the results into a priority queue that is order according to
  113810. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  113811. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  113812. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  113813. ** final OP_Sequence column. The last column is the record as a blob.
  113814. */
  113815. case SRT_DistQueue:
  113816. case SRT_Queue: {
  113817. int nKey;
  113818. int r1, r2, r3;
  113819. int addrTest = 0;
  113820. ExprList *pSO;
  113821. pSO = pDest->pOrderBy;
  113822. assert( pSO );
  113823. nKey = pSO->nExpr;
  113824. r1 = sqlite3GetTempReg(pParse);
  113825. r2 = sqlite3GetTempRange(pParse, nKey+2);
  113826. r3 = r2+nKey+1;
  113827. if( eDest==SRT_DistQueue ){
  113828. /* If the destination is DistQueue, then cursor (iParm+1) is open
  113829. ** on a second ephemeral index that holds all values every previously
  113830. ** added to the queue. */
  113831. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  113832. regResult, nResultCol);
  113833. VdbeCoverage(v);
  113834. }
  113835. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  113836. if( eDest==SRT_DistQueue ){
  113837. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  113838. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  113839. }
  113840. for(i=0; i<nKey; i++){
  113841. sqlite3VdbeAddOp2(v, OP_SCopy,
  113842. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  113843. r2+i);
  113844. }
  113845. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  113846. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  113847. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
  113848. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  113849. sqlite3ReleaseTempReg(pParse, r1);
  113850. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  113851. break;
  113852. }
  113853. #endif /* SQLITE_OMIT_CTE */
  113854. #if !defined(SQLITE_OMIT_TRIGGER)
  113855. /* Discard the results. This is used for SELECT statements inside
  113856. ** the body of a TRIGGER. The purpose of such selects is to call
  113857. ** user-defined functions that have side effects. We do not care
  113858. ** about the actual results of the select.
  113859. */
  113860. default: {
  113861. assert( eDest==SRT_Discard );
  113862. break;
  113863. }
  113864. #endif
  113865. }
  113866. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  113867. ** there is a sorter, in which case the sorter has already limited
  113868. ** the output for us.
  113869. */
  113870. if( pSort==0 && p->iLimit ){
  113871. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  113872. }
  113873. }
  113874. /*
  113875. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  113876. ** X extra columns.
  113877. */
  113878. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  113879. int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
  113880. KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
  113881. if( p ){
  113882. p->aSortOrder = (u8*)&p->aColl[N+X];
  113883. p->nKeyField = (u16)N;
  113884. p->nAllField = (u16)(N+X);
  113885. p->enc = ENC(db);
  113886. p->db = db;
  113887. p->nRef = 1;
  113888. memset(&p[1], 0, nExtra);
  113889. }else{
  113890. sqlite3OomFault(db);
  113891. }
  113892. return p;
  113893. }
  113894. /*
  113895. ** Deallocate a KeyInfo object
  113896. */
  113897. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  113898. if( p ){
  113899. assert( p->nRef>0 );
  113900. p->nRef--;
  113901. if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
  113902. }
  113903. }
  113904. /*
  113905. ** Make a new pointer to a KeyInfo object
  113906. */
  113907. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  113908. if( p ){
  113909. assert( p->nRef>0 );
  113910. p->nRef++;
  113911. }
  113912. return p;
  113913. }
  113914. #ifdef SQLITE_DEBUG
  113915. /*
  113916. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  113917. ** can only be changed if this is just a single reference to the object.
  113918. **
  113919. ** This routine is used only inside of assert() statements.
  113920. */
  113921. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  113922. #endif /* SQLITE_DEBUG */
  113923. /*
  113924. ** Given an expression list, generate a KeyInfo structure that records
  113925. ** the collating sequence for each expression in that expression list.
  113926. **
  113927. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  113928. ** KeyInfo structure is appropriate for initializing a virtual index to
  113929. ** implement that clause. If the ExprList is the result set of a SELECT
  113930. ** then the KeyInfo structure is appropriate for initializing a virtual
  113931. ** index to implement a DISTINCT test.
  113932. **
  113933. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  113934. ** function is responsible for seeing that this structure is eventually
  113935. ** freed.
  113936. */
  113937. static KeyInfo *keyInfoFromExprList(
  113938. Parse *pParse, /* Parsing context */
  113939. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  113940. int iStart, /* Begin with this column of pList */
  113941. int nExtra /* Add this many extra columns to the end */
  113942. ){
  113943. int nExpr;
  113944. KeyInfo *pInfo;
  113945. struct ExprList_item *pItem;
  113946. sqlite3 *db = pParse->db;
  113947. int i;
  113948. nExpr = pList->nExpr;
  113949. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  113950. if( pInfo ){
  113951. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  113952. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  113953. pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
  113954. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  113955. }
  113956. }
  113957. return pInfo;
  113958. }
  113959. /*
  113960. ** Name of the connection operator, used for error messages.
  113961. */
  113962. static const char *selectOpName(int id){
  113963. char *z;
  113964. switch( id ){
  113965. case TK_ALL: z = "UNION ALL"; break;
  113966. case TK_INTERSECT: z = "INTERSECT"; break;
  113967. case TK_EXCEPT: z = "EXCEPT"; break;
  113968. default: z = "UNION"; break;
  113969. }
  113970. return z;
  113971. }
  113972. #ifndef SQLITE_OMIT_EXPLAIN
  113973. /*
  113974. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  113975. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  113976. ** where the caption is of the form:
  113977. **
  113978. ** "USE TEMP B-TREE FOR xxx"
  113979. **
  113980. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  113981. ** is determined by the zUsage argument.
  113982. */
  113983. static void explainTempTable(Parse *pParse, const char *zUsage){
  113984. if( pParse->explain==2 ){
  113985. Vdbe *v = pParse->pVdbe;
  113986. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  113987. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  113988. }
  113989. }
  113990. /*
  113991. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  113992. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  113993. ** in sqlite3Select() to assign values to structure member variables that
  113994. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  113995. ** code with #ifndef directives.
  113996. */
  113997. # define explainSetInteger(a, b) a = b
  113998. #else
  113999. /* No-op versions of the explainXXX() functions and macros. */
  114000. # define explainTempTable(y,z)
  114001. # define explainSetInteger(y,z)
  114002. #endif
  114003. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  114004. /*
  114005. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  114006. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  114007. ** where the caption is of one of the two forms:
  114008. **
  114009. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  114010. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  114011. **
  114012. ** where iSub1 and iSub2 are the integers passed as the corresponding
  114013. ** function parameters, and op is the text representation of the parameter
  114014. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  114015. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  114016. ** false, or the second form if it is true.
  114017. */
  114018. static void explainComposite(
  114019. Parse *pParse, /* Parse context */
  114020. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  114021. int iSub1, /* Subquery id 1 */
  114022. int iSub2, /* Subquery id 2 */
  114023. int bUseTmp /* True if a temp table was used */
  114024. ){
  114025. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  114026. if( pParse->explain==2 ){
  114027. Vdbe *v = pParse->pVdbe;
  114028. char *zMsg = sqlite3MPrintf(
  114029. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  114030. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  114031. );
  114032. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  114033. }
  114034. }
  114035. #else
  114036. /* No-op versions of the explainXXX() functions and macros. */
  114037. # define explainComposite(v,w,x,y,z)
  114038. #endif
  114039. /*
  114040. ** If the inner loop was generated using a non-null pOrderBy argument,
  114041. ** then the results were placed in a sorter. After the loop is terminated
  114042. ** we need to run the sorter and output the results. The following
  114043. ** routine generates the code needed to do that.
  114044. */
  114045. static void generateSortTail(
  114046. Parse *pParse, /* Parsing context */
  114047. Select *p, /* The SELECT statement */
  114048. SortCtx *pSort, /* Information on the ORDER BY clause */
  114049. int nColumn, /* Number of columns of data */
  114050. SelectDest *pDest /* Write the sorted results here */
  114051. ){
  114052. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  114053. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  114054. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  114055. int addr;
  114056. int addrOnce = 0;
  114057. int iTab;
  114058. ExprList *pOrderBy = pSort->pOrderBy;
  114059. int eDest = pDest->eDest;
  114060. int iParm = pDest->iSDParm;
  114061. int regRow;
  114062. int regRowid;
  114063. int iCol;
  114064. int nKey;
  114065. int iSortTab; /* Sorter cursor to read from */
  114066. int nSortData; /* Trailing values to read from sorter */
  114067. int i;
  114068. int bSeq; /* True if sorter record includes seq. no. */
  114069. struct ExprList_item *aOutEx = p->pEList->a;
  114070. assert( addrBreak<0 );
  114071. if( pSort->labelBkOut ){
  114072. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  114073. sqlite3VdbeGoto(v, addrBreak);
  114074. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  114075. }
  114076. iTab = pSort->iECursor;
  114077. if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
  114078. regRowid = 0;
  114079. regRow = pDest->iSdst;
  114080. nSortData = nColumn;
  114081. }else{
  114082. regRowid = sqlite3GetTempReg(pParse);
  114083. regRow = sqlite3GetTempRange(pParse, nColumn);
  114084. nSortData = nColumn;
  114085. }
  114086. nKey = pOrderBy->nExpr - pSort->nOBSat;
  114087. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  114088. int regSortOut = ++pParse->nMem;
  114089. iSortTab = pParse->nTab++;
  114090. if( pSort->labelBkOut ){
  114091. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  114092. }
  114093. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  114094. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  114095. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  114096. VdbeCoverage(v);
  114097. codeOffset(v, p->iOffset, addrContinue);
  114098. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  114099. bSeq = 0;
  114100. }else{
  114101. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  114102. codeOffset(v, p->iOffset, addrContinue);
  114103. iSortTab = iTab;
  114104. bSeq = 1;
  114105. }
  114106. for(i=0, iCol=nKey+bSeq-1; i<nSortData; i++){
  114107. if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
  114108. }
  114109. for(i=nSortData-1; i>=0; i--){
  114110. int iRead;
  114111. if( aOutEx[i].u.x.iOrderByCol ){
  114112. iRead = aOutEx[i].u.x.iOrderByCol-1;
  114113. }else{
  114114. iRead = iCol--;
  114115. }
  114116. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
  114117. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  114118. }
  114119. switch( eDest ){
  114120. case SRT_Table:
  114121. case SRT_EphemTab: {
  114122. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  114123. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  114124. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  114125. break;
  114126. }
  114127. #ifndef SQLITE_OMIT_SUBQUERY
  114128. case SRT_Set: {
  114129. assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
  114130. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
  114131. pDest->zAffSdst, nColumn);
  114132. sqlite3ExprCacheAffinityChange(pParse, regRow, nColumn);
  114133. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
  114134. break;
  114135. }
  114136. case SRT_Mem: {
  114137. /* The LIMIT clause will terminate the loop for us */
  114138. break;
  114139. }
  114140. #endif
  114141. default: {
  114142. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  114143. testcase( eDest==SRT_Output );
  114144. testcase( eDest==SRT_Coroutine );
  114145. if( eDest==SRT_Output ){
  114146. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  114147. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  114148. }else{
  114149. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  114150. }
  114151. break;
  114152. }
  114153. }
  114154. if( regRowid ){
  114155. if( eDest==SRT_Set ){
  114156. sqlite3ReleaseTempRange(pParse, regRow, nColumn);
  114157. }else{
  114158. sqlite3ReleaseTempReg(pParse, regRow);
  114159. }
  114160. sqlite3ReleaseTempReg(pParse, regRowid);
  114161. }
  114162. /* The bottom of the loop
  114163. */
  114164. sqlite3VdbeResolveLabel(v, addrContinue);
  114165. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  114166. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  114167. }else{
  114168. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  114169. }
  114170. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  114171. sqlite3VdbeResolveLabel(v, addrBreak);
  114172. }
  114173. /*
  114174. ** Return a pointer to a string containing the 'declaration type' of the
  114175. ** expression pExpr. The string may be treated as static by the caller.
  114176. **
  114177. ** Also try to estimate the size of the returned value and return that
  114178. ** result in *pEstWidth.
  114179. **
  114180. ** The declaration type is the exact datatype definition extracted from the
  114181. ** original CREATE TABLE statement if the expression is a column. The
  114182. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  114183. ** is considered a column can be complex in the presence of subqueries. The
  114184. ** result-set expression in all of the following SELECT statements is
  114185. ** considered a column by this function.
  114186. **
  114187. ** SELECT col FROM tbl;
  114188. ** SELECT (SELECT col FROM tbl;
  114189. ** SELECT (SELECT col FROM tbl);
  114190. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  114191. **
  114192. ** The declaration type for any expression other than a column is NULL.
  114193. **
  114194. ** This routine has either 3 or 6 parameters depending on whether or not
  114195. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  114196. */
  114197. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  114198. # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
  114199. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  114200. # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
  114201. #endif
  114202. static const char *columnTypeImpl(
  114203. NameContext *pNC,
  114204. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  114205. Expr *pExpr
  114206. #else
  114207. Expr *pExpr,
  114208. const char **pzOrigDb,
  114209. const char **pzOrigTab,
  114210. const char **pzOrigCol
  114211. #endif
  114212. ){
  114213. char const *zType = 0;
  114214. int j;
  114215. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  114216. char const *zOrigDb = 0;
  114217. char const *zOrigTab = 0;
  114218. char const *zOrigCol = 0;
  114219. #endif
  114220. assert( pExpr!=0 );
  114221. assert( pNC->pSrcList!=0 );
  114222. assert( pExpr->op!=TK_AGG_COLUMN ); /* This routine runes before aggregates
  114223. ** are processed */
  114224. switch( pExpr->op ){
  114225. case TK_COLUMN: {
  114226. /* The expression is a column. Locate the table the column is being
  114227. ** extracted from in NameContext.pSrcList. This table may be real
  114228. ** database table or a subquery.
  114229. */
  114230. Table *pTab = 0; /* Table structure column is extracted from */
  114231. Select *pS = 0; /* Select the column is extracted from */
  114232. int iCol = pExpr->iColumn; /* Index of column in pTab */
  114233. while( pNC && !pTab ){
  114234. SrcList *pTabList = pNC->pSrcList;
  114235. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  114236. if( j<pTabList->nSrc ){
  114237. pTab = pTabList->a[j].pTab;
  114238. pS = pTabList->a[j].pSelect;
  114239. }else{
  114240. pNC = pNC->pNext;
  114241. }
  114242. }
  114243. if( pTab==0 ){
  114244. /* At one time, code such as "SELECT new.x" within a trigger would
  114245. ** cause this condition to run. Since then, we have restructured how
  114246. ** trigger code is generated and so this condition is no longer
  114247. ** possible. However, it can still be true for statements like
  114248. ** the following:
  114249. **
  114250. ** CREATE TABLE t1(col INTEGER);
  114251. ** SELECT (SELECT t1.col) FROM FROM t1;
  114252. **
  114253. ** when columnType() is called on the expression "t1.col" in the
  114254. ** sub-select. In this case, set the column type to NULL, even
  114255. ** though it should really be "INTEGER".
  114256. **
  114257. ** This is not a problem, as the column type of "t1.col" is never
  114258. ** used. When columnType() is called on the expression
  114259. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  114260. ** branch below. */
  114261. break;
  114262. }
  114263. assert( pTab && pExpr->pTab==pTab );
  114264. if( pS ){
  114265. /* The "table" is actually a sub-select or a view in the FROM clause
  114266. ** of the SELECT statement. Return the declaration type and origin
  114267. ** data for the result-set column of the sub-select.
  114268. */
  114269. if( iCol>=0 && iCol<pS->pEList->nExpr ){
  114270. /* If iCol is less than zero, then the expression requests the
  114271. ** rowid of the sub-select or view. This expression is legal (see
  114272. ** test case misc2.2.2) - it always evaluates to NULL.
  114273. */
  114274. NameContext sNC;
  114275. Expr *p = pS->pEList->a[iCol].pExpr;
  114276. sNC.pSrcList = pS->pSrc;
  114277. sNC.pNext = pNC;
  114278. sNC.pParse = pNC->pParse;
  114279. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
  114280. }
  114281. }else{
  114282. /* A real table or a CTE table */
  114283. assert( !pS );
  114284. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  114285. if( iCol<0 ) iCol = pTab->iPKey;
  114286. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  114287. if( iCol<0 ){
  114288. zType = "INTEGER";
  114289. zOrigCol = "rowid";
  114290. }else{
  114291. zOrigCol = pTab->aCol[iCol].zName;
  114292. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  114293. }
  114294. zOrigTab = pTab->zName;
  114295. if( pNC->pParse && pTab->pSchema ){
  114296. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  114297. zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
  114298. }
  114299. #else
  114300. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  114301. if( iCol<0 ){
  114302. zType = "INTEGER";
  114303. }else{
  114304. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  114305. }
  114306. #endif
  114307. }
  114308. break;
  114309. }
  114310. #ifndef SQLITE_OMIT_SUBQUERY
  114311. case TK_SELECT: {
  114312. /* The expression is a sub-select. Return the declaration type and
  114313. ** origin info for the single column in the result set of the SELECT
  114314. ** statement.
  114315. */
  114316. NameContext sNC;
  114317. Select *pS = pExpr->x.pSelect;
  114318. Expr *p = pS->pEList->a[0].pExpr;
  114319. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  114320. sNC.pSrcList = pS->pSrc;
  114321. sNC.pNext = pNC;
  114322. sNC.pParse = pNC->pParse;
  114323. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  114324. break;
  114325. }
  114326. #endif
  114327. }
  114328. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  114329. if( pzOrigDb ){
  114330. assert( pzOrigTab && pzOrigCol );
  114331. *pzOrigDb = zOrigDb;
  114332. *pzOrigTab = zOrigTab;
  114333. *pzOrigCol = zOrigCol;
  114334. }
  114335. #endif
  114336. return zType;
  114337. }
  114338. /*
  114339. ** Generate code that will tell the VDBE the declaration types of columns
  114340. ** in the result set.
  114341. */
  114342. static void generateColumnTypes(
  114343. Parse *pParse, /* Parser context */
  114344. SrcList *pTabList, /* List of tables */
  114345. ExprList *pEList /* Expressions defining the result set */
  114346. ){
  114347. #ifndef SQLITE_OMIT_DECLTYPE
  114348. Vdbe *v = pParse->pVdbe;
  114349. int i;
  114350. NameContext sNC;
  114351. sNC.pSrcList = pTabList;
  114352. sNC.pParse = pParse;
  114353. sNC.pNext = 0;
  114354. for(i=0; i<pEList->nExpr; i++){
  114355. Expr *p = pEList->a[i].pExpr;
  114356. const char *zType;
  114357. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  114358. const char *zOrigDb = 0;
  114359. const char *zOrigTab = 0;
  114360. const char *zOrigCol = 0;
  114361. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  114362. /* The vdbe must make its own copy of the column-type and other
  114363. ** column specific strings, in case the schema is reset before this
  114364. ** virtual machine is deleted.
  114365. */
  114366. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  114367. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  114368. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  114369. #else
  114370. zType = columnType(&sNC, p, 0, 0, 0);
  114371. #endif
  114372. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  114373. }
  114374. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  114375. }
  114376. /*
  114377. ** Compute the column names for a SELECT statement.
  114378. **
  114379. ** The only guarantee that SQLite makes about column names is that if the
  114380. ** column has an AS clause assigning it a name, that will be the name used.
  114381. ** That is the only documented guarantee. However, countless applications
  114382. ** developed over the years have made baseless assumptions about column names
  114383. ** and will break if those assumptions changes. Hence, use extreme caution
  114384. ** when modifying this routine to avoid breaking legacy.
  114385. **
  114386. ** See Also: sqlite3ColumnsFromExprList()
  114387. **
  114388. ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
  114389. ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
  114390. ** applications should operate this way. Nevertheless, we need to support the
  114391. ** other modes for legacy:
  114392. **
  114393. ** short=OFF, full=OFF: Column name is the text of the expression has it
  114394. ** originally appears in the SELECT statement. In
  114395. ** other words, the zSpan of the result expression.
  114396. **
  114397. ** short=ON, full=OFF: (This is the default setting). If the result
  114398. ** refers directly to a table column, then the
  114399. ** result column name is just the table column
  114400. ** name: COLUMN. Otherwise use zSpan.
  114401. **
  114402. ** full=ON, short=ANY: If the result refers directly to a table column,
  114403. ** then the result column name with the table name
  114404. ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
  114405. */
  114406. static void generateColumnNames(
  114407. Parse *pParse, /* Parser context */
  114408. Select *pSelect /* Generate column names for this SELECT statement */
  114409. ){
  114410. Vdbe *v = pParse->pVdbe;
  114411. int i;
  114412. Table *pTab;
  114413. SrcList *pTabList;
  114414. ExprList *pEList;
  114415. sqlite3 *db = pParse->db;
  114416. int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
  114417. int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
  114418. #ifndef SQLITE_OMIT_EXPLAIN
  114419. /* If this is an EXPLAIN, skip this step */
  114420. if( pParse->explain ){
  114421. return;
  114422. }
  114423. #endif
  114424. if( pParse->colNamesSet || db->mallocFailed ) return;
  114425. /* Column names are determined by the left-most term of a compound select */
  114426. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  114427. SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
  114428. pTabList = pSelect->pSrc;
  114429. pEList = pSelect->pEList;
  114430. assert( v!=0 );
  114431. assert( pTabList!=0 );
  114432. pParse->colNamesSet = 1;
  114433. fullName = (db->flags & SQLITE_FullColNames)!=0;
  114434. srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
  114435. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  114436. for(i=0; i<pEList->nExpr; i++){
  114437. Expr *p = pEList->a[i].pExpr;
  114438. assert( p!=0 );
  114439. assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
  114440. assert( p->op!=TK_COLUMN || p->pTab!=0 ); /* Covering idx not yet coded */
  114441. if( pEList->a[i].zName ){
  114442. /* An AS clause always takes first priority */
  114443. char *zName = pEList->a[i].zName;
  114444. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  114445. }else if( srcName && p->op==TK_COLUMN ){
  114446. char *zCol;
  114447. int iCol = p->iColumn;
  114448. pTab = p->pTab;
  114449. assert( pTab!=0 );
  114450. if( iCol<0 ) iCol = pTab->iPKey;
  114451. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  114452. if( iCol<0 ){
  114453. zCol = "rowid";
  114454. }else{
  114455. zCol = pTab->aCol[iCol].zName;
  114456. }
  114457. if( fullName ){
  114458. char *zName = 0;
  114459. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  114460. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  114461. }else{
  114462. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  114463. }
  114464. }else{
  114465. const char *z = pEList->a[i].zSpan;
  114466. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  114467. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  114468. }
  114469. }
  114470. generateColumnTypes(pParse, pTabList, pEList);
  114471. }
  114472. /*
  114473. ** Given an expression list (which is really the list of expressions
  114474. ** that form the result set of a SELECT statement) compute appropriate
  114475. ** column names for a table that would hold the expression list.
  114476. **
  114477. ** All column names will be unique.
  114478. **
  114479. ** Only the column names are computed. Column.zType, Column.zColl,
  114480. ** and other fields of Column are zeroed.
  114481. **
  114482. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  114483. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  114484. **
  114485. ** The only guarantee that SQLite makes about column names is that if the
  114486. ** column has an AS clause assigning it a name, that will be the name used.
  114487. ** That is the only documented guarantee. However, countless applications
  114488. ** developed over the years have made baseless assumptions about column names
  114489. ** and will break if those assumptions changes. Hence, use extreme caution
  114490. ** when modifying this routine to avoid breaking legacy.
  114491. **
  114492. ** See Also: generateColumnNames()
  114493. */
  114494. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  114495. Parse *pParse, /* Parsing context */
  114496. ExprList *pEList, /* Expr list from which to derive column names */
  114497. i16 *pnCol, /* Write the number of columns here */
  114498. Column **paCol /* Write the new column list here */
  114499. ){
  114500. sqlite3 *db = pParse->db; /* Database connection */
  114501. int i, j; /* Loop counters */
  114502. u32 cnt; /* Index added to make the name unique */
  114503. Column *aCol, *pCol; /* For looping over result columns */
  114504. int nCol; /* Number of columns in the result set */
  114505. char *zName; /* Column name */
  114506. int nName; /* Size of name in zName[] */
  114507. Hash ht; /* Hash table of column names */
  114508. sqlite3HashInit(&ht);
  114509. if( pEList ){
  114510. nCol = pEList->nExpr;
  114511. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  114512. testcase( aCol==0 );
  114513. if( nCol>32767 ) nCol = 32767;
  114514. }else{
  114515. nCol = 0;
  114516. aCol = 0;
  114517. }
  114518. assert( nCol==(i16)nCol );
  114519. *pnCol = nCol;
  114520. *paCol = aCol;
  114521. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  114522. /* Get an appropriate name for the column
  114523. */
  114524. if( (zName = pEList->a[i].zName)!=0 ){
  114525. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  114526. }else{
  114527. Expr *pColExpr = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  114528. while( pColExpr->op==TK_DOT ){
  114529. pColExpr = pColExpr->pRight;
  114530. assert( pColExpr!=0 );
  114531. }
  114532. assert( pColExpr->op!=TK_AGG_COLUMN );
  114533. if( pColExpr->op==TK_COLUMN ){
  114534. /* For columns use the column name name */
  114535. int iCol = pColExpr->iColumn;
  114536. Table *pTab = pColExpr->pTab;
  114537. assert( pTab!=0 );
  114538. if( iCol<0 ) iCol = pTab->iPKey;
  114539. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  114540. }else if( pColExpr->op==TK_ID ){
  114541. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  114542. zName = pColExpr->u.zToken;
  114543. }else{
  114544. /* Use the original text of the column expression as its name */
  114545. zName = pEList->a[i].zSpan;
  114546. }
  114547. }
  114548. if( zName ){
  114549. zName = sqlite3DbStrDup(db, zName);
  114550. }else{
  114551. zName = sqlite3MPrintf(db,"column%d",i+1);
  114552. }
  114553. /* Make sure the column name is unique. If the name is not unique,
  114554. ** append an integer to the name so that it becomes unique.
  114555. */
  114556. cnt = 0;
  114557. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  114558. nName = sqlite3Strlen30(zName);
  114559. if( nName>0 ){
  114560. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  114561. if( zName[j]==':' ) nName = j;
  114562. }
  114563. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  114564. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  114565. }
  114566. pCol->zName = zName;
  114567. sqlite3ColumnPropertiesFromName(0, pCol);
  114568. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  114569. sqlite3OomFault(db);
  114570. }
  114571. }
  114572. sqlite3HashClear(&ht);
  114573. if( db->mallocFailed ){
  114574. for(j=0; j<i; j++){
  114575. sqlite3DbFree(db, aCol[j].zName);
  114576. }
  114577. sqlite3DbFree(db, aCol);
  114578. *paCol = 0;
  114579. *pnCol = 0;
  114580. return SQLITE_NOMEM_BKPT;
  114581. }
  114582. return SQLITE_OK;
  114583. }
  114584. /*
  114585. ** Add type and collation information to a column list based on
  114586. ** a SELECT statement.
  114587. **
  114588. ** The column list presumably came from selectColumnNamesFromExprList().
  114589. ** The column list has only names, not types or collations. This
  114590. ** routine goes through and adds the types and collations.
  114591. **
  114592. ** This routine requires that all identifiers in the SELECT
  114593. ** statement be resolved.
  114594. */
  114595. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
  114596. Parse *pParse, /* Parsing contexts */
  114597. Table *pTab, /* Add column type information to this table */
  114598. Select *pSelect /* SELECT used to determine types and collations */
  114599. ){
  114600. sqlite3 *db = pParse->db;
  114601. NameContext sNC;
  114602. Column *pCol;
  114603. CollSeq *pColl;
  114604. int i;
  114605. Expr *p;
  114606. struct ExprList_item *a;
  114607. assert( pSelect!=0 );
  114608. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  114609. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  114610. if( db->mallocFailed ) return;
  114611. memset(&sNC, 0, sizeof(sNC));
  114612. sNC.pSrcList = pSelect->pSrc;
  114613. a = pSelect->pEList->a;
  114614. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  114615. const char *zType;
  114616. int n, m;
  114617. p = a[i].pExpr;
  114618. zType = columnType(&sNC, p, 0, 0, 0);
  114619. /* pCol->szEst = ... // Column size est for SELECT tables never used */
  114620. pCol->affinity = sqlite3ExprAffinity(p);
  114621. if( zType ){
  114622. m = sqlite3Strlen30(zType);
  114623. n = sqlite3Strlen30(pCol->zName);
  114624. pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
  114625. if( pCol->zName ){
  114626. memcpy(&pCol->zName[n+1], zType, m+1);
  114627. pCol->colFlags |= COLFLAG_HASTYPE;
  114628. }
  114629. }
  114630. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  114631. pColl = sqlite3ExprCollSeq(pParse, p);
  114632. if( pColl && pCol->zColl==0 ){
  114633. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  114634. }
  114635. }
  114636. pTab->szTabRow = 1; /* Any non-zero value works */
  114637. }
  114638. /*
  114639. ** Given a SELECT statement, generate a Table structure that describes
  114640. ** the result set of that SELECT.
  114641. */
  114642. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  114643. Table *pTab;
  114644. sqlite3 *db = pParse->db;
  114645. int savedFlags;
  114646. savedFlags = db->flags;
  114647. db->flags &= ~SQLITE_FullColNames;
  114648. db->flags |= SQLITE_ShortColNames;
  114649. sqlite3SelectPrep(pParse, pSelect, 0);
  114650. if( pParse->nErr ) return 0;
  114651. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  114652. db->flags = savedFlags;
  114653. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  114654. if( pTab==0 ){
  114655. return 0;
  114656. }
  114657. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  114658. ** is disabled */
  114659. assert( db->lookaside.bDisable );
  114660. pTab->nTabRef = 1;
  114661. pTab->zName = 0;
  114662. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  114663. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  114664. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  114665. pTab->iPKey = -1;
  114666. if( db->mallocFailed ){
  114667. sqlite3DeleteTable(db, pTab);
  114668. return 0;
  114669. }
  114670. return pTab;
  114671. }
  114672. /*
  114673. ** Get a VDBE for the given parser context. Create a new one if necessary.
  114674. ** If an error occurs, return NULL and leave a message in pParse.
  114675. */
  114676. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  114677. if( pParse->pVdbe ){
  114678. return pParse->pVdbe;
  114679. }
  114680. if( pParse->pToplevel==0
  114681. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  114682. ){
  114683. pParse->okConstFactor = 1;
  114684. }
  114685. return sqlite3VdbeCreate(pParse);
  114686. }
  114687. /*
  114688. ** Compute the iLimit and iOffset fields of the SELECT based on the
  114689. ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
  114690. ** that appear in the original SQL statement after the LIMIT and OFFSET
  114691. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  114692. ** are the integer memory register numbers for counters used to compute
  114693. ** the limit and offset. If there is no limit and/or offset, then
  114694. ** iLimit and iOffset are negative.
  114695. **
  114696. ** This routine changes the values of iLimit and iOffset only if
  114697. ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
  114698. ** and iOffset should have been preset to appropriate default values (zero)
  114699. ** prior to calling this routine.
  114700. **
  114701. ** The iOffset register (if it exists) is initialized to the value
  114702. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  114703. ** iOffset+1 is initialized to LIMIT+OFFSET.
  114704. **
  114705. ** Only if pLimit->pLeft!=0 do the limit registers get
  114706. ** redefined. The UNION ALL operator uses this property to force
  114707. ** the reuse of the same limit and offset registers across multiple
  114708. ** SELECT statements.
  114709. */
  114710. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  114711. Vdbe *v = 0;
  114712. int iLimit = 0;
  114713. int iOffset;
  114714. int n;
  114715. Expr *pLimit = p->pLimit;
  114716. if( p->iLimit ) return;
  114717. /*
  114718. ** "LIMIT -1" always shows all rows. There is some
  114719. ** controversy about what the correct behavior should be.
  114720. ** The current implementation interprets "LIMIT 0" to mean
  114721. ** no rows.
  114722. */
  114723. sqlite3ExprCacheClear(pParse);
  114724. if( pLimit ){
  114725. assert( pLimit->op==TK_LIMIT );
  114726. assert( pLimit->pLeft!=0 );
  114727. p->iLimit = iLimit = ++pParse->nMem;
  114728. v = sqlite3GetVdbe(pParse);
  114729. assert( v!=0 );
  114730. if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
  114731. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  114732. VdbeComment((v, "LIMIT counter"));
  114733. if( n==0 ){
  114734. sqlite3VdbeGoto(v, iBreak);
  114735. }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
  114736. p->nSelectRow = sqlite3LogEst((u64)n);
  114737. p->selFlags |= SF_FixedLimit;
  114738. }
  114739. }else{
  114740. sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
  114741. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  114742. VdbeComment((v, "LIMIT counter"));
  114743. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  114744. }
  114745. if( pLimit->pRight ){
  114746. p->iOffset = iOffset = ++pParse->nMem;
  114747. pParse->nMem++; /* Allocate an extra register for limit+offset */
  114748. sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
  114749. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  114750. VdbeComment((v, "OFFSET counter"));
  114751. sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
  114752. VdbeComment((v, "LIMIT+OFFSET"));
  114753. }
  114754. }
  114755. }
  114756. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  114757. /*
  114758. ** Return the appropriate collating sequence for the iCol-th column of
  114759. ** the result set for the compound-select statement "p". Return NULL if
  114760. ** the column has no default collating sequence.
  114761. **
  114762. ** The collating sequence for the compound select is taken from the
  114763. ** left-most term of the select that has a collating sequence.
  114764. */
  114765. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  114766. CollSeq *pRet;
  114767. if( p->pPrior ){
  114768. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  114769. }else{
  114770. pRet = 0;
  114771. }
  114772. assert( iCol>=0 );
  114773. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  114774. ** have been thrown during name resolution and we would not have gotten
  114775. ** this far */
  114776. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  114777. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  114778. }
  114779. return pRet;
  114780. }
  114781. /*
  114782. ** The select statement passed as the second parameter is a compound SELECT
  114783. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  114784. ** structure suitable for implementing the ORDER BY.
  114785. **
  114786. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  114787. ** function is responsible for ensuring that this structure is eventually
  114788. ** freed.
  114789. */
  114790. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  114791. ExprList *pOrderBy = p->pOrderBy;
  114792. int nOrderBy = p->pOrderBy->nExpr;
  114793. sqlite3 *db = pParse->db;
  114794. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  114795. if( pRet ){
  114796. int i;
  114797. for(i=0; i<nOrderBy; i++){
  114798. struct ExprList_item *pItem = &pOrderBy->a[i];
  114799. Expr *pTerm = pItem->pExpr;
  114800. CollSeq *pColl;
  114801. if( pTerm->flags & EP_Collate ){
  114802. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  114803. }else{
  114804. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  114805. if( pColl==0 ) pColl = db->pDfltColl;
  114806. pOrderBy->a[i].pExpr =
  114807. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  114808. }
  114809. assert( sqlite3KeyInfoIsWriteable(pRet) );
  114810. pRet->aColl[i] = pColl;
  114811. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  114812. }
  114813. }
  114814. return pRet;
  114815. }
  114816. #ifndef SQLITE_OMIT_CTE
  114817. /*
  114818. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  114819. ** query of the form:
  114820. **
  114821. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  114822. ** \___________/ \_______________/
  114823. ** p->pPrior p
  114824. **
  114825. **
  114826. ** There is exactly one reference to the recursive-table in the FROM clause
  114827. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  114828. **
  114829. ** The setup-query runs once to generate an initial set of rows that go
  114830. ** into a Queue table. Rows are extracted from the Queue table one by
  114831. ** one. Each row extracted from Queue is output to pDest. Then the single
  114832. ** extracted row (now in the iCurrent table) becomes the content of the
  114833. ** recursive-table for a recursive-query run. The output of the recursive-query
  114834. ** is added back into the Queue table. Then another row is extracted from Queue
  114835. ** and the iteration continues until the Queue table is empty.
  114836. **
  114837. ** If the compound query operator is UNION then no duplicate rows are ever
  114838. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  114839. ** that have ever been inserted into Queue and causes duplicates to be
  114840. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  114841. **
  114842. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  114843. ** ORDER BY order and the first entry is extracted for each cycle. Without
  114844. ** an ORDER BY, the Queue table is just a FIFO.
  114845. **
  114846. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  114847. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  114848. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  114849. ** with a positive value, then the first OFFSET outputs are discarded rather
  114850. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  114851. ** rows have been skipped.
  114852. */
  114853. static void generateWithRecursiveQuery(
  114854. Parse *pParse, /* Parsing context */
  114855. Select *p, /* The recursive SELECT to be coded */
  114856. SelectDest *pDest /* What to do with query results */
  114857. ){
  114858. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  114859. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  114860. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  114861. Select *pSetup = p->pPrior; /* The setup query */
  114862. int addrTop; /* Top of the loop */
  114863. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  114864. int iCurrent = 0; /* The Current table */
  114865. int regCurrent; /* Register holding Current table */
  114866. int iQueue; /* The Queue table */
  114867. int iDistinct = 0; /* To ensure unique results if UNION */
  114868. int eDest = SRT_Fifo; /* How to write to Queue */
  114869. SelectDest destQueue; /* SelectDest targetting the Queue table */
  114870. int i; /* Loop counter */
  114871. int rc; /* Result code */
  114872. ExprList *pOrderBy; /* The ORDER BY clause */
  114873. Expr *pLimit; /* Saved LIMIT and OFFSET */
  114874. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  114875. /* Obtain authorization to do a recursive query */
  114876. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  114877. /* Process the LIMIT and OFFSET clauses, if they exist */
  114878. addrBreak = sqlite3VdbeMakeLabel(v);
  114879. p->nSelectRow = 320; /* 4 billion rows */
  114880. computeLimitRegisters(pParse, p, addrBreak);
  114881. pLimit = p->pLimit;
  114882. regLimit = p->iLimit;
  114883. regOffset = p->iOffset;
  114884. p->pLimit = 0;
  114885. p->iLimit = p->iOffset = 0;
  114886. pOrderBy = p->pOrderBy;
  114887. /* Locate the cursor number of the Current table */
  114888. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  114889. if( pSrc->a[i].fg.isRecursive ){
  114890. iCurrent = pSrc->a[i].iCursor;
  114891. break;
  114892. }
  114893. }
  114894. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  114895. ** the Distinct table must be exactly one greater than Queue in order
  114896. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  114897. iQueue = pParse->nTab++;
  114898. if( p->op==TK_UNION ){
  114899. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  114900. iDistinct = pParse->nTab++;
  114901. }else{
  114902. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  114903. }
  114904. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  114905. /* Allocate cursors for Current, Queue, and Distinct. */
  114906. regCurrent = ++pParse->nMem;
  114907. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  114908. if( pOrderBy ){
  114909. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  114910. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  114911. (char*)pKeyInfo, P4_KEYINFO);
  114912. destQueue.pOrderBy = pOrderBy;
  114913. }else{
  114914. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  114915. }
  114916. VdbeComment((v, "Queue table"));
  114917. if( iDistinct ){
  114918. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  114919. p->selFlags |= SF_UsesEphemeral;
  114920. }
  114921. /* Detach the ORDER BY clause from the compound SELECT */
  114922. p->pOrderBy = 0;
  114923. /* Store the results of the setup-query in Queue. */
  114924. pSetup->pNext = 0;
  114925. rc = sqlite3Select(pParse, pSetup, &destQueue);
  114926. pSetup->pNext = p;
  114927. if( rc ) goto end_of_recursive_query;
  114928. /* Find the next row in the Queue and output that row */
  114929. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  114930. /* Transfer the next row in Queue over to Current */
  114931. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  114932. if( pOrderBy ){
  114933. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  114934. }else{
  114935. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  114936. }
  114937. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  114938. /* Output the single row in Current */
  114939. addrCont = sqlite3VdbeMakeLabel(v);
  114940. codeOffset(v, regOffset, addrCont);
  114941. selectInnerLoop(pParse, p, iCurrent,
  114942. 0, 0, pDest, addrCont, addrBreak);
  114943. if( regLimit ){
  114944. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  114945. VdbeCoverage(v);
  114946. }
  114947. sqlite3VdbeResolveLabel(v, addrCont);
  114948. /* Execute the recursive SELECT taking the single row in Current as
  114949. ** the value for the recursive-table. Store the results in the Queue.
  114950. */
  114951. if( p->selFlags & SF_Aggregate ){
  114952. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  114953. }else{
  114954. p->pPrior = 0;
  114955. sqlite3Select(pParse, p, &destQueue);
  114956. assert( p->pPrior==0 );
  114957. p->pPrior = pSetup;
  114958. }
  114959. /* Keep running the loop until the Queue is empty */
  114960. sqlite3VdbeGoto(v, addrTop);
  114961. sqlite3VdbeResolveLabel(v, addrBreak);
  114962. end_of_recursive_query:
  114963. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  114964. p->pOrderBy = pOrderBy;
  114965. p->pLimit = pLimit;
  114966. return;
  114967. }
  114968. #endif /* SQLITE_OMIT_CTE */
  114969. /* Forward references */
  114970. static int multiSelectOrderBy(
  114971. Parse *pParse, /* Parsing context */
  114972. Select *p, /* The right-most of SELECTs to be coded */
  114973. SelectDest *pDest /* What to do with query results */
  114974. );
  114975. /*
  114976. ** Handle the special case of a compound-select that originates from a
  114977. ** VALUES clause. By handling this as a special case, we avoid deep
  114978. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  114979. ** on a VALUES clause.
  114980. **
  114981. ** Because the Select object originates from a VALUES clause:
  114982. ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
  114983. ** (2) All terms are UNION ALL
  114984. ** (3) There is no ORDER BY clause
  114985. **
  114986. ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
  114987. ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
  114988. ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
  114989. ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
  114990. */
  114991. static int multiSelectValues(
  114992. Parse *pParse, /* Parsing context */
  114993. Select *p, /* The right-most of SELECTs to be coded */
  114994. SelectDest *pDest /* What to do with query results */
  114995. ){
  114996. Select *pPrior;
  114997. Select *pRightmost = p;
  114998. int nRow = 1;
  114999. int rc = 0;
  115000. assert( p->selFlags & SF_MultiValue );
  115001. do{
  115002. assert( p->selFlags & SF_Values );
  115003. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  115004. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  115005. if( p->pPrior==0 ) break;
  115006. assert( p->pPrior->pNext==p );
  115007. p = p->pPrior;
  115008. nRow++;
  115009. }while(1);
  115010. while( p ){
  115011. pPrior = p->pPrior;
  115012. p->pPrior = 0;
  115013. rc = sqlite3Select(pParse, p, pDest);
  115014. p->pPrior = pPrior;
  115015. if( rc || pRightmost->pLimit ) break;
  115016. p->nSelectRow = nRow;
  115017. p = p->pNext;
  115018. }
  115019. return rc;
  115020. }
  115021. /*
  115022. ** This routine is called to process a compound query form from
  115023. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  115024. ** INTERSECT
  115025. **
  115026. ** "p" points to the right-most of the two queries. the query on the
  115027. ** left is p->pPrior. The left query could also be a compound query
  115028. ** in which case this routine will be called recursively.
  115029. **
  115030. ** The results of the total query are to be written into a destination
  115031. ** of type eDest with parameter iParm.
  115032. **
  115033. ** Example 1: Consider a three-way compound SQL statement.
  115034. **
  115035. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  115036. **
  115037. ** This statement is parsed up as follows:
  115038. **
  115039. ** SELECT c FROM t3
  115040. ** |
  115041. ** `-----> SELECT b FROM t2
  115042. ** |
  115043. ** `------> SELECT a FROM t1
  115044. **
  115045. ** The arrows in the diagram above represent the Select.pPrior pointer.
  115046. ** So if this routine is called with p equal to the t3 query, then
  115047. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  115048. **
  115049. ** Notice that because of the way SQLite parses compound SELECTs, the
  115050. ** individual selects always group from left to right.
  115051. */
  115052. static int multiSelect(
  115053. Parse *pParse, /* Parsing context */
  115054. Select *p, /* The right-most of SELECTs to be coded */
  115055. SelectDest *pDest /* What to do with query results */
  115056. ){
  115057. int rc = SQLITE_OK; /* Success code from a subroutine */
  115058. Select *pPrior; /* Another SELECT immediately to our left */
  115059. Vdbe *v; /* Generate code to this VDBE */
  115060. SelectDest dest; /* Alternative data destination */
  115061. Select *pDelete = 0; /* Chain of simple selects to delete */
  115062. sqlite3 *db; /* Database connection */
  115063. #ifndef SQLITE_OMIT_EXPLAIN
  115064. int iSub1 = 0; /* EQP id of left-hand query */
  115065. int iSub2 = 0; /* EQP id of right-hand query */
  115066. #endif
  115067. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  115068. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  115069. */
  115070. assert( p && p->pPrior ); /* Calling function guarantees this much */
  115071. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  115072. db = pParse->db;
  115073. pPrior = p->pPrior;
  115074. dest = *pDest;
  115075. if( pPrior->pOrderBy || pPrior->pLimit ){
  115076. sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
  115077. pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
  115078. rc = 1;
  115079. goto multi_select_end;
  115080. }
  115081. v = sqlite3GetVdbe(pParse);
  115082. assert( v!=0 ); /* The VDBE already created by calling function */
  115083. /* Create the destination temporary table if necessary
  115084. */
  115085. if( dest.eDest==SRT_EphemTab ){
  115086. assert( p->pEList );
  115087. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  115088. dest.eDest = SRT_Table;
  115089. }
  115090. /* Special handling for a compound-select that originates as a VALUES clause.
  115091. */
  115092. if( p->selFlags & SF_MultiValue ){
  115093. rc = multiSelectValues(pParse, p, &dest);
  115094. goto multi_select_end;
  115095. }
  115096. /* Make sure all SELECTs in the statement have the same number of elements
  115097. ** in their result sets.
  115098. */
  115099. assert( p->pEList && pPrior->pEList );
  115100. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  115101. #ifndef SQLITE_OMIT_CTE
  115102. if( p->selFlags & SF_Recursive ){
  115103. generateWithRecursiveQuery(pParse, p, &dest);
  115104. }else
  115105. #endif
  115106. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  115107. */
  115108. if( p->pOrderBy ){
  115109. return multiSelectOrderBy(pParse, p, pDest);
  115110. }else
  115111. /* Generate code for the left and right SELECT statements.
  115112. */
  115113. switch( p->op ){
  115114. case TK_ALL: {
  115115. int addr = 0;
  115116. int nLimit;
  115117. assert( !pPrior->pLimit );
  115118. pPrior->iLimit = p->iLimit;
  115119. pPrior->iOffset = p->iOffset;
  115120. pPrior->pLimit = p->pLimit;
  115121. explainSetInteger(iSub1, pParse->iNextSelectId);
  115122. rc = sqlite3Select(pParse, pPrior, &dest);
  115123. p->pLimit = 0;
  115124. if( rc ){
  115125. goto multi_select_end;
  115126. }
  115127. p->pPrior = 0;
  115128. p->iLimit = pPrior->iLimit;
  115129. p->iOffset = pPrior->iOffset;
  115130. if( p->iLimit ){
  115131. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  115132. VdbeComment((v, "Jump ahead if LIMIT reached"));
  115133. if( p->iOffset ){
  115134. sqlite3VdbeAddOp3(v, OP_OffsetLimit,
  115135. p->iLimit, p->iOffset+1, p->iOffset);
  115136. }
  115137. }
  115138. explainSetInteger(iSub2, pParse->iNextSelectId);
  115139. rc = sqlite3Select(pParse, p, &dest);
  115140. testcase( rc!=SQLITE_OK );
  115141. pDelete = p->pPrior;
  115142. p->pPrior = pPrior;
  115143. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  115144. if( pPrior->pLimit
  115145. && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
  115146. && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
  115147. ){
  115148. p->nSelectRow = sqlite3LogEst((u64)nLimit);
  115149. }
  115150. if( addr ){
  115151. sqlite3VdbeJumpHere(v, addr);
  115152. }
  115153. break;
  115154. }
  115155. case TK_EXCEPT:
  115156. case TK_UNION: {
  115157. int unionTab; /* Cursor number of the temporary table holding result */
  115158. u8 op = 0; /* One of the SRT_ operations to apply to self */
  115159. int priorOp; /* The SRT_ operation to apply to prior selects */
  115160. Expr *pLimit; /* Saved values of p->nLimit */
  115161. int addr;
  115162. SelectDest uniondest;
  115163. testcase( p->op==TK_EXCEPT );
  115164. testcase( p->op==TK_UNION );
  115165. priorOp = SRT_Union;
  115166. if( dest.eDest==priorOp ){
  115167. /* We can reuse a temporary table generated by a SELECT to our
  115168. ** right.
  115169. */
  115170. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  115171. unionTab = dest.iSDParm;
  115172. }else{
  115173. /* We will need to create our own temporary table to hold the
  115174. ** intermediate results.
  115175. */
  115176. unionTab = pParse->nTab++;
  115177. assert( p->pOrderBy==0 );
  115178. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  115179. assert( p->addrOpenEphm[0] == -1 );
  115180. p->addrOpenEphm[0] = addr;
  115181. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  115182. assert( p->pEList );
  115183. }
  115184. /* Code the SELECT statements to our left
  115185. */
  115186. assert( !pPrior->pOrderBy );
  115187. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  115188. explainSetInteger(iSub1, pParse->iNextSelectId);
  115189. rc = sqlite3Select(pParse, pPrior, &uniondest);
  115190. if( rc ){
  115191. goto multi_select_end;
  115192. }
  115193. /* Code the current SELECT statement
  115194. */
  115195. if( p->op==TK_EXCEPT ){
  115196. op = SRT_Except;
  115197. }else{
  115198. assert( p->op==TK_UNION );
  115199. op = SRT_Union;
  115200. }
  115201. p->pPrior = 0;
  115202. pLimit = p->pLimit;
  115203. p->pLimit = 0;
  115204. uniondest.eDest = op;
  115205. explainSetInteger(iSub2, pParse->iNextSelectId);
  115206. rc = sqlite3Select(pParse, p, &uniondest);
  115207. testcase( rc!=SQLITE_OK );
  115208. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  115209. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  115210. sqlite3ExprListDelete(db, p->pOrderBy);
  115211. pDelete = p->pPrior;
  115212. p->pPrior = pPrior;
  115213. p->pOrderBy = 0;
  115214. if( p->op==TK_UNION ){
  115215. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  115216. }
  115217. sqlite3ExprDelete(db, p->pLimit);
  115218. p->pLimit = pLimit;
  115219. p->iLimit = 0;
  115220. p->iOffset = 0;
  115221. /* Convert the data in the temporary table into whatever form
  115222. ** it is that we currently need.
  115223. */
  115224. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  115225. if( dest.eDest!=priorOp ){
  115226. int iCont, iBreak, iStart;
  115227. assert( p->pEList );
  115228. iBreak = sqlite3VdbeMakeLabel(v);
  115229. iCont = sqlite3VdbeMakeLabel(v);
  115230. computeLimitRegisters(pParse, p, iBreak);
  115231. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  115232. iStart = sqlite3VdbeCurrentAddr(v);
  115233. selectInnerLoop(pParse, p, unionTab,
  115234. 0, 0, &dest, iCont, iBreak);
  115235. sqlite3VdbeResolveLabel(v, iCont);
  115236. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  115237. sqlite3VdbeResolveLabel(v, iBreak);
  115238. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  115239. }
  115240. break;
  115241. }
  115242. default: assert( p->op==TK_INTERSECT ); {
  115243. int tab1, tab2;
  115244. int iCont, iBreak, iStart;
  115245. Expr *pLimit;
  115246. int addr;
  115247. SelectDest intersectdest;
  115248. int r1;
  115249. /* INTERSECT is different from the others since it requires
  115250. ** two temporary tables. Hence it has its own case. Begin
  115251. ** by allocating the tables we will need.
  115252. */
  115253. tab1 = pParse->nTab++;
  115254. tab2 = pParse->nTab++;
  115255. assert( p->pOrderBy==0 );
  115256. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  115257. assert( p->addrOpenEphm[0] == -1 );
  115258. p->addrOpenEphm[0] = addr;
  115259. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  115260. assert( p->pEList );
  115261. /* Code the SELECTs to our left into temporary table "tab1".
  115262. */
  115263. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  115264. explainSetInteger(iSub1, pParse->iNextSelectId);
  115265. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  115266. if( rc ){
  115267. goto multi_select_end;
  115268. }
  115269. /* Code the current SELECT into temporary table "tab2"
  115270. */
  115271. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  115272. assert( p->addrOpenEphm[1] == -1 );
  115273. p->addrOpenEphm[1] = addr;
  115274. p->pPrior = 0;
  115275. pLimit = p->pLimit;
  115276. p->pLimit = 0;
  115277. intersectdest.iSDParm = tab2;
  115278. explainSetInteger(iSub2, pParse->iNextSelectId);
  115279. rc = sqlite3Select(pParse, p, &intersectdest);
  115280. testcase( rc!=SQLITE_OK );
  115281. pDelete = p->pPrior;
  115282. p->pPrior = pPrior;
  115283. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  115284. sqlite3ExprDelete(db, p->pLimit);
  115285. p->pLimit = pLimit;
  115286. /* Generate code to take the intersection of the two temporary
  115287. ** tables.
  115288. */
  115289. assert( p->pEList );
  115290. iBreak = sqlite3VdbeMakeLabel(v);
  115291. iCont = sqlite3VdbeMakeLabel(v);
  115292. computeLimitRegisters(pParse, p, iBreak);
  115293. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  115294. r1 = sqlite3GetTempReg(pParse);
  115295. iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
  115296. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  115297. sqlite3ReleaseTempReg(pParse, r1);
  115298. selectInnerLoop(pParse, p, tab1,
  115299. 0, 0, &dest, iCont, iBreak);
  115300. sqlite3VdbeResolveLabel(v, iCont);
  115301. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  115302. sqlite3VdbeResolveLabel(v, iBreak);
  115303. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  115304. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  115305. break;
  115306. }
  115307. }
  115308. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  115309. /* Compute collating sequences used by
  115310. ** temporary tables needed to implement the compound select.
  115311. ** Attach the KeyInfo structure to all temporary tables.
  115312. **
  115313. ** This section is run by the right-most SELECT statement only.
  115314. ** SELECT statements to the left always skip this part. The right-most
  115315. ** SELECT might also skip this part if it has no ORDER BY clause and
  115316. ** no temp tables are required.
  115317. */
  115318. if( p->selFlags & SF_UsesEphemeral ){
  115319. int i; /* Loop counter */
  115320. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  115321. Select *pLoop; /* For looping through SELECT statements */
  115322. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  115323. int nCol; /* Number of columns in result set */
  115324. assert( p->pNext==0 );
  115325. nCol = p->pEList->nExpr;
  115326. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  115327. if( !pKeyInfo ){
  115328. rc = SQLITE_NOMEM_BKPT;
  115329. goto multi_select_end;
  115330. }
  115331. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  115332. *apColl = multiSelectCollSeq(pParse, p, i);
  115333. if( 0==*apColl ){
  115334. *apColl = db->pDfltColl;
  115335. }
  115336. }
  115337. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  115338. for(i=0; i<2; i++){
  115339. int addr = pLoop->addrOpenEphm[i];
  115340. if( addr<0 ){
  115341. /* If [0] is unused then [1] is also unused. So we can
  115342. ** always safely abort as soon as the first unused slot is found */
  115343. assert( pLoop->addrOpenEphm[1]<0 );
  115344. break;
  115345. }
  115346. sqlite3VdbeChangeP2(v, addr, nCol);
  115347. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  115348. P4_KEYINFO);
  115349. pLoop->addrOpenEphm[i] = -1;
  115350. }
  115351. }
  115352. sqlite3KeyInfoUnref(pKeyInfo);
  115353. }
  115354. multi_select_end:
  115355. pDest->iSdst = dest.iSdst;
  115356. pDest->nSdst = dest.nSdst;
  115357. sqlite3SelectDelete(db, pDelete);
  115358. return rc;
  115359. }
  115360. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  115361. /*
  115362. ** Error message for when two or more terms of a compound select have different
  115363. ** size result sets.
  115364. */
  115365. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  115366. if( p->selFlags & SF_Values ){
  115367. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  115368. }else{
  115369. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  115370. " do not have the same number of result columns", selectOpName(p->op));
  115371. }
  115372. }
  115373. /*
  115374. ** Code an output subroutine for a coroutine implementation of a
  115375. ** SELECT statment.
  115376. **
  115377. ** The data to be output is contained in pIn->iSdst. There are
  115378. ** pIn->nSdst columns to be output. pDest is where the output should
  115379. ** be sent.
  115380. **
  115381. ** regReturn is the number of the register holding the subroutine
  115382. ** return address.
  115383. **
  115384. ** If regPrev>0 then it is the first register in a vector that
  115385. ** records the previous output. mem[regPrev] is a flag that is false
  115386. ** if there has been no previous output. If regPrev>0 then code is
  115387. ** generated to suppress duplicates. pKeyInfo is used for comparing
  115388. ** keys.
  115389. **
  115390. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  115391. ** iBreak.
  115392. */
  115393. static int generateOutputSubroutine(
  115394. Parse *pParse, /* Parsing context */
  115395. Select *p, /* The SELECT statement */
  115396. SelectDest *pIn, /* Coroutine supplying data */
  115397. SelectDest *pDest, /* Where to send the data */
  115398. int regReturn, /* The return address register */
  115399. int regPrev, /* Previous result register. No uniqueness if 0 */
  115400. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  115401. int iBreak /* Jump here if we hit the LIMIT */
  115402. ){
  115403. Vdbe *v = pParse->pVdbe;
  115404. int iContinue;
  115405. int addr;
  115406. addr = sqlite3VdbeCurrentAddr(v);
  115407. iContinue = sqlite3VdbeMakeLabel(v);
  115408. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  115409. */
  115410. if( regPrev ){
  115411. int addr1, addr2;
  115412. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  115413. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  115414. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  115415. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  115416. sqlite3VdbeJumpHere(v, addr1);
  115417. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  115418. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  115419. }
  115420. if( pParse->db->mallocFailed ) return 0;
  115421. /* Suppress the first OFFSET entries if there is an OFFSET clause
  115422. */
  115423. codeOffset(v, p->iOffset, iContinue);
  115424. assert( pDest->eDest!=SRT_Exists );
  115425. assert( pDest->eDest!=SRT_Table );
  115426. switch( pDest->eDest ){
  115427. /* Store the result as data using a unique key.
  115428. */
  115429. case SRT_EphemTab: {
  115430. int r1 = sqlite3GetTempReg(pParse);
  115431. int r2 = sqlite3GetTempReg(pParse);
  115432. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  115433. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  115434. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  115435. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  115436. sqlite3ReleaseTempReg(pParse, r2);
  115437. sqlite3ReleaseTempReg(pParse, r1);
  115438. break;
  115439. }
  115440. #ifndef SQLITE_OMIT_SUBQUERY
  115441. /* If we are creating a set for an "expr IN (SELECT ...)".
  115442. */
  115443. case SRT_Set: {
  115444. int r1;
  115445. testcase( pIn->nSdst>1 );
  115446. r1 = sqlite3GetTempReg(pParse);
  115447. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
  115448. r1, pDest->zAffSdst, pIn->nSdst);
  115449. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  115450. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
  115451. pIn->iSdst, pIn->nSdst);
  115452. sqlite3ReleaseTempReg(pParse, r1);
  115453. break;
  115454. }
  115455. /* If this is a scalar select that is part of an expression, then
  115456. ** store the results in the appropriate memory cell and break out
  115457. ** of the scan loop.
  115458. */
  115459. case SRT_Mem: {
  115460. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  115461. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  115462. /* The LIMIT clause will jump out of the loop for us */
  115463. break;
  115464. }
  115465. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  115466. /* The results are stored in a sequence of registers
  115467. ** starting at pDest->iSdst. Then the co-routine yields.
  115468. */
  115469. case SRT_Coroutine: {
  115470. if( pDest->iSdst==0 ){
  115471. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  115472. pDest->nSdst = pIn->nSdst;
  115473. }
  115474. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  115475. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  115476. break;
  115477. }
  115478. /* If none of the above, then the result destination must be
  115479. ** SRT_Output. This routine is never called with any other
  115480. ** destination other than the ones handled above or SRT_Output.
  115481. **
  115482. ** For SRT_Output, results are stored in a sequence of registers.
  115483. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  115484. ** return the next row of result.
  115485. */
  115486. default: {
  115487. assert( pDest->eDest==SRT_Output );
  115488. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  115489. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  115490. break;
  115491. }
  115492. }
  115493. /* Jump to the end of the loop if the LIMIT is reached.
  115494. */
  115495. if( p->iLimit ){
  115496. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  115497. }
  115498. /* Generate the subroutine return
  115499. */
  115500. sqlite3VdbeResolveLabel(v, iContinue);
  115501. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  115502. return addr;
  115503. }
  115504. /*
  115505. ** Alternative compound select code generator for cases when there
  115506. ** is an ORDER BY clause.
  115507. **
  115508. ** We assume a query of the following form:
  115509. **
  115510. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  115511. **
  115512. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  115513. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  115514. ** co-routines. Then run the co-routines in parallel and merge the results
  115515. ** into the output. In addition to the two coroutines (called selectA and
  115516. ** selectB) there are 7 subroutines:
  115517. **
  115518. ** outA: Move the output of the selectA coroutine into the output
  115519. ** of the compound query.
  115520. **
  115521. ** outB: Move the output of the selectB coroutine into the output
  115522. ** of the compound query. (Only generated for UNION and
  115523. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  115524. ** appears only in B.)
  115525. **
  115526. ** AltB: Called when there is data from both coroutines and A<B.
  115527. **
  115528. ** AeqB: Called when there is data from both coroutines and A==B.
  115529. **
  115530. ** AgtB: Called when there is data from both coroutines and A>B.
  115531. **
  115532. ** EofA: Called when data is exhausted from selectA.
  115533. **
  115534. ** EofB: Called when data is exhausted from selectB.
  115535. **
  115536. ** The implementation of the latter five subroutines depend on which
  115537. ** <operator> is used:
  115538. **
  115539. **
  115540. ** UNION ALL UNION EXCEPT INTERSECT
  115541. ** ------------- ----------------- -------------- -----------------
  115542. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  115543. **
  115544. ** AeqB: outA, nextA nextA nextA outA, nextA
  115545. **
  115546. ** AgtB: outB, nextB outB, nextB nextB nextB
  115547. **
  115548. ** EofA: outB, nextB outB, nextB halt halt
  115549. **
  115550. ** EofB: outA, nextA outA, nextA outA, nextA halt
  115551. **
  115552. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  115553. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  115554. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  115555. ** following nextX causes a jump to the end of the select processing.
  115556. **
  115557. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  115558. ** within the output subroutine. The regPrev register set holds the previously
  115559. ** output value. A comparison is made against this value and the output
  115560. ** is skipped if the next results would be the same as the previous.
  115561. **
  115562. ** The implementation plan is to implement the two coroutines and seven
  115563. ** subroutines first, then put the control logic at the bottom. Like this:
  115564. **
  115565. ** goto Init
  115566. ** coA: coroutine for left query (A)
  115567. ** coB: coroutine for right query (B)
  115568. ** outA: output one row of A
  115569. ** outB: output one row of B (UNION and UNION ALL only)
  115570. ** EofA: ...
  115571. ** EofB: ...
  115572. ** AltB: ...
  115573. ** AeqB: ...
  115574. ** AgtB: ...
  115575. ** Init: initialize coroutine registers
  115576. ** yield coA
  115577. ** if eof(A) goto EofA
  115578. ** yield coB
  115579. ** if eof(B) goto EofB
  115580. ** Cmpr: Compare A, B
  115581. ** Jump AltB, AeqB, AgtB
  115582. ** End: ...
  115583. **
  115584. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  115585. ** actually called using Gosub and they do not Return. EofA and EofB loop
  115586. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  115587. ** and AgtB jump to either L2 or to one of EofA or EofB.
  115588. */
  115589. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  115590. static int multiSelectOrderBy(
  115591. Parse *pParse, /* Parsing context */
  115592. Select *p, /* The right-most of SELECTs to be coded */
  115593. SelectDest *pDest /* What to do with query results */
  115594. ){
  115595. int i, j; /* Loop counters */
  115596. Select *pPrior; /* Another SELECT immediately to our left */
  115597. Vdbe *v; /* Generate code to this VDBE */
  115598. SelectDest destA; /* Destination for coroutine A */
  115599. SelectDest destB; /* Destination for coroutine B */
  115600. int regAddrA; /* Address register for select-A coroutine */
  115601. int regAddrB; /* Address register for select-B coroutine */
  115602. int addrSelectA; /* Address of the select-A coroutine */
  115603. int addrSelectB; /* Address of the select-B coroutine */
  115604. int regOutA; /* Address register for the output-A subroutine */
  115605. int regOutB; /* Address register for the output-B subroutine */
  115606. int addrOutA; /* Address of the output-A subroutine */
  115607. int addrOutB = 0; /* Address of the output-B subroutine */
  115608. int addrEofA; /* Address of the select-A-exhausted subroutine */
  115609. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  115610. int addrEofB; /* Address of the select-B-exhausted subroutine */
  115611. int addrAltB; /* Address of the A<B subroutine */
  115612. int addrAeqB; /* Address of the A==B subroutine */
  115613. int addrAgtB; /* Address of the A>B subroutine */
  115614. int regLimitA; /* Limit register for select-A */
  115615. int regLimitB; /* Limit register for select-A */
  115616. int regPrev; /* A range of registers to hold previous output */
  115617. int savedLimit; /* Saved value of p->iLimit */
  115618. int savedOffset; /* Saved value of p->iOffset */
  115619. int labelCmpr; /* Label for the start of the merge algorithm */
  115620. int labelEnd; /* Label for the end of the overall SELECT stmt */
  115621. int addr1; /* Jump instructions that get retargetted */
  115622. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  115623. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  115624. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  115625. sqlite3 *db; /* Database connection */
  115626. ExprList *pOrderBy; /* The ORDER BY clause */
  115627. int nOrderBy; /* Number of terms in the ORDER BY clause */
  115628. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  115629. #ifndef SQLITE_OMIT_EXPLAIN
  115630. int iSub1; /* EQP id of left-hand query */
  115631. int iSub2; /* EQP id of right-hand query */
  115632. #endif
  115633. assert( p->pOrderBy!=0 );
  115634. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  115635. db = pParse->db;
  115636. v = pParse->pVdbe;
  115637. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  115638. labelEnd = sqlite3VdbeMakeLabel(v);
  115639. labelCmpr = sqlite3VdbeMakeLabel(v);
  115640. /* Patch up the ORDER BY clause
  115641. */
  115642. op = p->op;
  115643. pPrior = p->pPrior;
  115644. assert( pPrior->pOrderBy==0 );
  115645. pOrderBy = p->pOrderBy;
  115646. assert( pOrderBy );
  115647. nOrderBy = pOrderBy->nExpr;
  115648. /* For operators other than UNION ALL we have to make sure that
  115649. ** the ORDER BY clause covers every term of the result set. Add
  115650. ** terms to the ORDER BY clause as necessary.
  115651. */
  115652. if( op!=TK_ALL ){
  115653. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  115654. struct ExprList_item *pItem;
  115655. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  115656. assert( pItem->u.x.iOrderByCol>0 );
  115657. if( pItem->u.x.iOrderByCol==i ) break;
  115658. }
  115659. if( j==nOrderBy ){
  115660. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  115661. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  115662. pNew->flags |= EP_IntValue;
  115663. pNew->u.iValue = i;
  115664. p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  115665. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  115666. }
  115667. }
  115668. }
  115669. /* Compute the comparison permutation and keyinfo that is used with
  115670. ** the permutation used to determine if the next
  115671. ** row of results comes from selectA or selectB. Also add explicit
  115672. ** collations to the ORDER BY clause terms so that when the subqueries
  115673. ** to the right and the left are evaluated, they use the correct
  115674. ** collation.
  115675. */
  115676. aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  115677. if( aPermute ){
  115678. struct ExprList_item *pItem;
  115679. aPermute[0] = nOrderBy;
  115680. for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  115681. assert( pItem->u.x.iOrderByCol>0 );
  115682. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  115683. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  115684. }
  115685. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  115686. }else{
  115687. pKeyMerge = 0;
  115688. }
  115689. /* Reattach the ORDER BY clause to the query.
  115690. */
  115691. p->pOrderBy = pOrderBy;
  115692. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  115693. /* Allocate a range of temporary registers and the KeyInfo needed
  115694. ** for the logic that removes duplicate result rows when the
  115695. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  115696. */
  115697. if( op==TK_ALL ){
  115698. regPrev = 0;
  115699. }else{
  115700. int nExpr = p->pEList->nExpr;
  115701. assert( nOrderBy>=nExpr || db->mallocFailed );
  115702. regPrev = pParse->nMem+1;
  115703. pParse->nMem += nExpr+1;
  115704. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  115705. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  115706. if( pKeyDup ){
  115707. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  115708. for(i=0; i<nExpr; i++){
  115709. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  115710. pKeyDup->aSortOrder[i] = 0;
  115711. }
  115712. }
  115713. }
  115714. /* Separate the left and the right query from one another
  115715. */
  115716. p->pPrior = 0;
  115717. pPrior->pNext = 0;
  115718. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  115719. if( pPrior->pPrior==0 ){
  115720. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  115721. }
  115722. /* Compute the limit registers */
  115723. computeLimitRegisters(pParse, p, labelEnd);
  115724. if( p->iLimit && op==TK_ALL ){
  115725. regLimitA = ++pParse->nMem;
  115726. regLimitB = ++pParse->nMem;
  115727. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  115728. regLimitA);
  115729. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  115730. }else{
  115731. regLimitA = regLimitB = 0;
  115732. }
  115733. sqlite3ExprDelete(db, p->pLimit);
  115734. p->pLimit = 0;
  115735. regAddrA = ++pParse->nMem;
  115736. regAddrB = ++pParse->nMem;
  115737. regOutA = ++pParse->nMem;
  115738. regOutB = ++pParse->nMem;
  115739. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  115740. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  115741. /* Generate a coroutine to evaluate the SELECT statement to the
  115742. ** left of the compound operator - the "A" select.
  115743. */
  115744. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  115745. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  115746. VdbeComment((v, "left SELECT"));
  115747. pPrior->iLimit = regLimitA;
  115748. explainSetInteger(iSub1, pParse->iNextSelectId);
  115749. sqlite3Select(pParse, pPrior, &destA);
  115750. sqlite3VdbeEndCoroutine(v, regAddrA);
  115751. sqlite3VdbeJumpHere(v, addr1);
  115752. /* Generate a coroutine to evaluate the SELECT statement on
  115753. ** the right - the "B" select
  115754. */
  115755. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  115756. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  115757. VdbeComment((v, "right SELECT"));
  115758. savedLimit = p->iLimit;
  115759. savedOffset = p->iOffset;
  115760. p->iLimit = regLimitB;
  115761. p->iOffset = 0;
  115762. explainSetInteger(iSub2, pParse->iNextSelectId);
  115763. sqlite3Select(pParse, p, &destB);
  115764. p->iLimit = savedLimit;
  115765. p->iOffset = savedOffset;
  115766. sqlite3VdbeEndCoroutine(v, regAddrB);
  115767. /* Generate a subroutine that outputs the current row of the A
  115768. ** select as the next output row of the compound select.
  115769. */
  115770. VdbeNoopComment((v, "Output routine for A"));
  115771. addrOutA = generateOutputSubroutine(pParse,
  115772. p, &destA, pDest, regOutA,
  115773. regPrev, pKeyDup, labelEnd);
  115774. /* Generate a subroutine that outputs the current row of the B
  115775. ** select as the next output row of the compound select.
  115776. */
  115777. if( op==TK_ALL || op==TK_UNION ){
  115778. VdbeNoopComment((v, "Output routine for B"));
  115779. addrOutB = generateOutputSubroutine(pParse,
  115780. p, &destB, pDest, regOutB,
  115781. regPrev, pKeyDup, labelEnd);
  115782. }
  115783. sqlite3KeyInfoUnref(pKeyDup);
  115784. /* Generate a subroutine to run when the results from select A
  115785. ** are exhausted and only data in select B remains.
  115786. */
  115787. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  115788. addrEofA_noB = addrEofA = labelEnd;
  115789. }else{
  115790. VdbeNoopComment((v, "eof-A subroutine"));
  115791. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  115792. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  115793. VdbeCoverage(v);
  115794. sqlite3VdbeGoto(v, addrEofA);
  115795. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  115796. }
  115797. /* Generate a subroutine to run when the results from select B
  115798. ** are exhausted and only data in select A remains.
  115799. */
  115800. if( op==TK_INTERSECT ){
  115801. addrEofB = addrEofA;
  115802. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  115803. }else{
  115804. VdbeNoopComment((v, "eof-B subroutine"));
  115805. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  115806. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  115807. sqlite3VdbeGoto(v, addrEofB);
  115808. }
  115809. /* Generate code to handle the case of A<B
  115810. */
  115811. VdbeNoopComment((v, "A-lt-B subroutine"));
  115812. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  115813. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  115814. sqlite3VdbeGoto(v, labelCmpr);
  115815. /* Generate code to handle the case of A==B
  115816. */
  115817. if( op==TK_ALL ){
  115818. addrAeqB = addrAltB;
  115819. }else if( op==TK_INTERSECT ){
  115820. addrAeqB = addrAltB;
  115821. addrAltB++;
  115822. }else{
  115823. VdbeNoopComment((v, "A-eq-B subroutine"));
  115824. addrAeqB =
  115825. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  115826. sqlite3VdbeGoto(v, labelCmpr);
  115827. }
  115828. /* Generate code to handle the case of A>B
  115829. */
  115830. VdbeNoopComment((v, "A-gt-B subroutine"));
  115831. addrAgtB = sqlite3VdbeCurrentAddr(v);
  115832. if( op==TK_ALL || op==TK_UNION ){
  115833. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  115834. }
  115835. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  115836. sqlite3VdbeGoto(v, labelCmpr);
  115837. /* This code runs once to initialize everything.
  115838. */
  115839. sqlite3VdbeJumpHere(v, addr1);
  115840. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  115841. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  115842. /* Implement the main merge loop
  115843. */
  115844. sqlite3VdbeResolveLabel(v, labelCmpr);
  115845. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  115846. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  115847. (char*)pKeyMerge, P4_KEYINFO);
  115848. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  115849. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  115850. /* Jump to the this point in order to terminate the query.
  115851. */
  115852. sqlite3VdbeResolveLabel(v, labelEnd);
  115853. /* Reassembly the compound query so that it will be freed correctly
  115854. ** by the calling function */
  115855. if( p->pPrior ){
  115856. sqlite3SelectDelete(db, p->pPrior);
  115857. }
  115858. p->pPrior = pPrior;
  115859. pPrior->pNext = p;
  115860. /*** TBD: Insert subroutine calls to close cursors on incomplete
  115861. **** subqueries ****/
  115862. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  115863. return pParse->nErr!=0;
  115864. }
  115865. #endif
  115866. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  115867. /* An instance of the SubstContext object describes an substitution edit
  115868. ** to be performed on a parse tree.
  115869. **
  115870. ** All references to columns in table iTable are to be replaced by corresponding
  115871. ** expressions in pEList.
  115872. */
  115873. typedef struct SubstContext {
  115874. Parse *pParse; /* The parsing context */
  115875. int iTable; /* Replace references to this table */
  115876. int iNewTable; /* New table number */
  115877. int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
  115878. ExprList *pEList; /* Replacement expressions */
  115879. } SubstContext;
  115880. /* Forward Declarations */
  115881. static void substExprList(SubstContext*, ExprList*);
  115882. static void substSelect(SubstContext*, Select*, int);
  115883. /*
  115884. ** Scan through the expression pExpr. Replace every reference to
  115885. ** a column in table number iTable with a copy of the iColumn-th
  115886. ** entry in pEList. (But leave references to the ROWID column
  115887. ** unchanged.)
  115888. **
  115889. ** This routine is part of the flattening procedure. A subquery
  115890. ** whose result set is defined by pEList appears as entry in the
  115891. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  115892. ** FORM clause entry is iTable. This routine makes the necessary
  115893. ** changes to pExpr so that it refers directly to the source table
  115894. ** of the subquery rather the result set of the subquery.
  115895. */
  115896. static Expr *substExpr(
  115897. SubstContext *pSubst, /* Description of the substitution */
  115898. Expr *pExpr /* Expr in which substitution occurs */
  115899. ){
  115900. if( pExpr==0 ) return 0;
  115901. if( ExprHasProperty(pExpr, EP_FromJoin)
  115902. && pExpr->iRightJoinTable==pSubst->iTable
  115903. ){
  115904. pExpr->iRightJoinTable = pSubst->iNewTable;
  115905. }
  115906. if( pExpr->op==TK_COLUMN && pExpr->iTable==pSubst->iTable ){
  115907. if( pExpr->iColumn<0 ){
  115908. pExpr->op = TK_NULL;
  115909. }else{
  115910. Expr *pNew;
  115911. Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
  115912. Expr ifNullRow;
  115913. assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
  115914. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  115915. if( sqlite3ExprIsVector(pCopy) ){
  115916. sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
  115917. }else{
  115918. sqlite3 *db = pSubst->pParse->db;
  115919. if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
  115920. memset(&ifNullRow, 0, sizeof(ifNullRow));
  115921. ifNullRow.op = TK_IF_NULL_ROW;
  115922. ifNullRow.pLeft = pCopy;
  115923. ifNullRow.iTable = pSubst->iNewTable;
  115924. pCopy = &ifNullRow;
  115925. }
  115926. pNew = sqlite3ExprDup(db, pCopy, 0);
  115927. if( pNew && pSubst->isLeftJoin ){
  115928. ExprSetProperty(pNew, EP_CanBeNull);
  115929. }
  115930. if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
  115931. pNew->iRightJoinTable = pExpr->iRightJoinTable;
  115932. ExprSetProperty(pNew, EP_FromJoin);
  115933. }
  115934. sqlite3ExprDelete(db, pExpr);
  115935. pExpr = pNew;
  115936. }
  115937. }
  115938. }else{
  115939. if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
  115940. pExpr->iTable = pSubst->iNewTable;
  115941. }
  115942. pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
  115943. pExpr->pRight = substExpr(pSubst, pExpr->pRight);
  115944. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  115945. substSelect(pSubst, pExpr->x.pSelect, 1);
  115946. }else{
  115947. substExprList(pSubst, pExpr->x.pList);
  115948. }
  115949. }
  115950. return pExpr;
  115951. }
  115952. static void substExprList(
  115953. SubstContext *pSubst, /* Description of the substitution */
  115954. ExprList *pList /* List to scan and in which to make substitutes */
  115955. ){
  115956. int i;
  115957. if( pList==0 ) return;
  115958. for(i=0; i<pList->nExpr; i++){
  115959. pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
  115960. }
  115961. }
  115962. static void substSelect(
  115963. SubstContext *pSubst, /* Description of the substitution */
  115964. Select *p, /* SELECT statement in which to make substitutions */
  115965. int doPrior /* Do substitutes on p->pPrior too */
  115966. ){
  115967. SrcList *pSrc;
  115968. struct SrcList_item *pItem;
  115969. int i;
  115970. if( !p ) return;
  115971. do{
  115972. substExprList(pSubst, p->pEList);
  115973. substExprList(pSubst, p->pGroupBy);
  115974. substExprList(pSubst, p->pOrderBy);
  115975. p->pHaving = substExpr(pSubst, p->pHaving);
  115976. p->pWhere = substExpr(pSubst, p->pWhere);
  115977. pSrc = p->pSrc;
  115978. assert( pSrc!=0 );
  115979. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  115980. substSelect(pSubst, pItem->pSelect, 1);
  115981. if( pItem->fg.isTabFunc ){
  115982. substExprList(pSubst, pItem->u1.pFuncArg);
  115983. }
  115984. }
  115985. }while( doPrior && (p = p->pPrior)!=0 );
  115986. }
  115987. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  115988. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  115989. /*
  115990. ** This routine attempts to flatten subqueries as a performance optimization.
  115991. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  115992. **
  115993. ** To understand the concept of flattening, consider the following
  115994. ** query:
  115995. **
  115996. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  115997. **
  115998. ** The default way of implementing this query is to execute the
  115999. ** subquery first and store the results in a temporary table, then
  116000. ** run the outer query on that temporary table. This requires two
  116001. ** passes over the data. Furthermore, because the temporary table
  116002. ** has no indices, the WHERE clause on the outer query cannot be
  116003. ** optimized.
  116004. **
  116005. ** This routine attempts to rewrite queries such as the above into
  116006. ** a single flat select, like this:
  116007. **
  116008. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  116009. **
  116010. ** The code generated for this simplification gives the same result
  116011. ** but only has to scan the data once. And because indices might
  116012. ** exist on the table t1, a complete scan of the data might be
  116013. ** avoided.
  116014. **
  116015. ** Flattening is subject to the following constraints:
  116016. **
  116017. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  116018. ** The subquery and the outer query cannot both be aggregates.
  116019. **
  116020. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  116021. ** (2) If the subquery is an aggregate then
  116022. ** (2a) the outer query must not be a join and
  116023. ** (2b) the outer query must not use subqueries
  116024. ** other than the one FROM-clause subquery that is a candidate
  116025. ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
  116026. ** from 2015-02-09.)
  116027. **
  116028. ** (3) If the subquery is the right operand of a LEFT JOIN then
  116029. ** (3a) the subquery may not be a join and
  116030. ** (3b) the FROM clause of the subquery may not contain a virtual
  116031. ** table and
  116032. ** (3c) the outer query may not be an aggregate.
  116033. **
  116034. ** (4) The subquery can not be DISTINCT.
  116035. **
  116036. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  116037. ** sub-queries that were excluded from this optimization. Restriction
  116038. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  116039. **
  116040. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  116041. ** If the subquery is aggregate, the outer query may not be DISTINCT.
  116042. **
  116043. ** (7) The subquery must have a FROM clause. TODO: For subqueries without
  116044. ** A FROM clause, consider adding a FROM clause with the special
  116045. ** table sqlite_once that consists of a single row containing a
  116046. ** single NULL.
  116047. **
  116048. ** (8) If the subquery uses LIMIT then the outer query may not be a join.
  116049. **
  116050. ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
  116051. **
  116052. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  116053. ** accidently carried the comment forward until 2014-09-15. Original
  116054. ** constraint: "If the subquery is aggregate then the outer query
  116055. ** may not use LIMIT."
  116056. **
  116057. ** (11) The subquery and the outer query may not both have ORDER BY clauses.
  116058. **
  116059. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  116060. ** a separate restriction deriving from ticket #350.
  116061. **
  116062. ** (13) The subquery and outer query may not both use LIMIT.
  116063. **
  116064. ** (14) The subquery may not use OFFSET.
  116065. **
  116066. ** (15) If the outer query is part of a compound select, then the
  116067. ** subquery may not use LIMIT.
  116068. ** (See ticket #2339 and ticket [02a8e81d44]).
  116069. **
  116070. ** (16) If the outer query is aggregate, then the subquery may not
  116071. ** use ORDER BY. (Ticket #2942) This used to not matter
  116072. ** until we introduced the group_concat() function.
  116073. **
  116074. ** (17) If the subquery is a compound select, then
  116075. ** (17a) all compound operators must be a UNION ALL, and
  116076. ** (17b) no terms within the subquery compound may be aggregate
  116077. ** or DISTINCT, and
  116078. ** (17c) every term within the subquery compound must have a FROM clause
  116079. ** (17d) the outer query may not be
  116080. ** (17d1) aggregate, or
  116081. ** (17d2) DISTINCT, or
  116082. ** (17d3) a join.
  116083. **
  116084. ** The parent and sub-query may contain WHERE clauses. Subject to
  116085. ** rules (11), (13) and (14), they may also contain ORDER BY,
  116086. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  116087. ** operator other than UNION ALL because all the other compound
  116088. ** operators have an implied DISTINCT which is disallowed by
  116089. ** restriction (4).
  116090. **
  116091. ** Also, each component of the sub-query must return the same number
  116092. ** of result columns. This is actually a requirement for any compound
  116093. ** SELECT statement, but all the code here does is make sure that no
  116094. ** such (illegal) sub-query is flattened. The caller will detect the
  116095. ** syntax error and return a detailed message.
  116096. **
  116097. ** (18) If the sub-query is a compound select, then all terms of the
  116098. ** ORDER BY clause of the parent must be simple references to
  116099. ** columns of the sub-query.
  116100. **
  116101. ** (19) If the subquery uses LIMIT then the outer query may not
  116102. ** have a WHERE clause.
  116103. **
  116104. ** (20) If the sub-query is a compound select, then it must not use
  116105. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  116106. ** somewhat by saying that the terms of the ORDER BY clause must
  116107. ** appear as unmodified result columns in the outer query. But we
  116108. ** have other optimizations in mind to deal with that case.
  116109. **
  116110. ** (21) If the subquery uses LIMIT then the outer query may not be
  116111. ** DISTINCT. (See ticket [752e1646fc]).
  116112. **
  116113. ** (22) The subquery may not be a recursive CTE.
  116114. **
  116115. ** (**) Subsumed into restriction (17d3). Was: If the outer query is
  116116. ** a recursive CTE, then the sub-query may not be a compound query.
  116117. ** This restriction is because transforming the
  116118. ** parent to a compound query confuses the code that handles
  116119. ** recursive queries in multiSelect().
  116120. **
  116121. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  116122. ** The subquery may not be an aggregate that uses the built-in min() or
  116123. ** or max() functions. (Without this restriction, a query like:
  116124. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  116125. ** return the value X for which Y was maximal.)
  116126. **
  116127. **
  116128. ** In this routine, the "p" parameter is a pointer to the outer query.
  116129. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  116130. ** uses aggregates.
  116131. **
  116132. ** If flattening is not attempted, this routine is a no-op and returns 0.
  116133. ** If flattening is attempted this routine returns 1.
  116134. **
  116135. ** All of the expression analysis must occur on both the outer query and
  116136. ** the subquery before this routine runs.
  116137. */
  116138. static int flattenSubquery(
  116139. Parse *pParse, /* Parsing context */
  116140. Select *p, /* The parent or outer SELECT statement */
  116141. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  116142. int isAgg /* True if outer SELECT uses aggregate functions */
  116143. ){
  116144. const char *zSavedAuthContext = pParse->zAuthContext;
  116145. Select *pParent; /* Current UNION ALL term of the other query */
  116146. Select *pSub; /* The inner query or "subquery" */
  116147. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  116148. SrcList *pSrc; /* The FROM clause of the outer query */
  116149. SrcList *pSubSrc; /* The FROM clause of the subquery */
  116150. int iParent; /* VDBE cursor number of the pSub result set temp table */
  116151. int iNewParent = -1;/* Replacement table for iParent */
  116152. int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
  116153. int i; /* Loop counter */
  116154. Expr *pWhere; /* The WHERE clause */
  116155. struct SrcList_item *pSubitem; /* The subquery */
  116156. sqlite3 *db = pParse->db;
  116157. /* Check to see if flattening is permitted. Return 0 if not.
  116158. */
  116159. assert( p!=0 );
  116160. assert( p->pPrior==0 );
  116161. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  116162. pSrc = p->pSrc;
  116163. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  116164. pSubitem = &pSrc->a[iFrom];
  116165. iParent = pSubitem->iCursor;
  116166. pSub = pSubitem->pSelect;
  116167. assert( pSub!=0 );
  116168. pSubSrc = pSub->pSrc;
  116169. assert( pSubSrc );
  116170. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  116171. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  116172. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  116173. ** became arbitrary expressions, we were forced to add restrictions (13)
  116174. ** and (14). */
  116175. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  116176. if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
  116177. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  116178. return 0; /* Restriction (15) */
  116179. }
  116180. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  116181. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
  116182. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  116183. return 0; /* Restrictions (8)(9) */
  116184. }
  116185. if( p->pOrderBy && pSub->pOrderBy ){
  116186. return 0; /* Restriction (11) */
  116187. }
  116188. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  116189. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  116190. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  116191. return 0; /* Restriction (21) */
  116192. }
  116193. if( pSub->selFlags & (SF_Recursive) ){
  116194. return 0; /* Restrictions (22) */
  116195. }
  116196. /*
  116197. ** If the subquery is the right operand of a LEFT JOIN, then the
  116198. ** subquery may not be a join itself (3a). Example of why this is not
  116199. ** allowed:
  116200. **
  116201. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  116202. **
  116203. ** If we flatten the above, we would get
  116204. **
  116205. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  116206. **
  116207. ** which is not at all the same thing.
  116208. **
  116209. ** If the subquery is the right operand of a LEFT JOIN, then the outer
  116210. ** query cannot be an aggregate. (3c) This is an artifact of the way
  116211. ** aggregates are processed - there is no mechanism to determine if
  116212. ** the LEFT JOIN table should be all-NULL.
  116213. **
  116214. ** See also tickets #306, #350, and #3300.
  116215. */
  116216. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  116217. isLeftJoin = 1;
  116218. if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
  116219. /* (3a) (3c) (3b) */
  116220. return 0;
  116221. }
  116222. }
  116223. #ifdef SQLITE_EXTRA_IFNULLROW
  116224. else if( iFrom>0 && !isAgg ){
  116225. /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
  116226. ** every reference to any result column from subquery in a join, even
  116227. ** though they are not necessary. This will stress-test the OP_IfNullRow
  116228. ** opcode. */
  116229. isLeftJoin = -1;
  116230. }
  116231. #endif
  116232. /* Restriction (17): If the sub-query is a compound SELECT, then it must
  116233. ** use only the UNION ALL operator. And none of the simple select queries
  116234. ** that make up the compound SELECT are allowed to be aggregate or distinct
  116235. ** queries.
  116236. */
  116237. if( pSub->pPrior ){
  116238. if( pSub->pOrderBy ){
  116239. return 0; /* Restriction (20) */
  116240. }
  116241. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  116242. return 0; /* (17d1), (17d2), or (17d3) */
  116243. }
  116244. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  116245. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  116246. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  116247. assert( pSub->pSrc!=0 );
  116248. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  116249. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
  116250. || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
  116251. || pSub1->pSrc->nSrc<1 /* (17c) */
  116252. ){
  116253. return 0;
  116254. }
  116255. testcase( pSub1->pSrc->nSrc>1 );
  116256. }
  116257. /* Restriction (18). */
  116258. if( p->pOrderBy ){
  116259. int ii;
  116260. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  116261. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  116262. }
  116263. }
  116264. }
  116265. /* Ex-restriction (23):
  116266. ** The only way that the recursive part of a CTE can contain a compound
  116267. ** subquery is for the subquery to be one term of a join. But if the
  116268. ** subquery is a join, then the flattening has already been stopped by
  116269. ** restriction (17d3)
  116270. */
  116271. assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
  116272. /***** If we reach this point, flattening is permitted. *****/
  116273. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  116274. pSub->zSelName, pSub, iFrom));
  116275. /* Authorize the subquery */
  116276. pParse->zAuthContext = pSubitem->zName;
  116277. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  116278. testcase( i==SQLITE_DENY );
  116279. pParse->zAuthContext = zSavedAuthContext;
  116280. /* If the sub-query is a compound SELECT statement, then (by restrictions
  116281. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  116282. ** be of the form:
  116283. **
  116284. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  116285. **
  116286. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  116287. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  116288. ** OFFSET clauses and joins them to the left-hand-side of the original
  116289. ** using UNION ALL operators. In this case N is the number of simple
  116290. ** select statements in the compound sub-query.
  116291. **
  116292. ** Example:
  116293. **
  116294. ** SELECT a+1 FROM (
  116295. ** SELECT x FROM tab
  116296. ** UNION ALL
  116297. ** SELECT y FROM tab
  116298. ** UNION ALL
  116299. ** SELECT abs(z*2) FROM tab2
  116300. ** ) WHERE a!=5 ORDER BY 1
  116301. **
  116302. ** Transformed into:
  116303. **
  116304. ** SELECT x+1 FROM tab WHERE x+1!=5
  116305. ** UNION ALL
  116306. ** SELECT y+1 FROM tab WHERE y+1!=5
  116307. ** UNION ALL
  116308. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  116309. ** ORDER BY 1
  116310. **
  116311. ** We call this the "compound-subquery flattening".
  116312. */
  116313. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  116314. Select *pNew;
  116315. ExprList *pOrderBy = p->pOrderBy;
  116316. Expr *pLimit = p->pLimit;
  116317. Select *pPrior = p->pPrior;
  116318. p->pOrderBy = 0;
  116319. p->pSrc = 0;
  116320. p->pPrior = 0;
  116321. p->pLimit = 0;
  116322. pNew = sqlite3SelectDup(db, p, 0);
  116323. sqlite3SelectSetName(pNew, pSub->zSelName);
  116324. p->pLimit = pLimit;
  116325. p->pOrderBy = pOrderBy;
  116326. p->pSrc = pSrc;
  116327. p->op = TK_ALL;
  116328. if( pNew==0 ){
  116329. p->pPrior = pPrior;
  116330. }else{
  116331. pNew->pPrior = pPrior;
  116332. if( pPrior ) pPrior->pNext = pNew;
  116333. pNew->pNext = p;
  116334. p->pPrior = pNew;
  116335. SELECTTRACE(2,pParse,p,
  116336. ("compound-subquery flattener creates %s.%p as peer\n",
  116337. pNew->zSelName, pNew));
  116338. }
  116339. if( db->mallocFailed ) return 1;
  116340. }
  116341. /* Begin flattening the iFrom-th entry of the FROM clause
  116342. ** in the outer query.
  116343. */
  116344. pSub = pSub1 = pSubitem->pSelect;
  116345. /* Delete the transient table structure associated with the
  116346. ** subquery
  116347. */
  116348. sqlite3DbFree(db, pSubitem->zDatabase);
  116349. sqlite3DbFree(db, pSubitem->zName);
  116350. sqlite3DbFree(db, pSubitem->zAlias);
  116351. pSubitem->zDatabase = 0;
  116352. pSubitem->zName = 0;
  116353. pSubitem->zAlias = 0;
  116354. pSubitem->pSelect = 0;
  116355. /* Defer deleting the Table object associated with the
  116356. ** subquery until code generation is
  116357. ** complete, since there may still exist Expr.pTab entries that
  116358. ** refer to the subquery even after flattening. Ticket #3346.
  116359. **
  116360. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  116361. */
  116362. if( ALWAYS(pSubitem->pTab!=0) ){
  116363. Table *pTabToDel = pSubitem->pTab;
  116364. if( pTabToDel->nTabRef==1 ){
  116365. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  116366. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  116367. pToplevel->pZombieTab = pTabToDel;
  116368. }else{
  116369. pTabToDel->nTabRef--;
  116370. }
  116371. pSubitem->pTab = 0;
  116372. }
  116373. /* The following loop runs once for each term in a compound-subquery
  116374. ** flattening (as described above). If we are doing a different kind
  116375. ** of flattening - a flattening other than a compound-subquery flattening -
  116376. ** then this loop only runs once.
  116377. **
  116378. ** This loop moves all of the FROM elements of the subquery into the
  116379. ** the FROM clause of the outer query. Before doing this, remember
  116380. ** the cursor number for the original outer query FROM element in
  116381. ** iParent. The iParent cursor will never be used. Subsequent code
  116382. ** will scan expressions looking for iParent references and replace
  116383. ** those references with expressions that resolve to the subquery FROM
  116384. ** elements we are now copying in.
  116385. */
  116386. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  116387. int nSubSrc;
  116388. u8 jointype = 0;
  116389. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  116390. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  116391. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  116392. if( pSrc ){
  116393. assert( pParent==p ); /* First time through the loop */
  116394. jointype = pSubitem->fg.jointype;
  116395. }else{
  116396. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  116397. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  116398. if( pSrc==0 ){
  116399. assert( db->mallocFailed );
  116400. break;
  116401. }
  116402. }
  116403. /* The subquery uses a single slot of the FROM clause of the outer
  116404. ** query. If the subquery has more than one element in its FROM clause,
  116405. ** then expand the outer query to make space for it to hold all elements
  116406. ** of the subquery.
  116407. **
  116408. ** Example:
  116409. **
  116410. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  116411. **
  116412. ** The outer query has 3 slots in its FROM clause. One slot of the
  116413. ** outer query (the middle slot) is used by the subquery. The next
  116414. ** block of code will expand the outer query FROM clause to 4 slots.
  116415. ** The middle slot is expanded to two slots in order to make space
  116416. ** for the two elements in the FROM clause of the subquery.
  116417. */
  116418. if( nSubSrc>1 ){
  116419. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  116420. if( db->mallocFailed ){
  116421. break;
  116422. }
  116423. }
  116424. /* Transfer the FROM clause terms from the subquery into the
  116425. ** outer query.
  116426. */
  116427. for(i=0; i<nSubSrc; i++){
  116428. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  116429. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  116430. pSrc->a[i+iFrom] = pSubSrc->a[i];
  116431. iNewParent = pSubSrc->a[i].iCursor;
  116432. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  116433. }
  116434. pSrc->a[iFrom].fg.jointype = jointype;
  116435. /* Now begin substituting subquery result set expressions for
  116436. ** references to the iParent in the outer query.
  116437. **
  116438. ** Example:
  116439. **
  116440. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  116441. ** \ \_____________ subquery __________/ /
  116442. ** \_____________________ outer query ______________________________/
  116443. **
  116444. ** We look at every expression in the outer query and every place we see
  116445. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  116446. */
  116447. if( pSub->pOrderBy ){
  116448. /* At this point, any non-zero iOrderByCol values indicate that the
  116449. ** ORDER BY column expression is identical to the iOrderByCol'th
  116450. ** expression returned by SELECT statement pSub. Since these values
  116451. ** do not necessarily correspond to columns in SELECT statement pParent,
  116452. ** zero them before transfering the ORDER BY clause.
  116453. **
  116454. ** Not doing this may cause an error if a subsequent call to this
  116455. ** function attempts to flatten a compound sub-query into pParent
  116456. ** (the only way this can happen is if the compound sub-query is
  116457. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  116458. ExprList *pOrderBy = pSub->pOrderBy;
  116459. for(i=0; i<pOrderBy->nExpr; i++){
  116460. pOrderBy->a[i].u.x.iOrderByCol = 0;
  116461. }
  116462. assert( pParent->pOrderBy==0 );
  116463. pParent->pOrderBy = pOrderBy;
  116464. pSub->pOrderBy = 0;
  116465. }
  116466. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  116467. if( isLeftJoin>0 ){
  116468. setJoinExpr(pWhere, iNewParent);
  116469. }
  116470. pParent->pWhere = sqlite3ExprAnd(db, pWhere, pParent->pWhere);
  116471. if( db->mallocFailed==0 ){
  116472. SubstContext x;
  116473. x.pParse = pParse;
  116474. x.iTable = iParent;
  116475. x.iNewTable = iNewParent;
  116476. x.isLeftJoin = isLeftJoin;
  116477. x.pEList = pSub->pEList;
  116478. substSelect(&x, pParent, 0);
  116479. }
  116480. /* The flattened query is distinct if either the inner or the
  116481. ** outer query is distinct.
  116482. */
  116483. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  116484. /*
  116485. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  116486. **
  116487. ** One is tempted to try to add a and b to combine the limits. But this
  116488. ** does not work if either limit is negative.
  116489. */
  116490. if( pSub->pLimit ){
  116491. pParent->pLimit = pSub->pLimit;
  116492. pSub->pLimit = 0;
  116493. }
  116494. }
  116495. /* Finially, delete what is left of the subquery and return
  116496. ** success.
  116497. */
  116498. sqlite3SelectDelete(db, pSub1);
  116499. #if SELECTTRACE_ENABLED
  116500. if( sqlite3SelectTrace & 0x100 ){
  116501. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  116502. sqlite3TreeViewSelect(0, p, 0);
  116503. }
  116504. #endif
  116505. return 1;
  116506. }
  116507. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  116508. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  116509. /*
  116510. ** Make copies of relevant WHERE clause terms of the outer query into
  116511. ** the WHERE clause of subquery. Example:
  116512. **
  116513. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  116514. **
  116515. ** Transformed into:
  116516. **
  116517. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  116518. ** WHERE x=5 AND y=10;
  116519. **
  116520. ** The hope is that the terms added to the inner query will make it more
  116521. ** efficient.
  116522. **
  116523. ** Do not attempt this optimization if:
  116524. **
  116525. ** (1) (** This restriction was removed on 2017-09-29. We used to
  116526. ** disallow this optimization for aggregate subqueries, but now
  116527. ** it is allowed by putting the extra terms on the HAVING clause.
  116528. ** The added HAVING clause is pointless if the subquery lacks
  116529. ** a GROUP BY clause. But such a HAVING clause is also harmless
  116530. ** so there does not appear to be any reason to add extra logic
  116531. ** to suppress it. **)
  116532. **
  116533. ** (2) The inner query is the recursive part of a common table expression.
  116534. **
  116535. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  116536. ** close would change the meaning of the LIMIT).
  116537. **
  116538. ** (4) The inner query is the right operand of a LEFT JOIN and the
  116539. ** expression to be pushed down does not come from the ON clause
  116540. ** on that LEFT JOIN.
  116541. **
  116542. ** (5) The WHERE clause expression originates in the ON or USING clause
  116543. ** of a LEFT JOIN where iCursor is not the right-hand table of that
  116544. ** left join. An example:
  116545. **
  116546. ** SELECT *
  116547. ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
  116548. ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
  116549. ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
  116550. **
  116551. ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
  116552. ** But if the (b2=2) term were to be pushed down into the bb subquery,
  116553. ** then the (1,1,NULL) row would be suppressed.
  116554. **
  116555. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  116556. ** terms are duplicated into the subquery.
  116557. */
  116558. static int pushDownWhereTerms(
  116559. Parse *pParse, /* Parse context (for malloc() and error reporting) */
  116560. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  116561. Expr *pWhere, /* The WHERE clause of the outer query */
  116562. int iCursor, /* Cursor number of the subquery */
  116563. int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */
  116564. ){
  116565. Expr *pNew;
  116566. int nChng = 0;
  116567. if( pWhere==0 ) return 0;
  116568. if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
  116569. #ifdef SQLITE_DEBUG
  116570. /* Only the first term of a compound can have a WITH clause. But make
  116571. ** sure no other terms are marked SF_Recursive in case something changes
  116572. ** in the future.
  116573. */
  116574. {
  116575. Select *pX;
  116576. for(pX=pSubq; pX; pX=pX->pPrior){
  116577. assert( (pX->selFlags & (SF_Recursive))==0 );
  116578. }
  116579. }
  116580. #endif
  116581. if( pSubq->pLimit!=0 ){
  116582. return 0; /* restriction (3) */
  116583. }
  116584. while( pWhere->op==TK_AND ){
  116585. nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
  116586. iCursor, isLeftJoin);
  116587. pWhere = pWhere->pLeft;
  116588. }
  116589. if( isLeftJoin
  116590. && (ExprHasProperty(pWhere,EP_FromJoin)==0
  116591. || pWhere->iRightJoinTable!=iCursor)
  116592. ){
  116593. return 0; /* restriction (4) */
  116594. }
  116595. if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
  116596. return 0; /* restriction (5) */
  116597. }
  116598. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  116599. nChng++;
  116600. while( pSubq ){
  116601. SubstContext x;
  116602. pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
  116603. unsetJoinExpr(pNew, -1);
  116604. x.pParse = pParse;
  116605. x.iTable = iCursor;
  116606. x.iNewTable = iCursor;
  116607. x.isLeftJoin = 0;
  116608. x.pEList = pSubq->pEList;
  116609. pNew = substExpr(&x, pNew);
  116610. if( pSubq->selFlags & SF_Aggregate ){
  116611. pSubq->pHaving = sqlite3ExprAnd(pParse->db, pSubq->pHaving, pNew);
  116612. }else{
  116613. pSubq->pWhere = sqlite3ExprAnd(pParse->db, pSubq->pWhere, pNew);
  116614. }
  116615. pSubq = pSubq->pPrior;
  116616. }
  116617. }
  116618. return nChng;
  116619. }
  116620. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  116621. /*
  116622. ** The pFunc is the only aggregate function in the query. Check to see
  116623. ** if the query is a candidate for the min/max optimization.
  116624. **
  116625. ** If the query is a candidate for the min/max optimization, then set
  116626. ** *ppMinMax to be an ORDER BY clause to be used for the optimization
  116627. ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
  116628. ** whether pFunc is a min() or max() function.
  116629. **
  116630. ** If the query is not a candidate for the min/max optimization, return
  116631. ** WHERE_ORDERBY_NORMAL (which must be zero).
  116632. **
  116633. ** This routine must be called after aggregate functions have been
  116634. ** located but before their arguments have been subjected to aggregate
  116635. ** analysis.
  116636. */
  116637. static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
  116638. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  116639. ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */
  116640. const char *zFunc; /* Name of aggregate function pFunc */
  116641. ExprList *pOrderBy;
  116642. u8 sortOrder;
  116643. assert( *ppMinMax==0 );
  116644. assert( pFunc->op==TK_AGG_FUNCTION );
  116645. if( pEList==0 || pEList->nExpr!=1 ) return eRet;
  116646. zFunc = pFunc->u.zToken;
  116647. if( sqlite3StrICmp(zFunc, "min")==0 ){
  116648. eRet = WHERE_ORDERBY_MIN;
  116649. sortOrder = SQLITE_SO_ASC;
  116650. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  116651. eRet = WHERE_ORDERBY_MAX;
  116652. sortOrder = SQLITE_SO_DESC;
  116653. }else{
  116654. return eRet;
  116655. }
  116656. *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
  116657. assert( pOrderBy!=0 || db->mallocFailed );
  116658. if( pOrderBy ) pOrderBy->a[0].sortOrder = sortOrder;
  116659. return eRet;
  116660. }
  116661. /*
  116662. ** The select statement passed as the first argument is an aggregate query.
  116663. ** The second argument is the associated aggregate-info object. This
  116664. ** function tests if the SELECT is of the form:
  116665. **
  116666. ** SELECT count(*) FROM <tbl>
  116667. **
  116668. ** where table is a database table, not a sub-select or view. If the query
  116669. ** does match this pattern, then a pointer to the Table object representing
  116670. ** <tbl> is returned. Otherwise, 0 is returned.
  116671. */
  116672. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  116673. Table *pTab;
  116674. Expr *pExpr;
  116675. assert( !p->pGroupBy );
  116676. if( p->pWhere || p->pEList->nExpr!=1
  116677. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  116678. ){
  116679. return 0;
  116680. }
  116681. pTab = p->pSrc->a[0].pTab;
  116682. pExpr = p->pEList->a[0].pExpr;
  116683. assert( pTab && !pTab->pSelect && pExpr );
  116684. if( IsVirtual(pTab) ) return 0;
  116685. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  116686. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  116687. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  116688. if( pExpr->flags&EP_Distinct ) return 0;
  116689. return pTab;
  116690. }
  116691. /*
  116692. ** If the source-list item passed as an argument was augmented with an
  116693. ** INDEXED BY clause, then try to locate the specified index. If there
  116694. ** was such a clause and the named index cannot be found, return
  116695. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  116696. ** pFrom->pIndex and return SQLITE_OK.
  116697. */
  116698. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  116699. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  116700. Table *pTab = pFrom->pTab;
  116701. char *zIndexedBy = pFrom->u1.zIndexedBy;
  116702. Index *pIdx;
  116703. for(pIdx=pTab->pIndex;
  116704. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  116705. pIdx=pIdx->pNext
  116706. );
  116707. if( !pIdx ){
  116708. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  116709. pParse->checkSchema = 1;
  116710. return SQLITE_ERROR;
  116711. }
  116712. pFrom->pIBIndex = pIdx;
  116713. }
  116714. return SQLITE_OK;
  116715. }
  116716. /*
  116717. ** Detect compound SELECT statements that use an ORDER BY clause with
  116718. ** an alternative collating sequence.
  116719. **
  116720. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  116721. **
  116722. ** These are rewritten as a subquery:
  116723. **
  116724. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  116725. ** ORDER BY ... COLLATE ...
  116726. **
  116727. ** This transformation is necessary because the multiSelectOrderBy() routine
  116728. ** above that generates the code for a compound SELECT with an ORDER BY clause
  116729. ** uses a merge algorithm that requires the same collating sequence on the
  116730. ** result columns as on the ORDER BY clause. See ticket
  116731. ** http://www.sqlite.org/src/info/6709574d2a
  116732. **
  116733. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  116734. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  116735. ** there are COLLATE terms in the ORDER BY.
  116736. */
  116737. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  116738. int i;
  116739. Select *pNew;
  116740. Select *pX;
  116741. sqlite3 *db;
  116742. struct ExprList_item *a;
  116743. SrcList *pNewSrc;
  116744. Parse *pParse;
  116745. Token dummy;
  116746. if( p->pPrior==0 ) return WRC_Continue;
  116747. if( p->pOrderBy==0 ) return WRC_Continue;
  116748. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  116749. if( pX==0 ) return WRC_Continue;
  116750. a = p->pOrderBy->a;
  116751. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  116752. if( a[i].pExpr->flags & EP_Collate ) break;
  116753. }
  116754. if( i<0 ) return WRC_Continue;
  116755. /* If we reach this point, that means the transformation is required. */
  116756. pParse = pWalker->pParse;
  116757. db = pParse->db;
  116758. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  116759. if( pNew==0 ) return WRC_Abort;
  116760. memset(&dummy, 0, sizeof(dummy));
  116761. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  116762. if( pNewSrc==0 ) return WRC_Abort;
  116763. *pNew = *p;
  116764. p->pSrc = pNewSrc;
  116765. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  116766. p->op = TK_SELECT;
  116767. p->pWhere = 0;
  116768. pNew->pGroupBy = 0;
  116769. pNew->pHaving = 0;
  116770. pNew->pOrderBy = 0;
  116771. p->pPrior = 0;
  116772. p->pNext = 0;
  116773. p->pWith = 0;
  116774. p->selFlags &= ~SF_Compound;
  116775. assert( (p->selFlags & SF_Converted)==0 );
  116776. p->selFlags |= SF_Converted;
  116777. assert( pNew->pPrior!=0 );
  116778. pNew->pPrior->pNext = pNew;
  116779. pNew->pLimit = 0;
  116780. return WRC_Continue;
  116781. }
  116782. /*
  116783. ** Check to see if the FROM clause term pFrom has table-valued function
  116784. ** arguments. If it does, leave an error message in pParse and return
  116785. ** non-zero, since pFrom is not allowed to be a table-valued function.
  116786. */
  116787. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  116788. if( pFrom->fg.isTabFunc ){
  116789. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  116790. return 1;
  116791. }
  116792. return 0;
  116793. }
  116794. #ifndef SQLITE_OMIT_CTE
  116795. /*
  116796. ** Argument pWith (which may be NULL) points to a linked list of nested
  116797. ** WITH contexts, from inner to outermost. If the table identified by
  116798. ** FROM clause element pItem is really a common-table-expression (CTE)
  116799. ** then return a pointer to the CTE definition for that table. Otherwise
  116800. ** return NULL.
  116801. **
  116802. ** If a non-NULL value is returned, set *ppContext to point to the With
  116803. ** object that the returned CTE belongs to.
  116804. */
  116805. static struct Cte *searchWith(
  116806. With *pWith, /* Current innermost WITH clause */
  116807. struct SrcList_item *pItem, /* FROM clause element to resolve */
  116808. With **ppContext /* OUT: WITH clause return value belongs to */
  116809. ){
  116810. const char *zName;
  116811. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  116812. With *p;
  116813. for(p=pWith; p; p=p->pOuter){
  116814. int i;
  116815. for(i=0; i<p->nCte; i++){
  116816. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  116817. *ppContext = p;
  116818. return &p->a[i];
  116819. }
  116820. }
  116821. }
  116822. }
  116823. return 0;
  116824. }
  116825. /* The code generator maintains a stack of active WITH clauses
  116826. ** with the inner-most WITH clause being at the top of the stack.
  116827. **
  116828. ** This routine pushes the WITH clause passed as the second argument
  116829. ** onto the top of the stack. If argument bFree is true, then this
  116830. ** WITH clause will never be popped from the stack. In this case it
  116831. ** should be freed along with the Parse object. In other cases, when
  116832. ** bFree==0, the With object will be freed along with the SELECT
  116833. ** statement with which it is associated.
  116834. */
  116835. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  116836. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  116837. if( pWith ){
  116838. assert( pParse->pWith!=pWith );
  116839. pWith->pOuter = pParse->pWith;
  116840. pParse->pWith = pWith;
  116841. if( bFree ) pParse->pWithToFree = pWith;
  116842. }
  116843. }
  116844. /*
  116845. ** This function checks if argument pFrom refers to a CTE declared by
  116846. ** a WITH clause on the stack currently maintained by the parser. And,
  116847. ** if currently processing a CTE expression, if it is a recursive
  116848. ** reference to the current CTE.
  116849. **
  116850. ** If pFrom falls into either of the two categories above, pFrom->pTab
  116851. ** and other fields are populated accordingly. The caller should check
  116852. ** (pFrom->pTab!=0) to determine whether or not a successful match
  116853. ** was found.
  116854. **
  116855. ** Whether or not a match is found, SQLITE_OK is returned if no error
  116856. ** occurs. If an error does occur, an error message is stored in the
  116857. ** parser and some error code other than SQLITE_OK returned.
  116858. */
  116859. static int withExpand(
  116860. Walker *pWalker,
  116861. struct SrcList_item *pFrom
  116862. ){
  116863. Parse *pParse = pWalker->pParse;
  116864. sqlite3 *db = pParse->db;
  116865. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  116866. With *pWith; /* WITH clause that pCte belongs to */
  116867. assert( pFrom->pTab==0 );
  116868. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  116869. if( pCte ){
  116870. Table *pTab;
  116871. ExprList *pEList;
  116872. Select *pSel;
  116873. Select *pLeft; /* Left-most SELECT statement */
  116874. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  116875. With *pSavedWith; /* Initial value of pParse->pWith */
  116876. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  116877. ** recursive reference to CTE pCte. Leave an error in pParse and return
  116878. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  116879. ** In this case, proceed. */
  116880. if( pCte->zCteErr ){
  116881. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  116882. return SQLITE_ERROR;
  116883. }
  116884. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  116885. assert( pFrom->pTab==0 );
  116886. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  116887. if( pTab==0 ) return WRC_Abort;
  116888. pTab->nTabRef = 1;
  116889. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  116890. pTab->iPKey = -1;
  116891. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  116892. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  116893. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  116894. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  116895. assert( pFrom->pSelect );
  116896. /* Check if this is a recursive CTE. */
  116897. pSel = pFrom->pSelect;
  116898. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  116899. if( bMayRecursive ){
  116900. int i;
  116901. SrcList *pSrc = pFrom->pSelect->pSrc;
  116902. for(i=0; i<pSrc->nSrc; i++){
  116903. struct SrcList_item *pItem = &pSrc->a[i];
  116904. if( pItem->zDatabase==0
  116905. && pItem->zName!=0
  116906. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  116907. ){
  116908. pItem->pTab = pTab;
  116909. pItem->fg.isRecursive = 1;
  116910. pTab->nTabRef++;
  116911. pSel->selFlags |= SF_Recursive;
  116912. }
  116913. }
  116914. }
  116915. /* Only one recursive reference is permitted. */
  116916. if( pTab->nTabRef>2 ){
  116917. sqlite3ErrorMsg(
  116918. pParse, "multiple references to recursive table: %s", pCte->zName
  116919. );
  116920. return SQLITE_ERROR;
  116921. }
  116922. assert( pTab->nTabRef==1 ||
  116923. ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
  116924. pCte->zCteErr = "circular reference: %s";
  116925. pSavedWith = pParse->pWith;
  116926. pParse->pWith = pWith;
  116927. if( bMayRecursive ){
  116928. Select *pPrior = pSel->pPrior;
  116929. assert( pPrior->pWith==0 );
  116930. pPrior->pWith = pSel->pWith;
  116931. sqlite3WalkSelect(pWalker, pPrior);
  116932. pPrior->pWith = 0;
  116933. }else{
  116934. sqlite3WalkSelect(pWalker, pSel);
  116935. }
  116936. pParse->pWith = pWith;
  116937. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  116938. pEList = pLeft->pEList;
  116939. if( pCte->pCols ){
  116940. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  116941. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  116942. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  116943. );
  116944. pParse->pWith = pSavedWith;
  116945. return SQLITE_ERROR;
  116946. }
  116947. pEList = pCte->pCols;
  116948. }
  116949. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  116950. if( bMayRecursive ){
  116951. if( pSel->selFlags & SF_Recursive ){
  116952. pCte->zCteErr = "multiple recursive references: %s";
  116953. }else{
  116954. pCte->zCteErr = "recursive reference in a subquery: %s";
  116955. }
  116956. sqlite3WalkSelect(pWalker, pSel);
  116957. }
  116958. pCte->zCteErr = 0;
  116959. pParse->pWith = pSavedWith;
  116960. }
  116961. return SQLITE_OK;
  116962. }
  116963. #endif
  116964. #ifndef SQLITE_OMIT_CTE
  116965. /*
  116966. ** If the SELECT passed as the second argument has an associated WITH
  116967. ** clause, pop it from the stack stored as part of the Parse object.
  116968. **
  116969. ** This function is used as the xSelectCallback2() callback by
  116970. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  116971. ** names and other FROM clause elements.
  116972. */
  116973. static void selectPopWith(Walker *pWalker, Select *p){
  116974. Parse *pParse = pWalker->pParse;
  116975. if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
  116976. With *pWith = findRightmost(p)->pWith;
  116977. if( pWith!=0 ){
  116978. assert( pParse->pWith==pWith );
  116979. pParse->pWith = pWith->pOuter;
  116980. }
  116981. }
  116982. }
  116983. #else
  116984. #define selectPopWith 0
  116985. #endif
  116986. /*
  116987. ** This routine is a Walker callback for "expanding" a SELECT statement.
  116988. ** "Expanding" means to do the following:
  116989. **
  116990. ** (1) Make sure VDBE cursor numbers have been assigned to every
  116991. ** element of the FROM clause.
  116992. **
  116993. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  116994. ** defines FROM clause. When views appear in the FROM clause,
  116995. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  116996. ** that implements the view. A copy is made of the view's SELECT
  116997. ** statement so that we can freely modify or delete that statement
  116998. ** without worrying about messing up the persistent representation
  116999. ** of the view.
  117000. **
  117001. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  117002. ** on joins and the ON and USING clause of joins.
  117003. **
  117004. ** (4) Scan the list of columns in the result set (pEList) looking
  117005. ** for instances of the "*" operator or the TABLE.* operator.
  117006. ** If found, expand each "*" to be every column in every table
  117007. ** and TABLE.* to be every column in TABLE.
  117008. **
  117009. */
  117010. static int selectExpander(Walker *pWalker, Select *p){
  117011. Parse *pParse = pWalker->pParse;
  117012. int i, j, k;
  117013. SrcList *pTabList;
  117014. ExprList *pEList;
  117015. struct SrcList_item *pFrom;
  117016. sqlite3 *db = pParse->db;
  117017. Expr *pE, *pRight, *pExpr;
  117018. u16 selFlags = p->selFlags;
  117019. u32 elistFlags = 0;
  117020. p->selFlags |= SF_Expanded;
  117021. if( db->mallocFailed ){
  117022. return WRC_Abort;
  117023. }
  117024. assert( p->pSrc!=0 );
  117025. if( (selFlags & SF_Expanded)!=0 ){
  117026. return WRC_Prune;
  117027. }
  117028. pTabList = p->pSrc;
  117029. pEList = p->pEList;
  117030. sqlite3WithPush(pParse, p->pWith, 0);
  117031. /* Make sure cursor numbers have been assigned to all entries in
  117032. ** the FROM clause of the SELECT statement.
  117033. */
  117034. sqlite3SrcListAssignCursors(pParse, pTabList);
  117035. /* Look up every table named in the FROM clause of the select. If
  117036. ** an entry of the FROM clause is a subquery instead of a table or view,
  117037. ** then create a transient table structure to describe the subquery.
  117038. */
  117039. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  117040. Table *pTab;
  117041. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  117042. if( pFrom->fg.isRecursive ) continue;
  117043. assert( pFrom->pTab==0 );
  117044. #ifndef SQLITE_OMIT_CTE
  117045. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  117046. if( pFrom->pTab ) {} else
  117047. #endif
  117048. if( pFrom->zName==0 ){
  117049. #ifndef SQLITE_OMIT_SUBQUERY
  117050. Select *pSel = pFrom->pSelect;
  117051. /* A sub-query in the FROM clause of a SELECT */
  117052. assert( pSel!=0 );
  117053. assert( pFrom->pTab==0 );
  117054. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  117055. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  117056. if( pTab==0 ) return WRC_Abort;
  117057. pTab->nTabRef = 1;
  117058. if( pFrom->zAlias ){
  117059. pTab->zName = sqlite3DbStrDup(db, pFrom->zAlias);
  117060. }else{
  117061. pTab->zName = sqlite3MPrintf(db, "subquery_%p", (void*)pTab);
  117062. }
  117063. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  117064. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  117065. pTab->iPKey = -1;
  117066. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  117067. pTab->tabFlags |= TF_Ephemeral;
  117068. #endif
  117069. }else{
  117070. /* An ordinary table or view name in the FROM clause */
  117071. assert( pFrom->pTab==0 );
  117072. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  117073. if( pTab==0 ) return WRC_Abort;
  117074. if( pTab->nTabRef>=0xffff ){
  117075. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  117076. pTab->zName);
  117077. pFrom->pTab = 0;
  117078. return WRC_Abort;
  117079. }
  117080. pTab->nTabRef++;
  117081. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  117082. return WRC_Abort;
  117083. }
  117084. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  117085. if( IsVirtual(pTab) || pTab->pSelect ){
  117086. i16 nCol;
  117087. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  117088. assert( pFrom->pSelect==0 );
  117089. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  117090. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  117091. nCol = pTab->nCol;
  117092. pTab->nCol = -1;
  117093. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  117094. pTab->nCol = nCol;
  117095. }
  117096. #endif
  117097. }
  117098. /* Locate the index named by the INDEXED BY clause, if any. */
  117099. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  117100. return WRC_Abort;
  117101. }
  117102. }
  117103. /* Process NATURAL keywords, and ON and USING clauses of joins.
  117104. */
  117105. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  117106. return WRC_Abort;
  117107. }
  117108. /* For every "*" that occurs in the column list, insert the names of
  117109. ** all columns in all tables. And for every TABLE.* insert the names
  117110. ** of all columns in TABLE. The parser inserted a special expression
  117111. ** with the TK_ASTERISK operator for each "*" that it found in the column
  117112. ** list. The following code just has to locate the TK_ASTERISK
  117113. ** expressions and expand each one to the list of all columns in
  117114. ** all tables.
  117115. **
  117116. ** The first loop just checks to see if there are any "*" operators
  117117. ** that need expanding.
  117118. */
  117119. for(k=0; k<pEList->nExpr; k++){
  117120. pE = pEList->a[k].pExpr;
  117121. if( pE->op==TK_ASTERISK ) break;
  117122. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  117123. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  117124. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  117125. elistFlags |= pE->flags;
  117126. }
  117127. if( k<pEList->nExpr ){
  117128. /*
  117129. ** If we get here it means the result set contains one or more "*"
  117130. ** operators that need to be expanded. Loop through each expression
  117131. ** in the result set and expand them one by one.
  117132. */
  117133. struct ExprList_item *a = pEList->a;
  117134. ExprList *pNew = 0;
  117135. int flags = pParse->db->flags;
  117136. int longNames = (flags & SQLITE_FullColNames)!=0
  117137. && (flags & SQLITE_ShortColNames)==0;
  117138. for(k=0; k<pEList->nExpr; k++){
  117139. pE = a[k].pExpr;
  117140. elistFlags |= pE->flags;
  117141. pRight = pE->pRight;
  117142. assert( pE->op!=TK_DOT || pRight!=0 );
  117143. if( pE->op!=TK_ASTERISK
  117144. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  117145. ){
  117146. /* This particular expression does not need to be expanded.
  117147. */
  117148. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  117149. if( pNew ){
  117150. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  117151. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  117152. a[k].zName = 0;
  117153. a[k].zSpan = 0;
  117154. }
  117155. a[k].pExpr = 0;
  117156. }else{
  117157. /* This expression is a "*" or a "TABLE.*" and needs to be
  117158. ** expanded. */
  117159. int tableSeen = 0; /* Set to 1 when TABLE matches */
  117160. char *zTName = 0; /* text of name of TABLE */
  117161. if( pE->op==TK_DOT ){
  117162. assert( pE->pLeft!=0 );
  117163. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  117164. zTName = pE->pLeft->u.zToken;
  117165. }
  117166. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  117167. Table *pTab = pFrom->pTab;
  117168. Select *pSub = pFrom->pSelect;
  117169. char *zTabName = pFrom->zAlias;
  117170. const char *zSchemaName = 0;
  117171. int iDb;
  117172. if( zTabName==0 ){
  117173. zTabName = pTab->zName;
  117174. }
  117175. if( db->mallocFailed ) break;
  117176. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  117177. pSub = 0;
  117178. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  117179. continue;
  117180. }
  117181. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  117182. zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
  117183. }
  117184. for(j=0; j<pTab->nCol; j++){
  117185. char *zName = pTab->aCol[j].zName;
  117186. char *zColname; /* The computed column name */
  117187. char *zToFree; /* Malloced string that needs to be freed */
  117188. Token sColname; /* Computed column name as a token */
  117189. assert( zName );
  117190. if( zTName && pSub
  117191. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  117192. ){
  117193. continue;
  117194. }
  117195. /* If a column is marked as 'hidden', omit it from the expanded
  117196. ** result-set list unless the SELECT has the SF_IncludeHidden
  117197. ** bit set.
  117198. */
  117199. if( (p->selFlags & SF_IncludeHidden)==0
  117200. && IsHiddenColumn(&pTab->aCol[j])
  117201. ){
  117202. continue;
  117203. }
  117204. tableSeen = 1;
  117205. if( i>0 && zTName==0 ){
  117206. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  117207. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  117208. ){
  117209. /* In a NATURAL join, omit the join columns from the
  117210. ** table to the right of the join */
  117211. continue;
  117212. }
  117213. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  117214. /* In a join with a USING clause, omit columns in the
  117215. ** using clause from the table on the right. */
  117216. continue;
  117217. }
  117218. }
  117219. pRight = sqlite3Expr(db, TK_ID, zName);
  117220. zColname = zName;
  117221. zToFree = 0;
  117222. if( longNames || pTabList->nSrc>1 ){
  117223. Expr *pLeft;
  117224. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  117225. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  117226. if( zSchemaName ){
  117227. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  117228. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
  117229. }
  117230. if( longNames ){
  117231. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  117232. zToFree = zColname;
  117233. }
  117234. }else{
  117235. pExpr = pRight;
  117236. }
  117237. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  117238. sqlite3TokenInit(&sColname, zColname);
  117239. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  117240. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  117241. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  117242. if( pSub ){
  117243. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  117244. testcase( pX->zSpan==0 );
  117245. }else{
  117246. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  117247. zSchemaName, zTabName, zColname);
  117248. testcase( pX->zSpan==0 );
  117249. }
  117250. pX->bSpanIsTab = 1;
  117251. }
  117252. sqlite3DbFree(db, zToFree);
  117253. }
  117254. }
  117255. if( !tableSeen ){
  117256. if( zTName ){
  117257. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  117258. }else{
  117259. sqlite3ErrorMsg(pParse, "no tables specified");
  117260. }
  117261. }
  117262. }
  117263. }
  117264. sqlite3ExprListDelete(db, pEList);
  117265. p->pEList = pNew;
  117266. }
  117267. if( p->pEList ){
  117268. if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  117269. sqlite3ErrorMsg(pParse, "too many columns in result set");
  117270. return WRC_Abort;
  117271. }
  117272. if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
  117273. p->selFlags |= SF_ComplexResult;
  117274. }
  117275. }
  117276. return WRC_Continue;
  117277. }
  117278. /*
  117279. ** No-op routine for the parse-tree walker.
  117280. **
  117281. ** When this routine is the Walker.xExprCallback then expression trees
  117282. ** are walked without any actions being taken at each node. Presumably,
  117283. ** when this routine is used for Walker.xExprCallback then
  117284. ** Walker.xSelectCallback is set to do something useful for every
  117285. ** subquery in the parser tree.
  117286. */
  117287. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  117288. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  117289. return WRC_Continue;
  117290. }
  117291. /*
  117292. ** No-op routine for the parse-tree walker for SELECT statements.
  117293. ** subquery in the parser tree.
  117294. */
  117295. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
  117296. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  117297. return WRC_Continue;
  117298. }
  117299. #if SQLITE_DEBUG
  117300. /*
  117301. ** Always assert. This xSelectCallback2 implementation proves that the
  117302. ** xSelectCallback2 is never invoked.
  117303. */
  117304. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
  117305. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  117306. assert( 0 );
  117307. }
  117308. #endif
  117309. /*
  117310. ** This routine "expands" a SELECT statement and all of its subqueries.
  117311. ** For additional information on what it means to "expand" a SELECT
  117312. ** statement, see the comment on the selectExpand worker callback above.
  117313. **
  117314. ** Expanding a SELECT statement is the first step in processing a
  117315. ** SELECT statement. The SELECT statement must be expanded before
  117316. ** name resolution is performed.
  117317. **
  117318. ** If anything goes wrong, an error message is written into pParse.
  117319. ** The calling function can detect the problem by looking at pParse->nErr
  117320. ** and/or pParse->db->mallocFailed.
  117321. */
  117322. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  117323. Walker w;
  117324. w.xExprCallback = sqlite3ExprWalkNoop;
  117325. w.pParse = pParse;
  117326. if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
  117327. w.xSelectCallback = convertCompoundSelectToSubquery;
  117328. w.xSelectCallback2 = 0;
  117329. sqlite3WalkSelect(&w, pSelect);
  117330. }
  117331. w.xSelectCallback = selectExpander;
  117332. w.xSelectCallback2 = selectPopWith;
  117333. sqlite3WalkSelect(&w, pSelect);
  117334. }
  117335. #ifndef SQLITE_OMIT_SUBQUERY
  117336. /*
  117337. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  117338. ** interface.
  117339. **
  117340. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  117341. ** information to the Table structure that represents the result set
  117342. ** of that subquery.
  117343. **
  117344. ** The Table structure that represents the result set was constructed
  117345. ** by selectExpander() but the type and collation information was omitted
  117346. ** at that point because identifiers had not yet been resolved. This
  117347. ** routine is called after identifier resolution.
  117348. */
  117349. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  117350. Parse *pParse;
  117351. int i;
  117352. SrcList *pTabList;
  117353. struct SrcList_item *pFrom;
  117354. assert( p->selFlags & SF_Resolved );
  117355. assert( (p->selFlags & SF_HasTypeInfo)==0 );
  117356. p->selFlags |= SF_HasTypeInfo;
  117357. pParse = pWalker->pParse;
  117358. pTabList = p->pSrc;
  117359. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  117360. Table *pTab = pFrom->pTab;
  117361. assert( pTab!=0 );
  117362. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  117363. /* A sub-query in the FROM clause of a SELECT */
  117364. Select *pSel = pFrom->pSelect;
  117365. if( pSel ){
  117366. while( pSel->pPrior ) pSel = pSel->pPrior;
  117367. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
  117368. }
  117369. }
  117370. }
  117371. }
  117372. #endif
  117373. /*
  117374. ** This routine adds datatype and collating sequence information to
  117375. ** the Table structures of all FROM-clause subqueries in a
  117376. ** SELECT statement.
  117377. **
  117378. ** Use this routine after name resolution.
  117379. */
  117380. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  117381. #ifndef SQLITE_OMIT_SUBQUERY
  117382. Walker w;
  117383. w.xSelectCallback = sqlite3SelectWalkNoop;
  117384. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  117385. w.xExprCallback = sqlite3ExprWalkNoop;
  117386. w.pParse = pParse;
  117387. sqlite3WalkSelect(&w, pSelect);
  117388. #endif
  117389. }
  117390. /*
  117391. ** This routine sets up a SELECT statement for processing. The
  117392. ** following is accomplished:
  117393. **
  117394. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  117395. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  117396. ** * ON and USING clauses are shifted into WHERE statements
  117397. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  117398. ** * Identifiers in expression are matched to tables.
  117399. **
  117400. ** This routine acts recursively on all subqueries within the SELECT.
  117401. */
  117402. SQLITE_PRIVATE void sqlite3SelectPrep(
  117403. Parse *pParse, /* The parser context */
  117404. Select *p, /* The SELECT statement being coded. */
  117405. NameContext *pOuterNC /* Name context for container */
  117406. ){
  117407. assert( p!=0 || pParse->db->mallocFailed );
  117408. if( pParse->db->mallocFailed ) return;
  117409. if( p->selFlags & SF_HasTypeInfo ) return;
  117410. sqlite3SelectExpand(pParse, p);
  117411. if( pParse->nErr || pParse->db->mallocFailed ) return;
  117412. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  117413. if( pParse->nErr || pParse->db->mallocFailed ) return;
  117414. sqlite3SelectAddTypeInfo(pParse, p);
  117415. }
  117416. /*
  117417. ** Reset the aggregate accumulator.
  117418. **
  117419. ** The aggregate accumulator is a set of memory cells that hold
  117420. ** intermediate results while calculating an aggregate. This
  117421. ** routine generates code that stores NULLs in all of those memory
  117422. ** cells.
  117423. */
  117424. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  117425. Vdbe *v = pParse->pVdbe;
  117426. int i;
  117427. struct AggInfo_func *pFunc;
  117428. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  117429. if( nReg==0 ) return;
  117430. #ifdef SQLITE_DEBUG
  117431. /* Verify that all AggInfo registers are within the range specified by
  117432. ** AggInfo.mnReg..AggInfo.mxReg */
  117433. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  117434. for(i=0; i<pAggInfo->nColumn; i++){
  117435. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  117436. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  117437. }
  117438. for(i=0; i<pAggInfo->nFunc; i++){
  117439. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  117440. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  117441. }
  117442. #endif
  117443. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  117444. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  117445. if( pFunc->iDistinct>=0 ){
  117446. Expr *pE = pFunc->pExpr;
  117447. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  117448. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  117449. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  117450. "argument");
  117451. pFunc->iDistinct = -1;
  117452. }else{
  117453. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  117454. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  117455. (char*)pKeyInfo, P4_KEYINFO);
  117456. }
  117457. }
  117458. }
  117459. }
  117460. /*
  117461. ** Invoke the OP_AggFinalize opcode for every aggregate function
  117462. ** in the AggInfo structure.
  117463. */
  117464. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  117465. Vdbe *v = pParse->pVdbe;
  117466. int i;
  117467. struct AggInfo_func *pF;
  117468. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  117469. ExprList *pList = pF->pExpr->x.pList;
  117470. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  117471. sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
  117472. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  117473. }
  117474. }
  117475. /*
  117476. ** Update the accumulator memory cells for an aggregate based on
  117477. ** the current cursor position.
  117478. */
  117479. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  117480. Vdbe *v = pParse->pVdbe;
  117481. int i;
  117482. int regHit = 0;
  117483. int addrHitTest = 0;
  117484. struct AggInfo_func *pF;
  117485. struct AggInfo_col *pC;
  117486. pAggInfo->directMode = 1;
  117487. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  117488. int nArg;
  117489. int addrNext = 0;
  117490. int regAgg;
  117491. ExprList *pList = pF->pExpr->x.pList;
  117492. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  117493. if( pList ){
  117494. nArg = pList->nExpr;
  117495. regAgg = sqlite3GetTempRange(pParse, nArg);
  117496. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  117497. }else{
  117498. nArg = 0;
  117499. regAgg = 0;
  117500. }
  117501. if( pF->iDistinct>=0 ){
  117502. addrNext = sqlite3VdbeMakeLabel(v);
  117503. testcase( nArg==0 ); /* Error condition */
  117504. testcase( nArg>1 ); /* Also an error */
  117505. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  117506. }
  117507. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  117508. CollSeq *pColl = 0;
  117509. struct ExprList_item *pItem;
  117510. int j;
  117511. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  117512. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  117513. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  117514. }
  117515. if( !pColl ){
  117516. pColl = pParse->db->pDfltColl;
  117517. }
  117518. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  117519. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  117520. }
  117521. sqlite3VdbeAddOp3(v, OP_AggStep0, 0, regAgg, pF->iMem);
  117522. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  117523. sqlite3VdbeChangeP5(v, (u8)nArg);
  117524. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  117525. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  117526. if( addrNext ){
  117527. sqlite3VdbeResolveLabel(v, addrNext);
  117528. sqlite3ExprCacheClear(pParse);
  117529. }
  117530. }
  117531. /* Before populating the accumulator registers, clear the column cache.
  117532. ** Otherwise, if any of the required column values are already present
  117533. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  117534. ** to pC->iMem. But by the time the value is used, the original register
  117535. ** may have been used, invalidating the underlying buffer holding the
  117536. ** text or blob value. See ticket [883034dcb5].
  117537. **
  117538. ** Another solution would be to change the OP_SCopy used to copy cached
  117539. ** values to an OP_Copy.
  117540. */
  117541. if( regHit ){
  117542. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  117543. }
  117544. sqlite3ExprCacheClear(pParse);
  117545. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  117546. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  117547. }
  117548. pAggInfo->directMode = 0;
  117549. sqlite3ExprCacheClear(pParse);
  117550. if( addrHitTest ){
  117551. sqlite3VdbeJumpHere(v, addrHitTest);
  117552. }
  117553. }
  117554. /*
  117555. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  117556. ** count(*) query ("SELECT count(*) FROM pTab").
  117557. */
  117558. #ifndef SQLITE_OMIT_EXPLAIN
  117559. static void explainSimpleCount(
  117560. Parse *pParse, /* Parse context */
  117561. Table *pTab, /* Table being queried */
  117562. Index *pIdx /* Index used to optimize scan, or NULL */
  117563. ){
  117564. if( pParse->explain==2 ){
  117565. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  117566. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  117567. pTab->zName,
  117568. bCover ? " USING COVERING INDEX " : "",
  117569. bCover ? pIdx->zName : ""
  117570. );
  117571. sqlite3VdbeAddOp4(
  117572. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  117573. );
  117574. }
  117575. }
  117576. #else
  117577. # define explainSimpleCount(a,b,c)
  117578. #endif
  117579. /*
  117580. ** sqlite3WalkExpr() callback used by havingToWhere().
  117581. **
  117582. ** If the node passed to the callback is a TK_AND node, return
  117583. ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
  117584. **
  117585. ** Otherwise, return WRC_Prune. In this case, also check if the
  117586. ** sub-expression matches the criteria for being moved to the WHERE
  117587. ** clause. If so, add it to the WHERE clause and replace the sub-expression
  117588. ** within the HAVING expression with a constant "1".
  117589. */
  117590. static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
  117591. if( pExpr->op!=TK_AND ){
  117592. Select *pS = pWalker->u.pSelect;
  117593. if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
  117594. sqlite3 *db = pWalker->pParse->db;
  117595. Expr *pNew = sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[1], 0);
  117596. if( pNew ){
  117597. Expr *pWhere = pS->pWhere;
  117598. SWAP(Expr, *pNew, *pExpr);
  117599. pNew = sqlite3ExprAnd(db, pWhere, pNew);
  117600. pS->pWhere = pNew;
  117601. pWalker->eCode = 1;
  117602. }
  117603. }
  117604. return WRC_Prune;
  117605. }
  117606. return WRC_Continue;
  117607. }
  117608. /*
  117609. ** Transfer eligible terms from the HAVING clause of a query, which is
  117610. ** processed after grouping, to the WHERE clause, which is processed before
  117611. ** grouping. For example, the query:
  117612. **
  117613. ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
  117614. **
  117615. ** can be rewritten as:
  117616. **
  117617. ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
  117618. **
  117619. ** A term of the HAVING expression is eligible for transfer if it consists
  117620. ** entirely of constants and expressions that are also GROUP BY terms that
  117621. ** use the "BINARY" collation sequence.
  117622. */
  117623. static void havingToWhere(Parse *pParse, Select *p){
  117624. Walker sWalker;
  117625. memset(&sWalker, 0, sizeof(sWalker));
  117626. sWalker.pParse = pParse;
  117627. sWalker.xExprCallback = havingToWhereExprCb;
  117628. sWalker.u.pSelect = p;
  117629. sqlite3WalkExpr(&sWalker, p->pHaving);
  117630. #if SELECTTRACE_ENABLED
  117631. if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
  117632. SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
  117633. sqlite3TreeViewSelect(0, p, 0);
  117634. }
  117635. #endif
  117636. }
  117637. /*
  117638. ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
  117639. ** If it is, then return the SrcList_item for the prior view. If it is not,
  117640. ** then return 0.
  117641. */
  117642. static struct SrcList_item *isSelfJoinView(
  117643. SrcList *pTabList, /* Search for self-joins in this FROM clause */
  117644. struct SrcList_item *pThis /* Search for prior reference to this subquery */
  117645. ){
  117646. struct SrcList_item *pItem;
  117647. for(pItem = pTabList->a; pItem<pThis; pItem++){
  117648. if( pItem->pSelect==0 ) continue;
  117649. if( pItem->fg.viaCoroutine ) continue;
  117650. if( pItem->zName==0 ) continue;
  117651. if( sqlite3_stricmp(pItem->zDatabase, pThis->zDatabase)!=0 ) continue;
  117652. if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
  117653. if( sqlite3ExprCompare(0,
  117654. pThis->pSelect->pWhere, pItem->pSelect->pWhere, -1)
  117655. ){
  117656. /* The view was modified by some other optimization such as
  117657. ** pushDownWhereTerms() */
  117658. continue;
  117659. }
  117660. return pItem;
  117661. }
  117662. return 0;
  117663. }
  117664. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  117665. /*
  117666. ** Attempt to transform a query of the form
  117667. **
  117668. ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
  117669. **
  117670. ** Into this:
  117671. **
  117672. ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
  117673. **
  117674. ** The transformation only works if all of the following are true:
  117675. **
  117676. ** * The subquery is a UNION ALL of two or more terms
  117677. ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
  117678. ** * The outer query is a simple count(*)
  117679. **
  117680. ** Return TRUE if the optimization is undertaken.
  117681. */
  117682. static int countOfViewOptimization(Parse *pParse, Select *p){
  117683. Select *pSub, *pPrior;
  117684. Expr *pExpr;
  117685. Expr *pCount;
  117686. sqlite3 *db;
  117687. if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
  117688. if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
  117689. pExpr = p->pEList->a[0].pExpr;
  117690. if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
  117691. if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
  117692. if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
  117693. if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
  117694. pSub = p->pSrc->a[0].pSelect;
  117695. if( pSub==0 ) return 0; /* The FROM is a subquery */
  117696. if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
  117697. do{
  117698. if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
  117699. if( pSub->pWhere ) return 0; /* No WHERE clause */
  117700. if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
  117701. pSub = pSub->pPrior; /* Repeat over compound */
  117702. }while( pSub );
  117703. /* If we reach this point then it is OK to perform the transformation */
  117704. db = pParse->db;
  117705. pCount = pExpr;
  117706. pExpr = 0;
  117707. pSub = p->pSrc->a[0].pSelect;
  117708. p->pSrc->a[0].pSelect = 0;
  117709. sqlite3SrcListDelete(db, p->pSrc);
  117710. p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
  117711. while( pSub ){
  117712. Expr *pTerm;
  117713. pPrior = pSub->pPrior;
  117714. pSub->pPrior = 0;
  117715. pSub->pNext = 0;
  117716. pSub->selFlags |= SF_Aggregate;
  117717. pSub->selFlags &= ~SF_Compound;
  117718. pSub->nSelectRow = 0;
  117719. sqlite3ExprListDelete(db, pSub->pEList);
  117720. pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
  117721. pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
  117722. pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  117723. sqlite3PExprAddSelect(pParse, pTerm, pSub);
  117724. if( pExpr==0 ){
  117725. pExpr = pTerm;
  117726. }else{
  117727. pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
  117728. }
  117729. pSub = pPrior;
  117730. }
  117731. p->pEList->a[0].pExpr = pExpr;
  117732. p->selFlags &= ~SF_Aggregate;
  117733. #if SELECTTRACE_ENABLED
  117734. if( sqlite3SelectTrace & 0x400 ){
  117735. SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
  117736. sqlite3TreeViewSelect(0, p, 0);
  117737. }
  117738. #endif
  117739. return 1;
  117740. }
  117741. #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
  117742. /*
  117743. ** Generate code for the SELECT statement given in the p argument.
  117744. **
  117745. ** The results are returned according to the SelectDest structure.
  117746. ** See comments in sqliteInt.h for further information.
  117747. **
  117748. ** This routine returns the number of errors. If any errors are
  117749. ** encountered, then an appropriate error message is left in
  117750. ** pParse->zErrMsg.
  117751. **
  117752. ** This routine does NOT free the Select structure passed in. The
  117753. ** calling function needs to do that.
  117754. */
  117755. SQLITE_PRIVATE int sqlite3Select(
  117756. Parse *pParse, /* The parser context */
  117757. Select *p, /* The SELECT statement being coded. */
  117758. SelectDest *pDest /* What to do with the query results */
  117759. ){
  117760. int i, j; /* Loop counters */
  117761. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  117762. Vdbe *v; /* The virtual machine under construction */
  117763. int isAgg; /* True for select lists like "count(*)" */
  117764. ExprList *pEList = 0; /* List of columns to extract. */
  117765. SrcList *pTabList; /* List of tables to select from */
  117766. Expr *pWhere; /* The WHERE clause. May be NULL */
  117767. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  117768. Expr *pHaving; /* The HAVING clause. May be NULL */
  117769. int rc = 1; /* Value to return from this function */
  117770. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  117771. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  117772. AggInfo sAggInfo; /* Information used by aggregate queries */
  117773. int iEnd; /* Address of the end of the query */
  117774. sqlite3 *db; /* The database connection */
  117775. ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
  117776. u8 minMaxFlag; /* Flag for min/max queries */
  117777. #ifndef SQLITE_OMIT_EXPLAIN
  117778. int iRestoreSelectId = pParse->iSelectId;
  117779. pParse->iSelectId = pParse->iNextSelectId++;
  117780. #endif
  117781. db = pParse->db;
  117782. if( p==0 || db->mallocFailed || pParse->nErr ){
  117783. return 1;
  117784. }
  117785. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  117786. memset(&sAggInfo, 0, sizeof(sAggInfo));
  117787. #if SELECTTRACE_ENABLED
  117788. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  117789. if( sqlite3SelectTrace & 0x100 ){
  117790. sqlite3TreeViewSelect(0, p, 0);
  117791. }
  117792. #endif
  117793. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  117794. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  117795. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  117796. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  117797. if( IgnorableOrderby(pDest) ){
  117798. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  117799. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  117800. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  117801. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  117802. /* If ORDER BY makes no difference in the output then neither does
  117803. ** DISTINCT so it can be removed too. */
  117804. sqlite3ExprListDelete(db, p->pOrderBy);
  117805. p->pOrderBy = 0;
  117806. p->selFlags &= ~SF_Distinct;
  117807. }
  117808. sqlite3SelectPrep(pParse, p, 0);
  117809. memset(&sSort, 0, sizeof(sSort));
  117810. sSort.pOrderBy = p->pOrderBy;
  117811. pTabList = p->pSrc;
  117812. if( pParse->nErr || db->mallocFailed ){
  117813. goto select_end;
  117814. }
  117815. assert( p->pEList!=0 );
  117816. isAgg = (p->selFlags & SF_Aggregate)!=0;
  117817. #if SELECTTRACE_ENABLED
  117818. if( sqlite3SelectTrace & 0x100 ){
  117819. SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
  117820. sqlite3TreeViewSelect(0, p, 0);
  117821. }
  117822. #endif
  117823. /* Get a pointer the VDBE under construction, allocating a new VDBE if one
  117824. ** does not already exist */
  117825. v = sqlite3GetVdbe(pParse);
  117826. if( v==0 ) goto select_end;
  117827. if( pDest->eDest==SRT_Output ){
  117828. generateColumnNames(pParse, p);
  117829. }
  117830. /* Try to various optimizations (flattening subqueries, and strength
  117831. ** reduction of join operators) in the FROM clause up into the main query
  117832. */
  117833. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  117834. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  117835. struct SrcList_item *pItem = &pTabList->a[i];
  117836. Select *pSub = pItem->pSelect;
  117837. Table *pTab = pItem->pTab;
  117838. /* Convert LEFT JOIN into JOIN if there are terms of the right table
  117839. ** of the LEFT JOIN used in the WHERE clause.
  117840. */
  117841. if( (pItem->fg.jointype & JT_LEFT)!=0
  117842. && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
  117843. && OptimizationEnabled(db, SQLITE_SimplifyJoin)
  117844. ){
  117845. SELECTTRACE(0x100,pParse,p,
  117846. ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
  117847. pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
  117848. unsetJoinExpr(p->pWhere, pItem->iCursor);
  117849. }
  117850. /* No futher action if this term of the FROM clause is no a subquery */
  117851. if( pSub==0 ) continue;
  117852. /* Catch mismatch in the declared columns of a view and the number of
  117853. ** columns in the SELECT on the RHS */
  117854. if( pTab->nCol!=pSub->pEList->nExpr ){
  117855. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  117856. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  117857. goto select_end;
  117858. }
  117859. /* Do not try to flatten an aggregate subquery.
  117860. **
  117861. ** Flattening an aggregate subquery is only possible if the outer query
  117862. ** is not a join. But if the outer query is not a join, then the subquery
  117863. ** will be implemented as a co-routine and there is no advantage to
  117864. ** flattening in that case.
  117865. */
  117866. if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
  117867. assert( pSub->pGroupBy==0 );
  117868. /* If the outer query contains a "complex" result set (that is,
  117869. ** if the result set of the outer query uses functions or subqueries)
  117870. ** and if the subquery contains an ORDER BY clause and if
  117871. ** it will be implemented as a co-routine, then do not flatten. This
  117872. ** restriction allows SQL constructs like this:
  117873. **
  117874. ** SELECT expensive_function(x)
  117875. ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  117876. **
  117877. ** The expensive_function() is only computed on the 10 rows that
  117878. ** are output, rather than every row of the table.
  117879. **
  117880. ** The requirement that the outer query have a complex result set
  117881. ** means that flattening does occur on simpler SQL constraints without
  117882. ** the expensive_function() like:
  117883. **
  117884. ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  117885. */
  117886. if( pSub->pOrderBy!=0
  117887. && i==0
  117888. && (p->selFlags & SF_ComplexResult)!=0
  117889. && (pTabList->nSrc==1
  117890. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
  117891. ){
  117892. continue;
  117893. }
  117894. if( flattenSubquery(pParse, p, i, isAgg) ){
  117895. /* This subquery can be absorbed into its parent. */
  117896. i = -1;
  117897. }
  117898. pTabList = p->pSrc;
  117899. if( db->mallocFailed ) goto select_end;
  117900. if( !IgnorableOrderby(pDest) ){
  117901. sSort.pOrderBy = p->pOrderBy;
  117902. }
  117903. }
  117904. #endif
  117905. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  117906. /* Handle compound SELECT statements using the separate multiSelect()
  117907. ** procedure.
  117908. */
  117909. if( p->pPrior ){
  117910. rc = multiSelect(pParse, p, pDest);
  117911. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  117912. #if SELECTTRACE_ENABLED
  117913. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  117914. #endif
  117915. return rc;
  117916. }
  117917. #endif
  117918. /* For each term in the FROM clause, do two things:
  117919. ** (1) Authorized unreferenced tables
  117920. ** (2) Generate code for all sub-queries
  117921. */
  117922. for(i=0; i<pTabList->nSrc; i++){
  117923. struct SrcList_item *pItem = &pTabList->a[i];
  117924. SelectDest dest;
  117925. Select *pSub;
  117926. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  117927. const char *zSavedAuthContext;
  117928. #endif
  117929. /* Issue SQLITE_READ authorizations with a fake column name for any
  117930. ** tables that are referenced but from which no values are extracted.
  117931. ** Examples of where these kinds of null SQLITE_READ authorizations
  117932. ** would occur:
  117933. **
  117934. ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
  117935. ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
  117936. **
  117937. ** The fake column name is an empty string. It is possible for a table to
  117938. ** have a column named by the empty string, in which case there is no way to
  117939. ** distinguish between an unreferenced table and an actual reference to the
  117940. ** "" column. The original design was for the fake column name to be a NULL,
  117941. ** which would be unambiguous. But legacy authorization callbacks might
  117942. ** assume the column name is non-NULL and segfault. The use of an empty
  117943. ** string for the fake column name seems safer.
  117944. */
  117945. if( pItem->colUsed==0 ){
  117946. sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
  117947. }
  117948. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  117949. /* Generate code for all sub-queries in the FROM clause
  117950. */
  117951. pSub = pItem->pSelect;
  117952. if( pSub==0 ) continue;
  117953. /* Sometimes the code for a subquery will be generated more than
  117954. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  117955. ** for example. In that case, do not regenerate the code to manifest
  117956. ** a view or the co-routine to implement a view. The first instance
  117957. ** is sufficient, though the subroutine to manifest the view does need
  117958. ** to be invoked again. */
  117959. if( pItem->addrFillSub ){
  117960. if( pItem->fg.viaCoroutine==0 ){
  117961. /* The subroutine that manifests the view might be a one-time routine,
  117962. ** or it might need to be rerun on each iteration because it
  117963. ** encodes a correlated subquery. */
  117964. testcase( sqlite3VdbeGetOp(v, pItem->addrFillSub)->opcode==OP_Once );
  117965. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  117966. }
  117967. continue;
  117968. }
  117969. /* Increment Parse.nHeight by the height of the largest expression
  117970. ** tree referred to by this, the parent select. The child select
  117971. ** may contain expression trees of at most
  117972. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  117973. ** more conservative than necessary, but much easier than enforcing
  117974. ** an exact limit.
  117975. */
  117976. pParse->nHeight += sqlite3SelectExprHeight(p);
  117977. /* Make copies of constant WHERE-clause terms in the outer query down
  117978. ** inside the subquery. This can help the subquery to run more efficiently.
  117979. */
  117980. if( OptimizationEnabled(db, SQLITE_PushDown)
  117981. && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
  117982. (pItem->fg.jointype & JT_OUTER)!=0)
  117983. ){
  117984. #if SELECTTRACE_ENABLED
  117985. if( sqlite3SelectTrace & 0x100 ){
  117986. SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
  117987. sqlite3TreeViewSelect(0, p, 0);
  117988. }
  117989. #endif
  117990. }else{
  117991. SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
  117992. }
  117993. zSavedAuthContext = pParse->zAuthContext;
  117994. pParse->zAuthContext = pItem->zName;
  117995. /* Generate code to implement the subquery
  117996. **
  117997. ** The subquery is implemented as a co-routine if the subquery is
  117998. ** guaranteed to be the outer loop (so that it does not need to be
  117999. ** computed more than once)
  118000. **
  118001. ** TODO: Are there other reasons beside (1) to use a co-routine
  118002. ** implementation?
  118003. */
  118004. if( i==0
  118005. && (pTabList->nSrc==1
  118006. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
  118007. ){
  118008. /* Implement a co-routine that will return a single row of the result
  118009. ** set on each invocation.
  118010. */
  118011. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  118012. pItem->regReturn = ++pParse->nMem;
  118013. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  118014. VdbeComment((v, "%s", pItem->pTab->zName));
  118015. pItem->addrFillSub = addrTop;
  118016. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  118017. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  118018. sqlite3Select(pParse, pSub, &dest);
  118019. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  118020. pItem->fg.viaCoroutine = 1;
  118021. pItem->regResult = dest.iSdst;
  118022. sqlite3VdbeEndCoroutine(v, pItem->regReturn);
  118023. sqlite3VdbeJumpHere(v, addrTop-1);
  118024. sqlite3ClearTempRegCache(pParse);
  118025. }else{
  118026. /* Generate a subroutine that will fill an ephemeral table with
  118027. ** the content of this subquery. pItem->addrFillSub will point
  118028. ** to the address of the generated subroutine. pItem->regReturn
  118029. ** is a register allocated to hold the subroutine return address
  118030. */
  118031. int topAddr;
  118032. int onceAddr = 0;
  118033. int retAddr;
  118034. struct SrcList_item *pPrior;
  118035. assert( pItem->addrFillSub==0 );
  118036. pItem->regReturn = ++pParse->nMem;
  118037. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  118038. pItem->addrFillSub = topAddr+1;
  118039. if( pItem->fg.isCorrelated==0 ){
  118040. /* If the subquery is not correlated and if we are not inside of
  118041. ** a trigger, then we only need to compute the value of the subquery
  118042. ** once. */
  118043. onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  118044. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  118045. }else{
  118046. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  118047. }
  118048. pPrior = isSelfJoinView(pTabList, pItem);
  118049. if( pPrior ){
  118050. sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
  118051. explainSetInteger(pItem->iSelectId, pPrior->iSelectId);
  118052. assert( pPrior->pSelect!=0 );
  118053. pSub->nSelectRow = pPrior->pSelect->nSelectRow;
  118054. }else{
  118055. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  118056. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  118057. sqlite3Select(pParse, pSub, &dest);
  118058. }
  118059. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  118060. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  118061. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  118062. VdbeComment((v, "end %s", pItem->pTab->zName));
  118063. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  118064. sqlite3ClearTempRegCache(pParse);
  118065. }
  118066. if( db->mallocFailed ) goto select_end;
  118067. pParse->nHeight -= sqlite3SelectExprHeight(p);
  118068. pParse->zAuthContext = zSavedAuthContext;
  118069. #endif
  118070. }
  118071. /* Various elements of the SELECT copied into local variables for
  118072. ** convenience */
  118073. pEList = p->pEList;
  118074. pWhere = p->pWhere;
  118075. pGroupBy = p->pGroupBy;
  118076. pHaving = p->pHaving;
  118077. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  118078. #if SELECTTRACE_ENABLED
  118079. if( sqlite3SelectTrace & 0x400 ){
  118080. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  118081. sqlite3TreeViewSelect(0, p, 0);
  118082. }
  118083. #endif
  118084. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  118085. if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
  118086. && countOfViewOptimization(pParse, p)
  118087. ){
  118088. if( db->mallocFailed ) goto select_end;
  118089. pEList = p->pEList;
  118090. pTabList = p->pSrc;
  118091. }
  118092. #endif
  118093. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  118094. ** if the select-list is the same as the ORDER BY list, then this query
  118095. ** can be rewritten as a GROUP BY. In other words, this:
  118096. **
  118097. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  118098. **
  118099. ** is transformed to:
  118100. **
  118101. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  118102. **
  118103. ** The second form is preferred as a single index (or temp-table) may be
  118104. ** used for both the ORDER BY and DISTINCT processing. As originally
  118105. ** written the query must use a temp-table for at least one of the ORDER
  118106. ** BY and DISTINCT, and an index or separate temp-table for the other.
  118107. */
  118108. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  118109. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  118110. ){
  118111. p->selFlags &= ~SF_Distinct;
  118112. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  118113. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  118114. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  118115. ** original setting of the SF_Distinct flag, not the current setting */
  118116. assert( sDistinct.isTnct );
  118117. #if SELECTTRACE_ENABLED
  118118. if( sqlite3SelectTrace & 0x400 ){
  118119. SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
  118120. sqlite3TreeViewSelect(0, p, 0);
  118121. }
  118122. #endif
  118123. }
  118124. /* If there is an ORDER BY clause, then create an ephemeral index to
  118125. ** do the sorting. But this sorting ephemeral index might end up
  118126. ** being unused if the data can be extracted in pre-sorted order.
  118127. ** If that is the case, then the OP_OpenEphemeral instruction will be
  118128. ** changed to an OP_Noop once we figure out that the sorting index is
  118129. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  118130. ** that change.
  118131. */
  118132. if( sSort.pOrderBy ){
  118133. KeyInfo *pKeyInfo;
  118134. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
  118135. sSort.iECursor = pParse->nTab++;
  118136. sSort.addrSortIndex =
  118137. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  118138. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  118139. (char*)pKeyInfo, P4_KEYINFO
  118140. );
  118141. }else{
  118142. sSort.addrSortIndex = -1;
  118143. }
  118144. /* If the output is destined for a temporary table, open that table.
  118145. */
  118146. if( pDest->eDest==SRT_EphemTab ){
  118147. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  118148. }
  118149. /* Set the limiter.
  118150. */
  118151. iEnd = sqlite3VdbeMakeLabel(v);
  118152. if( (p->selFlags & SF_FixedLimit)==0 ){
  118153. p->nSelectRow = 320; /* 4 billion rows */
  118154. }
  118155. computeLimitRegisters(pParse, p, iEnd);
  118156. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  118157. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  118158. sSort.sortFlags |= SORTFLAG_UseSorter;
  118159. }
  118160. /* Open an ephemeral index to use for the distinct set.
  118161. */
  118162. if( p->selFlags & SF_Distinct ){
  118163. sDistinct.tabTnct = pParse->nTab++;
  118164. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  118165. sDistinct.tabTnct, 0, 0,
  118166. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  118167. P4_KEYINFO);
  118168. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  118169. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  118170. }else{
  118171. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  118172. }
  118173. if( !isAgg && pGroupBy==0 ){
  118174. /* No aggregate functions and no GROUP BY clause */
  118175. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  118176. assert( WHERE_USE_LIMIT==SF_FixedLimit );
  118177. wctrlFlags |= p->selFlags & SF_FixedLimit;
  118178. /* Begin the database scan. */
  118179. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  118180. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  118181. p->pEList, wctrlFlags, p->nSelectRow);
  118182. if( pWInfo==0 ) goto select_end;
  118183. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  118184. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  118185. }
  118186. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  118187. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  118188. }
  118189. if( sSort.pOrderBy ){
  118190. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  118191. sSort.bOrderedInnerLoop = sqlite3WhereOrderedInnerLoop(pWInfo);
  118192. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  118193. sSort.pOrderBy = 0;
  118194. }
  118195. }
  118196. /* If sorting index that was created by a prior OP_OpenEphemeral
  118197. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  118198. ** into an OP_Noop.
  118199. */
  118200. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  118201. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  118202. }
  118203. /* Use the standard inner loop. */
  118204. assert( p->pEList==pEList );
  118205. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
  118206. sqlite3WhereContinueLabel(pWInfo),
  118207. sqlite3WhereBreakLabel(pWInfo));
  118208. /* End the database scan loop.
  118209. */
  118210. sqlite3WhereEnd(pWInfo);
  118211. }else{
  118212. /* This case when there exist aggregate functions or a GROUP BY clause
  118213. ** or both */
  118214. NameContext sNC; /* Name context for processing aggregate information */
  118215. int iAMem; /* First Mem address for storing current GROUP BY */
  118216. int iBMem; /* First Mem address for previous GROUP BY */
  118217. int iUseFlag; /* Mem address holding flag indicating that at least
  118218. ** one row of the input to the aggregator has been
  118219. ** processed */
  118220. int iAbortFlag; /* Mem address which causes query abort if positive */
  118221. int groupBySort; /* Rows come from source in GROUP BY order */
  118222. int addrEnd; /* End of processing for this SELECT */
  118223. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  118224. int sortOut = 0; /* Output register from the sorter */
  118225. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  118226. /* Remove any and all aliases between the result set and the
  118227. ** GROUP BY clause.
  118228. */
  118229. if( pGroupBy ){
  118230. int k; /* Loop counter */
  118231. struct ExprList_item *pItem; /* For looping over expression in a list */
  118232. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  118233. pItem->u.x.iAlias = 0;
  118234. }
  118235. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  118236. pItem->u.x.iAlias = 0;
  118237. }
  118238. assert( 66==sqlite3LogEst(100) );
  118239. if( p->nSelectRow>66 ) p->nSelectRow = 66;
  118240. }else{
  118241. assert( 0==sqlite3LogEst(1) );
  118242. p->nSelectRow = 0;
  118243. }
  118244. /* If there is both a GROUP BY and an ORDER BY clause and they are
  118245. ** identical, then it may be possible to disable the ORDER BY clause
  118246. ** on the grounds that the GROUP BY will cause elements to come out
  118247. ** in the correct order. It also may not - the GROUP BY might use a
  118248. ** database index that causes rows to be grouped together as required
  118249. ** but not actually sorted. Either way, record the fact that the
  118250. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  118251. ** variable. */
  118252. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  118253. orderByGrp = 1;
  118254. }
  118255. /* Create a label to jump to when we want to abort the query */
  118256. addrEnd = sqlite3VdbeMakeLabel(v);
  118257. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  118258. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  118259. ** SELECT statement.
  118260. */
  118261. memset(&sNC, 0, sizeof(sNC));
  118262. sNC.pParse = pParse;
  118263. sNC.pSrcList = pTabList;
  118264. sNC.pAggInfo = &sAggInfo;
  118265. sAggInfo.mnReg = pParse->nMem+1;
  118266. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  118267. sAggInfo.pGroupBy = pGroupBy;
  118268. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  118269. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  118270. if( pHaving ){
  118271. if( pGroupBy ){
  118272. assert( pWhere==p->pWhere );
  118273. assert( pHaving==p->pHaving );
  118274. assert( pGroupBy==p->pGroupBy );
  118275. havingToWhere(pParse, p);
  118276. pWhere = p->pWhere;
  118277. }
  118278. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  118279. }
  118280. sAggInfo.nAccumulator = sAggInfo.nColumn;
  118281. if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
  118282. minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
  118283. }else{
  118284. minMaxFlag = WHERE_ORDERBY_NORMAL;
  118285. }
  118286. for(i=0; i<sAggInfo.nFunc; i++){
  118287. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  118288. sNC.ncFlags |= NC_InAggFunc;
  118289. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  118290. sNC.ncFlags &= ~NC_InAggFunc;
  118291. }
  118292. sAggInfo.mxReg = pParse->nMem;
  118293. if( db->mallocFailed ) goto select_end;
  118294. #if SELECTTRACE_ENABLED
  118295. if( sqlite3SelectTrace & 0x400 ){
  118296. int ii;
  118297. SELECTTRACE(0x400,pParse,p,("After aggregate analysis:\n"));
  118298. sqlite3TreeViewSelect(0, p, 0);
  118299. for(ii=0; ii<sAggInfo.nColumn; ii++){
  118300. sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
  118301. ii, sAggInfo.aCol[ii].iMem);
  118302. sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
  118303. }
  118304. for(ii=0; ii<sAggInfo.nFunc; ii++){
  118305. sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
  118306. ii, sAggInfo.aFunc[ii].iMem);
  118307. sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
  118308. }
  118309. }
  118310. #endif
  118311. /* Processing for aggregates with GROUP BY is very different and
  118312. ** much more complex than aggregates without a GROUP BY.
  118313. */
  118314. if( pGroupBy ){
  118315. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  118316. int addr1; /* A-vs-B comparision jump */
  118317. int addrOutputRow; /* Start of subroutine that outputs a result row */
  118318. int regOutputRow; /* Return address register for output subroutine */
  118319. int addrSetAbort; /* Set the abort flag and return */
  118320. int addrTopOfLoop; /* Top of the input loop */
  118321. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  118322. int addrReset; /* Subroutine for resetting the accumulator */
  118323. int regReset; /* Return address register for reset subroutine */
  118324. /* If there is a GROUP BY clause we might need a sorting index to
  118325. ** implement it. Allocate that sorting index now. If it turns out
  118326. ** that we do not need it after all, the OP_SorterOpen instruction
  118327. ** will be converted into a Noop.
  118328. */
  118329. sAggInfo.sortingIdx = pParse->nTab++;
  118330. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
  118331. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  118332. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  118333. 0, (char*)pKeyInfo, P4_KEYINFO);
  118334. /* Initialize memory locations used by GROUP BY aggregate processing
  118335. */
  118336. iUseFlag = ++pParse->nMem;
  118337. iAbortFlag = ++pParse->nMem;
  118338. regOutputRow = ++pParse->nMem;
  118339. addrOutputRow = sqlite3VdbeMakeLabel(v);
  118340. regReset = ++pParse->nMem;
  118341. addrReset = sqlite3VdbeMakeLabel(v);
  118342. iAMem = pParse->nMem + 1;
  118343. pParse->nMem += pGroupBy->nExpr;
  118344. iBMem = pParse->nMem + 1;
  118345. pParse->nMem += pGroupBy->nExpr;
  118346. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  118347. VdbeComment((v, "clear abort flag"));
  118348. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  118349. VdbeComment((v, "indicate accumulator empty"));
  118350. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  118351. /* Begin a loop that will extract all source rows in GROUP BY order.
  118352. ** This might involve two separate loops with an OP_Sort in between, or
  118353. ** it might be a single loop that uses an index to extract information
  118354. ** in the right order to begin with.
  118355. */
  118356. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  118357. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  118358. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  118359. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  118360. );
  118361. if( pWInfo==0 ) goto select_end;
  118362. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  118363. /* The optimizer is able to deliver rows in group by order so
  118364. ** we do not have to sort. The OP_OpenEphemeral table will be
  118365. ** cancelled later because we still need to use the pKeyInfo
  118366. */
  118367. groupBySort = 0;
  118368. }else{
  118369. /* Rows are coming out in undetermined order. We have to push
  118370. ** each row into a sorting index, terminate the first loop,
  118371. ** then loop over the sorting index in order to get the output
  118372. ** in sorted order
  118373. */
  118374. int regBase;
  118375. int regRecord;
  118376. int nCol;
  118377. int nGroupBy;
  118378. explainTempTable(pParse,
  118379. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  118380. "DISTINCT" : "GROUP BY");
  118381. groupBySort = 1;
  118382. nGroupBy = pGroupBy->nExpr;
  118383. nCol = nGroupBy;
  118384. j = nGroupBy;
  118385. for(i=0; i<sAggInfo.nColumn; i++){
  118386. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  118387. nCol++;
  118388. j++;
  118389. }
  118390. }
  118391. regBase = sqlite3GetTempRange(pParse, nCol);
  118392. sqlite3ExprCacheClear(pParse);
  118393. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  118394. j = nGroupBy;
  118395. for(i=0; i<sAggInfo.nColumn; i++){
  118396. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  118397. if( pCol->iSorterColumn>=j ){
  118398. int r1 = j + regBase;
  118399. sqlite3ExprCodeGetColumnToReg(pParse,
  118400. pCol->pTab, pCol->iColumn, pCol->iTable, r1);
  118401. j++;
  118402. }
  118403. }
  118404. regRecord = sqlite3GetTempReg(pParse);
  118405. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  118406. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  118407. sqlite3ReleaseTempReg(pParse, regRecord);
  118408. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  118409. sqlite3WhereEnd(pWInfo);
  118410. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  118411. sortOut = sqlite3GetTempReg(pParse);
  118412. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  118413. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  118414. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  118415. sAggInfo.useSortingIdx = 1;
  118416. sqlite3ExprCacheClear(pParse);
  118417. }
  118418. /* If the index or temporary table used by the GROUP BY sort
  118419. ** will naturally deliver rows in the order required by the ORDER BY
  118420. ** clause, cancel the ephemeral table open coded earlier.
  118421. **
  118422. ** This is an optimization - the correct answer should result regardless.
  118423. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  118424. ** disable this optimization for testing purposes. */
  118425. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  118426. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  118427. ){
  118428. sSort.pOrderBy = 0;
  118429. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  118430. }
  118431. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  118432. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  118433. ** Then compare the current GROUP BY terms against the GROUP BY terms
  118434. ** from the previous row currently stored in a0, a1, a2...
  118435. */
  118436. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  118437. sqlite3ExprCacheClear(pParse);
  118438. if( groupBySort ){
  118439. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  118440. sortOut, sortPTab);
  118441. }
  118442. for(j=0; j<pGroupBy->nExpr; j++){
  118443. if( groupBySort ){
  118444. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  118445. }else{
  118446. sAggInfo.directMode = 1;
  118447. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  118448. }
  118449. }
  118450. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  118451. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  118452. addr1 = sqlite3VdbeCurrentAddr(v);
  118453. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  118454. /* Generate code that runs whenever the GROUP BY changes.
  118455. ** Changes in the GROUP BY are detected by the previous code
  118456. ** block. If there were no changes, this block is skipped.
  118457. **
  118458. ** This code copies current group by terms in b0,b1,b2,...
  118459. ** over to a0,a1,a2. It then calls the output subroutine
  118460. ** and resets the aggregate accumulator registers in preparation
  118461. ** for the next GROUP BY batch.
  118462. */
  118463. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  118464. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  118465. VdbeComment((v, "output one row"));
  118466. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  118467. VdbeComment((v, "check abort flag"));
  118468. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  118469. VdbeComment((v, "reset accumulator"));
  118470. /* Update the aggregate accumulators based on the content of
  118471. ** the current row
  118472. */
  118473. sqlite3VdbeJumpHere(v, addr1);
  118474. updateAccumulator(pParse, &sAggInfo);
  118475. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  118476. VdbeComment((v, "indicate data in accumulator"));
  118477. /* End of the loop
  118478. */
  118479. if( groupBySort ){
  118480. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  118481. VdbeCoverage(v);
  118482. }else{
  118483. sqlite3WhereEnd(pWInfo);
  118484. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  118485. }
  118486. /* Output the final row of result
  118487. */
  118488. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  118489. VdbeComment((v, "output final row"));
  118490. /* Jump over the subroutines
  118491. */
  118492. sqlite3VdbeGoto(v, addrEnd);
  118493. /* Generate a subroutine that outputs a single row of the result
  118494. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  118495. ** is less than or equal to zero, the subroutine is a no-op. If
  118496. ** the processing calls for the query to abort, this subroutine
  118497. ** increments the iAbortFlag memory location before returning in
  118498. ** order to signal the caller to abort.
  118499. */
  118500. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  118501. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  118502. VdbeComment((v, "set abort flag"));
  118503. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  118504. sqlite3VdbeResolveLabel(v, addrOutputRow);
  118505. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  118506. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  118507. VdbeCoverage(v);
  118508. VdbeComment((v, "Groupby result generator entry point"));
  118509. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  118510. finalizeAggFunctions(pParse, &sAggInfo);
  118511. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  118512. selectInnerLoop(pParse, p, -1, &sSort,
  118513. &sDistinct, pDest,
  118514. addrOutputRow+1, addrSetAbort);
  118515. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  118516. VdbeComment((v, "end groupby result generator"));
  118517. /* Generate a subroutine that will reset the group-by accumulator
  118518. */
  118519. sqlite3VdbeResolveLabel(v, addrReset);
  118520. resetAccumulator(pParse, &sAggInfo);
  118521. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  118522. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  118523. else {
  118524. #ifndef SQLITE_OMIT_BTREECOUNT
  118525. Table *pTab;
  118526. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  118527. /* If isSimpleCount() returns a pointer to a Table structure, then
  118528. ** the SQL statement is of the form:
  118529. **
  118530. ** SELECT count(*) FROM <tbl>
  118531. **
  118532. ** where the Table structure returned represents table <tbl>.
  118533. **
  118534. ** This statement is so common that it is optimized specially. The
  118535. ** OP_Count instruction is executed either on the intkey table that
  118536. ** contains the data for table <tbl> or on one of its indexes. It
  118537. ** is better to execute the op on an index, as indexes are almost
  118538. ** always spread across less pages than their corresponding tables.
  118539. */
  118540. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  118541. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  118542. Index *pIdx; /* Iterator variable */
  118543. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  118544. Index *pBest = 0; /* Best index found so far */
  118545. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  118546. sqlite3CodeVerifySchema(pParse, iDb);
  118547. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  118548. /* Search for the index that has the lowest scan cost.
  118549. **
  118550. ** (2011-04-15) Do not do a full scan of an unordered index.
  118551. **
  118552. ** (2013-10-03) Do not count the entries in a partial index.
  118553. **
  118554. ** In practice the KeyInfo structure will not be used. It is only
  118555. ** passed to keep OP_OpenRead happy.
  118556. */
  118557. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  118558. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  118559. if( pIdx->bUnordered==0
  118560. && pIdx->szIdxRow<pTab->szTabRow
  118561. && pIdx->pPartIdxWhere==0
  118562. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  118563. ){
  118564. pBest = pIdx;
  118565. }
  118566. }
  118567. if( pBest ){
  118568. iRoot = pBest->tnum;
  118569. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  118570. }
  118571. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  118572. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  118573. if( pKeyInfo ){
  118574. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  118575. }
  118576. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  118577. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  118578. explainSimpleCount(pParse, pTab, pBest);
  118579. }else
  118580. #endif /* SQLITE_OMIT_BTREECOUNT */
  118581. {
  118582. /* This case runs if the aggregate has no GROUP BY clause. The
  118583. ** processing is much simpler since there is only a single row
  118584. ** of output.
  118585. */
  118586. assert( p->pGroupBy==0 );
  118587. resetAccumulator(pParse, &sAggInfo);
  118588. /* If this query is a candidate for the min/max optimization, then
  118589. ** minMaxFlag will have been previously set to either
  118590. ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
  118591. ** be an appropriate ORDER BY expression for the optimization.
  118592. */
  118593. assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
  118594. assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
  118595. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  118596. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
  118597. 0, minMaxFlag, 0);
  118598. if( pWInfo==0 ){
  118599. goto select_end;
  118600. }
  118601. updateAccumulator(pParse, &sAggInfo);
  118602. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  118603. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  118604. VdbeComment((v, "%s() by index",
  118605. (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
  118606. }
  118607. sqlite3WhereEnd(pWInfo);
  118608. finalizeAggFunctions(pParse, &sAggInfo);
  118609. }
  118610. sSort.pOrderBy = 0;
  118611. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  118612. selectInnerLoop(pParse, p, -1, 0, 0,
  118613. pDest, addrEnd, addrEnd);
  118614. }
  118615. sqlite3VdbeResolveLabel(v, addrEnd);
  118616. } /* endif aggregate query */
  118617. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  118618. explainTempTable(pParse, "DISTINCT");
  118619. }
  118620. /* If there is an ORDER BY clause, then we need to sort the results
  118621. ** and send them to the callback one by one.
  118622. */
  118623. if( sSort.pOrderBy ){
  118624. explainTempTable(pParse,
  118625. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  118626. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  118627. }
  118628. /* Jump here to skip this query
  118629. */
  118630. sqlite3VdbeResolveLabel(v, iEnd);
  118631. /* The SELECT has been coded. If there is an error in the Parse structure,
  118632. ** set the return code to 1. Otherwise 0. */
  118633. rc = (pParse->nErr>0);
  118634. /* Control jumps to here if an error is encountered above, or upon
  118635. ** successful coding of the SELECT.
  118636. */
  118637. select_end:
  118638. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  118639. sqlite3ExprListDelete(db, pMinMaxOrderBy);
  118640. sqlite3DbFree(db, sAggInfo.aCol);
  118641. sqlite3DbFree(db, sAggInfo.aFunc);
  118642. #if SELECTTRACE_ENABLED
  118643. SELECTTRACE(1,pParse,p,("end processing\n"));
  118644. #endif
  118645. return rc;
  118646. }
  118647. /************** End of select.c **********************************************/
  118648. /************** Begin file table.c *******************************************/
  118649. /*
  118650. ** 2001 September 15
  118651. **
  118652. ** The author disclaims copyright to this source code. In place of
  118653. ** a legal notice, here is a blessing:
  118654. **
  118655. ** May you do good and not evil.
  118656. ** May you find forgiveness for yourself and forgive others.
  118657. ** May you share freely, never taking more than you give.
  118658. **
  118659. *************************************************************************
  118660. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  118661. ** interface routines. These are just wrappers around the main
  118662. ** interface routine of sqlite3_exec().
  118663. **
  118664. ** These routines are in a separate files so that they will not be linked
  118665. ** if they are not used.
  118666. */
  118667. /* #include "sqliteInt.h" */
  118668. #ifndef SQLITE_OMIT_GET_TABLE
  118669. /*
  118670. ** This structure is used to pass data from sqlite3_get_table() through
  118671. ** to the callback function is uses to build the result.
  118672. */
  118673. typedef struct TabResult {
  118674. char **azResult; /* Accumulated output */
  118675. char *zErrMsg; /* Error message text, if an error occurs */
  118676. u32 nAlloc; /* Slots allocated for azResult[] */
  118677. u32 nRow; /* Number of rows in the result */
  118678. u32 nColumn; /* Number of columns in the result */
  118679. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  118680. int rc; /* Return code from sqlite3_exec() */
  118681. } TabResult;
  118682. /*
  118683. ** This routine is called once for each row in the result table. Its job
  118684. ** is to fill in the TabResult structure appropriately, allocating new
  118685. ** memory as necessary.
  118686. */
  118687. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  118688. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  118689. int need; /* Slots needed in p->azResult[] */
  118690. int i; /* Loop counter */
  118691. char *z; /* A single column of result */
  118692. /* Make sure there is enough space in p->azResult to hold everything
  118693. ** we need to remember from this invocation of the callback.
  118694. */
  118695. if( p->nRow==0 && argv!=0 ){
  118696. need = nCol*2;
  118697. }else{
  118698. need = nCol;
  118699. }
  118700. if( p->nData + need > p->nAlloc ){
  118701. char **azNew;
  118702. p->nAlloc = p->nAlloc*2 + need;
  118703. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  118704. if( azNew==0 ) goto malloc_failed;
  118705. p->azResult = azNew;
  118706. }
  118707. /* If this is the first row, then generate an extra row containing
  118708. ** the names of all columns.
  118709. */
  118710. if( p->nRow==0 ){
  118711. p->nColumn = nCol;
  118712. for(i=0; i<nCol; i++){
  118713. z = sqlite3_mprintf("%s", colv[i]);
  118714. if( z==0 ) goto malloc_failed;
  118715. p->azResult[p->nData++] = z;
  118716. }
  118717. }else if( (int)p->nColumn!=nCol ){
  118718. sqlite3_free(p->zErrMsg);
  118719. p->zErrMsg = sqlite3_mprintf(
  118720. "sqlite3_get_table() called with two or more incompatible queries"
  118721. );
  118722. p->rc = SQLITE_ERROR;
  118723. return 1;
  118724. }
  118725. /* Copy over the row data
  118726. */
  118727. if( argv!=0 ){
  118728. for(i=0; i<nCol; i++){
  118729. if( argv[i]==0 ){
  118730. z = 0;
  118731. }else{
  118732. int n = sqlite3Strlen30(argv[i])+1;
  118733. z = sqlite3_malloc64( n );
  118734. if( z==0 ) goto malloc_failed;
  118735. memcpy(z, argv[i], n);
  118736. }
  118737. p->azResult[p->nData++] = z;
  118738. }
  118739. p->nRow++;
  118740. }
  118741. return 0;
  118742. malloc_failed:
  118743. p->rc = SQLITE_NOMEM_BKPT;
  118744. return 1;
  118745. }
  118746. /*
  118747. ** Query the database. But instead of invoking a callback for each row,
  118748. ** malloc() for space to hold the result and return the entire results
  118749. ** at the conclusion of the call.
  118750. **
  118751. ** The result that is written to ***pazResult is held in memory obtained
  118752. ** from malloc(). But the caller cannot free this memory directly.
  118753. ** Instead, the entire table should be passed to sqlite3_free_table() when
  118754. ** the calling procedure is finished using it.
  118755. */
  118756. SQLITE_API int sqlite3_get_table(
  118757. sqlite3 *db, /* The database on which the SQL executes */
  118758. const char *zSql, /* The SQL to be executed */
  118759. char ***pazResult, /* Write the result table here */
  118760. int *pnRow, /* Write the number of rows in the result here */
  118761. int *pnColumn, /* Write the number of columns of result here */
  118762. char **pzErrMsg /* Write error messages here */
  118763. ){
  118764. int rc;
  118765. TabResult res;
  118766. #ifdef SQLITE_ENABLE_API_ARMOR
  118767. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  118768. #endif
  118769. *pazResult = 0;
  118770. if( pnColumn ) *pnColumn = 0;
  118771. if( pnRow ) *pnRow = 0;
  118772. if( pzErrMsg ) *pzErrMsg = 0;
  118773. res.zErrMsg = 0;
  118774. res.nRow = 0;
  118775. res.nColumn = 0;
  118776. res.nData = 1;
  118777. res.nAlloc = 20;
  118778. res.rc = SQLITE_OK;
  118779. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  118780. if( res.azResult==0 ){
  118781. db->errCode = SQLITE_NOMEM;
  118782. return SQLITE_NOMEM_BKPT;
  118783. }
  118784. res.azResult[0] = 0;
  118785. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  118786. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  118787. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  118788. if( (rc&0xff)==SQLITE_ABORT ){
  118789. sqlite3_free_table(&res.azResult[1]);
  118790. if( res.zErrMsg ){
  118791. if( pzErrMsg ){
  118792. sqlite3_free(*pzErrMsg);
  118793. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  118794. }
  118795. sqlite3_free(res.zErrMsg);
  118796. }
  118797. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  118798. return res.rc;
  118799. }
  118800. sqlite3_free(res.zErrMsg);
  118801. if( rc!=SQLITE_OK ){
  118802. sqlite3_free_table(&res.azResult[1]);
  118803. return rc;
  118804. }
  118805. if( res.nAlloc>res.nData ){
  118806. char **azNew;
  118807. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  118808. if( azNew==0 ){
  118809. sqlite3_free_table(&res.azResult[1]);
  118810. db->errCode = SQLITE_NOMEM;
  118811. return SQLITE_NOMEM_BKPT;
  118812. }
  118813. res.azResult = azNew;
  118814. }
  118815. *pazResult = &res.azResult[1];
  118816. if( pnColumn ) *pnColumn = res.nColumn;
  118817. if( pnRow ) *pnRow = res.nRow;
  118818. return rc;
  118819. }
  118820. /*
  118821. ** This routine frees the space the sqlite3_get_table() malloced.
  118822. */
  118823. SQLITE_API void sqlite3_free_table(
  118824. char **azResult /* Result returned from sqlite3_get_table() */
  118825. ){
  118826. if( azResult ){
  118827. int i, n;
  118828. azResult--;
  118829. assert( azResult!=0 );
  118830. n = SQLITE_PTR_TO_INT(azResult[0]);
  118831. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  118832. sqlite3_free(azResult);
  118833. }
  118834. }
  118835. #endif /* SQLITE_OMIT_GET_TABLE */
  118836. /************** End of table.c ***********************************************/
  118837. /************** Begin file trigger.c *****************************************/
  118838. /*
  118839. **
  118840. ** The author disclaims copyright to this source code. In place of
  118841. ** a legal notice, here is a blessing:
  118842. **
  118843. ** May you do good and not evil.
  118844. ** May you find forgiveness for yourself and forgive others.
  118845. ** May you share freely, never taking more than you give.
  118846. **
  118847. *************************************************************************
  118848. ** This file contains the implementation for TRIGGERs
  118849. */
  118850. /* #include "sqliteInt.h" */
  118851. #ifndef SQLITE_OMIT_TRIGGER
  118852. /*
  118853. ** Delete a linked list of TriggerStep structures.
  118854. */
  118855. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  118856. while( pTriggerStep ){
  118857. TriggerStep * pTmp = pTriggerStep;
  118858. pTriggerStep = pTriggerStep->pNext;
  118859. sqlite3ExprDelete(db, pTmp->pWhere);
  118860. sqlite3ExprListDelete(db, pTmp->pExprList);
  118861. sqlite3SelectDelete(db, pTmp->pSelect);
  118862. sqlite3IdListDelete(db, pTmp->pIdList);
  118863. sqlite3DbFree(db, pTmp->zSpan);
  118864. sqlite3DbFree(db, pTmp);
  118865. }
  118866. }
  118867. /*
  118868. ** Given table pTab, return a list of all the triggers attached to
  118869. ** the table. The list is connected by Trigger.pNext pointers.
  118870. **
  118871. ** All of the triggers on pTab that are in the same database as pTab
  118872. ** are already attached to pTab->pTrigger. But there might be additional
  118873. ** triggers on pTab in the TEMP schema. This routine prepends all
  118874. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  118875. ** and returns the combined list.
  118876. **
  118877. ** To state it another way: This routine returns a list of all triggers
  118878. ** that fire off of pTab. The list will include any TEMP triggers on
  118879. ** pTab as well as the triggers lised in pTab->pTrigger.
  118880. */
  118881. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  118882. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  118883. Trigger *pList = 0; /* List of triggers to return */
  118884. if( pParse->disableTriggers ){
  118885. return 0;
  118886. }
  118887. if( pTmpSchema!=pTab->pSchema ){
  118888. HashElem *p;
  118889. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  118890. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  118891. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  118892. if( pTrig->pTabSchema==pTab->pSchema
  118893. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  118894. ){
  118895. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  118896. pList = pTrig;
  118897. }
  118898. }
  118899. }
  118900. return (pList ? pList : pTab->pTrigger);
  118901. }
  118902. /*
  118903. ** This is called by the parser when it sees a CREATE TRIGGER statement
  118904. ** up to the point of the BEGIN before the trigger actions. A Trigger
  118905. ** structure is generated based on the information available and stored
  118906. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  118907. ** sqlite3FinishTrigger() function is called to complete the trigger
  118908. ** construction process.
  118909. */
  118910. SQLITE_PRIVATE void sqlite3BeginTrigger(
  118911. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  118912. Token *pName1, /* The name of the trigger */
  118913. Token *pName2, /* The name of the trigger */
  118914. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  118915. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  118916. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  118917. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  118918. Expr *pWhen, /* WHEN clause */
  118919. int isTemp, /* True if the TEMPORARY keyword is present */
  118920. int noErr /* Suppress errors if the trigger already exists */
  118921. ){
  118922. Trigger *pTrigger = 0; /* The new trigger */
  118923. Table *pTab; /* Table that the trigger fires off of */
  118924. char *zName = 0; /* Name of the trigger */
  118925. sqlite3 *db = pParse->db; /* The database connection */
  118926. int iDb; /* The database to store the trigger in */
  118927. Token *pName; /* The unqualified db name */
  118928. DbFixer sFix; /* State vector for the DB fixer */
  118929. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  118930. assert( pName2!=0 );
  118931. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  118932. assert( op>0 && op<0xff );
  118933. if( isTemp ){
  118934. /* If TEMP was specified, then the trigger name may not be qualified. */
  118935. if( pName2->n>0 ){
  118936. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  118937. goto trigger_cleanup;
  118938. }
  118939. iDb = 1;
  118940. pName = pName1;
  118941. }else{
  118942. /* Figure out the db that the trigger will be created in */
  118943. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  118944. if( iDb<0 ){
  118945. goto trigger_cleanup;
  118946. }
  118947. }
  118948. if( !pTableName || db->mallocFailed ){
  118949. goto trigger_cleanup;
  118950. }
  118951. /* A long-standing parser bug is that this syntax was allowed:
  118952. **
  118953. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  118954. ** ^^^^^^^^
  118955. **
  118956. ** To maintain backwards compatibility, ignore the database
  118957. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  118958. */
  118959. if( db->init.busy && iDb!=1 ){
  118960. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  118961. pTableName->a[0].zDatabase = 0;
  118962. }
  118963. /* If the trigger name was unqualified, and the table is a temp table,
  118964. ** then set iDb to 1 to create the trigger in the temporary database.
  118965. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  118966. ** exist, the error is caught by the block below.
  118967. */
  118968. pTab = sqlite3SrcListLookup(pParse, pTableName);
  118969. if( db->init.busy==0 && pName2->n==0 && pTab
  118970. && pTab->pSchema==db->aDb[1].pSchema ){
  118971. iDb = 1;
  118972. }
  118973. /* Ensure the table name matches database name and that the table exists */
  118974. if( db->mallocFailed ) goto trigger_cleanup;
  118975. assert( pTableName->nSrc==1 );
  118976. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  118977. if( sqlite3FixSrcList(&sFix, pTableName) ){
  118978. goto trigger_cleanup;
  118979. }
  118980. pTab = sqlite3SrcListLookup(pParse, pTableName);
  118981. if( !pTab ){
  118982. /* The table does not exist. */
  118983. if( db->init.iDb==1 ){
  118984. /* Ticket #3810.
  118985. ** Normally, whenever a table is dropped, all associated triggers are
  118986. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  118987. ** and the table is dropped by a different database connection, the
  118988. ** trigger is not visible to the database connection that does the
  118989. ** drop so the trigger cannot be dropped. This results in an
  118990. ** "orphaned trigger" - a trigger whose associated table is missing.
  118991. */
  118992. db->init.orphanTrigger = 1;
  118993. }
  118994. goto trigger_cleanup;
  118995. }
  118996. if( IsVirtual(pTab) ){
  118997. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  118998. goto trigger_cleanup;
  118999. }
  119000. /* Check that the trigger name is not reserved and that no trigger of the
  119001. ** specified name exists */
  119002. zName = sqlite3NameFromToken(db, pName);
  119003. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  119004. goto trigger_cleanup;
  119005. }
  119006. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  119007. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  119008. if( !noErr ){
  119009. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  119010. }else{
  119011. assert( !db->init.busy );
  119012. sqlite3CodeVerifySchema(pParse, iDb);
  119013. }
  119014. goto trigger_cleanup;
  119015. }
  119016. /* Do not create a trigger on a system table */
  119017. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  119018. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  119019. goto trigger_cleanup;
  119020. }
  119021. /* INSTEAD of triggers are only for views and views only support INSTEAD
  119022. ** of triggers.
  119023. */
  119024. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  119025. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  119026. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  119027. goto trigger_cleanup;
  119028. }
  119029. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  119030. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  119031. " trigger on table: %S", pTableName, 0);
  119032. goto trigger_cleanup;
  119033. }
  119034. #ifndef SQLITE_OMIT_AUTHORIZATION
  119035. {
  119036. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  119037. int code = SQLITE_CREATE_TRIGGER;
  119038. const char *zDb = db->aDb[iTabDb].zDbSName;
  119039. const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
  119040. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  119041. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  119042. goto trigger_cleanup;
  119043. }
  119044. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  119045. goto trigger_cleanup;
  119046. }
  119047. }
  119048. #endif
  119049. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  119050. ** cannot appear on views. So we might as well translate every
  119051. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  119052. ** elsewhere.
  119053. */
  119054. if (tr_tm == TK_INSTEAD){
  119055. tr_tm = TK_BEFORE;
  119056. }
  119057. /* Build the Trigger object */
  119058. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  119059. if( pTrigger==0 ) goto trigger_cleanup;
  119060. pTrigger->zName = zName;
  119061. zName = 0;
  119062. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  119063. pTrigger->pSchema = db->aDb[iDb].pSchema;
  119064. pTrigger->pTabSchema = pTab->pSchema;
  119065. pTrigger->op = (u8)op;
  119066. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  119067. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  119068. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  119069. assert( pParse->pNewTrigger==0 );
  119070. pParse->pNewTrigger = pTrigger;
  119071. trigger_cleanup:
  119072. sqlite3DbFree(db, zName);
  119073. sqlite3SrcListDelete(db, pTableName);
  119074. sqlite3IdListDelete(db, pColumns);
  119075. sqlite3ExprDelete(db, pWhen);
  119076. if( !pParse->pNewTrigger ){
  119077. sqlite3DeleteTrigger(db, pTrigger);
  119078. }else{
  119079. assert( pParse->pNewTrigger==pTrigger );
  119080. }
  119081. }
  119082. /*
  119083. ** This routine is called after all of the trigger actions have been parsed
  119084. ** in order to complete the process of building the trigger.
  119085. */
  119086. SQLITE_PRIVATE void sqlite3FinishTrigger(
  119087. Parse *pParse, /* Parser context */
  119088. TriggerStep *pStepList, /* The triggered program */
  119089. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  119090. ){
  119091. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  119092. char *zName; /* Name of trigger */
  119093. sqlite3 *db = pParse->db; /* The database */
  119094. DbFixer sFix; /* Fixer object */
  119095. int iDb; /* Database containing the trigger */
  119096. Token nameToken; /* Trigger name for error reporting */
  119097. pParse->pNewTrigger = 0;
  119098. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  119099. zName = pTrig->zName;
  119100. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  119101. pTrig->step_list = pStepList;
  119102. while( pStepList ){
  119103. pStepList->pTrig = pTrig;
  119104. pStepList = pStepList->pNext;
  119105. }
  119106. sqlite3TokenInit(&nameToken, pTrig->zName);
  119107. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  119108. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  119109. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  119110. ){
  119111. goto triggerfinish_cleanup;
  119112. }
  119113. /* if we are not initializing,
  119114. ** build the sqlite_master entry
  119115. */
  119116. if( !db->init.busy ){
  119117. Vdbe *v;
  119118. char *z;
  119119. /* Make an entry in the sqlite_master table */
  119120. v = sqlite3GetVdbe(pParse);
  119121. if( v==0 ) goto triggerfinish_cleanup;
  119122. sqlite3BeginWriteOperation(pParse, 0, iDb);
  119123. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  119124. testcase( z==0 );
  119125. sqlite3NestedParse(pParse,
  119126. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  119127. db->aDb[iDb].zDbSName, MASTER_NAME, zName,
  119128. pTrig->table, z);
  119129. sqlite3DbFree(db, z);
  119130. sqlite3ChangeCookie(pParse, iDb);
  119131. sqlite3VdbeAddParseSchemaOp(v, iDb,
  119132. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  119133. }
  119134. if( db->init.busy ){
  119135. Trigger *pLink = pTrig;
  119136. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  119137. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  119138. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  119139. if( pTrig ){
  119140. sqlite3OomFault(db);
  119141. }else if( pLink->pSchema==pLink->pTabSchema ){
  119142. Table *pTab;
  119143. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  119144. assert( pTab!=0 );
  119145. pLink->pNext = pTab->pTrigger;
  119146. pTab->pTrigger = pLink;
  119147. }
  119148. }
  119149. triggerfinish_cleanup:
  119150. sqlite3DeleteTrigger(db, pTrig);
  119151. assert( !pParse->pNewTrigger );
  119152. sqlite3DeleteTriggerStep(db, pStepList);
  119153. }
  119154. /*
  119155. ** Duplicate a range of text from an SQL statement, then convert all
  119156. ** whitespace characters into ordinary space characters.
  119157. */
  119158. static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  119159. char *z = sqlite3DbSpanDup(db, zStart, zEnd);
  119160. int i;
  119161. if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
  119162. return z;
  119163. }
  119164. /*
  119165. ** Turn a SELECT statement (that the pSelect parameter points to) into
  119166. ** a trigger step. Return a pointer to a TriggerStep structure.
  119167. **
  119168. ** The parser calls this routine when it finds a SELECT statement in
  119169. ** body of a TRIGGER.
  119170. */
  119171. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
  119172. sqlite3 *db, /* Database connection */
  119173. Select *pSelect, /* The SELECT statement */
  119174. const char *zStart, /* Start of SQL text */
  119175. const char *zEnd /* End of SQL text */
  119176. ){
  119177. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  119178. if( pTriggerStep==0 ) {
  119179. sqlite3SelectDelete(db, pSelect);
  119180. return 0;
  119181. }
  119182. pTriggerStep->op = TK_SELECT;
  119183. pTriggerStep->pSelect = pSelect;
  119184. pTriggerStep->orconf = OE_Default;
  119185. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  119186. return pTriggerStep;
  119187. }
  119188. /*
  119189. ** Allocate space to hold a new trigger step. The allocated space
  119190. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  119191. **
  119192. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  119193. */
  119194. static TriggerStep *triggerStepAllocate(
  119195. sqlite3 *db, /* Database connection */
  119196. u8 op, /* Trigger opcode */
  119197. Token *pName, /* The target name */
  119198. const char *zStart, /* Start of SQL text */
  119199. const char *zEnd /* End of SQL text */
  119200. ){
  119201. TriggerStep *pTriggerStep;
  119202. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  119203. if( pTriggerStep ){
  119204. char *z = (char*)&pTriggerStep[1];
  119205. memcpy(z, pName->z, pName->n);
  119206. sqlite3Dequote(z);
  119207. pTriggerStep->zTarget = z;
  119208. pTriggerStep->op = op;
  119209. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  119210. }
  119211. return pTriggerStep;
  119212. }
  119213. /*
  119214. ** Build a trigger step out of an INSERT statement. Return a pointer
  119215. ** to the new trigger step.
  119216. **
  119217. ** The parser calls this routine when it sees an INSERT inside the
  119218. ** body of a trigger.
  119219. */
  119220. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  119221. sqlite3 *db, /* The database connection */
  119222. Token *pTableName, /* Name of the table into which we insert */
  119223. IdList *pColumn, /* List of columns in pTableName to insert into */
  119224. Select *pSelect, /* A SELECT statement that supplies values */
  119225. u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  119226. const char *zStart, /* Start of SQL text */
  119227. const char *zEnd /* End of SQL text */
  119228. ){
  119229. TriggerStep *pTriggerStep;
  119230. assert(pSelect != 0 || db->mallocFailed);
  119231. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName, zStart, zEnd);
  119232. if( pTriggerStep ){
  119233. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  119234. pTriggerStep->pIdList = pColumn;
  119235. pTriggerStep->orconf = orconf;
  119236. }else{
  119237. sqlite3IdListDelete(db, pColumn);
  119238. }
  119239. sqlite3SelectDelete(db, pSelect);
  119240. return pTriggerStep;
  119241. }
  119242. /*
  119243. ** Construct a trigger step that implements an UPDATE statement and return
  119244. ** a pointer to that trigger step. The parser calls this routine when it
  119245. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  119246. */
  119247. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  119248. sqlite3 *db, /* The database connection */
  119249. Token *pTableName, /* Name of the table to be updated */
  119250. ExprList *pEList, /* The SET clause: list of column and new values */
  119251. Expr *pWhere, /* The WHERE clause */
  119252. u8 orconf, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  119253. const char *zStart, /* Start of SQL text */
  119254. const char *zEnd /* End of SQL text */
  119255. ){
  119256. TriggerStep *pTriggerStep;
  119257. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName, zStart, zEnd);
  119258. if( pTriggerStep ){
  119259. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  119260. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  119261. pTriggerStep->orconf = orconf;
  119262. }
  119263. sqlite3ExprListDelete(db, pEList);
  119264. sqlite3ExprDelete(db, pWhere);
  119265. return pTriggerStep;
  119266. }
  119267. /*
  119268. ** Construct a trigger step that implements a DELETE statement and return
  119269. ** a pointer to that trigger step. The parser calls this routine when it
  119270. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  119271. */
  119272. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  119273. sqlite3 *db, /* Database connection */
  119274. Token *pTableName, /* The table from which rows are deleted */
  119275. Expr *pWhere, /* The WHERE clause */
  119276. const char *zStart, /* Start of SQL text */
  119277. const char *zEnd /* End of SQL text */
  119278. ){
  119279. TriggerStep *pTriggerStep;
  119280. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName, zStart, zEnd);
  119281. if( pTriggerStep ){
  119282. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  119283. pTriggerStep->orconf = OE_Default;
  119284. }
  119285. sqlite3ExprDelete(db, pWhere);
  119286. return pTriggerStep;
  119287. }
  119288. /*
  119289. ** Recursively delete a Trigger structure
  119290. */
  119291. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  119292. if( pTrigger==0 ) return;
  119293. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  119294. sqlite3DbFree(db, pTrigger->zName);
  119295. sqlite3DbFree(db, pTrigger->table);
  119296. sqlite3ExprDelete(db, pTrigger->pWhen);
  119297. sqlite3IdListDelete(db, pTrigger->pColumns);
  119298. sqlite3DbFree(db, pTrigger);
  119299. }
  119300. /*
  119301. ** This function is called to drop a trigger from the database schema.
  119302. **
  119303. ** This may be called directly from the parser and therefore identifies
  119304. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  119305. ** same job as this routine except it takes a pointer to the trigger
  119306. ** instead of the trigger name.
  119307. **/
  119308. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  119309. Trigger *pTrigger = 0;
  119310. int i;
  119311. const char *zDb;
  119312. const char *zName;
  119313. sqlite3 *db = pParse->db;
  119314. if( db->mallocFailed ) goto drop_trigger_cleanup;
  119315. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  119316. goto drop_trigger_cleanup;
  119317. }
  119318. assert( pName->nSrc==1 );
  119319. zDb = pName->a[0].zDatabase;
  119320. zName = pName->a[0].zName;
  119321. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  119322. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  119323. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  119324. if( zDb && sqlite3StrICmp(db->aDb[j].zDbSName, zDb) ) continue;
  119325. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  119326. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  119327. if( pTrigger ) break;
  119328. }
  119329. if( !pTrigger ){
  119330. if( !noErr ){
  119331. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  119332. }else{
  119333. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  119334. }
  119335. pParse->checkSchema = 1;
  119336. goto drop_trigger_cleanup;
  119337. }
  119338. sqlite3DropTriggerPtr(pParse, pTrigger);
  119339. drop_trigger_cleanup:
  119340. sqlite3SrcListDelete(db, pName);
  119341. }
  119342. /*
  119343. ** Return a pointer to the Table structure for the table that a trigger
  119344. ** is set on.
  119345. */
  119346. static Table *tableOfTrigger(Trigger *pTrigger){
  119347. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  119348. }
  119349. /*
  119350. ** Drop a trigger given a pointer to that trigger.
  119351. */
  119352. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  119353. Table *pTable;
  119354. Vdbe *v;
  119355. sqlite3 *db = pParse->db;
  119356. int iDb;
  119357. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  119358. assert( iDb>=0 && iDb<db->nDb );
  119359. pTable = tableOfTrigger(pTrigger);
  119360. assert( pTable );
  119361. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  119362. #ifndef SQLITE_OMIT_AUTHORIZATION
  119363. {
  119364. int code = SQLITE_DROP_TRIGGER;
  119365. const char *zDb = db->aDb[iDb].zDbSName;
  119366. const char *zTab = SCHEMA_TABLE(iDb);
  119367. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  119368. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  119369. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  119370. return;
  119371. }
  119372. }
  119373. #endif
  119374. /* Generate code to destroy the database record of the trigger.
  119375. */
  119376. assert( pTable!=0 );
  119377. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  119378. sqlite3NestedParse(pParse,
  119379. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  119380. db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
  119381. );
  119382. sqlite3ChangeCookie(pParse, iDb);
  119383. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  119384. }
  119385. }
  119386. /*
  119387. ** Remove a trigger from the hash tables of the sqlite* pointer.
  119388. */
  119389. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  119390. Trigger *pTrigger;
  119391. Hash *pHash;
  119392. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  119393. pHash = &(db->aDb[iDb].pSchema->trigHash);
  119394. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  119395. if( ALWAYS(pTrigger) ){
  119396. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  119397. Table *pTab = tableOfTrigger(pTrigger);
  119398. Trigger **pp;
  119399. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  119400. *pp = (*pp)->pNext;
  119401. }
  119402. sqlite3DeleteTrigger(db, pTrigger);
  119403. db->mDbFlags |= DBFLAG_SchemaChange;
  119404. }
  119405. }
  119406. /*
  119407. ** pEList is the SET clause of an UPDATE statement. Each entry
  119408. ** in pEList is of the format <id>=<expr>. If any of the entries
  119409. ** in pEList have an <id> which matches an identifier in pIdList,
  119410. ** then return TRUE. If pIdList==NULL, then it is considered a
  119411. ** wildcard that matches anything. Likewise if pEList==NULL then
  119412. ** it matches anything so always return true. Return false only
  119413. ** if there is no match.
  119414. */
  119415. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  119416. int e;
  119417. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  119418. for(e=0; e<pEList->nExpr; e++){
  119419. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  119420. }
  119421. return 0;
  119422. }
  119423. /*
  119424. ** Return a list of all triggers on table pTab if there exists at least
  119425. ** one trigger that must be fired when an operation of type 'op' is
  119426. ** performed on the table, and, if that operation is an UPDATE, if at
  119427. ** least one of the columns in pChanges is being modified.
  119428. */
  119429. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  119430. Parse *pParse, /* Parse context */
  119431. Table *pTab, /* The table the contains the triggers */
  119432. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  119433. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  119434. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  119435. ){
  119436. int mask = 0;
  119437. Trigger *pList = 0;
  119438. Trigger *p;
  119439. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  119440. pList = sqlite3TriggerList(pParse, pTab);
  119441. }
  119442. assert( pList==0 || IsVirtual(pTab)==0 );
  119443. for(p=pList; p; p=p->pNext){
  119444. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  119445. mask |= p->tr_tm;
  119446. }
  119447. }
  119448. if( pMask ){
  119449. *pMask = mask;
  119450. }
  119451. return (mask ? pList : 0);
  119452. }
  119453. /*
  119454. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  119455. ** to that SrcList.
  119456. **
  119457. ** This routine adds a specific database name, if needed, to the target when
  119458. ** forming the SrcList. This prevents a trigger in one database from
  119459. ** referring to a target in another database. An exception is when the
  119460. ** trigger is in TEMP in which case it can refer to any other database it
  119461. ** wants.
  119462. */
  119463. static SrcList *targetSrcList(
  119464. Parse *pParse, /* The parsing context */
  119465. TriggerStep *pStep /* The trigger containing the target token */
  119466. ){
  119467. sqlite3 *db = pParse->db;
  119468. int iDb; /* Index of the database to use */
  119469. SrcList *pSrc; /* SrcList to be returned */
  119470. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  119471. if( pSrc ){
  119472. assert( pSrc->nSrc>0 );
  119473. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  119474. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  119475. if( iDb==0 || iDb>=2 ){
  119476. const char *zDb;
  119477. assert( iDb<db->nDb );
  119478. zDb = db->aDb[iDb].zDbSName;
  119479. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
  119480. }
  119481. }
  119482. return pSrc;
  119483. }
  119484. /*
  119485. ** Generate VDBE code for the statements inside the body of a single
  119486. ** trigger.
  119487. */
  119488. static int codeTriggerProgram(
  119489. Parse *pParse, /* The parser context */
  119490. TriggerStep *pStepList, /* List of statements inside the trigger body */
  119491. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  119492. ){
  119493. TriggerStep *pStep;
  119494. Vdbe *v = pParse->pVdbe;
  119495. sqlite3 *db = pParse->db;
  119496. assert( pParse->pTriggerTab && pParse->pToplevel );
  119497. assert( pStepList );
  119498. assert( v!=0 );
  119499. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  119500. /* Figure out the ON CONFLICT policy that will be used for this step
  119501. ** of the trigger program. If the statement that caused this trigger
  119502. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  119503. ** the ON CONFLICT policy that was specified as part of the trigger
  119504. ** step statement. Example:
  119505. **
  119506. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  119507. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  119508. ** END;
  119509. **
  119510. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  119511. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  119512. */
  119513. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  119514. assert( pParse->okConstFactor==0 );
  119515. #ifndef SQLITE_OMIT_TRACE
  119516. if( pStep->zSpan ){
  119517. sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
  119518. sqlite3MPrintf(db, "-- %s", pStep->zSpan),
  119519. P4_DYNAMIC);
  119520. }
  119521. #endif
  119522. switch( pStep->op ){
  119523. case TK_UPDATE: {
  119524. sqlite3Update(pParse,
  119525. targetSrcList(pParse, pStep),
  119526. sqlite3ExprListDup(db, pStep->pExprList, 0),
  119527. sqlite3ExprDup(db, pStep->pWhere, 0),
  119528. pParse->eOrconf, 0, 0
  119529. );
  119530. break;
  119531. }
  119532. case TK_INSERT: {
  119533. sqlite3Insert(pParse,
  119534. targetSrcList(pParse, pStep),
  119535. sqlite3SelectDup(db, pStep->pSelect, 0),
  119536. sqlite3IdListDup(db, pStep->pIdList),
  119537. pParse->eOrconf
  119538. );
  119539. break;
  119540. }
  119541. case TK_DELETE: {
  119542. sqlite3DeleteFrom(pParse,
  119543. targetSrcList(pParse, pStep),
  119544. sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
  119545. );
  119546. break;
  119547. }
  119548. default: assert( pStep->op==TK_SELECT ); {
  119549. SelectDest sDest;
  119550. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  119551. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  119552. sqlite3Select(pParse, pSelect, &sDest);
  119553. sqlite3SelectDelete(db, pSelect);
  119554. break;
  119555. }
  119556. }
  119557. if( pStep->op!=TK_SELECT ){
  119558. sqlite3VdbeAddOp0(v, OP_ResetCount);
  119559. }
  119560. }
  119561. return 0;
  119562. }
  119563. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  119564. /*
  119565. ** This function is used to add VdbeComment() annotations to a VDBE
  119566. ** program. It is not used in production code, only for debugging.
  119567. */
  119568. static const char *onErrorText(int onError){
  119569. switch( onError ){
  119570. case OE_Abort: return "abort";
  119571. case OE_Rollback: return "rollback";
  119572. case OE_Fail: return "fail";
  119573. case OE_Replace: return "replace";
  119574. case OE_Ignore: return "ignore";
  119575. case OE_Default: return "default";
  119576. }
  119577. return "n/a";
  119578. }
  119579. #endif
  119580. /*
  119581. ** Parse context structure pFrom has just been used to create a sub-vdbe
  119582. ** (trigger program). If an error has occurred, transfer error information
  119583. ** from pFrom to pTo.
  119584. */
  119585. static void transferParseError(Parse *pTo, Parse *pFrom){
  119586. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  119587. assert( pTo->zErrMsg==0 || pTo->nErr );
  119588. if( pTo->nErr==0 ){
  119589. pTo->zErrMsg = pFrom->zErrMsg;
  119590. pTo->nErr = pFrom->nErr;
  119591. pTo->rc = pFrom->rc;
  119592. }else{
  119593. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  119594. }
  119595. }
  119596. /*
  119597. ** Create and populate a new TriggerPrg object with a sub-program
  119598. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  119599. */
  119600. static TriggerPrg *codeRowTrigger(
  119601. Parse *pParse, /* Current parse context */
  119602. Trigger *pTrigger, /* Trigger to code */
  119603. Table *pTab, /* The table pTrigger is attached to */
  119604. int orconf /* ON CONFLICT policy to code trigger program with */
  119605. ){
  119606. Parse *pTop = sqlite3ParseToplevel(pParse);
  119607. sqlite3 *db = pParse->db; /* Database handle */
  119608. TriggerPrg *pPrg; /* Value to return */
  119609. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  119610. Vdbe *v; /* Temporary VM */
  119611. NameContext sNC; /* Name context for sub-vdbe */
  119612. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  119613. Parse *pSubParse; /* Parse context for sub-vdbe */
  119614. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  119615. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  119616. assert( pTop->pVdbe );
  119617. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  119618. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  119619. ** list of the top-level Parse object sooner rather than later. */
  119620. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  119621. if( !pPrg ) return 0;
  119622. pPrg->pNext = pTop->pTriggerPrg;
  119623. pTop->pTriggerPrg = pPrg;
  119624. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  119625. if( !pProgram ) return 0;
  119626. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  119627. pPrg->pTrigger = pTrigger;
  119628. pPrg->orconf = orconf;
  119629. pPrg->aColmask[0] = 0xffffffff;
  119630. pPrg->aColmask[1] = 0xffffffff;
  119631. /* Allocate and populate a new Parse context to use for coding the
  119632. ** trigger sub-program. */
  119633. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  119634. if( !pSubParse ) return 0;
  119635. memset(&sNC, 0, sizeof(sNC));
  119636. sNC.pParse = pSubParse;
  119637. pSubParse->db = db;
  119638. pSubParse->pTriggerTab = pTab;
  119639. pSubParse->pToplevel = pTop;
  119640. pSubParse->zAuthContext = pTrigger->zName;
  119641. pSubParse->eTriggerOp = pTrigger->op;
  119642. pSubParse->nQueryLoop = pParse->nQueryLoop;
  119643. v = sqlite3GetVdbe(pSubParse);
  119644. if( v ){
  119645. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  119646. pTrigger->zName, onErrorText(orconf),
  119647. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  119648. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  119649. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  119650. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  119651. pTab->zName
  119652. ));
  119653. #ifndef SQLITE_OMIT_TRACE
  119654. if( pTrigger->zName ){
  119655. sqlite3VdbeChangeP4(v, -1,
  119656. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  119657. );
  119658. }
  119659. #endif
  119660. /* If one was specified, code the WHEN clause. If it evaluates to false
  119661. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  119662. ** OP_Halt inserted at the end of the program. */
  119663. if( pTrigger->pWhen ){
  119664. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  119665. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  119666. && db->mallocFailed==0
  119667. ){
  119668. iEndTrigger = sqlite3VdbeMakeLabel(v);
  119669. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  119670. }
  119671. sqlite3ExprDelete(db, pWhen);
  119672. }
  119673. /* Code the trigger program into the sub-vdbe. */
  119674. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  119675. /* Insert an OP_Halt at the end of the sub-program. */
  119676. if( iEndTrigger ){
  119677. sqlite3VdbeResolveLabel(v, iEndTrigger);
  119678. }
  119679. sqlite3VdbeAddOp0(v, OP_Halt);
  119680. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  119681. transferParseError(pParse, pSubParse);
  119682. if( db->mallocFailed==0 && pParse->nErr==0 ){
  119683. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  119684. }
  119685. pProgram->nMem = pSubParse->nMem;
  119686. pProgram->nCsr = pSubParse->nTab;
  119687. pProgram->token = (void *)pTrigger;
  119688. pPrg->aColmask[0] = pSubParse->oldmask;
  119689. pPrg->aColmask[1] = pSubParse->newmask;
  119690. sqlite3VdbeDelete(v);
  119691. }
  119692. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  119693. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  119694. sqlite3ParserReset(pSubParse);
  119695. sqlite3StackFree(db, pSubParse);
  119696. return pPrg;
  119697. }
  119698. /*
  119699. ** Return a pointer to a TriggerPrg object containing the sub-program for
  119700. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  119701. ** TriggerPrg object exists, a new object is allocated and populated before
  119702. ** being returned.
  119703. */
  119704. static TriggerPrg *getRowTrigger(
  119705. Parse *pParse, /* Current parse context */
  119706. Trigger *pTrigger, /* Trigger to code */
  119707. Table *pTab, /* The table trigger pTrigger is attached to */
  119708. int orconf /* ON CONFLICT algorithm. */
  119709. ){
  119710. Parse *pRoot = sqlite3ParseToplevel(pParse);
  119711. TriggerPrg *pPrg;
  119712. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  119713. /* It may be that this trigger has already been coded (or is in the
  119714. ** process of being coded). If this is the case, then an entry with
  119715. ** a matching TriggerPrg.pTrigger field will be present somewhere
  119716. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  119717. for(pPrg=pRoot->pTriggerPrg;
  119718. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  119719. pPrg=pPrg->pNext
  119720. );
  119721. /* If an existing TriggerPrg could not be located, create a new one. */
  119722. if( !pPrg ){
  119723. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  119724. }
  119725. return pPrg;
  119726. }
  119727. /*
  119728. ** Generate code for the trigger program associated with trigger p on
  119729. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  119730. ** function are the same as those described in the header function for
  119731. ** sqlite3CodeRowTrigger()
  119732. */
  119733. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  119734. Parse *pParse, /* Parse context */
  119735. Trigger *p, /* Trigger to code */
  119736. Table *pTab, /* The table to code triggers from */
  119737. int reg, /* Reg array containing OLD.* and NEW.* values */
  119738. int orconf, /* ON CONFLICT policy */
  119739. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  119740. ){
  119741. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  119742. TriggerPrg *pPrg;
  119743. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  119744. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  119745. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  119746. ** is a pointer to the sub-vdbe containing the trigger program. */
  119747. if( pPrg ){
  119748. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  119749. sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
  119750. (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  119751. VdbeComment(
  119752. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  119753. /* Set the P5 operand of the OP_Program instruction to non-zero if
  119754. ** recursive invocation of this trigger program is disallowed. Recursive
  119755. ** invocation is disallowed if (a) the sub-program is really a trigger,
  119756. ** not a foreign key action, and (b) the flag to enable recursive triggers
  119757. ** is clear. */
  119758. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  119759. }
  119760. }
  119761. /*
  119762. ** This is called to code the required FOR EACH ROW triggers for an operation
  119763. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  119764. ** is given by the op parameter. The tr_tm parameter determines whether the
  119765. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  119766. ** parameter pChanges is passed the list of columns being modified.
  119767. **
  119768. ** If there are no triggers that fire at the specified time for the specified
  119769. ** operation on pTab, this function is a no-op.
  119770. **
  119771. ** The reg argument is the address of the first in an array of registers
  119772. ** that contain the values substituted for the new.* and old.* references
  119773. ** in the trigger program. If N is the number of columns in table pTab
  119774. ** (a copy of pTab->nCol), then registers are populated as follows:
  119775. **
  119776. ** Register Contains
  119777. ** ------------------------------------------------------
  119778. ** reg+0 OLD.rowid
  119779. ** reg+1 OLD.* value of left-most column of pTab
  119780. ** ... ...
  119781. ** reg+N OLD.* value of right-most column of pTab
  119782. ** reg+N+1 NEW.rowid
  119783. ** reg+N+2 OLD.* value of left-most column of pTab
  119784. ** ... ...
  119785. ** reg+N+N+1 NEW.* value of right-most column of pTab
  119786. **
  119787. ** For ON DELETE triggers, the registers containing the NEW.* values will
  119788. ** never be accessed by the trigger program, so they are not allocated or
  119789. ** populated by the caller (there is no data to populate them with anyway).
  119790. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  119791. ** are never accessed, and so are not allocated by the caller. So, for an
  119792. ** ON INSERT trigger, the value passed to this function as parameter reg
  119793. ** is not a readable register, although registers (reg+N) through
  119794. ** (reg+N+N+1) are.
  119795. **
  119796. ** Parameter orconf is the default conflict resolution algorithm for the
  119797. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  119798. ** is the instruction that control should jump to if a trigger program
  119799. ** raises an IGNORE exception.
  119800. */
  119801. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  119802. Parse *pParse, /* Parse context */
  119803. Trigger *pTrigger, /* List of triggers on table pTab */
  119804. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  119805. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  119806. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  119807. Table *pTab, /* The table to code triggers from */
  119808. int reg, /* The first in an array of registers (see above) */
  119809. int orconf, /* ON CONFLICT policy */
  119810. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  119811. ){
  119812. Trigger *p; /* Used to iterate through pTrigger list */
  119813. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  119814. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  119815. assert( (op==TK_UPDATE)==(pChanges!=0) );
  119816. for(p=pTrigger; p; p=p->pNext){
  119817. /* Sanity checking: The schema for the trigger and for the table are
  119818. ** always defined. The trigger must be in the same schema as the table
  119819. ** or else it must be a TEMP trigger. */
  119820. assert( p->pSchema!=0 );
  119821. assert( p->pTabSchema!=0 );
  119822. assert( p->pSchema==p->pTabSchema
  119823. || p->pSchema==pParse->db->aDb[1].pSchema );
  119824. /* Determine whether we should code this trigger */
  119825. if( p->op==op
  119826. && p->tr_tm==tr_tm
  119827. && checkColumnOverlap(p->pColumns, pChanges)
  119828. ){
  119829. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  119830. }
  119831. }
  119832. }
  119833. /*
  119834. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  119835. ** This function returns a 32-bit bitmask indicating which columns of the
  119836. ** old.* or new.* tables actually are used by triggers. This information
  119837. ** may be used by the caller, for example, to avoid having to load the entire
  119838. ** old.* record into memory when executing an UPDATE or DELETE command.
  119839. **
  119840. ** Bit 0 of the returned mask is set if the left-most column of the
  119841. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  119842. ** the second leftmost column value is required, and so on. If there
  119843. ** are more than 32 columns in the table, and at least one of the columns
  119844. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  119845. **
  119846. ** It is not possible to determine if the old.rowid or new.rowid column is
  119847. ** accessed by triggers. The caller must always assume that it is.
  119848. **
  119849. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  119850. ** applies to the old.* table. If 1, the new.* table.
  119851. **
  119852. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  119853. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  119854. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  119855. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  119856. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  119857. */
  119858. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  119859. Parse *pParse, /* Parse context */
  119860. Trigger *pTrigger, /* List of triggers on table pTab */
  119861. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  119862. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  119863. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  119864. Table *pTab, /* The table to code triggers from */
  119865. int orconf /* Default ON CONFLICT policy for trigger steps */
  119866. ){
  119867. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  119868. u32 mask = 0;
  119869. Trigger *p;
  119870. assert( isNew==1 || isNew==0 );
  119871. for(p=pTrigger; p; p=p->pNext){
  119872. if( p->op==op && (tr_tm&p->tr_tm)
  119873. && checkColumnOverlap(p->pColumns,pChanges)
  119874. ){
  119875. TriggerPrg *pPrg;
  119876. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  119877. if( pPrg ){
  119878. mask |= pPrg->aColmask[isNew];
  119879. }
  119880. }
  119881. }
  119882. return mask;
  119883. }
  119884. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  119885. /************** End of trigger.c *********************************************/
  119886. /************** Begin file update.c ******************************************/
  119887. /*
  119888. ** 2001 September 15
  119889. **
  119890. ** The author disclaims copyright to this source code. In place of
  119891. ** a legal notice, here is a blessing:
  119892. **
  119893. ** May you do good and not evil.
  119894. ** May you find forgiveness for yourself and forgive others.
  119895. ** May you share freely, never taking more than you give.
  119896. **
  119897. *************************************************************************
  119898. ** This file contains C code routines that are called by the parser
  119899. ** to handle UPDATE statements.
  119900. */
  119901. /* #include "sqliteInt.h" */
  119902. #ifndef SQLITE_OMIT_VIRTUALTABLE
  119903. /* Forward declaration */
  119904. static void updateVirtualTable(
  119905. Parse *pParse, /* The parsing context */
  119906. SrcList *pSrc, /* The virtual table to be modified */
  119907. Table *pTab, /* The virtual table */
  119908. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  119909. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  119910. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  119911. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  119912. int onError /* ON CONFLICT strategy */
  119913. );
  119914. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  119915. /*
  119916. ** The most recently coded instruction was an OP_Column to retrieve the
  119917. ** i-th column of table pTab. This routine sets the P4 parameter of the
  119918. ** OP_Column to the default value, if any.
  119919. **
  119920. ** The default value of a column is specified by a DEFAULT clause in the
  119921. ** column definition. This was either supplied by the user when the table
  119922. ** was created, or added later to the table definition by an ALTER TABLE
  119923. ** command. If the latter, then the row-records in the table btree on disk
  119924. ** may not contain a value for the column and the default value, taken
  119925. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  119926. ** If the former, then all row-records are guaranteed to include a value
  119927. ** for the column and the P4 value is not required.
  119928. **
  119929. ** Column definitions created by an ALTER TABLE command may only have
  119930. ** literal default values specified: a number, null or a string. (If a more
  119931. ** complicated default expression value was provided, it is evaluated
  119932. ** when the ALTER TABLE is executed and one of the literal values written
  119933. ** into the sqlite_master table.)
  119934. **
  119935. ** Therefore, the P4 parameter is only required if the default value for
  119936. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  119937. ** function is capable of transforming these types of expressions into
  119938. ** sqlite3_value objects.
  119939. **
  119940. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  119941. ** on register iReg. This is used when an equivalent integer value is
  119942. ** stored in place of an 8-byte floating point value in order to save
  119943. ** space.
  119944. */
  119945. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  119946. assert( pTab!=0 );
  119947. if( !pTab->pSelect ){
  119948. sqlite3_value *pValue = 0;
  119949. u8 enc = ENC(sqlite3VdbeDb(v));
  119950. Column *pCol = &pTab->aCol[i];
  119951. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  119952. assert( i<pTab->nCol );
  119953. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  119954. pCol->affinity, &pValue);
  119955. if( pValue ){
  119956. sqlite3VdbeAppendP4(v, pValue, P4_MEM);
  119957. }
  119958. }
  119959. #ifndef SQLITE_OMIT_FLOATING_POINT
  119960. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  119961. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  119962. }
  119963. #endif
  119964. }
  119965. /*
  119966. ** Process an UPDATE statement.
  119967. **
  119968. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  119969. ** \_______/ \________/ \______/ \________________/
  119970. * onError pTabList pChanges pWhere
  119971. */
  119972. SQLITE_PRIVATE void sqlite3Update(
  119973. Parse *pParse, /* The parser context */
  119974. SrcList *pTabList, /* The table in which we should change things */
  119975. ExprList *pChanges, /* Things to be changed */
  119976. Expr *pWhere, /* The WHERE clause. May be null */
  119977. int onError, /* How to handle constraint errors */
  119978. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  119979. Expr *pLimit /* LIMIT clause. May be null */
  119980. ){
  119981. int i, j; /* Loop counters */
  119982. Table *pTab; /* The table to be updated */
  119983. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  119984. WhereInfo *pWInfo; /* Information about the WHERE clause */
  119985. Vdbe *v; /* The virtual database engine */
  119986. Index *pIdx; /* For looping over indices */
  119987. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  119988. int nIdx; /* Number of indices that need updating */
  119989. int iBaseCur; /* Base cursor number */
  119990. int iDataCur; /* Cursor for the canonical data btree */
  119991. int iIdxCur; /* Cursor for the first index */
  119992. sqlite3 *db; /* The database structure */
  119993. int *aRegIdx = 0; /* First register in array assigned to each index */
  119994. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  119995. ** an expression for the i-th column of the table.
  119996. ** aXRef[i]==-1 if the i-th column is not changed. */
  119997. u8 *aToOpen; /* 1 for tables and indices to be opened */
  119998. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  119999. u8 chngRowid; /* Rowid changed in a normal table */
  120000. u8 chngKey; /* Either chngPk or chngRowid */
  120001. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  120002. AuthContext sContext; /* The authorization context */
  120003. NameContext sNC; /* The name-context to resolve expressions in */
  120004. int iDb; /* Database containing the table being updated */
  120005. int eOnePass; /* ONEPASS_XXX value from where.c */
  120006. int hasFK; /* True if foreign key processing is required */
  120007. int labelBreak; /* Jump here to break out of UPDATE loop */
  120008. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  120009. int flags; /* Flags for sqlite3WhereBegin() */
  120010. #ifndef SQLITE_OMIT_TRIGGER
  120011. int isView; /* True when updating a view (INSTEAD OF trigger) */
  120012. Trigger *pTrigger; /* List of triggers on pTab, if required */
  120013. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  120014. #endif
  120015. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  120016. int iEph = 0; /* Ephemeral table holding all primary key values */
  120017. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  120018. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  120019. int addrOpen = 0; /* Address of OP_OpenEphemeral */
  120020. int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
  120021. i16 nPk = 0; /* Number of components of the PRIMARY KEY */
  120022. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  120023. /* Register Allocations */
  120024. int regRowCount = 0; /* A count of rows changed */
  120025. int regOldRowid = 0; /* The old rowid */
  120026. int regNewRowid = 0; /* The new rowid */
  120027. int regNew = 0; /* Content of the NEW.* table in triggers */
  120028. int regOld = 0; /* Content of OLD.* table in triggers */
  120029. int regRowSet = 0; /* Rowset of rows to be updated */
  120030. int regKey = 0; /* composite PRIMARY KEY value */
  120031. memset(&sContext, 0, sizeof(sContext));
  120032. db = pParse->db;
  120033. if( pParse->nErr || db->mallocFailed ){
  120034. goto update_cleanup;
  120035. }
  120036. assert( pTabList->nSrc==1 );
  120037. /* Locate the table which we want to update.
  120038. */
  120039. pTab = sqlite3SrcListLookup(pParse, pTabList);
  120040. if( pTab==0 ) goto update_cleanup;
  120041. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  120042. /* Figure out if we have any triggers and if the table being
  120043. ** updated is a view.
  120044. */
  120045. #ifndef SQLITE_OMIT_TRIGGER
  120046. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  120047. isView = pTab->pSelect!=0;
  120048. assert( pTrigger || tmask==0 );
  120049. #else
  120050. # define pTrigger 0
  120051. # define isView 0
  120052. # define tmask 0
  120053. #endif
  120054. #ifdef SQLITE_OMIT_VIEW
  120055. # undef isView
  120056. # define isView 0
  120057. #endif
  120058. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  120059. if( !isView ){
  120060. pWhere = sqlite3LimitWhere(
  120061. pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
  120062. );
  120063. pOrderBy = 0;
  120064. pLimit = 0;
  120065. }
  120066. #endif
  120067. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  120068. goto update_cleanup;
  120069. }
  120070. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  120071. goto update_cleanup;
  120072. }
  120073. /* Allocate a cursors for the main database table and for all indices.
  120074. ** The index cursors might not be used, but if they are used they
  120075. ** need to occur right after the database cursor. So go ahead and
  120076. ** allocate enough space, just in case.
  120077. */
  120078. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  120079. iIdxCur = iDataCur+1;
  120080. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  120081. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  120082. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  120083. iDataCur = pParse->nTab;
  120084. pTabList->a[0].iCursor = iDataCur;
  120085. }
  120086. pParse->nTab++;
  120087. }
  120088. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  120089. ** Initialize aXRef[] and aToOpen[] to their default values.
  120090. */
  120091. aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  120092. if( aXRef==0 ) goto update_cleanup;
  120093. aRegIdx = aXRef+pTab->nCol;
  120094. aToOpen = (u8*)(aRegIdx+nIdx);
  120095. memset(aToOpen, 1, nIdx+1);
  120096. aToOpen[nIdx+1] = 0;
  120097. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  120098. /* Initialize the name-context */
  120099. memset(&sNC, 0, sizeof(sNC));
  120100. sNC.pParse = pParse;
  120101. sNC.pSrcList = pTabList;
  120102. /* Resolve the column names in all the expressions of the
  120103. ** of the UPDATE statement. Also find the column index
  120104. ** for each column to be updated in the pChanges array. For each
  120105. ** column to be updated, make sure we have authorization to change
  120106. ** that column.
  120107. */
  120108. chngRowid = chngPk = 0;
  120109. for(i=0; i<pChanges->nExpr; i++){
  120110. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  120111. goto update_cleanup;
  120112. }
  120113. for(j=0; j<pTab->nCol; j++){
  120114. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  120115. if( j==pTab->iPKey ){
  120116. chngRowid = 1;
  120117. pRowidExpr = pChanges->a[i].pExpr;
  120118. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  120119. chngPk = 1;
  120120. }
  120121. aXRef[j] = i;
  120122. break;
  120123. }
  120124. }
  120125. if( j>=pTab->nCol ){
  120126. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  120127. j = -1;
  120128. chngRowid = 1;
  120129. pRowidExpr = pChanges->a[i].pExpr;
  120130. }else{
  120131. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  120132. pParse->checkSchema = 1;
  120133. goto update_cleanup;
  120134. }
  120135. }
  120136. #ifndef SQLITE_OMIT_AUTHORIZATION
  120137. {
  120138. int rc;
  120139. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  120140. j<0 ? "ROWID" : pTab->aCol[j].zName,
  120141. db->aDb[iDb].zDbSName);
  120142. if( rc==SQLITE_DENY ){
  120143. goto update_cleanup;
  120144. }else if( rc==SQLITE_IGNORE ){
  120145. aXRef[j] = -1;
  120146. }
  120147. }
  120148. #endif
  120149. }
  120150. assert( (chngRowid & chngPk)==0 );
  120151. assert( chngRowid==0 || chngRowid==1 );
  120152. assert( chngPk==0 || chngPk==1 );
  120153. chngKey = chngRowid + chngPk;
  120154. /* The SET expressions are not actually used inside the WHERE loop.
  120155. ** So reset the colUsed mask. Unless this is a virtual table. In that
  120156. ** case, set all bits of the colUsed mask (to ensure that the virtual
  120157. ** table implementation makes all columns available).
  120158. */
  120159. pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
  120160. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  120161. /* There is one entry in the aRegIdx[] array for each index on the table
  120162. ** being updated. Fill in aRegIdx[] with a register number that will hold
  120163. ** the key for accessing each index.
  120164. **
  120165. ** FIXME: Be smarter about omitting indexes that use expressions.
  120166. */
  120167. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  120168. int reg;
  120169. if( chngKey || hasFK>1 || pIdx->pPartIdxWhere || pIdx==pPk ){
  120170. reg = ++pParse->nMem;
  120171. pParse->nMem += pIdx->nColumn;
  120172. }else{
  120173. reg = 0;
  120174. for(i=0; i<pIdx->nKeyCol; i++){
  120175. i16 iIdxCol = pIdx->aiColumn[i];
  120176. if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
  120177. reg = ++pParse->nMem;
  120178. pParse->nMem += pIdx->nColumn;
  120179. if( (onError==OE_Replace)
  120180. || (onError==OE_Default && pIdx->onError==OE_Replace)
  120181. ){
  120182. bReplace = 1;
  120183. }
  120184. break;
  120185. }
  120186. }
  120187. }
  120188. if( reg==0 ) aToOpen[j+1] = 0;
  120189. aRegIdx[j] = reg;
  120190. }
  120191. if( bReplace ){
  120192. /* If REPLACE conflict resolution might be invoked, open cursors on all
  120193. ** indexes in case they are needed to delete records. */
  120194. memset(aToOpen, 1, nIdx+1);
  120195. }
  120196. /* Begin generating code. */
  120197. v = sqlite3GetVdbe(pParse);
  120198. if( v==0 ) goto update_cleanup;
  120199. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  120200. sqlite3BeginWriteOperation(pParse, 1, iDb);
  120201. /* Allocate required registers. */
  120202. if( !IsVirtual(pTab) ){
  120203. regRowSet = ++pParse->nMem;
  120204. regOldRowid = regNewRowid = ++pParse->nMem;
  120205. if( chngPk || pTrigger || hasFK ){
  120206. regOld = pParse->nMem + 1;
  120207. pParse->nMem += pTab->nCol;
  120208. }
  120209. if( chngKey || pTrigger || hasFK ){
  120210. regNewRowid = ++pParse->nMem;
  120211. }
  120212. regNew = pParse->nMem + 1;
  120213. pParse->nMem += pTab->nCol;
  120214. }
  120215. /* Start the view context. */
  120216. if( isView ){
  120217. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  120218. }
  120219. /* If we are trying to update a view, realize that view into
  120220. ** an ephemeral table.
  120221. */
  120222. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  120223. if( isView ){
  120224. sqlite3MaterializeView(pParse, pTab,
  120225. pWhere, pOrderBy, pLimit, iDataCur
  120226. );
  120227. pOrderBy = 0;
  120228. pLimit = 0;
  120229. }
  120230. #endif
  120231. /* Resolve the column names in all the expressions in the
  120232. ** WHERE clause.
  120233. */
  120234. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  120235. goto update_cleanup;
  120236. }
  120237. #ifndef SQLITE_OMIT_VIRTUALTABLE
  120238. /* Virtual tables must be handled separately */
  120239. if( IsVirtual(pTab) ){
  120240. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  120241. pWhere, onError);
  120242. goto update_cleanup;
  120243. }
  120244. #endif
  120245. /* Initialize the count of updated rows */
  120246. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  120247. regRowCount = ++pParse->nMem;
  120248. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  120249. }
  120250. if( HasRowid(pTab) ){
  120251. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  120252. }else{
  120253. assert( pPk!=0 );
  120254. nPk = pPk->nKeyCol;
  120255. iPk = pParse->nMem+1;
  120256. pParse->nMem += nPk;
  120257. regKey = ++pParse->nMem;
  120258. iEph = pParse->nTab++;
  120259. sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
  120260. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  120261. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  120262. }
  120263. /* Begin the database scan.
  120264. **
  120265. ** Do not consider a single-pass strategy for a multi-row update if
  120266. ** there are any triggers or foreign keys to process, or rows may
  120267. ** be deleted as a result of REPLACE conflict handling. Any of these
  120268. ** things might disturb a cursor being used to scan through the table
  120269. ** or index, causing a single-pass approach to malfunction. */
  120270. flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
  120271. if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
  120272. flags |= WHERE_ONEPASS_MULTIROW;
  120273. }
  120274. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
  120275. if( pWInfo==0 ) goto update_cleanup;
  120276. /* A one-pass strategy that might update more than one row may not
  120277. ** be used if any column of the index used for the scan is being
  120278. ** updated. Otherwise, if there is an index on "b", statements like
  120279. ** the following could create an infinite loop:
  120280. **
  120281. ** UPDATE t1 SET b=b+1 WHERE b>?
  120282. **
  120283. ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
  120284. ** strategy that uses an index for which one or more columns are being
  120285. ** updated. */
  120286. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  120287. if( eOnePass==ONEPASS_MULTI ){
  120288. int iCur = aiCurOnePass[1];
  120289. if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
  120290. eOnePass = ONEPASS_OFF;
  120291. }
  120292. assert( iCur!=iDataCur || !HasRowid(pTab) );
  120293. }
  120294. if( HasRowid(pTab) ){
  120295. /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
  120296. ** mode, write the rowid into the FIFO. In either of the one-pass modes,
  120297. ** leave it in register regOldRowid. */
  120298. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  120299. if( eOnePass==ONEPASS_OFF ){
  120300. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  120301. }
  120302. }else{
  120303. /* Read the PK of the current row into an array of registers. In
  120304. ** ONEPASS_OFF mode, serialize the array into a record and store it in
  120305. ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
  120306. ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
  120307. ** is not required) and leave the PK fields in the array of registers. */
  120308. for(i=0; i<nPk; i++){
  120309. assert( pPk->aiColumn[i]>=0 );
  120310. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,pPk->aiColumn[i],iPk+i);
  120311. }
  120312. if( eOnePass ){
  120313. sqlite3VdbeChangeToNoop(v, addrOpen);
  120314. nKey = nPk;
  120315. regKey = iPk;
  120316. }else{
  120317. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  120318. sqlite3IndexAffinityStr(db, pPk), nPk);
  120319. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
  120320. }
  120321. }
  120322. if( eOnePass!=ONEPASS_MULTI ){
  120323. sqlite3WhereEnd(pWInfo);
  120324. }
  120325. labelBreak = sqlite3VdbeMakeLabel(v);
  120326. if( !isView ){
  120327. int addrOnce = 0;
  120328. /* Open every index that needs updating. */
  120329. if( eOnePass!=ONEPASS_OFF ){
  120330. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  120331. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  120332. }
  120333. if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
  120334. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  120335. }
  120336. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
  120337. 0, 0);
  120338. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  120339. }
  120340. /* Top of the update loop */
  120341. if( eOnePass!=ONEPASS_OFF ){
  120342. if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
  120343. assert( pPk );
  120344. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  120345. VdbeCoverageNeverTaken(v);
  120346. }
  120347. if( eOnePass==ONEPASS_SINGLE ){
  120348. labelContinue = labelBreak;
  120349. }else{
  120350. labelContinue = sqlite3VdbeMakeLabel(v);
  120351. }
  120352. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  120353. VdbeCoverageIf(v, pPk==0);
  120354. VdbeCoverageIf(v, pPk!=0);
  120355. }else if( pPk ){
  120356. labelContinue = sqlite3VdbeMakeLabel(v);
  120357. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  120358. addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
  120359. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  120360. VdbeCoverage(v);
  120361. }else{
  120362. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  120363. regOldRowid);
  120364. VdbeCoverage(v);
  120365. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  120366. VdbeCoverage(v);
  120367. }
  120368. /* If the record number will change, set register regNewRowid to
  120369. ** contain the new value. If the record number is not being modified,
  120370. ** then regNewRowid is the same register as regOldRowid, which is
  120371. ** already populated. */
  120372. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  120373. if( chngRowid ){
  120374. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  120375. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  120376. }
  120377. /* Compute the old pre-UPDATE content of the row being changed, if that
  120378. ** information is needed */
  120379. if( chngPk || hasFK || pTrigger ){
  120380. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  120381. oldmask |= sqlite3TriggerColmask(pParse,
  120382. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  120383. );
  120384. for(i=0; i<pTab->nCol; i++){
  120385. if( oldmask==0xffffffff
  120386. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  120387. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  120388. ){
  120389. testcase( oldmask!=0xffffffff && i==31 );
  120390. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  120391. }else{
  120392. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  120393. }
  120394. }
  120395. if( chngRowid==0 && pPk==0 ){
  120396. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  120397. }
  120398. }
  120399. /* Populate the array of registers beginning at regNew with the new
  120400. ** row data. This array is used to check constants, create the new
  120401. ** table and index records, and as the values for any new.* references
  120402. ** made by triggers.
  120403. **
  120404. ** If there are one or more BEFORE triggers, then do not populate the
  120405. ** registers associated with columns that are (a) not modified by
  120406. ** this UPDATE statement and (b) not accessed by new.* references. The
  120407. ** values for registers not modified by the UPDATE must be reloaded from
  120408. ** the database after the BEFORE triggers are fired anyway (as the trigger
  120409. ** may have modified them). So not loading those that are not going to
  120410. ** be used eliminates some redundant opcodes.
  120411. */
  120412. newmask = sqlite3TriggerColmask(
  120413. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  120414. );
  120415. for(i=0; i<pTab->nCol; i++){
  120416. if( i==pTab->iPKey ){
  120417. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  120418. }else{
  120419. j = aXRef[i];
  120420. if( j>=0 ){
  120421. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  120422. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  120423. /* This branch loads the value of a column that will not be changed
  120424. ** into a register. This is done if there are no BEFORE triggers, or
  120425. ** if there are one or more BEFORE triggers that use this value via
  120426. ** a new.* reference in a trigger program.
  120427. */
  120428. testcase( i==31 );
  120429. testcase( i==32 );
  120430. sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
  120431. }else{
  120432. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  120433. }
  120434. }
  120435. }
  120436. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  120437. ** verified. One could argue that this is wrong.
  120438. */
  120439. if( tmask&TRIGGER_BEFORE ){
  120440. sqlite3TableAffinity(v, pTab, regNew);
  120441. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  120442. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  120443. /* The row-trigger may have deleted the row being updated. In this
  120444. ** case, jump to the next row. No updates or AFTER triggers are
  120445. ** required. This behavior - what happens when the row being updated
  120446. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  120447. ** documentation.
  120448. */
  120449. if( pPk ){
  120450. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  120451. VdbeCoverage(v);
  120452. }else{
  120453. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  120454. VdbeCoverage(v);
  120455. }
  120456. /* If it did not delete it, the row-trigger may still have modified
  120457. ** some of the columns of the row being updated. Load the values for
  120458. ** all columns not modified by the update statement into their
  120459. ** registers in case this has happened.
  120460. */
  120461. for(i=0; i<pTab->nCol; i++){
  120462. if( aXRef[i]<0 && i!=pTab->iPKey ){
  120463. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  120464. }
  120465. }
  120466. }
  120467. if( !isView ){
  120468. int addr1 = 0; /* Address of jump instruction */
  120469. /* Do constraint checks. */
  120470. assert( regOldRowid>0 );
  120471. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  120472. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
  120473. aXRef);
  120474. /* Do FK constraint checks. */
  120475. if( hasFK ){
  120476. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  120477. }
  120478. /* Delete the index entries associated with the current record. */
  120479. if( bReplace || chngKey ){
  120480. if( pPk ){
  120481. addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  120482. }else{
  120483. addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  120484. }
  120485. VdbeCoverageNeverTaken(v);
  120486. }
  120487. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  120488. /* If changing the rowid value, or if there are foreign key constraints
  120489. ** to process, delete the old record. Otherwise, add a noop OP_Delete
  120490. ** to invoke the pre-update hook.
  120491. **
  120492. ** That (regNew==regnewRowid+1) is true is also important for the
  120493. ** pre-update hook. If the caller invokes preupdate_new(), the returned
  120494. ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
  120495. ** is the column index supplied by the user.
  120496. */
  120497. assert( regNew==regNewRowid+1 );
  120498. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  120499. sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
  120500. OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
  120501. regNewRowid
  120502. );
  120503. if( eOnePass==ONEPASS_MULTI ){
  120504. assert( hasFK==0 && chngKey==0 );
  120505. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  120506. }
  120507. if( !pParse->nested ){
  120508. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  120509. }
  120510. #else
  120511. if( hasFK>1 || chngKey ){
  120512. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  120513. }
  120514. #endif
  120515. if( bReplace || chngKey ){
  120516. sqlite3VdbeJumpHere(v, addr1);
  120517. }
  120518. if( hasFK ){
  120519. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  120520. }
  120521. /* Insert the new index entries and the new record. */
  120522. sqlite3CompleteInsertion(
  120523. pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
  120524. OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
  120525. 0, 0
  120526. );
  120527. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  120528. ** handle rows (possibly in other tables) that refer via a foreign key
  120529. ** to the row just updated. */
  120530. if( hasFK ){
  120531. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  120532. }
  120533. }
  120534. /* Increment the row counter
  120535. */
  120536. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  120537. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  120538. }
  120539. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  120540. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  120541. /* Repeat the above with the next record to be updated, until
  120542. ** all record selected by the WHERE clause have been updated.
  120543. */
  120544. if( eOnePass==ONEPASS_SINGLE ){
  120545. /* Nothing to do at end-of-loop for a single-pass */
  120546. }else if( eOnePass==ONEPASS_MULTI ){
  120547. sqlite3VdbeResolveLabel(v, labelContinue);
  120548. sqlite3WhereEnd(pWInfo);
  120549. }else if( pPk ){
  120550. sqlite3VdbeResolveLabel(v, labelContinue);
  120551. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  120552. }else{
  120553. sqlite3VdbeGoto(v, labelContinue);
  120554. }
  120555. sqlite3VdbeResolveLabel(v, labelBreak);
  120556. /* Update the sqlite_sequence table by storing the content of the
  120557. ** maximum rowid counter values recorded while inserting into
  120558. ** autoincrement tables.
  120559. */
  120560. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  120561. sqlite3AutoincrementEnd(pParse);
  120562. }
  120563. /*
  120564. ** Return the number of rows that were changed. If this routine is
  120565. ** generating code because of a call to sqlite3NestedParse(), do not
  120566. ** invoke the callback function.
  120567. */
  120568. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  120569. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  120570. sqlite3VdbeSetNumCols(v, 1);
  120571. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  120572. }
  120573. update_cleanup:
  120574. sqlite3AuthContextPop(&sContext);
  120575. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  120576. sqlite3SrcListDelete(db, pTabList);
  120577. sqlite3ExprListDelete(db, pChanges);
  120578. sqlite3ExprDelete(db, pWhere);
  120579. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  120580. sqlite3ExprListDelete(db, pOrderBy);
  120581. sqlite3ExprDelete(db, pLimit);
  120582. #endif
  120583. return;
  120584. }
  120585. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  120586. ** they may interfere with compilation of other functions in this file
  120587. ** (or in another file, if this file becomes part of the amalgamation). */
  120588. #ifdef isView
  120589. #undef isView
  120590. #endif
  120591. #ifdef pTrigger
  120592. #undef pTrigger
  120593. #endif
  120594. #ifndef SQLITE_OMIT_VIRTUALTABLE
  120595. /*
  120596. ** Generate code for an UPDATE of a virtual table.
  120597. **
  120598. ** There are two possible strategies - the default and the special
  120599. ** "onepass" strategy. Onepass is only used if the virtual table
  120600. ** implementation indicates that pWhere may match at most one row.
  120601. **
  120602. ** The default strategy is to create an ephemeral table that contains
  120603. ** for each row to be changed:
  120604. **
  120605. ** (A) The original rowid of that row.
  120606. ** (B) The revised rowid for the row.
  120607. ** (C) The content of every column in the row.
  120608. **
  120609. ** Then loop through the contents of this ephemeral table executing a
  120610. ** VUpdate for each row. When finished, drop the ephemeral table.
  120611. **
  120612. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  120613. ** stores the same values (A, B and C above) in a register array and
  120614. ** makes a single invocation of VUpdate.
  120615. */
  120616. static void updateVirtualTable(
  120617. Parse *pParse, /* The parsing context */
  120618. SrcList *pSrc, /* The virtual table to be modified */
  120619. Table *pTab, /* The virtual table */
  120620. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  120621. Expr *pRowid, /* Expression used to recompute the rowid */
  120622. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  120623. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  120624. int onError /* ON CONFLICT strategy */
  120625. ){
  120626. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  120627. int ephemTab; /* Table holding the result of the SELECT */
  120628. int i; /* Loop counter */
  120629. sqlite3 *db = pParse->db; /* Database connection */
  120630. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  120631. WhereInfo *pWInfo;
  120632. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  120633. int regArg; /* First register in VUpdate arg array */
  120634. int regRec; /* Register in which to assemble record */
  120635. int regRowid; /* Register for ephem table rowid */
  120636. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  120637. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  120638. int bOnePass; /* True to use onepass strategy */
  120639. int addr; /* Address of OP_OpenEphemeral */
  120640. /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
  120641. ** create and open the ephemeral table in which the records created from
  120642. ** these arguments will be temporarily stored. */
  120643. assert( v );
  120644. ephemTab = pParse->nTab++;
  120645. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  120646. regArg = pParse->nMem + 1;
  120647. pParse->nMem += nArg;
  120648. regRec = ++pParse->nMem;
  120649. regRowid = ++pParse->nMem;
  120650. /* Start scanning the virtual table */
  120651. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  120652. if( pWInfo==0 ) return;
  120653. /* Populate the argument registers. */
  120654. for(i=0; i<pTab->nCol; i++){
  120655. if( aXRef[i]>=0 ){
  120656. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  120657. }else{
  120658. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  120659. sqlite3VdbeChangeP5(v, 1); /* Enable sqlite3_vtab_nochange() */
  120660. }
  120661. }
  120662. if( HasRowid(pTab) ){
  120663. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  120664. if( pRowid ){
  120665. sqlite3ExprCode(pParse, pRowid, regArg+1);
  120666. }else{
  120667. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  120668. }
  120669. }else{
  120670. Index *pPk; /* PRIMARY KEY index */
  120671. i16 iPk; /* PRIMARY KEY column */
  120672. pPk = sqlite3PrimaryKeyIndex(pTab);
  120673. assert( pPk!=0 );
  120674. assert( pPk->nKeyCol==1 );
  120675. iPk = pPk->aiColumn[0];
  120676. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
  120677. sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
  120678. }
  120679. bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  120680. if( bOnePass ){
  120681. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  120682. ** above. Also, if this is a top-level parse (not a trigger), clear the
  120683. ** multi-write flag so that the VM does not open a statement journal */
  120684. sqlite3VdbeChangeToNoop(v, addr);
  120685. if( sqlite3IsToplevel(pParse) ){
  120686. pParse->isMultiWrite = 0;
  120687. }
  120688. }else{
  120689. /* Create a record from the argument register contents and insert it into
  120690. ** the ephemeral table. */
  120691. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  120692. #ifdef SQLITE_DEBUG
  120693. /* Signal an assert() within OP_MakeRecord that it is allowed to
  120694. ** accept no-change records with serial_type 10 */
  120695. sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
  120696. #endif
  120697. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  120698. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  120699. }
  120700. if( bOnePass==0 ){
  120701. /* End the virtual table scan */
  120702. sqlite3WhereEnd(pWInfo);
  120703. /* Begin scannning through the ephemeral table. */
  120704. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  120705. /* Extract arguments from the current row of the ephemeral table and
  120706. ** invoke the VUpdate method. */
  120707. for(i=0; i<nArg; i++){
  120708. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  120709. }
  120710. }
  120711. sqlite3VtabMakeWritable(pParse, pTab);
  120712. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  120713. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  120714. sqlite3MayAbort(pParse);
  120715. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  120716. ** jump to here if the scan visited zero rows. */
  120717. if( bOnePass==0 ){
  120718. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  120719. sqlite3VdbeJumpHere(v, addr);
  120720. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  120721. }else{
  120722. sqlite3WhereEnd(pWInfo);
  120723. }
  120724. }
  120725. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  120726. /************** End of update.c **********************************************/
  120727. /************** Begin file vacuum.c ******************************************/
  120728. /*
  120729. ** 2003 April 6
  120730. **
  120731. ** The author disclaims copyright to this source code. In place of
  120732. ** a legal notice, here is a blessing:
  120733. **
  120734. ** May you do good and not evil.
  120735. ** May you find forgiveness for yourself and forgive others.
  120736. ** May you share freely, never taking more than you give.
  120737. **
  120738. *************************************************************************
  120739. ** This file contains code used to implement the VACUUM command.
  120740. **
  120741. ** Most of the code in this file may be omitted by defining the
  120742. ** SQLITE_OMIT_VACUUM macro.
  120743. */
  120744. /* #include "sqliteInt.h" */
  120745. /* #include "vdbeInt.h" */
  120746. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  120747. /*
  120748. ** Execute zSql on database db.
  120749. **
  120750. ** If zSql returns rows, then each row will have exactly one
  120751. ** column. (This will only happen if zSql begins with "SELECT".)
  120752. ** Take each row of result and call execSql() again recursively.
  120753. **
  120754. ** The execSqlF() routine does the same thing, except it accepts
  120755. ** a format string as its third argument
  120756. */
  120757. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  120758. sqlite3_stmt *pStmt;
  120759. int rc;
  120760. /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
  120761. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  120762. if( rc!=SQLITE_OK ) return rc;
  120763. while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  120764. const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
  120765. assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
  120766. assert( sqlite3_strnicmp(zSubSql,"SELECT",6)!=0 || CORRUPT_DB );
  120767. if( zSubSql && zSubSql[0]!='S' ){
  120768. rc = execSql(db, pzErrMsg, zSubSql);
  120769. if( rc!=SQLITE_OK ) break;
  120770. }
  120771. }
  120772. assert( rc!=SQLITE_ROW );
  120773. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  120774. if( rc ){
  120775. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  120776. }
  120777. (void)sqlite3_finalize(pStmt);
  120778. return rc;
  120779. }
  120780. static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
  120781. char *z;
  120782. va_list ap;
  120783. int rc;
  120784. va_start(ap, zSql);
  120785. z = sqlite3VMPrintf(db, zSql, ap);
  120786. va_end(ap);
  120787. if( z==0 ) return SQLITE_NOMEM;
  120788. rc = execSql(db, pzErrMsg, z);
  120789. sqlite3DbFree(db, z);
  120790. return rc;
  120791. }
  120792. /*
  120793. ** The VACUUM command is used to clean up the database,
  120794. ** collapse free space, etc. It is modelled after the VACUUM command
  120795. ** in PostgreSQL. The VACUUM command works as follows:
  120796. **
  120797. ** (1) Create a new transient database file
  120798. ** (2) Copy all content from the database being vacuumed into
  120799. ** the new transient database file
  120800. ** (3) Copy content from the transient database back into the
  120801. ** original database.
  120802. **
  120803. ** The transient database requires temporary disk space approximately
  120804. ** equal to the size of the original database. The copy operation of
  120805. ** step (3) requires additional temporary disk space approximately equal
  120806. ** to the size of the original database for the rollback journal.
  120807. ** Hence, temporary disk space that is approximately 2x the size of the
  120808. ** original database is required. Every page of the database is written
  120809. ** approximately 3 times: Once for step (2) and twice for step (3).
  120810. ** Two writes per page are required in step (3) because the original
  120811. ** database content must be written into the rollback journal prior to
  120812. ** overwriting the database with the vacuumed content.
  120813. **
  120814. ** Only 1x temporary space and only 1x writes would be required if
  120815. ** the copy of step (3) were replaced by deleting the original database
  120816. ** and renaming the transient database as the original. But that will
  120817. ** not work if other processes are attached to the original database.
  120818. ** And a power loss in between deleting the original and renaming the
  120819. ** transient would cause the database file to appear to be deleted
  120820. ** following reboot.
  120821. */
  120822. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm){
  120823. Vdbe *v = sqlite3GetVdbe(pParse);
  120824. int iDb = 0;
  120825. if( v==0 ) return;
  120826. if( pNm ){
  120827. #ifndef SQLITE_BUG_COMPATIBLE_20160819
  120828. /* Default behavior: Report an error if the argument to VACUUM is
  120829. ** not recognized */
  120830. iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
  120831. if( iDb<0 ) return;
  120832. #else
  120833. /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
  120834. ** to VACUUM are silently ignored. This is a back-out of a bug fix that
  120835. ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
  120836. ** The buggy behavior is required for binary compatibility with some
  120837. ** legacy applications. */
  120838. iDb = sqlite3FindDb(pParse->db, pNm);
  120839. if( iDb<0 ) iDb = 0;
  120840. #endif
  120841. }
  120842. if( iDb!=1 ){
  120843. sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
  120844. sqlite3VdbeUsesBtree(v, iDb);
  120845. }
  120846. return;
  120847. }
  120848. /*
  120849. ** This routine implements the OP_Vacuum opcode of the VDBE.
  120850. */
  120851. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
  120852. int rc = SQLITE_OK; /* Return code from service routines */
  120853. Btree *pMain; /* The database being vacuumed */
  120854. Btree *pTemp; /* The temporary database we vacuum into */
  120855. u16 saved_mDbFlags; /* Saved value of db->mDbFlags */
  120856. u32 saved_flags; /* Saved value of db->flags */
  120857. int saved_nChange; /* Saved value of db->nChange */
  120858. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  120859. u8 saved_mTrace; /* Saved trace settings */
  120860. Db *pDb = 0; /* Database to detach at end of vacuum */
  120861. int isMemDb; /* True if vacuuming a :memory: database */
  120862. int nRes; /* Bytes of reserved space at the end of each page */
  120863. int nDb; /* Number of attached databases */
  120864. const char *zDbMain; /* Schema name of database to vacuum */
  120865. if( !db->autoCommit ){
  120866. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  120867. return SQLITE_ERROR;
  120868. }
  120869. if( db->nVdbeActive>1 ){
  120870. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  120871. return SQLITE_ERROR;
  120872. }
  120873. /* Save the current value of the database flags so that it can be
  120874. ** restored before returning. Then set the writable-schema flag, and
  120875. ** disable CHECK and foreign key constraints. */
  120876. saved_flags = db->flags;
  120877. saved_mDbFlags = db->mDbFlags;
  120878. saved_nChange = db->nChange;
  120879. saved_nTotalChange = db->nTotalChange;
  120880. saved_mTrace = db->mTrace;
  120881. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
  120882. db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
  120883. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
  120884. db->mTrace = 0;
  120885. zDbMain = db->aDb[iDb].zDbSName;
  120886. pMain = db->aDb[iDb].pBt;
  120887. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  120888. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  120889. ** can be set to 'off' for this file, as it is not recovered if a crash
  120890. ** occurs anyway. The integrity of the database is maintained by a
  120891. ** (possibly synchronous) transaction opened on the main database before
  120892. ** sqlite3BtreeCopyFile() is called.
  120893. **
  120894. ** An optimisation would be to use a non-journaled pager.
  120895. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  120896. ** that actually made the VACUUM run slower. Very little journalling
  120897. ** actually occurs when doing a vacuum since the vacuum_db is initially
  120898. ** empty. Only the journal header is written. Apparently it takes more
  120899. ** time to parse and run the PRAGMA to turn journalling off than it does
  120900. ** to write the journal header file.
  120901. */
  120902. nDb = db->nDb;
  120903. rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
  120904. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  120905. assert( (db->nDb-1)==nDb );
  120906. pDb = &db->aDb[nDb];
  120907. assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
  120908. pTemp = pDb->pBt;
  120909. /* The call to execSql() to attach the temp database has left the file
  120910. ** locked (as there was more than one active statement when the transaction
  120911. ** to read the schema was concluded. Unlock it here so that this doesn't
  120912. ** cause problems for the call to BtreeSetPageSize() below. */
  120913. sqlite3BtreeCommit(pTemp);
  120914. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  120915. /* A VACUUM cannot change the pagesize of an encrypted database. */
  120916. #ifdef SQLITE_HAS_CODEC
  120917. if( db->nextPagesize ){
  120918. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  120919. int nKey;
  120920. char *zKey;
  120921. sqlite3CodecGetKey(db, iDb, (void**)&zKey, &nKey);
  120922. if( nKey ) db->nextPagesize = 0;
  120923. }
  120924. #endif
  120925. sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
  120926. sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
  120927. sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
  120928. /* Begin a transaction and take an exclusive lock on the main database
  120929. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  120930. ** to ensure that we do not try to change the page-size on a WAL database.
  120931. */
  120932. rc = execSql(db, pzErrMsg, "BEGIN");
  120933. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  120934. rc = sqlite3BtreeBeginTrans(pMain, 2);
  120935. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  120936. /* Do not attempt to change the page size for a WAL database */
  120937. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  120938. ==PAGER_JOURNALMODE_WAL ){
  120939. db->nextPagesize = 0;
  120940. }
  120941. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  120942. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  120943. || NEVER(db->mallocFailed)
  120944. ){
  120945. rc = SQLITE_NOMEM_BKPT;
  120946. goto end_of_vacuum;
  120947. }
  120948. #ifndef SQLITE_OMIT_AUTOVACUUM
  120949. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  120950. sqlite3BtreeGetAutoVacuum(pMain));
  120951. #endif
  120952. /* Query the schema of the main database. Create a mirror schema
  120953. ** in the temporary database.
  120954. */
  120955. db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
  120956. rc = execSqlF(db, pzErrMsg,
  120957. "SELECT sql FROM \"%w\".sqlite_master"
  120958. " WHERE type='table'AND name<>'sqlite_sequence'"
  120959. " AND coalesce(rootpage,1)>0",
  120960. zDbMain
  120961. );
  120962. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  120963. rc = execSqlF(db, pzErrMsg,
  120964. "SELECT sql FROM \"%w\".sqlite_master"
  120965. " WHERE type='index' AND length(sql)>10",
  120966. zDbMain
  120967. );
  120968. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  120969. db->init.iDb = 0;
  120970. /* Loop through the tables in the main database. For each, do
  120971. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  120972. ** the contents to the temporary database.
  120973. */
  120974. rc = execSqlF(db, pzErrMsg,
  120975. "SELECT'INSERT INTO vacuum_db.'||quote(name)"
  120976. "||' SELECT*FROM\"%w\".'||quote(name)"
  120977. "FROM vacuum_db.sqlite_master "
  120978. "WHERE type='table'AND coalesce(rootpage,1)>0",
  120979. zDbMain
  120980. );
  120981. assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
  120982. db->mDbFlags &= ~DBFLAG_Vacuum;
  120983. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  120984. /* Copy the triggers, views, and virtual tables from the main database
  120985. ** over to the temporary database. None of these objects has any
  120986. ** associated storage, so all we have to do is copy their entries
  120987. ** from the SQLITE_MASTER table.
  120988. */
  120989. rc = execSqlF(db, pzErrMsg,
  120990. "INSERT INTO vacuum_db.sqlite_master"
  120991. " SELECT*FROM \"%w\".sqlite_master"
  120992. " WHERE type IN('view','trigger')"
  120993. " OR(type='table'AND rootpage=0)",
  120994. zDbMain
  120995. );
  120996. if( rc ) goto end_of_vacuum;
  120997. /* At this point, there is a write transaction open on both the
  120998. ** vacuum database and the main database. Assuming no error occurs,
  120999. ** both transactions are closed by this block - the main database
  121000. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  121001. ** call to sqlite3BtreeCommit().
  121002. */
  121003. {
  121004. u32 meta;
  121005. int i;
  121006. /* This array determines which meta meta values are preserved in the
  121007. ** vacuum. Even entries are the meta value number and odd entries
  121008. ** are an increment to apply to the meta value after the vacuum.
  121009. ** The increment is used to increase the schema cookie so that other
  121010. ** connections to the same database will know to reread the schema.
  121011. */
  121012. static const unsigned char aCopy[] = {
  121013. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  121014. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  121015. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  121016. BTREE_USER_VERSION, 0, /* Preserve the user version */
  121017. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  121018. };
  121019. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  121020. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  121021. /* Copy Btree meta values */
  121022. for(i=0; i<ArraySize(aCopy); i+=2){
  121023. /* GetMeta() and UpdateMeta() cannot fail in this context because
  121024. ** we already have page 1 loaded into cache and marked dirty. */
  121025. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  121026. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  121027. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  121028. }
  121029. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  121030. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  121031. rc = sqlite3BtreeCommit(pTemp);
  121032. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  121033. #ifndef SQLITE_OMIT_AUTOVACUUM
  121034. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  121035. #endif
  121036. }
  121037. assert( rc==SQLITE_OK );
  121038. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  121039. end_of_vacuum:
  121040. /* Restore the original value of db->flags */
  121041. db->init.iDb = 0;
  121042. db->mDbFlags = saved_mDbFlags;
  121043. db->flags = saved_flags;
  121044. db->nChange = saved_nChange;
  121045. db->nTotalChange = saved_nTotalChange;
  121046. db->mTrace = saved_mTrace;
  121047. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  121048. /* Currently there is an SQL level transaction open on the vacuum
  121049. ** database. No locks are held on any other files (since the main file
  121050. ** was committed at the btree level). So it safe to end the transaction
  121051. ** by manually setting the autoCommit flag to true and detaching the
  121052. ** vacuum database. The vacuum_db journal file is deleted when the pager
  121053. ** is closed by the DETACH.
  121054. */
  121055. db->autoCommit = 1;
  121056. if( pDb ){
  121057. sqlite3BtreeClose(pDb->pBt);
  121058. pDb->pBt = 0;
  121059. pDb->pSchema = 0;
  121060. }
  121061. /* This both clears the schemas and reduces the size of the db->aDb[]
  121062. ** array. */
  121063. sqlite3ResetAllSchemasOfConnection(db);
  121064. return rc;
  121065. }
  121066. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  121067. /************** End of vacuum.c **********************************************/
  121068. /************** Begin file vtab.c ********************************************/
  121069. /*
  121070. ** 2006 June 10
  121071. **
  121072. ** The author disclaims copyright to this source code. In place of
  121073. ** a legal notice, here is a blessing:
  121074. **
  121075. ** May you do good and not evil.
  121076. ** May you find forgiveness for yourself and forgive others.
  121077. ** May you share freely, never taking more than you give.
  121078. **
  121079. *************************************************************************
  121080. ** This file contains code used to help implement virtual tables.
  121081. */
  121082. #ifndef SQLITE_OMIT_VIRTUALTABLE
  121083. /* #include "sqliteInt.h" */
  121084. /*
  121085. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  121086. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  121087. ** this struct allocated on the stack. It is used by the implementation of
  121088. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  121089. ** are invoked only from within xCreate and xConnect methods.
  121090. */
  121091. struct VtabCtx {
  121092. VTable *pVTable; /* The virtual table being constructed */
  121093. Table *pTab; /* The Table object to which the virtual table belongs */
  121094. VtabCtx *pPrior; /* Parent context (if any) */
  121095. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  121096. };
  121097. /*
  121098. ** Construct and install a Module object for a virtual table. When this
  121099. ** routine is called, it is guaranteed that all appropriate locks are held
  121100. ** and the module is not already part of the connection.
  121101. */
  121102. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  121103. sqlite3 *db, /* Database in which module is registered */
  121104. const char *zName, /* Name assigned to this module */
  121105. const sqlite3_module *pModule, /* The definition of the module */
  121106. void *pAux, /* Context pointer for xCreate/xConnect */
  121107. void (*xDestroy)(void *) /* Module destructor function */
  121108. ){
  121109. Module *pMod;
  121110. int nName = sqlite3Strlen30(zName);
  121111. pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
  121112. if( pMod==0 ){
  121113. sqlite3OomFault(db);
  121114. }else{
  121115. Module *pDel;
  121116. char *zCopy = (char *)(&pMod[1]);
  121117. memcpy(zCopy, zName, nName+1);
  121118. pMod->zName = zCopy;
  121119. pMod->pModule = pModule;
  121120. pMod->pAux = pAux;
  121121. pMod->xDestroy = xDestroy;
  121122. pMod->pEpoTab = 0;
  121123. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  121124. assert( pDel==0 || pDel==pMod );
  121125. if( pDel ){
  121126. sqlite3OomFault(db);
  121127. sqlite3DbFree(db, pDel);
  121128. pMod = 0;
  121129. }
  121130. }
  121131. return pMod;
  121132. }
  121133. /*
  121134. ** The actual function that does the work of creating a new module.
  121135. ** This function implements the sqlite3_create_module() and
  121136. ** sqlite3_create_module_v2() interfaces.
  121137. */
  121138. static int createModule(
  121139. sqlite3 *db, /* Database in which module is registered */
  121140. const char *zName, /* Name assigned to this module */
  121141. const sqlite3_module *pModule, /* The definition of the module */
  121142. void *pAux, /* Context pointer for xCreate/xConnect */
  121143. void (*xDestroy)(void *) /* Module destructor function */
  121144. ){
  121145. int rc = SQLITE_OK;
  121146. sqlite3_mutex_enter(db->mutex);
  121147. if( sqlite3HashFind(&db->aModule, zName) ){
  121148. rc = SQLITE_MISUSE_BKPT;
  121149. }else{
  121150. (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
  121151. }
  121152. rc = sqlite3ApiExit(db, rc);
  121153. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  121154. sqlite3_mutex_leave(db->mutex);
  121155. return rc;
  121156. }
  121157. /*
  121158. ** External API function used to create a new virtual-table module.
  121159. */
  121160. SQLITE_API int sqlite3_create_module(
  121161. sqlite3 *db, /* Database in which module is registered */
  121162. const char *zName, /* Name assigned to this module */
  121163. const sqlite3_module *pModule, /* The definition of the module */
  121164. void *pAux /* Context pointer for xCreate/xConnect */
  121165. ){
  121166. #ifdef SQLITE_ENABLE_API_ARMOR
  121167. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  121168. #endif
  121169. return createModule(db, zName, pModule, pAux, 0);
  121170. }
  121171. /*
  121172. ** External API function used to create a new virtual-table module.
  121173. */
  121174. SQLITE_API int sqlite3_create_module_v2(
  121175. sqlite3 *db, /* Database in which module is registered */
  121176. const char *zName, /* Name assigned to this module */
  121177. const sqlite3_module *pModule, /* The definition of the module */
  121178. void *pAux, /* Context pointer for xCreate/xConnect */
  121179. void (*xDestroy)(void *) /* Module destructor function */
  121180. ){
  121181. #ifdef SQLITE_ENABLE_API_ARMOR
  121182. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  121183. #endif
  121184. return createModule(db, zName, pModule, pAux, xDestroy);
  121185. }
  121186. /*
  121187. ** Lock the virtual table so that it cannot be disconnected.
  121188. ** Locks nest. Every lock should have a corresponding unlock.
  121189. ** If an unlock is omitted, resources leaks will occur.
  121190. **
  121191. ** If a disconnect is attempted while a virtual table is locked,
  121192. ** the disconnect is deferred until all locks have been removed.
  121193. */
  121194. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  121195. pVTab->nRef++;
  121196. }
  121197. /*
  121198. ** pTab is a pointer to a Table structure representing a virtual-table.
  121199. ** Return a pointer to the VTable object used by connection db to access
  121200. ** this virtual-table, if one has been created, or NULL otherwise.
  121201. */
  121202. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  121203. VTable *pVtab;
  121204. assert( IsVirtual(pTab) );
  121205. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  121206. return pVtab;
  121207. }
  121208. /*
  121209. ** Decrement the ref-count on a virtual table object. When the ref-count
  121210. ** reaches zero, call the xDisconnect() method to delete the object.
  121211. */
  121212. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  121213. sqlite3 *db = pVTab->db;
  121214. assert( db );
  121215. assert( pVTab->nRef>0 );
  121216. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  121217. pVTab->nRef--;
  121218. if( pVTab->nRef==0 ){
  121219. sqlite3_vtab *p = pVTab->pVtab;
  121220. if( p ){
  121221. p->pModule->xDisconnect(p);
  121222. }
  121223. sqlite3DbFree(db, pVTab);
  121224. }
  121225. }
  121226. /*
  121227. ** Table p is a virtual table. This function moves all elements in the
  121228. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  121229. ** database connections to be disconnected at the next opportunity.
  121230. ** Except, if argument db is not NULL, then the entry associated with
  121231. ** connection db is left in the p->pVTable list.
  121232. */
  121233. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  121234. VTable *pRet = 0;
  121235. VTable *pVTable = p->pVTable;
  121236. p->pVTable = 0;
  121237. /* Assert that the mutex (if any) associated with the BtShared database
  121238. ** that contains table p is held by the caller. See header comments
  121239. ** above function sqlite3VtabUnlockList() for an explanation of why
  121240. ** this makes it safe to access the sqlite3.pDisconnect list of any
  121241. ** database connection that may have an entry in the p->pVTable list.
  121242. */
  121243. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  121244. while( pVTable ){
  121245. sqlite3 *db2 = pVTable->db;
  121246. VTable *pNext = pVTable->pNext;
  121247. assert( db2 );
  121248. if( db2==db ){
  121249. pRet = pVTable;
  121250. p->pVTable = pRet;
  121251. pRet->pNext = 0;
  121252. }else{
  121253. pVTable->pNext = db2->pDisconnect;
  121254. db2->pDisconnect = pVTable;
  121255. }
  121256. pVTable = pNext;
  121257. }
  121258. assert( !db || pRet );
  121259. return pRet;
  121260. }
  121261. /*
  121262. ** Table *p is a virtual table. This function removes the VTable object
  121263. ** for table *p associated with database connection db from the linked
  121264. ** list in p->pVTab. It also decrements the VTable ref count. This is
  121265. ** used when closing database connection db to free all of its VTable
  121266. ** objects without disturbing the rest of the Schema object (which may
  121267. ** be being used by other shared-cache connections).
  121268. */
  121269. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  121270. VTable **ppVTab;
  121271. assert( IsVirtual(p) );
  121272. assert( sqlite3BtreeHoldsAllMutexes(db) );
  121273. assert( sqlite3_mutex_held(db->mutex) );
  121274. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  121275. if( (*ppVTab)->db==db ){
  121276. VTable *pVTab = *ppVTab;
  121277. *ppVTab = pVTab->pNext;
  121278. sqlite3VtabUnlock(pVTab);
  121279. break;
  121280. }
  121281. }
  121282. }
  121283. /*
  121284. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  121285. **
  121286. ** This function may only be called when the mutexes associated with all
  121287. ** shared b-tree databases opened using connection db are held by the
  121288. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  121289. ** sqlite3.pDisconnect list is accessed only as follows:
  121290. **
  121291. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  121292. ** associated with the database handle itself must be held.
  121293. **
  121294. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  121295. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  121296. ** associated with the database the virtual table is stored in is held
  121297. ** or, if the virtual table is stored in a non-sharable database, then
  121298. ** the database handle mutex is held.
  121299. **
  121300. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  121301. ** by multiple threads. It is thread-safe.
  121302. */
  121303. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  121304. VTable *p = db->pDisconnect;
  121305. db->pDisconnect = 0;
  121306. assert( sqlite3BtreeHoldsAllMutexes(db) );
  121307. assert( sqlite3_mutex_held(db->mutex) );
  121308. if( p ){
  121309. sqlite3ExpirePreparedStatements(db);
  121310. do {
  121311. VTable *pNext = p->pNext;
  121312. sqlite3VtabUnlock(p);
  121313. p = pNext;
  121314. }while( p );
  121315. }
  121316. }
  121317. /*
  121318. ** Clear any and all virtual-table information from the Table record.
  121319. ** This routine is called, for example, just before deleting the Table
  121320. ** record.
  121321. **
  121322. ** Since it is a virtual-table, the Table structure contains a pointer
  121323. ** to the head of a linked list of VTable structures. Each VTable
  121324. ** structure is associated with a single sqlite3* user of the schema.
  121325. ** The reference count of the VTable structure associated with database
  121326. ** connection db is decremented immediately (which may lead to the
  121327. ** structure being xDisconnected and free). Any other VTable structures
  121328. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  121329. ** database connection.
  121330. */
  121331. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  121332. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  121333. if( p->azModuleArg ){
  121334. int i;
  121335. for(i=0; i<p->nModuleArg; i++){
  121336. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  121337. }
  121338. sqlite3DbFree(db, p->azModuleArg);
  121339. }
  121340. }
  121341. /*
  121342. ** Add a new module argument to pTable->azModuleArg[].
  121343. ** The string is not copied - the pointer is stored. The
  121344. ** string will be freed automatically when the table is
  121345. ** deleted.
  121346. */
  121347. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  121348. int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  121349. char **azModuleArg;
  121350. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  121351. if( azModuleArg==0 ){
  121352. sqlite3DbFree(db, zArg);
  121353. }else{
  121354. int i = pTable->nModuleArg++;
  121355. azModuleArg[i] = zArg;
  121356. azModuleArg[i+1] = 0;
  121357. pTable->azModuleArg = azModuleArg;
  121358. }
  121359. }
  121360. /*
  121361. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  121362. ** statement. The module name has been parsed, but the optional list
  121363. ** of parameters that follow the module name are still pending.
  121364. */
  121365. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  121366. Parse *pParse, /* Parsing context */
  121367. Token *pName1, /* Name of new table, or database name */
  121368. Token *pName2, /* Name of new table or NULL */
  121369. Token *pModuleName, /* Name of the module for the virtual table */
  121370. int ifNotExists /* No error if the table already exists */
  121371. ){
  121372. int iDb; /* The database the table is being created in */
  121373. Table *pTable; /* The new virtual table */
  121374. sqlite3 *db; /* Database connection */
  121375. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  121376. pTable = pParse->pNewTable;
  121377. if( pTable==0 ) return;
  121378. assert( 0==pTable->pIndex );
  121379. db = pParse->db;
  121380. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  121381. assert( iDb>=0 );
  121382. assert( pTable->nModuleArg==0 );
  121383. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  121384. addModuleArgument(db, pTable, 0);
  121385. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  121386. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  121387. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  121388. );
  121389. pParse->sNameToken.n = (int)(
  121390. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  121391. );
  121392. #ifndef SQLITE_OMIT_AUTHORIZATION
  121393. /* Creating a virtual table invokes the authorization callback twice.
  121394. ** The first invocation, to obtain permission to INSERT a row into the
  121395. ** sqlite_master table, has already been made by sqlite3StartTable().
  121396. ** The second call, to obtain permission to create the table, is made now.
  121397. */
  121398. if( pTable->azModuleArg ){
  121399. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  121400. pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
  121401. }
  121402. #endif
  121403. }
  121404. /*
  121405. ** This routine takes the module argument that has been accumulating
  121406. ** in pParse->zArg[] and appends it to the list of arguments on the
  121407. ** virtual table currently under construction in pParse->pTable.
  121408. */
  121409. static void addArgumentToVtab(Parse *pParse){
  121410. if( pParse->sArg.z && pParse->pNewTable ){
  121411. const char *z = (const char*)pParse->sArg.z;
  121412. int n = pParse->sArg.n;
  121413. sqlite3 *db = pParse->db;
  121414. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  121415. }
  121416. }
  121417. /*
  121418. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  121419. ** has been completely parsed.
  121420. */
  121421. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  121422. Table *pTab = pParse->pNewTable; /* The table being constructed */
  121423. sqlite3 *db = pParse->db; /* The database connection */
  121424. if( pTab==0 ) return;
  121425. addArgumentToVtab(pParse);
  121426. pParse->sArg.z = 0;
  121427. if( pTab->nModuleArg<1 ) return;
  121428. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  121429. ** first time (in other words if the virtual table is actually being
  121430. ** created now instead of just being read out of sqlite_master) then
  121431. ** do additional initialization work and store the statement text
  121432. ** in the sqlite_master table.
  121433. */
  121434. if( !db->init.busy ){
  121435. char *zStmt;
  121436. char *zWhere;
  121437. int iDb;
  121438. int iReg;
  121439. Vdbe *v;
  121440. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  121441. if( pEnd ){
  121442. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  121443. }
  121444. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  121445. /* A slot for the record has already been allocated in the
  121446. ** SQLITE_MASTER table. We just need to update that slot with all
  121447. ** the information we've collected.
  121448. **
  121449. ** The VM register number pParse->regRowid holds the rowid of an
  121450. ** entry in the sqlite_master table tht was created for this vtab
  121451. ** by sqlite3StartTable().
  121452. */
  121453. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  121454. sqlite3NestedParse(pParse,
  121455. "UPDATE %Q.%s "
  121456. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  121457. "WHERE rowid=#%d",
  121458. db->aDb[iDb].zDbSName, MASTER_NAME,
  121459. pTab->zName,
  121460. pTab->zName,
  121461. zStmt,
  121462. pParse->regRowid
  121463. );
  121464. sqlite3DbFree(db, zStmt);
  121465. v = sqlite3GetVdbe(pParse);
  121466. sqlite3ChangeCookie(pParse, iDb);
  121467. sqlite3VdbeAddOp0(v, OP_Expire);
  121468. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  121469. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  121470. iReg = ++pParse->nMem;
  121471. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  121472. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  121473. }
  121474. /* If we are rereading the sqlite_master table create the in-memory
  121475. ** record of the table. The xConnect() method is not called until
  121476. ** the first time the virtual table is used in an SQL statement. This
  121477. ** allows a schema that contains virtual tables to be loaded before
  121478. ** the required virtual table implementations are registered. */
  121479. else {
  121480. Table *pOld;
  121481. Schema *pSchema = pTab->pSchema;
  121482. const char *zName = pTab->zName;
  121483. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  121484. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  121485. if( pOld ){
  121486. sqlite3OomFault(db);
  121487. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  121488. return;
  121489. }
  121490. pParse->pNewTable = 0;
  121491. }
  121492. }
  121493. /*
  121494. ** The parser calls this routine when it sees the first token
  121495. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  121496. */
  121497. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  121498. addArgumentToVtab(pParse);
  121499. pParse->sArg.z = 0;
  121500. pParse->sArg.n = 0;
  121501. }
  121502. /*
  121503. ** The parser calls this routine for each token after the first token
  121504. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  121505. */
  121506. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  121507. Token *pArg = &pParse->sArg;
  121508. if( pArg->z==0 ){
  121509. pArg->z = p->z;
  121510. pArg->n = p->n;
  121511. }else{
  121512. assert(pArg->z <= p->z);
  121513. pArg->n = (int)(&p->z[p->n] - pArg->z);
  121514. }
  121515. }
  121516. /*
  121517. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  121518. ** pointer to the function to invoke is passed as the fourth parameter
  121519. ** to this procedure.
  121520. */
  121521. static int vtabCallConstructor(
  121522. sqlite3 *db,
  121523. Table *pTab,
  121524. Module *pMod,
  121525. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  121526. char **pzErr
  121527. ){
  121528. VtabCtx sCtx;
  121529. VTable *pVTable;
  121530. int rc;
  121531. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  121532. int nArg = pTab->nModuleArg;
  121533. char *zErr = 0;
  121534. char *zModuleName;
  121535. int iDb;
  121536. VtabCtx *pCtx;
  121537. /* Check that the virtual-table is not already being initialized */
  121538. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  121539. if( pCtx->pTab==pTab ){
  121540. *pzErr = sqlite3MPrintf(db,
  121541. "vtable constructor called recursively: %s", pTab->zName
  121542. );
  121543. return SQLITE_LOCKED;
  121544. }
  121545. }
  121546. zModuleName = sqlite3DbStrDup(db, pTab->zName);
  121547. if( !zModuleName ){
  121548. return SQLITE_NOMEM_BKPT;
  121549. }
  121550. pVTable = sqlite3MallocZero(sizeof(VTable));
  121551. if( !pVTable ){
  121552. sqlite3OomFault(db);
  121553. sqlite3DbFree(db, zModuleName);
  121554. return SQLITE_NOMEM_BKPT;
  121555. }
  121556. pVTable->db = db;
  121557. pVTable->pMod = pMod;
  121558. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  121559. pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
  121560. /* Invoke the virtual table constructor */
  121561. assert( &db->pVtabCtx );
  121562. assert( xConstruct );
  121563. sCtx.pTab = pTab;
  121564. sCtx.pVTable = pVTable;
  121565. sCtx.pPrior = db->pVtabCtx;
  121566. sCtx.bDeclared = 0;
  121567. db->pVtabCtx = &sCtx;
  121568. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  121569. db->pVtabCtx = sCtx.pPrior;
  121570. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  121571. assert( sCtx.pTab==pTab );
  121572. if( SQLITE_OK!=rc ){
  121573. if( zErr==0 ){
  121574. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  121575. }else {
  121576. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  121577. sqlite3_free(zErr);
  121578. }
  121579. sqlite3DbFree(db, pVTable);
  121580. }else if( ALWAYS(pVTable->pVtab) ){
  121581. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  121582. ** the sqlite3_vtab object if successful. */
  121583. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  121584. pVTable->pVtab->pModule = pMod->pModule;
  121585. pVTable->nRef = 1;
  121586. if( sCtx.bDeclared==0 ){
  121587. const char *zFormat = "vtable constructor did not declare schema: %s";
  121588. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  121589. sqlite3VtabUnlock(pVTable);
  121590. rc = SQLITE_ERROR;
  121591. }else{
  121592. int iCol;
  121593. u8 oooHidden = 0;
  121594. /* If everything went according to plan, link the new VTable structure
  121595. ** into the linked list headed by pTab->pVTable. Then loop through the
  121596. ** columns of the table to see if any of them contain the token "hidden".
  121597. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  121598. ** the type string. */
  121599. pVTable->pNext = pTab->pVTable;
  121600. pTab->pVTable = pVTable;
  121601. for(iCol=0; iCol<pTab->nCol; iCol++){
  121602. char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
  121603. int nType;
  121604. int i = 0;
  121605. nType = sqlite3Strlen30(zType);
  121606. for(i=0; i<nType; i++){
  121607. if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
  121608. && (i==0 || zType[i-1]==' ')
  121609. && (zType[i+6]=='\0' || zType[i+6]==' ')
  121610. ){
  121611. break;
  121612. }
  121613. }
  121614. if( i<nType ){
  121615. int j;
  121616. int nDel = 6 + (zType[i+6] ? 1 : 0);
  121617. for(j=i; (j+nDel)<=nType; j++){
  121618. zType[j] = zType[j+nDel];
  121619. }
  121620. if( zType[i]=='\0' && i>0 ){
  121621. assert(zType[i-1]==' ');
  121622. zType[i-1] = '\0';
  121623. }
  121624. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  121625. oooHidden = TF_OOOHidden;
  121626. }else{
  121627. pTab->tabFlags |= oooHidden;
  121628. }
  121629. }
  121630. }
  121631. }
  121632. sqlite3DbFree(db, zModuleName);
  121633. return rc;
  121634. }
  121635. /*
  121636. ** This function is invoked by the parser to call the xConnect() method
  121637. ** of the virtual table pTab. If an error occurs, an error code is returned
  121638. ** and an error left in pParse.
  121639. **
  121640. ** This call is a no-op if table pTab is not a virtual table.
  121641. */
  121642. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  121643. sqlite3 *db = pParse->db;
  121644. const char *zMod;
  121645. Module *pMod;
  121646. int rc;
  121647. assert( pTab );
  121648. if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
  121649. return SQLITE_OK;
  121650. }
  121651. /* Locate the required virtual table module */
  121652. zMod = pTab->azModuleArg[0];
  121653. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  121654. if( !pMod ){
  121655. const char *zModule = pTab->azModuleArg[0];
  121656. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  121657. rc = SQLITE_ERROR;
  121658. }else{
  121659. char *zErr = 0;
  121660. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  121661. if( rc!=SQLITE_OK ){
  121662. sqlite3ErrorMsg(pParse, "%s", zErr);
  121663. pParse->rc = rc;
  121664. }
  121665. sqlite3DbFree(db, zErr);
  121666. }
  121667. return rc;
  121668. }
  121669. /*
  121670. ** Grow the db->aVTrans[] array so that there is room for at least one
  121671. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  121672. */
  121673. static int growVTrans(sqlite3 *db){
  121674. const int ARRAY_INCR = 5;
  121675. /* Grow the sqlite3.aVTrans array if required */
  121676. if( (db->nVTrans%ARRAY_INCR)==0 ){
  121677. VTable **aVTrans;
  121678. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  121679. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  121680. if( !aVTrans ){
  121681. return SQLITE_NOMEM_BKPT;
  121682. }
  121683. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  121684. db->aVTrans = aVTrans;
  121685. }
  121686. return SQLITE_OK;
  121687. }
  121688. /*
  121689. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  121690. ** have already been reserved using growVTrans().
  121691. */
  121692. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  121693. /* Add pVtab to the end of sqlite3.aVTrans */
  121694. db->aVTrans[db->nVTrans++] = pVTab;
  121695. sqlite3VtabLock(pVTab);
  121696. }
  121697. /*
  121698. ** This function is invoked by the vdbe to call the xCreate method
  121699. ** of the virtual table named zTab in database iDb.
  121700. **
  121701. ** If an error occurs, *pzErr is set to point to an English language
  121702. ** description of the error and an SQLITE_XXX error code is returned.
  121703. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  121704. */
  121705. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  121706. int rc = SQLITE_OK;
  121707. Table *pTab;
  121708. Module *pMod;
  121709. const char *zMod;
  121710. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  121711. assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
  121712. /* Locate the required virtual table module */
  121713. zMod = pTab->azModuleArg[0];
  121714. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  121715. /* If the module has been registered and includes a Create method,
  121716. ** invoke it now. If the module has not been registered, return an
  121717. ** error. Otherwise, do nothing.
  121718. */
  121719. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  121720. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  121721. rc = SQLITE_ERROR;
  121722. }else{
  121723. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  121724. }
  121725. /* Justification of ALWAYS(): The xConstructor method is required to
  121726. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  121727. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  121728. rc = growVTrans(db);
  121729. if( rc==SQLITE_OK ){
  121730. addToVTrans(db, sqlite3GetVTable(db, pTab));
  121731. }
  121732. }
  121733. return rc;
  121734. }
  121735. /*
  121736. ** This function is used to set the schema of a virtual table. It is only
  121737. ** valid to call this function from within the xCreate() or xConnect() of a
  121738. ** virtual table module.
  121739. */
  121740. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  121741. VtabCtx *pCtx;
  121742. int rc = SQLITE_OK;
  121743. Table *pTab;
  121744. char *zErr = 0;
  121745. Parse sParse;
  121746. #ifdef SQLITE_ENABLE_API_ARMOR
  121747. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  121748. return SQLITE_MISUSE_BKPT;
  121749. }
  121750. #endif
  121751. sqlite3_mutex_enter(db->mutex);
  121752. pCtx = db->pVtabCtx;
  121753. if( !pCtx || pCtx->bDeclared ){
  121754. sqlite3Error(db, SQLITE_MISUSE);
  121755. sqlite3_mutex_leave(db->mutex);
  121756. return SQLITE_MISUSE_BKPT;
  121757. }
  121758. pTab = pCtx->pTab;
  121759. assert( IsVirtual(pTab) );
  121760. memset(&sParse, 0, sizeof(sParse));
  121761. sParse.declareVtab = 1;
  121762. sParse.db = db;
  121763. sParse.nQueryLoop = 1;
  121764. if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
  121765. && sParse.pNewTable
  121766. && !db->mallocFailed
  121767. && !sParse.pNewTable->pSelect
  121768. && !IsVirtual(sParse.pNewTable)
  121769. ){
  121770. if( !pTab->aCol ){
  121771. Table *pNew = sParse.pNewTable;
  121772. Index *pIdx;
  121773. pTab->aCol = pNew->aCol;
  121774. pTab->nCol = pNew->nCol;
  121775. pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
  121776. pNew->nCol = 0;
  121777. pNew->aCol = 0;
  121778. assert( pTab->pIndex==0 );
  121779. assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
  121780. if( !HasRowid(pNew)
  121781. && pCtx->pVTable->pMod->pModule->xUpdate!=0
  121782. && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
  121783. ){
  121784. /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
  121785. ** or else must have a single-column PRIMARY KEY */
  121786. rc = SQLITE_ERROR;
  121787. }
  121788. pIdx = pNew->pIndex;
  121789. if( pIdx ){
  121790. assert( pIdx->pNext==0 );
  121791. pTab->pIndex = pIdx;
  121792. pNew->pIndex = 0;
  121793. pIdx->pTable = pTab;
  121794. }
  121795. }
  121796. pCtx->bDeclared = 1;
  121797. }else{
  121798. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  121799. sqlite3DbFree(db, zErr);
  121800. rc = SQLITE_ERROR;
  121801. }
  121802. sParse.declareVtab = 0;
  121803. if( sParse.pVdbe ){
  121804. sqlite3VdbeFinalize(sParse.pVdbe);
  121805. }
  121806. sqlite3DeleteTable(db, sParse.pNewTable);
  121807. sqlite3ParserReset(&sParse);
  121808. assert( (rc&0xff)==rc );
  121809. rc = sqlite3ApiExit(db, rc);
  121810. sqlite3_mutex_leave(db->mutex);
  121811. return rc;
  121812. }
  121813. /*
  121814. ** This function is invoked by the vdbe to call the xDestroy method
  121815. ** of the virtual table named zTab in database iDb. This occurs
  121816. ** when a DROP TABLE is mentioned.
  121817. **
  121818. ** This call is a no-op if zTab is not a virtual table.
  121819. */
  121820. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  121821. int rc = SQLITE_OK;
  121822. Table *pTab;
  121823. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  121824. if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
  121825. VTable *p;
  121826. int (*xDestroy)(sqlite3_vtab *);
  121827. for(p=pTab->pVTable; p; p=p->pNext){
  121828. assert( p->pVtab );
  121829. if( p->pVtab->nRef>0 ){
  121830. return SQLITE_LOCKED;
  121831. }
  121832. }
  121833. p = vtabDisconnectAll(db, pTab);
  121834. xDestroy = p->pMod->pModule->xDestroy;
  121835. assert( xDestroy!=0 ); /* Checked before the virtual table is created */
  121836. rc = xDestroy(p->pVtab);
  121837. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  121838. if( rc==SQLITE_OK ){
  121839. assert( pTab->pVTable==p && p->pNext==0 );
  121840. p->pVtab = 0;
  121841. pTab->pVTable = 0;
  121842. sqlite3VtabUnlock(p);
  121843. }
  121844. }
  121845. return rc;
  121846. }
  121847. /*
  121848. ** This function invokes either the xRollback or xCommit method
  121849. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  121850. ** called is identified by the second argument, "offset", which is
  121851. ** the offset of the method to call in the sqlite3_module structure.
  121852. **
  121853. ** The array is cleared after invoking the callbacks.
  121854. */
  121855. static void callFinaliser(sqlite3 *db, int offset){
  121856. int i;
  121857. if( db->aVTrans ){
  121858. VTable **aVTrans = db->aVTrans;
  121859. db->aVTrans = 0;
  121860. for(i=0; i<db->nVTrans; i++){
  121861. VTable *pVTab = aVTrans[i];
  121862. sqlite3_vtab *p = pVTab->pVtab;
  121863. if( p ){
  121864. int (*x)(sqlite3_vtab *);
  121865. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  121866. if( x ) x(p);
  121867. }
  121868. pVTab->iSavepoint = 0;
  121869. sqlite3VtabUnlock(pVTab);
  121870. }
  121871. sqlite3DbFree(db, aVTrans);
  121872. db->nVTrans = 0;
  121873. }
  121874. }
  121875. /*
  121876. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  121877. ** array. Return the error code for the first error that occurs, or
  121878. ** SQLITE_OK if all xSync operations are successful.
  121879. **
  121880. ** If an error message is available, leave it in p->zErrMsg.
  121881. */
  121882. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  121883. int i;
  121884. int rc = SQLITE_OK;
  121885. VTable **aVTrans = db->aVTrans;
  121886. db->aVTrans = 0;
  121887. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  121888. int (*x)(sqlite3_vtab *);
  121889. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  121890. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  121891. rc = x(pVtab);
  121892. sqlite3VtabImportErrmsg(p, pVtab);
  121893. }
  121894. }
  121895. db->aVTrans = aVTrans;
  121896. return rc;
  121897. }
  121898. /*
  121899. ** Invoke the xRollback method of all virtual tables in the
  121900. ** sqlite3.aVTrans array. Then clear the array itself.
  121901. */
  121902. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  121903. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  121904. return SQLITE_OK;
  121905. }
  121906. /*
  121907. ** Invoke the xCommit method of all virtual tables in the
  121908. ** sqlite3.aVTrans array. Then clear the array itself.
  121909. */
  121910. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  121911. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  121912. return SQLITE_OK;
  121913. }
  121914. /*
  121915. ** If the virtual table pVtab supports the transaction interface
  121916. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  121917. ** not currently open, invoke the xBegin method now.
  121918. **
  121919. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  121920. ** in the sqlite3.aVTrans array.
  121921. */
  121922. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  121923. int rc = SQLITE_OK;
  121924. const sqlite3_module *pModule;
  121925. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  121926. ** than zero, then this function is being called from within a
  121927. ** virtual module xSync() callback. It is illegal to write to
  121928. ** virtual module tables in this case, so return SQLITE_LOCKED.
  121929. */
  121930. if( sqlite3VtabInSync(db) ){
  121931. return SQLITE_LOCKED;
  121932. }
  121933. if( !pVTab ){
  121934. return SQLITE_OK;
  121935. }
  121936. pModule = pVTab->pVtab->pModule;
  121937. if( pModule->xBegin ){
  121938. int i;
  121939. /* If pVtab is already in the aVTrans array, return early */
  121940. for(i=0; i<db->nVTrans; i++){
  121941. if( db->aVTrans[i]==pVTab ){
  121942. return SQLITE_OK;
  121943. }
  121944. }
  121945. /* Invoke the xBegin method. If successful, add the vtab to the
  121946. ** sqlite3.aVTrans[] array. */
  121947. rc = growVTrans(db);
  121948. if( rc==SQLITE_OK ){
  121949. rc = pModule->xBegin(pVTab->pVtab);
  121950. if( rc==SQLITE_OK ){
  121951. int iSvpt = db->nStatement + db->nSavepoint;
  121952. addToVTrans(db, pVTab);
  121953. if( iSvpt && pModule->xSavepoint ){
  121954. pVTab->iSavepoint = iSvpt;
  121955. rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
  121956. }
  121957. }
  121958. }
  121959. }
  121960. return rc;
  121961. }
  121962. /*
  121963. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  121964. ** virtual tables that currently have an open transaction. Pass iSavepoint
  121965. ** as the second argument to the virtual table method invoked.
  121966. **
  121967. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  121968. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  121969. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  121970. ** an open transaction is invoked.
  121971. **
  121972. ** If any virtual table method returns an error code other than SQLITE_OK,
  121973. ** processing is abandoned and the error returned to the caller of this
  121974. ** function immediately. If all calls to virtual table methods are successful,
  121975. ** SQLITE_OK is returned.
  121976. */
  121977. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  121978. int rc = SQLITE_OK;
  121979. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  121980. assert( iSavepoint>=-1 );
  121981. if( db->aVTrans ){
  121982. int i;
  121983. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  121984. VTable *pVTab = db->aVTrans[i];
  121985. const sqlite3_module *pMod = pVTab->pMod->pModule;
  121986. if( pVTab->pVtab && pMod->iVersion>=2 ){
  121987. int (*xMethod)(sqlite3_vtab *, int);
  121988. switch( op ){
  121989. case SAVEPOINT_BEGIN:
  121990. xMethod = pMod->xSavepoint;
  121991. pVTab->iSavepoint = iSavepoint+1;
  121992. break;
  121993. case SAVEPOINT_ROLLBACK:
  121994. xMethod = pMod->xRollbackTo;
  121995. break;
  121996. default:
  121997. xMethod = pMod->xRelease;
  121998. break;
  121999. }
  122000. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  122001. rc = xMethod(pVTab->pVtab, iSavepoint);
  122002. }
  122003. }
  122004. }
  122005. }
  122006. return rc;
  122007. }
  122008. /*
  122009. ** The first parameter (pDef) is a function implementation. The
  122010. ** second parameter (pExpr) is the first argument to this function.
  122011. ** If pExpr is a column in a virtual table, then let the virtual
  122012. ** table implementation have an opportunity to overload the function.
  122013. **
  122014. ** This routine is used to allow virtual table implementations to
  122015. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  122016. **
  122017. ** Return either the pDef argument (indicating no change) or a
  122018. ** new FuncDef structure that is marked as ephemeral using the
  122019. ** SQLITE_FUNC_EPHEM flag.
  122020. */
  122021. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  122022. sqlite3 *db, /* Database connection for reporting malloc problems */
  122023. FuncDef *pDef, /* Function to possibly overload */
  122024. int nArg, /* Number of arguments to the function */
  122025. Expr *pExpr /* First argument to the function */
  122026. ){
  122027. Table *pTab;
  122028. sqlite3_vtab *pVtab;
  122029. sqlite3_module *pMod;
  122030. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  122031. void *pArg = 0;
  122032. FuncDef *pNew;
  122033. int rc = 0;
  122034. char *zLowerName;
  122035. unsigned char *z;
  122036. /* Check to see the left operand is a column in a virtual table */
  122037. if( NEVER(pExpr==0) ) return pDef;
  122038. if( pExpr->op!=TK_COLUMN ) return pDef;
  122039. pTab = pExpr->pTab;
  122040. if( pTab==0 ) return pDef;
  122041. if( !IsVirtual(pTab) ) return pDef;
  122042. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  122043. assert( pVtab!=0 );
  122044. assert( pVtab->pModule!=0 );
  122045. pMod = (sqlite3_module *)pVtab->pModule;
  122046. if( pMod->xFindFunction==0 ) return pDef;
  122047. /* Call the xFindFunction method on the virtual table implementation
  122048. ** to see if the implementation wants to overload this function
  122049. */
  122050. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  122051. if( zLowerName ){
  122052. for(z=(unsigned char*)zLowerName; *z; z++){
  122053. *z = sqlite3UpperToLower[*z];
  122054. }
  122055. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
  122056. sqlite3DbFree(db, zLowerName);
  122057. }
  122058. if( rc==0 ){
  122059. return pDef;
  122060. }
  122061. /* Create a new ephemeral function definition for the overloaded
  122062. ** function */
  122063. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  122064. + sqlite3Strlen30(pDef->zName) + 1);
  122065. if( pNew==0 ){
  122066. return pDef;
  122067. }
  122068. *pNew = *pDef;
  122069. pNew->zName = (const char*)&pNew[1];
  122070. memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  122071. pNew->xSFunc = xSFunc;
  122072. pNew->pUserData = pArg;
  122073. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  122074. return pNew;
  122075. }
  122076. /*
  122077. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  122078. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  122079. ** array if it is missing. If pTab is already in the array, this routine
  122080. ** is a no-op.
  122081. */
  122082. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  122083. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  122084. int i, n;
  122085. Table **apVtabLock;
  122086. assert( IsVirtual(pTab) );
  122087. for(i=0; i<pToplevel->nVtabLock; i++){
  122088. if( pTab==pToplevel->apVtabLock[i] ) return;
  122089. }
  122090. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  122091. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  122092. if( apVtabLock ){
  122093. pToplevel->apVtabLock = apVtabLock;
  122094. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  122095. }else{
  122096. sqlite3OomFault(pToplevel->db);
  122097. }
  122098. }
  122099. /*
  122100. ** Check to see if virtual table module pMod can be have an eponymous
  122101. ** virtual table instance. If it can, create one if one does not already
  122102. ** exist. Return non-zero if the eponymous virtual table instance exists
  122103. ** when this routine returns, and return zero if it does not exist.
  122104. **
  122105. ** An eponymous virtual table instance is one that is named after its
  122106. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  122107. ** statement in order to come into existance. Eponymous virtual table
  122108. ** instances always exist. They cannot be DROP-ed.
  122109. **
  122110. ** Any virtual table module for which xConnect and xCreate are the same
  122111. ** method can have an eponymous virtual table instance.
  122112. */
  122113. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  122114. const sqlite3_module *pModule = pMod->pModule;
  122115. Table *pTab;
  122116. char *zErr = 0;
  122117. int rc;
  122118. sqlite3 *db = pParse->db;
  122119. if( pMod->pEpoTab ) return 1;
  122120. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  122121. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  122122. if( pTab==0 ) return 0;
  122123. pTab->zName = sqlite3DbStrDup(db, pMod->zName);
  122124. if( pTab->zName==0 ){
  122125. sqlite3DbFree(db, pTab);
  122126. return 0;
  122127. }
  122128. pMod->pEpoTab = pTab;
  122129. pTab->nTabRef = 1;
  122130. pTab->pSchema = db->aDb[0].pSchema;
  122131. assert( pTab->nModuleArg==0 );
  122132. pTab->iPKey = -1;
  122133. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  122134. addModuleArgument(db, pTab, 0);
  122135. addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
  122136. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  122137. if( rc ){
  122138. sqlite3ErrorMsg(pParse, "%s", zErr);
  122139. sqlite3DbFree(db, zErr);
  122140. sqlite3VtabEponymousTableClear(db, pMod);
  122141. return 0;
  122142. }
  122143. return 1;
  122144. }
  122145. /*
  122146. ** Erase the eponymous virtual table instance associated with
  122147. ** virtual table module pMod, if it exists.
  122148. */
  122149. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  122150. Table *pTab = pMod->pEpoTab;
  122151. if( pTab!=0 ){
  122152. /* Mark the table as Ephemeral prior to deleting it, so that the
  122153. ** sqlite3DeleteTable() routine will know that it is not stored in
  122154. ** the schema. */
  122155. pTab->tabFlags |= TF_Ephemeral;
  122156. sqlite3DeleteTable(db, pTab);
  122157. pMod->pEpoTab = 0;
  122158. }
  122159. }
  122160. /*
  122161. ** Return the ON CONFLICT resolution mode in effect for the virtual
  122162. ** table update operation currently in progress.
  122163. **
  122164. ** The results of this routine are undefined unless it is called from
  122165. ** within an xUpdate method.
  122166. */
  122167. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  122168. static const unsigned char aMap[] = {
  122169. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  122170. };
  122171. #ifdef SQLITE_ENABLE_API_ARMOR
  122172. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  122173. #endif
  122174. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  122175. assert( OE_Ignore==4 && OE_Replace==5 );
  122176. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  122177. return (int)aMap[db->vtabOnConflict-1];
  122178. }
  122179. /*
  122180. ** Call from within the xCreate() or xConnect() methods to provide
  122181. ** the SQLite core with additional information about the behavior
  122182. ** of the virtual table being implemented.
  122183. */
  122184. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  122185. va_list ap;
  122186. int rc = SQLITE_OK;
  122187. #ifdef SQLITE_ENABLE_API_ARMOR
  122188. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  122189. #endif
  122190. sqlite3_mutex_enter(db->mutex);
  122191. va_start(ap, op);
  122192. switch( op ){
  122193. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  122194. VtabCtx *p = db->pVtabCtx;
  122195. if( !p ){
  122196. rc = SQLITE_MISUSE_BKPT;
  122197. }else{
  122198. assert( p->pTab==0 || IsVirtual(p->pTab) );
  122199. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  122200. }
  122201. break;
  122202. }
  122203. default:
  122204. rc = SQLITE_MISUSE_BKPT;
  122205. break;
  122206. }
  122207. va_end(ap);
  122208. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  122209. sqlite3_mutex_leave(db->mutex);
  122210. return rc;
  122211. }
  122212. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  122213. /************** End of vtab.c ************************************************/
  122214. /************** Begin file wherecode.c ***************************************/
  122215. /*
  122216. ** 2015-06-06
  122217. **
  122218. ** The author disclaims copyright to this source code. In place of
  122219. ** a legal notice, here is a blessing:
  122220. **
  122221. ** May you do good and not evil.
  122222. ** May you find forgiveness for yourself and forgive others.
  122223. ** May you share freely, never taking more than you give.
  122224. **
  122225. *************************************************************************
  122226. ** This module contains C code that generates VDBE code used to process
  122227. ** the WHERE clause of SQL statements.
  122228. **
  122229. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  122230. ** size of where.c and make it easier to edit. This file contains the routines
  122231. ** that actually generate the bulk of the WHERE loop code. The original where.c
  122232. ** file retains the code that does query planning and analysis.
  122233. */
  122234. /* #include "sqliteInt.h" */
  122235. /************** Include whereInt.h in the middle of wherecode.c **************/
  122236. /************** Begin file whereInt.h ****************************************/
  122237. /*
  122238. ** 2013-11-12
  122239. **
  122240. ** The author disclaims copyright to this source code. In place of
  122241. ** a legal notice, here is a blessing:
  122242. **
  122243. ** May you do good and not evil.
  122244. ** May you find forgiveness for yourself and forgive others.
  122245. ** May you share freely, never taking more than you give.
  122246. **
  122247. *************************************************************************
  122248. **
  122249. ** This file contains structure and macro definitions for the query
  122250. ** planner logic in "where.c". These definitions are broken out into
  122251. ** a separate source file for easier editing.
  122252. */
  122253. /*
  122254. ** Trace output macros
  122255. */
  122256. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  122257. /***/ extern int sqlite3WhereTrace;
  122258. #endif
  122259. #if defined(SQLITE_DEBUG) \
  122260. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  122261. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  122262. # define WHERETRACE_ENABLED 1
  122263. #else
  122264. # define WHERETRACE(K,X)
  122265. #endif
  122266. /* Forward references
  122267. */
  122268. typedef struct WhereClause WhereClause;
  122269. typedef struct WhereMaskSet WhereMaskSet;
  122270. typedef struct WhereOrInfo WhereOrInfo;
  122271. typedef struct WhereAndInfo WhereAndInfo;
  122272. typedef struct WhereLevel WhereLevel;
  122273. typedef struct WhereLoop WhereLoop;
  122274. typedef struct WherePath WherePath;
  122275. typedef struct WhereTerm WhereTerm;
  122276. typedef struct WhereLoopBuilder WhereLoopBuilder;
  122277. typedef struct WhereScan WhereScan;
  122278. typedef struct WhereOrCost WhereOrCost;
  122279. typedef struct WhereOrSet WhereOrSet;
  122280. /*
  122281. ** This object contains information needed to implement a single nested
  122282. ** loop in WHERE clause.
  122283. **
  122284. ** Contrast this object with WhereLoop. This object describes the
  122285. ** implementation of the loop. WhereLoop describes the algorithm.
  122286. ** This object contains a pointer to the WhereLoop algorithm as one of
  122287. ** its elements.
  122288. **
  122289. ** The WhereInfo object contains a single instance of this object for
  122290. ** each term in the FROM clause (which is to say, for each of the
  122291. ** nested loops as implemented). The order of WhereLevel objects determines
  122292. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  122293. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  122294. */
  122295. struct WhereLevel {
  122296. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  122297. int iTabCur; /* The VDBE cursor used to access the table */
  122298. int iIdxCur; /* The VDBE cursor used to access pIdx */
  122299. int addrBrk; /* Jump here to break out of the loop */
  122300. int addrNxt; /* Jump here to start the next IN combination */
  122301. int addrSkip; /* Jump here for next iteration of skip-scan */
  122302. int addrCont; /* Jump here to continue with the next loop cycle */
  122303. int addrFirst; /* First instruction of interior of the loop */
  122304. int addrBody; /* Beginning of the body of this loop */
  122305. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  122306. u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
  122307. int addrLikeRep; /* LIKE range processing address */
  122308. #endif
  122309. u8 iFrom; /* Which entry in the FROM clause */
  122310. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  122311. int p1, p2; /* Operands of the opcode used to ends the loop */
  122312. union { /* Information that depends on pWLoop->wsFlags */
  122313. struct {
  122314. int nIn; /* Number of entries in aInLoop[] */
  122315. struct InLoop {
  122316. int iCur; /* The VDBE cursor used by this IN operator */
  122317. int addrInTop; /* Top of the IN loop */
  122318. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  122319. } *aInLoop; /* Information about each nested IN operator */
  122320. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  122321. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  122322. } u;
  122323. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  122324. Bitmask notReady; /* FROM entries not usable at this level */
  122325. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  122326. int addrVisit; /* Address at which row is visited */
  122327. #endif
  122328. };
  122329. /*
  122330. ** Each instance of this object represents an algorithm for evaluating one
  122331. ** term of a join. Every term of the FROM clause will have at least
  122332. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  122333. ** prevent a query solution - which is an error) and many terms of the
  122334. ** FROM clause will have multiple WhereLoop objects, each describing a
  122335. ** potential way of implementing that FROM-clause term, together with
  122336. ** dependencies and cost estimates for using the chosen algorithm.
  122337. **
  122338. ** Query planning consists of building up a collection of these WhereLoop
  122339. ** objects, then computing a particular sequence of WhereLoop objects, with
  122340. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  122341. ** and that minimize the overall cost.
  122342. */
  122343. struct WhereLoop {
  122344. Bitmask prereq; /* Bitmask of other loops that must run first */
  122345. Bitmask maskSelf; /* Bitmask identifying table iTab */
  122346. #ifdef SQLITE_DEBUG
  122347. char cId; /* Symbolic ID of this loop for debugging use */
  122348. #endif
  122349. u8 iTab; /* Position in FROM clause of table for this loop */
  122350. u8 iSortIdx; /* Sorting index number. 0==None */
  122351. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  122352. LogEst rRun; /* Cost of running each loop */
  122353. LogEst nOut; /* Estimated number of output rows */
  122354. union {
  122355. struct { /* Information for internal btree tables */
  122356. u16 nEq; /* Number of equality constraints */
  122357. u16 nBtm; /* Size of BTM vector */
  122358. u16 nTop; /* Size of TOP vector */
  122359. u16 nIdxCol; /* Index column used for ORDER BY */
  122360. Index *pIndex; /* Index used, or NULL */
  122361. } btree;
  122362. struct { /* Information for virtual tables */
  122363. int idxNum; /* Index number */
  122364. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  122365. i8 isOrdered; /* True if satisfies ORDER BY */
  122366. u16 omitMask; /* Terms that may be omitted */
  122367. char *idxStr; /* Index identifier string */
  122368. } vtab;
  122369. } u;
  122370. u32 wsFlags; /* WHERE_* flags describing the plan */
  122371. u16 nLTerm; /* Number of entries in aLTerm[] */
  122372. u16 nSkip; /* Number of NULL aLTerm[] entries */
  122373. /**** whereLoopXfer() copies fields above ***********************/
  122374. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  122375. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  122376. WhereTerm **aLTerm; /* WhereTerms used */
  122377. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  122378. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  122379. };
  122380. /* This object holds the prerequisites and the cost of running a
  122381. ** subquery on one operand of an OR operator in the WHERE clause.
  122382. ** See WhereOrSet for additional information
  122383. */
  122384. struct WhereOrCost {
  122385. Bitmask prereq; /* Prerequisites */
  122386. LogEst rRun; /* Cost of running this subquery */
  122387. LogEst nOut; /* Number of outputs for this subquery */
  122388. };
  122389. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  122390. ** correspond to the subquery(s) of OR-clause processing. Only the
  122391. ** best N_OR_COST elements are retained.
  122392. */
  122393. #define N_OR_COST 3
  122394. struct WhereOrSet {
  122395. u16 n; /* Number of valid a[] entries */
  122396. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  122397. };
  122398. /*
  122399. ** Each instance of this object holds a sequence of WhereLoop objects
  122400. ** that implement some or all of a query plan.
  122401. **
  122402. ** Think of each WhereLoop object as a node in a graph with arcs
  122403. ** showing dependencies and costs for travelling between nodes. (That is
  122404. ** not a completely accurate description because WhereLoop costs are a
  122405. ** vector, not a scalar, and because dependencies are many-to-one, not
  122406. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  122407. ** Then a WherePath object is a path through the graph that visits some
  122408. ** or all of the WhereLoop objects once.
  122409. **
  122410. ** The "solver" works by creating the N best WherePath objects of length
  122411. ** 1. Then using those as a basis to compute the N best WherePath objects
  122412. ** of length 2. And so forth until the length of WherePaths equals the
  122413. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  122414. ** at the end is the chosen query plan.
  122415. */
  122416. struct WherePath {
  122417. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  122418. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  122419. LogEst nRow; /* Estimated number of rows generated by this path */
  122420. LogEst rCost; /* Total cost of this path */
  122421. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  122422. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  122423. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  122424. };
  122425. /*
  122426. ** The query generator uses an array of instances of this structure to
  122427. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  122428. ** clause subexpression is separated from the others by AND operators,
  122429. ** usually, or sometimes subexpressions separated by OR.
  122430. **
  122431. ** All WhereTerms are collected into a single WhereClause structure.
  122432. ** The following identity holds:
  122433. **
  122434. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  122435. **
  122436. ** When a term is of the form:
  122437. **
  122438. ** X <op> <expr>
  122439. **
  122440. ** where X is a column name and <op> is one of certain operators,
  122441. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  122442. ** cursor number and column number for X. WhereTerm.eOperator records
  122443. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  122444. ** use of a bitmask encoding for the operator allows us to search
  122445. ** quickly for terms that match any of several different operators.
  122446. **
  122447. ** A WhereTerm might also be two or more subterms connected by OR:
  122448. **
  122449. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  122450. **
  122451. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  122452. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  122453. ** is collected about the OR clause.
  122454. **
  122455. ** If a term in the WHERE clause does not match either of the two previous
  122456. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  122457. ** to the original subexpression content and wtFlags is set up appropriately
  122458. ** but no other fields in the WhereTerm object are meaningful.
  122459. **
  122460. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  122461. ** but they do so indirectly. A single WhereMaskSet structure translates
  122462. ** cursor number into bits and the translated bit is stored in the prereq
  122463. ** fields. The translation is used in order to maximize the number of
  122464. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  122465. ** spread out over the non-negative integers. For example, the cursor
  122466. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  122467. ** translates these sparse cursor numbers into consecutive integers
  122468. ** beginning with 0 in order to make the best possible use of the available
  122469. ** bits in the Bitmask. So, in the example above, the cursor numbers
  122470. ** would be mapped into integers 0 through 7.
  122471. **
  122472. ** The number of terms in a join is limited by the number of bits
  122473. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  122474. ** is only able to process joins with 64 or fewer tables.
  122475. */
  122476. struct WhereTerm {
  122477. Expr *pExpr; /* Pointer to the subexpression that is this term */
  122478. WhereClause *pWC; /* The clause this term is part of */
  122479. LogEst truthProb; /* Probability of truth for this expression */
  122480. u16 wtFlags; /* TERM_xxx bit flags. See below */
  122481. u16 eOperator; /* A WO_xx value describing <op> */
  122482. u8 nChild; /* Number of children that must disable us */
  122483. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  122484. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  122485. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  122486. int iField; /* Field in (?,?,?) IN (SELECT...) vector */
  122487. union {
  122488. int leftColumn; /* Column number of X in "X <op> <expr>" */
  122489. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  122490. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  122491. } u;
  122492. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  122493. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  122494. };
  122495. /*
  122496. ** Allowed values of WhereTerm.wtFlags
  122497. */
  122498. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  122499. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  122500. #define TERM_CODED 0x04 /* This term is already coded */
  122501. #define TERM_COPIED 0x08 /* Has a child */
  122502. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  122503. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  122504. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  122505. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  122506. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  122507. #else
  122508. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  122509. #endif
  122510. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  122511. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  122512. #define TERM_LIKE 0x400 /* The original LIKE operator */
  122513. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  122514. #define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
  122515. /*
  122516. ** An instance of the WhereScan object is used as an iterator for locating
  122517. ** terms in the WHERE clause that are useful to the query planner.
  122518. */
  122519. struct WhereScan {
  122520. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  122521. WhereClause *pWC; /* WhereClause currently being scanned */
  122522. const char *zCollName; /* Required collating sequence, if not NULL */
  122523. Expr *pIdxExpr; /* Search for this index expression */
  122524. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  122525. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  122526. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  122527. u32 opMask; /* Acceptable operators */
  122528. int k; /* Resume scanning at this->pWC->a[this->k] */
  122529. int aiCur[11]; /* Cursors in the equivalence class */
  122530. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  122531. };
  122532. /*
  122533. ** An instance of the following structure holds all information about a
  122534. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  122535. **
  122536. ** Explanation of pOuter: For a WHERE clause of the form
  122537. **
  122538. ** a AND ((b AND c) OR (d AND e)) AND f
  122539. **
  122540. ** There are separate WhereClause objects for the whole clause and for
  122541. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  122542. ** subclauses points to the WhereClause object for the whole clause.
  122543. */
  122544. struct WhereClause {
  122545. WhereInfo *pWInfo; /* WHERE clause processing context */
  122546. WhereClause *pOuter; /* Outer conjunction */
  122547. u8 op; /* Split operator. TK_AND or TK_OR */
  122548. int nTerm; /* Number of terms */
  122549. int nSlot; /* Number of entries in a[] */
  122550. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  122551. #if defined(SQLITE_SMALL_STACK)
  122552. WhereTerm aStatic[1]; /* Initial static space for a[] */
  122553. #else
  122554. WhereTerm aStatic[8]; /* Initial static space for a[] */
  122555. #endif
  122556. };
  122557. /*
  122558. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  122559. ** a dynamically allocated instance of the following structure.
  122560. */
  122561. struct WhereOrInfo {
  122562. WhereClause wc; /* Decomposition into subterms */
  122563. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  122564. };
  122565. /*
  122566. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  122567. ** a dynamically allocated instance of the following structure.
  122568. */
  122569. struct WhereAndInfo {
  122570. WhereClause wc; /* The subexpression broken out */
  122571. };
  122572. /*
  122573. ** An instance of the following structure keeps track of a mapping
  122574. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  122575. **
  122576. ** The VDBE cursor numbers are small integers contained in
  122577. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  122578. ** clause, the cursor numbers might not begin with 0 and they might
  122579. ** contain gaps in the numbering sequence. But we want to make maximum
  122580. ** use of the bits in our bitmasks. This structure provides a mapping
  122581. ** from the sparse cursor numbers into consecutive integers beginning
  122582. ** with 0.
  122583. **
  122584. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  122585. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  122586. **
  122587. ** For example, if the WHERE clause expression used these VDBE
  122588. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  122589. ** would map those cursor numbers into bits 0 through 5.
  122590. **
  122591. ** Note that the mapping is not necessarily ordered. In the example
  122592. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  122593. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  122594. ** does not really matter. What is important is that sparse cursor
  122595. ** numbers all get mapped into bit numbers that begin with 0 and contain
  122596. ** no gaps.
  122597. */
  122598. struct WhereMaskSet {
  122599. int bVarSelect; /* Used by sqlite3WhereExprUsage() */
  122600. int n; /* Number of assigned cursor values */
  122601. int ix[BMS]; /* Cursor assigned to each bit */
  122602. };
  122603. /*
  122604. ** Initialize a WhereMaskSet object
  122605. */
  122606. #define initMaskSet(P) (P)->n=0
  122607. /*
  122608. ** This object is a convenience wrapper holding all information needed
  122609. ** to construct WhereLoop objects for a particular query.
  122610. */
  122611. struct WhereLoopBuilder {
  122612. WhereInfo *pWInfo; /* Information about this WHERE */
  122613. WhereClause *pWC; /* WHERE clause terms */
  122614. ExprList *pOrderBy; /* ORDER BY clause */
  122615. WhereLoop *pNew; /* Template WhereLoop */
  122616. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  122617. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  122618. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  122619. int nRecValid; /* Number of valid fields currently in pRec */
  122620. #endif
  122621. unsigned int bldFlags; /* SQLITE_BLDF_* flags */
  122622. };
  122623. /* Allowed values for WhereLoopBuider.bldFlags */
  122624. #define SQLITE_BLDF_INDEXED 0x0001 /* An index is used */
  122625. #define SQLITE_BLDF_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
  122626. /*
  122627. ** The WHERE clause processing routine has two halves. The
  122628. ** first part does the start of the WHERE loop and the second
  122629. ** half does the tail of the WHERE loop. An instance of
  122630. ** this structure is returned by the first half and passed
  122631. ** into the second half to give some continuity.
  122632. **
  122633. ** An instance of this object holds the complete state of the query
  122634. ** planner.
  122635. */
  122636. struct WhereInfo {
  122637. Parse *pParse; /* Parsing and code generating context */
  122638. SrcList *pTabList; /* List of tables in the join */
  122639. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  122640. ExprList *pResultSet; /* Result set of the query */
  122641. Expr *pWhere; /* The complete WHERE clause */
  122642. LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
  122643. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  122644. int iContinue; /* Jump here to continue with next record */
  122645. int iBreak; /* Jump here to break out of the loop */
  122646. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  122647. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  122648. u8 nLevel; /* Number of nested loop */
  122649. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  122650. u8 sorted; /* True if really sorted (not just grouped) */
  122651. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  122652. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  122653. u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
  122654. u8 bOrderedInnerLoop; /* True if only the inner-most loop is ordered */
  122655. int iTop; /* The very beginning of the WHERE loop */
  122656. WhereLoop *pLoops; /* List of all WhereLoop objects */
  122657. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  122658. LogEst nRowOut; /* Estimated number of output rows */
  122659. WhereClause sWC; /* Decomposition of the WHERE clause */
  122660. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  122661. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  122662. };
  122663. /*
  122664. ** Private interfaces - callable only by other where.c routines.
  122665. **
  122666. ** where.c:
  122667. */
  122668. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  122669. #ifdef WHERETRACE_ENABLED
  122670. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
  122671. #endif
  122672. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  122673. WhereClause *pWC, /* The WHERE clause to be searched */
  122674. int iCur, /* Cursor number of LHS */
  122675. int iColumn, /* Column number of LHS */
  122676. Bitmask notReady, /* RHS must not overlap with this mask */
  122677. u32 op, /* Mask of WO_xx values describing operator */
  122678. Index *pIdx /* Must be compatible with this index, if not NULL */
  122679. );
  122680. /* wherecode.c: */
  122681. #ifndef SQLITE_OMIT_EXPLAIN
  122682. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  122683. Parse *pParse, /* Parse context */
  122684. SrcList *pTabList, /* Table list this loop refers to */
  122685. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  122686. int iLevel, /* Value for "level" column of output */
  122687. int iFrom, /* Value for "from" column of output */
  122688. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  122689. );
  122690. #else
  122691. # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
  122692. #endif /* SQLITE_OMIT_EXPLAIN */
  122693. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  122694. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  122695. Vdbe *v, /* Vdbe to add scanstatus entry to */
  122696. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  122697. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  122698. int addrExplain /* Address of OP_Explain (or 0) */
  122699. );
  122700. #else
  122701. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  122702. #endif
  122703. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  122704. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  122705. int iLevel, /* Which level of pWInfo->a[] should be coded */
  122706. Bitmask notReady /* Which tables are currently available */
  122707. );
  122708. /* whereexpr.c: */
  122709. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  122710. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  122711. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  122712. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  122713. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  122714. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  122715. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  122716. /*
  122717. ** Bitmasks for the operators on WhereTerm objects. These are all
  122718. ** operators that are of interest to the query planner. An
  122719. ** OR-ed combination of these values can be used when searching for
  122720. ** particular WhereTerms within a WhereClause.
  122721. **
  122722. ** Value constraints:
  122723. ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
  122724. ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
  122725. ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
  122726. ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
  122727. ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
  122728. */
  122729. #define WO_IN 0x0001
  122730. #define WO_EQ 0x0002
  122731. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  122732. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  122733. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  122734. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  122735. #define WO_AUX 0x0040 /* Op useful to virtual tables only */
  122736. #define WO_IS 0x0080
  122737. #define WO_ISNULL 0x0100
  122738. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  122739. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  122740. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  122741. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  122742. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  122743. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  122744. /*
  122745. ** These are definitions of bits in the WhereLoop.wsFlags field.
  122746. ** The particular combination of bits in each WhereLoop help to
  122747. ** determine the algorithm that WhereLoop represents.
  122748. */
  122749. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  122750. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  122751. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  122752. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  122753. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  122754. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  122755. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  122756. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  122757. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  122758. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  122759. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  122760. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  122761. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  122762. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  122763. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  122764. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  122765. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  122766. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  122767. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  122768. /************** End of whereInt.h ********************************************/
  122769. /************** Continuing where we left off in wherecode.c ******************/
  122770. #ifndef SQLITE_OMIT_EXPLAIN
  122771. /*
  122772. ** Return the name of the i-th column of the pIdx index.
  122773. */
  122774. static const char *explainIndexColumnName(Index *pIdx, int i){
  122775. i = pIdx->aiColumn[i];
  122776. if( i==XN_EXPR ) return "<expr>";
  122777. if( i==XN_ROWID ) return "rowid";
  122778. return pIdx->pTable->aCol[i].zName;
  122779. }
  122780. /*
  122781. ** This routine is a helper for explainIndexRange() below
  122782. **
  122783. ** pStr holds the text of an expression that we are building up one term
  122784. ** at a time. This routine adds a new term to the end of the expression.
  122785. ** Terms are separated by AND so add the "AND" text for second and subsequent
  122786. ** terms only.
  122787. */
  122788. static void explainAppendTerm(
  122789. StrAccum *pStr, /* The text expression being built */
  122790. Index *pIdx, /* Index to read column names from */
  122791. int nTerm, /* Number of terms */
  122792. int iTerm, /* Zero-based index of first term. */
  122793. int bAnd, /* Non-zero to append " AND " */
  122794. const char *zOp /* Name of the operator */
  122795. ){
  122796. int i;
  122797. assert( nTerm>=1 );
  122798. if( bAnd ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  122799. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
  122800. for(i=0; i<nTerm; i++){
  122801. if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
  122802. sqlite3StrAccumAppendAll(pStr, explainIndexColumnName(pIdx, iTerm+i));
  122803. }
  122804. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
  122805. sqlite3StrAccumAppend(pStr, zOp, 1);
  122806. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, "(", 1);
  122807. for(i=0; i<nTerm; i++){
  122808. if( i ) sqlite3StrAccumAppend(pStr, ",", 1);
  122809. sqlite3StrAccumAppend(pStr, "?", 1);
  122810. }
  122811. if( nTerm>1 ) sqlite3StrAccumAppend(pStr, ")", 1);
  122812. }
  122813. /*
  122814. ** Argument pLevel describes a strategy for scanning table pTab. This
  122815. ** function appends text to pStr that describes the subset of table
  122816. ** rows scanned by the strategy in the form of an SQL expression.
  122817. **
  122818. ** For example, if the query:
  122819. **
  122820. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  122821. **
  122822. ** is run and there is an index on (a, b), then this function returns a
  122823. ** string similar to:
  122824. **
  122825. ** "a=? AND b>?"
  122826. */
  122827. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  122828. Index *pIndex = pLoop->u.btree.pIndex;
  122829. u16 nEq = pLoop->u.btree.nEq;
  122830. u16 nSkip = pLoop->nSkip;
  122831. int i, j;
  122832. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  122833. sqlite3StrAccumAppend(pStr, " (", 2);
  122834. for(i=0; i<nEq; i++){
  122835. const char *z = explainIndexColumnName(pIndex, i);
  122836. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  122837. sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  122838. }
  122839. j = i;
  122840. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  122841. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
  122842. i = 1;
  122843. }
  122844. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  122845. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  122846. }
  122847. sqlite3StrAccumAppend(pStr, ")", 1);
  122848. }
  122849. /*
  122850. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  122851. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  122852. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  122853. ** is added to the output to describe the table scan strategy in pLevel.
  122854. **
  122855. ** If an OP_Explain opcode is added to the VM, its address is returned.
  122856. ** Otherwise, if no OP_Explain is coded, zero is returned.
  122857. */
  122858. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  122859. Parse *pParse, /* Parse context */
  122860. SrcList *pTabList, /* Table list this loop refers to */
  122861. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  122862. int iLevel, /* Value for "level" column of output */
  122863. int iFrom, /* Value for "from" column of output */
  122864. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  122865. ){
  122866. int ret = 0;
  122867. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  122868. if( sqlite3ParseToplevel(pParse)->explain==2 )
  122869. #endif
  122870. {
  122871. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  122872. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  122873. sqlite3 *db = pParse->db; /* Database handle */
  122874. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  122875. int isSearch; /* True for a SEARCH. False for SCAN. */
  122876. WhereLoop *pLoop; /* The controlling WhereLoop object */
  122877. u32 flags; /* Flags that describe this loop */
  122878. char *zMsg; /* Text to add to EQP output */
  122879. StrAccum str; /* EQP output string */
  122880. char zBuf[100]; /* Initial space for EQP output string */
  122881. pLoop = pLevel->pWLoop;
  122882. flags = pLoop->wsFlags;
  122883. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
  122884. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  122885. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  122886. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  122887. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  122888. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  122889. if( pItem->pSelect ){
  122890. sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
  122891. }else{
  122892. sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
  122893. }
  122894. if( pItem->zAlias ){
  122895. sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
  122896. }
  122897. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  122898. const char *zFmt = 0;
  122899. Index *pIdx;
  122900. assert( pLoop->u.btree.pIndex!=0 );
  122901. pIdx = pLoop->u.btree.pIndex;
  122902. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  122903. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  122904. if( isSearch ){
  122905. zFmt = "PRIMARY KEY";
  122906. }
  122907. }else if( flags & WHERE_PARTIALIDX ){
  122908. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  122909. }else if( flags & WHERE_AUTO_INDEX ){
  122910. zFmt = "AUTOMATIC COVERING INDEX";
  122911. }else if( flags & WHERE_IDX_ONLY ){
  122912. zFmt = "COVERING INDEX %s";
  122913. }else{
  122914. zFmt = "INDEX %s";
  122915. }
  122916. if( zFmt ){
  122917. sqlite3StrAccumAppend(&str, " USING ", 7);
  122918. sqlite3XPrintf(&str, zFmt, pIdx->zName);
  122919. explainIndexRange(&str, pLoop);
  122920. }
  122921. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  122922. const char *zRangeOp;
  122923. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  122924. zRangeOp = "=";
  122925. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  122926. zRangeOp = ">? AND rowid<";
  122927. }else if( flags&WHERE_BTM_LIMIT ){
  122928. zRangeOp = ">";
  122929. }else{
  122930. assert( flags&WHERE_TOP_LIMIT);
  122931. zRangeOp = "<";
  122932. }
  122933. sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  122934. }
  122935. #ifndef SQLITE_OMIT_VIRTUALTABLE
  122936. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  122937. sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
  122938. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  122939. }
  122940. #endif
  122941. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  122942. if( pLoop->nOut>=10 ){
  122943. sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  122944. }else{
  122945. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  122946. }
  122947. #endif
  122948. zMsg = sqlite3StrAccumFinish(&str);
  122949. ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
  122950. }
  122951. return ret;
  122952. }
  122953. #endif /* SQLITE_OMIT_EXPLAIN */
  122954. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  122955. /*
  122956. ** Configure the VM passed as the first argument with an
  122957. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  122958. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  122959. ** clause that the scan reads data from.
  122960. **
  122961. ** If argument addrExplain is not 0, it must be the address of an
  122962. ** OP_Explain instruction that describes the same loop.
  122963. */
  122964. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  122965. Vdbe *v, /* Vdbe to add scanstatus entry to */
  122966. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  122967. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  122968. int addrExplain /* Address of OP_Explain (or 0) */
  122969. ){
  122970. const char *zObj = 0;
  122971. WhereLoop *pLoop = pLvl->pWLoop;
  122972. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  122973. zObj = pLoop->u.btree.pIndex->zName;
  122974. }else{
  122975. zObj = pSrclist->a[pLvl->iFrom].zName;
  122976. }
  122977. sqlite3VdbeScanStatus(
  122978. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  122979. );
  122980. }
  122981. #endif
  122982. /*
  122983. ** Disable a term in the WHERE clause. Except, do not disable the term
  122984. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  122985. ** or USING clause of that join.
  122986. **
  122987. ** Consider the term t2.z='ok' in the following queries:
  122988. **
  122989. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  122990. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  122991. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  122992. **
  122993. ** The t2.z='ok' is disabled in the in (2) because it originates
  122994. ** in the ON clause. The term is disabled in (3) because it is not part
  122995. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  122996. **
  122997. ** Disabling a term causes that term to not be tested in the inner loop
  122998. ** of the join. Disabling is an optimization. When terms are satisfied
  122999. ** by indices, we disable them to prevent redundant tests in the inner
  123000. ** loop. We would get the correct results if nothing were ever disabled,
  123001. ** but joins might run a little slower. The trick is to disable as much
  123002. ** as we can without disabling too much. If we disabled in (1), we'd get
  123003. ** the wrong answer. See ticket #813.
  123004. **
  123005. ** If all the children of a term are disabled, then that term is also
  123006. ** automatically disabled. In this way, terms get disabled if derived
  123007. ** virtual terms are tested first. For example:
  123008. **
  123009. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  123010. ** \___________/ \______/ \_____/
  123011. ** parent child1 child2
  123012. **
  123013. ** Only the parent term was in the original WHERE clause. The child1
  123014. ** and child2 terms were added by the LIKE optimization. If both of
  123015. ** the virtual child terms are valid, then testing of the parent can be
  123016. ** skipped.
  123017. **
  123018. ** Usually the parent term is marked as TERM_CODED. But if the parent
  123019. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  123020. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  123021. ** a conditional such that is only evaluated on the second pass of a
  123022. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  123023. */
  123024. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  123025. int nLoop = 0;
  123026. assert( pTerm!=0 );
  123027. while( (pTerm->wtFlags & TERM_CODED)==0
  123028. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  123029. && (pLevel->notReady & pTerm->prereqAll)==0
  123030. ){
  123031. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  123032. pTerm->wtFlags |= TERM_LIKECOND;
  123033. }else{
  123034. pTerm->wtFlags |= TERM_CODED;
  123035. }
  123036. if( pTerm->iParent<0 ) break;
  123037. pTerm = &pTerm->pWC->a[pTerm->iParent];
  123038. assert( pTerm!=0 );
  123039. pTerm->nChild--;
  123040. if( pTerm->nChild!=0 ) break;
  123041. nLoop++;
  123042. }
  123043. }
  123044. /*
  123045. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  123046. ** to the n registers starting at base.
  123047. **
  123048. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  123049. ** beginning and end of zAff are ignored. If all entries in zAff are
  123050. ** SQLITE_AFF_BLOB, then no code gets generated.
  123051. **
  123052. ** This routine makes its own copy of zAff so that the caller is free
  123053. ** to modify zAff after this routine returns.
  123054. */
  123055. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  123056. Vdbe *v = pParse->pVdbe;
  123057. if( zAff==0 ){
  123058. assert( pParse->db->mallocFailed );
  123059. return;
  123060. }
  123061. assert( v!=0 );
  123062. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  123063. ** and end of the affinity string.
  123064. */
  123065. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  123066. n--;
  123067. base++;
  123068. zAff++;
  123069. }
  123070. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  123071. n--;
  123072. }
  123073. /* Code the OP_Affinity opcode if there is anything left to do. */
  123074. if( n>0 ){
  123075. sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
  123076. sqlite3ExprCacheAffinityChange(pParse, base, n);
  123077. }
  123078. }
  123079. /*
  123080. ** Expression pRight, which is the RHS of a comparison operation, is
  123081. ** either a vector of n elements or, if n==1, a scalar expression.
  123082. ** Before the comparison operation, affinity zAff is to be applied
  123083. ** to the pRight values. This function modifies characters within the
  123084. ** affinity string to SQLITE_AFF_BLOB if either:
  123085. **
  123086. ** * the comparison will be performed with no affinity, or
  123087. ** * the affinity change in zAff is guaranteed not to change the value.
  123088. */
  123089. static void updateRangeAffinityStr(
  123090. Expr *pRight, /* RHS of comparison */
  123091. int n, /* Number of vector elements in comparison */
  123092. char *zAff /* Affinity string to modify */
  123093. ){
  123094. int i;
  123095. for(i=0; i<n; i++){
  123096. Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
  123097. if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
  123098. || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
  123099. ){
  123100. zAff[i] = SQLITE_AFF_BLOB;
  123101. }
  123102. }
  123103. }
  123104. /*
  123105. ** pX is an expression of the form: (vector) IN (SELECT ...)
  123106. ** In other words, it is a vector IN operator with a SELECT clause on the
  123107. ** LHS. But not all terms in the vector are indexable and the terms might
  123108. ** not be in the correct order for indexing.
  123109. **
  123110. ** This routine makes a copy of the input pX expression and then adjusts
  123111. ** the vector on the LHS with corresponding changes to the SELECT so that
  123112. ** the vector contains only index terms and those terms are in the correct
  123113. ** order. The modified IN expression is returned. The caller is responsible
  123114. ** for deleting the returned expression.
  123115. **
  123116. ** Example:
  123117. **
  123118. ** CREATE TABLE t1(a,b,c,d,e,f);
  123119. ** CREATE INDEX t1x1 ON t1(e,c);
  123120. ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
  123121. ** \_______________________________________/
  123122. ** The pX expression
  123123. **
  123124. ** Since only columns e and c can be used with the index, in that order,
  123125. ** the modified IN expression that is returned will be:
  123126. **
  123127. ** (e,c) IN (SELECT z,x FROM t2)
  123128. **
  123129. ** The reduced pX is different from the original (obviously) and thus is
  123130. ** only used for indexing, to improve performance. The original unaltered
  123131. ** IN expression must also be run on each output row for correctness.
  123132. */
  123133. static Expr *removeUnindexableInClauseTerms(
  123134. Parse *pParse, /* The parsing context */
  123135. int iEq, /* Look at loop terms starting here */
  123136. WhereLoop *pLoop, /* The current loop */
  123137. Expr *pX /* The IN expression to be reduced */
  123138. ){
  123139. sqlite3 *db = pParse->db;
  123140. Expr *pNew = sqlite3ExprDup(db, pX, 0);
  123141. if( db->mallocFailed==0 ){
  123142. ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */
  123143. ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */
  123144. ExprList *pRhs = 0; /* New RHS after modifications */
  123145. ExprList *pLhs = 0; /* New LHS after mods */
  123146. int i; /* Loop counter */
  123147. Select *pSelect; /* Pointer to the SELECT on the RHS */
  123148. for(i=iEq; i<pLoop->nLTerm; i++){
  123149. if( pLoop->aLTerm[i]->pExpr==pX ){
  123150. int iField = pLoop->aLTerm[i]->iField - 1;
  123151. assert( pOrigRhs->a[iField].pExpr!=0 );
  123152. pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
  123153. pOrigRhs->a[iField].pExpr = 0;
  123154. assert( pOrigLhs->a[iField].pExpr!=0 );
  123155. pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
  123156. pOrigLhs->a[iField].pExpr = 0;
  123157. }
  123158. }
  123159. sqlite3ExprListDelete(db, pOrigRhs);
  123160. sqlite3ExprListDelete(db, pOrigLhs);
  123161. pNew->pLeft->x.pList = pLhs;
  123162. pNew->x.pSelect->pEList = pRhs;
  123163. if( pLhs && pLhs->nExpr==1 ){
  123164. /* Take care here not to generate a TK_VECTOR containing only a
  123165. ** single value. Since the parser never creates such a vector, some
  123166. ** of the subroutines do not handle this case. */
  123167. Expr *p = pLhs->a[0].pExpr;
  123168. pLhs->a[0].pExpr = 0;
  123169. sqlite3ExprDelete(db, pNew->pLeft);
  123170. pNew->pLeft = p;
  123171. }
  123172. pSelect = pNew->x.pSelect;
  123173. if( pSelect->pOrderBy ){
  123174. /* If the SELECT statement has an ORDER BY clause, zero the
  123175. ** iOrderByCol variables. These are set to non-zero when an
  123176. ** ORDER BY term exactly matches one of the terms of the
  123177. ** result-set. Since the result-set of the SELECT statement may
  123178. ** have been modified or reordered, these variables are no longer
  123179. ** set correctly. Since setting them is just an optimization,
  123180. ** it's easiest just to zero them here. */
  123181. ExprList *pOrderBy = pSelect->pOrderBy;
  123182. for(i=0; i<pOrderBy->nExpr; i++){
  123183. pOrderBy->a[i].u.x.iOrderByCol = 0;
  123184. }
  123185. }
  123186. #if 0
  123187. printf("For indexing, change the IN expr:\n");
  123188. sqlite3TreeViewExpr(0, pX, 0);
  123189. printf("Into:\n");
  123190. sqlite3TreeViewExpr(0, pNew, 0);
  123191. #endif
  123192. }
  123193. return pNew;
  123194. }
  123195. /*
  123196. ** Generate code for a single equality term of the WHERE clause. An equality
  123197. ** term can be either X=expr or X IN (...). pTerm is the term to be
  123198. ** coded.
  123199. **
  123200. ** The current value for the constraint is left in a register, the index
  123201. ** of which is returned. An attempt is made store the result in iTarget but
  123202. ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
  123203. ** constraint is a TK_EQ or TK_IS, then the current value might be left in
  123204. ** some other register and it is the caller's responsibility to compensate.
  123205. **
  123206. ** For a constraint of the form X=expr, the expression is evaluated in
  123207. ** straight-line code. For constraints of the form X IN (...)
  123208. ** this routine sets up a loop that will iterate over all values of X.
  123209. */
  123210. static int codeEqualityTerm(
  123211. Parse *pParse, /* The parsing context */
  123212. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  123213. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  123214. int iEq, /* Index of the equality term within this level */
  123215. int bRev, /* True for reverse-order IN operations */
  123216. int iTarget /* Attempt to leave results in this register */
  123217. ){
  123218. Expr *pX = pTerm->pExpr;
  123219. Vdbe *v = pParse->pVdbe;
  123220. int iReg; /* Register holding results */
  123221. assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  123222. assert( iTarget>0 );
  123223. if( pX->op==TK_EQ || pX->op==TK_IS ){
  123224. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  123225. }else if( pX->op==TK_ISNULL ){
  123226. iReg = iTarget;
  123227. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  123228. #ifndef SQLITE_OMIT_SUBQUERY
  123229. }else{
  123230. int eType = IN_INDEX_NOOP;
  123231. int iTab;
  123232. struct InLoop *pIn;
  123233. WhereLoop *pLoop = pLevel->pWLoop;
  123234. int i;
  123235. int nEq = 0;
  123236. int *aiMap = 0;
  123237. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  123238. && pLoop->u.btree.pIndex!=0
  123239. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  123240. ){
  123241. testcase( iEq==0 );
  123242. testcase( bRev );
  123243. bRev = !bRev;
  123244. }
  123245. assert( pX->op==TK_IN );
  123246. iReg = iTarget;
  123247. for(i=0; i<iEq; i++){
  123248. if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
  123249. disableTerm(pLevel, pTerm);
  123250. return iTarget;
  123251. }
  123252. }
  123253. for(i=iEq;i<pLoop->nLTerm; i++){
  123254. assert( pLoop->aLTerm[i]!=0 );
  123255. if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
  123256. }
  123257. if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
  123258. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0);
  123259. }else{
  123260. sqlite3 *db = pParse->db;
  123261. pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
  123262. if( !db->mallocFailed ){
  123263. aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
  123264. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap);
  123265. pTerm->pExpr->iTable = pX->iTable;
  123266. }
  123267. sqlite3ExprDelete(db, pX);
  123268. pX = pTerm->pExpr;
  123269. }
  123270. if( eType==IN_INDEX_INDEX_DESC ){
  123271. testcase( bRev );
  123272. bRev = !bRev;
  123273. }
  123274. iTab = pX->iTable;
  123275. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  123276. VdbeCoverageIf(v, bRev);
  123277. VdbeCoverageIf(v, !bRev);
  123278. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  123279. pLoop->wsFlags |= WHERE_IN_ABLE;
  123280. if( pLevel->u.in.nIn==0 ){
  123281. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  123282. }
  123283. i = pLevel->u.in.nIn;
  123284. pLevel->u.in.nIn += nEq;
  123285. pLevel->u.in.aInLoop =
  123286. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  123287. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  123288. pIn = pLevel->u.in.aInLoop;
  123289. if( pIn ){
  123290. int iMap = 0; /* Index in aiMap[] */
  123291. pIn += i;
  123292. for(i=iEq;i<pLoop->nLTerm; i++){
  123293. if( pLoop->aLTerm[i]->pExpr==pX ){
  123294. int iOut = iReg + i - iEq;
  123295. if( eType==IN_INDEX_ROWID ){
  123296. testcase( nEq>1 ); /* Happens with a UNIQUE index on ROWID */
  123297. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
  123298. }else{
  123299. int iCol = aiMap ? aiMap[iMap++] : 0;
  123300. pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
  123301. }
  123302. sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
  123303. if( i==iEq ){
  123304. pIn->iCur = iTab;
  123305. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  123306. }else{
  123307. pIn->eEndLoopOp = OP_Noop;
  123308. }
  123309. pIn++;
  123310. }
  123311. }
  123312. }else{
  123313. pLevel->u.in.nIn = 0;
  123314. }
  123315. sqlite3DbFree(pParse->db, aiMap);
  123316. #endif
  123317. }
  123318. disableTerm(pLevel, pTerm);
  123319. return iReg;
  123320. }
  123321. /*
  123322. ** Generate code that will evaluate all == and IN constraints for an
  123323. ** index scan.
  123324. **
  123325. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  123326. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  123327. ** The index has as many as three equality constraints, but in this
  123328. ** example, the third "c" value is an inequality. So only two
  123329. ** constraints are coded. This routine will generate code to evaluate
  123330. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  123331. ** in consecutive registers and the index of the first register is returned.
  123332. **
  123333. ** In the example above nEq==2. But this subroutine works for any value
  123334. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  123335. ** The only thing it does is allocate the pLevel->iMem memory cell and
  123336. ** compute the affinity string.
  123337. **
  123338. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  123339. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  123340. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  123341. ** occurs after the nEq quality constraints.
  123342. **
  123343. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  123344. ** the index of the first memory cell in that range. The code that
  123345. ** calls this routine will use that memory range to store keys for
  123346. ** start and termination conditions of the loop.
  123347. ** key value of the loop. If one or more IN operators appear, then
  123348. ** this routine allocates an additional nEq memory cells for internal
  123349. ** use.
  123350. **
  123351. ** Before returning, *pzAff is set to point to a buffer containing a
  123352. ** copy of the column affinity string of the index allocated using
  123353. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  123354. ** with equality constraints that use BLOB or NONE affinity are set to
  123355. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  123356. **
  123357. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  123358. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  123359. **
  123360. ** In the example above, the index on t1(a) has TEXT affinity. But since
  123361. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  123362. ** no conversion should be attempted before using a t2.b value as part of
  123363. ** a key to search the index. Hence the first byte in the returned affinity
  123364. ** string in this example would be set to SQLITE_AFF_BLOB.
  123365. */
  123366. static int codeAllEqualityTerms(
  123367. Parse *pParse, /* Parsing context */
  123368. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  123369. int bRev, /* Reverse the order of IN operators */
  123370. int nExtraReg, /* Number of extra registers to allocate */
  123371. char **pzAff /* OUT: Set to point to affinity string */
  123372. ){
  123373. u16 nEq; /* The number of == or IN constraints to code */
  123374. u16 nSkip; /* Number of left-most columns to skip */
  123375. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  123376. Index *pIdx; /* The index being used for this loop */
  123377. WhereTerm *pTerm; /* A single constraint term */
  123378. WhereLoop *pLoop; /* The WhereLoop object */
  123379. int j; /* Loop counter */
  123380. int regBase; /* Base register */
  123381. int nReg; /* Number of registers to allocate */
  123382. char *zAff; /* Affinity string to return */
  123383. /* This module is only called on query plans that use an index. */
  123384. pLoop = pLevel->pWLoop;
  123385. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  123386. nEq = pLoop->u.btree.nEq;
  123387. nSkip = pLoop->nSkip;
  123388. pIdx = pLoop->u.btree.pIndex;
  123389. assert( pIdx!=0 );
  123390. /* Figure out how many memory cells we will need then allocate them.
  123391. */
  123392. regBase = pParse->nMem + 1;
  123393. nReg = pLoop->u.btree.nEq + nExtraReg;
  123394. pParse->nMem += nReg;
  123395. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  123396. assert( zAff!=0 || pParse->db->mallocFailed );
  123397. if( nSkip ){
  123398. int iIdxCur = pLevel->iIdxCur;
  123399. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  123400. VdbeCoverageIf(v, bRev==0);
  123401. VdbeCoverageIf(v, bRev!=0);
  123402. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  123403. j = sqlite3VdbeAddOp0(v, OP_Goto);
  123404. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  123405. iIdxCur, 0, regBase, nSkip);
  123406. VdbeCoverageIf(v, bRev==0);
  123407. VdbeCoverageIf(v, bRev!=0);
  123408. sqlite3VdbeJumpHere(v, j);
  123409. for(j=0; j<nSkip; j++){
  123410. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  123411. testcase( pIdx->aiColumn[j]==XN_EXPR );
  123412. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  123413. }
  123414. }
  123415. /* Evaluate the equality constraints
  123416. */
  123417. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  123418. for(j=nSkip; j<nEq; j++){
  123419. int r1;
  123420. pTerm = pLoop->aLTerm[j];
  123421. assert( pTerm!=0 );
  123422. /* The following testcase is true for indices with redundant columns.
  123423. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  123424. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  123425. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  123426. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  123427. if( r1!=regBase+j ){
  123428. if( nReg==1 ){
  123429. sqlite3ReleaseTempReg(pParse, regBase);
  123430. regBase = r1;
  123431. }else{
  123432. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  123433. }
  123434. }
  123435. if( pTerm->eOperator & WO_IN ){
  123436. if( pTerm->pExpr->flags & EP_xIsSelect ){
  123437. /* No affinity ever needs to be (or should be) applied to a value
  123438. ** from the RHS of an "? IN (SELECT ...)" expression. The
  123439. ** sqlite3FindInIndex() routine has already ensured that the
  123440. ** affinity of the comparison has been applied to the value. */
  123441. if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
  123442. }
  123443. }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
  123444. Expr *pRight = pTerm->pExpr->pRight;
  123445. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  123446. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  123447. VdbeCoverage(v);
  123448. }
  123449. if( zAff ){
  123450. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  123451. zAff[j] = SQLITE_AFF_BLOB;
  123452. }
  123453. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  123454. zAff[j] = SQLITE_AFF_BLOB;
  123455. }
  123456. }
  123457. }
  123458. }
  123459. *pzAff = zAff;
  123460. return regBase;
  123461. }
  123462. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  123463. /*
  123464. ** If the most recently coded instruction is a constant range constraint
  123465. ** (a string literal) that originated from the LIKE optimization, then
  123466. ** set P3 and P5 on the OP_String opcode so that the string will be cast
  123467. ** to a BLOB at appropriate times.
  123468. **
  123469. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  123470. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  123471. ** scan loop run twice, once for strings and a second time for BLOBs.
  123472. ** The OP_String opcodes on the second pass convert the upper and lower
  123473. ** bound string constants to blobs. This routine makes the necessary changes
  123474. ** to the OP_String opcodes for that to happen.
  123475. **
  123476. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  123477. ** only the one pass through the string space is required, so this routine
  123478. ** becomes a no-op.
  123479. */
  123480. static void whereLikeOptimizationStringFixup(
  123481. Vdbe *v, /* prepared statement under construction */
  123482. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  123483. WhereTerm *pTerm /* The upper or lower bound just coded */
  123484. ){
  123485. if( pTerm->wtFlags & TERM_LIKEOPT ){
  123486. VdbeOp *pOp;
  123487. assert( pLevel->iLikeRepCntr>0 );
  123488. pOp = sqlite3VdbeGetOp(v, -1);
  123489. assert( pOp!=0 );
  123490. assert( pOp->opcode==OP_String8
  123491. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  123492. pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
  123493. pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
  123494. }
  123495. }
  123496. #else
  123497. # define whereLikeOptimizationStringFixup(A,B,C)
  123498. #endif
  123499. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  123500. /*
  123501. ** Information is passed from codeCursorHint() down to individual nodes of
  123502. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  123503. ** structure.
  123504. */
  123505. struct CCurHint {
  123506. int iTabCur; /* Cursor for the main table */
  123507. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  123508. Index *pIdx; /* The index used to access the table */
  123509. };
  123510. /*
  123511. ** This function is called for every node of an expression that is a candidate
  123512. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  123513. ** the table CCurHint.iTabCur, verify that the same column can be
  123514. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  123515. */
  123516. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  123517. struct CCurHint *pHint = pWalker->u.pCCurHint;
  123518. assert( pHint->pIdx!=0 );
  123519. if( pExpr->op==TK_COLUMN
  123520. && pExpr->iTable==pHint->iTabCur
  123521. && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
  123522. ){
  123523. pWalker->eCode = 1;
  123524. }
  123525. return WRC_Continue;
  123526. }
  123527. /*
  123528. ** Test whether or not expression pExpr, which was part of a WHERE clause,
  123529. ** should be included in the cursor-hint for a table that is on the rhs
  123530. ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
  123531. ** expression is not suitable.
  123532. **
  123533. ** An expression is unsuitable if it might evaluate to non NULL even if
  123534. ** a TK_COLUMN node that does affect the value of the expression is set
  123535. ** to NULL. For example:
  123536. **
  123537. ** col IS NULL
  123538. ** col IS NOT NULL
  123539. ** coalesce(col, 1)
  123540. ** CASE WHEN col THEN 0 ELSE 1 END
  123541. */
  123542. static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
  123543. if( pExpr->op==TK_IS
  123544. || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
  123545. || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
  123546. ){
  123547. pWalker->eCode = 1;
  123548. }else if( pExpr->op==TK_FUNCTION ){
  123549. int d1;
  123550. char d2[4];
  123551. if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
  123552. pWalker->eCode = 1;
  123553. }
  123554. }
  123555. return WRC_Continue;
  123556. }
  123557. /*
  123558. ** This function is called on every node of an expression tree used as an
  123559. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  123560. ** that accesses any table other than the one identified by
  123561. ** CCurHint.iTabCur, then do the following:
  123562. **
  123563. ** 1) allocate a register and code an OP_Column instruction to read
  123564. ** the specified column into the new register, and
  123565. **
  123566. ** 2) transform the expression node to a TK_REGISTER node that reads
  123567. ** from the newly populated register.
  123568. **
  123569. ** Also, if the node is a TK_COLUMN that does access the table idenified
  123570. ** by pCCurHint.iTabCur, and an index is being used (which we will
  123571. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  123572. ** an access of the index rather than the original table.
  123573. */
  123574. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  123575. int rc = WRC_Continue;
  123576. struct CCurHint *pHint = pWalker->u.pCCurHint;
  123577. if( pExpr->op==TK_COLUMN ){
  123578. if( pExpr->iTable!=pHint->iTabCur ){
  123579. Vdbe *v = pWalker->pParse->pVdbe;
  123580. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  123581. sqlite3ExprCodeGetColumnOfTable(
  123582. v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
  123583. );
  123584. pExpr->op = TK_REGISTER;
  123585. pExpr->iTable = reg;
  123586. }else if( pHint->pIdx!=0 ){
  123587. pExpr->iTable = pHint->iIdxCur;
  123588. pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
  123589. assert( pExpr->iColumn>=0 );
  123590. }
  123591. }else if( pExpr->op==TK_AGG_FUNCTION ){
  123592. /* An aggregate function in the WHERE clause of a query means this must
  123593. ** be a correlated sub-query, and expression pExpr is an aggregate from
  123594. ** the parent context. Do not walk the function arguments in this case.
  123595. **
  123596. ** todo: It should be possible to replace this node with a TK_REGISTER
  123597. ** expression, as the result of the expression must be stored in a
  123598. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  123599. rc = WRC_Prune;
  123600. }
  123601. return rc;
  123602. }
  123603. /*
  123604. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  123605. */
  123606. static void codeCursorHint(
  123607. struct SrcList_item *pTabItem, /* FROM clause item */
  123608. WhereInfo *pWInfo, /* The where clause */
  123609. WhereLevel *pLevel, /* Which loop to provide hints for */
  123610. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  123611. ){
  123612. Parse *pParse = pWInfo->pParse;
  123613. sqlite3 *db = pParse->db;
  123614. Vdbe *v = pParse->pVdbe;
  123615. Expr *pExpr = 0;
  123616. WhereLoop *pLoop = pLevel->pWLoop;
  123617. int iCur;
  123618. WhereClause *pWC;
  123619. WhereTerm *pTerm;
  123620. int i, j;
  123621. struct CCurHint sHint;
  123622. Walker sWalker;
  123623. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  123624. iCur = pLevel->iTabCur;
  123625. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  123626. sHint.iTabCur = iCur;
  123627. sHint.iIdxCur = pLevel->iIdxCur;
  123628. sHint.pIdx = pLoop->u.btree.pIndex;
  123629. memset(&sWalker, 0, sizeof(sWalker));
  123630. sWalker.pParse = pParse;
  123631. sWalker.u.pCCurHint = &sHint;
  123632. pWC = &pWInfo->sWC;
  123633. for(i=0; i<pWC->nTerm; i++){
  123634. pTerm = &pWC->a[i];
  123635. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  123636. if( pTerm->prereqAll & pLevel->notReady ) continue;
  123637. /* Any terms specified as part of the ON(...) clause for any LEFT
  123638. ** JOIN for which the current table is not the rhs are omitted
  123639. ** from the cursor-hint.
  123640. **
  123641. ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
  123642. ** that were specified as part of the WHERE clause must be excluded.
  123643. ** This is to address the following:
  123644. **
  123645. ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
  123646. **
  123647. ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
  123648. ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
  123649. ** pushed down to the cursor, this row is filtered out, causing
  123650. ** SQLite to synthesize a row of NULL values. Which does match the
  123651. ** WHERE clause, and so the query returns a row. Which is incorrect.
  123652. **
  123653. ** For the same reason, WHERE terms such as:
  123654. **
  123655. ** WHERE 1 = (t2.c IS NULL)
  123656. **
  123657. ** are also excluded. See codeCursorHintIsOrFunction() for details.
  123658. */
  123659. if( pTabItem->fg.jointype & JT_LEFT ){
  123660. Expr *pExpr = pTerm->pExpr;
  123661. if( !ExprHasProperty(pExpr, EP_FromJoin)
  123662. || pExpr->iRightJoinTable!=pTabItem->iCursor
  123663. ){
  123664. sWalker.eCode = 0;
  123665. sWalker.xExprCallback = codeCursorHintIsOrFunction;
  123666. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  123667. if( sWalker.eCode ) continue;
  123668. }
  123669. }else{
  123670. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  123671. }
  123672. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  123673. ** the cursor. These terms are not needed as hints for a pure range
  123674. ** scan (that has no == terms) so omit them. */
  123675. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  123676. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  123677. if( j<pLoop->nLTerm ) continue;
  123678. }
  123679. /* No subqueries or non-deterministic functions allowed */
  123680. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  123681. /* For an index scan, make sure referenced columns are actually in
  123682. ** the index. */
  123683. if( sHint.pIdx!=0 ){
  123684. sWalker.eCode = 0;
  123685. sWalker.xExprCallback = codeCursorHintCheckExpr;
  123686. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  123687. if( sWalker.eCode ) continue;
  123688. }
  123689. /* If we survive all prior tests, that means this term is worth hinting */
  123690. pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  123691. }
  123692. if( pExpr!=0 ){
  123693. sWalker.xExprCallback = codeCursorHintFixExpr;
  123694. sqlite3WalkExpr(&sWalker, pExpr);
  123695. sqlite3VdbeAddOp4(v, OP_CursorHint,
  123696. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  123697. (const char*)pExpr, P4_EXPR);
  123698. }
  123699. }
  123700. #else
  123701. # define codeCursorHint(A,B,C,D) /* No-op */
  123702. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  123703. /*
  123704. ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
  123705. ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
  123706. ** function generates code to do a deferred seek of cursor iCur to the
  123707. ** rowid stored in register iRowid.
  123708. **
  123709. ** Normally, this is just:
  123710. **
  123711. ** OP_DeferredSeek $iCur $iRowid
  123712. **
  123713. ** However, if the scan currently being coded is a branch of an OR-loop and
  123714. ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
  123715. ** is set to iIdxCur and P4 is set to point to an array of integers
  123716. ** containing one entry for each column of the table cursor iCur is open
  123717. ** on. For each table column, if the column is the i'th column of the
  123718. ** index, then the corresponding array entry is set to (i+1). If the column
  123719. ** does not appear in the index at all, the array entry is set to 0.
  123720. */
  123721. static void codeDeferredSeek(
  123722. WhereInfo *pWInfo, /* Where clause context */
  123723. Index *pIdx, /* Index scan is using */
  123724. int iCur, /* Cursor for IPK b-tree */
  123725. int iIdxCur /* Index cursor */
  123726. ){
  123727. Parse *pParse = pWInfo->pParse; /* Parse context */
  123728. Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
  123729. assert( iIdxCur>0 );
  123730. assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
  123731. sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
  123732. if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  123733. && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
  123734. ){
  123735. int i;
  123736. Table *pTab = pIdx->pTable;
  123737. int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
  123738. if( ai ){
  123739. ai[0] = pTab->nCol;
  123740. for(i=0; i<pIdx->nColumn-1; i++){
  123741. assert( pIdx->aiColumn[i]<pTab->nCol );
  123742. if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
  123743. }
  123744. sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
  123745. }
  123746. }
  123747. }
  123748. /*
  123749. ** If the expression passed as the second argument is a vector, generate
  123750. ** code to write the first nReg elements of the vector into an array
  123751. ** of registers starting with iReg.
  123752. **
  123753. ** If the expression is not a vector, then nReg must be passed 1. In
  123754. ** this case, generate code to evaluate the expression and leave the
  123755. ** result in register iReg.
  123756. */
  123757. static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
  123758. assert( nReg>0 );
  123759. if( p && sqlite3ExprIsVector(p) ){
  123760. #ifndef SQLITE_OMIT_SUBQUERY
  123761. if( (p->flags & EP_xIsSelect) ){
  123762. Vdbe *v = pParse->pVdbe;
  123763. int iSelect = sqlite3CodeSubselect(pParse, p, 0, 0);
  123764. sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
  123765. }else
  123766. #endif
  123767. {
  123768. int i;
  123769. ExprList *pList = p->x.pList;
  123770. assert( nReg<=pList->nExpr );
  123771. for(i=0; i<nReg; i++){
  123772. sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
  123773. }
  123774. }
  123775. }else{
  123776. assert( nReg==1 );
  123777. sqlite3ExprCode(pParse, p, iReg);
  123778. }
  123779. }
  123780. /* An instance of the IdxExprTrans object carries information about a
  123781. ** mapping from an expression on table columns into a column in an index
  123782. ** down through the Walker.
  123783. */
  123784. typedef struct IdxExprTrans {
  123785. Expr *pIdxExpr; /* The index expression */
  123786. int iTabCur; /* The cursor of the corresponding table */
  123787. int iIdxCur; /* The cursor for the index */
  123788. int iIdxCol; /* The column for the index */
  123789. } IdxExprTrans;
  123790. /* The walker node callback used to transform matching expressions into
  123791. ** a reference to an index column for an index on an expression.
  123792. **
  123793. ** If pExpr matches, then transform it into a reference to the index column
  123794. ** that contains the value of pExpr.
  123795. */
  123796. static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
  123797. IdxExprTrans *pX = p->u.pIdxTrans;
  123798. if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
  123799. pExpr->op = TK_COLUMN;
  123800. pExpr->iTable = pX->iIdxCur;
  123801. pExpr->iColumn = pX->iIdxCol;
  123802. pExpr->pTab = 0;
  123803. return WRC_Prune;
  123804. }else{
  123805. return WRC_Continue;
  123806. }
  123807. }
  123808. /*
  123809. ** For an indexes on expression X, locate every instance of expression X
  123810. ** in pExpr and change that subexpression into a reference to the appropriate
  123811. ** column of the index.
  123812. */
  123813. static void whereIndexExprTrans(
  123814. Index *pIdx, /* The Index */
  123815. int iTabCur, /* Cursor of the table that is being indexed */
  123816. int iIdxCur, /* Cursor of the index itself */
  123817. WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
  123818. ){
  123819. int iIdxCol; /* Column number of the index */
  123820. ExprList *aColExpr; /* Expressions that are indexed */
  123821. Walker w;
  123822. IdxExprTrans x;
  123823. aColExpr = pIdx->aColExpr;
  123824. if( aColExpr==0 ) return; /* Not an index on expressions */
  123825. memset(&w, 0, sizeof(w));
  123826. w.xExprCallback = whereIndexExprTransNode;
  123827. w.u.pIdxTrans = &x;
  123828. x.iTabCur = iTabCur;
  123829. x.iIdxCur = iIdxCur;
  123830. for(iIdxCol=0; iIdxCol<aColExpr->nExpr; iIdxCol++){
  123831. if( pIdx->aiColumn[iIdxCol]!=XN_EXPR ) continue;
  123832. assert( aColExpr->a[iIdxCol].pExpr!=0 );
  123833. x.iIdxCol = iIdxCol;
  123834. x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
  123835. sqlite3WalkExpr(&w, pWInfo->pWhere);
  123836. sqlite3WalkExprList(&w, pWInfo->pOrderBy);
  123837. sqlite3WalkExprList(&w, pWInfo->pResultSet);
  123838. }
  123839. }
  123840. /*
  123841. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  123842. ** implementation described by pWInfo.
  123843. */
  123844. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  123845. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  123846. int iLevel, /* Which level of pWInfo->a[] should be coded */
  123847. Bitmask notReady /* Which tables are currently available */
  123848. ){
  123849. int j, k; /* Loop counters */
  123850. int iCur; /* The VDBE cursor for the table */
  123851. int addrNxt; /* Where to jump to continue with the next IN case */
  123852. int omitTable; /* True if we use the index only */
  123853. int bRev; /* True if we need to scan in reverse order */
  123854. WhereLevel *pLevel; /* The where level to be coded */
  123855. WhereLoop *pLoop; /* The WhereLoop object being coded */
  123856. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  123857. WhereTerm *pTerm; /* A WHERE clause term */
  123858. Parse *pParse; /* Parsing context */
  123859. sqlite3 *db; /* Database connection */
  123860. Vdbe *v; /* The prepared stmt under constructions */
  123861. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  123862. int addrBrk; /* Jump here to break out of the loop */
  123863. int addrHalt; /* addrBrk for the outermost loop */
  123864. int addrCont; /* Jump here to continue with next cycle */
  123865. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  123866. int iReleaseReg = 0; /* Temp register to free before returning */
  123867. Index *pIdx = 0; /* Index used by loop (if any) */
  123868. int iLoop; /* Iteration of constraint generator loop */
  123869. pParse = pWInfo->pParse;
  123870. v = pParse->pVdbe;
  123871. pWC = &pWInfo->sWC;
  123872. db = pParse->db;
  123873. pLevel = &pWInfo->a[iLevel];
  123874. pLoop = pLevel->pWLoop;
  123875. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  123876. iCur = pTabItem->iCursor;
  123877. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  123878. bRev = (pWInfo->revMask>>iLevel)&1;
  123879. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  123880. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
  123881. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  123882. /* Create labels for the "break" and "continue" instructions
  123883. ** for the current loop. Jump to addrBrk to break out of a loop.
  123884. ** Jump to cont to go immediately to the next iteration of the
  123885. ** loop.
  123886. **
  123887. ** When there is an IN operator, we also have a "addrNxt" label that
  123888. ** means to continue with the next IN value combination. When
  123889. ** there are no IN operators in the constraints, the "addrNxt" label
  123890. ** is the same as "addrBrk".
  123891. */
  123892. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  123893. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  123894. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  123895. ** initialize a memory cell that records if this table matches any
  123896. ** row of the left table of the join.
  123897. */
  123898. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  123899. pLevel->iLeftJoin = ++pParse->nMem;
  123900. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  123901. VdbeComment((v, "init LEFT JOIN no-match flag"));
  123902. }
  123903. /* Compute a safe address to jump to if we discover that the table for
  123904. ** this loop is empty and can never contribute content. */
  123905. for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
  123906. addrHalt = pWInfo->a[j].addrBrk;
  123907. /* Special case of a FROM clause subquery implemented as a co-routine */
  123908. if( pTabItem->fg.viaCoroutine ){
  123909. int regYield = pTabItem->regReturn;
  123910. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  123911. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  123912. VdbeCoverage(v);
  123913. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  123914. pLevel->op = OP_Goto;
  123915. }else
  123916. #ifndef SQLITE_OMIT_VIRTUALTABLE
  123917. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  123918. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  123919. ** to access the data.
  123920. */
  123921. int iReg; /* P3 Value for OP_VFilter */
  123922. int addrNotFound;
  123923. int nConstraint = pLoop->nLTerm;
  123924. int iIn; /* Counter for IN constraints */
  123925. sqlite3ExprCachePush(pParse);
  123926. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  123927. addrNotFound = pLevel->addrBrk;
  123928. for(j=0; j<nConstraint; j++){
  123929. int iTarget = iReg+j+2;
  123930. pTerm = pLoop->aLTerm[j];
  123931. if( NEVER(pTerm==0) ) continue;
  123932. if( pTerm->eOperator & WO_IN ){
  123933. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  123934. addrNotFound = pLevel->addrNxt;
  123935. }else{
  123936. Expr *pRight = pTerm->pExpr->pRight;
  123937. codeExprOrVector(pParse, pRight, iTarget, 1);
  123938. }
  123939. }
  123940. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  123941. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  123942. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  123943. pLoop->u.vtab.idxStr,
  123944. pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
  123945. VdbeCoverage(v);
  123946. pLoop->u.vtab.needFree = 0;
  123947. pLevel->p1 = iCur;
  123948. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  123949. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  123950. iIn = pLevel->u.in.nIn;
  123951. for(j=nConstraint-1; j>=0; j--){
  123952. pTerm = pLoop->aLTerm[j];
  123953. if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
  123954. disableTerm(pLevel, pTerm);
  123955. }else if( (pTerm->eOperator & WO_IN)!=0 ){
  123956. Expr *pCompare; /* The comparison operator */
  123957. Expr *pRight; /* RHS of the comparison */
  123958. VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
  123959. /* Reload the constraint value into reg[iReg+j+2]. The same value
  123960. ** was loaded into the same register prior to the OP_VFilter, but
  123961. ** the xFilter implementation might have changed the datatype or
  123962. ** encoding of the value in the register, so it *must* be reloaded. */
  123963. assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
  123964. if( !db->mallocFailed ){
  123965. assert( iIn>0 );
  123966. pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
  123967. assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
  123968. assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
  123969. assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
  123970. testcase( pOp->opcode==OP_Rowid );
  123971. sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
  123972. }
  123973. /* Generate code that will continue to the next row if
  123974. ** the IN constraint is not satisfied */
  123975. pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
  123976. assert( pCompare!=0 || db->mallocFailed );
  123977. if( pCompare ){
  123978. pCompare->pLeft = pTerm->pExpr->pLeft;
  123979. pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
  123980. if( pRight ){
  123981. pRight->iTable = iReg+j+2;
  123982. sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
  123983. }
  123984. pCompare->pLeft = 0;
  123985. sqlite3ExprDelete(db, pCompare);
  123986. }
  123987. }
  123988. }
  123989. /* These registers need to be preserved in case there is an IN operator
  123990. ** loop. So we could deallocate the registers here (and potentially
  123991. ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
  123992. ** simpler and safer to simply not reuse the registers.
  123993. **
  123994. ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  123995. */
  123996. sqlite3ExprCachePop(pParse);
  123997. }else
  123998. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  123999. if( (pLoop->wsFlags & WHERE_IPK)!=0
  124000. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  124001. ){
  124002. /* Case 2: We can directly reference a single row using an
  124003. ** equality comparison against the ROWID field. Or
  124004. ** we reference multiple rows using a "rowid IN (...)"
  124005. ** construct.
  124006. */
  124007. assert( pLoop->u.btree.nEq==1 );
  124008. pTerm = pLoop->aLTerm[0];
  124009. assert( pTerm!=0 );
  124010. assert( pTerm->pExpr!=0 );
  124011. assert( omitTable==0 );
  124012. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  124013. iReleaseReg = ++pParse->nMem;
  124014. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  124015. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  124016. addrNxt = pLevel->addrNxt;
  124017. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
  124018. VdbeCoverage(v);
  124019. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  124020. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  124021. VdbeComment((v, "pk"));
  124022. pLevel->op = OP_Noop;
  124023. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  124024. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  124025. ){
  124026. /* Case 3: We have an inequality comparison against the ROWID field.
  124027. */
  124028. int testOp = OP_Noop;
  124029. int start;
  124030. int memEndValue = 0;
  124031. WhereTerm *pStart, *pEnd;
  124032. assert( omitTable==0 );
  124033. j = 0;
  124034. pStart = pEnd = 0;
  124035. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  124036. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  124037. assert( pStart!=0 || pEnd!=0 );
  124038. if( bRev ){
  124039. pTerm = pStart;
  124040. pStart = pEnd;
  124041. pEnd = pTerm;
  124042. }
  124043. codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
  124044. if( pStart ){
  124045. Expr *pX; /* The expression that defines the start bound */
  124046. int r1, rTemp; /* Registers for holding the start boundary */
  124047. int op; /* Cursor seek operation */
  124048. /* The following constant maps TK_xx codes into corresponding
  124049. ** seek opcodes. It depends on a particular ordering of TK_xx
  124050. */
  124051. const u8 aMoveOp[] = {
  124052. /* TK_GT */ OP_SeekGT,
  124053. /* TK_LE */ OP_SeekLE,
  124054. /* TK_LT */ OP_SeekLT,
  124055. /* TK_GE */ OP_SeekGE
  124056. };
  124057. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  124058. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  124059. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  124060. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  124061. testcase( pStart->wtFlags & TERM_VIRTUAL );
  124062. pX = pStart->pExpr;
  124063. assert( pX!=0 );
  124064. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  124065. if( sqlite3ExprIsVector(pX->pRight) ){
  124066. r1 = rTemp = sqlite3GetTempReg(pParse);
  124067. codeExprOrVector(pParse, pX->pRight, r1, 1);
  124068. testcase( pX->op==TK_GT );
  124069. testcase( pX->op==TK_GE );
  124070. testcase( pX->op==TK_LT );
  124071. testcase( pX->op==TK_LE );
  124072. op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
  124073. assert( pX->op!=TK_GT || op==OP_SeekGE );
  124074. assert( pX->op!=TK_GE || op==OP_SeekGE );
  124075. assert( pX->op!=TK_LT || op==OP_SeekLE );
  124076. assert( pX->op!=TK_LE || op==OP_SeekLE );
  124077. }else{
  124078. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  124079. disableTerm(pLevel, pStart);
  124080. op = aMoveOp[(pX->op - TK_GT)];
  124081. }
  124082. sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
  124083. VdbeComment((v, "pk"));
  124084. VdbeCoverageIf(v, pX->op==TK_GT);
  124085. VdbeCoverageIf(v, pX->op==TK_LE);
  124086. VdbeCoverageIf(v, pX->op==TK_LT);
  124087. VdbeCoverageIf(v, pX->op==TK_GE);
  124088. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  124089. sqlite3ReleaseTempReg(pParse, rTemp);
  124090. }else{
  124091. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
  124092. VdbeCoverageIf(v, bRev==0);
  124093. VdbeCoverageIf(v, bRev!=0);
  124094. }
  124095. if( pEnd ){
  124096. Expr *pX;
  124097. pX = pEnd->pExpr;
  124098. assert( pX!=0 );
  124099. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  124100. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  124101. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  124102. memEndValue = ++pParse->nMem;
  124103. codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
  124104. if( 0==sqlite3ExprIsVector(pX->pRight)
  124105. && (pX->op==TK_LT || pX->op==TK_GT)
  124106. ){
  124107. testOp = bRev ? OP_Le : OP_Ge;
  124108. }else{
  124109. testOp = bRev ? OP_Lt : OP_Gt;
  124110. }
  124111. if( 0==sqlite3ExprIsVector(pX->pRight) ){
  124112. disableTerm(pLevel, pEnd);
  124113. }
  124114. }
  124115. start = sqlite3VdbeCurrentAddr(v);
  124116. pLevel->op = bRev ? OP_Prev : OP_Next;
  124117. pLevel->p1 = iCur;
  124118. pLevel->p2 = start;
  124119. assert( pLevel->p5==0 );
  124120. if( testOp!=OP_Noop ){
  124121. iRowidReg = ++pParse->nMem;
  124122. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  124123. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  124124. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  124125. VdbeCoverageIf(v, testOp==OP_Le);
  124126. VdbeCoverageIf(v, testOp==OP_Lt);
  124127. VdbeCoverageIf(v, testOp==OP_Ge);
  124128. VdbeCoverageIf(v, testOp==OP_Gt);
  124129. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  124130. }
  124131. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  124132. /* Case 4: A scan using an index.
  124133. **
  124134. ** The WHERE clause may contain zero or more equality
  124135. ** terms ("==" or "IN" operators) that refer to the N
  124136. ** left-most columns of the index. It may also contain
  124137. ** inequality constraints (>, <, >= or <=) on the indexed
  124138. ** column that immediately follows the N equalities. Only
  124139. ** the right-most column can be an inequality - the rest must
  124140. ** use the "==" and "IN" operators. For example, if the
  124141. ** index is on (x,y,z), then the following clauses are all
  124142. ** optimized:
  124143. **
  124144. ** x=5
  124145. ** x=5 AND y=10
  124146. ** x=5 AND y<10
  124147. ** x=5 AND y>5 AND y<10
  124148. ** x=5 AND y=5 AND z<=10
  124149. **
  124150. ** The z<10 term of the following cannot be used, only
  124151. ** the x=5 term:
  124152. **
  124153. ** x=5 AND z<10
  124154. **
  124155. ** N may be zero if there are inequality constraints.
  124156. ** If there are no inequality constraints, then N is at
  124157. ** least one.
  124158. **
  124159. ** This case is also used when there are no WHERE clause
  124160. ** constraints but an index is selected anyway, in order
  124161. ** to force the output order to conform to an ORDER BY.
  124162. */
  124163. static const u8 aStartOp[] = {
  124164. 0,
  124165. 0,
  124166. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  124167. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  124168. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  124169. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  124170. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  124171. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  124172. };
  124173. static const u8 aEndOp[] = {
  124174. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  124175. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  124176. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  124177. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  124178. };
  124179. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  124180. u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
  124181. u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
  124182. int regBase; /* Base register holding constraint values */
  124183. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  124184. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  124185. int startEq; /* True if range start uses ==, >= or <= */
  124186. int endEq; /* True if range end uses ==, >= or <= */
  124187. int start_constraints; /* Start of range is constrained */
  124188. int nConstraint; /* Number of constraint terms */
  124189. int iIdxCur; /* The VDBE cursor for the index */
  124190. int nExtraReg = 0; /* Number of extra registers needed */
  124191. int op; /* Instruction opcode */
  124192. char *zStartAff; /* Affinity for start of range constraint */
  124193. char *zEndAff = 0; /* Affinity for end of range constraint */
  124194. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  124195. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  124196. pIdx = pLoop->u.btree.pIndex;
  124197. iIdxCur = pLevel->iIdxCur;
  124198. assert( nEq>=pLoop->nSkip );
  124199. /* If this loop satisfies a sort order (pOrderBy) request that
  124200. ** was passed to this function to implement a "SELECT min(x) ..."
  124201. ** query, then the caller will only allow the loop to run for
  124202. ** a single iteration. This means that the first row returned
  124203. ** should not have a NULL value stored in 'x'. If column 'x' is
  124204. ** the first one after the nEq equality constraints in the index,
  124205. ** this requires some special handling.
  124206. */
  124207. assert( pWInfo->pOrderBy==0
  124208. || pWInfo->pOrderBy->nExpr==1
  124209. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  124210. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  124211. && pWInfo->nOBSat>0
  124212. && (pIdx->nKeyCol>nEq)
  124213. ){
  124214. assert( pLoop->nSkip==0 );
  124215. bSeekPastNull = 1;
  124216. nExtraReg = 1;
  124217. }
  124218. /* Find any inequality constraint terms for the start and end
  124219. ** of the range.
  124220. */
  124221. j = nEq;
  124222. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  124223. pRangeStart = pLoop->aLTerm[j++];
  124224. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
  124225. /* Like optimization range constraints always occur in pairs */
  124226. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  124227. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  124228. }
  124229. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  124230. pRangeEnd = pLoop->aLTerm[j++];
  124231. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
  124232. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  124233. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  124234. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  124235. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  124236. pLevel->iLikeRepCntr = (u32)++pParse->nMem;
  124237. sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
  124238. VdbeComment((v, "LIKE loop counter"));
  124239. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  124240. /* iLikeRepCntr actually stores 2x the counter register number. The
  124241. ** bottom bit indicates whether the search order is ASC or DESC. */
  124242. testcase( bRev );
  124243. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  124244. assert( (bRev & ~1)==0 );
  124245. pLevel->iLikeRepCntr <<=1;
  124246. pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
  124247. }
  124248. #endif
  124249. if( pRangeStart==0 ){
  124250. j = pIdx->aiColumn[nEq];
  124251. if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
  124252. bSeekPastNull = 1;
  124253. }
  124254. }
  124255. }
  124256. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  124257. /* If we are doing a reverse order scan on an ascending index, or
  124258. ** a forward order scan on a descending index, interchange the
  124259. ** start and end terms (pRangeStart and pRangeEnd).
  124260. */
  124261. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  124262. || (bRev && pIdx->nKeyCol==nEq)
  124263. ){
  124264. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  124265. SWAP(u8, bSeekPastNull, bStopAtNull);
  124266. SWAP(u8, nBtm, nTop);
  124267. }
  124268. /* Generate code to evaluate all constraint terms using == or IN
  124269. ** and store the values of those terms in an array of registers
  124270. ** starting at regBase.
  124271. */
  124272. codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
  124273. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  124274. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  124275. if( zStartAff && nTop ){
  124276. zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
  124277. }
  124278. addrNxt = pLevel->addrNxt;
  124279. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  124280. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  124281. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  124282. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  124283. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  124284. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  124285. start_constraints = pRangeStart || nEq>0;
  124286. /* Seek the index cursor to the start of the range. */
  124287. nConstraint = nEq;
  124288. if( pRangeStart ){
  124289. Expr *pRight = pRangeStart->pExpr->pRight;
  124290. codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
  124291. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  124292. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  124293. && sqlite3ExprCanBeNull(pRight)
  124294. ){
  124295. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  124296. VdbeCoverage(v);
  124297. }
  124298. if( zStartAff ){
  124299. updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
  124300. }
  124301. nConstraint += nBtm;
  124302. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  124303. if( sqlite3ExprIsVector(pRight)==0 ){
  124304. disableTerm(pLevel, pRangeStart);
  124305. }else{
  124306. startEq = 1;
  124307. }
  124308. bSeekPastNull = 0;
  124309. }else if( bSeekPastNull ){
  124310. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  124311. nConstraint++;
  124312. startEq = 0;
  124313. start_constraints = 1;
  124314. }
  124315. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  124316. if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
  124317. /* The skip-scan logic inside the call to codeAllEqualityConstraints()
  124318. ** above has already left the cursor sitting on the correct row,
  124319. ** so no further seeking is needed */
  124320. }else{
  124321. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  124322. assert( op!=0 );
  124323. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  124324. VdbeCoverage(v);
  124325. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  124326. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  124327. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  124328. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  124329. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  124330. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  124331. }
  124332. /* Load the value for the inequality constraint at the end of the
  124333. ** range (if any).
  124334. */
  124335. nConstraint = nEq;
  124336. if( pRangeEnd ){
  124337. Expr *pRight = pRangeEnd->pExpr->pRight;
  124338. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  124339. codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
  124340. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  124341. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  124342. && sqlite3ExprCanBeNull(pRight)
  124343. ){
  124344. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  124345. VdbeCoverage(v);
  124346. }
  124347. if( zEndAff ){
  124348. updateRangeAffinityStr(pRight, nTop, zEndAff);
  124349. codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
  124350. }else{
  124351. assert( pParse->db->mallocFailed );
  124352. }
  124353. nConstraint += nTop;
  124354. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  124355. if( sqlite3ExprIsVector(pRight)==0 ){
  124356. disableTerm(pLevel, pRangeEnd);
  124357. }else{
  124358. endEq = 1;
  124359. }
  124360. }else if( bStopAtNull ){
  124361. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  124362. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  124363. endEq = 0;
  124364. nConstraint++;
  124365. }
  124366. sqlite3DbFree(db, zStartAff);
  124367. sqlite3DbFree(db, zEndAff);
  124368. /* Top of the loop body */
  124369. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  124370. /* Check if the index cursor is past the end of the range. */
  124371. if( nConstraint ){
  124372. op = aEndOp[bRev*2 + endEq];
  124373. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  124374. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  124375. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  124376. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  124377. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  124378. }
  124379. /* Seek the table cursor, if required */
  124380. if( omitTable ){
  124381. /* pIdx is a covering index. No need to access the main table. */
  124382. }else if( HasRowid(pIdx->pTable) ){
  124383. if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE) || (
  124384. (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)
  124385. && (pWInfo->eOnePass==ONEPASS_SINGLE)
  124386. )){
  124387. iRowidReg = ++pParse->nMem;
  124388. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  124389. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  124390. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  124391. VdbeCoverage(v);
  124392. }else{
  124393. codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
  124394. }
  124395. }else if( iCur!=iIdxCur ){
  124396. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  124397. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  124398. for(j=0; j<pPk->nKeyCol; j++){
  124399. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  124400. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  124401. }
  124402. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  124403. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  124404. }
  124405. /* If pIdx is an index on one or more expressions, then look through
  124406. ** all the expressions in pWInfo and try to transform matching expressions
  124407. ** into reference to index columns.
  124408. */
  124409. whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
  124410. /* Record the instruction used to terminate the loop. */
  124411. if( pLoop->wsFlags & WHERE_ONEROW ){
  124412. pLevel->op = OP_Noop;
  124413. }else if( bRev ){
  124414. pLevel->op = OP_Prev;
  124415. }else{
  124416. pLevel->op = OP_Next;
  124417. }
  124418. pLevel->p1 = iIdxCur;
  124419. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  124420. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  124421. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  124422. }else{
  124423. assert( pLevel->p5==0 );
  124424. }
  124425. if( omitTable ) pIdx = 0;
  124426. }else
  124427. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  124428. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  124429. /* Case 5: Two or more separately indexed terms connected by OR
  124430. **
  124431. ** Example:
  124432. **
  124433. ** CREATE TABLE t1(a,b,c,d);
  124434. ** CREATE INDEX i1 ON t1(a);
  124435. ** CREATE INDEX i2 ON t1(b);
  124436. ** CREATE INDEX i3 ON t1(c);
  124437. **
  124438. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  124439. **
  124440. ** In the example, there are three indexed terms connected by OR.
  124441. ** The top of the loop looks like this:
  124442. **
  124443. ** Null 1 # Zero the rowset in reg 1
  124444. **
  124445. ** Then, for each indexed term, the following. The arguments to
  124446. ** RowSetTest are such that the rowid of the current row is inserted
  124447. ** into the RowSet. If it is already present, control skips the
  124448. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  124449. **
  124450. ** sqlite3WhereBegin(<term>)
  124451. ** RowSetTest # Insert rowid into rowset
  124452. ** Gosub 2 A
  124453. ** sqlite3WhereEnd()
  124454. **
  124455. ** Following the above, code to terminate the loop. Label A, the target
  124456. ** of the Gosub above, jumps to the instruction right after the Goto.
  124457. **
  124458. ** Null 1 # Zero the rowset in reg 1
  124459. ** Goto B # The loop is finished.
  124460. **
  124461. ** A: <loop body> # Return data, whatever.
  124462. **
  124463. ** Return 2 # Jump back to the Gosub
  124464. **
  124465. ** B: <after the loop>
  124466. **
  124467. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  124468. ** use an ephemeral index instead of a RowSet to record the primary
  124469. ** keys of the rows we have already seen.
  124470. **
  124471. */
  124472. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  124473. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  124474. Index *pCov = 0; /* Potential covering index (or NULL) */
  124475. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  124476. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  124477. int regRowset = 0; /* Register for RowSet object */
  124478. int regRowid = 0; /* Register holding rowid */
  124479. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  124480. int iRetInit; /* Address of regReturn init */
  124481. int untestedTerms = 0; /* Some terms not completely tested */
  124482. int ii; /* Loop counter */
  124483. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  124484. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  124485. Table *pTab = pTabItem->pTab;
  124486. pTerm = pLoop->aLTerm[0];
  124487. assert( pTerm!=0 );
  124488. assert( pTerm->eOperator & WO_OR );
  124489. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  124490. pOrWc = &pTerm->u.pOrInfo->wc;
  124491. pLevel->op = OP_Return;
  124492. pLevel->p1 = regReturn;
  124493. /* Set up a new SrcList in pOrTab containing the table being scanned
  124494. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  124495. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  124496. */
  124497. if( pWInfo->nLevel>1 ){
  124498. int nNotReady; /* The number of notReady tables */
  124499. struct SrcList_item *origSrc; /* Original list of tables */
  124500. nNotReady = pWInfo->nLevel - iLevel - 1;
  124501. pOrTab = sqlite3StackAllocRaw(db,
  124502. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  124503. if( pOrTab==0 ) return notReady;
  124504. pOrTab->nAlloc = (u8)(nNotReady + 1);
  124505. pOrTab->nSrc = pOrTab->nAlloc;
  124506. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  124507. origSrc = pWInfo->pTabList->a;
  124508. for(k=1; k<=nNotReady; k++){
  124509. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  124510. }
  124511. }else{
  124512. pOrTab = pWInfo->pTabList;
  124513. }
  124514. /* Initialize the rowset register to contain NULL. An SQL NULL is
  124515. ** equivalent to an empty rowset. Or, create an ephemeral index
  124516. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  124517. **
  124518. ** Also initialize regReturn to contain the address of the instruction
  124519. ** immediately following the OP_Return at the bottom of the loop. This
  124520. ** is required in a few obscure LEFT JOIN cases where control jumps
  124521. ** over the top of the loop into the body of it. In this case the
  124522. ** correct response for the end-of-loop code (the OP_Return) is to
  124523. ** fall through to the next instruction, just as an OP_Next does if
  124524. ** called on an uninitialized cursor.
  124525. */
  124526. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  124527. if( HasRowid(pTab) ){
  124528. regRowset = ++pParse->nMem;
  124529. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  124530. }else{
  124531. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  124532. regRowset = pParse->nTab++;
  124533. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  124534. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  124535. }
  124536. regRowid = ++pParse->nMem;
  124537. }
  124538. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  124539. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  124540. ** Then for every term xN, evaluate as the subexpression: xN AND z
  124541. ** That way, terms in y that are factored into the disjunction will
  124542. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  124543. **
  124544. ** Actually, each subexpression is converted to "xN AND w" where w is
  124545. ** the "interesting" terms of z - terms that did not originate in the
  124546. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  124547. ** indices.
  124548. **
  124549. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  124550. ** is not contained in the ON clause of a LEFT JOIN.
  124551. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  124552. */
  124553. if( pWC->nTerm>1 ){
  124554. int iTerm;
  124555. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  124556. Expr *pExpr = pWC->a[iTerm].pExpr;
  124557. if( &pWC->a[iTerm] == pTerm ) continue;
  124558. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  124559. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  124560. testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
  124561. if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
  124562. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  124563. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  124564. pExpr = sqlite3ExprDup(db, pExpr, 0);
  124565. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  124566. }
  124567. if( pAndExpr ){
  124568. pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr);
  124569. }
  124570. }
  124571. /* Run a separate WHERE clause for each term of the OR clause. After
  124572. ** eliminating duplicates from other WHERE clauses, the action for each
  124573. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  124574. */
  124575. wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
  124576. for(ii=0; ii<pOrWc->nTerm; ii++){
  124577. WhereTerm *pOrTerm = &pOrWc->a[ii];
  124578. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  124579. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  124580. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  124581. int jmp1 = 0; /* Address of jump operation */
  124582. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  124583. pAndExpr->pLeft = pOrExpr;
  124584. pOrExpr = pAndExpr;
  124585. }
  124586. /* Loop through table entries that match term pOrTerm. */
  124587. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  124588. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  124589. wctrlFlags, iCovCur);
  124590. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  124591. if( pSubWInfo ){
  124592. WhereLoop *pSubLoop;
  124593. int addrExplain = sqlite3WhereExplainOneScan(
  124594. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  124595. );
  124596. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  124597. /* This is the sub-WHERE clause body. First skip over
  124598. ** duplicate rows from prior sub-WHERE clauses, and record the
  124599. ** rowid (or PRIMARY KEY) for the current row so that the same
  124600. ** row will be skipped in subsequent sub-WHERE clauses.
  124601. */
  124602. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  124603. int r;
  124604. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  124605. if( HasRowid(pTab) ){
  124606. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  124607. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  124608. r,iSet);
  124609. VdbeCoverage(v);
  124610. }else{
  124611. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  124612. int nPk = pPk->nKeyCol;
  124613. int iPk;
  124614. /* Read the PK into an array of temp registers. */
  124615. r = sqlite3GetTempRange(pParse, nPk);
  124616. for(iPk=0; iPk<nPk; iPk++){
  124617. int iCol = pPk->aiColumn[iPk];
  124618. sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
  124619. }
  124620. /* Check if the temp table already contains this key. If so,
  124621. ** the row has already been included in the result set and
  124622. ** can be ignored (by jumping past the Gosub below). Otherwise,
  124623. ** insert the key into the temp table and proceed with processing
  124624. ** the row.
  124625. **
  124626. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  124627. ** is zero, assume that the key cannot already be present in
  124628. ** the temp table. And if iSet is -1, assume that there is no
  124629. ** need to insert the key into the temp table, as it will never
  124630. ** be tested for. */
  124631. if( iSet ){
  124632. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  124633. VdbeCoverage(v);
  124634. }
  124635. if( iSet>=0 ){
  124636. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  124637. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
  124638. r, nPk);
  124639. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  124640. }
  124641. /* Release the array of temp registers */
  124642. sqlite3ReleaseTempRange(pParse, r, nPk);
  124643. }
  124644. }
  124645. /* Invoke the main loop body as a subroutine */
  124646. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  124647. /* Jump here (skipping the main loop body subroutine) if the
  124648. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  124649. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  124650. /* The pSubWInfo->untestedTerms flag means that this OR term
  124651. ** contained one or more AND term from a notReady table. The
  124652. ** terms from the notReady table could not be tested and will
  124653. ** need to be tested later.
  124654. */
  124655. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  124656. /* If all of the OR-connected terms are optimized using the same
  124657. ** index, and the index is opened using the same cursor number
  124658. ** by each call to sqlite3WhereBegin() made by this loop, it may
  124659. ** be possible to use that index as a covering index.
  124660. **
  124661. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  124662. ** uses an index, and this is either the first OR-connected term
  124663. ** processed or the index is the same as that used by all previous
  124664. ** terms, set pCov to the candidate covering index. Otherwise, set
  124665. ** pCov to NULL to indicate that no candidate covering index will
  124666. ** be available.
  124667. */
  124668. pSubLoop = pSubWInfo->a[0].pWLoop;
  124669. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  124670. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  124671. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  124672. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  124673. ){
  124674. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  124675. pCov = pSubLoop->u.btree.pIndex;
  124676. }else{
  124677. pCov = 0;
  124678. }
  124679. /* Finish the loop through table entries that match term pOrTerm. */
  124680. sqlite3WhereEnd(pSubWInfo);
  124681. }
  124682. }
  124683. }
  124684. pLevel->u.pCovidx = pCov;
  124685. if( pCov ) pLevel->iIdxCur = iCovCur;
  124686. if( pAndExpr ){
  124687. pAndExpr->pLeft = 0;
  124688. sqlite3ExprDelete(db, pAndExpr);
  124689. }
  124690. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  124691. sqlite3VdbeGoto(v, pLevel->addrBrk);
  124692. sqlite3VdbeResolveLabel(v, iLoopBody);
  124693. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  124694. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  124695. }else
  124696. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  124697. {
  124698. /* Case 6: There is no usable index. We must do a complete
  124699. ** scan of the entire table.
  124700. */
  124701. static const u8 aStep[] = { OP_Next, OP_Prev };
  124702. static const u8 aStart[] = { OP_Rewind, OP_Last };
  124703. assert( bRev==0 || bRev==1 );
  124704. if( pTabItem->fg.isRecursive ){
  124705. /* Tables marked isRecursive have only a single row that is stored in
  124706. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  124707. pLevel->op = OP_Noop;
  124708. }else{
  124709. codeCursorHint(pTabItem, pWInfo, pLevel, 0);
  124710. pLevel->op = aStep[bRev];
  124711. pLevel->p1 = iCur;
  124712. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
  124713. VdbeCoverageIf(v, bRev==0);
  124714. VdbeCoverageIf(v, bRev!=0);
  124715. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  124716. }
  124717. }
  124718. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  124719. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  124720. #endif
  124721. /* Insert code to test every subexpression that can be completely
  124722. ** computed using the current set of tables.
  124723. **
  124724. ** This loop may run between one and three times, depending on the
  124725. ** constraints to be generated. The value of stack variable iLoop
  124726. ** determines the constraints coded by each iteration, as follows:
  124727. **
  124728. ** iLoop==1: Code only expressions that are entirely covered by pIdx.
  124729. ** iLoop==2: Code remaining expressions that do not contain correlated
  124730. ** sub-queries.
  124731. ** iLoop==3: Code all remaining expressions.
  124732. **
  124733. ** An effort is made to skip unnecessary iterations of the loop.
  124734. */
  124735. iLoop = (pIdx ? 1 : 2);
  124736. do{
  124737. int iNext = 0; /* Next value for iLoop */
  124738. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  124739. Expr *pE;
  124740. int skipLikeAddr = 0;
  124741. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  124742. testcase( pTerm->wtFlags & TERM_CODED );
  124743. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  124744. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  124745. testcase( pWInfo->untestedTerms==0
  124746. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
  124747. pWInfo->untestedTerms = 1;
  124748. continue;
  124749. }
  124750. pE = pTerm->pExpr;
  124751. assert( pE!=0 );
  124752. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  124753. continue;
  124754. }
  124755. if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
  124756. iNext = 2;
  124757. continue;
  124758. }
  124759. if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
  124760. if( iNext==0 ) iNext = 3;
  124761. continue;
  124762. }
  124763. if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
  124764. /* If the TERM_LIKECOND flag is set, that means that the range search
  124765. ** is sufficient to guarantee that the LIKE operator is true, so we
  124766. ** can skip the call to the like(A,B) function. But this only works
  124767. ** for strings. So do not skip the call to the function on the pass
  124768. ** that compares BLOBs. */
  124769. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  124770. continue;
  124771. #else
  124772. u32 x = pLevel->iLikeRepCntr;
  124773. if( x>0 ){
  124774. skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
  124775. }
  124776. VdbeCoverage(v);
  124777. #endif
  124778. }
  124779. #ifdef WHERETRACE_ENABLED /* 0xffff */
  124780. if( sqlite3WhereTrace ){
  124781. VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
  124782. pWC->nTerm-j, pTerm, iLoop));
  124783. }
  124784. #endif
  124785. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  124786. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  124787. pTerm->wtFlags |= TERM_CODED;
  124788. }
  124789. iLoop = iNext;
  124790. }while( iLoop>0 );
  124791. /* Insert code to test for implied constraints based on transitivity
  124792. ** of the "==" operator.
  124793. **
  124794. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  124795. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  124796. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  124797. ** the implied "t1.a=123" constraint.
  124798. */
  124799. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  124800. Expr *pE, sEAlt;
  124801. WhereTerm *pAlt;
  124802. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  124803. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  124804. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  124805. if( pTerm->leftCursor!=iCur ) continue;
  124806. if( pLevel->iLeftJoin ) continue;
  124807. pE = pTerm->pExpr;
  124808. assert( !ExprHasProperty(pE, EP_FromJoin) );
  124809. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  124810. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  124811. WO_EQ|WO_IN|WO_IS, 0);
  124812. if( pAlt==0 ) continue;
  124813. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  124814. if( (pAlt->eOperator & WO_IN)
  124815. && (pAlt->pExpr->flags & EP_xIsSelect)
  124816. && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
  124817. ){
  124818. continue;
  124819. }
  124820. testcase( pAlt->eOperator & WO_EQ );
  124821. testcase( pAlt->eOperator & WO_IS );
  124822. testcase( pAlt->eOperator & WO_IN );
  124823. VdbeModuleComment((v, "begin transitive constraint"));
  124824. sEAlt = *pAlt->pExpr;
  124825. sEAlt.pLeft = pE->pLeft;
  124826. sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
  124827. }
  124828. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  124829. ** at least one row of the right table has matched the left table.
  124830. */
  124831. if( pLevel->iLeftJoin ){
  124832. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  124833. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  124834. VdbeComment((v, "record LEFT JOIN hit"));
  124835. sqlite3ExprCacheClear(pParse);
  124836. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  124837. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  124838. testcase( pTerm->wtFlags & TERM_CODED );
  124839. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  124840. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  124841. assert( pWInfo->untestedTerms );
  124842. continue;
  124843. }
  124844. assert( pTerm->pExpr );
  124845. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  124846. pTerm->wtFlags |= TERM_CODED;
  124847. }
  124848. }
  124849. return pLevel->notReady;
  124850. }
  124851. /************** End of wherecode.c *******************************************/
  124852. /************** Begin file whereexpr.c ***************************************/
  124853. /*
  124854. ** 2015-06-08
  124855. **
  124856. ** The author disclaims copyright to this source code. In place of
  124857. ** a legal notice, here is a blessing:
  124858. **
  124859. ** May you do good and not evil.
  124860. ** May you find forgiveness for yourself and forgive others.
  124861. ** May you share freely, never taking more than you give.
  124862. **
  124863. *************************************************************************
  124864. ** This module contains C code that generates VDBE code used to process
  124865. ** the WHERE clause of SQL statements.
  124866. **
  124867. ** This file was originally part of where.c but was split out to improve
  124868. ** readability and editabiliity. This file contains utility routines for
  124869. ** analyzing Expr objects in the WHERE clause.
  124870. */
  124871. /* #include "sqliteInt.h" */
  124872. /* #include "whereInt.h" */
  124873. /* Forward declarations */
  124874. static void exprAnalyze(SrcList*, WhereClause*, int);
  124875. /*
  124876. ** Deallocate all memory associated with a WhereOrInfo object.
  124877. */
  124878. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  124879. sqlite3WhereClauseClear(&p->wc);
  124880. sqlite3DbFree(db, p);
  124881. }
  124882. /*
  124883. ** Deallocate all memory associated with a WhereAndInfo object.
  124884. */
  124885. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  124886. sqlite3WhereClauseClear(&p->wc);
  124887. sqlite3DbFree(db, p);
  124888. }
  124889. /*
  124890. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  124891. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  124892. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  124893. ** 0 is returned if the new WhereTerm could not be added due to a memory
  124894. ** allocation error. The memory allocation failure will be recorded in
  124895. ** the db->mallocFailed flag so that higher-level functions can detect it.
  124896. **
  124897. ** This routine will increase the size of the pWC->a[] array as necessary.
  124898. **
  124899. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  124900. ** for freeing the expression p is assumed by the WhereClause object pWC.
  124901. ** This is true even if this routine fails to allocate a new WhereTerm.
  124902. **
  124903. ** WARNING: This routine might reallocate the space used to store
  124904. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  124905. ** calling this routine. Such pointers may be reinitialized by referencing
  124906. ** the pWC->a[] array.
  124907. */
  124908. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  124909. WhereTerm *pTerm;
  124910. int idx;
  124911. testcase( wtFlags & TERM_VIRTUAL );
  124912. if( pWC->nTerm>=pWC->nSlot ){
  124913. WhereTerm *pOld = pWC->a;
  124914. sqlite3 *db = pWC->pWInfo->pParse->db;
  124915. pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  124916. if( pWC->a==0 ){
  124917. if( wtFlags & TERM_DYNAMIC ){
  124918. sqlite3ExprDelete(db, p);
  124919. }
  124920. pWC->a = pOld;
  124921. return 0;
  124922. }
  124923. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  124924. if( pOld!=pWC->aStatic ){
  124925. sqlite3DbFree(db, pOld);
  124926. }
  124927. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  124928. }
  124929. pTerm = &pWC->a[idx = pWC->nTerm++];
  124930. if( p && ExprHasProperty(p, EP_Unlikely) ){
  124931. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  124932. }else{
  124933. pTerm->truthProb = 1;
  124934. }
  124935. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  124936. pTerm->wtFlags = wtFlags;
  124937. pTerm->pWC = pWC;
  124938. pTerm->iParent = -1;
  124939. memset(&pTerm->eOperator, 0,
  124940. sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
  124941. return idx;
  124942. }
  124943. /*
  124944. ** Return TRUE if the given operator is one of the operators that is
  124945. ** allowed for an indexable WHERE clause term. The allowed operators are
  124946. ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
  124947. */
  124948. static int allowedOp(int op){
  124949. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  124950. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  124951. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  124952. assert( TK_GE==TK_EQ+4 );
  124953. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  124954. }
  124955. /*
  124956. ** Commute a comparison operator. Expressions of the form "X op Y"
  124957. ** are converted into "Y op X".
  124958. **
  124959. ** If left/right precedence rules come into play when determining the
  124960. ** collating sequence, then COLLATE operators are adjusted to ensure
  124961. ** that the collating sequence does not change. For example:
  124962. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  124963. ** the left hand side of a comparison overrides any collation sequence
  124964. ** attached to the right. For the same reason the EP_Collate flag
  124965. ** is not commuted.
  124966. */
  124967. static void exprCommute(Parse *pParse, Expr *pExpr){
  124968. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  124969. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  124970. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  124971. if( expRight==expLeft ){
  124972. /* Either X and Y both have COLLATE operator or neither do */
  124973. if( expRight ){
  124974. /* Both X and Y have COLLATE operators. Make sure X is always
  124975. ** used by clearing the EP_Collate flag from Y. */
  124976. pExpr->pRight->flags &= ~EP_Collate;
  124977. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  124978. /* Neither X nor Y have COLLATE operators, but X has a non-default
  124979. ** collating sequence. So add the EP_Collate marker on X to cause
  124980. ** it to be searched first. */
  124981. pExpr->pLeft->flags |= EP_Collate;
  124982. }
  124983. }
  124984. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  124985. if( pExpr->op>=TK_GT ){
  124986. assert( TK_LT==TK_GT+2 );
  124987. assert( TK_GE==TK_LE+2 );
  124988. assert( TK_GT>TK_EQ );
  124989. assert( TK_GT<TK_LE );
  124990. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  124991. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  124992. }
  124993. }
  124994. /*
  124995. ** Translate from TK_xx operator to WO_xx bitmask.
  124996. */
  124997. static u16 operatorMask(int op){
  124998. u16 c;
  124999. assert( allowedOp(op) );
  125000. if( op==TK_IN ){
  125001. c = WO_IN;
  125002. }else if( op==TK_ISNULL ){
  125003. c = WO_ISNULL;
  125004. }else if( op==TK_IS ){
  125005. c = WO_IS;
  125006. }else{
  125007. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  125008. c = (u16)(WO_EQ<<(op-TK_EQ));
  125009. }
  125010. assert( op!=TK_ISNULL || c==WO_ISNULL );
  125011. assert( op!=TK_IN || c==WO_IN );
  125012. assert( op!=TK_EQ || c==WO_EQ );
  125013. assert( op!=TK_LT || c==WO_LT );
  125014. assert( op!=TK_LE || c==WO_LE );
  125015. assert( op!=TK_GT || c==WO_GT );
  125016. assert( op!=TK_GE || c==WO_GE );
  125017. assert( op!=TK_IS || c==WO_IS );
  125018. return c;
  125019. }
  125020. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  125021. /*
  125022. ** Check to see if the given expression is a LIKE or GLOB operator that
  125023. ** can be optimized using inequality constraints. Return TRUE if it is
  125024. ** so and false if not.
  125025. **
  125026. ** In order for the operator to be optimizible, the RHS must be a string
  125027. ** literal that does not begin with a wildcard. The LHS must be a column
  125028. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  125029. ** that virtual tables cannot participate in the LIKE optimization.) The
  125030. ** collating sequence for the column on the LHS must be appropriate for
  125031. ** the operator.
  125032. */
  125033. static int isLikeOrGlob(
  125034. Parse *pParse, /* Parsing and code generating context */
  125035. Expr *pExpr, /* Test this expression */
  125036. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  125037. int *pisComplete, /* True if the only wildcard is % in the last character */
  125038. int *pnoCase /* True if uppercase is equivalent to lowercase */
  125039. ){
  125040. const u8 *z = 0; /* String on RHS of LIKE operator */
  125041. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  125042. ExprList *pList; /* List of operands to the LIKE operator */
  125043. int c; /* One character in z[] */
  125044. int cnt; /* Number of non-wildcard prefix characters */
  125045. char wc[4]; /* Wildcard characters */
  125046. sqlite3 *db = pParse->db; /* Database connection */
  125047. sqlite3_value *pVal = 0;
  125048. int op; /* Opcode of pRight */
  125049. int rc; /* Result code to return */
  125050. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  125051. return 0;
  125052. }
  125053. #ifdef SQLITE_EBCDIC
  125054. if( *pnoCase ) return 0;
  125055. #endif
  125056. pList = pExpr->x.pList;
  125057. pLeft = pList->a[1].pExpr;
  125058. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  125059. op = pRight->op;
  125060. if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  125061. Vdbe *pReprepare = pParse->pReprepare;
  125062. int iCol = pRight->iColumn;
  125063. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  125064. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  125065. z = sqlite3_value_text(pVal);
  125066. }
  125067. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  125068. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  125069. }else if( op==TK_STRING ){
  125070. z = (u8*)pRight->u.zToken;
  125071. }
  125072. if( z ){
  125073. /* If the RHS begins with a digit or a minus sign, then the LHS must
  125074. ** be an ordinary column (not a virtual table column) with TEXT affinity.
  125075. ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
  125076. ** even though "lhs LIKE rhs" is true. But if the RHS does not start
  125077. ** with a digit or '-', then "lhs LIKE rhs" will always be false if
  125078. ** the LHS is numeric and so the optimization still works.
  125079. */
  125080. if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
  125081. if( pLeft->op!=TK_COLUMN
  125082. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  125083. || IsVirtual(pLeft->pTab) /* Value might be numeric */
  125084. ){
  125085. sqlite3ValueFree(pVal);
  125086. return 0;
  125087. }
  125088. }
  125089. /* Count the number of prefix characters prior to the first wildcard */
  125090. cnt = 0;
  125091. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  125092. cnt++;
  125093. if( c==wc[3] && z[cnt]!=0 ) cnt++;
  125094. }
  125095. /* The optimization is possible only if (1) the pattern does not begin
  125096. ** with a wildcard and if (2) the non-wildcard prefix does not end with
  125097. ** an (illegal 0xff) character. The second condition is necessary so
  125098. ** that we can increment the prefix key to find an upper bound for the
  125099. ** range search.
  125100. */
  125101. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  125102. Expr *pPrefix;
  125103. /* A "complete" match if the pattern ends with "*" or "%" */
  125104. *pisComplete = c==wc[0] && z[cnt+1]==0;
  125105. /* Get the pattern prefix. Remove all escapes from the prefix. */
  125106. pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
  125107. if( pPrefix ){
  125108. int iFrom, iTo;
  125109. char *zNew = pPrefix->u.zToken;
  125110. zNew[cnt] = 0;
  125111. for(iFrom=iTo=0; iFrom<cnt; iFrom++){
  125112. if( zNew[iFrom]==wc[3] ) iFrom++;
  125113. zNew[iTo++] = zNew[iFrom];
  125114. }
  125115. zNew[iTo] = 0;
  125116. }
  125117. *ppPrefix = pPrefix;
  125118. /* If the RHS pattern is a bound parameter, make arrangements to
  125119. ** reprepare the statement when that parameter is rebound */
  125120. if( op==TK_VARIABLE ){
  125121. Vdbe *v = pParse->pVdbe;
  125122. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  125123. if( *pisComplete && pRight->u.zToken[1] ){
  125124. /* If the rhs of the LIKE expression is a variable, and the current
  125125. ** value of the variable means there is no need to invoke the LIKE
  125126. ** function, then no OP_Variable will be added to the program.
  125127. ** This causes problems for the sqlite3_bind_parameter_name()
  125128. ** API. To work around them, add a dummy OP_Variable here.
  125129. */
  125130. int r1 = sqlite3GetTempReg(pParse);
  125131. sqlite3ExprCodeTarget(pParse, pRight, r1);
  125132. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  125133. sqlite3ReleaseTempReg(pParse, r1);
  125134. }
  125135. }
  125136. }else{
  125137. z = 0;
  125138. }
  125139. }
  125140. rc = (z!=0);
  125141. sqlite3ValueFree(pVal);
  125142. return rc;
  125143. }
  125144. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  125145. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125146. /*
  125147. ** Check to see if the pExpr expression is a form that needs to be passed
  125148. ** to the xBestIndex method of virtual tables. Forms of interest include:
  125149. **
  125150. ** Expression Virtual Table Operator
  125151. ** ----------------------- ---------------------------------
  125152. ** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
  125153. ** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
  125154. ** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
  125155. ** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
  125156. ** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
  125157. ** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
  125158. ** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
  125159. ** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
  125160. ** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
  125161. **
  125162. ** In every case, "column" must be a column of a virtual table. If there
  125163. ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
  125164. ** "expr" expression (even though in forms (6) and (8) the column is on the
  125165. ** right and the expression is on the left). Also set *peOp2 to the
  125166. ** appropriate virtual table operator. The return value is 1 or 2 if there
  125167. ** is a match. The usual return is 1, but if the RHS is also a column
  125168. ** of virtual table in forms (5) or (7) then return 2.
  125169. **
  125170. ** If the expression matches none of the patterns above, return 0.
  125171. */
  125172. static int isAuxiliaryVtabOperator(
  125173. Expr *pExpr, /* Test this expression */
  125174. unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
  125175. Expr **ppLeft, /* Column expression to left of MATCH/op2 */
  125176. Expr **ppRight /* Expression to left of MATCH/op2 */
  125177. ){
  125178. if( pExpr->op==TK_FUNCTION ){
  125179. static const struct Op2 {
  125180. const char *zOp;
  125181. unsigned char eOp2;
  125182. } aOp[] = {
  125183. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  125184. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  125185. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  125186. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  125187. };
  125188. ExprList *pList;
  125189. Expr *pCol; /* Column reference */
  125190. int i;
  125191. pList = pExpr->x.pList;
  125192. if( pList==0 || pList->nExpr!=2 ){
  125193. return 0;
  125194. }
  125195. pCol = pList->a[1].pExpr;
  125196. if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
  125197. return 0;
  125198. }
  125199. for(i=0; i<ArraySize(aOp); i++){
  125200. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  125201. *peOp2 = aOp[i].eOp2;
  125202. *ppRight = pList->a[0].pExpr;
  125203. *ppLeft = pCol;
  125204. return 1;
  125205. }
  125206. }
  125207. }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
  125208. int res = 0;
  125209. Expr *pLeft = pExpr->pLeft;
  125210. Expr *pRight = pExpr->pRight;
  125211. if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->pTab) ){
  125212. res++;
  125213. }
  125214. if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->pTab) ){
  125215. res++;
  125216. SWAP(Expr*, pLeft, pRight);
  125217. }
  125218. *ppLeft = pLeft;
  125219. *ppRight = pRight;
  125220. if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
  125221. if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
  125222. if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
  125223. return res;
  125224. }
  125225. return 0;
  125226. }
  125227. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  125228. /*
  125229. ** If the pBase expression originated in the ON or USING clause of
  125230. ** a join, then transfer the appropriate markings over to derived.
  125231. */
  125232. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  125233. if( pDerived ){
  125234. pDerived->flags |= pBase->flags & EP_FromJoin;
  125235. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  125236. }
  125237. }
  125238. /*
  125239. ** Mark term iChild as being a child of term iParent
  125240. */
  125241. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  125242. pWC->a[iChild].iParent = iParent;
  125243. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  125244. pWC->a[iParent].nChild++;
  125245. }
  125246. /*
  125247. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  125248. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  125249. ** the number of available subterms, return NULL.
  125250. */
  125251. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  125252. if( pTerm->eOperator!=WO_AND ){
  125253. return N==0 ? pTerm : 0;
  125254. }
  125255. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  125256. return &pTerm->u.pAndInfo->wc.a[N];
  125257. }
  125258. return 0;
  125259. }
  125260. /*
  125261. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  125262. ** two subterms are in disjunction - they are OR-ed together.
  125263. **
  125264. ** If these two terms are both of the form: "A op B" with the same
  125265. ** A and B values but different operators and if the operators are
  125266. ** compatible (if one is = and the other is <, for example) then
  125267. ** add a new virtual AND term to pWC that is the combination of the
  125268. ** two.
  125269. **
  125270. ** Some examples:
  125271. **
  125272. ** x<y OR x=y --> x<=y
  125273. ** x=y OR x=y --> x=y
  125274. ** x<=y OR x<y --> x<=y
  125275. **
  125276. ** The following is NOT generated:
  125277. **
  125278. ** x<y OR x>y --> x!=y
  125279. */
  125280. static void whereCombineDisjuncts(
  125281. SrcList *pSrc, /* the FROM clause */
  125282. WhereClause *pWC, /* The complete WHERE clause */
  125283. WhereTerm *pOne, /* First disjunct */
  125284. WhereTerm *pTwo /* Second disjunct */
  125285. ){
  125286. u16 eOp = pOne->eOperator | pTwo->eOperator;
  125287. sqlite3 *db; /* Database connection (for malloc) */
  125288. Expr *pNew; /* New virtual expression */
  125289. int op; /* Operator for the combined expression */
  125290. int idxNew; /* Index in pWC of the next virtual term */
  125291. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  125292. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  125293. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  125294. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  125295. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  125296. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  125297. if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  125298. if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
  125299. /* If we reach this point, it means the two subterms can be combined */
  125300. if( (eOp & (eOp-1))!=0 ){
  125301. if( eOp & (WO_LT|WO_LE) ){
  125302. eOp = WO_LE;
  125303. }else{
  125304. assert( eOp & (WO_GT|WO_GE) );
  125305. eOp = WO_GE;
  125306. }
  125307. }
  125308. db = pWC->pWInfo->pParse->db;
  125309. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  125310. if( pNew==0 ) return;
  125311. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  125312. pNew->op = op;
  125313. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  125314. exprAnalyze(pSrc, pWC, idxNew);
  125315. }
  125316. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  125317. /*
  125318. ** Analyze a term that consists of two or more OR-connected
  125319. ** subterms. So in:
  125320. **
  125321. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  125322. ** ^^^^^^^^^^^^^^^^^^^^
  125323. **
  125324. ** This routine analyzes terms such as the middle term in the above example.
  125325. ** A WhereOrTerm object is computed and attached to the term under
  125326. ** analysis, regardless of the outcome of the analysis. Hence:
  125327. **
  125328. ** WhereTerm.wtFlags |= TERM_ORINFO
  125329. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  125330. **
  125331. ** The term being analyzed must have two or more of OR-connected subterms.
  125332. ** A single subterm might be a set of AND-connected sub-subterms.
  125333. ** Examples of terms under analysis:
  125334. **
  125335. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  125336. ** (B) x=expr1 OR expr2=x OR x=expr3
  125337. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  125338. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  125339. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  125340. ** (F) x>A OR (x=A AND y>=B)
  125341. **
  125342. ** CASE 1:
  125343. **
  125344. ** If all subterms are of the form T.C=expr for some single column of C and
  125345. ** a single table T (as shown in example B above) then create a new virtual
  125346. ** term that is an equivalent IN expression. In other words, if the term
  125347. ** being analyzed is:
  125348. **
  125349. ** x = expr1 OR expr2 = x OR x = expr3
  125350. **
  125351. ** then create a new virtual term like this:
  125352. **
  125353. ** x IN (expr1,expr2,expr3)
  125354. **
  125355. ** CASE 2:
  125356. **
  125357. ** If there are exactly two disjuncts and one side has x>A and the other side
  125358. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  125359. ** WHERE clause of the form "x>=A". Example:
  125360. **
  125361. ** x>A OR (x=A AND y>B) adds: x>=A
  125362. **
  125363. ** The added conjunct can sometimes be helpful in query planning.
  125364. **
  125365. ** CASE 3:
  125366. **
  125367. ** If all subterms are indexable by a single table T, then set
  125368. **
  125369. ** WhereTerm.eOperator = WO_OR
  125370. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  125371. **
  125372. ** A subterm is "indexable" if it is of the form
  125373. ** "T.C <op> <expr>" where C is any column of table T and
  125374. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  125375. ** A subterm is also indexable if it is an AND of two or more
  125376. ** subsubterms at least one of which is indexable. Indexable AND
  125377. ** subterms have their eOperator set to WO_AND and they have
  125378. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  125379. **
  125380. ** From another point of view, "indexable" means that the subterm could
  125381. ** potentially be used with an index if an appropriate index exists.
  125382. ** This analysis does not consider whether or not the index exists; that
  125383. ** is decided elsewhere. This analysis only looks at whether subterms
  125384. ** appropriate for indexing exist.
  125385. **
  125386. ** All examples A through E above satisfy case 3. But if a term
  125387. ** also satisfies case 1 (such as B) we know that the optimizer will
  125388. ** always prefer case 1, so in that case we pretend that case 3 is not
  125389. ** satisfied.
  125390. **
  125391. ** It might be the case that multiple tables are indexable. For example,
  125392. ** (E) above is indexable on tables P, Q, and R.
  125393. **
  125394. ** Terms that satisfy case 3 are candidates for lookup by using
  125395. ** separate indices to find rowids for each subterm and composing
  125396. ** the union of all rowids using a RowSet object. This is similar
  125397. ** to "bitmap indices" in other database engines.
  125398. **
  125399. ** OTHERWISE:
  125400. **
  125401. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  125402. ** zero. This term is not useful for search.
  125403. */
  125404. static void exprAnalyzeOrTerm(
  125405. SrcList *pSrc, /* the FROM clause */
  125406. WhereClause *pWC, /* the complete WHERE clause */
  125407. int idxTerm /* Index of the OR-term to be analyzed */
  125408. ){
  125409. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  125410. Parse *pParse = pWInfo->pParse; /* Parser context */
  125411. sqlite3 *db = pParse->db; /* Database connection */
  125412. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  125413. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  125414. int i; /* Loop counters */
  125415. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  125416. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  125417. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  125418. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  125419. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  125420. /*
  125421. ** Break the OR clause into its separate subterms. The subterms are
  125422. ** stored in a WhereClause structure containing within the WhereOrInfo
  125423. ** object that is attached to the original OR clause term.
  125424. */
  125425. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  125426. assert( pExpr->op==TK_OR );
  125427. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  125428. if( pOrInfo==0 ) return;
  125429. pTerm->wtFlags |= TERM_ORINFO;
  125430. pOrWc = &pOrInfo->wc;
  125431. memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
  125432. sqlite3WhereClauseInit(pOrWc, pWInfo);
  125433. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  125434. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  125435. if( db->mallocFailed ) return;
  125436. assert( pOrWc->nTerm>=2 );
  125437. /*
  125438. ** Compute the set of tables that might satisfy cases 1 or 3.
  125439. */
  125440. indexable = ~(Bitmask)0;
  125441. chngToIN = ~(Bitmask)0;
  125442. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  125443. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  125444. WhereAndInfo *pAndInfo;
  125445. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  125446. chngToIN = 0;
  125447. pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
  125448. if( pAndInfo ){
  125449. WhereClause *pAndWC;
  125450. WhereTerm *pAndTerm;
  125451. int j;
  125452. Bitmask b = 0;
  125453. pOrTerm->u.pAndInfo = pAndInfo;
  125454. pOrTerm->wtFlags |= TERM_ANDINFO;
  125455. pOrTerm->eOperator = WO_AND;
  125456. pAndWC = &pAndInfo->wc;
  125457. memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
  125458. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  125459. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  125460. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  125461. pAndWC->pOuter = pWC;
  125462. if( !db->mallocFailed ){
  125463. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  125464. assert( pAndTerm->pExpr );
  125465. if( allowedOp(pAndTerm->pExpr->op)
  125466. || pAndTerm->eOperator==WO_AUX
  125467. ){
  125468. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  125469. }
  125470. }
  125471. }
  125472. indexable &= b;
  125473. }
  125474. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  125475. /* Skip this term for now. We revisit it when we process the
  125476. ** corresponding TERM_VIRTUAL term */
  125477. }else{
  125478. Bitmask b;
  125479. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  125480. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  125481. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  125482. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  125483. }
  125484. indexable &= b;
  125485. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  125486. chngToIN = 0;
  125487. }else{
  125488. chngToIN &= b;
  125489. }
  125490. }
  125491. }
  125492. /*
  125493. ** Record the set of tables that satisfy case 3. The set might be
  125494. ** empty.
  125495. */
  125496. pOrInfo->indexable = indexable;
  125497. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  125498. /* For a two-way OR, attempt to implementation case 2.
  125499. */
  125500. if( indexable && pOrWc->nTerm==2 ){
  125501. int iOne = 0;
  125502. WhereTerm *pOne;
  125503. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  125504. int iTwo = 0;
  125505. WhereTerm *pTwo;
  125506. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  125507. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  125508. }
  125509. }
  125510. }
  125511. /*
  125512. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  125513. ** we have to do some additional checking to see if case 1 really
  125514. ** is satisfied.
  125515. **
  125516. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  125517. ** that there is no possibility of transforming the OR clause into an
  125518. ** IN operator because one or more terms in the OR clause contain
  125519. ** something other than == on a column in the single table. The 1-bit
  125520. ** case means that every term of the OR clause is of the form
  125521. ** "table.column=expr" for some single table. The one bit that is set
  125522. ** will correspond to the common table. We still need to check to make
  125523. ** sure the same column is used on all terms. The 2-bit case is when
  125524. ** the all terms are of the form "table1.column=table2.column". It
  125525. ** might be possible to form an IN operator with either table1.column
  125526. ** or table2.column as the LHS if either is common to every term of
  125527. ** the OR clause.
  125528. **
  125529. ** Note that terms of the form "table.column1=table.column2" (the
  125530. ** same table on both sizes of the ==) cannot be optimized.
  125531. */
  125532. if( chngToIN ){
  125533. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  125534. int iColumn = -1; /* Column index on lhs of IN operator */
  125535. int iCursor = -1; /* Table cursor common to all terms */
  125536. int j = 0; /* Loop counter */
  125537. /* Search for a table and column that appears on one side or the
  125538. ** other of the == operator in every subterm. That table and column
  125539. ** will be recorded in iCursor and iColumn. There might not be any
  125540. ** such table and column. Set okToChngToIN if an appropriate table
  125541. ** and column is found but leave okToChngToIN false if not found.
  125542. */
  125543. for(j=0; j<2 && !okToChngToIN; j++){
  125544. pOrTerm = pOrWc->a;
  125545. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  125546. assert( pOrTerm->eOperator & WO_EQ );
  125547. pOrTerm->wtFlags &= ~TERM_OR_OK;
  125548. if( pOrTerm->leftCursor==iCursor ){
  125549. /* This is the 2-bit case and we are on the second iteration and
  125550. ** current term is from the first iteration. So skip this term. */
  125551. assert( j==1 );
  125552. continue;
  125553. }
  125554. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  125555. pOrTerm->leftCursor))==0 ){
  125556. /* This term must be of the form t1.a==t2.b where t2 is in the
  125557. ** chngToIN set but t1 is not. This term will be either preceded
  125558. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  125559. ** and use its inversion. */
  125560. testcase( pOrTerm->wtFlags & TERM_COPIED );
  125561. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  125562. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  125563. continue;
  125564. }
  125565. iColumn = pOrTerm->u.leftColumn;
  125566. iCursor = pOrTerm->leftCursor;
  125567. break;
  125568. }
  125569. if( i<0 ){
  125570. /* No candidate table+column was found. This can only occur
  125571. ** on the second iteration */
  125572. assert( j==1 );
  125573. assert( IsPowerOfTwo(chngToIN) );
  125574. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  125575. break;
  125576. }
  125577. testcase( j==1 );
  125578. /* We have found a candidate table and column. Check to see if that
  125579. ** table and column is common to every term in the OR clause */
  125580. okToChngToIN = 1;
  125581. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  125582. assert( pOrTerm->eOperator & WO_EQ );
  125583. if( pOrTerm->leftCursor!=iCursor ){
  125584. pOrTerm->wtFlags &= ~TERM_OR_OK;
  125585. }else if( pOrTerm->u.leftColumn!=iColumn ){
  125586. okToChngToIN = 0;
  125587. }else{
  125588. int affLeft, affRight;
  125589. /* If the right-hand side is also a column, then the affinities
  125590. ** of both right and left sides must be such that no type
  125591. ** conversions are required on the right. (Ticket #2249)
  125592. */
  125593. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  125594. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  125595. if( affRight!=0 && affRight!=affLeft ){
  125596. okToChngToIN = 0;
  125597. }else{
  125598. pOrTerm->wtFlags |= TERM_OR_OK;
  125599. }
  125600. }
  125601. }
  125602. }
  125603. /* At this point, okToChngToIN is true if original pTerm satisfies
  125604. ** case 1. In that case, construct a new virtual term that is
  125605. ** pTerm converted into an IN operator.
  125606. */
  125607. if( okToChngToIN ){
  125608. Expr *pDup; /* A transient duplicate expression */
  125609. ExprList *pList = 0; /* The RHS of the IN operator */
  125610. Expr *pLeft = 0; /* The LHS of the IN operator */
  125611. Expr *pNew; /* The complete IN operator */
  125612. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  125613. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  125614. assert( pOrTerm->eOperator & WO_EQ );
  125615. assert( pOrTerm->leftCursor==iCursor );
  125616. assert( pOrTerm->u.leftColumn==iColumn );
  125617. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  125618. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  125619. pLeft = pOrTerm->pExpr->pLeft;
  125620. }
  125621. assert( pLeft!=0 );
  125622. pDup = sqlite3ExprDup(db, pLeft, 0);
  125623. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
  125624. if( pNew ){
  125625. int idxNew;
  125626. transferJoinMarkings(pNew, pExpr);
  125627. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  125628. pNew->x.pList = pList;
  125629. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  125630. testcase( idxNew==0 );
  125631. exprAnalyze(pSrc, pWC, idxNew);
  125632. pTerm = &pWC->a[idxTerm];
  125633. markTermAsChild(pWC, idxNew, idxTerm);
  125634. }else{
  125635. sqlite3ExprListDelete(db, pList);
  125636. }
  125637. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
  125638. }
  125639. }
  125640. }
  125641. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  125642. /*
  125643. ** We already know that pExpr is a binary operator where both operands are
  125644. ** column references. This routine checks to see if pExpr is an equivalence
  125645. ** relation:
  125646. ** 1. The SQLITE_Transitive optimization must be enabled
  125647. ** 2. Must be either an == or an IS operator
  125648. ** 3. Not originating in the ON clause of an OUTER JOIN
  125649. ** 4. The affinities of A and B must be compatible
  125650. ** 5a. Both operands use the same collating sequence OR
  125651. ** 5b. The overall collating sequence is BINARY
  125652. ** If this routine returns TRUE, that means that the RHS can be substituted
  125653. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  125654. ** This is an optimization. No harm comes from returning 0. But if 1 is
  125655. ** returned when it should not be, then incorrect answers might result.
  125656. */
  125657. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  125658. char aff1, aff2;
  125659. CollSeq *pColl;
  125660. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  125661. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  125662. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  125663. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  125664. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  125665. if( aff1!=aff2
  125666. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  125667. ){
  125668. return 0;
  125669. }
  125670. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  125671. if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
  125672. return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
  125673. }
  125674. /*
  125675. ** Recursively walk the expressions of a SELECT statement and generate
  125676. ** a bitmask indicating which tables are used in that expression
  125677. ** tree.
  125678. */
  125679. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  125680. Bitmask mask = 0;
  125681. while( pS ){
  125682. SrcList *pSrc = pS->pSrc;
  125683. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  125684. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  125685. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  125686. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  125687. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  125688. if( ALWAYS(pSrc!=0) ){
  125689. int i;
  125690. for(i=0; i<pSrc->nSrc; i++){
  125691. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  125692. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  125693. if( pSrc->a[i].fg.isTabFunc ){
  125694. mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
  125695. }
  125696. }
  125697. }
  125698. pS = pS->pPrior;
  125699. }
  125700. return mask;
  125701. }
  125702. /*
  125703. ** Expression pExpr is one operand of a comparison operator that might
  125704. ** be useful for indexing. This routine checks to see if pExpr appears
  125705. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  125706. ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
  125707. ** number of the table that is indexed and aiCurCol[1] to the column number
  125708. ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
  125709. ** indexed.
  125710. **
  125711. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  125712. ** true even if that particular column is not indexed, because the column
  125713. ** might be added to an automatic index later.
  125714. */
  125715. static SQLITE_NOINLINE int exprMightBeIndexed2(
  125716. SrcList *pFrom, /* The FROM clause */
  125717. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  125718. int *aiCurCol, /* Write the referenced table cursor and column here */
  125719. Expr *pExpr /* An operand of a comparison operator */
  125720. ){
  125721. Index *pIdx;
  125722. int i;
  125723. int iCur;
  125724. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  125725. iCur = pFrom->a[i].iCursor;
  125726. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  125727. if( pIdx->aColExpr==0 ) continue;
  125728. for(i=0; i<pIdx->nKeyCol; i++){
  125729. if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
  125730. if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  125731. aiCurCol[0] = iCur;
  125732. aiCurCol[1] = XN_EXPR;
  125733. return 1;
  125734. }
  125735. }
  125736. }
  125737. return 0;
  125738. }
  125739. static int exprMightBeIndexed(
  125740. SrcList *pFrom, /* The FROM clause */
  125741. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  125742. int *aiCurCol, /* Write the referenced table cursor & column here */
  125743. Expr *pExpr, /* An operand of a comparison operator */
  125744. int op /* The specific comparison operator */
  125745. ){
  125746. /* If this expression is a vector to the left or right of a
  125747. ** inequality constraint (>, <, >= or <=), perform the processing
  125748. ** on the first element of the vector. */
  125749. assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
  125750. assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
  125751. assert( op<=TK_GE );
  125752. if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
  125753. pExpr = pExpr->x.pList->a[0].pExpr;
  125754. }
  125755. if( pExpr->op==TK_COLUMN ){
  125756. aiCurCol[0] = pExpr->iTable;
  125757. aiCurCol[1] = pExpr->iColumn;
  125758. return 1;
  125759. }
  125760. if( mPrereq==0 ) return 0; /* No table references */
  125761. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  125762. return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
  125763. }
  125764. /*
  125765. ** The input to this routine is an WhereTerm structure with only the
  125766. ** "pExpr" field filled in. The job of this routine is to analyze the
  125767. ** subexpression and populate all the other fields of the WhereTerm
  125768. ** structure.
  125769. **
  125770. ** If the expression is of the form "<expr> <op> X" it gets commuted
  125771. ** to the standard form of "X <op> <expr>".
  125772. **
  125773. ** If the expression is of the form "X <op> Y" where both X and Y are
  125774. ** columns, then the original expression is unchanged and a new virtual
  125775. ** term of the form "Y <op> X" is added to the WHERE clause and
  125776. ** analyzed separately. The original term is marked with TERM_COPIED
  125777. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  125778. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  125779. ** is a commuted copy of a prior term.) The original term has nChild=1
  125780. ** and the copy has idxParent set to the index of the original term.
  125781. */
  125782. static void exprAnalyze(
  125783. SrcList *pSrc, /* the FROM clause */
  125784. WhereClause *pWC, /* the WHERE clause */
  125785. int idxTerm /* Index of the term to be analyzed */
  125786. ){
  125787. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  125788. WhereTerm *pTerm; /* The term to be analyzed */
  125789. WhereMaskSet *pMaskSet; /* Set of table index masks */
  125790. Expr *pExpr; /* The expression to be analyzed */
  125791. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  125792. Bitmask prereqAll; /* Prerequesites of pExpr */
  125793. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  125794. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  125795. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  125796. int noCase = 0; /* uppercase equivalent to lowercase */
  125797. int op; /* Top-level operator. pExpr->op */
  125798. Parse *pParse = pWInfo->pParse; /* Parsing context */
  125799. sqlite3 *db = pParse->db; /* Database connection */
  125800. unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
  125801. int nLeft; /* Number of elements on left side vector */
  125802. if( db->mallocFailed ){
  125803. return;
  125804. }
  125805. pTerm = &pWC->a[idxTerm];
  125806. pMaskSet = &pWInfo->sMaskSet;
  125807. pExpr = pTerm->pExpr;
  125808. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  125809. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  125810. op = pExpr->op;
  125811. if( op==TK_IN ){
  125812. assert( pExpr->pRight==0 );
  125813. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  125814. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  125815. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  125816. }else{
  125817. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  125818. }
  125819. }else if( op==TK_ISNULL ){
  125820. pTerm->prereqRight = 0;
  125821. }else{
  125822. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  125823. }
  125824. pMaskSet->bVarSelect = 0;
  125825. prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
  125826. if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
  125827. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  125828. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  125829. prereqAll |= x;
  125830. extraRight = x-1; /* ON clause terms may not be used with an index
  125831. ** on left table of a LEFT JOIN. Ticket #3015 */
  125832. if( (prereqAll>>1)>=x ){
  125833. sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
  125834. return;
  125835. }
  125836. }
  125837. pTerm->prereqAll = prereqAll;
  125838. pTerm->leftCursor = -1;
  125839. pTerm->iParent = -1;
  125840. pTerm->eOperator = 0;
  125841. if( allowedOp(op) ){
  125842. int aiCurCol[2];
  125843. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  125844. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  125845. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  125846. if( pTerm->iField>0 ){
  125847. assert( op==TK_IN );
  125848. assert( pLeft->op==TK_VECTOR );
  125849. pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
  125850. }
  125851. if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
  125852. pTerm->leftCursor = aiCurCol[0];
  125853. pTerm->u.leftColumn = aiCurCol[1];
  125854. pTerm->eOperator = operatorMask(op) & opMask;
  125855. }
  125856. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  125857. if( pRight
  125858. && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
  125859. ){
  125860. WhereTerm *pNew;
  125861. Expr *pDup;
  125862. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  125863. assert( pTerm->iField==0 );
  125864. if( pTerm->leftCursor>=0 ){
  125865. int idxNew;
  125866. pDup = sqlite3ExprDup(db, pExpr, 0);
  125867. if( db->mallocFailed ){
  125868. sqlite3ExprDelete(db, pDup);
  125869. return;
  125870. }
  125871. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  125872. if( idxNew==0 ) return;
  125873. pNew = &pWC->a[idxNew];
  125874. markTermAsChild(pWC, idxNew, idxTerm);
  125875. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  125876. pTerm = &pWC->a[idxTerm];
  125877. pTerm->wtFlags |= TERM_COPIED;
  125878. if( termIsEquivalence(pParse, pDup) ){
  125879. pTerm->eOperator |= WO_EQUIV;
  125880. eExtraOp = WO_EQUIV;
  125881. }
  125882. }else{
  125883. pDup = pExpr;
  125884. pNew = pTerm;
  125885. }
  125886. exprCommute(pParse, pDup);
  125887. pNew->leftCursor = aiCurCol[0];
  125888. pNew->u.leftColumn = aiCurCol[1];
  125889. testcase( (prereqLeft | extraRight) != prereqLeft );
  125890. pNew->prereqRight = prereqLeft | extraRight;
  125891. pNew->prereqAll = prereqAll;
  125892. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  125893. }
  125894. }
  125895. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  125896. /* If a term is the BETWEEN operator, create two new virtual terms
  125897. ** that define the range that the BETWEEN implements. For example:
  125898. **
  125899. ** a BETWEEN b AND c
  125900. **
  125901. ** is converted into:
  125902. **
  125903. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  125904. **
  125905. ** The two new terms are added onto the end of the WhereClause object.
  125906. ** The new terms are "dynamic" and are children of the original BETWEEN
  125907. ** term. That means that if the BETWEEN term is coded, the children are
  125908. ** skipped. Or, if the children are satisfied by an index, the original
  125909. ** BETWEEN term is skipped.
  125910. */
  125911. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  125912. ExprList *pList = pExpr->x.pList;
  125913. int i;
  125914. static const u8 ops[] = {TK_GE, TK_LE};
  125915. assert( pList!=0 );
  125916. assert( pList->nExpr==2 );
  125917. for(i=0; i<2; i++){
  125918. Expr *pNewExpr;
  125919. int idxNew;
  125920. pNewExpr = sqlite3PExpr(pParse, ops[i],
  125921. sqlite3ExprDup(db, pExpr->pLeft, 0),
  125922. sqlite3ExprDup(db, pList->a[i].pExpr, 0));
  125923. transferJoinMarkings(pNewExpr, pExpr);
  125924. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  125925. testcase( idxNew==0 );
  125926. exprAnalyze(pSrc, pWC, idxNew);
  125927. pTerm = &pWC->a[idxTerm];
  125928. markTermAsChild(pWC, idxNew, idxTerm);
  125929. }
  125930. }
  125931. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  125932. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  125933. /* Analyze a term that is composed of two or more subterms connected by
  125934. ** an OR operator.
  125935. */
  125936. else if( pExpr->op==TK_OR ){
  125937. assert( pWC->op==TK_AND );
  125938. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  125939. pTerm = &pWC->a[idxTerm];
  125940. }
  125941. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  125942. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  125943. /* Add constraints to reduce the search space on a LIKE or GLOB
  125944. ** operator.
  125945. **
  125946. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  125947. **
  125948. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  125949. **
  125950. ** The last character of the prefix "abc" is incremented to form the
  125951. ** termination condition "abd". If case is not significant (the default
  125952. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  125953. ** bound is made all lowercase so that the bounds also work when comparing
  125954. ** BLOBs.
  125955. */
  125956. if( pWC->op==TK_AND
  125957. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  125958. ){
  125959. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  125960. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  125961. Expr *pNewExpr1;
  125962. Expr *pNewExpr2;
  125963. int idxNew1;
  125964. int idxNew2;
  125965. const char *zCollSeqName; /* Name of collating sequence */
  125966. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  125967. pLeft = pExpr->x.pList->a[1].pExpr;
  125968. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  125969. /* Convert the lower bound to upper-case and the upper bound to
  125970. ** lower-case (upper-case is less than lower-case in ASCII) so that
  125971. ** the range constraints also work for BLOBs
  125972. */
  125973. if( noCase && !pParse->db->mallocFailed ){
  125974. int i;
  125975. char c;
  125976. pTerm->wtFlags |= TERM_LIKE;
  125977. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  125978. pStr1->u.zToken[i] = sqlite3Toupper(c);
  125979. pStr2->u.zToken[i] = sqlite3Tolower(c);
  125980. }
  125981. }
  125982. if( !db->mallocFailed ){
  125983. u8 c, *pC; /* Last character before the first wildcard */
  125984. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  125985. c = *pC;
  125986. if( noCase ){
  125987. /* The point is to increment the last character before the first
  125988. ** wildcard. But if we increment '@', that will push it into the
  125989. ** alphabetic range where case conversions will mess up the
  125990. ** inequality. To avoid this, make sure to also run the full
  125991. ** LIKE on all candidate expressions by clearing the isComplete flag
  125992. */
  125993. if( c=='A'-1 ) isComplete = 0;
  125994. c = sqlite3UpperToLower[c];
  125995. }
  125996. *pC = c + 1;
  125997. }
  125998. zCollSeqName = noCase ? "NOCASE" : "BINARY";
  125999. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  126000. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  126001. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  126002. pStr1);
  126003. transferJoinMarkings(pNewExpr1, pExpr);
  126004. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  126005. testcase( idxNew1==0 );
  126006. exprAnalyze(pSrc, pWC, idxNew1);
  126007. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  126008. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  126009. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  126010. pStr2);
  126011. transferJoinMarkings(pNewExpr2, pExpr);
  126012. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  126013. testcase( idxNew2==0 );
  126014. exprAnalyze(pSrc, pWC, idxNew2);
  126015. pTerm = &pWC->a[idxTerm];
  126016. if( isComplete ){
  126017. markTermAsChild(pWC, idxNew1, idxTerm);
  126018. markTermAsChild(pWC, idxNew2, idxTerm);
  126019. }
  126020. }
  126021. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  126022. #ifndef SQLITE_OMIT_VIRTUALTABLE
  126023. /* Add a WO_AUX auxiliary term to the constraint set if the
  126024. ** current expression is of the form "column OP expr" where OP
  126025. ** is an operator that gets passed into virtual tables but which is
  126026. ** not normally optimized for ordinary tables. In other words, OP
  126027. ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
  126028. ** This information is used by the xBestIndex methods of
  126029. ** virtual tables. The native query optimizer does not attempt
  126030. ** to do anything with MATCH functions.
  126031. */
  126032. if( pWC->op==TK_AND ){
  126033. Expr *pRight = 0, *pLeft = 0;
  126034. int res = isAuxiliaryVtabOperator(pExpr, &eOp2, &pLeft, &pRight);
  126035. while( res-- > 0 ){
  126036. int idxNew;
  126037. WhereTerm *pNewTerm;
  126038. Bitmask prereqColumn, prereqExpr;
  126039. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  126040. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  126041. if( (prereqExpr & prereqColumn)==0 ){
  126042. Expr *pNewExpr;
  126043. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  126044. 0, sqlite3ExprDup(db, pRight, 0));
  126045. if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
  126046. ExprSetProperty(pNewExpr, EP_FromJoin);
  126047. }
  126048. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  126049. testcase( idxNew==0 );
  126050. pNewTerm = &pWC->a[idxNew];
  126051. pNewTerm->prereqRight = prereqExpr;
  126052. pNewTerm->leftCursor = pLeft->iTable;
  126053. pNewTerm->u.leftColumn = pLeft->iColumn;
  126054. pNewTerm->eOperator = WO_AUX;
  126055. pNewTerm->eMatchOp = eOp2;
  126056. markTermAsChild(pWC, idxNew, idxTerm);
  126057. pTerm = &pWC->a[idxTerm];
  126058. pTerm->wtFlags |= TERM_COPIED;
  126059. pNewTerm->prereqAll = pTerm->prereqAll;
  126060. }
  126061. SWAP(Expr*, pLeft, pRight);
  126062. }
  126063. }
  126064. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  126065. /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
  126066. ** new terms for each component comparison - "a = ?" and "b = ?". The
  126067. ** new terms completely replace the original vector comparison, which is
  126068. ** no longer used.
  126069. **
  126070. ** This is only required if at least one side of the comparison operation
  126071. ** is not a sub-select. */
  126072. if( pWC->op==TK_AND
  126073. && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
  126074. && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
  126075. && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
  126076. && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
  126077. || (pExpr->pRight->flags & EP_xIsSelect)==0)
  126078. ){
  126079. int i;
  126080. for(i=0; i<nLeft; i++){
  126081. int idxNew;
  126082. Expr *pNew;
  126083. Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
  126084. Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
  126085. pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
  126086. transferJoinMarkings(pNew, pExpr);
  126087. idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
  126088. exprAnalyze(pSrc, pWC, idxNew);
  126089. }
  126090. pTerm = &pWC->a[idxTerm];
  126091. pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
  126092. pTerm->eOperator = 0;
  126093. }
  126094. /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
  126095. ** a virtual term for each vector component. The expression object
  126096. ** used by each such virtual term is pExpr (the full vector IN(...)
  126097. ** expression). The WhereTerm.iField variable identifies the index within
  126098. ** the vector on the LHS that the virtual term represents.
  126099. **
  126100. ** This only works if the RHS is a simple SELECT, not a compound
  126101. */
  126102. if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
  126103. && pExpr->pLeft->op==TK_VECTOR
  126104. && pExpr->x.pSelect->pPrior==0
  126105. ){
  126106. int i;
  126107. for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
  126108. int idxNew;
  126109. idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
  126110. pWC->a[idxNew].iField = i+1;
  126111. exprAnalyze(pSrc, pWC, idxNew);
  126112. markTermAsChild(pWC, idxNew, idxTerm);
  126113. }
  126114. }
  126115. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  126116. /* When sqlite_stat3 histogram data is available an operator of the
  126117. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  126118. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  126119. ** virtual term of that form.
  126120. **
  126121. ** Note that the virtual term must be tagged with TERM_VNULL.
  126122. */
  126123. if( pExpr->op==TK_NOTNULL
  126124. && pExpr->pLeft->op==TK_COLUMN
  126125. && pExpr->pLeft->iColumn>=0
  126126. && OptimizationEnabled(db, SQLITE_Stat34)
  126127. ){
  126128. Expr *pNewExpr;
  126129. Expr *pLeft = pExpr->pLeft;
  126130. int idxNew;
  126131. WhereTerm *pNewTerm;
  126132. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  126133. sqlite3ExprDup(db, pLeft, 0),
  126134. sqlite3ExprAlloc(db, TK_NULL, 0, 0));
  126135. idxNew = whereClauseInsert(pWC, pNewExpr,
  126136. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  126137. if( idxNew ){
  126138. pNewTerm = &pWC->a[idxNew];
  126139. pNewTerm->prereqRight = 0;
  126140. pNewTerm->leftCursor = pLeft->iTable;
  126141. pNewTerm->u.leftColumn = pLeft->iColumn;
  126142. pNewTerm->eOperator = WO_GT;
  126143. markTermAsChild(pWC, idxNew, idxTerm);
  126144. pTerm = &pWC->a[idxTerm];
  126145. pTerm->wtFlags |= TERM_COPIED;
  126146. pNewTerm->prereqAll = pTerm->prereqAll;
  126147. }
  126148. }
  126149. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  126150. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  126151. ** an index for tables to the left of the join.
  126152. */
  126153. testcase( pTerm!=&pWC->a[idxTerm] );
  126154. pTerm = &pWC->a[idxTerm];
  126155. pTerm->prereqRight |= extraRight;
  126156. }
  126157. /***************************************************************************
  126158. ** Routines with file scope above. Interface to the rest of the where.c
  126159. ** subsystem follows.
  126160. ***************************************************************************/
  126161. /*
  126162. ** This routine identifies subexpressions in the WHERE clause where
  126163. ** each subexpression is separated by the AND operator or some other
  126164. ** operator specified in the op parameter. The WhereClause structure
  126165. ** is filled with pointers to subexpressions. For example:
  126166. **
  126167. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  126168. ** \________/ \_______________/ \________________/
  126169. ** slot[0] slot[1] slot[2]
  126170. **
  126171. ** The original WHERE clause in pExpr is unaltered. All this routine
  126172. ** does is make slot[] entries point to substructure within pExpr.
  126173. **
  126174. ** In the previous sentence and in the diagram, "slot[]" refers to
  126175. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  126176. ** all terms of the WHERE clause.
  126177. */
  126178. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  126179. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  126180. pWC->op = op;
  126181. if( pE2==0 ) return;
  126182. if( pE2->op!=op ){
  126183. whereClauseInsert(pWC, pExpr, 0);
  126184. }else{
  126185. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  126186. sqlite3WhereSplit(pWC, pE2->pRight, op);
  126187. }
  126188. }
  126189. /*
  126190. ** Initialize a preallocated WhereClause structure.
  126191. */
  126192. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  126193. WhereClause *pWC, /* The WhereClause to be initialized */
  126194. WhereInfo *pWInfo /* The WHERE processing context */
  126195. ){
  126196. pWC->pWInfo = pWInfo;
  126197. pWC->pOuter = 0;
  126198. pWC->nTerm = 0;
  126199. pWC->nSlot = ArraySize(pWC->aStatic);
  126200. pWC->a = pWC->aStatic;
  126201. }
  126202. /*
  126203. ** Deallocate a WhereClause structure. The WhereClause structure
  126204. ** itself is not freed. This routine is the inverse of
  126205. ** sqlite3WhereClauseInit().
  126206. */
  126207. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  126208. int i;
  126209. WhereTerm *a;
  126210. sqlite3 *db = pWC->pWInfo->pParse->db;
  126211. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  126212. if( a->wtFlags & TERM_DYNAMIC ){
  126213. sqlite3ExprDelete(db, a->pExpr);
  126214. }
  126215. if( a->wtFlags & TERM_ORINFO ){
  126216. whereOrInfoDelete(db, a->u.pOrInfo);
  126217. }else if( a->wtFlags & TERM_ANDINFO ){
  126218. whereAndInfoDelete(db, a->u.pAndInfo);
  126219. }
  126220. }
  126221. if( pWC->a!=pWC->aStatic ){
  126222. sqlite3DbFree(db, pWC->a);
  126223. }
  126224. }
  126225. /*
  126226. ** These routines walk (recursively) an expression tree and generate
  126227. ** a bitmask indicating which tables are used in that expression
  126228. ** tree.
  126229. */
  126230. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  126231. Bitmask mask;
  126232. if( p==0 ) return 0;
  126233. if( p->op==TK_COLUMN ){
  126234. return sqlite3WhereGetMask(pMaskSet, p->iTable);
  126235. }
  126236. mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
  126237. assert( !ExprHasProperty(p, EP_TokenOnly) );
  126238. if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
  126239. if( p->pRight ){
  126240. mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
  126241. assert( p->x.pList==0 );
  126242. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  126243. if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
  126244. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  126245. }else if( p->x.pList ){
  126246. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  126247. }
  126248. return mask;
  126249. }
  126250. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  126251. int i;
  126252. Bitmask mask = 0;
  126253. if( pList ){
  126254. for(i=0; i<pList->nExpr; i++){
  126255. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  126256. }
  126257. }
  126258. return mask;
  126259. }
  126260. /*
  126261. ** Call exprAnalyze on all terms in a WHERE clause.
  126262. **
  126263. ** Note that exprAnalyze() might add new virtual terms onto the
  126264. ** end of the WHERE clause. We do not want to analyze these new
  126265. ** virtual terms, so start analyzing at the end and work forward
  126266. ** so that the added virtual terms are never processed.
  126267. */
  126268. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  126269. SrcList *pTabList, /* the FROM clause */
  126270. WhereClause *pWC /* the WHERE clause to be analyzed */
  126271. ){
  126272. int i;
  126273. for(i=pWC->nTerm-1; i>=0; i--){
  126274. exprAnalyze(pTabList, pWC, i);
  126275. }
  126276. }
  126277. /*
  126278. ** For table-valued-functions, transform the function arguments into
  126279. ** new WHERE clause terms.
  126280. **
  126281. ** Each function argument translates into an equality constraint against
  126282. ** a HIDDEN column in the table.
  126283. */
  126284. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  126285. Parse *pParse, /* Parsing context */
  126286. struct SrcList_item *pItem, /* The FROM clause term to process */
  126287. WhereClause *pWC /* Xfer function arguments to here */
  126288. ){
  126289. Table *pTab;
  126290. int j, k;
  126291. ExprList *pArgs;
  126292. Expr *pColRef;
  126293. Expr *pTerm;
  126294. if( pItem->fg.isTabFunc==0 ) return;
  126295. pTab = pItem->pTab;
  126296. assert( pTab!=0 );
  126297. pArgs = pItem->u1.pFuncArg;
  126298. if( pArgs==0 ) return;
  126299. for(j=k=0; j<pArgs->nExpr; j++){
  126300. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  126301. if( k>=pTab->nCol ){
  126302. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  126303. pTab->zName, j);
  126304. return;
  126305. }
  126306. pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
  126307. if( pColRef==0 ) return;
  126308. pColRef->iTable = pItem->iCursor;
  126309. pColRef->iColumn = k++;
  126310. pColRef->pTab = pTab;
  126311. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
  126312. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
  126313. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  126314. }
  126315. }
  126316. /************** End of whereexpr.c *******************************************/
  126317. /************** Begin file where.c *******************************************/
  126318. /*
  126319. ** 2001 September 15
  126320. **
  126321. ** The author disclaims copyright to this source code. In place of
  126322. ** a legal notice, here is a blessing:
  126323. **
  126324. ** May you do good and not evil.
  126325. ** May you find forgiveness for yourself and forgive others.
  126326. ** May you share freely, never taking more than you give.
  126327. **
  126328. *************************************************************************
  126329. ** This module contains C code that generates VDBE code used to process
  126330. ** the WHERE clause of SQL statements. This module is responsible for
  126331. ** generating the code that loops through a table looking for applicable
  126332. ** rows. Indices are selected and used to speed the search when doing
  126333. ** so is applicable. Because this module is responsible for selecting
  126334. ** indices, you might also think of this module as the "query optimizer".
  126335. */
  126336. /* #include "sqliteInt.h" */
  126337. /* #include "whereInt.h" */
  126338. /*
  126339. ** Extra information appended to the end of sqlite3_index_info but not
  126340. ** visible to the xBestIndex function, at least not directly. The
  126341. ** sqlite3_vtab_collation() interface knows how to reach it, however.
  126342. **
  126343. ** This object is not an API and can be changed from one release to the
  126344. ** next. As long as allocateIndexInfo() and sqlite3_vtab_collation()
  126345. ** agree on the structure, all will be well.
  126346. */
  126347. typedef struct HiddenIndexInfo HiddenIndexInfo;
  126348. struct HiddenIndexInfo {
  126349. WhereClause *pWC; /* The Where clause being analyzed */
  126350. Parse *pParse; /* The parsing context */
  126351. };
  126352. /* Forward declaration of methods */
  126353. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  126354. /* Test variable that can be set to enable WHERE tracing */
  126355. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  126356. /***/ int sqlite3WhereTrace = 0;
  126357. #endif
  126358. /*
  126359. ** Return the estimated number of output rows from a WHERE clause
  126360. */
  126361. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  126362. return pWInfo->nRowOut;
  126363. }
  126364. /*
  126365. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  126366. ** WHERE clause returns outputs for DISTINCT processing.
  126367. */
  126368. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  126369. return pWInfo->eDistinct;
  126370. }
  126371. /*
  126372. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  126373. ** Return FALSE if the output needs to be sorted.
  126374. */
  126375. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  126376. return pWInfo->nOBSat;
  126377. }
  126378. /*
  126379. ** Return TRUE if the innermost loop of the WHERE clause implementation
  126380. ** returns rows in ORDER BY order for complete run of the inner loop.
  126381. **
  126382. ** Across multiple iterations of outer loops, the output rows need not be
  126383. ** sorted. As long as rows are sorted for just the innermost loop, this
  126384. ** routine can return TRUE.
  126385. */
  126386. SQLITE_PRIVATE int sqlite3WhereOrderedInnerLoop(WhereInfo *pWInfo){
  126387. return pWInfo->bOrderedInnerLoop;
  126388. }
  126389. /*
  126390. ** Return the VDBE address or label to jump to in order to continue
  126391. ** immediately with the next row of a WHERE clause.
  126392. */
  126393. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  126394. assert( pWInfo->iContinue!=0 );
  126395. return pWInfo->iContinue;
  126396. }
  126397. /*
  126398. ** Return the VDBE address or label to jump to in order to break
  126399. ** out of a WHERE loop.
  126400. */
  126401. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  126402. return pWInfo->iBreak;
  126403. }
  126404. /*
  126405. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  126406. ** operate directly on the rowis returned by a WHERE clause. Return
  126407. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  126408. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  126409. ** optimization can be used on multiple
  126410. **
  126411. ** If the ONEPASS optimization is used (if this routine returns true)
  126412. ** then also write the indices of open cursors used by ONEPASS
  126413. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  126414. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  126415. ** Either value may be -1, indicating that cursor is not used.
  126416. ** Any cursors returned will have been opened for writing.
  126417. **
  126418. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  126419. ** unable to use the ONEPASS optimization.
  126420. */
  126421. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  126422. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  126423. #ifdef WHERETRACE_ENABLED
  126424. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  126425. sqlite3DebugPrintf("%s cursors: %d %d\n",
  126426. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  126427. aiCur[0], aiCur[1]);
  126428. }
  126429. #endif
  126430. return pWInfo->eOnePass;
  126431. }
  126432. /*
  126433. ** Move the content of pSrc into pDest
  126434. */
  126435. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  126436. pDest->n = pSrc->n;
  126437. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  126438. }
  126439. /*
  126440. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  126441. **
  126442. ** The new entry might overwrite an existing entry, or it might be
  126443. ** appended, or it might be discarded. Do whatever is the right thing
  126444. ** so that pSet keeps the N_OR_COST best entries seen so far.
  126445. */
  126446. static int whereOrInsert(
  126447. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  126448. Bitmask prereq, /* Prerequisites of the new entry */
  126449. LogEst rRun, /* Run-cost of the new entry */
  126450. LogEst nOut /* Number of outputs for the new entry */
  126451. ){
  126452. u16 i;
  126453. WhereOrCost *p;
  126454. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  126455. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  126456. goto whereOrInsert_done;
  126457. }
  126458. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  126459. return 0;
  126460. }
  126461. }
  126462. if( pSet->n<N_OR_COST ){
  126463. p = &pSet->a[pSet->n++];
  126464. p->nOut = nOut;
  126465. }else{
  126466. p = pSet->a;
  126467. for(i=1; i<pSet->n; i++){
  126468. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  126469. }
  126470. if( p->rRun<=rRun ) return 0;
  126471. }
  126472. whereOrInsert_done:
  126473. p->prereq = prereq;
  126474. p->rRun = rRun;
  126475. if( p->nOut>nOut ) p->nOut = nOut;
  126476. return 1;
  126477. }
  126478. /*
  126479. ** Return the bitmask for the given cursor number. Return 0 if
  126480. ** iCursor is not in the set.
  126481. */
  126482. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  126483. int i;
  126484. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  126485. for(i=0; i<pMaskSet->n; i++){
  126486. if( pMaskSet->ix[i]==iCursor ){
  126487. return MASKBIT(i);
  126488. }
  126489. }
  126490. return 0;
  126491. }
  126492. /*
  126493. ** Create a new mask for cursor iCursor.
  126494. **
  126495. ** There is one cursor per table in the FROM clause. The number of
  126496. ** tables in the FROM clause is limited by a test early in the
  126497. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  126498. ** array will never overflow.
  126499. */
  126500. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  126501. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  126502. pMaskSet->ix[pMaskSet->n++] = iCursor;
  126503. }
  126504. /*
  126505. ** Advance to the next WhereTerm that matches according to the criteria
  126506. ** established when the pScan object was initialized by whereScanInit().
  126507. ** Return NULL if there are no more matching WhereTerms.
  126508. */
  126509. static WhereTerm *whereScanNext(WhereScan *pScan){
  126510. int iCur; /* The cursor on the LHS of the term */
  126511. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  126512. Expr *pX; /* An expression being tested */
  126513. WhereClause *pWC; /* Shorthand for pScan->pWC */
  126514. WhereTerm *pTerm; /* The term being tested */
  126515. int k = pScan->k; /* Where to start scanning */
  126516. assert( pScan->iEquiv<=pScan->nEquiv );
  126517. pWC = pScan->pWC;
  126518. while(1){
  126519. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  126520. iCur = pScan->aiCur[pScan->iEquiv-1];
  126521. assert( pWC!=0 );
  126522. do{
  126523. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  126524. if( pTerm->leftCursor==iCur
  126525. && pTerm->u.leftColumn==iColumn
  126526. && (iColumn!=XN_EXPR
  126527. || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
  126528. pScan->pIdxExpr,iCur)==0)
  126529. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  126530. ){
  126531. if( (pTerm->eOperator & WO_EQUIV)!=0
  126532. && pScan->nEquiv<ArraySize(pScan->aiCur)
  126533. && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
  126534. ){
  126535. int j;
  126536. for(j=0; j<pScan->nEquiv; j++){
  126537. if( pScan->aiCur[j]==pX->iTable
  126538. && pScan->aiColumn[j]==pX->iColumn ){
  126539. break;
  126540. }
  126541. }
  126542. if( j==pScan->nEquiv ){
  126543. pScan->aiCur[j] = pX->iTable;
  126544. pScan->aiColumn[j] = pX->iColumn;
  126545. pScan->nEquiv++;
  126546. }
  126547. }
  126548. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  126549. /* Verify the affinity and collating sequence match */
  126550. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  126551. CollSeq *pColl;
  126552. Parse *pParse = pWC->pWInfo->pParse;
  126553. pX = pTerm->pExpr;
  126554. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  126555. continue;
  126556. }
  126557. assert(pX->pLeft);
  126558. pColl = sqlite3BinaryCompareCollSeq(pParse,
  126559. pX->pLeft, pX->pRight);
  126560. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  126561. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  126562. continue;
  126563. }
  126564. }
  126565. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  126566. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  126567. && pX->iTable==pScan->aiCur[0]
  126568. && pX->iColumn==pScan->aiColumn[0]
  126569. ){
  126570. testcase( pTerm->eOperator & WO_IS );
  126571. continue;
  126572. }
  126573. pScan->pWC = pWC;
  126574. pScan->k = k+1;
  126575. return pTerm;
  126576. }
  126577. }
  126578. }
  126579. pWC = pWC->pOuter;
  126580. k = 0;
  126581. }while( pWC!=0 );
  126582. if( pScan->iEquiv>=pScan->nEquiv ) break;
  126583. pWC = pScan->pOrigWC;
  126584. k = 0;
  126585. pScan->iEquiv++;
  126586. }
  126587. return 0;
  126588. }
  126589. /*
  126590. ** Initialize a WHERE clause scanner object. Return a pointer to the
  126591. ** first match. Return NULL if there are no matches.
  126592. **
  126593. ** The scanner will be searching the WHERE clause pWC. It will look
  126594. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  126595. ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
  126596. ** must be one of the indexes of table iCur.
  126597. **
  126598. ** The <op> must be one of the operators described by opMask.
  126599. **
  126600. ** If the search is for X and the WHERE clause contains terms of the
  126601. ** form X=Y then this routine might also return terms of the form
  126602. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  126603. ** but is enough to handle most commonly occurring SQL statements.
  126604. **
  126605. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  126606. ** index pIdx.
  126607. */
  126608. static WhereTerm *whereScanInit(
  126609. WhereScan *pScan, /* The WhereScan object being initialized */
  126610. WhereClause *pWC, /* The WHERE clause to be scanned */
  126611. int iCur, /* Cursor to scan for */
  126612. int iColumn, /* Column to scan for */
  126613. u32 opMask, /* Operator(s) to scan for */
  126614. Index *pIdx /* Must be compatible with this index */
  126615. ){
  126616. pScan->pOrigWC = pWC;
  126617. pScan->pWC = pWC;
  126618. pScan->pIdxExpr = 0;
  126619. pScan->idxaff = 0;
  126620. pScan->zCollName = 0;
  126621. if( pIdx ){
  126622. int j = iColumn;
  126623. iColumn = pIdx->aiColumn[j];
  126624. if( iColumn==XN_EXPR ){
  126625. pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  126626. pScan->zCollName = pIdx->azColl[j];
  126627. }else if( iColumn==pIdx->pTable->iPKey ){
  126628. iColumn = XN_ROWID;
  126629. }else if( iColumn>=0 ){
  126630. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  126631. pScan->zCollName = pIdx->azColl[j];
  126632. }
  126633. }else if( iColumn==XN_EXPR ){
  126634. return 0;
  126635. }
  126636. pScan->opMask = opMask;
  126637. pScan->k = 0;
  126638. pScan->aiCur[0] = iCur;
  126639. pScan->aiColumn[0] = iColumn;
  126640. pScan->nEquiv = 1;
  126641. pScan->iEquiv = 1;
  126642. return whereScanNext(pScan);
  126643. }
  126644. /*
  126645. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  126646. ** where X is a reference to the iColumn of table iCur or of index pIdx
  126647. ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
  126648. ** the op parameter. Return a pointer to the term. Return 0 if not found.
  126649. **
  126650. ** If pIdx!=0 then it must be one of the indexes of table iCur.
  126651. ** Search for terms matching the iColumn-th column of pIdx
  126652. ** rather than the iColumn-th column of table iCur.
  126653. **
  126654. ** The term returned might by Y=<expr> if there is another constraint in
  126655. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  126656. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  126657. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  126658. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  126659. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  126660. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  126661. **
  126662. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  126663. ** then try for the one with no dependencies on <expr> - in other words where
  126664. ** <expr> is a constant expression of some kind. Only return entries of
  126665. ** the form "X <op> Y" where Y is a column in another table if no terms of
  126666. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  126667. ** exist, try to return a term that does not use WO_EQUIV.
  126668. */
  126669. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  126670. WhereClause *pWC, /* The WHERE clause to be searched */
  126671. int iCur, /* Cursor number of LHS */
  126672. int iColumn, /* Column number of LHS */
  126673. Bitmask notReady, /* RHS must not overlap with this mask */
  126674. u32 op, /* Mask of WO_xx values describing operator */
  126675. Index *pIdx /* Must be compatible with this index, if not NULL */
  126676. ){
  126677. WhereTerm *pResult = 0;
  126678. WhereTerm *p;
  126679. WhereScan scan;
  126680. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  126681. op &= WO_EQ|WO_IS;
  126682. while( p ){
  126683. if( (p->prereqRight & notReady)==0 ){
  126684. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  126685. testcase( p->eOperator & WO_IS );
  126686. return p;
  126687. }
  126688. if( pResult==0 ) pResult = p;
  126689. }
  126690. p = whereScanNext(&scan);
  126691. }
  126692. return pResult;
  126693. }
  126694. /*
  126695. ** This function searches pList for an entry that matches the iCol-th column
  126696. ** of index pIdx.
  126697. **
  126698. ** If such an expression is found, its index in pList->a[] is returned. If
  126699. ** no expression is found, -1 is returned.
  126700. */
  126701. static int findIndexCol(
  126702. Parse *pParse, /* Parse context */
  126703. ExprList *pList, /* Expression list to search */
  126704. int iBase, /* Cursor for table associated with pIdx */
  126705. Index *pIdx, /* Index to match column of */
  126706. int iCol /* Column of index to match */
  126707. ){
  126708. int i;
  126709. const char *zColl = pIdx->azColl[iCol];
  126710. for(i=0; i<pList->nExpr; i++){
  126711. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  126712. if( p->op==TK_COLUMN
  126713. && p->iColumn==pIdx->aiColumn[iCol]
  126714. && p->iTable==iBase
  126715. ){
  126716. CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
  126717. if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
  126718. return i;
  126719. }
  126720. }
  126721. }
  126722. return -1;
  126723. }
  126724. /*
  126725. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  126726. */
  126727. static int indexColumnNotNull(Index *pIdx, int iCol){
  126728. int j;
  126729. assert( pIdx!=0 );
  126730. assert( iCol>=0 && iCol<pIdx->nColumn );
  126731. j = pIdx->aiColumn[iCol];
  126732. if( j>=0 ){
  126733. return pIdx->pTable->aCol[j].notNull;
  126734. }else if( j==(-1) ){
  126735. return 1;
  126736. }else{
  126737. assert( j==(-2) );
  126738. return 0; /* Assume an indexed expression can always yield a NULL */
  126739. }
  126740. }
  126741. /*
  126742. ** Return true if the DISTINCT expression-list passed as the third argument
  126743. ** is redundant.
  126744. **
  126745. ** A DISTINCT list is redundant if any subset of the columns in the
  126746. ** DISTINCT list are collectively unique and individually non-null.
  126747. */
  126748. static int isDistinctRedundant(
  126749. Parse *pParse, /* Parsing context */
  126750. SrcList *pTabList, /* The FROM clause */
  126751. WhereClause *pWC, /* The WHERE clause */
  126752. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  126753. ){
  126754. Table *pTab;
  126755. Index *pIdx;
  126756. int i;
  126757. int iBase;
  126758. /* If there is more than one table or sub-select in the FROM clause of
  126759. ** this query, then it will not be possible to show that the DISTINCT
  126760. ** clause is redundant. */
  126761. if( pTabList->nSrc!=1 ) return 0;
  126762. iBase = pTabList->a[0].iCursor;
  126763. pTab = pTabList->a[0].pTab;
  126764. /* If any of the expressions is an IPK column on table iBase, then return
  126765. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  126766. ** current SELECT is a correlated sub-query.
  126767. */
  126768. for(i=0; i<pDistinct->nExpr; i++){
  126769. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  126770. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  126771. }
  126772. /* Loop through all indices on the table, checking each to see if it makes
  126773. ** the DISTINCT qualifier redundant. It does so if:
  126774. **
  126775. ** 1. The index is itself UNIQUE, and
  126776. **
  126777. ** 2. All of the columns in the index are either part of the pDistinct
  126778. ** list, or else the WHERE clause contains a term of the form "col=X",
  126779. ** where X is a constant value. The collation sequences of the
  126780. ** comparison and select-list expressions must match those of the index.
  126781. **
  126782. ** 3. All of those index columns for which the WHERE clause does not
  126783. ** contain a "col=X" term are subject to a NOT NULL constraint.
  126784. */
  126785. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  126786. if( !IsUniqueIndex(pIdx) ) continue;
  126787. for(i=0; i<pIdx->nKeyCol; i++){
  126788. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  126789. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  126790. if( indexColumnNotNull(pIdx, i)==0 ) break;
  126791. }
  126792. }
  126793. if( i==pIdx->nKeyCol ){
  126794. /* This index implies that the DISTINCT qualifier is redundant. */
  126795. return 1;
  126796. }
  126797. }
  126798. return 0;
  126799. }
  126800. /*
  126801. ** Estimate the logarithm of the input value to base 2.
  126802. */
  126803. static LogEst estLog(LogEst N){
  126804. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  126805. }
  126806. /*
  126807. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  126808. **
  126809. ** This routine runs over generated VDBE code and translates OP_Column
  126810. ** opcodes into OP_Copy when the table is being accessed via co-routine
  126811. ** instead of via table lookup.
  126812. **
  126813. ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
  126814. ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
  126815. ** then each OP_Rowid is transformed into an instruction to increment the
  126816. ** value stored in its output register.
  126817. */
  126818. static void translateColumnToCopy(
  126819. Parse *pParse, /* Parsing context */
  126820. int iStart, /* Translate from this opcode to the end */
  126821. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  126822. int iRegister, /* The first column is in this register */
  126823. int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
  126824. ){
  126825. Vdbe *v = pParse->pVdbe;
  126826. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  126827. int iEnd = sqlite3VdbeCurrentAddr(v);
  126828. if( pParse->db->mallocFailed ) return;
  126829. for(; iStart<iEnd; iStart++, pOp++){
  126830. if( pOp->p1!=iTabCur ) continue;
  126831. if( pOp->opcode==OP_Column ){
  126832. pOp->opcode = OP_Copy;
  126833. pOp->p1 = pOp->p2 + iRegister;
  126834. pOp->p2 = pOp->p3;
  126835. pOp->p3 = 0;
  126836. }else if( pOp->opcode==OP_Rowid ){
  126837. if( bIncrRowid ){
  126838. /* Increment the value stored in the P2 operand of the OP_Rowid. */
  126839. pOp->opcode = OP_AddImm;
  126840. pOp->p1 = pOp->p2;
  126841. pOp->p2 = 1;
  126842. }else{
  126843. pOp->opcode = OP_Null;
  126844. pOp->p1 = 0;
  126845. pOp->p3 = 0;
  126846. }
  126847. }
  126848. }
  126849. }
  126850. /*
  126851. ** Two routines for printing the content of an sqlite3_index_info
  126852. ** structure. Used for testing and debugging only. If neither
  126853. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  126854. ** are no-ops.
  126855. */
  126856. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  126857. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  126858. int i;
  126859. if( !sqlite3WhereTrace ) return;
  126860. for(i=0; i<p->nConstraint; i++){
  126861. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  126862. i,
  126863. p->aConstraint[i].iColumn,
  126864. p->aConstraint[i].iTermOffset,
  126865. p->aConstraint[i].op,
  126866. p->aConstraint[i].usable);
  126867. }
  126868. for(i=0; i<p->nOrderBy; i++){
  126869. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  126870. i,
  126871. p->aOrderBy[i].iColumn,
  126872. p->aOrderBy[i].desc);
  126873. }
  126874. }
  126875. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  126876. int i;
  126877. if( !sqlite3WhereTrace ) return;
  126878. for(i=0; i<p->nConstraint; i++){
  126879. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  126880. i,
  126881. p->aConstraintUsage[i].argvIndex,
  126882. p->aConstraintUsage[i].omit);
  126883. }
  126884. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  126885. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  126886. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  126887. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  126888. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  126889. }
  126890. #else
  126891. #define TRACE_IDX_INPUTS(A)
  126892. #define TRACE_IDX_OUTPUTS(A)
  126893. #endif
  126894. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  126895. /*
  126896. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  126897. ** could be used with an index to access pSrc, assuming an appropriate
  126898. ** index existed.
  126899. */
  126900. static int termCanDriveIndex(
  126901. WhereTerm *pTerm, /* WHERE clause term to check */
  126902. struct SrcList_item *pSrc, /* Table we are trying to access */
  126903. Bitmask notReady /* Tables in outer loops of the join */
  126904. ){
  126905. char aff;
  126906. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  126907. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  126908. if( (pSrc->fg.jointype & JT_LEFT)
  126909. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  126910. && (pTerm->eOperator & WO_IS)
  126911. ){
  126912. /* Cannot use an IS term from the WHERE clause as an index driver for
  126913. ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
  126914. ** the ON clause. */
  126915. return 0;
  126916. }
  126917. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  126918. if( pTerm->u.leftColumn<0 ) return 0;
  126919. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  126920. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  126921. testcase( pTerm->pExpr->op==TK_IS );
  126922. return 1;
  126923. }
  126924. #endif
  126925. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  126926. /*
  126927. ** Generate code to construct the Index object for an automatic index
  126928. ** and to set up the WhereLevel object pLevel so that the code generator
  126929. ** makes use of the automatic index.
  126930. */
  126931. static void constructAutomaticIndex(
  126932. Parse *pParse, /* The parsing context */
  126933. WhereClause *pWC, /* The WHERE clause */
  126934. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  126935. Bitmask notReady, /* Mask of cursors that are not available */
  126936. WhereLevel *pLevel /* Write new index here */
  126937. ){
  126938. int nKeyCol; /* Number of columns in the constructed index */
  126939. WhereTerm *pTerm; /* A single term of the WHERE clause */
  126940. WhereTerm *pWCEnd; /* End of pWC->a[] */
  126941. Index *pIdx; /* Object describing the transient index */
  126942. Vdbe *v; /* Prepared statement under construction */
  126943. int addrInit; /* Address of the initialization bypass jump */
  126944. Table *pTable; /* The table being indexed */
  126945. int addrTop; /* Top of the index fill loop */
  126946. int regRecord; /* Register holding an index record */
  126947. int n; /* Column counter */
  126948. int i; /* Loop counter */
  126949. int mxBitCol; /* Maximum column in pSrc->colUsed */
  126950. CollSeq *pColl; /* Collating sequence to on a column */
  126951. WhereLoop *pLoop; /* The Loop object */
  126952. char *zNotUsed; /* Extra space on the end of pIdx */
  126953. Bitmask idxCols; /* Bitmap of columns used for indexing */
  126954. Bitmask extraCols; /* Bitmap of additional columns */
  126955. u8 sentWarning = 0; /* True if a warnning has been issued */
  126956. Expr *pPartial = 0; /* Partial Index Expression */
  126957. int iContinue = 0; /* Jump here to skip excluded rows */
  126958. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  126959. int addrCounter = 0; /* Address where integer counter is initialized */
  126960. int regBase; /* Array of registers where record is assembled */
  126961. /* Generate code to skip over the creation and initialization of the
  126962. ** transient index on 2nd and subsequent iterations of the loop. */
  126963. v = pParse->pVdbe;
  126964. assert( v!=0 );
  126965. addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  126966. /* Count the number of columns that will be added to the index
  126967. ** and used to match WHERE clause constraints */
  126968. nKeyCol = 0;
  126969. pTable = pSrc->pTab;
  126970. pWCEnd = &pWC->a[pWC->nTerm];
  126971. pLoop = pLevel->pWLoop;
  126972. idxCols = 0;
  126973. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  126974. Expr *pExpr = pTerm->pExpr;
  126975. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  126976. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  126977. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  126978. if( pLoop->prereq==0
  126979. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  126980. && !ExprHasProperty(pExpr, EP_FromJoin)
  126981. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  126982. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  126983. sqlite3ExprDup(pParse->db, pExpr, 0));
  126984. }
  126985. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  126986. int iCol = pTerm->u.leftColumn;
  126987. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  126988. testcase( iCol==BMS );
  126989. testcase( iCol==BMS-1 );
  126990. if( !sentWarning ){
  126991. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  126992. "automatic index on %s(%s)", pTable->zName,
  126993. pTable->aCol[iCol].zName);
  126994. sentWarning = 1;
  126995. }
  126996. if( (idxCols & cMask)==0 ){
  126997. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  126998. goto end_auto_index_create;
  126999. }
  127000. pLoop->aLTerm[nKeyCol++] = pTerm;
  127001. idxCols |= cMask;
  127002. }
  127003. }
  127004. }
  127005. assert( nKeyCol>0 );
  127006. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  127007. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  127008. | WHERE_AUTO_INDEX;
  127009. /* Count the number of additional columns needed to create a
  127010. ** covering index. A "covering index" is an index that contains all
  127011. ** columns that are needed by the query. With a covering index, the
  127012. ** original table never needs to be accessed. Automatic indices must
  127013. ** be a covering index because the index will not be updated if the
  127014. ** original table changes and the index and table cannot both be used
  127015. ** if they go out of sync.
  127016. */
  127017. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  127018. mxBitCol = MIN(BMS-1,pTable->nCol);
  127019. testcase( pTable->nCol==BMS-1 );
  127020. testcase( pTable->nCol==BMS-2 );
  127021. for(i=0; i<mxBitCol; i++){
  127022. if( extraCols & MASKBIT(i) ) nKeyCol++;
  127023. }
  127024. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  127025. nKeyCol += pTable->nCol - BMS + 1;
  127026. }
  127027. /* Construct the Index object to describe this index */
  127028. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  127029. if( pIdx==0 ) goto end_auto_index_create;
  127030. pLoop->u.btree.pIndex = pIdx;
  127031. pIdx->zName = "auto-index";
  127032. pIdx->pTable = pTable;
  127033. n = 0;
  127034. idxCols = 0;
  127035. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  127036. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  127037. int iCol = pTerm->u.leftColumn;
  127038. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  127039. testcase( iCol==BMS-1 );
  127040. testcase( iCol==BMS );
  127041. if( (idxCols & cMask)==0 ){
  127042. Expr *pX = pTerm->pExpr;
  127043. idxCols |= cMask;
  127044. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  127045. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  127046. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  127047. n++;
  127048. }
  127049. }
  127050. }
  127051. assert( (u32)n==pLoop->u.btree.nEq );
  127052. /* Add additional columns needed to make the automatic index into
  127053. ** a covering index */
  127054. for(i=0; i<mxBitCol; i++){
  127055. if( extraCols & MASKBIT(i) ){
  127056. pIdx->aiColumn[n] = i;
  127057. pIdx->azColl[n] = sqlite3StrBINARY;
  127058. n++;
  127059. }
  127060. }
  127061. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  127062. for(i=BMS-1; i<pTable->nCol; i++){
  127063. pIdx->aiColumn[n] = i;
  127064. pIdx->azColl[n] = sqlite3StrBINARY;
  127065. n++;
  127066. }
  127067. }
  127068. assert( n==nKeyCol );
  127069. pIdx->aiColumn[n] = XN_ROWID;
  127070. pIdx->azColl[n] = sqlite3StrBINARY;
  127071. /* Create the automatic index */
  127072. assert( pLevel->iIdxCur>=0 );
  127073. pLevel->iIdxCur = pParse->nTab++;
  127074. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  127075. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  127076. VdbeComment((v, "for %s", pTable->zName));
  127077. /* Fill the automatic index with content */
  127078. sqlite3ExprCachePush(pParse);
  127079. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  127080. if( pTabItem->fg.viaCoroutine ){
  127081. int regYield = pTabItem->regReturn;
  127082. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  127083. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  127084. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  127085. VdbeCoverage(v);
  127086. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  127087. }else{
  127088. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  127089. }
  127090. if( pPartial ){
  127091. iContinue = sqlite3VdbeMakeLabel(v);
  127092. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  127093. pLoop->wsFlags |= WHERE_PARTIALIDX;
  127094. }
  127095. regRecord = sqlite3GetTempReg(pParse);
  127096. regBase = sqlite3GenerateIndexKey(
  127097. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  127098. );
  127099. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  127100. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  127101. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  127102. if( pTabItem->fg.viaCoroutine ){
  127103. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  127104. testcase( pParse->db->mallocFailed );
  127105. translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
  127106. pTabItem->regResult, 1);
  127107. sqlite3VdbeGoto(v, addrTop);
  127108. pTabItem->fg.viaCoroutine = 0;
  127109. }else{
  127110. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  127111. }
  127112. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  127113. sqlite3VdbeJumpHere(v, addrTop);
  127114. sqlite3ReleaseTempReg(pParse, regRecord);
  127115. sqlite3ExprCachePop(pParse);
  127116. /* Jump here when skipping the initialization */
  127117. sqlite3VdbeJumpHere(v, addrInit);
  127118. end_auto_index_create:
  127119. sqlite3ExprDelete(pParse->db, pPartial);
  127120. }
  127121. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  127122. #ifndef SQLITE_OMIT_VIRTUALTABLE
  127123. /*
  127124. ** Allocate and populate an sqlite3_index_info structure. It is the
  127125. ** responsibility of the caller to eventually release the structure
  127126. ** by passing the pointer returned by this function to sqlite3_free().
  127127. */
  127128. static sqlite3_index_info *allocateIndexInfo(
  127129. Parse *pParse, /* The parsing context */
  127130. WhereClause *pWC, /* The WHERE clause being analyzed */
  127131. Bitmask mUnusable, /* Ignore terms with these prereqs */
  127132. struct SrcList_item *pSrc, /* The FROM clause term that is the vtab */
  127133. ExprList *pOrderBy, /* The ORDER BY clause */
  127134. u16 *pmNoOmit /* Mask of terms not to omit */
  127135. ){
  127136. int i, j;
  127137. int nTerm;
  127138. struct sqlite3_index_constraint *pIdxCons;
  127139. struct sqlite3_index_orderby *pIdxOrderBy;
  127140. struct sqlite3_index_constraint_usage *pUsage;
  127141. struct HiddenIndexInfo *pHidden;
  127142. WhereTerm *pTerm;
  127143. int nOrderBy;
  127144. sqlite3_index_info *pIdxInfo;
  127145. u16 mNoOmit = 0;
  127146. /* Count the number of possible WHERE clause constraints referring
  127147. ** to this virtual table */
  127148. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  127149. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  127150. if( pTerm->prereqRight & mUnusable ) continue;
  127151. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  127152. testcase( pTerm->eOperator & WO_IN );
  127153. testcase( pTerm->eOperator & WO_ISNULL );
  127154. testcase( pTerm->eOperator & WO_IS );
  127155. testcase( pTerm->eOperator & WO_ALL );
  127156. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  127157. if( pTerm->wtFlags & TERM_VNULL ) continue;
  127158. assert( pTerm->u.leftColumn>=(-1) );
  127159. nTerm++;
  127160. }
  127161. /* If the ORDER BY clause contains only columns in the current
  127162. ** virtual table then allocate space for the aOrderBy part of
  127163. ** the sqlite3_index_info structure.
  127164. */
  127165. nOrderBy = 0;
  127166. if( pOrderBy ){
  127167. int n = pOrderBy->nExpr;
  127168. for(i=0; i<n; i++){
  127169. Expr *pExpr = pOrderBy->a[i].pExpr;
  127170. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  127171. }
  127172. if( i==n){
  127173. nOrderBy = n;
  127174. }
  127175. }
  127176. /* Allocate the sqlite3_index_info structure
  127177. */
  127178. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  127179. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  127180. + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );
  127181. if( pIdxInfo==0 ){
  127182. sqlite3ErrorMsg(pParse, "out of memory");
  127183. return 0;
  127184. }
  127185. /* Initialize the structure. The sqlite3_index_info structure contains
  127186. ** many fields that are declared "const" to prevent xBestIndex from
  127187. ** changing them. We have to do some funky casting in order to
  127188. ** initialize those fields.
  127189. */
  127190. pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
  127191. pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
  127192. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  127193. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  127194. *(int*)&pIdxInfo->nConstraint = nTerm;
  127195. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  127196. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  127197. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  127198. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  127199. pUsage;
  127200. pHidden->pWC = pWC;
  127201. pHidden->pParse = pParse;
  127202. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  127203. u16 op;
  127204. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  127205. if( pTerm->prereqRight & mUnusable ) continue;
  127206. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  127207. testcase( pTerm->eOperator & WO_IN );
  127208. testcase( pTerm->eOperator & WO_IS );
  127209. testcase( pTerm->eOperator & WO_ISNULL );
  127210. testcase( pTerm->eOperator & WO_ALL );
  127211. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  127212. if( pTerm->wtFlags & TERM_VNULL ) continue;
  127213. assert( pTerm->u.leftColumn>=(-1) );
  127214. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  127215. pIdxCons[j].iTermOffset = i;
  127216. op = pTerm->eOperator & WO_ALL;
  127217. if( op==WO_IN ) op = WO_EQ;
  127218. if( op==WO_AUX ){
  127219. pIdxCons[j].op = pTerm->eMatchOp;
  127220. }else if( op & (WO_ISNULL|WO_IS) ){
  127221. if( op==WO_ISNULL ){
  127222. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
  127223. }else{
  127224. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
  127225. }
  127226. }else{
  127227. pIdxCons[j].op = (u8)op;
  127228. /* The direct assignment in the previous line is possible only because
  127229. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  127230. ** following asserts verify this fact. */
  127231. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  127232. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  127233. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  127234. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  127235. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  127236. assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
  127237. if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
  127238. && sqlite3ExprIsVector(pTerm->pExpr->pRight)
  127239. ){
  127240. if( i<16 ) mNoOmit |= (1 << i);
  127241. if( op==WO_LT ) pIdxCons[j].op = WO_LE;
  127242. if( op==WO_GT ) pIdxCons[j].op = WO_GE;
  127243. }
  127244. }
  127245. j++;
  127246. }
  127247. for(i=0; i<nOrderBy; i++){
  127248. Expr *pExpr = pOrderBy->a[i].pExpr;
  127249. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  127250. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  127251. }
  127252. *pmNoOmit = mNoOmit;
  127253. return pIdxInfo;
  127254. }
  127255. /*
  127256. ** The table object reference passed as the second argument to this function
  127257. ** must represent a virtual table. This function invokes the xBestIndex()
  127258. ** method of the virtual table with the sqlite3_index_info object that
  127259. ** comes in as the 3rd argument to this function.
  127260. **
  127261. ** If an error occurs, pParse is populated with an error message and a
  127262. ** non-zero value is returned. Otherwise, 0 is returned and the output
  127263. ** part of the sqlite3_index_info structure is left populated.
  127264. **
  127265. ** Whether or not an error is returned, it is the responsibility of the
  127266. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  127267. ** that this is required.
  127268. */
  127269. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  127270. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  127271. int rc;
  127272. TRACE_IDX_INPUTS(p);
  127273. rc = pVtab->pModule->xBestIndex(pVtab, p);
  127274. TRACE_IDX_OUTPUTS(p);
  127275. if( rc!=SQLITE_OK ){
  127276. if( rc==SQLITE_NOMEM ){
  127277. sqlite3OomFault(pParse->db);
  127278. }else if( !pVtab->zErrMsg ){
  127279. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  127280. }else{
  127281. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  127282. }
  127283. }
  127284. sqlite3_free(pVtab->zErrMsg);
  127285. pVtab->zErrMsg = 0;
  127286. #if 0
  127287. /* This error is now caught by the caller.
  127288. ** Search for "xBestIndex malfunction" below */
  127289. for(i=0; i<p->nConstraint; i++){
  127290. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  127291. sqlite3ErrorMsg(pParse,
  127292. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  127293. }
  127294. }
  127295. #endif
  127296. return pParse->nErr;
  127297. }
  127298. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  127299. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  127300. /*
  127301. ** Estimate the location of a particular key among all keys in an
  127302. ** index. Store the results in aStat as follows:
  127303. **
  127304. ** aStat[0] Est. number of rows less than pRec
  127305. ** aStat[1] Est. number of rows equal to pRec
  127306. **
  127307. ** Return the index of the sample that is the smallest sample that
  127308. ** is greater than or equal to pRec. Note that this index is not an index
  127309. ** into the aSample[] array - it is an index into a virtual set of samples
  127310. ** based on the contents of aSample[] and the number of fields in record
  127311. ** pRec.
  127312. */
  127313. static int whereKeyStats(
  127314. Parse *pParse, /* Database connection */
  127315. Index *pIdx, /* Index to consider domain of */
  127316. UnpackedRecord *pRec, /* Vector of values to consider */
  127317. int roundUp, /* Round up if true. Round down if false */
  127318. tRowcnt *aStat /* OUT: stats written here */
  127319. ){
  127320. IndexSample *aSample = pIdx->aSample;
  127321. int iCol; /* Index of required stats in anEq[] etc. */
  127322. int i; /* Index of first sample >= pRec */
  127323. int iSample; /* Smallest sample larger than or equal to pRec */
  127324. int iMin = 0; /* Smallest sample not yet tested */
  127325. int iTest; /* Next sample to test */
  127326. int res; /* Result of comparison operation */
  127327. int nField; /* Number of fields in pRec */
  127328. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  127329. #ifndef SQLITE_DEBUG
  127330. UNUSED_PARAMETER( pParse );
  127331. #endif
  127332. assert( pRec!=0 );
  127333. assert( pIdx->nSample>0 );
  127334. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  127335. /* Do a binary search to find the first sample greater than or equal
  127336. ** to pRec. If pRec contains a single field, the set of samples to search
  127337. ** is simply the aSample[] array. If the samples in aSample[] contain more
  127338. ** than one fields, all fields following the first are ignored.
  127339. **
  127340. ** If pRec contains N fields, where N is more than one, then as well as the
  127341. ** samples in aSample[] (truncated to N fields), the search also has to
  127342. ** consider prefixes of those samples. For example, if the set of samples
  127343. ** in aSample is:
  127344. **
  127345. ** aSample[0] = (a, 5)
  127346. ** aSample[1] = (a, 10)
  127347. ** aSample[2] = (b, 5)
  127348. ** aSample[3] = (c, 100)
  127349. ** aSample[4] = (c, 105)
  127350. **
  127351. ** Then the search space should ideally be the samples above and the
  127352. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  127353. ** the code actually searches this set:
  127354. **
  127355. ** 0: (a)
  127356. ** 1: (a, 5)
  127357. ** 2: (a, 10)
  127358. ** 3: (a, 10)
  127359. ** 4: (b)
  127360. ** 5: (b, 5)
  127361. ** 6: (c)
  127362. ** 7: (c, 100)
  127363. ** 8: (c, 105)
  127364. ** 9: (c, 105)
  127365. **
  127366. ** For each sample in the aSample[] array, N samples are present in the
  127367. ** effective sample array. In the above, samples 0 and 1 are based on
  127368. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  127369. **
  127370. ** Often, sample i of each block of N effective samples has (i+1) fields.
  127371. ** Except, each sample may be extended to ensure that it is greater than or
  127372. ** equal to the previous sample in the array. For example, in the above,
  127373. ** sample 2 is the first sample of a block of N samples, so at first it
  127374. ** appears that it should be 1 field in size. However, that would make it
  127375. ** smaller than sample 1, so the binary search would not work. As a result,
  127376. ** it is extended to two fields. The duplicates that this creates do not
  127377. ** cause any problems.
  127378. */
  127379. nField = pRec->nField;
  127380. iCol = 0;
  127381. iSample = pIdx->nSample * nField;
  127382. do{
  127383. int iSamp; /* Index in aSample[] of test sample */
  127384. int n; /* Number of fields in test sample */
  127385. iTest = (iMin+iSample)/2;
  127386. iSamp = iTest / nField;
  127387. if( iSamp>0 ){
  127388. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  127389. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  127390. ** fields that is greater than the previous effective sample. */
  127391. for(n=(iTest % nField) + 1; n<nField; n++){
  127392. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  127393. }
  127394. }else{
  127395. n = iTest + 1;
  127396. }
  127397. pRec->nField = n;
  127398. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  127399. if( res<0 ){
  127400. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  127401. iMin = iTest+1;
  127402. }else if( res==0 && n<nField ){
  127403. iLower = aSample[iSamp].anLt[n-1];
  127404. iMin = iTest+1;
  127405. res = -1;
  127406. }else{
  127407. iSample = iTest;
  127408. iCol = n-1;
  127409. }
  127410. }while( res && iMin<iSample );
  127411. i = iSample / nField;
  127412. #ifdef SQLITE_DEBUG
  127413. /* The following assert statements check that the binary search code
  127414. ** above found the right answer. This block serves no purpose other
  127415. ** than to invoke the asserts. */
  127416. if( pParse->db->mallocFailed==0 ){
  127417. if( res==0 ){
  127418. /* If (res==0) is true, then pRec must be equal to sample i. */
  127419. assert( i<pIdx->nSample );
  127420. assert( iCol==nField-1 );
  127421. pRec->nField = nField;
  127422. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  127423. || pParse->db->mallocFailed
  127424. );
  127425. }else{
  127426. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  127427. ** all samples in the aSample[] array, pRec must be smaller than the
  127428. ** (iCol+1) field prefix of sample i. */
  127429. assert( i<=pIdx->nSample && i>=0 );
  127430. pRec->nField = iCol+1;
  127431. assert( i==pIdx->nSample
  127432. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  127433. || pParse->db->mallocFailed );
  127434. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  127435. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  127436. ** be greater than or equal to the (iCol) field prefix of sample i.
  127437. ** If (i>0), then pRec must also be greater than sample (i-1). */
  127438. if( iCol>0 ){
  127439. pRec->nField = iCol;
  127440. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  127441. || pParse->db->mallocFailed );
  127442. }
  127443. if( i>0 ){
  127444. pRec->nField = nField;
  127445. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  127446. || pParse->db->mallocFailed );
  127447. }
  127448. }
  127449. }
  127450. #endif /* ifdef SQLITE_DEBUG */
  127451. if( res==0 ){
  127452. /* Record pRec is equal to sample i */
  127453. assert( iCol==nField-1 );
  127454. aStat[0] = aSample[i].anLt[iCol];
  127455. aStat[1] = aSample[i].anEq[iCol];
  127456. }else{
  127457. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  127458. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  127459. ** is larger than all samples in the array. */
  127460. tRowcnt iUpper, iGap;
  127461. if( i>=pIdx->nSample ){
  127462. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  127463. }else{
  127464. iUpper = aSample[i].anLt[iCol];
  127465. }
  127466. if( iLower>=iUpper ){
  127467. iGap = 0;
  127468. }else{
  127469. iGap = iUpper - iLower;
  127470. }
  127471. if( roundUp ){
  127472. iGap = (iGap*2)/3;
  127473. }else{
  127474. iGap = iGap/3;
  127475. }
  127476. aStat[0] = iLower + iGap;
  127477. aStat[1] = pIdx->aAvgEq[nField-1];
  127478. }
  127479. /* Restore the pRec->nField value before returning. */
  127480. pRec->nField = nField;
  127481. return i;
  127482. }
  127483. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  127484. /*
  127485. ** If it is not NULL, pTerm is a term that provides an upper or lower
  127486. ** bound on a range scan. Without considering pTerm, it is estimated
  127487. ** that the scan will visit nNew rows. This function returns the number
  127488. ** estimated to be visited after taking pTerm into account.
  127489. **
  127490. ** If the user explicitly specified a likelihood() value for this term,
  127491. ** then the return value is the likelihood multiplied by the number of
  127492. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  127493. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  127494. */
  127495. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  127496. LogEst nRet = nNew;
  127497. if( pTerm ){
  127498. if( pTerm->truthProb<=0 ){
  127499. nRet += pTerm->truthProb;
  127500. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  127501. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  127502. }
  127503. }
  127504. return nRet;
  127505. }
  127506. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  127507. /*
  127508. ** Return the affinity for a single column of an index.
  127509. */
  127510. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  127511. assert( iCol>=0 && iCol<pIdx->nColumn );
  127512. if( !pIdx->zColAff ){
  127513. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  127514. }
  127515. return pIdx->zColAff[iCol];
  127516. }
  127517. #endif
  127518. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  127519. /*
  127520. ** This function is called to estimate the number of rows visited by a
  127521. ** range-scan on a skip-scan index. For example:
  127522. **
  127523. ** CREATE INDEX i1 ON t1(a, b, c);
  127524. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  127525. **
  127526. ** Value pLoop->nOut is currently set to the estimated number of rows
  127527. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  127528. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  127529. ** on the stat4 data for the index. this scan will be peformed multiple
  127530. ** times (once for each (a,b) combination that matches a=?) is dealt with
  127531. ** by the caller.
  127532. **
  127533. ** It does this by scanning through all stat4 samples, comparing values
  127534. ** extracted from pLower and pUpper with the corresponding column in each
  127535. ** sample. If L and U are the number of samples found to be less than or
  127536. ** equal to the values extracted from pLower and pUpper respectively, and
  127537. ** N is the total number of samples, the pLoop->nOut value is adjusted
  127538. ** as follows:
  127539. **
  127540. ** nOut = nOut * ( min(U - L, 1) / N )
  127541. **
  127542. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  127543. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  127544. ** U is set to N.
  127545. **
  127546. ** Normally, this function sets *pbDone to 1 before returning. However,
  127547. ** if no value can be extracted from either pLower or pUpper (and so the
  127548. ** estimate of the number of rows delivered remains unchanged), *pbDone
  127549. ** is left as is.
  127550. **
  127551. ** If an error occurs, an SQLite error code is returned. Otherwise,
  127552. ** SQLITE_OK.
  127553. */
  127554. static int whereRangeSkipScanEst(
  127555. Parse *pParse, /* Parsing & code generating context */
  127556. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  127557. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  127558. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  127559. int *pbDone /* Set to true if at least one expr. value extracted */
  127560. ){
  127561. Index *p = pLoop->u.btree.pIndex;
  127562. int nEq = pLoop->u.btree.nEq;
  127563. sqlite3 *db = pParse->db;
  127564. int nLower = -1;
  127565. int nUpper = p->nSample+1;
  127566. int rc = SQLITE_OK;
  127567. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  127568. CollSeq *pColl;
  127569. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  127570. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  127571. sqlite3_value *pVal = 0; /* Value extracted from record */
  127572. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  127573. if( pLower ){
  127574. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  127575. nLower = 0;
  127576. }
  127577. if( pUpper && rc==SQLITE_OK ){
  127578. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  127579. nUpper = p2 ? 0 : p->nSample;
  127580. }
  127581. if( p1 || p2 ){
  127582. int i;
  127583. int nDiff;
  127584. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  127585. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  127586. if( rc==SQLITE_OK && p1 ){
  127587. int res = sqlite3MemCompare(p1, pVal, pColl);
  127588. if( res>=0 ) nLower++;
  127589. }
  127590. if( rc==SQLITE_OK && p2 ){
  127591. int res = sqlite3MemCompare(p2, pVal, pColl);
  127592. if( res>=0 ) nUpper++;
  127593. }
  127594. }
  127595. nDiff = (nUpper - nLower);
  127596. if( nDiff<=0 ) nDiff = 1;
  127597. /* If there is both an upper and lower bound specified, and the
  127598. ** comparisons indicate that they are close together, use the fallback
  127599. ** method (assume that the scan visits 1/64 of the rows) for estimating
  127600. ** the number of rows visited. Otherwise, estimate the number of rows
  127601. ** using the method described in the header comment for this function. */
  127602. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  127603. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  127604. pLoop->nOut -= nAdjust;
  127605. *pbDone = 1;
  127606. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  127607. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  127608. }
  127609. }else{
  127610. assert( *pbDone==0 );
  127611. }
  127612. sqlite3ValueFree(p1);
  127613. sqlite3ValueFree(p2);
  127614. sqlite3ValueFree(pVal);
  127615. return rc;
  127616. }
  127617. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  127618. /*
  127619. ** This function is used to estimate the number of rows that will be visited
  127620. ** by scanning an index for a range of values. The range may have an upper
  127621. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  127622. ** and lower bounds are represented by pLower and pUpper respectively. For
  127623. ** example, assuming that index p is on t1(a):
  127624. **
  127625. ** ... FROM t1 WHERE a > ? AND a < ? ...
  127626. ** |_____| |_____|
  127627. ** | |
  127628. ** pLower pUpper
  127629. **
  127630. ** If either of the upper or lower bound is not present, then NULL is passed in
  127631. ** place of the corresponding WhereTerm.
  127632. **
  127633. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  127634. ** column subject to the range constraint. Or, equivalently, the number of
  127635. ** equality constraints optimized by the proposed index scan. For example,
  127636. ** assuming index p is on t1(a, b), and the SQL query is:
  127637. **
  127638. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  127639. **
  127640. ** then nEq is set to 1 (as the range restricted column, b, is the second
  127641. ** left-most column of the index). Or, if the query is:
  127642. **
  127643. ** ... FROM t1 WHERE a > ? AND a < ? ...
  127644. **
  127645. ** then nEq is set to 0.
  127646. **
  127647. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  127648. ** number of rows that the index scan is expected to visit without
  127649. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  127650. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  127651. ** to account for the range constraints pLower and pUpper.
  127652. **
  127653. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  127654. ** used, a single range inequality reduces the search space by a factor of 4.
  127655. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  127656. ** rows visited by a factor of 64.
  127657. */
  127658. static int whereRangeScanEst(
  127659. Parse *pParse, /* Parsing & code generating context */
  127660. WhereLoopBuilder *pBuilder,
  127661. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  127662. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  127663. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  127664. ){
  127665. int rc = SQLITE_OK;
  127666. int nOut = pLoop->nOut;
  127667. LogEst nNew;
  127668. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  127669. Index *p = pLoop->u.btree.pIndex;
  127670. int nEq = pLoop->u.btree.nEq;
  127671. if( p->nSample>0 && nEq<p->nSampleCol ){
  127672. if( nEq==pBuilder->nRecValid ){
  127673. UnpackedRecord *pRec = pBuilder->pRec;
  127674. tRowcnt a[2];
  127675. int nBtm = pLoop->u.btree.nBtm;
  127676. int nTop = pLoop->u.btree.nTop;
  127677. /* Variable iLower will be set to the estimate of the number of rows in
  127678. ** the index that are less than the lower bound of the range query. The
  127679. ** lower bound being the concatenation of $P and $L, where $P is the
  127680. ** key-prefix formed by the nEq values matched against the nEq left-most
  127681. ** columns of the index, and $L is the value in pLower.
  127682. **
  127683. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  127684. ** is not a simple variable or literal value), the lower bound of the
  127685. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  127686. ** if $L is available, whereKeyStats() is called for both ($P) and
  127687. ** ($P:$L) and the larger of the two returned values is used.
  127688. **
  127689. ** Similarly, iUpper is to be set to the estimate of the number of rows
  127690. ** less than the upper bound of the range query. Where the upper bound
  127691. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  127692. ** of iUpper are requested of whereKeyStats() and the smaller used.
  127693. **
  127694. ** The number of rows between the two bounds is then just iUpper-iLower.
  127695. */
  127696. tRowcnt iLower; /* Rows less than the lower bound */
  127697. tRowcnt iUpper; /* Rows less than the upper bound */
  127698. int iLwrIdx = -2; /* aSample[] for the lower bound */
  127699. int iUprIdx = -1; /* aSample[] for the upper bound */
  127700. if( pRec ){
  127701. testcase( pRec->nField!=pBuilder->nRecValid );
  127702. pRec->nField = pBuilder->nRecValid;
  127703. }
  127704. /* Determine iLower and iUpper using ($P) only. */
  127705. if( nEq==0 ){
  127706. iLower = 0;
  127707. iUpper = p->nRowEst0;
  127708. }else{
  127709. /* Note: this call could be optimized away - since the same values must
  127710. ** have been requested when testing key $P in whereEqualScanEst(). */
  127711. whereKeyStats(pParse, p, pRec, 0, a);
  127712. iLower = a[0];
  127713. iUpper = a[0] + a[1];
  127714. }
  127715. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  127716. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  127717. assert( p->aSortOrder!=0 );
  127718. if( p->aSortOrder[nEq] ){
  127719. /* The roles of pLower and pUpper are swapped for a DESC index */
  127720. SWAP(WhereTerm*, pLower, pUpper);
  127721. SWAP(int, nBtm, nTop);
  127722. }
  127723. /* If possible, improve on the iLower estimate using ($P:$L). */
  127724. if( pLower ){
  127725. int n; /* Values extracted from pExpr */
  127726. Expr *pExpr = pLower->pExpr->pRight;
  127727. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
  127728. if( rc==SQLITE_OK && n ){
  127729. tRowcnt iNew;
  127730. u16 mask = WO_GT|WO_LE;
  127731. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  127732. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  127733. iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
  127734. if( iNew>iLower ) iLower = iNew;
  127735. nOut--;
  127736. pLower = 0;
  127737. }
  127738. }
  127739. /* If possible, improve on the iUpper estimate using ($P:$U). */
  127740. if( pUpper ){
  127741. int n; /* Values extracted from pExpr */
  127742. Expr *pExpr = pUpper->pExpr->pRight;
  127743. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
  127744. if( rc==SQLITE_OK && n ){
  127745. tRowcnt iNew;
  127746. u16 mask = WO_GT|WO_LE;
  127747. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  127748. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  127749. iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
  127750. if( iNew<iUpper ) iUpper = iNew;
  127751. nOut--;
  127752. pUpper = 0;
  127753. }
  127754. }
  127755. pBuilder->pRec = pRec;
  127756. if( rc==SQLITE_OK ){
  127757. if( iUpper>iLower ){
  127758. nNew = sqlite3LogEst(iUpper - iLower);
  127759. /* TUNING: If both iUpper and iLower are derived from the same
  127760. ** sample, then assume they are 4x more selective. This brings
  127761. ** the estimated selectivity more in line with what it would be
  127762. ** if estimated without the use of STAT3/4 tables. */
  127763. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  127764. }else{
  127765. nNew = 10; assert( 10==sqlite3LogEst(2) );
  127766. }
  127767. if( nNew<nOut ){
  127768. nOut = nNew;
  127769. }
  127770. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  127771. (u32)iLower, (u32)iUpper, nOut));
  127772. }
  127773. }else{
  127774. int bDone = 0;
  127775. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  127776. if( bDone ) return rc;
  127777. }
  127778. }
  127779. #else
  127780. UNUSED_PARAMETER(pParse);
  127781. UNUSED_PARAMETER(pBuilder);
  127782. assert( pLower || pUpper );
  127783. #endif
  127784. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  127785. nNew = whereRangeAdjust(pLower, nOut);
  127786. nNew = whereRangeAdjust(pUpper, nNew);
  127787. /* TUNING: If there is both an upper and lower limit and neither limit
  127788. ** has an application-defined likelihood(), assume the range is
  127789. ** reduced by an additional 75%. This means that, by default, an open-ended
  127790. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  127791. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  127792. ** match 1/64 of the index. */
  127793. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  127794. nNew -= 20;
  127795. }
  127796. nOut -= (pLower!=0) + (pUpper!=0);
  127797. if( nNew<10 ) nNew = 10;
  127798. if( nNew<nOut ) nOut = nNew;
  127799. #if defined(WHERETRACE_ENABLED)
  127800. if( pLoop->nOut>nOut ){
  127801. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  127802. pLoop->nOut, nOut));
  127803. }
  127804. #endif
  127805. pLoop->nOut = (LogEst)nOut;
  127806. return rc;
  127807. }
  127808. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  127809. /*
  127810. ** Estimate the number of rows that will be returned based on
  127811. ** an equality constraint x=VALUE and where that VALUE occurs in
  127812. ** the histogram data. This only works when x is the left-most
  127813. ** column of an index and sqlite_stat3 histogram data is available
  127814. ** for that index. When pExpr==NULL that means the constraint is
  127815. ** "x IS NULL" instead of "x=VALUE".
  127816. **
  127817. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  127818. ** If unable to make an estimate, leave *pnRow unchanged and return
  127819. ** non-zero.
  127820. **
  127821. ** This routine can fail if it is unable to load a collating sequence
  127822. ** required for string comparison, or if unable to allocate memory
  127823. ** for a UTF conversion required for comparison. The error is stored
  127824. ** in the pParse structure.
  127825. */
  127826. static int whereEqualScanEst(
  127827. Parse *pParse, /* Parsing & code generating context */
  127828. WhereLoopBuilder *pBuilder,
  127829. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  127830. tRowcnt *pnRow /* Write the revised row estimate here */
  127831. ){
  127832. Index *p = pBuilder->pNew->u.btree.pIndex;
  127833. int nEq = pBuilder->pNew->u.btree.nEq;
  127834. UnpackedRecord *pRec = pBuilder->pRec;
  127835. int rc; /* Subfunction return code */
  127836. tRowcnt a[2]; /* Statistics */
  127837. int bOk;
  127838. assert( nEq>=1 );
  127839. assert( nEq<=p->nColumn );
  127840. assert( p->aSample!=0 );
  127841. assert( p->nSample>0 );
  127842. assert( pBuilder->nRecValid<nEq );
  127843. /* If values are not available for all fields of the index to the left
  127844. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  127845. if( pBuilder->nRecValid<(nEq-1) ){
  127846. return SQLITE_NOTFOUND;
  127847. }
  127848. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  127849. ** below would return the same value. */
  127850. if( nEq>=p->nColumn ){
  127851. *pnRow = 1;
  127852. return SQLITE_OK;
  127853. }
  127854. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
  127855. pBuilder->pRec = pRec;
  127856. if( rc!=SQLITE_OK ) return rc;
  127857. if( bOk==0 ) return SQLITE_NOTFOUND;
  127858. pBuilder->nRecValid = nEq;
  127859. whereKeyStats(pParse, p, pRec, 0, a);
  127860. WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
  127861. p->zName, nEq-1, (int)a[1]));
  127862. *pnRow = a[1];
  127863. return rc;
  127864. }
  127865. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  127866. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  127867. /*
  127868. ** Estimate the number of rows that will be returned based on
  127869. ** an IN constraint where the right-hand side of the IN operator
  127870. ** is a list of values. Example:
  127871. **
  127872. ** WHERE x IN (1,2,3,4)
  127873. **
  127874. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  127875. ** If unable to make an estimate, leave *pnRow unchanged and return
  127876. ** non-zero.
  127877. **
  127878. ** This routine can fail if it is unable to load a collating sequence
  127879. ** required for string comparison, or if unable to allocate memory
  127880. ** for a UTF conversion required for comparison. The error is stored
  127881. ** in the pParse structure.
  127882. */
  127883. static int whereInScanEst(
  127884. Parse *pParse, /* Parsing & code generating context */
  127885. WhereLoopBuilder *pBuilder,
  127886. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  127887. tRowcnt *pnRow /* Write the revised row estimate here */
  127888. ){
  127889. Index *p = pBuilder->pNew->u.btree.pIndex;
  127890. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  127891. int nRecValid = pBuilder->nRecValid;
  127892. int rc = SQLITE_OK; /* Subfunction return code */
  127893. tRowcnt nEst; /* Number of rows for a single term */
  127894. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  127895. int i; /* Loop counter */
  127896. assert( p->aSample!=0 );
  127897. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  127898. nEst = nRow0;
  127899. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  127900. nRowEst += nEst;
  127901. pBuilder->nRecValid = nRecValid;
  127902. }
  127903. if( rc==SQLITE_OK ){
  127904. if( nRowEst > nRow0 ) nRowEst = nRow0;
  127905. *pnRow = nRowEst;
  127906. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  127907. }
  127908. assert( pBuilder->nRecValid==nRecValid );
  127909. return rc;
  127910. }
  127911. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  127912. #ifdef WHERETRACE_ENABLED
  127913. /*
  127914. ** Print the content of a WhereTerm object
  127915. */
  127916. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  127917. if( pTerm==0 ){
  127918. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  127919. }else{
  127920. char zType[4];
  127921. char zLeft[50];
  127922. memcpy(zType, "...", 4);
  127923. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  127924. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  127925. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  127926. if( pTerm->eOperator & WO_SINGLE ){
  127927. sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
  127928. pTerm->leftCursor, pTerm->u.leftColumn);
  127929. }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
  127930. sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
  127931. pTerm->u.pOrInfo->indexable);
  127932. }else{
  127933. sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
  127934. }
  127935. sqlite3DebugPrintf(
  127936. "TERM-%-3d %p %s %-12s prob=%-3d op=0x%03x wtFlags=0x%04x",
  127937. iTerm, pTerm, zType, zLeft, pTerm->truthProb,
  127938. pTerm->eOperator, pTerm->wtFlags);
  127939. if( pTerm->iField ){
  127940. sqlite3DebugPrintf(" iField=%d\n", pTerm->iField);
  127941. }else{
  127942. sqlite3DebugPrintf("\n");
  127943. }
  127944. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  127945. }
  127946. }
  127947. #endif
  127948. #ifdef WHERETRACE_ENABLED
  127949. /*
  127950. ** Show the complete content of a WhereClause
  127951. */
  127952. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
  127953. int i;
  127954. for(i=0; i<pWC->nTerm; i++){
  127955. whereTermPrint(&pWC->a[i], i);
  127956. }
  127957. }
  127958. #endif
  127959. #ifdef WHERETRACE_ENABLED
  127960. /*
  127961. ** Print a WhereLoop object for debugging purposes
  127962. */
  127963. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  127964. WhereInfo *pWInfo = pWC->pWInfo;
  127965. int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
  127966. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  127967. Table *pTab = pItem->pTab;
  127968. Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
  127969. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  127970. p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
  127971. sqlite3DebugPrintf(" %12s",
  127972. pItem->zAlias ? pItem->zAlias : pTab->zName);
  127973. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  127974. const char *zName;
  127975. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  127976. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  127977. int i = sqlite3Strlen30(zName) - 1;
  127978. while( zName[i]!='_' ) i--;
  127979. zName += i;
  127980. }
  127981. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  127982. }else{
  127983. sqlite3DebugPrintf("%20s","");
  127984. }
  127985. }else{
  127986. char *z;
  127987. if( p->u.vtab.idxStr ){
  127988. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  127989. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  127990. }else{
  127991. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  127992. }
  127993. sqlite3DebugPrintf(" %-19s", z);
  127994. sqlite3_free(z);
  127995. }
  127996. if( p->wsFlags & WHERE_SKIPSCAN ){
  127997. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  127998. }else{
  127999. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  128000. }
  128001. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  128002. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  128003. int i;
  128004. for(i=0; i<p->nLTerm; i++){
  128005. whereTermPrint(p->aLTerm[i], i);
  128006. }
  128007. }
  128008. }
  128009. #endif
  128010. /*
  128011. ** Convert bulk memory into a valid WhereLoop that can be passed
  128012. ** to whereLoopClear harmlessly.
  128013. */
  128014. static void whereLoopInit(WhereLoop *p){
  128015. p->aLTerm = p->aLTermSpace;
  128016. p->nLTerm = 0;
  128017. p->nLSlot = ArraySize(p->aLTermSpace);
  128018. p->wsFlags = 0;
  128019. }
  128020. /*
  128021. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  128022. */
  128023. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  128024. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  128025. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  128026. sqlite3_free(p->u.vtab.idxStr);
  128027. p->u.vtab.needFree = 0;
  128028. p->u.vtab.idxStr = 0;
  128029. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  128030. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  128031. sqlite3DbFreeNN(db, p->u.btree.pIndex);
  128032. p->u.btree.pIndex = 0;
  128033. }
  128034. }
  128035. }
  128036. /*
  128037. ** Deallocate internal memory used by a WhereLoop object
  128038. */
  128039. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  128040. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  128041. whereLoopClearUnion(db, p);
  128042. whereLoopInit(p);
  128043. }
  128044. /*
  128045. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  128046. */
  128047. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  128048. WhereTerm **paNew;
  128049. if( p->nLSlot>=n ) return SQLITE_OK;
  128050. n = (n+7)&~7;
  128051. paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  128052. if( paNew==0 ) return SQLITE_NOMEM_BKPT;
  128053. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  128054. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  128055. p->aLTerm = paNew;
  128056. p->nLSlot = n;
  128057. return SQLITE_OK;
  128058. }
  128059. /*
  128060. ** Transfer content from the second pLoop into the first.
  128061. */
  128062. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  128063. whereLoopClearUnion(db, pTo);
  128064. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  128065. memset(&pTo->u, 0, sizeof(pTo->u));
  128066. return SQLITE_NOMEM_BKPT;
  128067. }
  128068. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  128069. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  128070. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  128071. pFrom->u.vtab.needFree = 0;
  128072. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  128073. pFrom->u.btree.pIndex = 0;
  128074. }
  128075. return SQLITE_OK;
  128076. }
  128077. /*
  128078. ** Delete a WhereLoop object
  128079. */
  128080. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  128081. whereLoopClear(db, p);
  128082. sqlite3DbFreeNN(db, p);
  128083. }
  128084. /*
  128085. ** Free a WhereInfo structure
  128086. */
  128087. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  128088. int i;
  128089. assert( pWInfo!=0 );
  128090. for(i=0; i<pWInfo->nLevel; i++){
  128091. WhereLevel *pLevel = &pWInfo->a[i];
  128092. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  128093. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  128094. }
  128095. }
  128096. sqlite3WhereClauseClear(&pWInfo->sWC);
  128097. while( pWInfo->pLoops ){
  128098. WhereLoop *p = pWInfo->pLoops;
  128099. pWInfo->pLoops = p->pNextLoop;
  128100. whereLoopDelete(db, p);
  128101. }
  128102. sqlite3DbFreeNN(db, pWInfo);
  128103. }
  128104. /*
  128105. ** Return TRUE if all of the following are true:
  128106. **
  128107. ** (1) X has the same or lower cost that Y
  128108. ** (2) X uses fewer WHERE clause terms than Y
  128109. ** (3) Every WHERE clause term used by X is also used by Y
  128110. ** (4) X skips at least as many columns as Y
  128111. ** (5) If X is a covering index, than Y is too
  128112. **
  128113. ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
  128114. ** If X is a proper subset of Y then Y is a better choice and ought
  128115. ** to have a lower cost. This routine returns TRUE when that cost
  128116. ** relationship is inverted and needs to be adjusted. Constraint (4)
  128117. ** was added because if X uses skip-scan less than Y it still might
  128118. ** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
  128119. ** was added because a covering index probably deserves to have a lower cost
  128120. ** than a non-covering index even if it is a proper subset.
  128121. */
  128122. static int whereLoopCheaperProperSubset(
  128123. const WhereLoop *pX, /* First WhereLoop to compare */
  128124. const WhereLoop *pY /* Compare against this WhereLoop */
  128125. ){
  128126. int i, j;
  128127. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  128128. return 0; /* X is not a subset of Y */
  128129. }
  128130. if( pY->nSkip > pX->nSkip ) return 0;
  128131. if( pX->rRun >= pY->rRun ){
  128132. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  128133. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  128134. }
  128135. for(i=pX->nLTerm-1; i>=0; i--){
  128136. if( pX->aLTerm[i]==0 ) continue;
  128137. for(j=pY->nLTerm-1; j>=0; j--){
  128138. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  128139. }
  128140. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  128141. }
  128142. if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
  128143. && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
  128144. return 0; /* Constraint (5) */
  128145. }
  128146. return 1; /* All conditions meet */
  128147. }
  128148. /*
  128149. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  128150. ** that:
  128151. **
  128152. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  128153. ** subset of pTemplate
  128154. **
  128155. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  128156. ** is a proper subset.
  128157. **
  128158. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  128159. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  128160. ** also used by Y.
  128161. */
  128162. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  128163. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  128164. for(; p; p=p->pNextLoop){
  128165. if( p->iTab!=pTemplate->iTab ) continue;
  128166. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  128167. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  128168. /* Adjust pTemplate cost downward so that it is cheaper than its
  128169. ** subset p. */
  128170. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  128171. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  128172. pTemplate->rRun = p->rRun;
  128173. pTemplate->nOut = p->nOut - 1;
  128174. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  128175. /* Adjust pTemplate cost upward so that it is costlier than p since
  128176. ** pTemplate is a proper subset of p */
  128177. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  128178. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  128179. pTemplate->rRun = p->rRun;
  128180. pTemplate->nOut = p->nOut + 1;
  128181. }
  128182. }
  128183. }
  128184. /*
  128185. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  128186. ** replaced by pTemplate.
  128187. **
  128188. ** Return NULL if pTemplate does not belong on the WhereLoop list.
  128189. ** In other words if pTemplate ought to be dropped from further consideration.
  128190. **
  128191. ** If pX is a WhereLoop that pTemplate can replace, then return the
  128192. ** link that points to pX.
  128193. **
  128194. ** If pTemplate cannot replace any existing element of the list but needs
  128195. ** to be added to the list as a new entry, then return a pointer to the
  128196. ** tail of the list.
  128197. */
  128198. static WhereLoop **whereLoopFindLesser(
  128199. WhereLoop **ppPrev,
  128200. const WhereLoop *pTemplate
  128201. ){
  128202. WhereLoop *p;
  128203. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  128204. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  128205. /* If either the iTab or iSortIdx values for two WhereLoop are different
  128206. ** then those WhereLoops need to be considered separately. Neither is
  128207. ** a candidate to replace the other. */
  128208. continue;
  128209. }
  128210. /* In the current implementation, the rSetup value is either zero
  128211. ** or the cost of building an automatic index (NlogN) and the NlogN
  128212. ** is the same for compatible WhereLoops. */
  128213. assert( p->rSetup==0 || pTemplate->rSetup==0
  128214. || p->rSetup==pTemplate->rSetup );
  128215. /* whereLoopAddBtree() always generates and inserts the automatic index
  128216. ** case first. Hence compatible candidate WhereLoops never have a larger
  128217. ** rSetup. Call this SETUP-INVARIANT */
  128218. assert( p->rSetup>=pTemplate->rSetup );
  128219. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  128220. ** UNIQUE constraint) with one or more == constraints is better
  128221. ** than an automatic index. Unless it is a skip-scan. */
  128222. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  128223. && (pTemplate->nSkip)==0
  128224. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  128225. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  128226. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  128227. ){
  128228. break;
  128229. }
  128230. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  128231. ** discarded. WhereLoop p is better if:
  128232. ** (1) p has no more dependencies than pTemplate, and
  128233. ** (2) p has an equal or lower cost than pTemplate
  128234. */
  128235. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  128236. && p->rSetup<=pTemplate->rSetup /* (2a) */
  128237. && p->rRun<=pTemplate->rRun /* (2b) */
  128238. && p->nOut<=pTemplate->nOut /* (2c) */
  128239. ){
  128240. return 0; /* Discard pTemplate */
  128241. }
  128242. /* If pTemplate is always better than p, then cause p to be overwritten
  128243. ** with pTemplate. pTemplate is better than p if:
  128244. ** (1) pTemplate has no more dependences than p, and
  128245. ** (2) pTemplate has an equal or lower cost than p.
  128246. */
  128247. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  128248. && p->rRun>=pTemplate->rRun /* (2a) */
  128249. && p->nOut>=pTemplate->nOut /* (2b) */
  128250. ){
  128251. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  128252. break; /* Cause p to be overwritten by pTemplate */
  128253. }
  128254. }
  128255. return ppPrev;
  128256. }
  128257. /*
  128258. ** Insert or replace a WhereLoop entry using the template supplied.
  128259. **
  128260. ** An existing WhereLoop entry might be overwritten if the new template
  128261. ** is better and has fewer dependencies. Or the template will be ignored
  128262. ** and no insert will occur if an existing WhereLoop is faster and has
  128263. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  128264. ** added based on the template.
  128265. **
  128266. ** If pBuilder->pOrSet is not NULL then we care about only the
  128267. ** prerequisites and rRun and nOut costs of the N best loops. That
  128268. ** information is gathered in the pBuilder->pOrSet object. This special
  128269. ** processing mode is used only for OR clause processing.
  128270. **
  128271. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  128272. ** still might overwrite similar loops with the new template if the
  128273. ** new template is better. Loops may be overwritten if the following
  128274. ** conditions are met:
  128275. **
  128276. ** (1) They have the same iTab.
  128277. ** (2) They have the same iSortIdx.
  128278. ** (3) The template has same or fewer dependencies than the current loop
  128279. ** (4) The template has the same or lower cost than the current loop
  128280. */
  128281. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  128282. WhereLoop **ppPrev, *p;
  128283. WhereInfo *pWInfo = pBuilder->pWInfo;
  128284. sqlite3 *db = pWInfo->pParse->db;
  128285. int rc;
  128286. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  128287. ** and prereqs.
  128288. */
  128289. if( pBuilder->pOrSet!=0 ){
  128290. if( pTemplate->nLTerm ){
  128291. #if WHERETRACE_ENABLED
  128292. u16 n = pBuilder->pOrSet->n;
  128293. int x =
  128294. #endif
  128295. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  128296. pTemplate->nOut);
  128297. #if WHERETRACE_ENABLED /* 0x8 */
  128298. if( sqlite3WhereTrace & 0x8 ){
  128299. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  128300. whereLoopPrint(pTemplate, pBuilder->pWC);
  128301. }
  128302. #endif
  128303. }
  128304. return SQLITE_OK;
  128305. }
  128306. /* Look for an existing WhereLoop to replace with pTemplate
  128307. */
  128308. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  128309. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  128310. if( ppPrev==0 ){
  128311. /* There already exists a WhereLoop on the list that is better
  128312. ** than pTemplate, so just ignore pTemplate */
  128313. #if WHERETRACE_ENABLED /* 0x8 */
  128314. if( sqlite3WhereTrace & 0x8 ){
  128315. sqlite3DebugPrintf(" skip: ");
  128316. whereLoopPrint(pTemplate, pBuilder->pWC);
  128317. }
  128318. #endif
  128319. return SQLITE_OK;
  128320. }else{
  128321. p = *ppPrev;
  128322. }
  128323. /* If we reach this point it means that either p[] should be overwritten
  128324. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  128325. ** WhereLoop and insert it.
  128326. */
  128327. #if WHERETRACE_ENABLED /* 0x8 */
  128328. if( sqlite3WhereTrace & 0x8 ){
  128329. if( p!=0 ){
  128330. sqlite3DebugPrintf("replace: ");
  128331. whereLoopPrint(p, pBuilder->pWC);
  128332. sqlite3DebugPrintf(" with: ");
  128333. }else{
  128334. sqlite3DebugPrintf(" add: ");
  128335. }
  128336. whereLoopPrint(pTemplate, pBuilder->pWC);
  128337. }
  128338. #endif
  128339. if( p==0 ){
  128340. /* Allocate a new WhereLoop to add to the end of the list */
  128341. *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  128342. if( p==0 ) return SQLITE_NOMEM_BKPT;
  128343. whereLoopInit(p);
  128344. p->pNextLoop = 0;
  128345. }else{
  128346. /* We will be overwriting WhereLoop p[]. But before we do, first
  128347. ** go through the rest of the list and delete any other entries besides
  128348. ** p[] that are also supplated by pTemplate */
  128349. WhereLoop **ppTail = &p->pNextLoop;
  128350. WhereLoop *pToDel;
  128351. while( *ppTail ){
  128352. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  128353. if( ppTail==0 ) break;
  128354. pToDel = *ppTail;
  128355. if( pToDel==0 ) break;
  128356. *ppTail = pToDel->pNextLoop;
  128357. #if WHERETRACE_ENABLED /* 0x8 */
  128358. if( sqlite3WhereTrace & 0x8 ){
  128359. sqlite3DebugPrintf(" delete: ");
  128360. whereLoopPrint(pToDel, pBuilder->pWC);
  128361. }
  128362. #endif
  128363. whereLoopDelete(db, pToDel);
  128364. }
  128365. }
  128366. rc = whereLoopXfer(db, p, pTemplate);
  128367. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  128368. Index *pIndex = p->u.btree.pIndex;
  128369. if( pIndex && pIndex->tnum==0 ){
  128370. p->u.btree.pIndex = 0;
  128371. }
  128372. }
  128373. return rc;
  128374. }
  128375. /*
  128376. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  128377. ** WHERE clause that reference the loop but which are not used by an
  128378. ** index.
  128379. *
  128380. ** For every WHERE clause term that is not used by the index
  128381. ** and which has a truth probability assigned by one of the likelihood(),
  128382. ** likely(), or unlikely() SQL functions, reduce the estimated number
  128383. ** of output rows by the probability specified.
  128384. **
  128385. ** TUNING: For every WHERE clause term that is not used by the index
  128386. ** and which does not have an assigned truth probability, heuristics
  128387. ** described below are used to try to estimate the truth probability.
  128388. ** TODO --> Perhaps this is something that could be improved by better
  128389. ** table statistics.
  128390. **
  128391. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  128392. ** value corresponds to -1 in LogEst notation, so this means decrement
  128393. ** the WhereLoop.nOut field for every such WHERE clause term.
  128394. **
  128395. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  128396. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  128397. ** final output row estimate is no greater than 1/4 of the total number
  128398. ** of rows in the table. In other words, assume that x==EXPR will filter
  128399. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  128400. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  128401. ** on the "x" column and so in that case only cap the output row estimate
  128402. ** at 1/2 instead of 1/4.
  128403. */
  128404. static void whereLoopOutputAdjust(
  128405. WhereClause *pWC, /* The WHERE clause */
  128406. WhereLoop *pLoop, /* The loop to adjust downward */
  128407. LogEst nRow /* Number of rows in the entire table */
  128408. ){
  128409. WhereTerm *pTerm, *pX;
  128410. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  128411. int i, j, k;
  128412. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  128413. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  128414. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  128415. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  128416. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  128417. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  128418. for(j=pLoop->nLTerm-1; j>=0; j--){
  128419. pX = pLoop->aLTerm[j];
  128420. if( pX==0 ) continue;
  128421. if( pX==pTerm ) break;
  128422. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  128423. }
  128424. if( j<0 ){
  128425. if( pTerm->truthProb<=0 ){
  128426. /* If a truth probability is specified using the likelihood() hints,
  128427. ** then use the probability provided by the application. */
  128428. pLoop->nOut += pTerm->truthProb;
  128429. }else{
  128430. /* In the absence of explicit truth probabilities, use heuristics to
  128431. ** guess a reasonable truth probability. */
  128432. pLoop->nOut--;
  128433. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  128434. Expr *pRight = pTerm->pExpr->pRight;
  128435. testcase( pTerm->pExpr->op==TK_IS );
  128436. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  128437. k = 10;
  128438. }else{
  128439. k = 20;
  128440. }
  128441. if( iReduce<k ) iReduce = k;
  128442. }
  128443. }
  128444. }
  128445. }
  128446. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  128447. }
  128448. /*
  128449. ** Term pTerm is a vector range comparison operation. The first comparison
  128450. ** in the vector can be optimized using column nEq of the index. This
  128451. ** function returns the total number of vector elements that can be used
  128452. ** as part of the range comparison.
  128453. **
  128454. ** For example, if the query is:
  128455. **
  128456. ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
  128457. **
  128458. ** and the index:
  128459. **
  128460. ** CREATE INDEX ... ON (a, b, c, d, e)
  128461. **
  128462. ** then this function would be invoked with nEq=1. The value returned in
  128463. ** this case is 3.
  128464. */
  128465. static int whereRangeVectorLen(
  128466. Parse *pParse, /* Parsing context */
  128467. int iCur, /* Cursor open on pIdx */
  128468. Index *pIdx, /* The index to be used for a inequality constraint */
  128469. int nEq, /* Number of prior equality constraints on same index */
  128470. WhereTerm *pTerm /* The vector inequality constraint */
  128471. ){
  128472. int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
  128473. int i;
  128474. nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
  128475. for(i=1; i<nCmp; i++){
  128476. /* Test if comparison i of pTerm is compatible with column (i+nEq)
  128477. ** of the index. If not, exit the loop. */
  128478. char aff; /* Comparison affinity */
  128479. char idxaff = 0; /* Indexed columns affinity */
  128480. CollSeq *pColl; /* Comparison collation sequence */
  128481. Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
  128482. Expr *pRhs = pTerm->pExpr->pRight;
  128483. if( pRhs->flags & EP_xIsSelect ){
  128484. pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
  128485. }else{
  128486. pRhs = pRhs->x.pList->a[i].pExpr;
  128487. }
  128488. /* Check that the LHS of the comparison is a column reference to
  128489. ** the right column of the right source table. And that the sort
  128490. ** order of the index column is the same as the sort order of the
  128491. ** leftmost index column. */
  128492. if( pLhs->op!=TK_COLUMN
  128493. || pLhs->iTable!=iCur
  128494. || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
  128495. || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
  128496. ){
  128497. break;
  128498. }
  128499. testcase( pLhs->iColumn==XN_ROWID );
  128500. aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
  128501. idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
  128502. if( aff!=idxaff ) break;
  128503. pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  128504. if( pColl==0 ) break;
  128505. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
  128506. }
  128507. return i;
  128508. }
  128509. /*
  128510. ** Adjust the cost C by the costMult facter T. This only occurs if
  128511. ** compiled with -DSQLITE_ENABLE_COSTMULT
  128512. */
  128513. #ifdef SQLITE_ENABLE_COSTMULT
  128514. # define ApplyCostMultiplier(C,T) C += T
  128515. #else
  128516. # define ApplyCostMultiplier(C,T)
  128517. #endif
  128518. /*
  128519. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  128520. ** index pIndex. Try to match one more.
  128521. **
  128522. ** When this function is called, pBuilder->pNew->nOut contains the
  128523. ** number of rows expected to be visited by filtering using the nEq
  128524. ** terms only. If it is modified, this value is restored before this
  128525. ** function returns.
  128526. **
  128527. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  128528. ** INTEGER PRIMARY KEY.
  128529. */
  128530. static int whereLoopAddBtreeIndex(
  128531. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  128532. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  128533. Index *pProbe, /* An index on pSrc */
  128534. LogEst nInMul /* log(Number of iterations due to IN) */
  128535. ){
  128536. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  128537. Parse *pParse = pWInfo->pParse; /* Parsing context */
  128538. sqlite3 *db = pParse->db; /* Database connection malloc context */
  128539. WhereLoop *pNew; /* Template WhereLoop under construction */
  128540. WhereTerm *pTerm; /* A WhereTerm under consideration */
  128541. int opMask; /* Valid operators for constraints */
  128542. WhereScan scan; /* Iterator for WHERE terms */
  128543. Bitmask saved_prereq; /* Original value of pNew->prereq */
  128544. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  128545. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  128546. u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
  128547. u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
  128548. u16 saved_nSkip; /* Original value of pNew->nSkip */
  128549. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  128550. LogEst saved_nOut; /* Original value of pNew->nOut */
  128551. int rc = SQLITE_OK; /* Return code */
  128552. LogEst rSize; /* Number of rows in the table */
  128553. LogEst rLogSize; /* Logarithm of table size */
  128554. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  128555. pNew = pBuilder->pNew;
  128556. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  128557. WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d\n",
  128558. pProbe->pTable->zName,pProbe->zName, pNew->u.btree.nEq));
  128559. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  128560. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  128561. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  128562. opMask = WO_LT|WO_LE;
  128563. }else{
  128564. assert( pNew->u.btree.nBtm==0 );
  128565. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  128566. }
  128567. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  128568. assert( pNew->u.btree.nEq<pProbe->nColumn );
  128569. saved_nEq = pNew->u.btree.nEq;
  128570. saved_nBtm = pNew->u.btree.nBtm;
  128571. saved_nTop = pNew->u.btree.nTop;
  128572. saved_nSkip = pNew->nSkip;
  128573. saved_nLTerm = pNew->nLTerm;
  128574. saved_wsFlags = pNew->wsFlags;
  128575. saved_prereq = pNew->prereq;
  128576. saved_nOut = pNew->nOut;
  128577. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  128578. opMask, pProbe);
  128579. pNew->rSetup = 0;
  128580. rSize = pProbe->aiRowLogEst[0];
  128581. rLogSize = estLog(rSize);
  128582. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  128583. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  128584. LogEst rCostIdx;
  128585. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  128586. int nIn = 0;
  128587. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  128588. int nRecValid = pBuilder->nRecValid;
  128589. #endif
  128590. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  128591. && indexColumnNotNull(pProbe, saved_nEq)
  128592. ){
  128593. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  128594. }
  128595. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  128596. /* Do not allow the upper bound of a LIKE optimization range constraint
  128597. ** to mix with a lower range bound from some other source */
  128598. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  128599. /* Do not allow IS constraints from the WHERE clause to be used by the
  128600. ** right table of a LEFT JOIN. Only constraints in the ON clause are
  128601. ** allowed */
  128602. if( (pSrc->fg.jointype & JT_LEFT)!=0
  128603. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  128604. && (eOp & (WO_IS|WO_ISNULL))!=0
  128605. ){
  128606. testcase( eOp & WO_IS );
  128607. testcase( eOp & WO_ISNULL );
  128608. continue;
  128609. }
  128610. if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
  128611. pBuilder->bldFlags |= SQLITE_BLDF_UNIQUE;
  128612. }else{
  128613. pBuilder->bldFlags |= SQLITE_BLDF_INDEXED;
  128614. }
  128615. pNew->wsFlags = saved_wsFlags;
  128616. pNew->u.btree.nEq = saved_nEq;
  128617. pNew->u.btree.nBtm = saved_nBtm;
  128618. pNew->u.btree.nTop = saved_nTop;
  128619. pNew->nLTerm = saved_nLTerm;
  128620. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  128621. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  128622. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  128623. assert( nInMul==0
  128624. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  128625. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  128626. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  128627. );
  128628. if( eOp & WO_IN ){
  128629. Expr *pExpr = pTerm->pExpr;
  128630. pNew->wsFlags |= WHERE_COLUMN_IN;
  128631. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  128632. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  128633. int i;
  128634. nIn = 46; assert( 46==sqlite3LogEst(25) );
  128635. /* The expression may actually be of the form (x, y) IN (SELECT...).
  128636. ** In this case there is a separate term for each of (x) and (y).
  128637. ** However, the nIn multiplier should only be applied once, not once
  128638. ** for each such term. The following loop checks that pTerm is the
  128639. ** first such term in use, and sets nIn back to 0 if it is not. */
  128640. for(i=0; i<pNew->nLTerm-1; i++){
  128641. if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
  128642. }
  128643. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  128644. /* "x IN (value, value, ...)" */
  128645. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  128646. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  128647. ** changes "x IN (?)" into "x=?". */
  128648. }
  128649. }else if( eOp & (WO_EQ|WO_IS) ){
  128650. int iCol = pProbe->aiColumn[saved_nEq];
  128651. pNew->wsFlags |= WHERE_COLUMN_EQ;
  128652. assert( saved_nEq==pNew->u.btree.nEq );
  128653. if( iCol==XN_ROWID
  128654. || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  128655. ){
  128656. if( iCol==XN_ROWID || pProbe->uniqNotNull
  128657. || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
  128658. ){
  128659. pNew->wsFlags |= WHERE_ONEROW;
  128660. }else{
  128661. pNew->wsFlags |= WHERE_UNQ_WANTED;
  128662. }
  128663. }
  128664. }else if( eOp & WO_ISNULL ){
  128665. pNew->wsFlags |= WHERE_COLUMN_NULL;
  128666. }else if( eOp & (WO_GT|WO_GE) ){
  128667. testcase( eOp & WO_GT );
  128668. testcase( eOp & WO_GE );
  128669. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  128670. pNew->u.btree.nBtm = whereRangeVectorLen(
  128671. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  128672. );
  128673. pBtm = pTerm;
  128674. pTop = 0;
  128675. if( pTerm->wtFlags & TERM_LIKEOPT ){
  128676. /* Range contraints that come from the LIKE optimization are
  128677. ** always used in pairs. */
  128678. pTop = &pTerm[1];
  128679. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  128680. assert( pTop->wtFlags & TERM_LIKEOPT );
  128681. assert( pTop->eOperator==WO_LT );
  128682. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  128683. pNew->aLTerm[pNew->nLTerm++] = pTop;
  128684. pNew->wsFlags |= WHERE_TOP_LIMIT;
  128685. pNew->u.btree.nTop = 1;
  128686. }
  128687. }else{
  128688. assert( eOp & (WO_LT|WO_LE) );
  128689. testcase( eOp & WO_LT );
  128690. testcase( eOp & WO_LE );
  128691. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  128692. pNew->u.btree.nTop = whereRangeVectorLen(
  128693. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  128694. );
  128695. pTop = pTerm;
  128696. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  128697. pNew->aLTerm[pNew->nLTerm-2] : 0;
  128698. }
  128699. /* At this point pNew->nOut is set to the number of rows expected to
  128700. ** be visited by the index scan before considering term pTerm, or the
  128701. ** values of nIn and nInMul. In other words, assuming that all
  128702. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  128703. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  128704. assert( pNew->nOut==saved_nOut );
  128705. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  128706. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  128707. ** data, using some other estimate. */
  128708. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  128709. }else{
  128710. int nEq = ++pNew->u.btree.nEq;
  128711. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  128712. assert( pNew->nOut==saved_nOut );
  128713. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  128714. assert( (eOp & WO_IN) || nIn==0 );
  128715. testcase( eOp & WO_IN );
  128716. pNew->nOut += pTerm->truthProb;
  128717. pNew->nOut -= nIn;
  128718. }else{
  128719. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  128720. tRowcnt nOut = 0;
  128721. if( nInMul==0
  128722. && pProbe->nSample
  128723. && pNew->u.btree.nEq<=pProbe->nSampleCol
  128724. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  128725. ){
  128726. Expr *pExpr = pTerm->pExpr;
  128727. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  128728. testcase( eOp & WO_EQ );
  128729. testcase( eOp & WO_IS );
  128730. testcase( eOp & WO_ISNULL );
  128731. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  128732. }else{
  128733. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  128734. }
  128735. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  128736. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  128737. if( nOut ){
  128738. pNew->nOut = sqlite3LogEst(nOut);
  128739. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  128740. pNew->nOut -= nIn;
  128741. }
  128742. }
  128743. if( nOut==0 )
  128744. #endif
  128745. {
  128746. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  128747. if( eOp & WO_ISNULL ){
  128748. /* TUNING: If there is no likelihood() value, assume that a
  128749. ** "col IS NULL" expression matches twice as many rows
  128750. ** as (col=?). */
  128751. pNew->nOut += 10;
  128752. }
  128753. }
  128754. }
  128755. }
  128756. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  128757. ** it to pNew->rRun, which is currently set to the cost of the index
  128758. ** seek only. Then, if this is a non-covering index, add the cost of
  128759. ** visiting the rows in the main table. */
  128760. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  128761. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  128762. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  128763. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  128764. }
  128765. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  128766. nOutUnadjusted = pNew->nOut;
  128767. pNew->rRun += nInMul + nIn;
  128768. pNew->nOut += nInMul + nIn;
  128769. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  128770. rc = whereLoopInsert(pBuilder, pNew);
  128771. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  128772. pNew->nOut = saved_nOut;
  128773. }else{
  128774. pNew->nOut = nOutUnadjusted;
  128775. }
  128776. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  128777. && pNew->u.btree.nEq<pProbe->nColumn
  128778. ){
  128779. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  128780. }
  128781. pNew->nOut = saved_nOut;
  128782. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  128783. pBuilder->nRecValid = nRecValid;
  128784. #endif
  128785. }
  128786. pNew->prereq = saved_prereq;
  128787. pNew->u.btree.nEq = saved_nEq;
  128788. pNew->u.btree.nBtm = saved_nBtm;
  128789. pNew->u.btree.nTop = saved_nTop;
  128790. pNew->nSkip = saved_nSkip;
  128791. pNew->wsFlags = saved_wsFlags;
  128792. pNew->nOut = saved_nOut;
  128793. pNew->nLTerm = saved_nLTerm;
  128794. /* Consider using a skip-scan if there are no WHERE clause constraints
  128795. ** available for the left-most terms of the index, and if the average
  128796. ** number of repeats in the left-most terms is at least 18.
  128797. **
  128798. ** The magic number 18 is selected on the basis that scanning 17 rows
  128799. ** is almost always quicker than an index seek (even though if the index
  128800. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  128801. ** the code). And, even if it is not, it should not be too much slower.
  128802. ** On the other hand, the extra seeks could end up being significantly
  128803. ** more expensive. */
  128804. assert( 42==sqlite3LogEst(18) );
  128805. if( saved_nEq==saved_nSkip
  128806. && saved_nEq+1<pProbe->nKeyCol
  128807. && pProbe->noSkipScan==0
  128808. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  128809. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  128810. ){
  128811. LogEst nIter;
  128812. pNew->u.btree.nEq++;
  128813. pNew->nSkip++;
  128814. pNew->aLTerm[pNew->nLTerm++] = 0;
  128815. pNew->wsFlags |= WHERE_SKIPSCAN;
  128816. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  128817. pNew->nOut -= nIter;
  128818. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  128819. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  128820. nIter += 5;
  128821. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  128822. pNew->nOut = saved_nOut;
  128823. pNew->u.btree.nEq = saved_nEq;
  128824. pNew->nSkip = saved_nSkip;
  128825. pNew->wsFlags = saved_wsFlags;
  128826. }
  128827. WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
  128828. pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
  128829. return rc;
  128830. }
  128831. /*
  128832. ** Return True if it is possible that pIndex might be useful in
  128833. ** implementing the ORDER BY clause in pBuilder.
  128834. **
  128835. ** Return False if pBuilder does not contain an ORDER BY clause or
  128836. ** if there is no way for pIndex to be useful in implementing that
  128837. ** ORDER BY clause.
  128838. */
  128839. static int indexMightHelpWithOrderBy(
  128840. WhereLoopBuilder *pBuilder,
  128841. Index *pIndex,
  128842. int iCursor
  128843. ){
  128844. ExprList *pOB;
  128845. ExprList *aColExpr;
  128846. int ii, jj;
  128847. if( pIndex->bUnordered ) return 0;
  128848. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  128849. for(ii=0; ii<pOB->nExpr; ii++){
  128850. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  128851. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  128852. if( pExpr->iColumn<0 ) return 1;
  128853. for(jj=0; jj<pIndex->nKeyCol; jj++){
  128854. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  128855. }
  128856. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  128857. for(jj=0; jj<pIndex->nKeyCol; jj++){
  128858. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  128859. if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  128860. return 1;
  128861. }
  128862. }
  128863. }
  128864. }
  128865. return 0;
  128866. }
  128867. /*
  128868. ** Return a bitmask where 1s indicate that the corresponding column of
  128869. ** the table is used by an index. Only the first 63 columns are considered.
  128870. */
  128871. static Bitmask columnsInIndex(Index *pIdx){
  128872. Bitmask m = 0;
  128873. int j;
  128874. for(j=pIdx->nColumn-1; j>=0; j--){
  128875. int x = pIdx->aiColumn[j];
  128876. if( x>=0 ){
  128877. testcase( x==BMS-1 );
  128878. testcase( x==BMS-2 );
  128879. if( x<BMS-1 ) m |= MASKBIT(x);
  128880. }
  128881. }
  128882. return m;
  128883. }
  128884. /* Check to see if a partial index with pPartIndexWhere can be used
  128885. ** in the current query. Return true if it can be and false if not.
  128886. */
  128887. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  128888. int i;
  128889. WhereTerm *pTerm;
  128890. Parse *pParse = pWC->pWInfo->pParse;
  128891. while( pWhere->op==TK_AND ){
  128892. if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
  128893. pWhere = pWhere->pRight;
  128894. }
  128895. if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
  128896. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  128897. Expr *pExpr = pTerm->pExpr;
  128898. if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  128899. && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
  128900. ){
  128901. return 1;
  128902. }
  128903. }
  128904. return 0;
  128905. }
  128906. /*
  128907. ** Add all WhereLoop objects for a single table of the join where the table
  128908. ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
  128909. ** a b-tree table, not a virtual table.
  128910. **
  128911. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  128912. ** are calculated as follows:
  128913. **
  128914. ** For a full scan, assuming the table (or index) contains nRow rows:
  128915. **
  128916. ** cost = nRow * 3.0 // full-table scan
  128917. ** cost = nRow * K // scan of covering index
  128918. ** cost = nRow * (K+3.0) // scan of non-covering index
  128919. **
  128920. ** where K is a value between 1.1 and 3.0 set based on the relative
  128921. ** estimated average size of the index and table records.
  128922. **
  128923. ** For an index scan, where nVisit is the number of index rows visited
  128924. ** by the scan, and nSeek is the number of seek operations required on
  128925. ** the index b-tree:
  128926. **
  128927. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  128928. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  128929. **
  128930. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  128931. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  128932. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  128933. **
  128934. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  128935. ** of uncertainty. For this reason, scoring is designed to pick plans that
  128936. ** "do the least harm" if the estimates are inaccurate. For example, a
  128937. ** log(nRow) factor is omitted from a non-covering index scan in order to
  128938. ** bias the scoring in favor of using an index, since the worst-case
  128939. ** performance of using an index is far better than the worst-case performance
  128940. ** of a full table scan.
  128941. */
  128942. static int whereLoopAddBtree(
  128943. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  128944. Bitmask mPrereq /* Extra prerequesites for using this table */
  128945. ){
  128946. WhereInfo *pWInfo; /* WHERE analysis context */
  128947. Index *pProbe; /* An index we are evaluating */
  128948. Index sPk; /* A fake index object for the primary key */
  128949. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  128950. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  128951. SrcList *pTabList; /* The FROM clause */
  128952. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  128953. WhereLoop *pNew; /* Template WhereLoop object */
  128954. int rc = SQLITE_OK; /* Return code */
  128955. int iSortIdx = 1; /* Index number */
  128956. int b; /* A boolean value */
  128957. LogEst rSize; /* number of rows in the table */
  128958. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  128959. WhereClause *pWC; /* The parsed WHERE clause */
  128960. Table *pTab; /* Table being queried */
  128961. pNew = pBuilder->pNew;
  128962. pWInfo = pBuilder->pWInfo;
  128963. pTabList = pWInfo->pTabList;
  128964. pSrc = pTabList->a + pNew->iTab;
  128965. pTab = pSrc->pTab;
  128966. pWC = pBuilder->pWC;
  128967. assert( !IsVirtual(pSrc->pTab) );
  128968. if( pSrc->pIBIndex ){
  128969. /* An INDEXED BY clause specifies a particular index to use */
  128970. pProbe = pSrc->pIBIndex;
  128971. }else if( !HasRowid(pTab) ){
  128972. pProbe = pTab->pIndex;
  128973. }else{
  128974. /* There is no INDEXED BY clause. Create a fake Index object in local
  128975. ** variable sPk to represent the rowid primary key index. Make this
  128976. ** fake index the first in a chain of Index objects with all of the real
  128977. ** indices to follow */
  128978. Index *pFirst; /* First of real indices on the table */
  128979. memset(&sPk, 0, sizeof(Index));
  128980. sPk.nKeyCol = 1;
  128981. sPk.nColumn = 1;
  128982. sPk.aiColumn = &aiColumnPk;
  128983. sPk.aiRowLogEst = aiRowEstPk;
  128984. sPk.onError = OE_Replace;
  128985. sPk.pTable = pTab;
  128986. sPk.szIdxRow = pTab->szTabRow;
  128987. aiRowEstPk[0] = pTab->nRowLogEst;
  128988. aiRowEstPk[1] = 0;
  128989. pFirst = pSrc->pTab->pIndex;
  128990. if( pSrc->fg.notIndexed==0 ){
  128991. /* The real indices of the table are only considered if the
  128992. ** NOT INDEXED qualifier is omitted from the FROM clause */
  128993. sPk.pNext = pFirst;
  128994. }
  128995. pProbe = &sPk;
  128996. }
  128997. rSize = pTab->nRowLogEst;
  128998. rLogSize = estLog(rSize);
  128999. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  129000. /* Automatic indexes */
  129001. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  129002. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  129003. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  129004. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  129005. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  129006. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  129007. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  129008. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  129009. ){
  129010. /* Generate auto-index WhereLoops */
  129011. WhereTerm *pTerm;
  129012. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  129013. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  129014. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  129015. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  129016. pNew->u.btree.nEq = 1;
  129017. pNew->nSkip = 0;
  129018. pNew->u.btree.pIndex = 0;
  129019. pNew->nLTerm = 1;
  129020. pNew->aLTerm[0] = pTerm;
  129021. /* TUNING: One-time cost for computing the automatic index is
  129022. ** estimated to be X*N*log2(N) where N is the number of rows in
  129023. ** the table being indexed and where X is 7 (LogEst=28) for normal
  129024. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  129025. ** of X is smaller for views and subqueries so that the query planner
  129026. ** will be more aggressive about generating automatic indexes for
  129027. ** those objects, since there is no opportunity to add schema
  129028. ** indexes on subqueries and views. */
  129029. pNew->rSetup = rLogSize + rSize + 4;
  129030. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  129031. pNew->rSetup += 24;
  129032. }
  129033. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  129034. if( pNew->rSetup<0 ) pNew->rSetup = 0;
  129035. /* TUNING: Each index lookup yields 20 rows in the table. This
  129036. ** is more than the usual guess of 10 rows, since we have no way
  129037. ** of knowing how selective the index will ultimately be. It would
  129038. ** not be unreasonable to make this value much larger. */
  129039. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  129040. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  129041. pNew->wsFlags = WHERE_AUTO_INDEX;
  129042. pNew->prereq = mPrereq | pTerm->prereqRight;
  129043. rc = whereLoopInsert(pBuilder, pNew);
  129044. }
  129045. }
  129046. }
  129047. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  129048. /* Loop over all indices. If there was an INDEXED BY clause, then only
  129049. ** consider index pProbe. */
  129050. for(; rc==SQLITE_OK && pProbe;
  129051. pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
  129052. ){
  129053. if( pProbe->pPartIdxWhere!=0
  129054. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  129055. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  129056. continue; /* Partial index inappropriate for this query */
  129057. }
  129058. if( pProbe->bNoQuery ) continue;
  129059. rSize = pProbe->aiRowLogEst[0];
  129060. pNew->u.btree.nEq = 0;
  129061. pNew->u.btree.nBtm = 0;
  129062. pNew->u.btree.nTop = 0;
  129063. pNew->nSkip = 0;
  129064. pNew->nLTerm = 0;
  129065. pNew->iSortIdx = 0;
  129066. pNew->rSetup = 0;
  129067. pNew->prereq = mPrereq;
  129068. pNew->nOut = rSize;
  129069. pNew->u.btree.pIndex = pProbe;
  129070. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  129071. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  129072. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  129073. if( pProbe->tnum<=0 ){
  129074. /* Integer primary key index */
  129075. pNew->wsFlags = WHERE_IPK;
  129076. /* Full table scan */
  129077. pNew->iSortIdx = b ? iSortIdx : 0;
  129078. /* TUNING: Cost of full table scan is (N*3.0). */
  129079. pNew->rRun = rSize + 16;
  129080. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  129081. whereLoopOutputAdjust(pWC, pNew, rSize);
  129082. rc = whereLoopInsert(pBuilder, pNew);
  129083. pNew->nOut = rSize;
  129084. if( rc ) break;
  129085. }else{
  129086. Bitmask m;
  129087. if( pProbe->isCovering ){
  129088. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  129089. m = 0;
  129090. }else{
  129091. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  129092. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  129093. }
  129094. /* Full scan via index */
  129095. if( b
  129096. || !HasRowid(pTab)
  129097. || pProbe->pPartIdxWhere!=0
  129098. || ( m==0
  129099. && pProbe->bUnordered==0
  129100. && (pProbe->szIdxRow<pTab->szTabRow)
  129101. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  129102. && sqlite3GlobalConfig.bUseCis
  129103. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  129104. )
  129105. ){
  129106. pNew->iSortIdx = b ? iSortIdx : 0;
  129107. /* The cost of visiting the index rows is N*K, where K is
  129108. ** between 1.1 and 3.0, depending on the relative sizes of the
  129109. ** index and table rows. */
  129110. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  129111. if( m!=0 ){
  129112. /* If this is a non-covering index scan, add in the cost of
  129113. ** doing table lookups. The cost will be 3x the number of
  129114. ** lookups. Take into account WHERE clause terms that can be
  129115. ** satisfied using just the index, and that do not require a
  129116. ** table lookup. */
  129117. LogEst nLookup = rSize + 16; /* Base cost: N*3 */
  129118. int ii;
  129119. int iCur = pSrc->iCursor;
  129120. WhereClause *pWC2 = &pWInfo->sWC;
  129121. for(ii=0; ii<pWC2->nTerm; ii++){
  129122. WhereTerm *pTerm = &pWC2->a[ii];
  129123. if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
  129124. break;
  129125. }
  129126. /* pTerm can be evaluated using just the index. So reduce
  129127. ** the expected number of table lookups accordingly */
  129128. if( pTerm->truthProb<=0 ){
  129129. nLookup += pTerm->truthProb;
  129130. }else{
  129131. nLookup--;
  129132. if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
  129133. }
  129134. }
  129135. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
  129136. }
  129137. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  129138. whereLoopOutputAdjust(pWC, pNew, rSize);
  129139. rc = whereLoopInsert(pBuilder, pNew);
  129140. pNew->nOut = rSize;
  129141. if( rc ) break;
  129142. }
  129143. }
  129144. pBuilder->bldFlags = 0;
  129145. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  129146. if( pBuilder->bldFlags==SQLITE_BLDF_INDEXED ){
  129147. /* If a non-unique index is used, or if a prefix of the key for
  129148. ** unique index is used (making the index functionally non-unique)
  129149. ** then the sqlite_stat1 data becomes important for scoring the
  129150. ** plan */
  129151. pTab->tabFlags |= TF_StatsUsed;
  129152. }
  129153. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  129154. sqlite3Stat4ProbeFree(pBuilder->pRec);
  129155. pBuilder->nRecValid = 0;
  129156. pBuilder->pRec = 0;
  129157. #endif
  129158. }
  129159. return rc;
  129160. }
  129161. #ifndef SQLITE_OMIT_VIRTUALTABLE
  129162. /*
  129163. ** Argument pIdxInfo is already populated with all constraints that may
  129164. ** be used by the virtual table identified by pBuilder->pNew->iTab. This
  129165. ** function marks a subset of those constraints usable, invokes the
  129166. ** xBestIndex method and adds the returned plan to pBuilder.
  129167. **
  129168. ** A constraint is marked usable if:
  129169. **
  129170. ** * Argument mUsable indicates that its prerequisites are available, and
  129171. **
  129172. ** * It is not one of the operators specified in the mExclude mask passed
  129173. ** as the fourth argument (which in practice is either WO_IN or 0).
  129174. **
  129175. ** Argument mPrereq is a mask of tables that must be scanned before the
  129176. ** virtual table in question. These are added to the plans prerequisites
  129177. ** before it is added to pBuilder.
  129178. **
  129179. ** Output parameter *pbIn is set to true if the plan added to pBuilder
  129180. ** uses one or more WO_IN terms, or false otherwise.
  129181. */
  129182. static int whereLoopAddVirtualOne(
  129183. WhereLoopBuilder *pBuilder,
  129184. Bitmask mPrereq, /* Mask of tables that must be used. */
  129185. Bitmask mUsable, /* Mask of usable tables */
  129186. u16 mExclude, /* Exclude terms using these operators */
  129187. sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
  129188. u16 mNoOmit, /* Do not omit these constraints */
  129189. int *pbIn /* OUT: True if plan uses an IN(...) op */
  129190. ){
  129191. WhereClause *pWC = pBuilder->pWC;
  129192. struct sqlite3_index_constraint *pIdxCons;
  129193. struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
  129194. int i;
  129195. int mxTerm;
  129196. int rc = SQLITE_OK;
  129197. WhereLoop *pNew = pBuilder->pNew;
  129198. Parse *pParse = pBuilder->pWInfo->pParse;
  129199. struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
  129200. int nConstraint = pIdxInfo->nConstraint;
  129201. assert( (mUsable & mPrereq)==mPrereq );
  129202. *pbIn = 0;
  129203. pNew->prereq = mPrereq;
  129204. /* Set the usable flag on the subset of constraints identified by
  129205. ** arguments mUsable and mExclude. */
  129206. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  129207. for(i=0; i<nConstraint; i++, pIdxCons++){
  129208. WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
  129209. pIdxCons->usable = 0;
  129210. if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
  129211. && (pTerm->eOperator & mExclude)==0
  129212. ){
  129213. pIdxCons->usable = 1;
  129214. }
  129215. }
  129216. /* Initialize the output fields of the sqlite3_index_info structure */
  129217. memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
  129218. assert( pIdxInfo->needToFreeIdxStr==0 );
  129219. pIdxInfo->idxStr = 0;
  129220. pIdxInfo->idxNum = 0;
  129221. pIdxInfo->orderByConsumed = 0;
  129222. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  129223. pIdxInfo->estimatedRows = 25;
  129224. pIdxInfo->idxFlags = 0;
  129225. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  129226. /* Invoke the virtual table xBestIndex() method */
  129227. rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
  129228. if( rc ) return rc;
  129229. mxTerm = -1;
  129230. assert( pNew->nLSlot>=nConstraint );
  129231. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  129232. pNew->u.vtab.omitMask = 0;
  129233. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  129234. for(i=0; i<nConstraint; i++, pIdxCons++){
  129235. int iTerm;
  129236. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  129237. WhereTerm *pTerm;
  129238. int j = pIdxCons->iTermOffset;
  129239. if( iTerm>=nConstraint
  129240. || j<0
  129241. || j>=pWC->nTerm
  129242. || pNew->aLTerm[iTerm]!=0
  129243. || pIdxCons->usable==0
  129244. ){
  129245. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  129246. testcase( pIdxInfo->needToFreeIdxStr );
  129247. return SQLITE_ERROR;
  129248. }
  129249. testcase( iTerm==nConstraint-1 );
  129250. testcase( j==0 );
  129251. testcase( j==pWC->nTerm-1 );
  129252. pTerm = &pWC->a[j];
  129253. pNew->prereq |= pTerm->prereqRight;
  129254. assert( iTerm<pNew->nLSlot );
  129255. pNew->aLTerm[iTerm] = pTerm;
  129256. if( iTerm>mxTerm ) mxTerm = iTerm;
  129257. testcase( iTerm==15 );
  129258. testcase( iTerm==16 );
  129259. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  129260. if( (pTerm->eOperator & WO_IN)!=0 ){
  129261. /* A virtual table that is constrained by an IN clause may not
  129262. ** consume the ORDER BY clause because (1) the order of IN terms
  129263. ** is not necessarily related to the order of output terms and
  129264. ** (2) Multiple outputs from a single IN value will not merge
  129265. ** together. */
  129266. pIdxInfo->orderByConsumed = 0;
  129267. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  129268. *pbIn = 1; assert( (mExclude & WO_IN)==0 );
  129269. }
  129270. }
  129271. }
  129272. pNew->u.vtab.omitMask &= ~mNoOmit;
  129273. pNew->nLTerm = mxTerm+1;
  129274. for(i=0; i<=mxTerm; i++){
  129275. if( pNew->aLTerm[i]==0 ){
  129276. /* The non-zero argvIdx values must be contiguous. Raise an
  129277. ** error if they are not */
  129278. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  129279. testcase( pIdxInfo->needToFreeIdxStr );
  129280. return SQLITE_ERROR;
  129281. }
  129282. }
  129283. assert( pNew->nLTerm<=pNew->nLSlot );
  129284. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  129285. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  129286. pIdxInfo->needToFreeIdxStr = 0;
  129287. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  129288. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  129289. pIdxInfo->nOrderBy : 0);
  129290. pNew->rSetup = 0;
  129291. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  129292. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  129293. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  129294. ** that the scan will visit at most one row. Clear it otherwise. */
  129295. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  129296. pNew->wsFlags |= WHERE_ONEROW;
  129297. }else{
  129298. pNew->wsFlags &= ~WHERE_ONEROW;
  129299. }
  129300. rc = whereLoopInsert(pBuilder, pNew);
  129301. if( pNew->u.vtab.needFree ){
  129302. sqlite3_free(pNew->u.vtab.idxStr);
  129303. pNew->u.vtab.needFree = 0;
  129304. }
  129305. WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
  129306. *pbIn, (sqlite3_uint64)mPrereq,
  129307. (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
  129308. return rc;
  129309. }
  129310. /*
  129311. ** If this function is invoked from within an xBestIndex() callback, it
  129312. ** returns a pointer to a buffer containing the name of the collation
  129313. ** sequence associated with element iCons of the sqlite3_index_info.aConstraint
  129314. ** array. Or, if iCons is out of range or there is no active xBestIndex
  129315. ** call, return NULL.
  129316. */
  129317. SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
  129318. HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  129319. const char *zRet = 0;
  129320. if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
  129321. CollSeq *pC = 0;
  129322. int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
  129323. Expr *pX = pHidden->pWC->a[iTerm].pExpr;
  129324. if( pX->pLeft ){
  129325. pC = sqlite3BinaryCompareCollSeq(pHidden->pParse, pX->pLeft, pX->pRight);
  129326. }
  129327. zRet = (pC ? pC->zName : "BINARY");
  129328. }
  129329. return zRet;
  129330. }
  129331. /*
  129332. ** Add all WhereLoop objects for a table of the join identified by
  129333. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  129334. **
  129335. ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
  129336. ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
  129337. ** entries that occur before the virtual table in the FROM clause and are
  129338. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  129339. ** mUnusable mask contains all FROM clause entries that occur after the
  129340. ** virtual table and are separated from it by at least one LEFT or
  129341. ** CROSS JOIN.
  129342. **
  129343. ** For example, if the query were:
  129344. **
  129345. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  129346. **
  129347. ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
  129348. **
  129349. ** All the tables in mPrereq must be scanned before the current virtual
  129350. ** table. So any terms for which all prerequisites are satisfied by
  129351. ** mPrereq may be specified as "usable" in all calls to xBestIndex.
  129352. ** Conversely, all tables in mUnusable must be scanned after the current
  129353. ** virtual table, so any terms for which the prerequisites overlap with
  129354. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  129355. */
  129356. static int whereLoopAddVirtual(
  129357. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  129358. Bitmask mPrereq, /* Tables that must be scanned before this one */
  129359. Bitmask mUnusable /* Tables that must be scanned after this one */
  129360. ){
  129361. int rc = SQLITE_OK; /* Return code */
  129362. WhereInfo *pWInfo; /* WHERE analysis context */
  129363. Parse *pParse; /* The parsing context */
  129364. WhereClause *pWC; /* The WHERE clause */
  129365. struct SrcList_item *pSrc; /* The FROM clause term to search */
  129366. sqlite3_index_info *p; /* Object to pass to xBestIndex() */
  129367. int nConstraint; /* Number of constraints in p */
  129368. int bIn; /* True if plan uses IN(...) operator */
  129369. WhereLoop *pNew;
  129370. Bitmask mBest; /* Tables used by best possible plan */
  129371. u16 mNoOmit;
  129372. assert( (mPrereq & mUnusable)==0 );
  129373. pWInfo = pBuilder->pWInfo;
  129374. pParse = pWInfo->pParse;
  129375. pWC = pBuilder->pWC;
  129376. pNew = pBuilder->pNew;
  129377. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  129378. assert( IsVirtual(pSrc->pTab) );
  129379. p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
  129380. &mNoOmit);
  129381. if( p==0 ) return SQLITE_NOMEM_BKPT;
  129382. pNew->rSetup = 0;
  129383. pNew->wsFlags = WHERE_VIRTUALTABLE;
  129384. pNew->nLTerm = 0;
  129385. pNew->u.vtab.needFree = 0;
  129386. nConstraint = p->nConstraint;
  129387. if( whereLoopResize(pParse->db, pNew, nConstraint) ){
  129388. sqlite3DbFree(pParse->db, p);
  129389. return SQLITE_NOMEM_BKPT;
  129390. }
  129391. /* First call xBestIndex() with all constraints usable. */
  129392. WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
  129393. WHERETRACE(0x40, (" VirtualOne: all usable\n"));
  129394. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
  129395. /* If the call to xBestIndex() with all terms enabled produced a plan
  129396. ** that does not require any source tables (IOW: a plan with mBest==0),
  129397. ** then there is no point in making any further calls to xBestIndex()
  129398. ** since they will all return the same result (if the xBestIndex()
  129399. ** implementation is sane). */
  129400. if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
  129401. int seenZero = 0; /* True if a plan with no prereqs seen */
  129402. int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
  129403. Bitmask mPrev = 0;
  129404. Bitmask mBestNoIn = 0;
  129405. /* If the plan produced by the earlier call uses an IN(...) term, call
  129406. ** xBestIndex again, this time with IN(...) terms disabled. */
  129407. if( bIn ){
  129408. WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
  129409. rc = whereLoopAddVirtualOne(
  129410. pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
  129411. assert( bIn==0 );
  129412. mBestNoIn = pNew->prereq & ~mPrereq;
  129413. if( mBestNoIn==0 ){
  129414. seenZero = 1;
  129415. seenZeroNoIN = 1;
  129416. }
  129417. }
  129418. /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
  129419. ** in the set of terms that apply to the current virtual table. */
  129420. while( rc==SQLITE_OK ){
  129421. int i;
  129422. Bitmask mNext = ALLBITS;
  129423. assert( mNext>0 );
  129424. for(i=0; i<nConstraint; i++){
  129425. Bitmask mThis = (
  129426. pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
  129427. );
  129428. if( mThis>mPrev && mThis<mNext ) mNext = mThis;
  129429. }
  129430. mPrev = mNext;
  129431. if( mNext==ALLBITS ) break;
  129432. if( mNext==mBest || mNext==mBestNoIn ) continue;
  129433. WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
  129434. (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
  129435. rc = whereLoopAddVirtualOne(
  129436. pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
  129437. if( pNew->prereq==mPrereq ){
  129438. seenZero = 1;
  129439. if( bIn==0 ) seenZeroNoIN = 1;
  129440. }
  129441. }
  129442. /* If the calls to xBestIndex() in the above loop did not find a plan
  129443. ** that requires no source tables at all (i.e. one guaranteed to be
  129444. ** usable), make a call here with all source tables disabled */
  129445. if( rc==SQLITE_OK && seenZero==0 ){
  129446. WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
  129447. rc = whereLoopAddVirtualOne(
  129448. pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
  129449. if( bIn==0 ) seenZeroNoIN = 1;
  129450. }
  129451. /* If the calls to xBestIndex() have so far failed to find a plan
  129452. ** that requires no source tables at all and does not use an IN(...)
  129453. ** operator, make a final call to obtain one here. */
  129454. if( rc==SQLITE_OK && seenZeroNoIN==0 ){
  129455. WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
  129456. rc = whereLoopAddVirtualOne(
  129457. pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
  129458. }
  129459. }
  129460. if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  129461. sqlite3DbFreeNN(pParse->db, p);
  129462. WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
  129463. return rc;
  129464. }
  129465. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  129466. /*
  129467. ** Add WhereLoop entries to handle OR terms. This works for either
  129468. ** btrees or virtual tables.
  129469. */
  129470. static int whereLoopAddOr(
  129471. WhereLoopBuilder *pBuilder,
  129472. Bitmask mPrereq,
  129473. Bitmask mUnusable
  129474. ){
  129475. WhereInfo *pWInfo = pBuilder->pWInfo;
  129476. WhereClause *pWC;
  129477. WhereLoop *pNew;
  129478. WhereTerm *pTerm, *pWCEnd;
  129479. int rc = SQLITE_OK;
  129480. int iCur;
  129481. WhereClause tempWC;
  129482. WhereLoopBuilder sSubBuild;
  129483. WhereOrSet sSum, sCur;
  129484. struct SrcList_item *pItem;
  129485. pWC = pBuilder->pWC;
  129486. pWCEnd = pWC->a + pWC->nTerm;
  129487. pNew = pBuilder->pNew;
  129488. memset(&sSum, 0, sizeof(sSum));
  129489. pItem = pWInfo->pTabList->a + pNew->iTab;
  129490. iCur = pItem->iCursor;
  129491. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  129492. if( (pTerm->eOperator & WO_OR)!=0
  129493. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  129494. ){
  129495. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  129496. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  129497. WhereTerm *pOrTerm;
  129498. int once = 1;
  129499. int i, j;
  129500. sSubBuild = *pBuilder;
  129501. sSubBuild.pOrderBy = 0;
  129502. sSubBuild.pOrSet = &sCur;
  129503. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  129504. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  129505. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  129506. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  129507. }else if( pOrTerm->leftCursor==iCur ){
  129508. tempWC.pWInfo = pWC->pWInfo;
  129509. tempWC.pOuter = pWC;
  129510. tempWC.op = TK_AND;
  129511. tempWC.nTerm = 1;
  129512. tempWC.a = pOrTerm;
  129513. sSubBuild.pWC = &tempWC;
  129514. }else{
  129515. continue;
  129516. }
  129517. sCur.n = 0;
  129518. #ifdef WHERETRACE_ENABLED
  129519. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  129520. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  129521. if( sqlite3WhereTrace & 0x400 ){
  129522. sqlite3WhereClausePrint(sSubBuild.pWC);
  129523. }
  129524. #endif
  129525. #ifndef SQLITE_OMIT_VIRTUALTABLE
  129526. if( IsVirtual(pItem->pTab) ){
  129527. rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
  129528. }else
  129529. #endif
  129530. {
  129531. rc = whereLoopAddBtree(&sSubBuild, mPrereq);
  129532. }
  129533. if( rc==SQLITE_OK ){
  129534. rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
  129535. }
  129536. assert( rc==SQLITE_OK || sCur.n==0 );
  129537. if( sCur.n==0 ){
  129538. sSum.n = 0;
  129539. break;
  129540. }else if( once ){
  129541. whereOrMove(&sSum, &sCur);
  129542. once = 0;
  129543. }else{
  129544. WhereOrSet sPrev;
  129545. whereOrMove(&sPrev, &sSum);
  129546. sSum.n = 0;
  129547. for(i=0; i<sPrev.n; i++){
  129548. for(j=0; j<sCur.n; j++){
  129549. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  129550. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  129551. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  129552. }
  129553. }
  129554. }
  129555. }
  129556. pNew->nLTerm = 1;
  129557. pNew->aLTerm[0] = pTerm;
  129558. pNew->wsFlags = WHERE_MULTI_OR;
  129559. pNew->rSetup = 0;
  129560. pNew->iSortIdx = 0;
  129561. memset(&pNew->u, 0, sizeof(pNew->u));
  129562. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  129563. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  129564. ** of all sub-scans required by the OR-scan. However, due to rounding
  129565. ** errors, it may be that the cost of the OR-scan is equal to its
  129566. ** most expensive sub-scan. Add the smallest possible penalty
  129567. ** (equivalent to multiplying the cost by 1.07) to ensure that
  129568. ** this does not happen. Otherwise, for WHERE clauses such as the
  129569. ** following where there is an index on "y":
  129570. **
  129571. ** WHERE likelihood(x=?, 0.99) OR y=?
  129572. **
  129573. ** the planner may elect to "OR" together a full-table scan and an
  129574. ** index lookup. And other similarly odd results. */
  129575. pNew->rRun = sSum.a[i].rRun + 1;
  129576. pNew->nOut = sSum.a[i].nOut;
  129577. pNew->prereq = sSum.a[i].prereq;
  129578. rc = whereLoopInsert(pBuilder, pNew);
  129579. }
  129580. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  129581. }
  129582. }
  129583. return rc;
  129584. }
  129585. /*
  129586. ** Add all WhereLoop objects for all tables
  129587. */
  129588. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  129589. WhereInfo *pWInfo = pBuilder->pWInfo;
  129590. Bitmask mPrereq = 0;
  129591. Bitmask mPrior = 0;
  129592. int iTab;
  129593. SrcList *pTabList = pWInfo->pTabList;
  129594. struct SrcList_item *pItem;
  129595. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  129596. sqlite3 *db = pWInfo->pParse->db;
  129597. int rc = SQLITE_OK;
  129598. WhereLoop *pNew;
  129599. u8 priorJointype = 0;
  129600. /* Loop over the tables in the join, from left to right */
  129601. pNew = pBuilder->pNew;
  129602. whereLoopInit(pNew);
  129603. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  129604. Bitmask mUnusable = 0;
  129605. pNew->iTab = iTab;
  129606. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  129607. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  129608. /* This condition is true when pItem is the FROM clause term on the
  129609. ** right-hand-side of a LEFT or CROSS JOIN. */
  129610. mPrereq = mPrior;
  129611. }
  129612. priorJointype = pItem->fg.jointype;
  129613. #ifndef SQLITE_OMIT_VIRTUALTABLE
  129614. if( IsVirtual(pItem->pTab) ){
  129615. struct SrcList_item *p;
  129616. for(p=&pItem[1]; p<pEnd; p++){
  129617. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  129618. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  129619. }
  129620. }
  129621. rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
  129622. }else
  129623. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  129624. {
  129625. rc = whereLoopAddBtree(pBuilder, mPrereq);
  129626. }
  129627. if( rc==SQLITE_OK ){
  129628. rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
  129629. }
  129630. mPrior |= pNew->maskSelf;
  129631. if( rc || db->mallocFailed ) break;
  129632. }
  129633. whereLoopClear(db, pNew);
  129634. return rc;
  129635. }
  129636. /*
  129637. ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
  129638. ** parameters) to see if it outputs rows in the requested ORDER BY
  129639. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  129640. **
  129641. ** N>0: N terms of the ORDER BY clause are satisfied
  129642. ** N==0: No terms of the ORDER BY clause are satisfied
  129643. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  129644. **
  129645. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  129646. ** strict. With GROUP BY and DISTINCT the only requirement is that
  129647. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  129648. ** and DISTINCT do not require rows to appear in any particular order as long
  129649. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  129650. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  129651. ** pOrderBy terms must be matched in strict left-to-right order.
  129652. */
  129653. static i8 wherePathSatisfiesOrderBy(
  129654. WhereInfo *pWInfo, /* The WHERE clause */
  129655. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  129656. WherePath *pPath, /* The WherePath to check */
  129657. u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
  129658. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  129659. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  129660. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  129661. ){
  129662. u8 revSet; /* True if rev is known */
  129663. u8 rev; /* Composite sort order */
  129664. u8 revIdx; /* Index sort order */
  129665. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  129666. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  129667. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  129668. u16 eqOpMask; /* Allowed equality operators */
  129669. u16 nKeyCol; /* Number of key columns in pIndex */
  129670. u16 nColumn; /* Total number of ordered columns in the index */
  129671. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  129672. int iLoop; /* Index of WhereLoop in pPath being processed */
  129673. int i, j; /* Loop counters */
  129674. int iCur; /* Cursor number for current WhereLoop */
  129675. int iColumn; /* A column number within table iCur */
  129676. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  129677. WhereTerm *pTerm; /* A single term of the WHERE clause */
  129678. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  129679. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  129680. Index *pIndex; /* The index associated with pLoop */
  129681. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  129682. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  129683. Bitmask obDone; /* Mask of all ORDER BY terms */
  129684. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  129685. Bitmask ready; /* Mask of inner loops */
  129686. /*
  129687. ** We say the WhereLoop is "one-row" if it generates no more than one
  129688. ** row of output. A WhereLoop is one-row if all of the following are true:
  129689. ** (a) All index columns match with WHERE_COLUMN_EQ.
  129690. ** (b) The index is unique
  129691. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  129692. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  129693. **
  129694. ** We say the WhereLoop is "order-distinct" if the set of columns from
  129695. ** that WhereLoop that are in the ORDER BY clause are different for every
  129696. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  129697. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  129698. ** is not order-distinct. To be order-distinct is not quite the same as being
  129699. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  129700. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  129701. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  129702. **
  129703. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  129704. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  129705. ** automatically order-distinct.
  129706. */
  129707. assert( pOrderBy!=0 );
  129708. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  129709. nOrderBy = pOrderBy->nExpr;
  129710. testcase( nOrderBy==BMS-1 );
  129711. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  129712. isOrderDistinct = 1;
  129713. obDone = MASKBIT(nOrderBy)-1;
  129714. orderDistinctMask = 0;
  129715. ready = 0;
  129716. eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
  129717. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
  129718. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  129719. if( iLoop>0 ) ready |= pLoop->maskSelf;
  129720. if( iLoop<nLoop ){
  129721. pLoop = pPath->aLoop[iLoop];
  129722. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
  129723. }else{
  129724. pLoop = pLast;
  129725. }
  129726. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  129727. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  129728. break;
  129729. }else{
  129730. pLoop->u.btree.nIdxCol = 0;
  129731. }
  129732. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  129733. /* Mark off any ORDER BY term X that is a column in the table of
  129734. ** the current loop for which there is term in the WHERE
  129735. ** clause of the form X IS NULL or X=? that reference only outer
  129736. ** loops.
  129737. */
  129738. for(i=0; i<nOrderBy; i++){
  129739. if( MASKBIT(i) & obSat ) continue;
  129740. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  129741. if( pOBExpr->op!=TK_COLUMN ) continue;
  129742. if( pOBExpr->iTable!=iCur ) continue;
  129743. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  129744. ~ready, eqOpMask, 0);
  129745. if( pTerm==0 ) continue;
  129746. if( pTerm->eOperator==WO_IN ){
  129747. /* IN terms are only valid for sorting in the ORDER BY LIMIT
  129748. ** optimization, and then only if they are actually used
  129749. ** by the query plan */
  129750. assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
  129751. for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
  129752. if( j>=pLoop->nLTerm ) continue;
  129753. }
  129754. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  129755. if( sqlite3ExprCollSeqMatch(pWInfo->pParse,
  129756. pOrderBy->a[i].pExpr, pTerm->pExpr)==0 ){
  129757. continue;
  129758. }
  129759. testcase( pTerm->pExpr->op==TK_IS );
  129760. }
  129761. obSat |= MASKBIT(i);
  129762. }
  129763. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  129764. if( pLoop->wsFlags & WHERE_IPK ){
  129765. pIndex = 0;
  129766. nKeyCol = 0;
  129767. nColumn = 1;
  129768. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  129769. return 0;
  129770. }else{
  129771. nKeyCol = pIndex->nKeyCol;
  129772. nColumn = pIndex->nColumn;
  129773. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  129774. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  129775. || !HasRowid(pIndex->pTable));
  129776. isOrderDistinct = IsUniqueIndex(pIndex);
  129777. }
  129778. /* Loop through all columns of the index and deal with the ones
  129779. ** that are not constrained by == or IN.
  129780. */
  129781. rev = revSet = 0;
  129782. distinctColumns = 0;
  129783. for(j=0; j<nColumn; j++){
  129784. u8 bOnce = 1; /* True to run the ORDER BY search loop */
  129785. assert( j>=pLoop->u.btree.nEq
  129786. || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
  129787. );
  129788. if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
  129789. u16 eOp = pLoop->aLTerm[j]->eOperator;
  129790. /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
  129791. ** doing WHERE_ORDERBY_LIMIT processing).
  129792. **
  129793. ** If the current term is a column of an ((?,?) IN (SELECT...))
  129794. ** expression for which the SELECT returns more than one column,
  129795. ** check that it is the only column used by this loop. Otherwise,
  129796. ** if it is one of two or more, none of the columns can be
  129797. ** considered to match an ORDER BY term. */
  129798. if( (eOp & eqOpMask)!=0 ){
  129799. if( eOp & WO_ISNULL ){
  129800. testcase( isOrderDistinct );
  129801. isOrderDistinct = 0;
  129802. }
  129803. continue;
  129804. }else if( ALWAYS(eOp & WO_IN) ){
  129805. /* ALWAYS() justification: eOp is an equality operator due to the
  129806. ** j<pLoop->u.btree.nEq constraint above. Any equality other
  129807. ** than WO_IN is captured by the previous "if". So this one
  129808. ** always has to be WO_IN. */
  129809. Expr *pX = pLoop->aLTerm[j]->pExpr;
  129810. for(i=j+1; i<pLoop->u.btree.nEq; i++){
  129811. if( pLoop->aLTerm[i]->pExpr==pX ){
  129812. assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
  129813. bOnce = 0;
  129814. break;
  129815. }
  129816. }
  129817. }
  129818. }
  129819. /* Get the column number in the table (iColumn) and sort order
  129820. ** (revIdx) for the j-th column of the index.
  129821. */
  129822. if( pIndex ){
  129823. iColumn = pIndex->aiColumn[j];
  129824. revIdx = pIndex->aSortOrder[j];
  129825. if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
  129826. }else{
  129827. iColumn = XN_ROWID;
  129828. revIdx = 0;
  129829. }
  129830. /* An unconstrained column that might be NULL means that this
  129831. ** WhereLoop is not well-ordered
  129832. */
  129833. if( isOrderDistinct
  129834. && iColumn>=0
  129835. && j>=pLoop->u.btree.nEq
  129836. && pIndex->pTable->aCol[iColumn].notNull==0
  129837. ){
  129838. isOrderDistinct = 0;
  129839. }
  129840. /* Find the ORDER BY term that corresponds to the j-th column
  129841. ** of the index and mark that ORDER BY term off
  129842. */
  129843. isMatch = 0;
  129844. for(i=0; bOnce && i<nOrderBy; i++){
  129845. if( MASKBIT(i) & obSat ) continue;
  129846. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  129847. testcase( wctrlFlags & WHERE_GROUPBY );
  129848. testcase( wctrlFlags & WHERE_DISTINCTBY );
  129849. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  129850. if( iColumn>=XN_ROWID ){
  129851. if( pOBExpr->op!=TK_COLUMN ) continue;
  129852. if( pOBExpr->iTable!=iCur ) continue;
  129853. if( pOBExpr->iColumn!=iColumn ) continue;
  129854. }else{
  129855. Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
  129856. if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
  129857. continue;
  129858. }
  129859. }
  129860. if( iColumn!=XN_ROWID ){
  129861. pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  129862. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  129863. }
  129864. pLoop->u.btree.nIdxCol = j+1;
  129865. isMatch = 1;
  129866. break;
  129867. }
  129868. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  129869. /* Make sure the sort order is compatible in an ORDER BY clause.
  129870. ** Sort order is irrelevant for a GROUP BY clause. */
  129871. if( revSet ){
  129872. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  129873. }else{
  129874. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  129875. if( rev ) *pRevMask |= MASKBIT(iLoop);
  129876. revSet = 1;
  129877. }
  129878. }
  129879. if( isMatch ){
  129880. if( iColumn==XN_ROWID ){
  129881. testcase( distinctColumns==0 );
  129882. distinctColumns = 1;
  129883. }
  129884. obSat |= MASKBIT(i);
  129885. }else{
  129886. /* No match found */
  129887. if( j==0 || j<nKeyCol ){
  129888. testcase( isOrderDistinct!=0 );
  129889. isOrderDistinct = 0;
  129890. }
  129891. break;
  129892. }
  129893. } /* end Loop over all index columns */
  129894. if( distinctColumns ){
  129895. testcase( isOrderDistinct==0 );
  129896. isOrderDistinct = 1;
  129897. }
  129898. } /* end-if not one-row */
  129899. /* Mark off any other ORDER BY terms that reference pLoop */
  129900. if( isOrderDistinct ){
  129901. orderDistinctMask |= pLoop->maskSelf;
  129902. for(i=0; i<nOrderBy; i++){
  129903. Expr *p;
  129904. Bitmask mTerm;
  129905. if( MASKBIT(i) & obSat ) continue;
  129906. p = pOrderBy->a[i].pExpr;
  129907. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  129908. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  129909. if( (mTerm&~orderDistinctMask)==0 ){
  129910. obSat |= MASKBIT(i);
  129911. }
  129912. }
  129913. }
  129914. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  129915. if( obSat==obDone ) return (i8)nOrderBy;
  129916. if( !isOrderDistinct ){
  129917. for(i=nOrderBy-1; i>0; i--){
  129918. Bitmask m = MASKBIT(i) - 1;
  129919. if( (obSat&m)==m ) return i;
  129920. }
  129921. return 0;
  129922. }
  129923. return -1;
  129924. }
  129925. /*
  129926. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  129927. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  129928. ** BY clause - and so any order that groups rows as required satisfies the
  129929. ** request.
  129930. **
  129931. ** Normally, in this case it is not possible for the caller to determine
  129932. ** whether or not the rows are really being delivered in sorted order, or
  129933. ** just in some other order that provides the required grouping. However,
  129934. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  129935. ** this function may be called on the returned WhereInfo object. It returns
  129936. ** true if the rows really will be sorted in the specified order, or false
  129937. ** otherwise.
  129938. **
  129939. ** For example, assuming:
  129940. **
  129941. ** CREATE INDEX i1 ON t1(x, Y);
  129942. **
  129943. ** then
  129944. **
  129945. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  129946. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  129947. */
  129948. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  129949. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  129950. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  129951. return pWInfo->sorted;
  129952. }
  129953. #ifdef WHERETRACE_ENABLED
  129954. /* For debugging use only: */
  129955. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  129956. static char zName[65];
  129957. int i;
  129958. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  129959. if( pLast ) zName[i++] = pLast->cId;
  129960. zName[i] = 0;
  129961. return zName;
  129962. }
  129963. #endif
  129964. /*
  129965. ** Return the cost of sorting nRow rows, assuming that the keys have
  129966. ** nOrderby columns and that the first nSorted columns are already in
  129967. ** order.
  129968. */
  129969. static LogEst whereSortingCost(
  129970. WhereInfo *pWInfo,
  129971. LogEst nRow,
  129972. int nOrderBy,
  129973. int nSorted
  129974. ){
  129975. /* TUNING: Estimated cost of a full external sort, where N is
  129976. ** the number of rows to sort is:
  129977. **
  129978. ** cost = (3.0 * N * log(N)).
  129979. **
  129980. ** Or, if the order-by clause has X terms but only the last Y
  129981. ** terms are out of order, then block-sorting will reduce the
  129982. ** sorting cost to:
  129983. **
  129984. ** cost = (3.0 * N * log(N)) * (Y/X)
  129985. **
  129986. ** The (Y/X) term is implemented using stack variable rScale
  129987. ** below. */
  129988. LogEst rScale, rSortCost;
  129989. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  129990. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  129991. rSortCost = nRow + rScale + 16;
  129992. /* Multiple by log(M) where M is the number of output rows.
  129993. ** Use the LIMIT for M if it is smaller */
  129994. if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
  129995. nRow = pWInfo->iLimit;
  129996. }
  129997. rSortCost += estLog(nRow);
  129998. return rSortCost;
  129999. }
  130000. /*
  130001. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  130002. ** attempts to find the lowest cost path that visits each WhereLoop
  130003. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  130004. **
  130005. ** Assume that the total number of output rows that will need to be sorted
  130006. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  130007. ** costs if nRowEst==0.
  130008. **
  130009. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  130010. ** error occurs.
  130011. */
  130012. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  130013. int mxChoice; /* Maximum number of simultaneous paths tracked */
  130014. int nLoop; /* Number of terms in the join */
  130015. Parse *pParse; /* Parsing context */
  130016. sqlite3 *db; /* The database connection */
  130017. int iLoop; /* Loop counter over the terms of the join */
  130018. int ii, jj; /* Loop counters */
  130019. int mxI = 0; /* Index of next entry to replace */
  130020. int nOrderBy; /* Number of ORDER BY clause terms */
  130021. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  130022. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  130023. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  130024. WherePath *aFrom; /* All nFrom paths at the previous level */
  130025. WherePath *aTo; /* The nTo best paths at the current level */
  130026. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  130027. WherePath *pTo; /* An element of aTo[] that we are working on */
  130028. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  130029. WhereLoop **pX; /* Used to divy up the pSpace memory */
  130030. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  130031. char *pSpace; /* Temporary memory used by this routine */
  130032. int nSpace; /* Bytes of space allocated at pSpace */
  130033. pParse = pWInfo->pParse;
  130034. db = pParse->db;
  130035. nLoop = pWInfo->nLevel;
  130036. /* TUNING: For simple queries, only the best path is tracked.
  130037. ** For 2-way joins, the 5 best paths are followed.
  130038. ** For joins of 3 or more tables, track the 10 best paths */
  130039. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  130040. assert( nLoop<=pWInfo->pTabList->nSrc );
  130041. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  130042. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  130043. ** case the purpose of this call is to estimate the number of rows returned
  130044. ** by the overall query. Once this estimate has been obtained, the caller
  130045. ** will invoke this function a second time, passing the estimate as the
  130046. ** nRowEst parameter. */
  130047. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  130048. nOrderBy = 0;
  130049. }else{
  130050. nOrderBy = pWInfo->pOrderBy->nExpr;
  130051. }
  130052. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  130053. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  130054. nSpace += sizeof(LogEst) * nOrderBy;
  130055. pSpace = sqlite3DbMallocRawNN(db, nSpace);
  130056. if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
  130057. aTo = (WherePath*)pSpace;
  130058. aFrom = aTo+mxChoice;
  130059. memset(aFrom, 0, sizeof(aFrom[0]));
  130060. pX = (WhereLoop**)(aFrom+mxChoice);
  130061. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  130062. pFrom->aLoop = pX;
  130063. }
  130064. if( nOrderBy ){
  130065. /* If there is an ORDER BY clause and it is not being ignored, set up
  130066. ** space for the aSortCost[] array. Each element of the aSortCost array
  130067. ** is either zero - meaning it has not yet been initialized - or the
  130068. ** cost of sorting nRowEst rows of data where the first X terms of
  130069. ** the ORDER BY clause are already in order, where X is the array
  130070. ** index. */
  130071. aSortCost = (LogEst*)pX;
  130072. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  130073. }
  130074. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  130075. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  130076. /* Seed the search with a single WherePath containing zero WhereLoops.
  130077. **
  130078. ** TUNING: Do not let the number of iterations go above 28. If the cost
  130079. ** of computing an automatic index is not paid back within the first 28
  130080. ** rows, then do not use the automatic index. */
  130081. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  130082. nFrom = 1;
  130083. assert( aFrom[0].isOrdered==0 );
  130084. if( nOrderBy ){
  130085. /* If nLoop is zero, then there are no FROM terms in the query. Since
  130086. ** in this case the query may return a maximum of one row, the results
  130087. ** are already in the requested order. Set isOrdered to nOrderBy to
  130088. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  130089. ** -1, indicating that the result set may or may not be ordered,
  130090. ** depending on the loops added to the current plan. */
  130091. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  130092. }
  130093. /* Compute successively longer WherePaths using the previous generation
  130094. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  130095. ** best paths at each generation */
  130096. for(iLoop=0; iLoop<nLoop; iLoop++){
  130097. nTo = 0;
  130098. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  130099. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  130100. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  130101. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  130102. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  130103. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  130104. Bitmask maskNew; /* Mask of src visited by (..) */
  130105. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  130106. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  130107. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  130108. if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
  130109. /* Do not use an automatic index if the this loop is expected
  130110. ** to run less than 2 times. */
  130111. assert( 10==sqlite3LogEst(2) );
  130112. continue;
  130113. }
  130114. /* At this point, pWLoop is a candidate to be the next loop.
  130115. ** Compute its cost */
  130116. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  130117. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  130118. nOut = pFrom->nRow + pWLoop->nOut;
  130119. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  130120. if( isOrdered<0 ){
  130121. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  130122. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  130123. iLoop, pWLoop, &revMask);
  130124. }else{
  130125. revMask = pFrom->revLoop;
  130126. }
  130127. if( isOrdered>=0 && isOrdered<nOrderBy ){
  130128. if( aSortCost[isOrdered]==0 ){
  130129. aSortCost[isOrdered] = whereSortingCost(
  130130. pWInfo, nRowEst, nOrderBy, isOrdered
  130131. );
  130132. }
  130133. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  130134. WHERETRACE(0x002,
  130135. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  130136. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  130137. rUnsorted, rCost));
  130138. }else{
  130139. rCost = rUnsorted;
  130140. rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
  130141. }
  130142. /* Check to see if pWLoop should be added to the set of
  130143. ** mxChoice best-so-far paths.
  130144. **
  130145. ** First look for an existing path among best-so-far paths
  130146. ** that covers the same set of loops and has the same isOrdered
  130147. ** setting as the current path candidate.
  130148. **
  130149. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  130150. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  130151. ** of legal values for isOrdered, -1..64.
  130152. */
  130153. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  130154. if( pTo->maskLoop==maskNew
  130155. && ((pTo->isOrdered^isOrdered)&0x80)==0
  130156. ){
  130157. testcase( jj==nTo-1 );
  130158. break;
  130159. }
  130160. }
  130161. if( jj>=nTo ){
  130162. /* None of the existing best-so-far paths match the candidate. */
  130163. if( nTo>=mxChoice
  130164. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  130165. ){
  130166. /* The current candidate is no better than any of the mxChoice
  130167. ** paths currently in the best-so-far buffer. So discard
  130168. ** this candidate as not viable. */
  130169. #ifdef WHERETRACE_ENABLED /* 0x4 */
  130170. if( sqlite3WhereTrace&0x4 ){
  130171. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
  130172. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  130173. isOrdered>=0 ? isOrdered+'0' : '?');
  130174. }
  130175. #endif
  130176. continue;
  130177. }
  130178. /* If we reach this points it means that the new candidate path
  130179. ** needs to be added to the set of best-so-far paths. */
  130180. if( nTo<mxChoice ){
  130181. /* Increase the size of the aTo set by one */
  130182. jj = nTo++;
  130183. }else{
  130184. /* New path replaces the prior worst to keep count below mxChoice */
  130185. jj = mxI;
  130186. }
  130187. pTo = &aTo[jj];
  130188. #ifdef WHERETRACE_ENABLED /* 0x4 */
  130189. if( sqlite3WhereTrace&0x4 ){
  130190. sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
  130191. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  130192. isOrdered>=0 ? isOrdered+'0' : '?');
  130193. }
  130194. #endif
  130195. }else{
  130196. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  130197. ** same set of loops and has the same isOrdered setting as the
  130198. ** candidate path. Check to see if the candidate should replace
  130199. ** pTo or if the candidate should be skipped.
  130200. **
  130201. ** The conditional is an expanded vector comparison equivalent to:
  130202. ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
  130203. */
  130204. if( pTo->rCost<rCost
  130205. || (pTo->rCost==rCost
  130206. && (pTo->nRow<nOut
  130207. || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
  130208. )
  130209. )
  130210. ){
  130211. #ifdef WHERETRACE_ENABLED /* 0x4 */
  130212. if( sqlite3WhereTrace&0x4 ){
  130213. sqlite3DebugPrintf(
  130214. "Skip %s cost=%-3d,%3d,%3d order=%c",
  130215. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  130216. isOrdered>=0 ? isOrdered+'0' : '?');
  130217. sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
  130218. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  130219. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  130220. }
  130221. #endif
  130222. /* Discard the candidate path from further consideration */
  130223. testcase( pTo->rCost==rCost );
  130224. continue;
  130225. }
  130226. testcase( pTo->rCost==rCost+1 );
  130227. /* Control reaches here if the candidate path is better than the
  130228. ** pTo path. Replace pTo with the candidate. */
  130229. #ifdef WHERETRACE_ENABLED /* 0x4 */
  130230. if( sqlite3WhereTrace&0x4 ){
  130231. sqlite3DebugPrintf(
  130232. "Update %s cost=%-3d,%3d,%3d order=%c",
  130233. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  130234. isOrdered>=0 ? isOrdered+'0' : '?');
  130235. sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
  130236. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  130237. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  130238. }
  130239. #endif
  130240. }
  130241. /* pWLoop is a winner. Add it to the set of best so far */
  130242. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  130243. pTo->revLoop = revMask;
  130244. pTo->nRow = nOut;
  130245. pTo->rCost = rCost;
  130246. pTo->rUnsorted = rUnsorted;
  130247. pTo->isOrdered = isOrdered;
  130248. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  130249. pTo->aLoop[iLoop] = pWLoop;
  130250. if( nTo>=mxChoice ){
  130251. mxI = 0;
  130252. mxCost = aTo[0].rCost;
  130253. mxUnsorted = aTo[0].nRow;
  130254. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  130255. if( pTo->rCost>mxCost
  130256. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  130257. ){
  130258. mxCost = pTo->rCost;
  130259. mxUnsorted = pTo->rUnsorted;
  130260. mxI = jj;
  130261. }
  130262. }
  130263. }
  130264. }
  130265. }
  130266. #ifdef WHERETRACE_ENABLED /* >=2 */
  130267. if( sqlite3WhereTrace & 0x02 ){
  130268. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  130269. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  130270. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  130271. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  130272. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  130273. if( pTo->isOrdered>0 ){
  130274. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  130275. }else{
  130276. sqlite3DebugPrintf("\n");
  130277. }
  130278. }
  130279. }
  130280. #endif
  130281. /* Swap the roles of aFrom and aTo for the next generation */
  130282. pFrom = aTo;
  130283. aTo = aFrom;
  130284. aFrom = pFrom;
  130285. nFrom = nTo;
  130286. }
  130287. if( nFrom==0 ){
  130288. sqlite3ErrorMsg(pParse, "no query solution");
  130289. sqlite3DbFreeNN(db, pSpace);
  130290. return SQLITE_ERROR;
  130291. }
  130292. /* Find the lowest cost path. pFrom will be left pointing to that path */
  130293. pFrom = aFrom;
  130294. for(ii=1; ii<nFrom; ii++){
  130295. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  130296. }
  130297. assert( pWInfo->nLevel==nLoop );
  130298. /* Load the lowest cost path into pWInfo */
  130299. for(iLoop=0; iLoop<nLoop; iLoop++){
  130300. WhereLevel *pLevel = pWInfo->a + iLoop;
  130301. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  130302. pLevel->iFrom = pWLoop->iTab;
  130303. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  130304. }
  130305. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  130306. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  130307. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  130308. && nRowEst
  130309. ){
  130310. Bitmask notUsed;
  130311. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  130312. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  130313. if( rc==pWInfo->pResultSet->nExpr ){
  130314. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  130315. }
  130316. }
  130317. if( pWInfo->pOrderBy ){
  130318. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  130319. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  130320. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  130321. }
  130322. }else{
  130323. pWInfo->nOBSat = pFrom->isOrdered;
  130324. pWInfo->revMask = pFrom->revLoop;
  130325. if( pWInfo->nOBSat<=0 ){
  130326. pWInfo->nOBSat = 0;
  130327. if( nLoop>0 ){
  130328. u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
  130329. if( (wsFlags & WHERE_ONEROW)==0
  130330. && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
  130331. ){
  130332. Bitmask m = 0;
  130333. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
  130334. WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
  130335. testcase( wsFlags & WHERE_IPK );
  130336. testcase( wsFlags & WHERE_COLUMN_IN );
  130337. if( rc==pWInfo->pOrderBy->nExpr ){
  130338. pWInfo->bOrderedInnerLoop = 1;
  130339. pWInfo->revMask = m;
  130340. }
  130341. }
  130342. }
  130343. }
  130344. }
  130345. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  130346. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  130347. ){
  130348. Bitmask revMask = 0;
  130349. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  130350. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  130351. );
  130352. assert( pWInfo->sorted==0 );
  130353. if( nOrder==pWInfo->pOrderBy->nExpr ){
  130354. pWInfo->sorted = 1;
  130355. pWInfo->revMask = revMask;
  130356. }
  130357. }
  130358. }
  130359. pWInfo->nRowOut = pFrom->nRow;
  130360. /* Free temporary memory and return success */
  130361. sqlite3DbFreeNN(db, pSpace);
  130362. return SQLITE_OK;
  130363. }
  130364. /*
  130365. ** Most queries use only a single table (they are not joins) and have
  130366. ** simple == constraints against indexed fields. This routine attempts
  130367. ** to plan those simple cases using much less ceremony than the
  130368. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  130369. ** times for the common case.
  130370. **
  130371. ** Return non-zero on success, if this query can be handled by this
  130372. ** no-frills query planner. Return zero if this query needs the
  130373. ** general-purpose query planner.
  130374. */
  130375. static int whereShortCut(WhereLoopBuilder *pBuilder){
  130376. WhereInfo *pWInfo;
  130377. struct SrcList_item *pItem;
  130378. WhereClause *pWC;
  130379. WhereTerm *pTerm;
  130380. WhereLoop *pLoop;
  130381. int iCur;
  130382. int j;
  130383. Table *pTab;
  130384. Index *pIdx;
  130385. pWInfo = pBuilder->pWInfo;
  130386. if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
  130387. assert( pWInfo->pTabList->nSrc>=1 );
  130388. pItem = pWInfo->pTabList->a;
  130389. pTab = pItem->pTab;
  130390. if( IsVirtual(pTab) ) return 0;
  130391. if( pItem->fg.isIndexedBy ) return 0;
  130392. iCur = pItem->iCursor;
  130393. pWC = &pWInfo->sWC;
  130394. pLoop = pBuilder->pNew;
  130395. pLoop->wsFlags = 0;
  130396. pLoop->nSkip = 0;
  130397. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  130398. if( pTerm ){
  130399. testcase( pTerm->eOperator & WO_IS );
  130400. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  130401. pLoop->aLTerm[0] = pTerm;
  130402. pLoop->nLTerm = 1;
  130403. pLoop->u.btree.nEq = 1;
  130404. /* TUNING: Cost of a rowid lookup is 10 */
  130405. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  130406. }else{
  130407. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  130408. int opMask;
  130409. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  130410. if( !IsUniqueIndex(pIdx)
  130411. || pIdx->pPartIdxWhere!=0
  130412. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  130413. ) continue;
  130414. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  130415. for(j=0; j<pIdx->nKeyCol; j++){
  130416. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  130417. if( pTerm==0 ) break;
  130418. testcase( pTerm->eOperator & WO_IS );
  130419. pLoop->aLTerm[j] = pTerm;
  130420. }
  130421. if( j!=pIdx->nKeyCol ) continue;
  130422. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  130423. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  130424. pLoop->wsFlags |= WHERE_IDX_ONLY;
  130425. }
  130426. pLoop->nLTerm = j;
  130427. pLoop->u.btree.nEq = j;
  130428. pLoop->u.btree.pIndex = pIdx;
  130429. /* TUNING: Cost of a unique index lookup is 15 */
  130430. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  130431. break;
  130432. }
  130433. }
  130434. if( pLoop->wsFlags ){
  130435. pLoop->nOut = (LogEst)1;
  130436. pWInfo->a[0].pWLoop = pLoop;
  130437. assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
  130438. pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
  130439. pWInfo->a[0].iTabCur = iCur;
  130440. pWInfo->nRowOut = 1;
  130441. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  130442. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  130443. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  130444. }
  130445. #ifdef SQLITE_DEBUG
  130446. pLoop->cId = '0';
  130447. #endif
  130448. return 1;
  130449. }
  130450. return 0;
  130451. }
  130452. /*
  130453. ** Helper function for exprIsDeterministic().
  130454. */
  130455. static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
  130456. if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
  130457. pWalker->eCode = 0;
  130458. return WRC_Abort;
  130459. }
  130460. return WRC_Continue;
  130461. }
  130462. /*
  130463. ** Return true if the expression contains no non-deterministic SQL
  130464. ** functions. Do not consider non-deterministic SQL functions that are
  130465. ** part of sub-select statements.
  130466. */
  130467. static int exprIsDeterministic(Expr *p){
  130468. Walker w;
  130469. memset(&w, 0, sizeof(w));
  130470. w.eCode = 1;
  130471. w.xExprCallback = exprNodeIsDeterministic;
  130472. w.xSelectCallback = sqlite3SelectWalkFail;
  130473. sqlite3WalkExpr(&w, p);
  130474. return w.eCode;
  130475. }
  130476. /*
  130477. ** Generate the beginning of the loop used for WHERE clause processing.
  130478. ** The return value is a pointer to an opaque structure that contains
  130479. ** information needed to terminate the loop. Later, the calling routine
  130480. ** should invoke sqlite3WhereEnd() with the return value of this function
  130481. ** in order to complete the WHERE clause processing.
  130482. **
  130483. ** If an error occurs, this routine returns NULL.
  130484. **
  130485. ** The basic idea is to do a nested loop, one loop for each table in
  130486. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  130487. ** same as a SELECT with only a single table in the FROM clause.) For
  130488. ** example, if the SQL is this:
  130489. **
  130490. ** SELECT * FROM t1, t2, t3 WHERE ...;
  130491. **
  130492. ** Then the code generated is conceptually like the following:
  130493. **
  130494. ** foreach row1 in t1 do \ Code generated
  130495. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  130496. ** foreach row3 in t3 do /
  130497. ** ...
  130498. ** end \ Code generated
  130499. ** end |-- by sqlite3WhereEnd()
  130500. ** end /
  130501. **
  130502. ** Note that the loops might not be nested in the order in which they
  130503. ** appear in the FROM clause if a different order is better able to make
  130504. ** use of indices. Note also that when the IN operator appears in
  130505. ** the WHERE clause, it might result in additional nested loops for
  130506. ** scanning through all values on the right-hand side of the IN.
  130507. **
  130508. ** There are Btree cursors associated with each table. t1 uses cursor
  130509. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  130510. ** And so forth. This routine generates code to open those VDBE cursors
  130511. ** and sqlite3WhereEnd() generates the code to close them.
  130512. **
  130513. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  130514. ** in pTabList pointing at their appropriate entries. The [...] code
  130515. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  130516. ** data from the various tables of the loop.
  130517. **
  130518. ** If the WHERE clause is empty, the foreach loops must each scan their
  130519. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  130520. ** the tables have indices and there are terms in the WHERE clause that
  130521. ** refer to those indices, a complete table scan can be avoided and the
  130522. ** code will run much faster. Most of the work of this routine is checking
  130523. ** to see if there are indices that can be used to speed up the loop.
  130524. **
  130525. ** Terms of the WHERE clause are also used to limit which rows actually
  130526. ** make it to the "..." in the middle of the loop. After each "foreach",
  130527. ** terms of the WHERE clause that use only terms in that loop and outer
  130528. ** loops are evaluated and if false a jump is made around all subsequent
  130529. ** inner loops (or around the "..." if the test occurs within the inner-
  130530. ** most loop)
  130531. **
  130532. ** OUTER JOINS
  130533. **
  130534. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  130535. **
  130536. ** foreach row1 in t1 do
  130537. ** flag = 0
  130538. ** foreach row2 in t2 do
  130539. ** start:
  130540. ** ...
  130541. ** flag = 1
  130542. ** end
  130543. ** if flag==0 then
  130544. ** move the row2 cursor to a null row
  130545. ** goto start
  130546. ** fi
  130547. ** end
  130548. **
  130549. ** ORDER BY CLAUSE PROCESSING
  130550. **
  130551. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  130552. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  130553. ** if there is one. If there is no ORDER BY clause or if this routine
  130554. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  130555. **
  130556. ** The iIdxCur parameter is the cursor number of an index. If
  130557. ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
  130558. ** to use for OR clause processing. The WHERE clause should use this
  130559. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  130560. ** the first cursor in an array of cursors for all indices. iIdxCur should
  130561. ** be used to compute the appropriate cursor depending on which index is
  130562. ** used.
  130563. */
  130564. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  130565. Parse *pParse, /* The parser context */
  130566. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  130567. Expr *pWhere, /* The WHERE clause */
  130568. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  130569. ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
  130570. u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
  130571. int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
  130572. ** If WHERE_USE_LIMIT, then the limit amount */
  130573. ){
  130574. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  130575. int nTabList; /* Number of elements in pTabList */
  130576. WhereInfo *pWInfo; /* Will become the return value of this function */
  130577. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  130578. Bitmask notReady; /* Cursors that are not yet positioned */
  130579. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  130580. WhereMaskSet *pMaskSet; /* The expression mask set */
  130581. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  130582. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  130583. int ii; /* Loop counter */
  130584. sqlite3 *db; /* Database connection */
  130585. int rc; /* Return code */
  130586. u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
  130587. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  130588. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  130589. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  130590. ));
  130591. /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
  130592. assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  130593. || (wctrlFlags & WHERE_USE_LIMIT)==0 );
  130594. /* Variable initialization */
  130595. db = pParse->db;
  130596. memset(&sWLB, 0, sizeof(sWLB));
  130597. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  130598. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  130599. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  130600. sWLB.pOrderBy = pOrderBy;
  130601. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  130602. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  130603. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  130604. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  130605. }
  130606. /* The number of tables in the FROM clause is limited by the number of
  130607. ** bits in a Bitmask
  130608. */
  130609. testcase( pTabList->nSrc==BMS );
  130610. if( pTabList->nSrc>BMS ){
  130611. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  130612. return 0;
  130613. }
  130614. /* This function normally generates a nested loop for all tables in
  130615. ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
  130616. ** only generate code for the first table in pTabList and assume that
  130617. ** any cursors associated with subsequent tables are uninitialized.
  130618. */
  130619. nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
  130620. /* Allocate and initialize the WhereInfo structure that will become the
  130621. ** return value. A single allocation is used to store the WhereInfo
  130622. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  130623. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  130624. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  130625. ** some architectures. Hence the ROUND8() below.
  130626. */
  130627. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  130628. pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
  130629. if( db->mallocFailed ){
  130630. sqlite3DbFree(db, pWInfo);
  130631. pWInfo = 0;
  130632. goto whereBeginError;
  130633. }
  130634. pWInfo->pParse = pParse;
  130635. pWInfo->pTabList = pTabList;
  130636. pWInfo->pOrderBy = pOrderBy;
  130637. pWInfo->pWhere = pWhere;
  130638. pWInfo->pResultSet = pResultSet;
  130639. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  130640. pWInfo->nLevel = nTabList;
  130641. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  130642. pWInfo->wctrlFlags = wctrlFlags;
  130643. pWInfo->iLimit = iAuxArg;
  130644. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  130645. memset(&pWInfo->nOBSat, 0,
  130646. offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
  130647. memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
  130648. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  130649. pMaskSet = &pWInfo->sMaskSet;
  130650. sWLB.pWInfo = pWInfo;
  130651. sWLB.pWC = &pWInfo->sWC;
  130652. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  130653. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  130654. whereLoopInit(sWLB.pNew);
  130655. #ifdef SQLITE_DEBUG
  130656. sWLB.pNew->cId = '*';
  130657. #endif
  130658. /* Split the WHERE clause into separate subexpressions where each
  130659. ** subexpression is separated by an AND operator.
  130660. */
  130661. initMaskSet(pMaskSet);
  130662. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  130663. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  130664. /* Special case: No FROM clause
  130665. */
  130666. if( nTabList==0 ){
  130667. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  130668. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  130669. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  130670. }
  130671. }else{
  130672. /* Assign a bit from the bitmask to every term in the FROM clause.
  130673. **
  130674. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  130675. **
  130676. ** The rule of the previous sentence ensures thta if X is the bitmask for
  130677. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  130678. ** Knowing the bitmask for all tables to the left of a left join is
  130679. ** important. Ticket #3015.
  130680. **
  130681. ** Note that bitmasks are created for all pTabList->nSrc tables in
  130682. ** pTabList, not just the first nTabList tables. nTabList is normally
  130683. ** equal to pTabList->nSrc but might be shortened to 1 if the
  130684. ** WHERE_OR_SUBCLAUSE flag is set.
  130685. */
  130686. ii = 0;
  130687. do{
  130688. createMask(pMaskSet, pTabList->a[ii].iCursor);
  130689. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  130690. }while( (++ii)<pTabList->nSrc );
  130691. #ifdef SQLITE_DEBUG
  130692. {
  130693. Bitmask mx = 0;
  130694. for(ii=0; ii<pTabList->nSrc; ii++){
  130695. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  130696. assert( m>=mx );
  130697. mx = m;
  130698. }
  130699. }
  130700. #endif
  130701. }
  130702. /* Analyze all of the subexpressions. */
  130703. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  130704. if( db->mallocFailed ) goto whereBeginError;
  130705. /* Special case: WHERE terms that do not refer to any tables in the join
  130706. ** (constant expressions). Evaluate each such term, and jump over all the
  130707. ** generated code if the result is not true.
  130708. **
  130709. ** Do not do this if the expression contains non-deterministic functions
  130710. ** that are not within a sub-select. This is not strictly required, but
  130711. ** preserves SQLite's legacy behaviour in the following two cases:
  130712. **
  130713. ** FROM ... WHERE random()>0; -- eval random() once per row
  130714. ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall
  130715. */
  130716. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  130717. WhereTerm *pT = &sWLB.pWC->a[ii];
  130718. if( pT->wtFlags & TERM_VIRTUAL ) continue;
  130719. if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
  130720. sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  130721. pT->wtFlags |= TERM_CODED;
  130722. }
  130723. }
  130724. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  130725. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  130726. /* The DISTINCT marking is pointless. Ignore it. */
  130727. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  130728. }else if( pOrderBy==0 ){
  130729. /* Try to ORDER BY the result set to make distinct processing easier */
  130730. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  130731. pWInfo->pOrderBy = pResultSet;
  130732. }
  130733. }
  130734. /* Construct the WhereLoop objects */
  130735. #if defined(WHERETRACE_ENABLED)
  130736. if( sqlite3WhereTrace & 0xffff ){
  130737. sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
  130738. if( wctrlFlags & WHERE_USE_LIMIT ){
  130739. sqlite3DebugPrintf(", limit: %d", iAuxArg);
  130740. }
  130741. sqlite3DebugPrintf(")\n");
  130742. }
  130743. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  130744. sqlite3WhereClausePrint(sWLB.pWC);
  130745. }
  130746. #endif
  130747. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  130748. rc = whereLoopAddAll(&sWLB);
  130749. if( rc ) goto whereBeginError;
  130750. #ifdef WHERETRACE_ENABLED
  130751. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  130752. WhereLoop *p;
  130753. int i;
  130754. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  130755. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  130756. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  130757. p->cId = zLabel[i%(sizeof(zLabel)-1)];
  130758. whereLoopPrint(p, sWLB.pWC);
  130759. }
  130760. }
  130761. #endif
  130762. wherePathSolver(pWInfo, 0);
  130763. if( db->mallocFailed ) goto whereBeginError;
  130764. if( pWInfo->pOrderBy ){
  130765. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  130766. if( db->mallocFailed ) goto whereBeginError;
  130767. }
  130768. }
  130769. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  130770. pWInfo->revMask = ALLBITS;
  130771. }
  130772. if( pParse->nErr || NEVER(db->mallocFailed) ){
  130773. goto whereBeginError;
  130774. }
  130775. #ifdef WHERETRACE_ENABLED
  130776. if( sqlite3WhereTrace ){
  130777. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  130778. if( pWInfo->nOBSat>0 ){
  130779. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  130780. }
  130781. switch( pWInfo->eDistinct ){
  130782. case WHERE_DISTINCT_UNIQUE: {
  130783. sqlite3DebugPrintf(" DISTINCT=unique");
  130784. break;
  130785. }
  130786. case WHERE_DISTINCT_ORDERED: {
  130787. sqlite3DebugPrintf(" DISTINCT=ordered");
  130788. break;
  130789. }
  130790. case WHERE_DISTINCT_UNORDERED: {
  130791. sqlite3DebugPrintf(" DISTINCT=unordered");
  130792. break;
  130793. }
  130794. }
  130795. sqlite3DebugPrintf("\n");
  130796. for(ii=0; ii<pWInfo->nLevel; ii++){
  130797. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  130798. }
  130799. }
  130800. #endif
  130801. /* Attempt to omit tables from the join that do not affect the result.
  130802. ** For a table to not affect the result, the following must be true:
  130803. **
  130804. ** 1) The query must not be an aggregate.
  130805. ** 2) The table must be the RHS of a LEFT JOIN.
  130806. ** 3) Either the query must be DISTINCT, or else the ON or USING clause
  130807. ** must contain a constraint that limits the scan of the table to
  130808. ** at most a single row.
  130809. ** 4) The table must not be referenced by any part of the query apart
  130810. ** from its own USING or ON clause.
  130811. **
  130812. ** For example, given:
  130813. **
  130814. ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
  130815. ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
  130816. ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
  130817. **
  130818. ** then table t2 can be omitted from the following:
  130819. **
  130820. ** SELECT v1, v3 FROM t1
  130821. ** LEFT JOIN t2 USING (t1.ipk=t2.ipk)
  130822. ** LEFT JOIN t3 USING (t1.ipk=t3.ipk)
  130823. **
  130824. ** or from:
  130825. **
  130826. ** SELECT DISTINCT v1, v3 FROM t1
  130827. ** LEFT JOIN t2
  130828. ** LEFT JOIN t3 USING (t1.ipk=t3.ipk)
  130829. */
  130830. notReady = ~(Bitmask)0;
  130831. if( pWInfo->nLevel>=2
  130832. && pResultSet!=0 /* guarantees condition (1) above */
  130833. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  130834. ){
  130835. int i;
  130836. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  130837. if( sWLB.pOrderBy ){
  130838. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  130839. }
  130840. for(i=pWInfo->nLevel-1; i>=1; i--){
  130841. WhereTerm *pTerm, *pEnd;
  130842. struct SrcList_item *pItem;
  130843. pLoop = pWInfo->a[i].pWLoop;
  130844. pItem = &pWInfo->pTabList->a[pLoop->iTab];
  130845. if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
  130846. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  130847. && (pLoop->wsFlags & WHERE_ONEROW)==0
  130848. ){
  130849. continue;
  130850. }
  130851. if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
  130852. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  130853. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  130854. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  130855. if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  130856. || pTerm->pExpr->iRightJoinTable!=pItem->iCursor
  130857. ){
  130858. break;
  130859. }
  130860. }
  130861. }
  130862. if( pTerm<pEnd ) continue;
  130863. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  130864. notReady &= ~pLoop->maskSelf;
  130865. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  130866. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  130867. pTerm->wtFlags |= TERM_CODED;
  130868. }
  130869. }
  130870. if( i!=pWInfo->nLevel-1 ){
  130871. int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
  130872. memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
  130873. }
  130874. pWInfo->nLevel--;
  130875. nTabList--;
  130876. }
  130877. }
  130878. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  130879. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  130880. /* If the caller is an UPDATE or DELETE statement that is requesting
  130881. ** to use a one-pass algorithm, determine if this is appropriate.
  130882. **
  130883. ** A one-pass approach can be used if the caller has requested one
  130884. ** and either (a) the scan visits at most one row or (b) each
  130885. ** of the following are true:
  130886. **
  130887. ** * the caller has indicated that a one-pass approach can be used
  130888. ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
  130889. ** * the table is not a virtual table, and
  130890. ** * either the scan does not use the OR optimization or the caller
  130891. ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
  130892. ** for DELETE).
  130893. **
  130894. ** The last qualification is because an UPDATE statement uses
  130895. ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
  130896. ** use a one-pass approach, and this is not set accurately for scans
  130897. ** that use the OR optimization.
  130898. */
  130899. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  130900. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  130901. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  130902. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  130903. if( bOnerow || (
  130904. 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
  130905. && 0==(wsFlags & WHERE_VIRTUALTABLE)
  130906. && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
  130907. )){
  130908. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  130909. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  130910. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  130911. bFordelete = OPFLAG_FORDELETE;
  130912. }
  130913. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  130914. }
  130915. }
  130916. }
  130917. /* Open all tables in the pTabList and any indices selected for
  130918. ** searching those tables.
  130919. */
  130920. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  130921. Table *pTab; /* Table to open */
  130922. int iDb; /* Index of database containing table/index */
  130923. struct SrcList_item *pTabItem;
  130924. pTabItem = &pTabList->a[pLevel->iFrom];
  130925. pTab = pTabItem->pTab;
  130926. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  130927. pLoop = pLevel->pWLoop;
  130928. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  130929. /* Do nothing */
  130930. }else
  130931. #ifndef SQLITE_OMIT_VIRTUALTABLE
  130932. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  130933. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  130934. int iCur = pTabItem->iCursor;
  130935. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  130936. }else if( IsVirtual(pTab) ){
  130937. /* noop */
  130938. }else
  130939. #endif
  130940. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  130941. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  130942. int op = OP_OpenRead;
  130943. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  130944. op = OP_OpenWrite;
  130945. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  130946. };
  130947. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  130948. assert( pTabItem->iCursor==pLevel->iTabCur );
  130949. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  130950. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  130951. if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
  130952. Bitmask b = pTabItem->colUsed;
  130953. int n = 0;
  130954. for(; b; b=b>>1, n++){}
  130955. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
  130956. assert( n<=pTab->nCol );
  130957. }
  130958. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  130959. if( pLoop->u.btree.pIndex!=0 ){
  130960. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  130961. }else
  130962. #endif
  130963. {
  130964. sqlite3VdbeChangeP5(v, bFordelete);
  130965. }
  130966. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  130967. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  130968. (const u8*)&pTabItem->colUsed, P4_INT64);
  130969. #endif
  130970. }else{
  130971. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  130972. }
  130973. if( pLoop->wsFlags & WHERE_INDEXED ){
  130974. Index *pIx = pLoop->u.btree.pIndex;
  130975. int iIndexCur;
  130976. int op = OP_OpenRead;
  130977. /* iAuxArg is always set to a positive value if ONEPASS is possible */
  130978. assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  130979. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  130980. && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
  130981. ){
  130982. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  130983. ** WITHOUT ROWID table. No need for a separate index */
  130984. iIndexCur = pLevel->iTabCur;
  130985. op = 0;
  130986. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  130987. Index *pJ = pTabItem->pTab->pIndex;
  130988. iIndexCur = iAuxArg;
  130989. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  130990. while( ALWAYS(pJ) && pJ!=pIx ){
  130991. iIndexCur++;
  130992. pJ = pJ->pNext;
  130993. }
  130994. op = OP_OpenWrite;
  130995. pWInfo->aiCurOnePass[1] = iIndexCur;
  130996. }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
  130997. iIndexCur = iAuxArg;
  130998. op = OP_ReopenIdx;
  130999. }else{
  131000. iIndexCur = pParse->nTab++;
  131001. }
  131002. pLevel->iIdxCur = iIndexCur;
  131003. assert( pIx->pSchema==pTab->pSchema );
  131004. assert( iIndexCur>=0 );
  131005. if( op ){
  131006. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  131007. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  131008. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  131009. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  131010. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  131011. && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
  131012. ){
  131013. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  131014. }
  131015. VdbeComment((v, "%s", pIx->zName));
  131016. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  131017. {
  131018. u64 colUsed = 0;
  131019. int ii, jj;
  131020. for(ii=0; ii<pIx->nColumn; ii++){
  131021. jj = pIx->aiColumn[ii];
  131022. if( jj<0 ) continue;
  131023. if( jj>63 ) jj = 63;
  131024. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  131025. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  131026. }
  131027. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  131028. (u8*)&colUsed, P4_INT64);
  131029. }
  131030. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  131031. }
  131032. }
  131033. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  131034. }
  131035. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  131036. if( db->mallocFailed ) goto whereBeginError;
  131037. /* Generate the code to do the search. Each iteration of the for
  131038. ** loop below generates code for a single nested loop of the VM
  131039. ** program.
  131040. */
  131041. for(ii=0; ii<nTabList; ii++){
  131042. int addrExplain;
  131043. int wsFlags;
  131044. pLevel = &pWInfo->a[ii];
  131045. wsFlags = pLevel->pWLoop->wsFlags;
  131046. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  131047. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  131048. constructAutomaticIndex(pParse, &pWInfo->sWC,
  131049. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  131050. if( db->mallocFailed ) goto whereBeginError;
  131051. }
  131052. #endif
  131053. addrExplain = sqlite3WhereExplainOneScan(
  131054. pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
  131055. );
  131056. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  131057. notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
  131058. pWInfo->iContinue = pLevel->addrCont;
  131059. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
  131060. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  131061. }
  131062. }
  131063. /* Done. */
  131064. VdbeModuleComment((v, "Begin WHERE-core"));
  131065. return pWInfo;
  131066. /* Jump here if malloc fails */
  131067. whereBeginError:
  131068. if( pWInfo ){
  131069. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  131070. whereInfoFree(db, pWInfo);
  131071. }
  131072. return 0;
  131073. }
  131074. /*
  131075. ** Generate the end of the WHERE loop. See comments on
  131076. ** sqlite3WhereBegin() for additional information.
  131077. */
  131078. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  131079. Parse *pParse = pWInfo->pParse;
  131080. Vdbe *v = pParse->pVdbe;
  131081. int i;
  131082. WhereLevel *pLevel;
  131083. WhereLoop *pLoop;
  131084. SrcList *pTabList = pWInfo->pTabList;
  131085. sqlite3 *db = pParse->db;
  131086. /* Generate loop termination code.
  131087. */
  131088. VdbeModuleComment((v, "End WHERE-core"));
  131089. sqlite3ExprCacheClear(pParse);
  131090. for(i=pWInfo->nLevel-1; i>=0; i--){
  131091. int addr;
  131092. pLevel = &pWInfo->a[i];
  131093. pLoop = pLevel->pWLoop;
  131094. if( pLevel->op!=OP_Noop ){
  131095. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  131096. int addrSeek = 0;
  131097. Index *pIdx;
  131098. int n;
  131099. if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
  131100. && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
  131101. && (pLoop->wsFlags & WHERE_INDEXED)!=0
  131102. && (pIdx = pLoop->u.btree.pIndex)->hasStat1
  131103. && (n = pLoop->u.btree.nIdxCol)>0
  131104. && pIdx->aiRowLogEst[n]>=36
  131105. ){
  131106. int r1 = pParse->nMem+1;
  131107. int j, op;
  131108. for(j=0; j<n; j++){
  131109. sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
  131110. }
  131111. pParse->nMem += n+1;
  131112. op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
  131113. addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
  131114. VdbeCoverageIf(v, op==OP_SeekLT);
  131115. VdbeCoverageIf(v, op==OP_SeekGT);
  131116. sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
  131117. }
  131118. #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
  131119. /* The common case: Advance to the next row */
  131120. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  131121. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  131122. sqlite3VdbeChangeP5(v, pLevel->p5);
  131123. VdbeCoverage(v);
  131124. VdbeCoverageIf(v, pLevel->op==OP_Next);
  131125. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  131126. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  131127. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  131128. if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
  131129. #endif
  131130. }else{
  131131. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  131132. }
  131133. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  131134. struct InLoop *pIn;
  131135. int j;
  131136. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  131137. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  131138. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  131139. if( pIn->eEndLoopOp!=OP_Noop ){
  131140. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  131141. VdbeCoverage(v);
  131142. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  131143. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  131144. }
  131145. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  131146. }
  131147. }
  131148. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  131149. if( pLevel->addrSkip ){
  131150. sqlite3VdbeGoto(v, pLevel->addrSkip);
  131151. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  131152. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  131153. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  131154. }
  131155. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  131156. if( pLevel->addrLikeRep ){
  131157. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
  131158. pLevel->addrLikeRep);
  131159. VdbeCoverage(v);
  131160. }
  131161. #endif
  131162. if( pLevel->iLeftJoin ){
  131163. int ws = pLoop->wsFlags;
  131164. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  131165. assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
  131166. if( (ws & WHERE_IDX_ONLY)==0 ){
  131167. assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
  131168. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
  131169. }
  131170. if( (ws & WHERE_INDEXED)
  131171. || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
  131172. ){
  131173. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  131174. }
  131175. if( pLevel->op==OP_Return ){
  131176. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  131177. }else{
  131178. sqlite3VdbeGoto(v, pLevel->addrFirst);
  131179. }
  131180. sqlite3VdbeJumpHere(v, addr);
  131181. }
  131182. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  131183. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  131184. }
  131185. /* The "break" point is here, just past the end of the outer loop.
  131186. ** Set it.
  131187. */
  131188. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  131189. assert( pWInfo->nLevel<=pTabList->nSrc );
  131190. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  131191. int k, last;
  131192. VdbeOp *pOp;
  131193. Index *pIdx = 0;
  131194. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  131195. Table *pTab = pTabItem->pTab;
  131196. assert( pTab!=0 );
  131197. pLoop = pLevel->pWLoop;
  131198. /* For a co-routine, change all OP_Column references to the table of
  131199. ** the co-routine into OP_Copy of result contained in a register.
  131200. ** OP_Rowid becomes OP_Null.
  131201. */
  131202. if( pTabItem->fg.viaCoroutine ){
  131203. testcase( pParse->db->mallocFailed );
  131204. translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
  131205. pTabItem->regResult, 0);
  131206. continue;
  131207. }
  131208. /* If this scan uses an index, make VDBE code substitutions to read data
  131209. ** from the index instead of from the table where possible. In some cases
  131210. ** this optimization prevents the table from ever being read, which can
  131211. ** yield a significant performance boost.
  131212. **
  131213. ** Calls to the code generator in between sqlite3WhereBegin and
  131214. ** sqlite3WhereEnd will have created code that references the table
  131215. ** directly. This loop scans all that code looking for opcodes
  131216. ** that reference the table and converts them into opcodes that
  131217. ** reference the index.
  131218. */
  131219. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  131220. pIdx = pLoop->u.btree.pIndex;
  131221. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  131222. pIdx = pLevel->u.pCovidx;
  131223. }
  131224. if( pIdx
  131225. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  131226. && !db->mallocFailed
  131227. ){
  131228. last = sqlite3VdbeCurrentAddr(v);
  131229. k = pLevel->addrBody;
  131230. pOp = sqlite3VdbeGetOp(v, k);
  131231. for(; k<last; k++, pOp++){
  131232. if( pOp->p1!=pLevel->iTabCur ) continue;
  131233. if( pOp->opcode==OP_Column
  131234. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  131235. || pOp->opcode==OP_Offset
  131236. #endif
  131237. ){
  131238. int x = pOp->p2;
  131239. assert( pIdx->pTable==pTab );
  131240. if( !HasRowid(pTab) ){
  131241. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  131242. x = pPk->aiColumn[x];
  131243. assert( x>=0 );
  131244. }
  131245. x = sqlite3ColumnOfIndex(pIdx, x);
  131246. if( x>=0 ){
  131247. pOp->p2 = x;
  131248. pOp->p1 = pLevel->iIdxCur;
  131249. }
  131250. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
  131251. || pWInfo->eOnePass );
  131252. }else if( pOp->opcode==OP_Rowid ){
  131253. pOp->p1 = pLevel->iIdxCur;
  131254. pOp->opcode = OP_IdxRowid;
  131255. }else if( pOp->opcode==OP_IfNullRow ){
  131256. pOp->p1 = pLevel->iIdxCur;
  131257. }
  131258. }
  131259. }
  131260. }
  131261. /* Final cleanup
  131262. */
  131263. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  131264. whereInfoFree(db, pWInfo);
  131265. return;
  131266. }
  131267. /************** End of where.c ***********************************************/
  131268. /************** Begin file parse.c *******************************************/
  131269. /*
  131270. ** 2000-05-29
  131271. **
  131272. ** The author disclaims copyright to this source code. In place of
  131273. ** a legal notice, here is a blessing:
  131274. **
  131275. ** May you do good and not evil.
  131276. ** May you find forgiveness for yourself and forgive others.
  131277. ** May you share freely, never taking more than you give.
  131278. **
  131279. *************************************************************************
  131280. ** Driver template for the LEMON parser generator.
  131281. **
  131282. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  131283. ** this template to construct a parser. The "lemon" program inserts text
  131284. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  131285. ** interstitial "-" characters) contained in this template is changed into
  131286. ** the value of the %name directive from the grammar. Otherwise, the content
  131287. ** of this template is copied straight through into the generate parser
  131288. ** source file.
  131289. **
  131290. ** The following is the concatenation of all %include directives from the
  131291. ** input grammar file:
  131292. */
  131293. /* #include <stdio.h> */
  131294. /************ Begin %include sections from the grammar ************************/
  131295. /* #include "sqliteInt.h" */
  131296. /*
  131297. ** Disable all error recovery processing in the parser push-down
  131298. ** automaton.
  131299. */
  131300. #define YYNOERRORRECOVERY 1
  131301. /*
  131302. ** Make yytestcase() the same as testcase()
  131303. */
  131304. #define yytestcase(X) testcase(X)
  131305. /*
  131306. ** Indicate that sqlite3ParserFree() will never be called with a null
  131307. ** pointer.
  131308. */
  131309. #define YYPARSEFREENEVERNULL 1
  131310. /*
  131311. ** In the amalgamation, the parse.c file generated by lemon and the
  131312. ** tokenize.c file are concatenated. In that case, sqlite3RunParser()
  131313. ** has access to the the size of the yyParser object and so the parser
  131314. ** engine can be allocated from stack. In that case, only the
  131315. ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
  131316. ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
  131317. ** omitted.
  131318. */
  131319. #ifdef SQLITE_AMALGAMATION
  131320. # define sqlite3Parser_ENGINEALWAYSONSTACK 1
  131321. #endif
  131322. /*
  131323. ** Alternative datatype for the argument to the malloc() routine passed
  131324. ** into sqlite3ParserAlloc(). The default is size_t.
  131325. */
  131326. #define YYMALLOCARGTYPE u64
  131327. /*
  131328. ** An instance of the following structure describes the event of a
  131329. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  131330. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  131331. **
  131332. ** UPDATE ON (a,b,c)
  131333. **
  131334. ** Then the "b" IdList records the list "a,b,c".
  131335. */
  131336. struct TrigEvent { int a; IdList * b; };
  131337. /*
  131338. ** Disable lookaside memory allocation for objects that might be
  131339. ** shared across database connections.
  131340. */
  131341. static void disableLookaside(Parse *pParse){
  131342. pParse->disableLookaside++;
  131343. pParse->db->lookaside.bDisable++;
  131344. }
  131345. /*
  131346. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  131347. ** all elements in the list. And make sure list length does not exceed
  131348. ** SQLITE_LIMIT_COMPOUND_SELECT.
  131349. */
  131350. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  131351. if( p->pPrior ){
  131352. Select *pNext = 0, *pLoop;
  131353. int mxSelect, cnt = 0;
  131354. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  131355. pLoop->pNext = pNext;
  131356. pLoop->selFlags |= SF_Compound;
  131357. }
  131358. if( (p->selFlags & SF_MultiValue)==0 &&
  131359. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  131360. cnt>mxSelect
  131361. ){
  131362. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  131363. }
  131364. }
  131365. }
  131366. /* Construct a new Expr object from a single identifier. Use the
  131367. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  131368. ** that created the expression.
  131369. */
  131370. static Expr *tokenExpr(Parse *pParse, int op, Token t){
  131371. Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
  131372. if( p ){
  131373. memset(p, 0, sizeof(Expr));
  131374. p->op = (u8)op;
  131375. p->flags = EP_Leaf;
  131376. p->iAgg = -1;
  131377. p->u.zToken = (char*)&p[1];
  131378. memcpy(p->u.zToken, t.z, t.n);
  131379. p->u.zToken[t.n] = 0;
  131380. if( sqlite3Isquote(p->u.zToken[0]) ){
  131381. if( p->u.zToken[0]=='"' ) p->flags |= EP_DblQuoted;
  131382. sqlite3Dequote(p->u.zToken);
  131383. }
  131384. #if SQLITE_MAX_EXPR_DEPTH>0
  131385. p->nHeight = 1;
  131386. #endif
  131387. }
  131388. return p;
  131389. }
  131390. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  131391. ** unary TK_ISNULL or TK_NOTNULL expression. */
  131392. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  131393. sqlite3 *db = pParse->db;
  131394. if( pA && pY && pY->op==TK_NULL ){
  131395. pA->op = (u8)op;
  131396. sqlite3ExprDelete(db, pA->pRight);
  131397. pA->pRight = 0;
  131398. }
  131399. }
  131400. /* Add a single new term to an ExprList that is used to store a
  131401. ** list of identifiers. Report an error if the ID list contains
  131402. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  131403. ** error while parsing a legacy schema.
  131404. */
  131405. static ExprList *parserAddExprIdListTerm(
  131406. Parse *pParse,
  131407. ExprList *pPrior,
  131408. Token *pIdToken,
  131409. int hasCollate,
  131410. int sortOrder
  131411. ){
  131412. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  131413. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  131414. && pParse->db->init.busy==0
  131415. ){
  131416. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  131417. pIdToken->n, pIdToken->z);
  131418. }
  131419. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  131420. return p;
  131421. }
  131422. /**************** End of %include directives **********************************/
  131423. /* These constants specify the various numeric values for terminal symbols
  131424. ** in a format understandable to "makeheaders". This section is blank unless
  131425. ** "lemon" is run with the "-m" command-line option.
  131426. ***************** Begin makeheaders token definitions *************************/
  131427. /**************** End makeheaders token definitions ***************************/
  131428. /* The next sections is a series of control #defines.
  131429. ** various aspects of the generated parser.
  131430. ** YYCODETYPE is the data type used to store the integer codes
  131431. ** that represent terminal and non-terminal symbols.
  131432. ** "unsigned char" is used if there are fewer than
  131433. ** 256 symbols. Larger types otherwise.
  131434. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  131435. ** any terminal or nonterminal symbol.
  131436. ** YYFALLBACK If defined, this indicates that one or more tokens
  131437. ** (also known as: "terminal symbols") have fall-back
  131438. ** values which should be used if the original symbol
  131439. ** would not parse. This permits keywords to sometimes
  131440. ** be used as identifiers, for example.
  131441. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  131442. ** that indicate what to do in response to the next
  131443. ** token.
  131444. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  131445. ** symbols. Background: A "minor type" is a semantic
  131446. ** value associated with a terminal or non-terminal
  131447. ** symbols. For example, for an "ID" terminal symbol,
  131448. ** the minor type might be the name of the identifier.
  131449. ** Each non-terminal can have a different minor type.
  131450. ** Terminal symbols all have the same minor type, though.
  131451. ** This macros defines the minor type for terminal
  131452. ** symbols.
  131453. ** YYMINORTYPE is the data type used for all minor types.
  131454. ** This is typically a union of many types, one of
  131455. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  131456. ** for terminal symbols is called "yy0".
  131457. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  131458. ** zero the stack is dynamically sized using realloc()
  131459. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  131460. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  131461. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  131462. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  131463. ** YYERRORSYMBOL is the code number of the error symbol. If not
  131464. ** defined, then do no error processing.
  131465. ** YYNSTATE the combined number of states.
  131466. ** YYNRULE the number of rules in the grammar
  131467. ** YYNTOKEN Number of terminal symbols
  131468. ** YY_MAX_SHIFT Maximum value for shift actions
  131469. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  131470. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  131471. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  131472. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  131473. ** YY_NO_ACTION The yy_action[] code for no-op
  131474. ** YY_MIN_REDUCE Minimum value for reduce actions
  131475. ** YY_MAX_REDUCE Maximum value for reduce actions
  131476. */
  131477. #ifndef INTERFACE
  131478. # define INTERFACE 1
  131479. #endif
  131480. /************* Begin control #defines *****************************************/
  131481. #define YYCODETYPE unsigned char
  131482. #define YYNOCODE 253
  131483. #define YYACTIONTYPE unsigned short int
  131484. #define YYWILDCARD 83
  131485. #define sqlite3ParserTOKENTYPE Token
  131486. typedef union {
  131487. int yyinit;
  131488. sqlite3ParserTOKENTYPE yy0;
  131489. int yy4;
  131490. struct TrigEvent yy90;
  131491. TriggerStep* yy203;
  131492. struct {int value; int mask;} yy215;
  131493. SrcList* yy259;
  131494. Expr* yy314;
  131495. ExprList* yy322;
  131496. const char* yy336;
  131497. IdList* yy384;
  131498. Select* yy387;
  131499. With* yy451;
  131500. } YYMINORTYPE;
  131501. #ifndef YYSTACKDEPTH
  131502. #define YYSTACKDEPTH 100
  131503. #endif
  131504. #define sqlite3ParserARG_SDECL Parse *pParse;
  131505. #define sqlite3ParserARG_PDECL ,Parse *pParse
  131506. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  131507. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  131508. #define YYFALLBACK 1
  131509. #define YYNSTATE 472
  131510. #define YYNRULE 333
  131511. #define YYNTOKEN 143
  131512. #define YY_MAX_SHIFT 471
  131513. #define YY_MIN_SHIFTREDUCE 681
  131514. #define YY_MAX_SHIFTREDUCE 1013
  131515. #define YY_ERROR_ACTION 1014
  131516. #define YY_ACCEPT_ACTION 1015
  131517. #define YY_NO_ACTION 1016
  131518. #define YY_MIN_REDUCE 1017
  131519. #define YY_MAX_REDUCE 1349
  131520. /************* End control #defines *******************************************/
  131521. /* Define the yytestcase() macro to be a no-op if is not already defined
  131522. ** otherwise.
  131523. **
  131524. ** Applications can choose to define yytestcase() in the %include section
  131525. ** to a macro that can assist in verifying code coverage. For production
  131526. ** code the yytestcase() macro should be turned off. But it is useful
  131527. ** for testing.
  131528. */
  131529. #ifndef yytestcase
  131530. # define yytestcase(X)
  131531. #endif
  131532. /* Next are the tables used to determine what action to take based on the
  131533. ** current state and lookahead token. These tables are used to implement
  131534. ** functions that take a state number and lookahead value and return an
  131535. ** action integer.
  131536. **
  131537. ** Suppose the action integer is N. Then the action is determined as
  131538. ** follows
  131539. **
  131540. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  131541. ** token onto the stack and goto state N.
  131542. **
  131543. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  131544. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  131545. **
  131546. ** N == YY_ERROR_ACTION A syntax error has occurred.
  131547. **
  131548. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  131549. **
  131550. ** N == YY_NO_ACTION No such action. Denotes unused
  131551. ** slots in the yy_action[] table.
  131552. **
  131553. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  131554. ** and YY_MAX_REDUCE
  131555. **
  131556. ** The action table is constructed as a single large table named yy_action[].
  131557. ** Given state S and lookahead X, the action is computed as either:
  131558. **
  131559. ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
  131560. ** (B) N = yy_default[S]
  131561. **
  131562. ** The (A) formula is preferred. The B formula is used instead if
  131563. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.
  131564. **
  131565. ** The formulas above are for computing the action when the lookahead is
  131566. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  131567. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  131568. ** the yy_shift_ofst[] array.
  131569. **
  131570. ** The following are the tables generated in this section:
  131571. **
  131572. ** yy_action[] A single table containing all actions.
  131573. ** yy_lookahead[] A table containing the lookahead for each entry in
  131574. ** yy_action. Used to detect hash collisions.
  131575. ** yy_shift_ofst[] For each state, the offset into yy_action for
  131576. ** shifting terminals.
  131577. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  131578. ** shifting non-terminals after a reduce.
  131579. ** yy_default[] Default action for each state.
  131580. **
  131581. *********** Begin parsing tables **********************************************/
  131582. #define YY_ACTTAB_COUNT (1566)
  131583. static const YYACTIONTYPE yy_action[] = {
  131584. /* 0 */ 1169, 1015, 167, 167, 1, 168, 466, 1313, 466, 1083,
  131585. /* 10 */ 1062, 466, 97, 94, 183, 1057, 466, 329, 1083, 342,
  131586. /* 20 */ 97, 94, 183, 459, 459, 459, 436, 57, 57, 57,
  131587. /* 30 */ 57, 807, 57, 57, 367, 367, 367, 57, 57, 808,
  131588. /* 40 */ 1270, 1088, 1088, 104, 105, 95, 991, 991, 868, 871,
  131589. /* 50 */ 860, 860, 102, 102, 103, 103, 103, 103, 233, 233,
  131590. /* 60 */ 326, 1011, 449, 437, 449, 446, 351, 449, 461, 1142,
  131591. /* 70 */ 463, 342, 449, 426, 1316, 209, 180, 742, 80, 299,
  131592. /* 80 */ 857, 857, 869, 872, 101, 101, 101, 101, 100, 100,
  131593. /* 90 */ 99, 99, 99, 98, 368, 104, 105, 95, 991, 991,
  131594. /* 100 */ 868, 871, 860, 860, 102, 102, 103, 103, 103, 103,
  131595. /* 110 */ 99, 99, 99, 98, 368, 355, 97, 94, 183, 228,
  131596. /* 120 */ 106, 1012, 407, 342, 101, 101, 101, 101, 100, 100,
  131597. /* 130 */ 99, 99, 99, 98, 368, 861, 101, 101, 101, 101,
  131598. /* 140 */ 100, 100, 99, 99, 99, 98, 368, 104, 105, 95,
  131599. /* 150 */ 991, 991, 868, 871, 860, 860, 102, 102, 103, 103,
  131600. /* 160 */ 103, 103, 201, 368, 375, 420, 417, 416, 387, 273,
  131601. /* 170 */ 65, 97, 94, 183, 168, 342, 415, 951, 1343, 396,
  131602. /* 180 */ 66, 1343, 320, 959, 371, 970, 334, 340, 101, 101,
  131603. /* 190 */ 101, 101, 100, 100, 99, 99, 99, 98, 368, 104,
  131604. /* 200 */ 105, 95, 991, 991, 868, 871, 860, 860, 102, 102,
  131605. /* 210 */ 103, 103, 103, 103, 373, 100, 100, 99, 99, 99,
  131606. /* 220 */ 98, 368, 970, 971, 972, 201, 1100, 342, 420, 417,
  131607. /* 230 */ 416, 287, 366, 365, 337, 970, 1162, 463, 949, 415,
  131608. /* 240 */ 101, 101, 101, 101, 100, 100, 99, 99, 99, 98,
  131609. /* 250 */ 368, 104, 105, 95, 991, 991, 868, 871, 860, 860,
  131610. /* 260 */ 102, 102, 103, 103, 103, 103, 777, 241, 233, 233,
  131611. /* 270 */ 9, 847, 970, 971, 972, 390, 998, 1141, 998, 342,
  131612. /* 280 */ 463, 252, 829, 719, 98, 368, 840, 298, 338, 142,
  131613. /* 290 */ 839, 339, 101, 101, 101, 101, 100, 100, 99, 99,
  131614. /* 300 */ 99, 98, 368, 104, 105, 95, 991, 991, 868, 871,
  131615. /* 310 */ 860, 860, 102, 102, 103, 103, 103, 103, 272, 466,
  131616. /* 320 */ 392, 839, 839, 841, 97, 94, 183, 390, 1317, 253,
  131617. /* 330 */ 456, 342, 125, 166, 807, 712, 208, 407, 386, 970,
  131618. /* 340 */ 57, 57, 808, 238, 101, 101, 101, 101, 100, 100,
  131619. /* 350 */ 99, 99, 99, 98, 368, 104, 105, 95, 991, 991,
  131620. /* 360 */ 868, 871, 860, 860, 102, 102, 103, 103, 103, 103,
  131621. /* 370 */ 466, 108, 466, 267, 465, 442, 970, 971, 972, 261,
  131622. /* 380 */ 951, 1344, 909, 342, 1344, 142, 829, 848, 1292, 959,
  131623. /* 390 */ 371, 55, 55, 57, 57, 242, 101, 101, 101, 101,
  131624. /* 400 */ 100, 100, 99, 99, 99, 98, 368, 104, 105, 95,
  131625. /* 410 */ 991, 991, 868, 871, 860, 860, 102, 102, 103, 103,
  131626. /* 420 */ 103, 103, 272, 382, 262, 253, 456, 310, 364, 253,
  131627. /* 430 */ 456, 86, 264, 84, 266, 342, 441, 176, 175, 834,
  131628. /* 440 */ 464, 949, 767, 767, 332, 313, 1094, 396, 101, 101,
  131629. /* 450 */ 101, 101, 100, 100, 99, 99, 99, 98, 368, 104,
  131630. /* 460 */ 105, 95, 991, 991, 868, 871, 860, 860, 102, 102,
  131631. /* 470 */ 103, 103, 103, 103, 227, 227, 233, 233, 233, 233,
  131632. /* 480 */ 387, 273, 234, 234, 326, 950, 463, 342, 463, 298,
  131633. /* 490 */ 463, 914, 914, 404, 463, 1037, 123, 265, 27, 970,
  131634. /* 500 */ 101, 101, 101, 101, 100, 100, 99, 99, 99, 98,
  131635. /* 510 */ 368, 104, 105, 95, 991, 991, 868, 871, 860, 860,
  131636. /* 520 */ 102, 102, 103, 103, 103, 103, 435, 233, 233, 466,
  131637. /* 530 */ 285, 686, 687, 688, 127, 271, 970, 971, 972, 463,
  131638. /* 540 */ 1345, 327, 342, 407, 157, 1012, 988, 13, 13, 181,
  131639. /* 550 */ 41, 41, 101, 101, 101, 101, 100, 100, 99, 99,
  131640. /* 560 */ 99, 98, 368, 715, 794, 378, 104, 105, 95, 991,
  131641. /* 570 */ 991, 868, 871, 860, 860, 102, 102, 103, 103, 103,
  131642. /* 580 */ 103, 970, 378, 377, 346, 239, 847, 1086, 1086, 280,
  131643. /* 590 */ 1169, 283, 204, 203, 202, 177, 298, 342, 407, 298,
  131644. /* 600 */ 715, 840, 169, 299, 407, 839, 82, 101, 101, 101,
  131645. /* 610 */ 101, 100, 100, 99, 99, 99, 98, 368, 970, 971,
  131646. /* 620 */ 972, 104, 105, 95, 991, 991, 868, 871, 860, 860,
  131647. /* 630 */ 102, 102, 103, 103, 103, 103, 839, 839, 841, 362,
  131648. /* 640 */ 240, 124, 1169, 172, 126, 378, 1269, 1169, 1066, 342,
  131649. /* 650 */ 253, 456, 407, 407, 407, 396, 352, 401, 407, 429,
  131650. /* 660 */ 398, 85, 101, 101, 101, 101, 100, 100, 99, 99,
  131651. /* 670 */ 99, 98, 368, 104, 105, 95, 991, 991, 868, 871,
  131652. /* 680 */ 860, 860, 102, 102, 103, 103, 103, 103, 1169, 466,
  131653. /* 690 */ 230, 233, 233, 792, 1235, 1095, 1091, 1293, 1, 77,
  131654. /* 700 */ 278, 342, 205, 463, 974, 911, 1040, 348, 353, 911,
  131655. /* 710 */ 42, 42, 79, 403, 101, 101, 101, 101, 100, 100,
  131656. /* 720 */ 99, 99, 99, 98, 368, 104, 93, 95, 991, 991,
  131657. /* 730 */ 868, 871, 860, 860, 102, 102, 103, 103, 103, 103,
  131658. /* 740 */ 402, 9, 974, 243, 772, 458, 348, 232, 180, 771,
  131659. /* 750 */ 946, 312, 342, 328, 363, 349, 143, 831, 389, 1278,
  131660. /* 760 */ 211, 211, 21, 347, 432, 182, 101, 101, 101, 101,
  131661. /* 770 */ 100, 100, 99, 99, 99, 98, 368, 105, 95, 991,
  131662. /* 780 */ 991, 868, 871, 860, 860, 102, 102, 103, 103, 103,
  131663. /* 790 */ 103, 792, 724, 22, 732, 731, 233, 233, 1239, 256,
  131664. /* 800 */ 391, 274, 342, 211, 79, 360, 257, 413, 463, 397,
  131665. /* 810 */ 207, 288, 260, 450, 79, 1239, 1241, 101, 101, 101,
  131666. /* 820 */ 101, 100, 100, 99, 99, 99, 98, 368, 95, 991,
  131667. /* 830 */ 991, 868, 871, 860, 860, 102, 102, 103, 103, 103,
  131668. /* 840 */ 103, 91, 457, 296, 3, 233, 233, 5, 438, 212,
  131669. /* 850 */ 331, 394, 739, 740, 295, 898, 894, 463, 460, 207,
  131670. /* 860 */ 801, 1237, 722, 211, 698, 843, 1283, 101, 101, 101,
  131671. /* 870 */ 101, 100, 100, 99, 99, 99, 98, 368, 1239, 380,
  131672. /* 880 */ 357, 369, 233, 233, 989, 219, 236, 297, 423, 292,
  131673. /* 890 */ 422, 206, 454, 898, 463, 970, 91, 457, 290, 3,
  131674. /* 900 */ 722, 142, 268, 843, 847, 466, 1258, 149, 388, 425,
  131675. /* 910 */ 88, 89, 769, 460, 930, 87, 447, 90, 369, 468,
  131676. /* 920 */ 467, 385, 989, 839, 1257, 439, 57, 57, 395, 931,
  131677. /* 930 */ 1065, 158, 970, 971, 972, 772, 369, 471, 1019, 399,
  131678. /* 940 */ 771, 253, 456, 254, 932, 119, 891, 454, 233, 233,
  131679. /* 950 */ 4, 970, 1096, 275, 839, 839, 841, 842, 19, 847,
  131680. /* 960 */ 463, 449, 448, 163, 453, 88, 89, 776, 970, 1127,
  131681. /* 970 */ 279, 930, 90, 369, 468, 467, 91, 457, 839, 3,
  131682. /* 980 */ 235, 1064, 466, 1228, 233, 233, 931, 970, 970, 971,
  131683. /* 990 */ 972, 970, 908, 460, 908, 2, 463, 81, 457, 212,
  131684. /* 1000 */ 3, 932, 282, 10, 10, 970, 971, 972, 189, 839,
  131685. /* 1010 */ 839, 841, 842, 19, 460, 284, 369, 354, 907, 286,
  131686. /* 1020 */ 907, 753, 466, 1079, 970, 971, 972, 454, 970, 971,
  131687. /* 1030 */ 972, 754, 970, 1063, 989, 372, 792, 369, 1118, 847,
  131688. /* 1040 */ 291, 452, 466, 10, 10, 88, 89, 142, 454, 168,
  131689. /* 1050 */ 300, 412, 90, 369, 468, 467, 793, 356, 839, 706,
  131690. /* 1060 */ 847, 341, 121, 10, 10, 301, 88, 89, 379, 970,
  131691. /* 1070 */ 971, 972, 989, 90, 369, 468, 467, 244, 205, 839,
  131692. /* 1080 */ 1306, 245, 1135, 245, 250, 1168, 1114, 253, 456, 839,
  131693. /* 1090 */ 839, 841, 842, 19, 1125, 237, 122, 451, 1174, 733,
  131694. /* 1100 */ 324, 324, 323, 222, 321, 466, 1046, 695, 182, 225,
  131695. /* 1110 */ 839, 839, 841, 842, 19, 103, 103, 103, 103, 96,
  131696. /* 1120 */ 185, 466, 259, 1039, 1028, 170, 10, 10, 1027, 421,
  131697. /* 1130 */ 258, 1029, 1300, 708, 792, 466, 408, 734, 8, 347,
  131698. /* 1140 */ 444, 174, 12, 12, 290, 101, 101, 101, 101, 100,
  131699. /* 1150 */ 100, 99, 99, 99, 98, 368, 32, 32, 466, 187,
  131700. /* 1160 */ 466, 1111, 103, 103, 103, 103, 188, 466, 325, 138,
  131701. /* 1170 */ 186, 708, 303, 305, 307, 358, 970, 270, 393, 43,
  131702. /* 1180 */ 43, 44, 44, 1157, 333, 178, 418, 294, 45, 45,
  131703. /* 1190 */ 1232, 318, 101, 101, 101, 101, 100, 100, 99, 99,
  131704. /* 1200 */ 99, 98, 368, 381, 343, 366, 365, 466, 263, 253,
  131705. /* 1210 */ 456, 466, 1062, 970, 971, 972, 1231, 997, 309, 466,
  131706. /* 1220 */ 455, 466, 427, 466, 995, 173, 996, 1303, 46, 46,
  131707. /* 1230 */ 145, 376, 37, 37, 1006, 1277, 466, 214, 1275, 64,
  131708. /* 1240 */ 47, 47, 33, 33, 34, 34, 1003, 67, 466, 998,
  131709. /* 1250 */ 350, 998, 466, 155, 233, 233, 466, 36, 36, 24,
  131710. /* 1260 */ 140, 77, 1154, 466, 383, 466, 463, 428, 466, 48,
  131711. /* 1270 */ 48, 466, 147, 49, 49, 466, 150, 50, 50, 466,
  131712. /* 1280 */ 151, 152, 466, 384, 11, 11, 51, 51, 466, 110,
  131713. /* 1290 */ 110, 153, 52, 52, 411, 466, 38, 38, 466, 191,
  131714. /* 1300 */ 53, 53, 466, 54, 54, 466, 400, 466, 330, 39,
  131715. /* 1310 */ 39, 466, 1164, 466, 25, 466, 56, 56, 466, 131,
  131716. /* 1320 */ 131, 72, 466, 132, 132, 159, 133, 133, 61, 61,
  131717. /* 1330 */ 1226, 195, 40, 40, 111, 111, 58, 58, 406, 112,
  131718. /* 1340 */ 112, 466, 277, 113, 113, 466, 226, 466, 1246, 466,
  131719. /* 1350 */ 197, 466, 164, 466, 409, 466, 198, 466, 199, 466,
  131720. /* 1360 */ 335, 281, 109, 109, 466, 1030, 130, 130, 129, 129,
  131721. /* 1370 */ 117, 117, 116, 116, 114, 114, 115, 115, 60, 60,
  131722. /* 1380 */ 62, 62, 466, 359, 466, 59, 59, 424, 1082, 1081,
  131723. /* 1390 */ 1080, 724, 1073, 1054, 336, 293, 1053, 1052, 1315, 431,
  131724. /* 1400 */ 361, 76, 248, 31, 31, 35, 35, 1072, 249, 440,
  131725. /* 1410 */ 302, 434, 213, 1122, 6, 311, 1212, 107, 83, 251,
  131726. /* 1420 */ 78, 1123, 445, 220, 443, 1036, 304, 23, 1121, 469,
  131727. /* 1430 */ 965, 221, 223, 1104, 314, 224, 344, 317, 315, 316,
  131728. /* 1440 */ 470, 306, 1025, 1120, 308, 1262, 1020, 134, 120, 246,
  131729. /* 1450 */ 682, 370, 171, 255, 1263, 135, 184, 1261, 1260, 374,
  131730. /* 1460 */ 118, 906, 904, 827, 1050, 146, 136, 137, 148, 1049,
  131731. /* 1470 */ 63, 1047, 756, 190, 269, 920, 154, 156, 68, 69,
  131732. /* 1480 */ 70, 71, 139, 923, 192, 193, 144, 919, 345, 128,
  131733. /* 1490 */ 14, 194, 276, 211, 1000, 405, 196, 161, 912, 160,
  131734. /* 1500 */ 26, 697, 410, 295, 200, 289, 414, 162, 419, 73,
  131735. /* 1510 */ 15, 16, 141, 74, 28, 247, 846, 845, 735, 874,
  131736. /* 1520 */ 954, 75, 430, 955, 29, 433, 179, 229, 231, 800,
  131737. /* 1530 */ 165, 795, 87, 210, 889, 79, 875, 17, 873, 877,
  131738. /* 1540 */ 929, 18, 928, 216, 215, 878, 20, 30, 462, 844,
  131739. /* 1550 */ 707, 92, 766, 770, 7, 322, 217, 218, 319, 1308,
  131740. /* 1560 */ 960, 1016, 1016, 1016, 1016, 1307,
  131741. };
  131742. static const YYCODETYPE yy_lookahead[] = {
  131743. /* 0 */ 152, 144, 145, 146, 147, 152, 152, 172, 152, 180,
  131744. /* 10 */ 181, 152, 223, 224, 225, 180, 152, 164, 189, 19,
  131745. /* 20 */ 223, 224, 225, 168, 169, 170, 163, 173, 174, 173,
  131746. /* 30 */ 174, 31, 173, 174, 168, 169, 170, 173, 174, 39,
  131747. /* 40 */ 243, 191, 192, 43, 44, 45, 46, 47, 48, 49,
  131748. /* 50 */ 50, 51, 52, 53, 54, 55, 56, 57, 195, 196,
  131749. /* 60 */ 22, 23, 208, 209, 208, 209, 218, 208, 209, 176,
  131750. /* 70 */ 207, 19, 208, 209, 23, 212, 213, 26, 26, 152,
  131751. /* 80 */ 46, 47, 48, 49, 84, 85, 86, 87, 88, 89,
  131752. /* 90 */ 90, 91, 92, 93, 94, 43, 44, 45, 46, 47,
  131753. /* 100 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  131754. /* 110 */ 90, 91, 92, 93, 94, 188, 223, 224, 225, 171,
  131755. /* 120 */ 68, 83, 152, 19, 84, 85, 86, 87, 88, 89,
  131756. /* 130 */ 90, 91, 92, 93, 94, 101, 84, 85, 86, 87,
  131757. /* 140 */ 88, 89, 90, 91, 92, 93, 94, 43, 44, 45,
  131758. /* 150 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  131759. /* 160 */ 56, 57, 99, 94, 194, 102, 103, 104, 109, 110,
  131760. /* 170 */ 66, 223, 224, 225, 152, 19, 113, 22, 23, 152,
  131761. /* 180 */ 24, 26, 160, 1, 2, 59, 164, 173, 84, 85,
  131762. /* 190 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 43,
  131763. /* 200 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  131764. /* 210 */ 54, 55, 56, 57, 244, 88, 89, 90, 91, 92,
  131765. /* 220 */ 93, 94, 96, 97, 98, 99, 196, 19, 102, 103,
  131766. /* 230 */ 104, 23, 88, 89, 173, 59, 163, 207, 83, 113,
  131767. /* 240 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  131768. /* 250 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  131769. /* 260 */ 52, 53, 54, 55, 56, 57, 90, 240, 195, 196,
  131770. /* 270 */ 171, 82, 96, 97, 98, 152, 132, 176, 134, 19,
  131771. /* 280 */ 207, 200, 72, 23, 93, 94, 97, 152, 173, 79,
  131772. /* 290 */ 101, 210, 84, 85, 86, 87, 88, 89, 90, 91,
  131773. /* 300 */ 92, 93, 94, 43, 44, 45, 46, 47, 48, 49,
  131774. /* 310 */ 50, 51, 52, 53, 54, 55, 56, 57, 108, 152,
  131775. /* 320 */ 152, 132, 133, 134, 223, 224, 225, 152, 186, 119,
  131776. /* 330 */ 120, 19, 197, 234, 31, 23, 26, 152, 239, 59,
  131777. /* 340 */ 173, 174, 39, 220, 84, 85, 86, 87, 88, 89,
  131778. /* 350 */ 90, 91, 92, 93, 94, 43, 44, 45, 46, 47,
  131779. /* 360 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  131780. /* 370 */ 152, 22, 152, 16, 152, 208, 96, 97, 98, 194,
  131781. /* 380 */ 22, 23, 11, 19, 26, 79, 72, 23, 0, 1,
  131782. /* 390 */ 2, 173, 174, 173, 174, 220, 84, 85, 86, 87,
  131783. /* 400 */ 88, 89, 90, 91, 92, 93, 94, 43, 44, 45,
  131784. /* 410 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  131785. /* 420 */ 56, 57, 108, 109, 110, 119, 120, 152, 208, 119,
  131786. /* 430 */ 120, 137, 75, 139, 77, 19, 152, 88, 89, 23,
  131787. /* 440 */ 115, 83, 117, 118, 163, 227, 163, 152, 84, 85,
  131788. /* 450 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 43,
  131789. /* 460 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  131790. /* 470 */ 54, 55, 56, 57, 195, 196, 195, 196, 195, 196,
  131791. /* 480 */ 109, 110, 195, 196, 22, 23, 207, 19, 207, 152,
  131792. /* 490 */ 207, 108, 109, 110, 207, 163, 22, 140, 24, 59,
  131793. /* 500 */ 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  131794. /* 510 */ 94, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  131795. /* 520 */ 52, 53, 54, 55, 56, 57, 152, 195, 196, 152,
  131796. /* 530 */ 16, 7, 8, 9, 197, 240, 96, 97, 98, 207,
  131797. /* 540 */ 249, 250, 19, 152, 22, 83, 26, 173, 174, 152,
  131798. /* 550 */ 173, 174, 84, 85, 86, 87, 88, 89, 90, 91,
  131799. /* 560 */ 92, 93, 94, 59, 124, 152, 43, 44, 45, 46,
  131800. /* 570 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  131801. /* 580 */ 57, 59, 169, 170, 157, 194, 82, 191, 192, 75,
  131802. /* 590 */ 152, 77, 108, 109, 110, 26, 152, 19, 152, 152,
  131803. /* 600 */ 96, 97, 24, 152, 152, 101, 138, 84, 85, 86,
  131804. /* 610 */ 87, 88, 89, 90, 91, 92, 93, 94, 96, 97,
  131805. /* 620 */ 98, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  131806. /* 630 */ 52, 53, 54, 55, 56, 57, 132, 133, 134, 188,
  131807. /* 640 */ 194, 197, 152, 123, 197, 232, 194, 152, 182, 19,
  131808. /* 650 */ 119, 120, 152, 152, 152, 152, 218, 230, 152, 163,
  131809. /* 660 */ 233, 138, 84, 85, 86, 87, 88, 89, 90, 91,
  131810. /* 670 */ 92, 93, 94, 43, 44, 45, 46, 47, 48, 49,
  131811. /* 680 */ 50, 51, 52, 53, 54, 55, 56, 57, 152, 152,
  131812. /* 690 */ 23, 195, 196, 26, 194, 194, 194, 146, 147, 130,
  131813. /* 700 */ 194, 19, 46, 207, 59, 29, 166, 167, 218, 33,
  131814. /* 710 */ 173, 174, 26, 218, 84, 85, 86, 87, 88, 89,
  131815. /* 720 */ 90, 91, 92, 93, 94, 43, 44, 45, 46, 47,
  131816. /* 730 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  131817. /* 740 */ 64, 171, 97, 240, 116, 166, 167, 212, 213, 121,
  131818. /* 750 */ 23, 152, 19, 26, 218, 247, 248, 23, 23, 152,
  131819. /* 760 */ 26, 26, 22, 107, 163, 98, 84, 85, 86, 87,
  131820. /* 770 */ 88, 89, 90, 91, 92, 93, 94, 44, 45, 46,
  131821. /* 780 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  131822. /* 790 */ 57, 124, 106, 53, 100, 101, 195, 196, 152, 152,
  131823. /* 800 */ 23, 23, 19, 26, 26, 19, 152, 23, 207, 239,
  131824. /* 810 */ 26, 23, 152, 163, 26, 169, 170, 84, 85, 86,
  131825. /* 820 */ 87, 88, 89, 90, 91, 92, 93, 94, 45, 46,
  131826. /* 830 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  131827. /* 840 */ 57, 19, 20, 101, 22, 195, 196, 22, 19, 24,
  131828. /* 850 */ 163, 19, 7, 8, 112, 59, 23, 207, 36, 26,
  131829. /* 860 */ 23, 152, 59, 26, 21, 59, 152, 84, 85, 86,
  131830. /* 870 */ 87, 88, 89, 90, 91, 92, 93, 94, 232, 221,
  131831. /* 880 */ 94, 59, 195, 196, 59, 99, 100, 101, 102, 103,
  131832. /* 890 */ 104, 105, 70, 97, 207, 59, 19, 20, 112, 22,
  131833. /* 900 */ 97, 79, 152, 97, 82, 152, 152, 71, 221, 90,
  131834. /* 910 */ 88, 89, 23, 36, 12, 26, 163, 95, 96, 97,
  131835. /* 920 */ 98, 78, 97, 101, 152, 96, 173, 174, 96, 27,
  131836. /* 930 */ 182, 22, 96, 97, 98, 116, 59, 148, 149, 152,
  131837. /* 940 */ 121, 119, 120, 154, 42, 156, 103, 70, 195, 196,
  131838. /* 950 */ 22, 59, 163, 152, 132, 133, 134, 135, 136, 82,
  131839. /* 960 */ 207, 208, 209, 71, 62, 88, 89, 90, 59, 152,
  131840. /* 970 */ 152, 12, 95, 96, 97, 98, 19, 20, 101, 22,
  131841. /* 980 */ 22, 182, 152, 140, 195, 196, 27, 59, 96, 97,
  131842. /* 990 */ 98, 59, 132, 36, 134, 22, 207, 19, 20, 24,
  131843. /* 1000 */ 22, 42, 152, 173, 174, 96, 97, 98, 219, 132,
  131844. /* 1010 */ 133, 134, 135, 136, 36, 152, 59, 187, 132, 152,
  131845. /* 1020 */ 134, 62, 152, 152, 96, 97, 98, 70, 96, 97,
  131846. /* 1030 */ 98, 72, 59, 152, 59, 246, 26, 59, 214, 82,
  131847. /* 1040 */ 152, 192, 152, 173, 174, 88, 89, 79, 70, 152,
  131848. /* 1050 */ 152, 19, 95, 96, 97, 98, 124, 187, 101, 23,
  131849. /* 1060 */ 82, 164, 26, 173, 174, 152, 88, 89, 100, 96,
  131850. /* 1070 */ 97, 98, 97, 95, 96, 97, 98, 187, 46, 101,
  131851. /* 1080 */ 122, 184, 152, 186, 211, 152, 152, 119, 120, 132,
  131852. /* 1090 */ 133, 134, 135, 136, 152, 5, 22, 152, 152, 35,
  131853. /* 1100 */ 10, 11, 12, 13, 14, 152, 152, 17, 98, 235,
  131854. /* 1110 */ 132, 133, 134, 135, 136, 54, 55, 56, 57, 58,
  131855. /* 1120 */ 30, 152, 32, 152, 152, 198, 173, 174, 152, 65,
  131856. /* 1130 */ 40, 152, 152, 59, 124, 152, 236, 73, 199, 107,
  131857. /* 1140 */ 187, 171, 173, 174, 112, 84, 85, 86, 87, 88,
  131858. /* 1150 */ 89, 90, 91, 92, 93, 94, 173, 174, 152, 69,
  131859. /* 1160 */ 152, 211, 54, 55, 56, 57, 76, 152, 150, 79,
  131860. /* 1170 */ 80, 97, 211, 211, 211, 111, 59, 241, 241, 173,
  131861. /* 1180 */ 174, 173, 174, 202, 202, 185, 177, 176, 173, 174,
  131862. /* 1190 */ 176, 201, 84, 85, 86, 87, 88, 89, 90, 91,
  131863. /* 1200 */ 92, 93, 94, 215, 114, 88, 89, 152, 215, 119,
  131864. /* 1210 */ 120, 152, 181, 96, 97, 98, 176, 100, 215, 152,
  131865. /* 1220 */ 229, 152, 163, 152, 107, 199, 109, 155, 173, 174,
  131866. /* 1230 */ 245, 141, 173, 174, 60, 159, 152, 122, 159, 242,
  131867. /* 1240 */ 173, 174, 173, 174, 173, 174, 38, 242, 152, 132,
  131868. /* 1250 */ 159, 134, 152, 22, 195, 196, 152, 173, 174, 222,
  131869. /* 1260 */ 43, 130, 202, 152, 18, 152, 207, 208, 152, 173,
  131870. /* 1270 */ 174, 152, 190, 173, 174, 152, 193, 173, 174, 152,
  131871. /* 1280 */ 193, 193, 152, 159, 173, 174, 173, 174, 152, 173,
  131872. /* 1290 */ 174, 193, 173, 174, 18, 152, 173, 174, 152, 158,
  131873. /* 1300 */ 173, 174, 152, 173, 174, 152, 159, 152, 202, 173,
  131874. /* 1310 */ 174, 152, 190, 152, 222, 152, 173, 174, 152, 173,
  131875. /* 1320 */ 174, 137, 152, 173, 174, 190, 173, 174, 173, 174,
  131876. /* 1330 */ 202, 158, 173, 174, 173, 174, 173, 174, 61, 173,
  131877. /* 1340 */ 174, 152, 237, 173, 174, 152, 159, 152, 238, 152,
  131878. /* 1350 */ 158, 152, 22, 152, 178, 152, 158, 152, 158, 152,
  131879. /* 1360 */ 178, 159, 173, 174, 152, 159, 173, 174, 173, 174,
  131880. /* 1370 */ 173, 174, 173, 174, 173, 174, 173, 174, 173, 174,
  131881. /* 1380 */ 173, 174, 152, 63, 152, 173, 174, 107, 175, 175,
  131882. /* 1390 */ 175, 106, 183, 175, 178, 175, 177, 175, 175, 178,
  131883. /* 1400 */ 94, 107, 231, 173, 174, 173, 174, 183, 231, 125,
  131884. /* 1410 */ 216, 178, 159, 217, 22, 159, 226, 129, 137, 228,
  131885. /* 1420 */ 128, 217, 126, 25, 127, 162, 216, 26, 217, 161,
  131886. /* 1430 */ 13, 153, 153, 206, 205, 6, 251, 202, 204, 203,
  131887. /* 1440 */ 151, 216, 151, 217, 216, 171, 151, 165, 179, 179,
  131888. /* 1450 */ 4, 3, 22, 142, 171, 165, 15, 171, 171, 81,
  131889. /* 1460 */ 16, 23, 23, 120, 171, 131, 165, 111, 123, 171,
  131890. /* 1470 */ 171, 171, 20, 125, 16, 1, 123, 131, 53, 53,
  131891. /* 1480 */ 53, 53, 111, 96, 34, 122, 248, 1, 251, 5,
  131892. /* 1490 */ 22, 107, 140, 26, 74, 41, 122, 107, 67, 67,
  131893. /* 1500 */ 24, 20, 19, 112, 105, 23, 66, 22, 66, 22,
  131894. /* 1510 */ 22, 22, 37, 22, 22, 66, 23, 23, 28, 23,
  131895. /* 1520 */ 23, 26, 24, 23, 22, 24, 122, 23, 23, 96,
  131896. /* 1530 */ 22, 124, 26, 34, 23, 26, 23, 34, 23, 23,
  131897. /* 1540 */ 23, 34, 23, 22, 26, 11, 22, 22, 26, 23,
  131898. /* 1550 */ 23, 22, 116, 23, 22, 15, 122, 122, 23, 122,
  131899. /* 1560 */ 1, 252, 252, 252, 252, 122, 252, 252, 252, 252,
  131900. /* 1570 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131901. /* 1580 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131902. /* 1590 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131903. /* 1600 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131904. /* 1610 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131905. /* 1620 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131906. /* 1630 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131907. /* 1640 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131908. /* 1650 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131909. /* 1660 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131910. /* 1670 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131911. /* 1680 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131912. /* 1690 */ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131913. /* 1700 */ 252, 252, 252, 252, 252, 252, 252, 252, 252,
  131914. };
  131915. #define YY_SHIFT_COUNT (471)
  131916. #define YY_SHIFT_MIN (0)
  131917. #define YY_SHIFT_MAX (1559)
  131918. static const unsigned short int yy_shift_ofst[] = {
  131919. /* 0 */ 182, 1090, 822, 822, 306, 957, 957, 957, 957, 210,
  131920. /* 10 */ 0, 0, 104, 630, 957, 957, 957, 957, 957, 957,
  131921. /* 20 */ 957, 1117, 1117, 126, 968, 306, 306, 306, 306, 306,
  131922. /* 30 */ 306, 52, 156, 208, 260, 312, 364, 416, 468, 523,
  131923. /* 40 */ 578, 630, 630, 630, 630, 630, 630, 630, 630, 630,
  131924. /* 50 */ 630, 630, 630, 630, 630, 630, 630, 630, 682, 630,
  131925. /* 60 */ 733, 783, 783, 877, 957, 957, 957, 957, 957, 957,
  131926. /* 70 */ 957, 957, 957, 957, 957, 957, 957, 957, 957, 957,
  131927. /* 80 */ 957, 957, 957, 957, 957, 957, 957, 957, 957, 957,
  131928. /* 90 */ 957, 957, 957, 957, 957, 978, 957, 957, 957, 957,
  131929. /* 100 */ 957, 957, 957, 957, 957, 957, 957, 957, 957, 1061,
  131930. /* 110 */ 1108, 1108, 1108, 1108, 1108, 40, 127, 20, 280, 843,
  131931. /* 120 */ 1032, 144, 144, 280, 310, 310, 310, 310, 59, 191,
  131932. /* 130 */ 69, 1566, 1566, 1566, 786, 786, 786, 522, 836, 522,
  131933. /* 140 */ 959, 959, 892, 155, 358, 280, 280, 280, 280, 280,
  131934. /* 150 */ 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,
  131935. /* 160 */ 280, 280, 280, 280, 280, 280, 371, 388, 645, 645,
  131936. /* 170 */ 531, 1566, 1566, 1566, 504, 189, 189, 909, 63, 176,
  131937. /* 180 */ 928, 440, 932, 973, 280, 280, 280, 280, 280, 314,
  131938. /* 190 */ 280, 280, 280, 280, 280, 280, 280, 280, 280, 280,
  131939. /* 200 */ 280, 280, 1064, 1064, 1064, 280, 280, 280, 280, 667,
  131940. /* 210 */ 280, 280, 280, 825, 280, 280, 902, 280, 280, 280,
  131941. /* 220 */ 280, 280, 280, 280, 280, 383, 676, 325, 975, 975,
  131942. /* 230 */ 975, 975, 1010, 325, 325, 819, 349, 524, 569, 829,
  131943. /* 240 */ 829, 832, 569, 832, 686, 51, 656, 303, 303, 303,
  131944. /* 250 */ 829, 294, 520, 628, 474, 1174, 1115, 1115, 1208, 1208,
  131945. /* 260 */ 1115, 1231, 1217, 1131, 1246, 1246, 1246, 1246, 1115, 1276,
  131946. /* 270 */ 1131, 1231, 1217, 1217, 1131, 1115, 1276, 1184, 1277, 1115,
  131947. /* 280 */ 1276, 1330, 1115, 1276, 1115, 1276, 1330, 1280, 1280, 1280,
  131948. /* 290 */ 1320, 1330, 1280, 1285, 1280, 1320, 1280, 1280, 1330, 1306,
  131949. /* 300 */ 1306, 1330, 1284, 1294, 1284, 1294, 1284, 1294, 1284, 1294,
  131950. /* 310 */ 1115, 1392, 1115, 1281, 1288, 1296, 1292, 1297, 1131, 1398,
  131951. /* 320 */ 1401, 1417, 1417, 1429, 1429, 1429, 1566, 1566, 1566, 1566,
  131952. /* 330 */ 1566, 1566, 1566, 1566, 1566, 1566, 1566, 1566, 1566, 1566,
  131953. /* 340 */ 1566, 1566, 34, 357, 38, 462, 514, 484, 1074, 727,
  131954. /* 350 */ 740, 734, 735, 777, 778, 784, 788, 803, 694, 845,
  131955. /* 360 */ 742, 796, 833, 837, 889, 860, 886, 1036, 806, 958,
  131956. /* 370 */ 1446, 1448, 1430, 1311, 1441, 1378, 1444, 1438, 1439, 1343,
  131957. /* 380 */ 1334, 1356, 1345, 1452, 1348, 1458, 1474, 1353, 1346, 1425,
  131958. /* 390 */ 1426, 1427, 1428, 1371, 1387, 1450, 1363, 1486, 1484, 1468,
  131959. /* 400 */ 1384, 1352, 1431, 1467, 1432, 1420, 1454, 1374, 1390, 1476,
  131960. /* 410 */ 1481, 1483, 1391, 1399, 1485, 1440, 1487, 1488, 1482, 1489,
  131961. /* 420 */ 1442, 1490, 1491, 1449, 1475, 1493, 1494, 1496, 1495, 1497,
  131962. /* 430 */ 1492, 1498, 1500, 1502, 1501, 1404, 1504, 1505, 1433, 1499,
  131963. /* 440 */ 1508, 1407, 1506, 1503, 1509, 1507, 1511, 1513, 1515, 1506,
  131964. /* 450 */ 1516, 1517, 1518, 1519, 1521, 1534, 1524, 1525, 1526, 1527,
  131965. /* 460 */ 1529, 1530, 1532, 1522, 1436, 1434, 1435, 1437, 1443, 1535,
  131966. /* 470 */ 1540, 1559,
  131967. };
  131968. #define YY_REDUCE_COUNT (341)
  131969. #define YY_REDUCE_MIN (-211)
  131970. #define YY_REDUCE_MAX (1301)
  131971. static const short yy_reduce_ofst[] = {
  131972. /* 0 */ -143, 789, 753, 1059, -137, -146, -144, -141, -136, 687,
  131973. /* 10 */ -107, 101, -203, -52, 830, 870, 890, 167, 953, 218,
  131974. /* 20 */ 220, 413, 646, 897, 73, 281, 283, 332, 496, 601,
  131975. /* 30 */ 650, -211, -211, -211, -211, -211, -211, -211, -211, -211,
  131976. /* 40 */ -211, -211, -211, -211, -211, -211, -211, -211, -211, -211,
  131977. /* 50 */ -211, -211, -211, -211, -211, -211, -211, -211, -211, -211,
  131978. /* 60 */ -211, -211, -211, 374, 377, 537, 969, 983, 1006, 1008,
  131979. /* 70 */ 1015, 1055, 1067, 1069, 1071, 1084, 1096, 1100, 1104, 1111,
  131980. /* 80 */ 1113, 1116, 1119, 1123, 1127, 1130, 1136, 1143, 1146, 1150,
  131981. /* 90 */ 1153, 1155, 1159, 1161, 1163, 1166, 1170, 1189, 1193, 1195,
  131982. /* 100 */ 1197, 1199, 1201, 1203, 1205, 1207, 1212, 1230, 1232, -211,
  131983. /* 110 */ -211, -211, -211, -211, -211, -211, -211, -211, -30, 427,
  131984. /* 120 */ -171, -145, -134, 22, 279, 287, 279, 287, 99, -211,
  131985. /* 130 */ -211, -211, -211, -211, -165, -165, -165, 123, 135, 175,
  131986. /* 140 */ -150, 396, 337, 291, 291, -147, 185, 391, 446, 444,
  131987. /* 150 */ 452, 500, 501, 502, 27, -152, 295, 438, 490, 503,
  131988. /* 160 */ 495, 506, -73, 447, 451, 536, 570, 551, 540, 579,
  131989. /* 170 */ 30, 508, 535, 81, 14, 61, 115, 168, 142, 222,
  131990. /* 180 */ 275, 284, 397, 599, 607, 647, 654, 660, 709, 658,
  131991. /* 190 */ 714, 750, 754, 772, 787, 801, 817, 818, 850, 863,
  131992. /* 200 */ 867, 871, 466, 748, 799, 881, 888, 898, 913, 824,
  131993. /* 210 */ 930, 933, 934, 873, 942, 945, 849, 946, 222, 954,
  131994. /* 220 */ 971, 972, 976, 979, 980, 900, 874, 927, 950, 961,
  131995. /* 230 */ 962, 963, 824, 927, 927, 939, 970, 1018, 981, 988,
  131996. /* 240 */ 993, 936, 982, 937, 1009, 1000, 1031, 1011, 1014, 1040,
  131997. /* 250 */ 1003, 991, 990, 1026, 1072, 985, 1076, 1079, 997, 1005,
  131998. /* 260 */ 1091, 1037, 1082, 1060, 1083, 1087, 1088, 1098, 1124, 1141,
  131999. /* 270 */ 1106, 1092, 1122, 1135, 1128, 1147, 1173, 1110, 1105, 1187,
  132000. /* 280 */ 1192, 1176, 1202, 1198, 1206, 1200, 1182, 1213, 1214, 1215,
  132001. /* 290 */ 1209, 1216, 1218, 1219, 1220, 1224, 1222, 1223, 1221, 1171,
  132002. /* 300 */ 1177, 1233, 1196, 1194, 1204, 1210, 1211, 1225, 1226, 1228,
  132003. /* 310 */ 1253, 1190, 1256, 1191, 1227, 1229, 1234, 1236, 1235, 1263,
  132004. /* 320 */ 1268, 1278, 1279, 1289, 1291, 1295, 1185, 1237, 1238, 1282,
  132005. /* 330 */ 1274, 1283, 1286, 1287, 1290, 1269, 1270, 1293, 1298, 1299,
  132006. /* 340 */ 1300, 1301,
  132007. };
  132008. static const YYACTIONTYPE yy_default[] = {
  132009. /* 0 */ 1297, 1349, 1221, 1014, 1119, 1221, 1221, 1221, 1221, 1014,
  132010. /* 10 */ 1145, 1145, 1272, 1045, 1014, 1014, 1014, 1014, 1014, 1220,
  132011. /* 20 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132012. /* 30 */ 1014, 1151, 1014, 1014, 1014, 1014, 1222, 1223, 1014, 1014,
  132013. /* 40 */ 1014, 1271, 1273, 1161, 1160, 1159, 1158, 1254, 1132, 1156,
  132014. /* 50 */ 1149, 1153, 1216, 1217, 1215, 1219, 1222, 1223, 1014, 1152,
  132015. /* 60 */ 1186, 1200, 1185, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132016. /* 70 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132017. /* 80 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132018. /* 90 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132019. /* 100 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1194,
  132020. /* 110 */ 1199, 1206, 1198, 1195, 1188, 1187, 1189, 1190, 1014, 1035,
  132021. /* 120 */ 1084, 1014, 1014, 1014, 1289, 1288, 1014, 1014, 1045, 1191,
  132022. /* 130 */ 1192, 1203, 1202, 1201, 1279, 1305, 1304, 1014, 1014, 1014,
  132023. /* 140 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132024. /* 150 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132025. /* 160 */ 1014, 1014, 1014, 1014, 1014, 1014, 1045, 1297, 1041, 1041,
  132026. /* 170 */ 1014, 1284, 1119, 1110, 1014, 1014, 1014, 1014, 1014, 1014,
  132027. /* 180 */ 1014, 1014, 1014, 1014, 1014, 1276, 1274, 1014, 1236, 1014,
  132028. /* 190 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132029. /* 200 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132030. /* 210 */ 1014, 1014, 1014, 1115, 1014, 1014, 1014, 1014, 1014, 1014,
  132031. /* 220 */ 1014, 1014, 1014, 1014, 1299, 1014, 1249, 1098, 1115, 1115,
  132032. /* 230 */ 1115, 1115, 1117, 1099, 1097, 1109, 1045, 1021, 1155, 1134,
  132033. /* 240 */ 1134, 1338, 1155, 1338, 1059, 1319, 1056, 1145, 1145, 1145,
  132034. /* 250 */ 1134, 1218, 1116, 1109, 1014, 1341, 1124, 1124, 1340, 1340,
  132035. /* 260 */ 1124, 1166, 1087, 1155, 1093, 1093, 1093, 1093, 1124, 1032,
  132036. /* 270 */ 1155, 1166, 1087, 1087, 1155, 1124, 1032, 1253, 1335, 1124,
  132037. /* 280 */ 1032, 1229, 1124, 1032, 1124, 1032, 1229, 1085, 1085, 1085,
  132038. /* 290 */ 1074, 1229, 1085, 1059, 1085, 1074, 1085, 1085, 1229, 1233,
  132039. /* 300 */ 1233, 1229, 1138, 1133, 1138, 1133, 1138, 1133, 1138, 1133,
  132040. /* 310 */ 1124, 1224, 1124, 1014, 1150, 1139, 1148, 1146, 1155, 1038,
  132041. /* 320 */ 1077, 1302, 1302, 1298, 1298, 1298, 1346, 1346, 1284, 1314,
  132042. /* 330 */ 1045, 1045, 1045, 1045, 1314, 1061, 1061, 1045, 1045, 1045,
  132043. /* 340 */ 1045, 1314, 1014, 1014, 1014, 1014, 1014, 1014, 1309, 1014,
  132044. /* 350 */ 1238, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132045. /* 360 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1171,
  132046. /* 370 */ 1014, 1017, 1281, 1014, 1014, 1280, 1014, 1014, 1014, 1014,
  132047. /* 380 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132048. /* 390 */ 1014, 1014, 1014, 1014, 1014, 1014, 1337, 1014, 1014, 1014,
  132049. /* 400 */ 1014, 1014, 1014, 1252, 1251, 1014, 1014, 1126, 1014, 1014,
  132050. /* 410 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132051. /* 420 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132052. /* 430 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132053. /* 440 */ 1014, 1014, 1147, 1014, 1140, 1014, 1014, 1014, 1014, 1328,
  132054. /* 450 */ 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014, 1014,
  132055. /* 460 */ 1014, 1014, 1014, 1323, 1101, 1173, 1014, 1172, 1176, 1014,
  132056. /* 470 */ 1026, 1014,
  132057. };
  132058. /********** End of lemon-generated parsing tables *****************************/
  132059. /* The next table maps tokens (terminal symbols) into fallback tokens.
  132060. ** If a construct like the following:
  132061. **
  132062. ** %fallback ID X Y Z.
  132063. **
  132064. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  132065. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  132066. ** but it does not parse, the type of the token is changed to ID and
  132067. ** the parse is retried before an error is thrown.
  132068. **
  132069. ** This feature can be used, for example, to cause some keywords in a language
  132070. ** to revert to identifiers if they keyword does not apply in the context where
  132071. ** it appears.
  132072. */
  132073. #ifdef YYFALLBACK
  132074. static const YYCODETYPE yyFallback[] = {
  132075. 0, /* $ => nothing */
  132076. 0, /* SEMI => nothing */
  132077. 59, /* EXPLAIN => ID */
  132078. 59, /* QUERY => ID */
  132079. 59, /* PLAN => ID */
  132080. 59, /* BEGIN => ID */
  132081. 0, /* TRANSACTION => nothing */
  132082. 59, /* DEFERRED => ID */
  132083. 59, /* IMMEDIATE => ID */
  132084. 59, /* EXCLUSIVE => ID */
  132085. 0, /* COMMIT => nothing */
  132086. 59, /* END => ID */
  132087. 59, /* ROLLBACK => ID */
  132088. 59, /* SAVEPOINT => ID */
  132089. 59, /* RELEASE => ID */
  132090. 0, /* TO => nothing */
  132091. 0, /* TABLE => nothing */
  132092. 0, /* CREATE => nothing */
  132093. 59, /* IF => ID */
  132094. 0, /* NOT => nothing */
  132095. 0, /* EXISTS => nothing */
  132096. 59, /* TEMP => ID */
  132097. 0, /* LP => nothing */
  132098. 0, /* RP => nothing */
  132099. 0, /* AS => nothing */
  132100. 59, /* WITHOUT => ID */
  132101. 0, /* COMMA => nothing */
  132102. 59, /* ABORT => ID */
  132103. 59, /* ACTION => ID */
  132104. 59, /* AFTER => ID */
  132105. 59, /* ANALYZE => ID */
  132106. 59, /* ASC => ID */
  132107. 59, /* ATTACH => ID */
  132108. 59, /* BEFORE => ID */
  132109. 59, /* BY => ID */
  132110. 59, /* CASCADE => ID */
  132111. 59, /* CAST => ID */
  132112. 59, /* CONFLICT => ID */
  132113. 59, /* DATABASE => ID */
  132114. 59, /* DESC => ID */
  132115. 59, /* DETACH => ID */
  132116. 59, /* EACH => ID */
  132117. 59, /* FAIL => ID */
  132118. 0, /* OR => nothing */
  132119. 0, /* AND => nothing */
  132120. 0, /* IS => nothing */
  132121. 59, /* MATCH => ID */
  132122. 59, /* LIKE_KW => ID */
  132123. 0, /* BETWEEN => nothing */
  132124. 0, /* IN => nothing */
  132125. 0, /* ISNULL => nothing */
  132126. 0, /* NOTNULL => nothing */
  132127. 0, /* NE => nothing */
  132128. 0, /* EQ => nothing */
  132129. 0, /* GT => nothing */
  132130. 0, /* LE => nothing */
  132131. 0, /* LT => nothing */
  132132. 0, /* GE => nothing */
  132133. 0, /* ESCAPE => nothing */
  132134. 0, /* ID => nothing */
  132135. 59, /* COLUMNKW => ID */
  132136. 59, /* FOR => ID */
  132137. 59, /* IGNORE => ID */
  132138. 59, /* INITIALLY => ID */
  132139. 59, /* INSTEAD => ID */
  132140. 59, /* NO => ID */
  132141. 59, /* KEY => ID */
  132142. 59, /* OF => ID */
  132143. 59, /* OFFSET => ID */
  132144. 59, /* PRAGMA => ID */
  132145. 59, /* RAISE => ID */
  132146. 59, /* RECURSIVE => ID */
  132147. 59, /* REPLACE => ID */
  132148. 59, /* RESTRICT => ID */
  132149. 59, /* ROW => ID */
  132150. 59, /* TRIGGER => ID */
  132151. 59, /* VACUUM => ID */
  132152. 59, /* VIEW => ID */
  132153. 59, /* VIRTUAL => ID */
  132154. 59, /* WITH => ID */
  132155. 59, /* REINDEX => ID */
  132156. 59, /* RENAME => ID */
  132157. 59, /* CTIME_KW => ID */
  132158. };
  132159. #endif /* YYFALLBACK */
  132160. /* The following structure represents a single element of the
  132161. ** parser's stack. Information stored includes:
  132162. **
  132163. ** + The state number for the parser at this level of the stack.
  132164. **
  132165. ** + The value of the token stored at this level of the stack.
  132166. ** (In other words, the "major" token.)
  132167. **
  132168. ** + The semantic value stored at this level of the stack. This is
  132169. ** the information used by the action routines in the grammar.
  132170. ** It is sometimes called the "minor" token.
  132171. **
  132172. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  132173. ** actually contains the reduce action for the second half of the
  132174. ** SHIFTREDUCE.
  132175. */
  132176. struct yyStackEntry {
  132177. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  132178. YYCODETYPE major; /* The major token value. This is the code
  132179. ** number for the token at this stack level */
  132180. YYMINORTYPE minor; /* The user-supplied minor token value. This
  132181. ** is the value of the token */
  132182. };
  132183. typedef struct yyStackEntry yyStackEntry;
  132184. /* The state of the parser is completely contained in an instance of
  132185. ** the following structure */
  132186. struct yyParser {
  132187. yyStackEntry *yytos; /* Pointer to top element of the stack */
  132188. #ifdef YYTRACKMAXSTACKDEPTH
  132189. int yyhwm; /* High-water mark of the stack */
  132190. #endif
  132191. #ifndef YYNOERRORRECOVERY
  132192. int yyerrcnt; /* Shifts left before out of the error */
  132193. #endif
  132194. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  132195. #if YYSTACKDEPTH<=0
  132196. int yystksz; /* Current side of the stack */
  132197. yyStackEntry *yystack; /* The parser's stack */
  132198. yyStackEntry yystk0; /* First stack entry */
  132199. #else
  132200. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  132201. yyStackEntry *yystackEnd; /* Last entry in the stack */
  132202. #endif
  132203. };
  132204. typedef struct yyParser yyParser;
  132205. #ifndef NDEBUG
  132206. /* #include <stdio.h> */
  132207. static FILE *yyTraceFILE = 0;
  132208. static char *yyTracePrompt = 0;
  132209. #endif /* NDEBUG */
  132210. #ifndef NDEBUG
  132211. /*
  132212. ** Turn parser tracing on by giving a stream to which to write the trace
  132213. ** and a prompt to preface each trace message. Tracing is turned off
  132214. ** by making either argument NULL
  132215. **
  132216. ** Inputs:
  132217. ** <ul>
  132218. ** <li> A FILE* to which trace output should be written.
  132219. ** If NULL, then tracing is turned off.
  132220. ** <li> A prefix string written at the beginning of every
  132221. ** line of trace output. If NULL, then tracing is
  132222. ** turned off.
  132223. ** </ul>
  132224. **
  132225. ** Outputs:
  132226. ** None.
  132227. */
  132228. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  132229. yyTraceFILE = TraceFILE;
  132230. yyTracePrompt = zTracePrompt;
  132231. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  132232. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  132233. }
  132234. #endif /* NDEBUG */
  132235. #if defined(YYCOVERAGE) || !defined(NDEBUG)
  132236. /* For tracing shifts, the names of all terminals and nonterminals
  132237. ** are required. The following table supplies these names */
  132238. static const char *const yyTokenName[] = {
  132239. /* 0 */ "$",
  132240. /* 1 */ "SEMI",
  132241. /* 2 */ "EXPLAIN",
  132242. /* 3 */ "QUERY",
  132243. /* 4 */ "PLAN",
  132244. /* 5 */ "BEGIN",
  132245. /* 6 */ "TRANSACTION",
  132246. /* 7 */ "DEFERRED",
  132247. /* 8 */ "IMMEDIATE",
  132248. /* 9 */ "EXCLUSIVE",
  132249. /* 10 */ "COMMIT",
  132250. /* 11 */ "END",
  132251. /* 12 */ "ROLLBACK",
  132252. /* 13 */ "SAVEPOINT",
  132253. /* 14 */ "RELEASE",
  132254. /* 15 */ "TO",
  132255. /* 16 */ "TABLE",
  132256. /* 17 */ "CREATE",
  132257. /* 18 */ "IF",
  132258. /* 19 */ "NOT",
  132259. /* 20 */ "EXISTS",
  132260. /* 21 */ "TEMP",
  132261. /* 22 */ "LP",
  132262. /* 23 */ "RP",
  132263. /* 24 */ "AS",
  132264. /* 25 */ "WITHOUT",
  132265. /* 26 */ "COMMA",
  132266. /* 27 */ "ABORT",
  132267. /* 28 */ "ACTION",
  132268. /* 29 */ "AFTER",
  132269. /* 30 */ "ANALYZE",
  132270. /* 31 */ "ASC",
  132271. /* 32 */ "ATTACH",
  132272. /* 33 */ "BEFORE",
  132273. /* 34 */ "BY",
  132274. /* 35 */ "CASCADE",
  132275. /* 36 */ "CAST",
  132276. /* 37 */ "CONFLICT",
  132277. /* 38 */ "DATABASE",
  132278. /* 39 */ "DESC",
  132279. /* 40 */ "DETACH",
  132280. /* 41 */ "EACH",
  132281. /* 42 */ "FAIL",
  132282. /* 43 */ "OR",
  132283. /* 44 */ "AND",
  132284. /* 45 */ "IS",
  132285. /* 46 */ "MATCH",
  132286. /* 47 */ "LIKE_KW",
  132287. /* 48 */ "BETWEEN",
  132288. /* 49 */ "IN",
  132289. /* 50 */ "ISNULL",
  132290. /* 51 */ "NOTNULL",
  132291. /* 52 */ "NE",
  132292. /* 53 */ "EQ",
  132293. /* 54 */ "GT",
  132294. /* 55 */ "LE",
  132295. /* 56 */ "LT",
  132296. /* 57 */ "GE",
  132297. /* 58 */ "ESCAPE",
  132298. /* 59 */ "ID",
  132299. /* 60 */ "COLUMNKW",
  132300. /* 61 */ "FOR",
  132301. /* 62 */ "IGNORE",
  132302. /* 63 */ "INITIALLY",
  132303. /* 64 */ "INSTEAD",
  132304. /* 65 */ "NO",
  132305. /* 66 */ "KEY",
  132306. /* 67 */ "OF",
  132307. /* 68 */ "OFFSET",
  132308. /* 69 */ "PRAGMA",
  132309. /* 70 */ "RAISE",
  132310. /* 71 */ "RECURSIVE",
  132311. /* 72 */ "REPLACE",
  132312. /* 73 */ "RESTRICT",
  132313. /* 74 */ "ROW",
  132314. /* 75 */ "TRIGGER",
  132315. /* 76 */ "VACUUM",
  132316. /* 77 */ "VIEW",
  132317. /* 78 */ "VIRTUAL",
  132318. /* 79 */ "WITH",
  132319. /* 80 */ "REINDEX",
  132320. /* 81 */ "RENAME",
  132321. /* 82 */ "CTIME_KW",
  132322. /* 83 */ "ANY",
  132323. /* 84 */ "BITAND",
  132324. /* 85 */ "BITOR",
  132325. /* 86 */ "LSHIFT",
  132326. /* 87 */ "RSHIFT",
  132327. /* 88 */ "PLUS",
  132328. /* 89 */ "MINUS",
  132329. /* 90 */ "STAR",
  132330. /* 91 */ "SLASH",
  132331. /* 92 */ "REM",
  132332. /* 93 */ "CONCAT",
  132333. /* 94 */ "COLLATE",
  132334. /* 95 */ "BITNOT",
  132335. /* 96 */ "INDEXED",
  132336. /* 97 */ "STRING",
  132337. /* 98 */ "JOIN_KW",
  132338. /* 99 */ "CONSTRAINT",
  132339. /* 100 */ "DEFAULT",
  132340. /* 101 */ "NULL",
  132341. /* 102 */ "PRIMARY",
  132342. /* 103 */ "UNIQUE",
  132343. /* 104 */ "CHECK",
  132344. /* 105 */ "REFERENCES",
  132345. /* 106 */ "AUTOINCR",
  132346. /* 107 */ "ON",
  132347. /* 108 */ "INSERT",
  132348. /* 109 */ "DELETE",
  132349. /* 110 */ "UPDATE",
  132350. /* 111 */ "SET",
  132351. /* 112 */ "DEFERRABLE",
  132352. /* 113 */ "FOREIGN",
  132353. /* 114 */ "DROP",
  132354. /* 115 */ "UNION",
  132355. /* 116 */ "ALL",
  132356. /* 117 */ "EXCEPT",
  132357. /* 118 */ "INTERSECT",
  132358. /* 119 */ "SELECT",
  132359. /* 120 */ "VALUES",
  132360. /* 121 */ "DISTINCT",
  132361. /* 122 */ "DOT",
  132362. /* 123 */ "FROM",
  132363. /* 124 */ "JOIN",
  132364. /* 125 */ "USING",
  132365. /* 126 */ "ORDER",
  132366. /* 127 */ "GROUP",
  132367. /* 128 */ "HAVING",
  132368. /* 129 */ "LIMIT",
  132369. /* 130 */ "WHERE",
  132370. /* 131 */ "INTO",
  132371. /* 132 */ "FLOAT",
  132372. /* 133 */ "BLOB",
  132373. /* 134 */ "INTEGER",
  132374. /* 135 */ "VARIABLE",
  132375. /* 136 */ "CASE",
  132376. /* 137 */ "WHEN",
  132377. /* 138 */ "THEN",
  132378. /* 139 */ "ELSE",
  132379. /* 140 */ "INDEX",
  132380. /* 141 */ "ALTER",
  132381. /* 142 */ "ADD",
  132382. /* 143 */ "error",
  132383. /* 144 */ "input",
  132384. /* 145 */ "cmdlist",
  132385. /* 146 */ "ecmd",
  132386. /* 147 */ "explain",
  132387. /* 148 */ "cmdx",
  132388. /* 149 */ "cmd",
  132389. /* 150 */ "transtype",
  132390. /* 151 */ "trans_opt",
  132391. /* 152 */ "nm",
  132392. /* 153 */ "savepoint_opt",
  132393. /* 154 */ "create_table",
  132394. /* 155 */ "create_table_args",
  132395. /* 156 */ "createkw",
  132396. /* 157 */ "temp",
  132397. /* 158 */ "ifnotexists",
  132398. /* 159 */ "dbnm",
  132399. /* 160 */ "columnlist",
  132400. /* 161 */ "conslist_opt",
  132401. /* 162 */ "table_options",
  132402. /* 163 */ "select",
  132403. /* 164 */ "columnname",
  132404. /* 165 */ "carglist",
  132405. /* 166 */ "typetoken",
  132406. /* 167 */ "typename",
  132407. /* 168 */ "signed",
  132408. /* 169 */ "plus_num",
  132409. /* 170 */ "minus_num",
  132410. /* 171 */ "scanpt",
  132411. /* 172 */ "ccons",
  132412. /* 173 */ "term",
  132413. /* 174 */ "expr",
  132414. /* 175 */ "onconf",
  132415. /* 176 */ "sortorder",
  132416. /* 177 */ "autoinc",
  132417. /* 178 */ "eidlist_opt",
  132418. /* 179 */ "refargs",
  132419. /* 180 */ "defer_subclause",
  132420. /* 181 */ "refarg",
  132421. /* 182 */ "refact",
  132422. /* 183 */ "init_deferred_pred_opt",
  132423. /* 184 */ "conslist",
  132424. /* 185 */ "tconscomma",
  132425. /* 186 */ "tcons",
  132426. /* 187 */ "sortlist",
  132427. /* 188 */ "eidlist",
  132428. /* 189 */ "defer_subclause_opt",
  132429. /* 190 */ "orconf",
  132430. /* 191 */ "resolvetype",
  132431. /* 192 */ "raisetype",
  132432. /* 193 */ "ifexists",
  132433. /* 194 */ "fullname",
  132434. /* 195 */ "selectnowith",
  132435. /* 196 */ "oneselect",
  132436. /* 197 */ "wqlist",
  132437. /* 198 */ "multiselect_op",
  132438. /* 199 */ "distinct",
  132439. /* 200 */ "selcollist",
  132440. /* 201 */ "from",
  132441. /* 202 */ "where_opt",
  132442. /* 203 */ "groupby_opt",
  132443. /* 204 */ "having_opt",
  132444. /* 205 */ "orderby_opt",
  132445. /* 206 */ "limit_opt",
  132446. /* 207 */ "values",
  132447. /* 208 */ "nexprlist",
  132448. /* 209 */ "exprlist",
  132449. /* 210 */ "sclp",
  132450. /* 211 */ "as",
  132451. /* 212 */ "seltablist",
  132452. /* 213 */ "stl_prefix",
  132453. /* 214 */ "joinop",
  132454. /* 215 */ "indexed_opt",
  132455. /* 216 */ "on_opt",
  132456. /* 217 */ "using_opt",
  132457. /* 218 */ "idlist",
  132458. /* 219 */ "with",
  132459. /* 220 */ "setlist",
  132460. /* 221 */ "insert_cmd",
  132461. /* 222 */ "idlist_opt",
  132462. /* 223 */ "likeop",
  132463. /* 224 */ "between_op",
  132464. /* 225 */ "in_op",
  132465. /* 226 */ "paren_exprlist",
  132466. /* 227 */ "case_operand",
  132467. /* 228 */ "case_exprlist",
  132468. /* 229 */ "case_else",
  132469. /* 230 */ "uniqueflag",
  132470. /* 231 */ "collate",
  132471. /* 232 */ "nmnum",
  132472. /* 233 */ "trigger_decl",
  132473. /* 234 */ "trigger_cmd_list",
  132474. /* 235 */ "trigger_time",
  132475. /* 236 */ "trigger_event",
  132476. /* 237 */ "foreach_clause",
  132477. /* 238 */ "when_clause",
  132478. /* 239 */ "trigger_cmd",
  132479. /* 240 */ "trnm",
  132480. /* 241 */ "tridxby",
  132481. /* 242 */ "database_kw_opt",
  132482. /* 243 */ "key_opt",
  132483. /* 244 */ "add_column_fullname",
  132484. /* 245 */ "kwcolumn_opt",
  132485. /* 246 */ "create_vtab",
  132486. /* 247 */ "vtabarglist",
  132487. /* 248 */ "vtabarg",
  132488. /* 249 */ "vtabargtoken",
  132489. /* 250 */ "lp",
  132490. /* 251 */ "anylist",
  132491. };
  132492. #endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
  132493. #ifndef NDEBUG
  132494. /* For tracing reduce actions, the names of all rules are required.
  132495. */
  132496. static const char *const yyRuleName[] = {
  132497. /* 0 */ "explain ::= EXPLAIN",
  132498. /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
  132499. /* 2 */ "cmdx ::= cmd",
  132500. /* 3 */ "cmd ::= BEGIN transtype trans_opt",
  132501. /* 4 */ "transtype ::=",
  132502. /* 5 */ "transtype ::= DEFERRED",
  132503. /* 6 */ "transtype ::= IMMEDIATE",
  132504. /* 7 */ "transtype ::= EXCLUSIVE",
  132505. /* 8 */ "cmd ::= COMMIT|END trans_opt",
  132506. /* 9 */ "cmd ::= ROLLBACK trans_opt",
  132507. /* 10 */ "cmd ::= SAVEPOINT nm",
  132508. /* 11 */ "cmd ::= RELEASE savepoint_opt nm",
  132509. /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  132510. /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  132511. /* 14 */ "createkw ::= CREATE",
  132512. /* 15 */ "ifnotexists ::=",
  132513. /* 16 */ "ifnotexists ::= IF NOT EXISTS",
  132514. /* 17 */ "temp ::= TEMP",
  132515. /* 18 */ "temp ::=",
  132516. /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  132517. /* 20 */ "create_table_args ::= AS select",
  132518. /* 21 */ "table_options ::=",
  132519. /* 22 */ "table_options ::= WITHOUT nm",
  132520. /* 23 */ "columnname ::= nm typetoken",
  132521. /* 24 */ "typetoken ::=",
  132522. /* 25 */ "typetoken ::= typename LP signed RP",
  132523. /* 26 */ "typetoken ::= typename LP signed COMMA signed RP",
  132524. /* 27 */ "typename ::= typename ID|STRING",
  132525. /* 28 */ "scanpt ::=",
  132526. /* 29 */ "ccons ::= CONSTRAINT nm",
  132527. /* 30 */ "ccons ::= DEFAULT scanpt term scanpt",
  132528. /* 31 */ "ccons ::= DEFAULT LP expr RP",
  132529. /* 32 */ "ccons ::= DEFAULT PLUS term scanpt",
  132530. /* 33 */ "ccons ::= DEFAULT MINUS term scanpt",
  132531. /* 34 */ "ccons ::= DEFAULT scanpt ID|INDEXED",
  132532. /* 35 */ "ccons ::= NOT NULL onconf",
  132533. /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  132534. /* 37 */ "ccons ::= UNIQUE onconf",
  132535. /* 38 */ "ccons ::= CHECK LP expr RP",
  132536. /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  132537. /* 40 */ "ccons ::= defer_subclause",
  132538. /* 41 */ "ccons ::= COLLATE ID|STRING",
  132539. /* 42 */ "autoinc ::=",
  132540. /* 43 */ "autoinc ::= AUTOINCR",
  132541. /* 44 */ "refargs ::=",
  132542. /* 45 */ "refargs ::= refargs refarg",
  132543. /* 46 */ "refarg ::= MATCH nm",
  132544. /* 47 */ "refarg ::= ON INSERT refact",
  132545. /* 48 */ "refarg ::= ON DELETE refact",
  132546. /* 49 */ "refarg ::= ON UPDATE refact",
  132547. /* 50 */ "refact ::= SET NULL",
  132548. /* 51 */ "refact ::= SET DEFAULT",
  132549. /* 52 */ "refact ::= CASCADE",
  132550. /* 53 */ "refact ::= RESTRICT",
  132551. /* 54 */ "refact ::= NO ACTION",
  132552. /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  132553. /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  132554. /* 57 */ "init_deferred_pred_opt ::=",
  132555. /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  132556. /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  132557. /* 60 */ "conslist_opt ::=",
  132558. /* 61 */ "tconscomma ::= COMMA",
  132559. /* 62 */ "tcons ::= CONSTRAINT nm",
  132560. /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  132561. /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  132562. /* 65 */ "tcons ::= CHECK LP expr RP onconf",
  132563. /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  132564. /* 67 */ "defer_subclause_opt ::=",
  132565. /* 68 */ "onconf ::=",
  132566. /* 69 */ "onconf ::= ON CONFLICT resolvetype",
  132567. /* 70 */ "orconf ::=",
  132568. /* 71 */ "orconf ::= OR resolvetype",
  132569. /* 72 */ "resolvetype ::= IGNORE",
  132570. /* 73 */ "resolvetype ::= REPLACE",
  132571. /* 74 */ "cmd ::= DROP TABLE ifexists fullname",
  132572. /* 75 */ "ifexists ::= IF EXISTS",
  132573. /* 76 */ "ifexists ::=",
  132574. /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  132575. /* 78 */ "cmd ::= DROP VIEW ifexists fullname",
  132576. /* 79 */ "cmd ::= select",
  132577. /* 80 */ "select ::= WITH wqlist selectnowith",
  132578. /* 81 */ "select ::= WITH RECURSIVE wqlist selectnowith",
  132579. /* 82 */ "select ::= selectnowith",
  132580. /* 83 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  132581. /* 84 */ "multiselect_op ::= UNION",
  132582. /* 85 */ "multiselect_op ::= UNION ALL",
  132583. /* 86 */ "multiselect_op ::= EXCEPT|INTERSECT",
  132584. /* 87 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  132585. /* 88 */ "values ::= VALUES LP nexprlist RP",
  132586. /* 89 */ "values ::= values COMMA LP exprlist RP",
  132587. /* 90 */ "distinct ::= DISTINCT",
  132588. /* 91 */ "distinct ::= ALL",
  132589. /* 92 */ "distinct ::=",
  132590. /* 93 */ "sclp ::=",
  132591. /* 94 */ "selcollist ::= sclp scanpt expr scanpt as",
  132592. /* 95 */ "selcollist ::= sclp scanpt STAR",
  132593. /* 96 */ "selcollist ::= sclp scanpt nm DOT STAR",
  132594. /* 97 */ "as ::= AS nm",
  132595. /* 98 */ "as ::=",
  132596. /* 99 */ "from ::=",
  132597. /* 100 */ "from ::= FROM seltablist",
  132598. /* 101 */ "stl_prefix ::= seltablist joinop",
  132599. /* 102 */ "stl_prefix ::=",
  132600. /* 103 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  132601. /* 104 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  132602. /* 105 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  132603. /* 106 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  132604. /* 107 */ "dbnm ::=",
  132605. /* 108 */ "dbnm ::= DOT nm",
  132606. /* 109 */ "fullname ::= nm",
  132607. /* 110 */ "fullname ::= nm DOT nm",
  132608. /* 111 */ "joinop ::= COMMA|JOIN",
  132609. /* 112 */ "joinop ::= JOIN_KW JOIN",
  132610. /* 113 */ "joinop ::= JOIN_KW nm JOIN",
  132611. /* 114 */ "joinop ::= JOIN_KW nm nm JOIN",
  132612. /* 115 */ "on_opt ::= ON expr",
  132613. /* 116 */ "on_opt ::=",
  132614. /* 117 */ "indexed_opt ::=",
  132615. /* 118 */ "indexed_opt ::= INDEXED BY nm",
  132616. /* 119 */ "indexed_opt ::= NOT INDEXED",
  132617. /* 120 */ "using_opt ::= USING LP idlist RP",
  132618. /* 121 */ "using_opt ::=",
  132619. /* 122 */ "orderby_opt ::=",
  132620. /* 123 */ "orderby_opt ::= ORDER BY sortlist",
  132621. /* 124 */ "sortlist ::= sortlist COMMA expr sortorder",
  132622. /* 125 */ "sortlist ::= expr sortorder",
  132623. /* 126 */ "sortorder ::= ASC",
  132624. /* 127 */ "sortorder ::= DESC",
  132625. /* 128 */ "sortorder ::=",
  132626. /* 129 */ "groupby_opt ::=",
  132627. /* 130 */ "groupby_opt ::= GROUP BY nexprlist",
  132628. /* 131 */ "having_opt ::=",
  132629. /* 132 */ "having_opt ::= HAVING expr",
  132630. /* 133 */ "limit_opt ::=",
  132631. /* 134 */ "limit_opt ::= LIMIT expr",
  132632. /* 135 */ "limit_opt ::= LIMIT expr OFFSET expr",
  132633. /* 136 */ "limit_opt ::= LIMIT expr COMMA expr",
  132634. /* 137 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  132635. /* 138 */ "where_opt ::=",
  132636. /* 139 */ "where_opt ::= WHERE expr",
  132637. /* 140 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  132638. /* 141 */ "setlist ::= setlist COMMA nm EQ expr",
  132639. /* 142 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
  132640. /* 143 */ "setlist ::= nm EQ expr",
  132641. /* 144 */ "setlist ::= LP idlist RP EQ expr",
  132642. /* 145 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
  132643. /* 146 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
  132644. /* 147 */ "insert_cmd ::= INSERT orconf",
  132645. /* 148 */ "insert_cmd ::= REPLACE",
  132646. /* 149 */ "idlist_opt ::=",
  132647. /* 150 */ "idlist_opt ::= LP idlist RP",
  132648. /* 151 */ "idlist ::= idlist COMMA nm",
  132649. /* 152 */ "idlist ::= nm",
  132650. /* 153 */ "expr ::= LP expr RP",
  132651. /* 154 */ "expr ::= ID|INDEXED",
  132652. /* 155 */ "expr ::= JOIN_KW",
  132653. /* 156 */ "expr ::= nm DOT nm",
  132654. /* 157 */ "expr ::= nm DOT nm DOT nm",
  132655. /* 158 */ "term ::= NULL|FLOAT|BLOB",
  132656. /* 159 */ "term ::= STRING",
  132657. /* 160 */ "term ::= INTEGER",
  132658. /* 161 */ "expr ::= VARIABLE",
  132659. /* 162 */ "expr ::= expr COLLATE ID|STRING",
  132660. /* 163 */ "expr ::= CAST LP expr AS typetoken RP",
  132661. /* 164 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  132662. /* 165 */ "expr ::= ID|INDEXED LP STAR RP",
  132663. /* 166 */ "term ::= CTIME_KW",
  132664. /* 167 */ "expr ::= LP nexprlist COMMA expr RP",
  132665. /* 168 */ "expr ::= expr AND expr",
  132666. /* 169 */ "expr ::= expr OR expr",
  132667. /* 170 */ "expr ::= expr LT|GT|GE|LE expr",
  132668. /* 171 */ "expr ::= expr EQ|NE expr",
  132669. /* 172 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  132670. /* 173 */ "expr ::= expr PLUS|MINUS expr",
  132671. /* 174 */ "expr ::= expr STAR|SLASH|REM expr",
  132672. /* 175 */ "expr ::= expr CONCAT expr",
  132673. /* 176 */ "likeop ::= NOT LIKE_KW|MATCH",
  132674. /* 177 */ "expr ::= expr likeop expr",
  132675. /* 178 */ "expr ::= expr likeop expr ESCAPE expr",
  132676. /* 179 */ "expr ::= expr ISNULL|NOTNULL",
  132677. /* 180 */ "expr ::= expr NOT NULL",
  132678. /* 181 */ "expr ::= expr IS expr",
  132679. /* 182 */ "expr ::= expr IS NOT expr",
  132680. /* 183 */ "expr ::= NOT expr",
  132681. /* 184 */ "expr ::= BITNOT expr",
  132682. /* 185 */ "expr ::= MINUS expr",
  132683. /* 186 */ "expr ::= PLUS expr",
  132684. /* 187 */ "between_op ::= BETWEEN",
  132685. /* 188 */ "between_op ::= NOT BETWEEN",
  132686. /* 189 */ "expr ::= expr between_op expr AND expr",
  132687. /* 190 */ "in_op ::= IN",
  132688. /* 191 */ "in_op ::= NOT IN",
  132689. /* 192 */ "expr ::= expr in_op LP exprlist RP",
  132690. /* 193 */ "expr ::= LP select RP",
  132691. /* 194 */ "expr ::= expr in_op LP select RP",
  132692. /* 195 */ "expr ::= expr in_op nm dbnm paren_exprlist",
  132693. /* 196 */ "expr ::= EXISTS LP select RP",
  132694. /* 197 */ "expr ::= CASE case_operand case_exprlist case_else END",
  132695. /* 198 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  132696. /* 199 */ "case_exprlist ::= WHEN expr THEN expr",
  132697. /* 200 */ "case_else ::= ELSE expr",
  132698. /* 201 */ "case_else ::=",
  132699. /* 202 */ "case_operand ::= expr",
  132700. /* 203 */ "case_operand ::=",
  132701. /* 204 */ "exprlist ::=",
  132702. /* 205 */ "nexprlist ::= nexprlist COMMA expr",
  132703. /* 206 */ "nexprlist ::= expr",
  132704. /* 207 */ "paren_exprlist ::=",
  132705. /* 208 */ "paren_exprlist ::= LP exprlist RP",
  132706. /* 209 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  132707. /* 210 */ "uniqueflag ::= UNIQUE",
  132708. /* 211 */ "uniqueflag ::=",
  132709. /* 212 */ "eidlist_opt ::=",
  132710. /* 213 */ "eidlist_opt ::= LP eidlist RP",
  132711. /* 214 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  132712. /* 215 */ "eidlist ::= nm collate sortorder",
  132713. /* 216 */ "collate ::=",
  132714. /* 217 */ "collate ::= COLLATE ID|STRING",
  132715. /* 218 */ "cmd ::= DROP INDEX ifexists fullname",
  132716. /* 219 */ "cmd ::= VACUUM",
  132717. /* 220 */ "cmd ::= VACUUM nm",
  132718. /* 221 */ "cmd ::= PRAGMA nm dbnm",
  132719. /* 222 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  132720. /* 223 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  132721. /* 224 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  132722. /* 225 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  132723. /* 226 */ "plus_num ::= PLUS INTEGER|FLOAT",
  132724. /* 227 */ "minus_num ::= MINUS INTEGER|FLOAT",
  132725. /* 228 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  132726. /* 229 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  132727. /* 230 */ "trigger_time ::= BEFORE|AFTER",
  132728. /* 231 */ "trigger_time ::= INSTEAD OF",
  132729. /* 232 */ "trigger_time ::=",
  132730. /* 233 */ "trigger_event ::= DELETE|INSERT",
  132731. /* 234 */ "trigger_event ::= UPDATE",
  132732. /* 235 */ "trigger_event ::= UPDATE OF idlist",
  132733. /* 236 */ "when_clause ::=",
  132734. /* 237 */ "when_clause ::= WHEN expr",
  132735. /* 238 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  132736. /* 239 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  132737. /* 240 */ "trnm ::= nm DOT nm",
  132738. /* 241 */ "tridxby ::= INDEXED BY nm",
  132739. /* 242 */ "tridxby ::= NOT INDEXED",
  132740. /* 243 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt",
  132741. /* 244 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select scanpt",
  132742. /* 245 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
  132743. /* 246 */ "trigger_cmd ::= scanpt select scanpt",
  132744. /* 247 */ "expr ::= RAISE LP IGNORE RP",
  132745. /* 248 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  132746. /* 249 */ "raisetype ::= ROLLBACK",
  132747. /* 250 */ "raisetype ::= ABORT",
  132748. /* 251 */ "raisetype ::= FAIL",
  132749. /* 252 */ "cmd ::= DROP TRIGGER ifexists fullname",
  132750. /* 253 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  132751. /* 254 */ "cmd ::= DETACH database_kw_opt expr",
  132752. /* 255 */ "key_opt ::=",
  132753. /* 256 */ "key_opt ::= KEY expr",
  132754. /* 257 */ "cmd ::= REINDEX",
  132755. /* 258 */ "cmd ::= REINDEX nm dbnm",
  132756. /* 259 */ "cmd ::= ANALYZE",
  132757. /* 260 */ "cmd ::= ANALYZE nm dbnm",
  132758. /* 261 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  132759. /* 262 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
  132760. /* 263 */ "add_column_fullname ::= fullname",
  132761. /* 264 */ "cmd ::= create_vtab",
  132762. /* 265 */ "cmd ::= create_vtab LP vtabarglist RP",
  132763. /* 266 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  132764. /* 267 */ "vtabarg ::=",
  132765. /* 268 */ "vtabargtoken ::= ANY",
  132766. /* 269 */ "vtabargtoken ::= lp anylist RP",
  132767. /* 270 */ "lp ::= LP",
  132768. /* 271 */ "with ::= WITH wqlist",
  132769. /* 272 */ "with ::= WITH RECURSIVE wqlist",
  132770. /* 273 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  132771. /* 274 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  132772. /* 275 */ "input ::= cmdlist",
  132773. /* 276 */ "cmdlist ::= cmdlist ecmd",
  132774. /* 277 */ "cmdlist ::= ecmd",
  132775. /* 278 */ "ecmd ::= SEMI",
  132776. /* 279 */ "ecmd ::= explain cmdx SEMI",
  132777. /* 280 */ "explain ::=",
  132778. /* 281 */ "trans_opt ::=",
  132779. /* 282 */ "trans_opt ::= TRANSACTION",
  132780. /* 283 */ "trans_opt ::= TRANSACTION nm",
  132781. /* 284 */ "savepoint_opt ::= SAVEPOINT",
  132782. /* 285 */ "savepoint_opt ::=",
  132783. /* 286 */ "cmd ::= create_table create_table_args",
  132784. /* 287 */ "columnlist ::= columnlist COMMA columnname carglist",
  132785. /* 288 */ "columnlist ::= columnname carglist",
  132786. /* 289 */ "nm ::= ID|INDEXED",
  132787. /* 290 */ "nm ::= STRING",
  132788. /* 291 */ "nm ::= JOIN_KW",
  132789. /* 292 */ "typetoken ::= typename",
  132790. /* 293 */ "typename ::= ID|STRING",
  132791. /* 294 */ "signed ::= plus_num",
  132792. /* 295 */ "signed ::= minus_num",
  132793. /* 296 */ "carglist ::= carglist ccons",
  132794. /* 297 */ "carglist ::=",
  132795. /* 298 */ "ccons ::= NULL onconf",
  132796. /* 299 */ "conslist_opt ::= COMMA conslist",
  132797. /* 300 */ "conslist ::= conslist tconscomma tcons",
  132798. /* 301 */ "conslist ::= tcons",
  132799. /* 302 */ "tconscomma ::=",
  132800. /* 303 */ "defer_subclause_opt ::= defer_subclause",
  132801. /* 304 */ "resolvetype ::= raisetype",
  132802. /* 305 */ "selectnowith ::= oneselect",
  132803. /* 306 */ "oneselect ::= values",
  132804. /* 307 */ "sclp ::= selcollist COMMA",
  132805. /* 308 */ "as ::= ID|STRING",
  132806. /* 309 */ "expr ::= term",
  132807. /* 310 */ "likeop ::= LIKE_KW|MATCH",
  132808. /* 311 */ "exprlist ::= nexprlist",
  132809. /* 312 */ "nmnum ::= plus_num",
  132810. /* 313 */ "nmnum ::= nm",
  132811. /* 314 */ "nmnum ::= ON",
  132812. /* 315 */ "nmnum ::= DELETE",
  132813. /* 316 */ "nmnum ::= DEFAULT",
  132814. /* 317 */ "plus_num ::= INTEGER|FLOAT",
  132815. /* 318 */ "foreach_clause ::=",
  132816. /* 319 */ "foreach_clause ::= FOR EACH ROW",
  132817. /* 320 */ "trnm ::= nm",
  132818. /* 321 */ "tridxby ::=",
  132819. /* 322 */ "database_kw_opt ::= DATABASE",
  132820. /* 323 */ "database_kw_opt ::=",
  132821. /* 324 */ "kwcolumn_opt ::=",
  132822. /* 325 */ "kwcolumn_opt ::= COLUMNKW",
  132823. /* 326 */ "vtabarglist ::= vtabarg",
  132824. /* 327 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  132825. /* 328 */ "vtabarg ::= vtabarg vtabargtoken",
  132826. /* 329 */ "anylist ::=",
  132827. /* 330 */ "anylist ::= anylist LP anylist RP",
  132828. /* 331 */ "anylist ::= anylist ANY",
  132829. /* 332 */ "with ::=",
  132830. };
  132831. #endif /* NDEBUG */
  132832. #if YYSTACKDEPTH<=0
  132833. /*
  132834. ** Try to increase the size of the parser stack. Return the number
  132835. ** of errors. Return 0 on success.
  132836. */
  132837. static int yyGrowStack(yyParser *p){
  132838. int newSize;
  132839. int idx;
  132840. yyStackEntry *pNew;
  132841. newSize = p->yystksz*2 + 100;
  132842. idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
  132843. if( p->yystack==&p->yystk0 ){
  132844. pNew = malloc(newSize*sizeof(pNew[0]));
  132845. if( pNew ) pNew[0] = p->yystk0;
  132846. }else{
  132847. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  132848. }
  132849. if( pNew ){
  132850. p->yystack = pNew;
  132851. p->yytos = &p->yystack[idx];
  132852. #ifndef NDEBUG
  132853. if( yyTraceFILE ){
  132854. fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  132855. yyTracePrompt, p->yystksz, newSize);
  132856. }
  132857. #endif
  132858. p->yystksz = newSize;
  132859. }
  132860. return pNew==0;
  132861. }
  132862. #endif
  132863. /* Datatype of the argument to the memory allocated passed as the
  132864. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  132865. ** putting an appropriate #define in the %include section of the input
  132866. ** grammar.
  132867. */
  132868. #ifndef YYMALLOCARGTYPE
  132869. # define YYMALLOCARGTYPE size_t
  132870. #endif
  132871. /* Initialize a new parser that has already been allocated.
  132872. */
  132873. SQLITE_PRIVATE void sqlite3ParserInit(void *yypParser){
  132874. yyParser *pParser = (yyParser*)yypParser;
  132875. #ifdef YYTRACKMAXSTACKDEPTH
  132876. pParser->yyhwm = 0;
  132877. #endif
  132878. #if YYSTACKDEPTH<=0
  132879. pParser->yytos = NULL;
  132880. pParser->yystack = NULL;
  132881. pParser->yystksz = 0;
  132882. if( yyGrowStack(pParser) ){
  132883. pParser->yystack = &pParser->yystk0;
  132884. pParser->yystksz = 1;
  132885. }
  132886. #endif
  132887. #ifndef YYNOERRORRECOVERY
  132888. pParser->yyerrcnt = -1;
  132889. #endif
  132890. pParser->yytos = pParser->yystack;
  132891. pParser->yystack[0].stateno = 0;
  132892. pParser->yystack[0].major = 0;
  132893. #if YYSTACKDEPTH>0
  132894. pParser->yystackEnd = &pParser->yystack[YYSTACKDEPTH-1];
  132895. #endif
  132896. }
  132897. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  132898. /*
  132899. ** This function allocates a new parser.
  132900. ** The only argument is a pointer to a function which works like
  132901. ** malloc.
  132902. **
  132903. ** Inputs:
  132904. ** A pointer to the function used to allocate memory.
  132905. **
  132906. ** Outputs:
  132907. ** A pointer to a parser. This pointer is used in subsequent calls
  132908. ** to sqlite3Parser and sqlite3ParserFree.
  132909. */
  132910. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE)){
  132911. yyParser *pParser;
  132912. pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  132913. if( pParser ) sqlite3ParserInit(pParser);
  132914. return pParser;
  132915. }
  132916. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  132917. /* The following function deletes the "minor type" or semantic value
  132918. ** associated with a symbol. The symbol can be either a terminal
  132919. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  132920. ** a pointer to the value to be deleted. The code used to do the
  132921. ** deletions is derived from the %destructor and/or %token_destructor
  132922. ** directives of the input grammar.
  132923. */
  132924. static void yy_destructor(
  132925. yyParser *yypParser, /* The parser */
  132926. YYCODETYPE yymajor, /* Type code for object to destroy */
  132927. YYMINORTYPE *yypminor /* The object to be destroyed */
  132928. ){
  132929. sqlite3ParserARG_FETCH;
  132930. switch( yymajor ){
  132931. /* Here is inserted the actions which take place when a
  132932. ** terminal or non-terminal is destroyed. This can happen
  132933. ** when the symbol is popped from the stack during a
  132934. ** reduce or during error processing or when a parser is
  132935. ** being destroyed before it is finished parsing.
  132936. **
  132937. ** Note: during a reduce, the only symbols destroyed are those
  132938. ** which appear on the RHS of the rule, but which are *not* used
  132939. ** inside the C code.
  132940. */
  132941. /********* Begin destructor definitions ***************************************/
  132942. case 163: /* select */
  132943. case 195: /* selectnowith */
  132944. case 196: /* oneselect */
  132945. case 207: /* values */
  132946. {
  132947. sqlite3SelectDelete(pParse->db, (yypminor->yy387));
  132948. }
  132949. break;
  132950. case 173: /* term */
  132951. case 174: /* expr */
  132952. case 202: /* where_opt */
  132953. case 204: /* having_opt */
  132954. case 216: /* on_opt */
  132955. case 227: /* case_operand */
  132956. case 229: /* case_else */
  132957. case 238: /* when_clause */
  132958. case 243: /* key_opt */
  132959. {
  132960. sqlite3ExprDelete(pParse->db, (yypminor->yy314));
  132961. }
  132962. break;
  132963. case 178: /* eidlist_opt */
  132964. case 187: /* sortlist */
  132965. case 188: /* eidlist */
  132966. case 200: /* selcollist */
  132967. case 203: /* groupby_opt */
  132968. case 205: /* orderby_opt */
  132969. case 208: /* nexprlist */
  132970. case 209: /* exprlist */
  132971. case 210: /* sclp */
  132972. case 220: /* setlist */
  132973. case 226: /* paren_exprlist */
  132974. case 228: /* case_exprlist */
  132975. {
  132976. sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
  132977. }
  132978. break;
  132979. case 194: /* fullname */
  132980. case 201: /* from */
  132981. case 212: /* seltablist */
  132982. case 213: /* stl_prefix */
  132983. {
  132984. sqlite3SrcListDelete(pParse->db, (yypminor->yy259));
  132985. }
  132986. break;
  132987. case 197: /* wqlist */
  132988. {
  132989. sqlite3WithDelete(pParse->db, (yypminor->yy451));
  132990. }
  132991. break;
  132992. case 217: /* using_opt */
  132993. case 218: /* idlist */
  132994. case 222: /* idlist_opt */
  132995. {
  132996. sqlite3IdListDelete(pParse->db, (yypminor->yy384));
  132997. }
  132998. break;
  132999. case 234: /* trigger_cmd_list */
  133000. case 239: /* trigger_cmd */
  133001. {
  133002. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy203));
  133003. }
  133004. break;
  133005. case 236: /* trigger_event */
  133006. {
  133007. sqlite3IdListDelete(pParse->db, (yypminor->yy90).b);
  133008. }
  133009. break;
  133010. /********* End destructor definitions *****************************************/
  133011. default: break; /* If no destructor action specified: do nothing */
  133012. }
  133013. }
  133014. /*
  133015. ** Pop the parser's stack once.
  133016. **
  133017. ** If there is a destructor routine associated with the token which
  133018. ** is popped from the stack, then call it.
  133019. */
  133020. static void yy_pop_parser_stack(yyParser *pParser){
  133021. yyStackEntry *yytos;
  133022. assert( pParser->yytos!=0 );
  133023. assert( pParser->yytos > pParser->yystack );
  133024. yytos = pParser->yytos--;
  133025. #ifndef NDEBUG
  133026. if( yyTraceFILE ){
  133027. fprintf(yyTraceFILE,"%sPopping %s\n",
  133028. yyTracePrompt,
  133029. yyTokenName[yytos->major]);
  133030. }
  133031. #endif
  133032. yy_destructor(pParser, yytos->major, &yytos->minor);
  133033. }
  133034. /*
  133035. ** Clear all secondary memory allocations from the parser
  133036. */
  133037. SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
  133038. yyParser *pParser = (yyParser*)p;
  133039. while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
  133040. #if YYSTACKDEPTH<=0
  133041. if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
  133042. #endif
  133043. }
  133044. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  133045. /*
  133046. ** Deallocate and destroy a parser. Destructors are called for
  133047. ** all stack elements before shutting the parser down.
  133048. **
  133049. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  133050. ** is defined in a %include section of the input grammar) then it is
  133051. ** assumed that the input pointer is never NULL.
  133052. */
  133053. SQLITE_PRIVATE void sqlite3ParserFree(
  133054. void *p, /* The parser to be deleted */
  133055. void (*freeProc)(void*) /* Function used to reclaim memory */
  133056. ){
  133057. #ifndef YYPARSEFREENEVERNULL
  133058. if( p==0 ) return;
  133059. #endif
  133060. sqlite3ParserFinalize(p);
  133061. (*freeProc)(p);
  133062. }
  133063. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  133064. /*
  133065. ** Return the peak depth of the stack for a parser.
  133066. */
  133067. #ifdef YYTRACKMAXSTACKDEPTH
  133068. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  133069. yyParser *pParser = (yyParser*)p;
  133070. return pParser->yyhwm;
  133071. }
  133072. #endif
  133073. /* This array of booleans keeps track of the parser statement
  133074. ** coverage. The element yycoverage[X][Y] is set when the parser
  133075. ** is in state X and has a lookahead token Y. In a well-tested
  133076. ** systems, every element of this matrix should end up being set.
  133077. */
  133078. #if defined(YYCOVERAGE)
  133079. static unsigned char yycoverage[YYNSTATE][YYNTOKEN];
  133080. #endif
  133081. /*
  133082. ** Write into out a description of every state/lookahead combination that
  133083. **
  133084. ** (1) has not been used by the parser, and
  133085. ** (2) is not a syntax error.
  133086. **
  133087. ** Return the number of missed state/lookahead combinations.
  133088. */
  133089. #if defined(YYCOVERAGE)
  133090. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){
  133091. int stateno, iLookAhead, i;
  133092. int nMissed = 0;
  133093. for(stateno=0; stateno<YYNSTATE; stateno++){
  133094. i = yy_shift_ofst[stateno];
  133095. for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){
  133096. if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  133097. if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  133098. if( out ){
  133099. fprintf(out,"State %d lookahead %s %s\n", stateno,
  133100. yyTokenName[iLookAhead],
  133101. yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  133102. }
  133103. }
  133104. }
  133105. return nMissed;
  133106. }
  133107. #endif
  133108. /*
  133109. ** Find the appropriate action for a parser given the terminal
  133110. ** look-ahead token iLookAhead.
  133111. */
  133112. static unsigned int yy_find_shift_action(
  133113. yyParser *pParser, /* The parser */
  133114. YYCODETYPE iLookAhead /* The look-ahead token */
  133115. ){
  133116. int i;
  133117. int stateno = pParser->yytos->stateno;
  133118. if( stateno>YY_MAX_SHIFT ) return stateno;
  133119. assert( stateno <= YY_SHIFT_COUNT );
  133120. #if defined(YYCOVERAGE)
  133121. yycoverage[stateno][iLookAhead] = 1;
  133122. #endif
  133123. do{
  133124. i = yy_shift_ofst[stateno];
  133125. assert( i>=0 );
  133126. assert( i+YYNTOKEN<=(int)sizeof(yy_lookahead)/sizeof(yy_lookahead[0]) );
  133127. assert( iLookAhead!=YYNOCODE );
  133128. assert( iLookAhead < YYNTOKEN );
  133129. i += iLookAhead;
  133130. if( yy_lookahead[i]!=iLookAhead ){
  133131. #ifdef YYFALLBACK
  133132. YYCODETYPE iFallback; /* Fallback token */
  133133. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  133134. && (iFallback = yyFallback[iLookAhead])!=0 ){
  133135. #ifndef NDEBUG
  133136. if( yyTraceFILE ){
  133137. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  133138. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  133139. }
  133140. #endif
  133141. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  133142. iLookAhead = iFallback;
  133143. continue;
  133144. }
  133145. #endif
  133146. #ifdef YYWILDCARD
  133147. {
  133148. int j = i - iLookAhead + YYWILDCARD;
  133149. if(
  133150. #if YY_SHIFT_MIN+YYWILDCARD<0
  133151. j>=0 &&
  133152. #endif
  133153. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  133154. j<YY_ACTTAB_COUNT &&
  133155. #endif
  133156. yy_lookahead[j]==YYWILDCARD && iLookAhead>0
  133157. ){
  133158. #ifndef NDEBUG
  133159. if( yyTraceFILE ){
  133160. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  133161. yyTracePrompt, yyTokenName[iLookAhead],
  133162. yyTokenName[YYWILDCARD]);
  133163. }
  133164. #endif /* NDEBUG */
  133165. return yy_action[j];
  133166. }
  133167. }
  133168. #endif /* YYWILDCARD */
  133169. return yy_default[stateno];
  133170. }else{
  133171. return yy_action[i];
  133172. }
  133173. }while(1);
  133174. }
  133175. /*
  133176. ** Find the appropriate action for a parser given the non-terminal
  133177. ** look-ahead token iLookAhead.
  133178. */
  133179. static int yy_find_reduce_action(
  133180. int stateno, /* Current state number */
  133181. YYCODETYPE iLookAhead /* The look-ahead token */
  133182. ){
  133183. int i;
  133184. #ifdef YYERRORSYMBOL
  133185. if( stateno>YY_REDUCE_COUNT ){
  133186. return yy_default[stateno];
  133187. }
  133188. #else
  133189. assert( stateno<=YY_REDUCE_COUNT );
  133190. #endif
  133191. i = yy_reduce_ofst[stateno];
  133192. assert( iLookAhead!=YYNOCODE );
  133193. i += iLookAhead;
  133194. #ifdef YYERRORSYMBOL
  133195. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  133196. return yy_default[stateno];
  133197. }
  133198. #else
  133199. assert( i>=0 && i<YY_ACTTAB_COUNT );
  133200. assert( yy_lookahead[i]==iLookAhead );
  133201. #endif
  133202. return yy_action[i];
  133203. }
  133204. /*
  133205. ** The following routine is called if the stack overflows.
  133206. */
  133207. static void yyStackOverflow(yyParser *yypParser){
  133208. sqlite3ParserARG_FETCH;
  133209. #ifndef NDEBUG
  133210. if( yyTraceFILE ){
  133211. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  133212. }
  133213. #endif
  133214. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  133215. /* Here code is inserted which will execute if the parser
  133216. ** stack every overflows */
  133217. /******** Begin %stack_overflow code ******************************************/
  133218. sqlite3ErrorMsg(pParse, "parser stack overflow");
  133219. /******** End %stack_overflow code ********************************************/
  133220. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  133221. }
  133222. /*
  133223. ** Print tracing information for a SHIFT action
  133224. */
  133225. #ifndef NDEBUG
  133226. static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){
  133227. if( yyTraceFILE ){
  133228. if( yyNewState<YYNSTATE ){
  133229. fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n",
  133230. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  133231. yyNewState);
  133232. }else{
  133233. fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  133234. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  133235. yyNewState - YY_MIN_REDUCE);
  133236. }
  133237. }
  133238. }
  133239. #else
  133240. # define yyTraceShift(X,Y,Z)
  133241. #endif
  133242. /*
  133243. ** Perform a shift action.
  133244. */
  133245. static void yy_shift(
  133246. yyParser *yypParser, /* The parser to be shifted */
  133247. int yyNewState, /* The new state to shift in */
  133248. int yyMajor, /* The major token to shift in */
  133249. sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
  133250. ){
  133251. yyStackEntry *yytos;
  133252. yypParser->yytos++;
  133253. #ifdef YYTRACKMAXSTACKDEPTH
  133254. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  133255. yypParser->yyhwm++;
  133256. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
  133257. }
  133258. #endif
  133259. #if YYSTACKDEPTH>0
  133260. if( yypParser->yytos>yypParser->yystackEnd ){
  133261. yypParser->yytos--;
  133262. yyStackOverflow(yypParser);
  133263. return;
  133264. }
  133265. #else
  133266. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
  133267. if( yyGrowStack(yypParser) ){
  133268. yypParser->yytos--;
  133269. yyStackOverflow(yypParser);
  133270. return;
  133271. }
  133272. }
  133273. #endif
  133274. if( yyNewState > YY_MAX_SHIFT ){
  133275. yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  133276. }
  133277. yytos = yypParser->yytos;
  133278. yytos->stateno = (YYACTIONTYPE)yyNewState;
  133279. yytos->major = (YYCODETYPE)yyMajor;
  133280. yytos->minor.yy0 = yyMinor;
  133281. yyTraceShift(yypParser, yyNewState, "Shift");
  133282. }
  133283. /* The following table contains information about every rule that
  133284. ** is used during the reduce.
  133285. */
  133286. static const struct {
  133287. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  133288. signed char nrhs; /* Negative of the number of RHS symbols in the rule */
  133289. } yyRuleInfo[] = {
  133290. { 147, -1 }, /* (0) explain ::= EXPLAIN */
  133291. { 147, -3 }, /* (1) explain ::= EXPLAIN QUERY PLAN */
  133292. { 148, -1 }, /* (2) cmdx ::= cmd */
  133293. { 149, -3 }, /* (3) cmd ::= BEGIN transtype trans_opt */
  133294. { 150, 0 }, /* (4) transtype ::= */
  133295. { 150, -1 }, /* (5) transtype ::= DEFERRED */
  133296. { 150, -1 }, /* (6) transtype ::= IMMEDIATE */
  133297. { 150, -1 }, /* (7) transtype ::= EXCLUSIVE */
  133298. { 149, -2 }, /* (8) cmd ::= COMMIT|END trans_opt */
  133299. { 149, -2 }, /* (9) cmd ::= ROLLBACK trans_opt */
  133300. { 149, -2 }, /* (10) cmd ::= SAVEPOINT nm */
  133301. { 149, -3 }, /* (11) cmd ::= RELEASE savepoint_opt nm */
  133302. { 149, -5 }, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  133303. { 154, -6 }, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  133304. { 156, -1 }, /* (14) createkw ::= CREATE */
  133305. { 158, 0 }, /* (15) ifnotexists ::= */
  133306. { 158, -3 }, /* (16) ifnotexists ::= IF NOT EXISTS */
  133307. { 157, -1 }, /* (17) temp ::= TEMP */
  133308. { 157, 0 }, /* (18) temp ::= */
  133309. { 155, -5 }, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
  133310. { 155, -2 }, /* (20) create_table_args ::= AS select */
  133311. { 162, 0 }, /* (21) table_options ::= */
  133312. { 162, -2 }, /* (22) table_options ::= WITHOUT nm */
  133313. { 164, -2 }, /* (23) columnname ::= nm typetoken */
  133314. { 166, 0 }, /* (24) typetoken ::= */
  133315. { 166, -4 }, /* (25) typetoken ::= typename LP signed RP */
  133316. { 166, -6 }, /* (26) typetoken ::= typename LP signed COMMA signed RP */
  133317. { 167, -2 }, /* (27) typename ::= typename ID|STRING */
  133318. { 171, 0 }, /* (28) scanpt ::= */
  133319. { 172, -2 }, /* (29) ccons ::= CONSTRAINT nm */
  133320. { 172, -4 }, /* (30) ccons ::= DEFAULT scanpt term scanpt */
  133321. { 172, -4 }, /* (31) ccons ::= DEFAULT LP expr RP */
  133322. { 172, -4 }, /* (32) ccons ::= DEFAULT PLUS term scanpt */
  133323. { 172, -4 }, /* (33) ccons ::= DEFAULT MINUS term scanpt */
  133324. { 172, -3 }, /* (34) ccons ::= DEFAULT scanpt ID|INDEXED */
  133325. { 172, -3 }, /* (35) ccons ::= NOT NULL onconf */
  133326. { 172, -5 }, /* (36) ccons ::= PRIMARY KEY sortorder onconf autoinc */
  133327. { 172, -2 }, /* (37) ccons ::= UNIQUE onconf */
  133328. { 172, -4 }, /* (38) ccons ::= CHECK LP expr RP */
  133329. { 172, -4 }, /* (39) ccons ::= REFERENCES nm eidlist_opt refargs */
  133330. { 172, -1 }, /* (40) ccons ::= defer_subclause */
  133331. { 172, -2 }, /* (41) ccons ::= COLLATE ID|STRING */
  133332. { 177, 0 }, /* (42) autoinc ::= */
  133333. { 177, -1 }, /* (43) autoinc ::= AUTOINCR */
  133334. { 179, 0 }, /* (44) refargs ::= */
  133335. { 179, -2 }, /* (45) refargs ::= refargs refarg */
  133336. { 181, -2 }, /* (46) refarg ::= MATCH nm */
  133337. { 181, -3 }, /* (47) refarg ::= ON INSERT refact */
  133338. { 181, -3 }, /* (48) refarg ::= ON DELETE refact */
  133339. { 181, -3 }, /* (49) refarg ::= ON UPDATE refact */
  133340. { 182, -2 }, /* (50) refact ::= SET NULL */
  133341. { 182, -2 }, /* (51) refact ::= SET DEFAULT */
  133342. { 182, -1 }, /* (52) refact ::= CASCADE */
  133343. { 182, -1 }, /* (53) refact ::= RESTRICT */
  133344. { 182, -2 }, /* (54) refact ::= NO ACTION */
  133345. { 180, -3 }, /* (55) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  133346. { 180, -2 }, /* (56) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  133347. { 183, 0 }, /* (57) init_deferred_pred_opt ::= */
  133348. { 183, -2 }, /* (58) init_deferred_pred_opt ::= INITIALLY DEFERRED */
  133349. { 183, -2 }, /* (59) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  133350. { 161, 0 }, /* (60) conslist_opt ::= */
  133351. { 185, -1 }, /* (61) tconscomma ::= COMMA */
  133352. { 186, -2 }, /* (62) tcons ::= CONSTRAINT nm */
  133353. { 186, -7 }, /* (63) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  133354. { 186, -5 }, /* (64) tcons ::= UNIQUE LP sortlist RP onconf */
  133355. { 186, -5 }, /* (65) tcons ::= CHECK LP expr RP onconf */
  133356. { 186, -10 }, /* (66) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  133357. { 189, 0 }, /* (67) defer_subclause_opt ::= */
  133358. { 175, 0 }, /* (68) onconf ::= */
  133359. { 175, -3 }, /* (69) onconf ::= ON CONFLICT resolvetype */
  133360. { 190, 0 }, /* (70) orconf ::= */
  133361. { 190, -2 }, /* (71) orconf ::= OR resolvetype */
  133362. { 191, -1 }, /* (72) resolvetype ::= IGNORE */
  133363. { 191, -1 }, /* (73) resolvetype ::= REPLACE */
  133364. { 149, -4 }, /* (74) cmd ::= DROP TABLE ifexists fullname */
  133365. { 193, -2 }, /* (75) ifexists ::= IF EXISTS */
  133366. { 193, 0 }, /* (76) ifexists ::= */
  133367. { 149, -9 }, /* (77) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  133368. { 149, -4 }, /* (78) cmd ::= DROP VIEW ifexists fullname */
  133369. { 149, -1 }, /* (79) cmd ::= select */
  133370. { 163, -3 }, /* (80) select ::= WITH wqlist selectnowith */
  133371. { 163, -4 }, /* (81) select ::= WITH RECURSIVE wqlist selectnowith */
  133372. { 163, -1 }, /* (82) select ::= selectnowith */
  133373. { 195, -3 }, /* (83) selectnowith ::= selectnowith multiselect_op oneselect */
  133374. { 198, -1 }, /* (84) multiselect_op ::= UNION */
  133375. { 198, -2 }, /* (85) multiselect_op ::= UNION ALL */
  133376. { 198, -1 }, /* (86) multiselect_op ::= EXCEPT|INTERSECT */
  133377. { 196, -9 }, /* (87) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  133378. { 207, -4 }, /* (88) values ::= VALUES LP nexprlist RP */
  133379. { 207, -5 }, /* (89) values ::= values COMMA LP exprlist RP */
  133380. { 199, -1 }, /* (90) distinct ::= DISTINCT */
  133381. { 199, -1 }, /* (91) distinct ::= ALL */
  133382. { 199, 0 }, /* (92) distinct ::= */
  133383. { 210, 0 }, /* (93) sclp ::= */
  133384. { 200, -5 }, /* (94) selcollist ::= sclp scanpt expr scanpt as */
  133385. { 200, -3 }, /* (95) selcollist ::= sclp scanpt STAR */
  133386. { 200, -5 }, /* (96) selcollist ::= sclp scanpt nm DOT STAR */
  133387. { 211, -2 }, /* (97) as ::= AS nm */
  133388. { 211, 0 }, /* (98) as ::= */
  133389. { 201, 0 }, /* (99) from ::= */
  133390. { 201, -2 }, /* (100) from ::= FROM seltablist */
  133391. { 213, -2 }, /* (101) stl_prefix ::= seltablist joinop */
  133392. { 213, 0 }, /* (102) stl_prefix ::= */
  133393. { 212, -7 }, /* (103) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  133394. { 212, -9 }, /* (104) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  133395. { 212, -7 }, /* (105) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  133396. { 212, -7 }, /* (106) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  133397. { 159, 0 }, /* (107) dbnm ::= */
  133398. { 159, -2 }, /* (108) dbnm ::= DOT nm */
  133399. { 194, -1 }, /* (109) fullname ::= nm */
  133400. { 194, -3 }, /* (110) fullname ::= nm DOT nm */
  133401. { 214, -1 }, /* (111) joinop ::= COMMA|JOIN */
  133402. { 214, -2 }, /* (112) joinop ::= JOIN_KW JOIN */
  133403. { 214, -3 }, /* (113) joinop ::= JOIN_KW nm JOIN */
  133404. { 214, -4 }, /* (114) joinop ::= JOIN_KW nm nm JOIN */
  133405. { 216, -2 }, /* (115) on_opt ::= ON expr */
  133406. { 216, 0 }, /* (116) on_opt ::= */
  133407. { 215, 0 }, /* (117) indexed_opt ::= */
  133408. { 215, -3 }, /* (118) indexed_opt ::= INDEXED BY nm */
  133409. { 215, -2 }, /* (119) indexed_opt ::= NOT INDEXED */
  133410. { 217, -4 }, /* (120) using_opt ::= USING LP idlist RP */
  133411. { 217, 0 }, /* (121) using_opt ::= */
  133412. { 205, 0 }, /* (122) orderby_opt ::= */
  133413. { 205, -3 }, /* (123) orderby_opt ::= ORDER BY sortlist */
  133414. { 187, -4 }, /* (124) sortlist ::= sortlist COMMA expr sortorder */
  133415. { 187, -2 }, /* (125) sortlist ::= expr sortorder */
  133416. { 176, -1 }, /* (126) sortorder ::= ASC */
  133417. { 176, -1 }, /* (127) sortorder ::= DESC */
  133418. { 176, 0 }, /* (128) sortorder ::= */
  133419. { 203, 0 }, /* (129) groupby_opt ::= */
  133420. { 203, -3 }, /* (130) groupby_opt ::= GROUP BY nexprlist */
  133421. { 204, 0 }, /* (131) having_opt ::= */
  133422. { 204, -2 }, /* (132) having_opt ::= HAVING expr */
  133423. { 206, 0 }, /* (133) limit_opt ::= */
  133424. { 206, -2 }, /* (134) limit_opt ::= LIMIT expr */
  133425. { 206, -4 }, /* (135) limit_opt ::= LIMIT expr OFFSET expr */
  133426. { 206, -4 }, /* (136) limit_opt ::= LIMIT expr COMMA expr */
  133427. { 149, -6 }, /* (137) cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  133428. { 202, 0 }, /* (138) where_opt ::= */
  133429. { 202, -2 }, /* (139) where_opt ::= WHERE expr */
  133430. { 149, -8 }, /* (140) cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  133431. { 220, -5 }, /* (141) setlist ::= setlist COMMA nm EQ expr */
  133432. { 220, -7 }, /* (142) setlist ::= setlist COMMA LP idlist RP EQ expr */
  133433. { 220, -3 }, /* (143) setlist ::= nm EQ expr */
  133434. { 220, -5 }, /* (144) setlist ::= LP idlist RP EQ expr */
  133435. { 149, -6 }, /* (145) cmd ::= with insert_cmd INTO fullname idlist_opt select */
  133436. { 149, -7 }, /* (146) cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
  133437. { 221, -2 }, /* (147) insert_cmd ::= INSERT orconf */
  133438. { 221, -1 }, /* (148) insert_cmd ::= REPLACE */
  133439. { 222, 0 }, /* (149) idlist_opt ::= */
  133440. { 222, -3 }, /* (150) idlist_opt ::= LP idlist RP */
  133441. { 218, -3 }, /* (151) idlist ::= idlist COMMA nm */
  133442. { 218, -1 }, /* (152) idlist ::= nm */
  133443. { 174, -3 }, /* (153) expr ::= LP expr RP */
  133444. { 174, -1 }, /* (154) expr ::= ID|INDEXED */
  133445. { 174, -1 }, /* (155) expr ::= JOIN_KW */
  133446. { 174, -3 }, /* (156) expr ::= nm DOT nm */
  133447. { 174, -5 }, /* (157) expr ::= nm DOT nm DOT nm */
  133448. { 173, -1 }, /* (158) term ::= NULL|FLOAT|BLOB */
  133449. { 173, -1 }, /* (159) term ::= STRING */
  133450. { 173, -1 }, /* (160) term ::= INTEGER */
  133451. { 174, -1 }, /* (161) expr ::= VARIABLE */
  133452. { 174, -3 }, /* (162) expr ::= expr COLLATE ID|STRING */
  133453. { 174, -6 }, /* (163) expr ::= CAST LP expr AS typetoken RP */
  133454. { 174, -5 }, /* (164) expr ::= ID|INDEXED LP distinct exprlist RP */
  133455. { 174, -4 }, /* (165) expr ::= ID|INDEXED LP STAR RP */
  133456. { 173, -1 }, /* (166) term ::= CTIME_KW */
  133457. { 174, -5 }, /* (167) expr ::= LP nexprlist COMMA expr RP */
  133458. { 174, -3 }, /* (168) expr ::= expr AND expr */
  133459. { 174, -3 }, /* (169) expr ::= expr OR expr */
  133460. { 174, -3 }, /* (170) expr ::= expr LT|GT|GE|LE expr */
  133461. { 174, -3 }, /* (171) expr ::= expr EQ|NE expr */
  133462. { 174, -3 }, /* (172) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  133463. { 174, -3 }, /* (173) expr ::= expr PLUS|MINUS expr */
  133464. { 174, -3 }, /* (174) expr ::= expr STAR|SLASH|REM expr */
  133465. { 174, -3 }, /* (175) expr ::= expr CONCAT expr */
  133466. { 223, -2 }, /* (176) likeop ::= NOT LIKE_KW|MATCH */
  133467. { 174, -3 }, /* (177) expr ::= expr likeop expr */
  133468. { 174, -5 }, /* (178) expr ::= expr likeop expr ESCAPE expr */
  133469. { 174, -2 }, /* (179) expr ::= expr ISNULL|NOTNULL */
  133470. { 174, -3 }, /* (180) expr ::= expr NOT NULL */
  133471. { 174, -3 }, /* (181) expr ::= expr IS expr */
  133472. { 174, -4 }, /* (182) expr ::= expr IS NOT expr */
  133473. { 174, -2 }, /* (183) expr ::= NOT expr */
  133474. { 174, -2 }, /* (184) expr ::= BITNOT expr */
  133475. { 174, -2 }, /* (185) expr ::= MINUS expr */
  133476. { 174, -2 }, /* (186) expr ::= PLUS expr */
  133477. { 224, -1 }, /* (187) between_op ::= BETWEEN */
  133478. { 224, -2 }, /* (188) between_op ::= NOT BETWEEN */
  133479. { 174, -5 }, /* (189) expr ::= expr between_op expr AND expr */
  133480. { 225, -1 }, /* (190) in_op ::= IN */
  133481. { 225, -2 }, /* (191) in_op ::= NOT IN */
  133482. { 174, -5 }, /* (192) expr ::= expr in_op LP exprlist RP */
  133483. { 174, -3 }, /* (193) expr ::= LP select RP */
  133484. { 174, -5 }, /* (194) expr ::= expr in_op LP select RP */
  133485. { 174, -5 }, /* (195) expr ::= expr in_op nm dbnm paren_exprlist */
  133486. { 174, -4 }, /* (196) expr ::= EXISTS LP select RP */
  133487. { 174, -5 }, /* (197) expr ::= CASE case_operand case_exprlist case_else END */
  133488. { 228, -5 }, /* (198) case_exprlist ::= case_exprlist WHEN expr THEN expr */
  133489. { 228, -4 }, /* (199) case_exprlist ::= WHEN expr THEN expr */
  133490. { 229, -2 }, /* (200) case_else ::= ELSE expr */
  133491. { 229, 0 }, /* (201) case_else ::= */
  133492. { 227, -1 }, /* (202) case_operand ::= expr */
  133493. { 227, 0 }, /* (203) case_operand ::= */
  133494. { 209, 0 }, /* (204) exprlist ::= */
  133495. { 208, -3 }, /* (205) nexprlist ::= nexprlist COMMA expr */
  133496. { 208, -1 }, /* (206) nexprlist ::= expr */
  133497. { 226, 0 }, /* (207) paren_exprlist ::= */
  133498. { 226, -3 }, /* (208) paren_exprlist ::= LP exprlist RP */
  133499. { 149, -12 }, /* (209) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  133500. { 230, -1 }, /* (210) uniqueflag ::= UNIQUE */
  133501. { 230, 0 }, /* (211) uniqueflag ::= */
  133502. { 178, 0 }, /* (212) eidlist_opt ::= */
  133503. { 178, -3 }, /* (213) eidlist_opt ::= LP eidlist RP */
  133504. { 188, -5 }, /* (214) eidlist ::= eidlist COMMA nm collate sortorder */
  133505. { 188, -3 }, /* (215) eidlist ::= nm collate sortorder */
  133506. { 231, 0 }, /* (216) collate ::= */
  133507. { 231, -2 }, /* (217) collate ::= COLLATE ID|STRING */
  133508. { 149, -4 }, /* (218) cmd ::= DROP INDEX ifexists fullname */
  133509. { 149, -1 }, /* (219) cmd ::= VACUUM */
  133510. { 149, -2 }, /* (220) cmd ::= VACUUM nm */
  133511. { 149, -3 }, /* (221) cmd ::= PRAGMA nm dbnm */
  133512. { 149, -5 }, /* (222) cmd ::= PRAGMA nm dbnm EQ nmnum */
  133513. { 149, -6 }, /* (223) cmd ::= PRAGMA nm dbnm LP nmnum RP */
  133514. { 149, -5 }, /* (224) cmd ::= PRAGMA nm dbnm EQ minus_num */
  133515. { 149, -6 }, /* (225) cmd ::= PRAGMA nm dbnm LP minus_num RP */
  133516. { 169, -2 }, /* (226) plus_num ::= PLUS INTEGER|FLOAT */
  133517. { 170, -2 }, /* (227) minus_num ::= MINUS INTEGER|FLOAT */
  133518. { 149, -5 }, /* (228) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  133519. { 233, -11 }, /* (229) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  133520. { 235, -1 }, /* (230) trigger_time ::= BEFORE|AFTER */
  133521. { 235, -2 }, /* (231) trigger_time ::= INSTEAD OF */
  133522. { 235, 0 }, /* (232) trigger_time ::= */
  133523. { 236, -1 }, /* (233) trigger_event ::= DELETE|INSERT */
  133524. { 236, -1 }, /* (234) trigger_event ::= UPDATE */
  133525. { 236, -3 }, /* (235) trigger_event ::= UPDATE OF idlist */
  133526. { 238, 0 }, /* (236) when_clause ::= */
  133527. { 238, -2 }, /* (237) when_clause ::= WHEN expr */
  133528. { 234, -3 }, /* (238) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  133529. { 234, -2 }, /* (239) trigger_cmd_list ::= trigger_cmd SEMI */
  133530. { 240, -3 }, /* (240) trnm ::= nm DOT nm */
  133531. { 241, -3 }, /* (241) tridxby ::= INDEXED BY nm */
  133532. { 241, -2 }, /* (242) tridxby ::= NOT INDEXED */
  133533. { 239, -8 }, /* (243) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  133534. { 239, -7 }, /* (244) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select scanpt */
  133535. { 239, -6 }, /* (245) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  133536. { 239, -3 }, /* (246) trigger_cmd ::= scanpt select scanpt */
  133537. { 174, -4 }, /* (247) expr ::= RAISE LP IGNORE RP */
  133538. { 174, -6 }, /* (248) expr ::= RAISE LP raisetype COMMA nm RP */
  133539. { 192, -1 }, /* (249) raisetype ::= ROLLBACK */
  133540. { 192, -1 }, /* (250) raisetype ::= ABORT */
  133541. { 192, -1 }, /* (251) raisetype ::= FAIL */
  133542. { 149, -4 }, /* (252) cmd ::= DROP TRIGGER ifexists fullname */
  133543. { 149, -6 }, /* (253) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  133544. { 149, -3 }, /* (254) cmd ::= DETACH database_kw_opt expr */
  133545. { 243, 0 }, /* (255) key_opt ::= */
  133546. { 243, -2 }, /* (256) key_opt ::= KEY expr */
  133547. { 149, -1 }, /* (257) cmd ::= REINDEX */
  133548. { 149, -3 }, /* (258) cmd ::= REINDEX nm dbnm */
  133549. { 149, -1 }, /* (259) cmd ::= ANALYZE */
  133550. { 149, -3 }, /* (260) cmd ::= ANALYZE nm dbnm */
  133551. { 149, -6 }, /* (261) cmd ::= ALTER TABLE fullname RENAME TO nm */
  133552. { 149, -7 }, /* (262) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  133553. { 244, -1 }, /* (263) add_column_fullname ::= fullname */
  133554. { 149, -1 }, /* (264) cmd ::= create_vtab */
  133555. { 149, -4 }, /* (265) cmd ::= create_vtab LP vtabarglist RP */
  133556. { 246, -8 }, /* (266) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  133557. { 248, 0 }, /* (267) vtabarg ::= */
  133558. { 249, -1 }, /* (268) vtabargtoken ::= ANY */
  133559. { 249, -3 }, /* (269) vtabargtoken ::= lp anylist RP */
  133560. { 250, -1 }, /* (270) lp ::= LP */
  133561. { 219, -2 }, /* (271) with ::= WITH wqlist */
  133562. { 219, -3 }, /* (272) with ::= WITH RECURSIVE wqlist */
  133563. { 197, -6 }, /* (273) wqlist ::= nm eidlist_opt AS LP select RP */
  133564. { 197, -8 }, /* (274) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  133565. { 144, -1 }, /* (275) input ::= cmdlist */
  133566. { 145, -2 }, /* (276) cmdlist ::= cmdlist ecmd */
  133567. { 145, -1 }, /* (277) cmdlist ::= ecmd */
  133568. { 146, -1 }, /* (278) ecmd ::= SEMI */
  133569. { 146, -3 }, /* (279) ecmd ::= explain cmdx SEMI */
  133570. { 147, 0 }, /* (280) explain ::= */
  133571. { 151, 0 }, /* (281) trans_opt ::= */
  133572. { 151, -1 }, /* (282) trans_opt ::= TRANSACTION */
  133573. { 151, -2 }, /* (283) trans_opt ::= TRANSACTION nm */
  133574. { 153, -1 }, /* (284) savepoint_opt ::= SAVEPOINT */
  133575. { 153, 0 }, /* (285) savepoint_opt ::= */
  133576. { 149, -2 }, /* (286) cmd ::= create_table create_table_args */
  133577. { 160, -4 }, /* (287) columnlist ::= columnlist COMMA columnname carglist */
  133578. { 160, -2 }, /* (288) columnlist ::= columnname carglist */
  133579. { 152, -1 }, /* (289) nm ::= ID|INDEXED */
  133580. { 152, -1 }, /* (290) nm ::= STRING */
  133581. { 152, -1 }, /* (291) nm ::= JOIN_KW */
  133582. { 166, -1 }, /* (292) typetoken ::= typename */
  133583. { 167, -1 }, /* (293) typename ::= ID|STRING */
  133584. { 168, -1 }, /* (294) signed ::= plus_num */
  133585. { 168, -1 }, /* (295) signed ::= minus_num */
  133586. { 165, -2 }, /* (296) carglist ::= carglist ccons */
  133587. { 165, 0 }, /* (297) carglist ::= */
  133588. { 172, -2 }, /* (298) ccons ::= NULL onconf */
  133589. { 161, -2 }, /* (299) conslist_opt ::= COMMA conslist */
  133590. { 184, -3 }, /* (300) conslist ::= conslist tconscomma tcons */
  133591. { 184, -1 }, /* (301) conslist ::= tcons */
  133592. { 185, 0 }, /* (302) tconscomma ::= */
  133593. { 189, -1 }, /* (303) defer_subclause_opt ::= defer_subclause */
  133594. { 191, -1 }, /* (304) resolvetype ::= raisetype */
  133595. { 195, -1 }, /* (305) selectnowith ::= oneselect */
  133596. { 196, -1 }, /* (306) oneselect ::= values */
  133597. { 210, -2 }, /* (307) sclp ::= selcollist COMMA */
  133598. { 211, -1 }, /* (308) as ::= ID|STRING */
  133599. { 174, -1 }, /* (309) expr ::= term */
  133600. { 223, -1 }, /* (310) likeop ::= LIKE_KW|MATCH */
  133601. { 209, -1 }, /* (311) exprlist ::= nexprlist */
  133602. { 232, -1 }, /* (312) nmnum ::= plus_num */
  133603. { 232, -1 }, /* (313) nmnum ::= nm */
  133604. { 232, -1 }, /* (314) nmnum ::= ON */
  133605. { 232, -1 }, /* (315) nmnum ::= DELETE */
  133606. { 232, -1 }, /* (316) nmnum ::= DEFAULT */
  133607. { 169, -1 }, /* (317) plus_num ::= INTEGER|FLOAT */
  133608. { 237, 0 }, /* (318) foreach_clause ::= */
  133609. { 237, -3 }, /* (319) foreach_clause ::= FOR EACH ROW */
  133610. { 240, -1 }, /* (320) trnm ::= nm */
  133611. { 241, 0 }, /* (321) tridxby ::= */
  133612. { 242, -1 }, /* (322) database_kw_opt ::= DATABASE */
  133613. { 242, 0 }, /* (323) database_kw_opt ::= */
  133614. { 245, 0 }, /* (324) kwcolumn_opt ::= */
  133615. { 245, -1 }, /* (325) kwcolumn_opt ::= COLUMNKW */
  133616. { 247, -1 }, /* (326) vtabarglist ::= vtabarg */
  133617. { 247, -3 }, /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */
  133618. { 248, -2 }, /* (328) vtabarg ::= vtabarg vtabargtoken */
  133619. { 251, 0 }, /* (329) anylist ::= */
  133620. { 251, -4 }, /* (330) anylist ::= anylist LP anylist RP */
  133621. { 251, -2 }, /* (331) anylist ::= anylist ANY */
  133622. { 219, 0 }, /* (332) with ::= */
  133623. };
  133624. static void yy_accept(yyParser*); /* Forward Declaration */
  133625. /*
  133626. ** Perform a reduce action and the shift that must immediately
  133627. ** follow the reduce.
  133628. **
  133629. ** The yyLookahead and yyLookaheadToken parameters provide reduce actions
  133630. ** access to the lookahead token (if any). The yyLookahead will be YYNOCODE
  133631. ** if the lookahead token has already been consumed. As this procedure is
  133632. ** only called from one place, optimizing compilers will in-line it, which
  133633. ** means that the extra parameters have no performance impact.
  133634. */
  133635. static void yy_reduce(
  133636. yyParser *yypParser, /* The parser */
  133637. unsigned int yyruleno, /* Number of the rule by which to reduce */
  133638. int yyLookahead, /* Lookahead token, or YYNOCODE if none */
  133639. sqlite3ParserTOKENTYPE yyLookaheadToken /* Value of the lookahead token */
  133640. ){
  133641. int yygoto; /* The next state */
  133642. int yyact; /* The next action */
  133643. yyStackEntry *yymsp; /* The top of the parser's stack */
  133644. int yysize; /* Amount to pop the stack */
  133645. sqlite3ParserARG_FETCH;
  133646. (void)yyLookahead;
  133647. (void)yyLookaheadToken;
  133648. yymsp = yypParser->yytos;
  133649. #ifndef NDEBUG
  133650. if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  133651. yysize = yyRuleInfo[yyruleno].nrhs;
  133652. if( yysize ){
  133653. fprintf(yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
  133654. yyTracePrompt,
  133655. yyruleno, yyRuleName[yyruleno], yymsp[yysize].stateno);
  133656. }else{
  133657. fprintf(yyTraceFILE, "%sReduce %d [%s].\n",
  133658. yyTracePrompt, yyruleno, yyRuleName[yyruleno]);
  133659. }
  133660. }
  133661. #endif /* NDEBUG */
  133662. /* Check that the stack is large enough to grow by a single entry
  133663. ** if the RHS of the rule is empty. This ensures that there is room
  133664. ** enough on the stack to push the LHS value */
  133665. if( yyRuleInfo[yyruleno].nrhs==0 ){
  133666. #ifdef YYTRACKMAXSTACKDEPTH
  133667. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  133668. yypParser->yyhwm++;
  133669. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
  133670. }
  133671. #endif
  133672. #if YYSTACKDEPTH>0
  133673. if( yypParser->yytos>=yypParser->yystackEnd ){
  133674. yyStackOverflow(yypParser);
  133675. return;
  133676. }
  133677. #else
  133678. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
  133679. if( yyGrowStack(yypParser) ){
  133680. yyStackOverflow(yypParser);
  133681. return;
  133682. }
  133683. yymsp = yypParser->yytos;
  133684. }
  133685. #endif
  133686. }
  133687. switch( yyruleno ){
  133688. /* Beginning here are the reduction cases. A typical example
  133689. ** follows:
  133690. ** case 0:
  133691. ** #line <lineno> <grammarfile>
  133692. ** { ... } // User supplied code
  133693. ** #line <lineno> <thisfile>
  133694. ** break;
  133695. */
  133696. /********** Begin reduce actions **********************************************/
  133697. YYMINORTYPE yylhsminor;
  133698. case 0: /* explain ::= EXPLAIN */
  133699. { pParse->explain = 1; }
  133700. break;
  133701. case 1: /* explain ::= EXPLAIN QUERY PLAN */
  133702. { pParse->explain = 2; }
  133703. break;
  133704. case 2: /* cmdx ::= cmd */
  133705. { sqlite3FinishCoding(pParse); }
  133706. break;
  133707. case 3: /* cmd ::= BEGIN transtype trans_opt */
  133708. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy4);}
  133709. break;
  133710. case 4: /* transtype ::= */
  133711. {yymsp[1].minor.yy4 = TK_DEFERRED;}
  133712. break;
  133713. case 5: /* transtype ::= DEFERRED */
  133714. case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
  133715. case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
  133716. {yymsp[0].minor.yy4 = yymsp[0].major; /*A-overwrites-X*/}
  133717. break;
  133718. case 8: /* cmd ::= COMMIT|END trans_opt */
  133719. case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
  133720. {sqlite3EndTransaction(pParse,yymsp[-1].major);}
  133721. break;
  133722. case 10: /* cmd ::= SAVEPOINT nm */
  133723. {
  133724. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  133725. }
  133726. break;
  133727. case 11: /* cmd ::= RELEASE savepoint_opt nm */
  133728. {
  133729. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  133730. }
  133731. break;
  133732. case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  133733. {
  133734. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  133735. }
  133736. break;
  133737. case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  133738. {
  133739. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy4,0,0,yymsp[-2].minor.yy4);
  133740. }
  133741. break;
  133742. case 14: /* createkw ::= CREATE */
  133743. {disableLookaside(pParse);}
  133744. break;
  133745. case 15: /* ifnotexists ::= */
  133746. case 18: /* temp ::= */ yytestcase(yyruleno==18);
  133747. case 21: /* table_options ::= */ yytestcase(yyruleno==21);
  133748. case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
  133749. case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
  133750. case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
  133751. case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
  133752. case 92: /* distinct ::= */ yytestcase(yyruleno==92);
  133753. case 216: /* collate ::= */ yytestcase(yyruleno==216);
  133754. {yymsp[1].minor.yy4 = 0;}
  133755. break;
  133756. case 16: /* ifnotexists ::= IF NOT EXISTS */
  133757. {yymsp[-2].minor.yy4 = 1;}
  133758. break;
  133759. case 17: /* temp ::= TEMP */
  133760. case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
  133761. {yymsp[0].minor.yy4 = 1;}
  133762. break;
  133763. case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  133764. {
  133765. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy4,0);
  133766. }
  133767. break;
  133768. case 20: /* create_table_args ::= AS select */
  133769. {
  133770. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy387);
  133771. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
  133772. }
  133773. break;
  133774. case 22: /* table_options ::= WITHOUT nm */
  133775. {
  133776. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  133777. yymsp[-1].minor.yy4 = TF_WithoutRowid | TF_NoVisibleRowid;
  133778. }else{
  133779. yymsp[-1].minor.yy4 = 0;
  133780. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  133781. }
  133782. }
  133783. break;
  133784. case 23: /* columnname ::= nm typetoken */
  133785. {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  133786. break;
  133787. case 24: /* typetoken ::= */
  133788. case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
  133789. case 98: /* as ::= */ yytestcase(yyruleno==98);
  133790. {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
  133791. break;
  133792. case 25: /* typetoken ::= typename LP signed RP */
  133793. {
  133794. yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  133795. }
  133796. break;
  133797. case 26: /* typetoken ::= typename LP signed COMMA signed RP */
  133798. {
  133799. yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  133800. }
  133801. break;
  133802. case 27: /* typename ::= typename ID|STRING */
  133803. {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  133804. break;
  133805. case 28: /* scanpt ::= */
  133806. {
  133807. assert( yyLookahead!=YYNOCODE );
  133808. yymsp[1].minor.yy336 = yyLookaheadToken.z;
  133809. }
  133810. break;
  133811. case 29: /* ccons ::= CONSTRAINT nm */
  133812. case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
  133813. {pParse->constraintName = yymsp[0].minor.yy0;}
  133814. break;
  133815. case 30: /* ccons ::= DEFAULT scanpt term scanpt */
  133816. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy314,yymsp[-2].minor.yy336,yymsp[0].minor.yy336);}
  133817. break;
  133818. case 31: /* ccons ::= DEFAULT LP expr RP */
  133819. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy314,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
  133820. break;
  133821. case 32: /* ccons ::= DEFAULT PLUS term scanpt */
  133822. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy314,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy336);}
  133823. break;
  133824. case 33: /* ccons ::= DEFAULT MINUS term scanpt */
  133825. {
  133826. Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[-1].minor.yy314, 0);
  133827. sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy336);
  133828. }
  133829. break;
  133830. case 34: /* ccons ::= DEFAULT scanpt ID|INDEXED */
  133831. {
  133832. Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
  133833. if( p ){
  133834. sqlite3ExprIdToTrueFalse(p);
  133835. testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
  133836. }
  133837. sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
  133838. }
  133839. break;
  133840. case 35: /* ccons ::= NOT NULL onconf */
  133841. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy4);}
  133842. break;
  133843. case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  133844. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy4,yymsp[0].minor.yy4,yymsp[-2].minor.yy4);}
  133845. break;
  133846. case 37: /* ccons ::= UNIQUE onconf */
  133847. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy4,0,0,0,0,
  133848. SQLITE_IDXTYPE_UNIQUE);}
  133849. break;
  133850. case 38: /* ccons ::= CHECK LP expr RP */
  133851. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy314);}
  133852. break;
  133853. case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  133854. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy4);}
  133855. break;
  133856. case 40: /* ccons ::= defer_subclause */
  133857. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy4);}
  133858. break;
  133859. case 41: /* ccons ::= COLLATE ID|STRING */
  133860. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  133861. break;
  133862. case 44: /* refargs ::= */
  133863. { yymsp[1].minor.yy4 = OE_None*0x0101; /* EV: R-19803-45884 */}
  133864. break;
  133865. case 45: /* refargs ::= refargs refarg */
  133866. { yymsp[-1].minor.yy4 = (yymsp[-1].minor.yy4 & ~yymsp[0].minor.yy215.mask) | yymsp[0].minor.yy215.value; }
  133867. break;
  133868. case 46: /* refarg ::= MATCH nm */
  133869. { yymsp[-1].minor.yy215.value = 0; yymsp[-1].minor.yy215.mask = 0x000000; }
  133870. break;
  133871. case 47: /* refarg ::= ON INSERT refact */
  133872. { yymsp[-2].minor.yy215.value = 0; yymsp[-2].minor.yy215.mask = 0x000000; }
  133873. break;
  133874. case 48: /* refarg ::= ON DELETE refact */
  133875. { yymsp[-2].minor.yy215.value = yymsp[0].minor.yy4; yymsp[-2].minor.yy215.mask = 0x0000ff; }
  133876. break;
  133877. case 49: /* refarg ::= ON UPDATE refact */
  133878. { yymsp[-2].minor.yy215.value = yymsp[0].minor.yy4<<8; yymsp[-2].minor.yy215.mask = 0x00ff00; }
  133879. break;
  133880. case 50: /* refact ::= SET NULL */
  133881. { yymsp[-1].minor.yy4 = OE_SetNull; /* EV: R-33326-45252 */}
  133882. break;
  133883. case 51: /* refact ::= SET DEFAULT */
  133884. { yymsp[-1].minor.yy4 = OE_SetDflt; /* EV: R-33326-45252 */}
  133885. break;
  133886. case 52: /* refact ::= CASCADE */
  133887. { yymsp[0].minor.yy4 = OE_Cascade; /* EV: R-33326-45252 */}
  133888. break;
  133889. case 53: /* refact ::= RESTRICT */
  133890. { yymsp[0].minor.yy4 = OE_Restrict; /* EV: R-33326-45252 */}
  133891. break;
  133892. case 54: /* refact ::= NO ACTION */
  133893. { yymsp[-1].minor.yy4 = OE_None; /* EV: R-33326-45252 */}
  133894. break;
  133895. case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  133896. {yymsp[-2].minor.yy4 = 0;}
  133897. break;
  133898. case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  133899. case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
  133900. case 147: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==147);
  133901. {yymsp[-1].minor.yy4 = yymsp[0].minor.yy4;}
  133902. break;
  133903. case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  133904. case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
  133905. case 188: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==188);
  133906. case 191: /* in_op ::= NOT IN */ yytestcase(yyruleno==191);
  133907. case 217: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==217);
  133908. {yymsp[-1].minor.yy4 = 1;}
  133909. break;
  133910. case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  133911. {yymsp[-1].minor.yy4 = 0;}
  133912. break;
  133913. case 61: /* tconscomma ::= COMMA */
  133914. {pParse->constraintName.n = 0;}
  133915. break;
  133916. case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  133917. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy4,yymsp[-2].minor.yy4,0);}
  133918. break;
  133919. case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
  133920. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy4,0,0,0,0,
  133921. SQLITE_IDXTYPE_UNIQUE);}
  133922. break;
  133923. case 65: /* tcons ::= CHECK LP expr RP onconf */
  133924. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy314);}
  133925. break;
  133926. case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  133927. {
  133928. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy4);
  133929. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy4);
  133930. }
  133931. break;
  133932. case 68: /* onconf ::= */
  133933. case 70: /* orconf ::= */ yytestcase(yyruleno==70);
  133934. {yymsp[1].minor.yy4 = OE_Default;}
  133935. break;
  133936. case 69: /* onconf ::= ON CONFLICT resolvetype */
  133937. {yymsp[-2].minor.yy4 = yymsp[0].minor.yy4;}
  133938. break;
  133939. case 72: /* resolvetype ::= IGNORE */
  133940. {yymsp[0].minor.yy4 = OE_Ignore;}
  133941. break;
  133942. case 73: /* resolvetype ::= REPLACE */
  133943. case 148: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==148);
  133944. {yymsp[0].minor.yy4 = OE_Replace;}
  133945. break;
  133946. case 74: /* cmd ::= DROP TABLE ifexists fullname */
  133947. {
  133948. sqlite3DropTable(pParse, yymsp[0].minor.yy259, 0, yymsp[-1].minor.yy4);
  133949. }
  133950. break;
  133951. case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  133952. {
  133953. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[0].minor.yy387, yymsp[-7].minor.yy4, yymsp[-5].minor.yy4);
  133954. }
  133955. break;
  133956. case 78: /* cmd ::= DROP VIEW ifexists fullname */
  133957. {
  133958. sqlite3DropTable(pParse, yymsp[0].minor.yy259, 1, yymsp[-1].minor.yy4);
  133959. }
  133960. break;
  133961. case 79: /* cmd ::= select */
  133962. {
  133963. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  133964. sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
  133965. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
  133966. }
  133967. break;
  133968. case 80: /* select ::= WITH wqlist selectnowith */
  133969. {
  133970. Select *p = yymsp[0].minor.yy387;
  133971. if( p ){
  133972. p->pWith = yymsp[-1].minor.yy451;
  133973. parserDoubleLinkSelect(pParse, p);
  133974. }else{
  133975. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy451);
  133976. }
  133977. yymsp[-2].minor.yy387 = p;
  133978. }
  133979. break;
  133980. case 81: /* select ::= WITH RECURSIVE wqlist selectnowith */
  133981. {
  133982. Select *p = yymsp[0].minor.yy387;
  133983. if( p ){
  133984. p->pWith = yymsp[-1].minor.yy451;
  133985. parserDoubleLinkSelect(pParse, p);
  133986. }else{
  133987. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy451);
  133988. }
  133989. yymsp[-3].minor.yy387 = p;
  133990. }
  133991. break;
  133992. case 82: /* select ::= selectnowith */
  133993. {
  133994. Select *p = yymsp[0].minor.yy387;
  133995. if( p ){
  133996. parserDoubleLinkSelect(pParse, p);
  133997. }
  133998. yymsp[0].minor.yy387 = p; /*A-overwrites-X*/
  133999. }
  134000. break;
  134001. case 83: /* selectnowith ::= selectnowith multiselect_op oneselect */
  134002. {
  134003. Select *pRhs = yymsp[0].minor.yy387;
  134004. Select *pLhs = yymsp[-2].minor.yy387;
  134005. if( pRhs && pRhs->pPrior ){
  134006. SrcList *pFrom;
  134007. Token x;
  134008. x.n = 0;
  134009. parserDoubleLinkSelect(pParse, pRhs);
  134010. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  134011. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
  134012. }
  134013. if( pRhs ){
  134014. pRhs->op = (u8)yymsp[-1].minor.yy4;
  134015. pRhs->pPrior = pLhs;
  134016. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  134017. pRhs->selFlags &= ~SF_MultiValue;
  134018. if( yymsp[-1].minor.yy4!=TK_ALL ) pParse->hasCompound = 1;
  134019. }else{
  134020. sqlite3SelectDelete(pParse->db, pLhs);
  134021. }
  134022. yymsp[-2].minor.yy387 = pRhs;
  134023. }
  134024. break;
  134025. case 84: /* multiselect_op ::= UNION */
  134026. case 86: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==86);
  134027. {yymsp[0].minor.yy4 = yymsp[0].major; /*A-overwrites-OP*/}
  134028. break;
  134029. case 85: /* multiselect_op ::= UNION ALL */
  134030. {yymsp[-1].minor.yy4 = TK_ALL;}
  134031. break;
  134032. case 87: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  134033. {
  134034. #if SELECTTRACE_ENABLED
  134035. Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
  134036. #endif
  134037. yymsp[-8].minor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy259,yymsp[-4].minor.yy314,yymsp[-3].minor.yy322,yymsp[-2].minor.yy314,yymsp[-1].minor.yy322,yymsp[-7].minor.yy4,yymsp[0].minor.yy314);
  134038. #if SELECTTRACE_ENABLED
  134039. /* Populate the Select.zSelName[] string that is used to help with
  134040. ** query planner debugging, to differentiate between multiple Select
  134041. ** objects in a complex query.
  134042. **
  134043. ** If the SELECT keyword is immediately followed by a C-style comment
  134044. ** then extract the first few alphanumeric characters from within that
  134045. ** comment to be the zSelName value. Otherwise, the label is #N where
  134046. ** is an integer that is incremented with each SELECT statement seen.
  134047. */
  134048. if( yymsp[-8].minor.yy387!=0 ){
  134049. const char *z = s.z+6;
  134050. int i;
  134051. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy387->zSelName), yymsp[-8].minor.yy387->zSelName,"#%d",++pParse->nSelect);
  134052. while( z[0]==' ' ) z++;
  134053. if( z[0]=='/' && z[1]=='*' ){
  134054. z += 2;
  134055. while( z[0]==' ' ) z++;
  134056. for(i=0; sqlite3Isalnum(z[i]); i++){}
  134057. sqlite3_snprintf(sizeof(yymsp[-8].minor.yy387->zSelName), yymsp[-8].minor.yy387->zSelName, "%.*s", i, z);
  134058. }
  134059. }
  134060. #endif /* SELECTRACE_ENABLED */
  134061. }
  134062. break;
  134063. case 88: /* values ::= VALUES LP nexprlist RP */
  134064. {
  134065. yymsp[-3].minor.yy387 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values,0);
  134066. }
  134067. break;
  134068. case 89: /* values ::= values COMMA LP exprlist RP */
  134069. {
  134070. Select *pRight, *pLeft = yymsp[-4].minor.yy387;
  134071. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values|SF_MultiValue,0);
  134072. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  134073. if( pRight ){
  134074. pRight->op = TK_ALL;
  134075. pRight->pPrior = pLeft;
  134076. yymsp[-4].minor.yy387 = pRight;
  134077. }else{
  134078. yymsp[-4].minor.yy387 = pLeft;
  134079. }
  134080. }
  134081. break;
  134082. case 90: /* distinct ::= DISTINCT */
  134083. {yymsp[0].minor.yy4 = SF_Distinct;}
  134084. break;
  134085. case 91: /* distinct ::= ALL */
  134086. {yymsp[0].minor.yy4 = SF_All;}
  134087. break;
  134088. case 93: /* sclp ::= */
  134089. case 122: /* orderby_opt ::= */ yytestcase(yyruleno==122);
  134090. case 129: /* groupby_opt ::= */ yytestcase(yyruleno==129);
  134091. case 204: /* exprlist ::= */ yytestcase(yyruleno==204);
  134092. case 207: /* paren_exprlist ::= */ yytestcase(yyruleno==207);
  134093. case 212: /* eidlist_opt ::= */ yytestcase(yyruleno==212);
  134094. {yymsp[1].minor.yy322 = 0;}
  134095. break;
  134096. case 94: /* selcollist ::= sclp scanpt expr scanpt as */
  134097. {
  134098. yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[-2].minor.yy314);
  134099. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy322, &yymsp[0].minor.yy0, 1);
  134100. sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy322,yymsp[-3].minor.yy336,yymsp[-1].minor.yy336);
  134101. }
  134102. break;
  134103. case 95: /* selcollist ::= sclp scanpt STAR */
  134104. {
  134105. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  134106. yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, p);
  134107. }
  134108. break;
  134109. case 96: /* selcollist ::= sclp scanpt nm DOT STAR */
  134110. {
  134111. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
  134112. Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  134113. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  134114. yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, pDot);
  134115. }
  134116. break;
  134117. case 97: /* as ::= AS nm */
  134118. case 108: /* dbnm ::= DOT nm */ yytestcase(yyruleno==108);
  134119. case 226: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==226);
  134120. case 227: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==227);
  134121. {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
  134122. break;
  134123. case 99: /* from ::= */
  134124. {yymsp[1].minor.yy259 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy259));}
  134125. break;
  134126. case 100: /* from ::= FROM seltablist */
  134127. {
  134128. yymsp[-1].minor.yy259 = yymsp[0].minor.yy259;
  134129. sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy259);
  134130. }
  134131. break;
  134132. case 101: /* stl_prefix ::= seltablist joinop */
  134133. {
  134134. if( ALWAYS(yymsp[-1].minor.yy259 && yymsp[-1].minor.yy259->nSrc>0) ) yymsp[-1].minor.yy259->a[yymsp[-1].minor.yy259->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy4;
  134135. }
  134136. break;
  134137. case 102: /* stl_prefix ::= */
  134138. {yymsp[1].minor.yy259 = 0;}
  134139. break;
  134140. case 103: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  134141. {
  134142. yymsp[-6].minor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  134143. sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy259, &yymsp[-2].minor.yy0);
  134144. }
  134145. break;
  134146. case 104: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  134147. {
  134148. yymsp[-8].minor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy259,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  134149. sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy259, yymsp[-4].minor.yy322);
  134150. }
  134151. break;
  134152. case 105: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  134153. {
  134154. yymsp[-6].minor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  134155. }
  134156. break;
  134157. case 106: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  134158. {
  134159. if( yymsp[-6].minor.yy259==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy314==0 && yymsp[0].minor.yy384==0 ){
  134160. yymsp[-6].minor.yy259 = yymsp[-4].minor.yy259;
  134161. }else if( yymsp[-4].minor.yy259->nSrc==1 ){
  134162. yymsp[-6].minor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  134163. if( yymsp[-6].minor.yy259 ){
  134164. struct SrcList_item *pNew = &yymsp[-6].minor.yy259->a[yymsp[-6].minor.yy259->nSrc-1];
  134165. struct SrcList_item *pOld = yymsp[-4].minor.yy259->a;
  134166. pNew->zName = pOld->zName;
  134167. pNew->zDatabase = pOld->zDatabase;
  134168. pNew->pSelect = pOld->pSelect;
  134169. pOld->zName = pOld->zDatabase = 0;
  134170. pOld->pSelect = 0;
  134171. }
  134172. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy259);
  134173. }else{
  134174. Select *pSubquery;
  134175. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy259);
  134176. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy259,0,0,0,0,SF_NestedFrom,0);
  134177. yymsp[-6].minor.yy259 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy259,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy314,yymsp[0].minor.yy384);
  134178. }
  134179. }
  134180. break;
  134181. case 107: /* dbnm ::= */
  134182. case 117: /* indexed_opt ::= */ yytestcase(yyruleno==117);
  134183. {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
  134184. break;
  134185. case 109: /* fullname ::= nm */
  134186. {yymsp[0].minor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
  134187. break;
  134188. case 110: /* fullname ::= nm DOT nm */
  134189. {yymsp[-2].minor.yy259 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
  134190. break;
  134191. case 111: /* joinop ::= COMMA|JOIN */
  134192. { yymsp[0].minor.yy4 = JT_INNER; }
  134193. break;
  134194. case 112: /* joinop ::= JOIN_KW JOIN */
  134195. {yymsp[-1].minor.yy4 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
  134196. break;
  134197. case 113: /* joinop ::= JOIN_KW nm JOIN */
  134198. {yymsp[-2].minor.yy4 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
  134199. break;
  134200. case 114: /* joinop ::= JOIN_KW nm nm JOIN */
  134201. {yymsp[-3].minor.yy4 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
  134202. break;
  134203. case 115: /* on_opt ::= ON expr */
  134204. case 132: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==132);
  134205. case 139: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==139);
  134206. case 200: /* case_else ::= ELSE expr */ yytestcase(yyruleno==200);
  134207. {yymsp[-1].minor.yy314 = yymsp[0].minor.yy314;}
  134208. break;
  134209. case 116: /* on_opt ::= */
  134210. case 131: /* having_opt ::= */ yytestcase(yyruleno==131);
  134211. case 133: /* limit_opt ::= */ yytestcase(yyruleno==133);
  134212. case 138: /* where_opt ::= */ yytestcase(yyruleno==138);
  134213. case 201: /* case_else ::= */ yytestcase(yyruleno==201);
  134214. case 203: /* case_operand ::= */ yytestcase(yyruleno==203);
  134215. {yymsp[1].minor.yy314 = 0;}
  134216. break;
  134217. case 118: /* indexed_opt ::= INDEXED BY nm */
  134218. {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
  134219. break;
  134220. case 119: /* indexed_opt ::= NOT INDEXED */
  134221. {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
  134222. break;
  134223. case 120: /* using_opt ::= USING LP idlist RP */
  134224. {yymsp[-3].minor.yy384 = yymsp[-1].minor.yy384;}
  134225. break;
  134226. case 121: /* using_opt ::= */
  134227. case 149: /* idlist_opt ::= */ yytestcase(yyruleno==149);
  134228. {yymsp[1].minor.yy384 = 0;}
  134229. break;
  134230. case 123: /* orderby_opt ::= ORDER BY sortlist */
  134231. case 130: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==130);
  134232. {yymsp[-2].minor.yy322 = yymsp[0].minor.yy322;}
  134233. break;
  134234. case 124: /* sortlist ::= sortlist COMMA expr sortorder */
  134235. {
  134236. yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322,yymsp[-1].minor.yy314);
  134237. sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy322,yymsp[0].minor.yy4);
  134238. }
  134239. break;
  134240. case 125: /* sortlist ::= expr sortorder */
  134241. {
  134242. yymsp[-1].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy314); /*A-overwrites-Y*/
  134243. sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy322,yymsp[0].minor.yy4);
  134244. }
  134245. break;
  134246. case 126: /* sortorder ::= ASC */
  134247. {yymsp[0].minor.yy4 = SQLITE_SO_ASC;}
  134248. break;
  134249. case 127: /* sortorder ::= DESC */
  134250. {yymsp[0].minor.yy4 = SQLITE_SO_DESC;}
  134251. break;
  134252. case 128: /* sortorder ::= */
  134253. {yymsp[1].minor.yy4 = SQLITE_SO_UNDEFINED;}
  134254. break;
  134255. case 134: /* limit_opt ::= LIMIT expr */
  134256. {yymsp[-1].minor.yy314 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy314,0);}
  134257. break;
  134258. case 135: /* limit_opt ::= LIMIT expr OFFSET expr */
  134259. {yymsp[-3].minor.yy314 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy314,yymsp[0].minor.yy314);}
  134260. break;
  134261. case 136: /* limit_opt ::= LIMIT expr COMMA expr */
  134262. {yymsp[-3].minor.yy314 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy314,yymsp[-2].minor.yy314);}
  134263. break;
  134264. case 137: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  134265. {
  134266. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy259, &yymsp[-1].minor.yy0);
  134267. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy259,yymsp[0].minor.yy314,0,0);
  134268. }
  134269. break;
  134270. case 140: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  134271. {
  134272. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy259, &yymsp[-3].minor.yy0);
  134273. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy322,"set list");
  134274. sqlite3Update(pParse,yymsp[-4].minor.yy259,yymsp[-1].minor.yy322,yymsp[0].minor.yy314,yymsp[-5].minor.yy4,0,0);
  134275. }
  134276. break;
  134277. case 141: /* setlist ::= setlist COMMA nm EQ expr */
  134278. {
  134279. yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy314);
  134280. sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, 1);
  134281. }
  134282. break;
  134283. case 142: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
  134284. {
  134285. yymsp[-6].minor.yy322 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy322, yymsp[-3].minor.yy384, yymsp[0].minor.yy314);
  134286. }
  134287. break;
  134288. case 143: /* setlist ::= nm EQ expr */
  134289. {
  134290. yylhsminor.yy322 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy314);
  134291. sqlite3ExprListSetName(pParse, yylhsminor.yy322, &yymsp[-2].minor.yy0, 1);
  134292. }
  134293. yymsp[-2].minor.yy322 = yylhsminor.yy322;
  134294. break;
  134295. case 144: /* setlist ::= LP idlist RP EQ expr */
  134296. {
  134297. yymsp[-4].minor.yy322 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy384, yymsp[0].minor.yy314);
  134298. }
  134299. break;
  134300. case 145: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
  134301. {
  134302. sqlite3Insert(pParse, yymsp[-2].minor.yy259, yymsp[0].minor.yy387, yymsp[-1].minor.yy384, yymsp[-4].minor.yy4);
  134303. }
  134304. break;
  134305. case 146: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
  134306. {
  134307. sqlite3Insert(pParse, yymsp[-3].minor.yy259, 0, yymsp[-2].minor.yy384, yymsp[-5].minor.yy4);
  134308. }
  134309. break;
  134310. case 150: /* idlist_opt ::= LP idlist RP */
  134311. {yymsp[-2].minor.yy384 = yymsp[-1].minor.yy384;}
  134312. break;
  134313. case 151: /* idlist ::= idlist COMMA nm */
  134314. {yymsp[-2].minor.yy384 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy384,&yymsp[0].minor.yy0);}
  134315. break;
  134316. case 152: /* idlist ::= nm */
  134317. {yymsp[0].minor.yy384 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
  134318. break;
  134319. case 153: /* expr ::= LP expr RP */
  134320. {yymsp[-2].minor.yy314 = yymsp[-1].minor.yy314;}
  134321. break;
  134322. case 154: /* expr ::= ID|INDEXED */
  134323. case 155: /* expr ::= JOIN_KW */ yytestcase(yyruleno==155);
  134324. {yymsp[0].minor.yy314=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  134325. break;
  134326. case 156: /* expr ::= nm DOT nm */
  134327. {
  134328. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  134329. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  134330. yylhsminor.yy314 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
  134331. }
  134332. yymsp[-2].minor.yy314 = yylhsminor.yy314;
  134333. break;
  134334. case 157: /* expr ::= nm DOT nm DOT nm */
  134335. {
  134336. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
  134337. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  134338. Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  134339. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  134340. yylhsminor.yy314 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
  134341. }
  134342. yymsp[-4].minor.yy314 = yylhsminor.yy314;
  134343. break;
  134344. case 158: /* term ::= NULL|FLOAT|BLOB */
  134345. case 159: /* term ::= STRING */ yytestcase(yyruleno==159);
  134346. {yymsp[0].minor.yy314=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  134347. break;
  134348. case 160: /* term ::= INTEGER */
  134349. {
  134350. yylhsminor.yy314 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  134351. }
  134352. yymsp[0].minor.yy314 = yylhsminor.yy314;
  134353. break;
  134354. case 161: /* expr ::= VARIABLE */
  134355. {
  134356. if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
  134357. u32 n = yymsp[0].minor.yy0.n;
  134358. yymsp[0].minor.yy314 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
  134359. sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy314, n);
  134360. }else{
  134361. /* When doing a nested parse, one can include terms in an expression
  134362. ** that look like this: #1 #2 ... These terms refer to registers
  134363. ** in the virtual machine. #N is the N-th register. */
  134364. Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
  134365. assert( t.n>=2 );
  134366. if( pParse->nested==0 ){
  134367. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
  134368. yymsp[0].minor.yy314 = 0;
  134369. }else{
  134370. yymsp[0].minor.yy314 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
  134371. if( yymsp[0].minor.yy314 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy314->iTable);
  134372. }
  134373. }
  134374. }
  134375. break;
  134376. case 162: /* expr ::= expr COLLATE ID|STRING */
  134377. {
  134378. yymsp[-2].minor.yy314 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy314, &yymsp[0].minor.yy0, 1);
  134379. }
  134380. break;
  134381. case 163: /* expr ::= CAST LP expr AS typetoken RP */
  134382. {
  134383. yymsp[-5].minor.yy314 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  134384. sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy314, yymsp[-3].minor.yy314, 0);
  134385. }
  134386. break;
  134387. case 164: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  134388. {
  134389. if( yymsp[-1].minor.yy322 && yymsp[-1].minor.yy322->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  134390. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  134391. }
  134392. yylhsminor.yy314 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0);
  134393. if( yymsp[-2].minor.yy4==SF_Distinct && yylhsminor.yy314 ){
  134394. yylhsminor.yy314->flags |= EP_Distinct;
  134395. }
  134396. }
  134397. yymsp[-4].minor.yy314 = yylhsminor.yy314;
  134398. break;
  134399. case 165: /* expr ::= ID|INDEXED LP STAR RP */
  134400. {
  134401. yylhsminor.yy314 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  134402. }
  134403. yymsp[-3].minor.yy314 = yylhsminor.yy314;
  134404. break;
  134405. case 166: /* term ::= CTIME_KW */
  134406. {
  134407. yylhsminor.yy314 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  134408. }
  134409. yymsp[0].minor.yy314 = yylhsminor.yy314;
  134410. break;
  134411. case 167: /* expr ::= LP nexprlist COMMA expr RP */
  134412. {
  134413. ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy322, yymsp[-1].minor.yy314);
  134414. yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  134415. if( yymsp[-4].minor.yy314 ){
  134416. yymsp[-4].minor.yy314->x.pList = pList;
  134417. }else{
  134418. sqlite3ExprListDelete(pParse->db, pList);
  134419. }
  134420. }
  134421. break;
  134422. case 168: /* expr ::= expr AND expr */
  134423. case 169: /* expr ::= expr OR expr */ yytestcase(yyruleno==169);
  134424. case 170: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==170);
  134425. case 171: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==171);
  134426. case 172: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==172);
  134427. case 173: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==173);
  134428. case 174: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==174);
  134429. case 175: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==175);
  134430. {yymsp[-2].minor.yy314=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy314,yymsp[0].minor.yy314);}
  134431. break;
  134432. case 176: /* likeop ::= NOT LIKE_KW|MATCH */
  134433. {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
  134434. break;
  134435. case 177: /* expr ::= expr likeop expr */
  134436. {
  134437. ExprList *pList;
  134438. int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  134439. yymsp[-1].minor.yy0.n &= 0x7fffffff;
  134440. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy314);
  134441. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy314);
  134442. yymsp[-2].minor.yy314 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0);
  134443. if( bNot ) yymsp[-2].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy314, 0);
  134444. if( yymsp[-2].minor.yy314 ) yymsp[-2].minor.yy314->flags |= EP_InfixFunc;
  134445. }
  134446. break;
  134447. case 178: /* expr ::= expr likeop expr ESCAPE expr */
  134448. {
  134449. ExprList *pList;
  134450. int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  134451. yymsp[-3].minor.yy0.n &= 0x7fffffff;
  134452. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy314);
  134453. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy314);
  134454. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy314);
  134455. yymsp[-4].minor.yy314 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0);
  134456. if( bNot ) yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy314, 0);
  134457. if( yymsp[-4].minor.yy314 ) yymsp[-4].minor.yy314->flags |= EP_InfixFunc;
  134458. }
  134459. break;
  134460. case 179: /* expr ::= expr ISNULL|NOTNULL */
  134461. {yymsp[-1].minor.yy314 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy314,0);}
  134462. break;
  134463. case 180: /* expr ::= expr NOT NULL */
  134464. {yymsp[-2].minor.yy314 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy314,0);}
  134465. break;
  134466. case 181: /* expr ::= expr IS expr */
  134467. {
  134468. yymsp[-2].minor.yy314 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy314,yymsp[0].minor.yy314);
  134469. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy314, yymsp[-2].minor.yy314, TK_ISNULL);
  134470. }
  134471. break;
  134472. case 182: /* expr ::= expr IS NOT expr */
  134473. {
  134474. yymsp[-3].minor.yy314 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy314,yymsp[0].minor.yy314);
  134475. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy314, yymsp[-3].minor.yy314, TK_NOTNULL);
  134476. }
  134477. break;
  134478. case 183: /* expr ::= NOT expr */
  134479. case 184: /* expr ::= BITNOT expr */ yytestcase(yyruleno==184);
  134480. {yymsp[-1].minor.yy314 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy314, 0);/*A-overwrites-B*/}
  134481. break;
  134482. case 185: /* expr ::= MINUS expr */
  134483. {yymsp[-1].minor.yy314 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy314, 0);}
  134484. break;
  134485. case 186: /* expr ::= PLUS expr */
  134486. {yymsp[-1].minor.yy314 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy314, 0);}
  134487. break;
  134488. case 187: /* between_op ::= BETWEEN */
  134489. case 190: /* in_op ::= IN */ yytestcase(yyruleno==190);
  134490. {yymsp[0].minor.yy4 = 0;}
  134491. break;
  134492. case 189: /* expr ::= expr between_op expr AND expr */
  134493. {
  134494. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy314);
  134495. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy314);
  134496. yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy314, 0);
  134497. if( yymsp[-4].minor.yy314 ){
  134498. yymsp[-4].minor.yy314->x.pList = pList;
  134499. }else{
  134500. sqlite3ExprListDelete(pParse->db, pList);
  134501. }
  134502. if( yymsp[-3].minor.yy4 ) yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy314, 0);
  134503. }
  134504. break;
  134505. case 192: /* expr ::= expr in_op LP exprlist RP */
  134506. {
  134507. if( yymsp[-1].minor.yy322==0 ){
  134508. /* Expressions of the form
  134509. **
  134510. ** expr1 IN ()
  134511. ** expr1 NOT IN ()
  134512. **
  134513. ** simplify to constants 0 (false) and 1 (true), respectively,
  134514. ** regardless of the value of expr1.
  134515. */
  134516. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy314);
  134517. yymsp[-4].minor.yy314 = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[yymsp[-3].minor.yy4],1);
  134518. }else if( yymsp[-1].minor.yy322->nExpr==1 ){
  134519. /* Expressions of the form:
  134520. **
  134521. ** expr1 IN (?1)
  134522. ** expr1 NOT IN (?2)
  134523. **
  134524. ** with exactly one value on the RHS can be simplified to something
  134525. ** like this:
  134526. **
  134527. ** expr1 == ?1
  134528. ** expr1 <> ?2
  134529. **
  134530. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  134531. ** so that it may not contribute to the computation of comparison
  134532. ** affinity or the collating sequence to use for comparison. Otherwise,
  134533. ** the semantics would be subtly different from IN or NOT IN.
  134534. */
  134535. Expr *pRHS = yymsp[-1].minor.yy322->a[0].pExpr;
  134536. yymsp[-1].minor.yy322->a[0].pExpr = 0;
  134537. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
  134538. /* pRHS cannot be NULL because a malloc error would have been detected
  134539. ** before now and control would have never reached this point */
  134540. if( ALWAYS(pRHS) ){
  134541. pRHS->flags &= ~EP_Collate;
  134542. pRHS->flags |= EP_Generic;
  134543. }
  134544. yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, yymsp[-3].minor.yy4 ? TK_NE : TK_EQ, yymsp[-4].minor.yy314, pRHS);
  134545. }else{
  134546. yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy314, 0);
  134547. if( yymsp[-4].minor.yy314 ){
  134548. yymsp[-4].minor.yy314->x.pList = yymsp[-1].minor.yy322;
  134549. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy314);
  134550. }else{
  134551. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
  134552. }
  134553. if( yymsp[-3].minor.yy4 ) yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy314, 0);
  134554. }
  134555. }
  134556. break;
  134557. case 193: /* expr ::= LP select RP */
  134558. {
  134559. yymsp[-2].minor.yy314 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  134560. sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy314, yymsp[-1].minor.yy387);
  134561. }
  134562. break;
  134563. case 194: /* expr ::= expr in_op LP select RP */
  134564. {
  134565. yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy314, 0);
  134566. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy314, yymsp[-1].minor.yy387);
  134567. if( yymsp[-3].minor.yy4 ) yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy314, 0);
  134568. }
  134569. break;
  134570. case 195: /* expr ::= expr in_op nm dbnm paren_exprlist */
  134571. {
  134572. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
  134573. Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
  134574. if( yymsp[0].minor.yy322 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy322);
  134575. yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy314, 0);
  134576. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy314, pSelect);
  134577. if( yymsp[-3].minor.yy4 ) yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy314, 0);
  134578. }
  134579. break;
  134580. case 196: /* expr ::= EXISTS LP select RP */
  134581. {
  134582. Expr *p;
  134583. p = yymsp[-3].minor.yy314 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
  134584. sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy387);
  134585. }
  134586. break;
  134587. case 197: /* expr ::= CASE case_operand case_exprlist case_else END */
  134588. {
  134589. yymsp[-4].minor.yy314 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy314, 0);
  134590. if( yymsp[-4].minor.yy314 ){
  134591. yymsp[-4].minor.yy314->x.pList = yymsp[-1].minor.yy314 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[-1].minor.yy314) : yymsp[-2].minor.yy322;
  134592. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy314);
  134593. }else{
  134594. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
  134595. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy314);
  134596. }
  134597. }
  134598. break;
  134599. case 198: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  134600. {
  134601. yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy314);
  134602. yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[0].minor.yy314);
  134603. }
  134604. break;
  134605. case 199: /* case_exprlist ::= WHEN expr THEN expr */
  134606. {
  134607. yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy314);
  134608. yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, yymsp[0].minor.yy314);
  134609. }
  134610. break;
  134611. case 202: /* case_operand ::= expr */
  134612. {yymsp[0].minor.yy314 = yymsp[0].minor.yy314; /*A-overwrites-X*/}
  134613. break;
  134614. case 205: /* nexprlist ::= nexprlist COMMA expr */
  134615. {yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy314);}
  134616. break;
  134617. case 206: /* nexprlist ::= expr */
  134618. {yymsp[0].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy314); /*A-overwrites-Y*/}
  134619. break;
  134620. case 208: /* paren_exprlist ::= LP exprlist RP */
  134621. case 213: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==213);
  134622. {yymsp[-2].minor.yy322 = yymsp[-1].minor.yy322;}
  134623. break;
  134624. case 209: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  134625. {
  134626. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  134627. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy322, yymsp[-10].minor.yy4,
  134628. &yymsp[-11].minor.yy0, yymsp[0].minor.yy314, SQLITE_SO_ASC, yymsp[-8].minor.yy4, SQLITE_IDXTYPE_APPDEF);
  134629. }
  134630. break;
  134631. case 210: /* uniqueflag ::= UNIQUE */
  134632. case 250: /* raisetype ::= ABORT */ yytestcase(yyruleno==250);
  134633. {yymsp[0].minor.yy4 = OE_Abort;}
  134634. break;
  134635. case 211: /* uniqueflag ::= */
  134636. {yymsp[1].minor.yy4 = OE_None;}
  134637. break;
  134638. case 214: /* eidlist ::= eidlist COMMA nm collate sortorder */
  134639. {
  134640. yymsp[-4].minor.yy322 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy4, yymsp[0].minor.yy4);
  134641. }
  134642. break;
  134643. case 215: /* eidlist ::= nm collate sortorder */
  134644. {
  134645. yymsp[-2].minor.yy322 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy4, yymsp[0].minor.yy4); /*A-overwrites-Y*/
  134646. }
  134647. break;
  134648. case 218: /* cmd ::= DROP INDEX ifexists fullname */
  134649. {sqlite3DropIndex(pParse, yymsp[0].minor.yy259, yymsp[-1].minor.yy4);}
  134650. break;
  134651. case 219: /* cmd ::= VACUUM */
  134652. {sqlite3Vacuum(pParse,0);}
  134653. break;
  134654. case 220: /* cmd ::= VACUUM nm */
  134655. {sqlite3Vacuum(pParse,&yymsp[0].minor.yy0);}
  134656. break;
  134657. case 221: /* cmd ::= PRAGMA nm dbnm */
  134658. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  134659. break;
  134660. case 222: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  134661. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  134662. break;
  134663. case 223: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  134664. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  134665. break;
  134666. case 224: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  134667. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  134668. break;
  134669. case 225: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  134670. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  134671. break;
  134672. case 228: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  134673. {
  134674. Token all;
  134675. all.z = yymsp[-3].minor.yy0.z;
  134676. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  134677. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy203, &all);
  134678. }
  134679. break;
  134680. case 229: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  134681. {
  134682. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy4, yymsp[-4].minor.yy90.a, yymsp[-4].minor.yy90.b, yymsp[-2].minor.yy259, yymsp[0].minor.yy314, yymsp[-10].minor.yy4, yymsp[-8].minor.yy4);
  134683. yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
  134684. }
  134685. break;
  134686. case 230: /* trigger_time ::= BEFORE|AFTER */
  134687. { yymsp[0].minor.yy4 = yymsp[0].major; /*A-overwrites-X*/ }
  134688. break;
  134689. case 231: /* trigger_time ::= INSTEAD OF */
  134690. { yymsp[-1].minor.yy4 = TK_INSTEAD;}
  134691. break;
  134692. case 232: /* trigger_time ::= */
  134693. { yymsp[1].minor.yy4 = TK_BEFORE; }
  134694. break;
  134695. case 233: /* trigger_event ::= DELETE|INSERT */
  134696. case 234: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==234);
  134697. {yymsp[0].minor.yy90.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy90.b = 0;}
  134698. break;
  134699. case 235: /* trigger_event ::= UPDATE OF idlist */
  134700. {yymsp[-2].minor.yy90.a = TK_UPDATE; yymsp[-2].minor.yy90.b = yymsp[0].minor.yy384;}
  134701. break;
  134702. case 236: /* when_clause ::= */
  134703. case 255: /* key_opt ::= */ yytestcase(yyruleno==255);
  134704. { yymsp[1].minor.yy314 = 0; }
  134705. break;
  134706. case 237: /* when_clause ::= WHEN expr */
  134707. case 256: /* key_opt ::= KEY expr */ yytestcase(yyruleno==256);
  134708. { yymsp[-1].minor.yy314 = yymsp[0].minor.yy314; }
  134709. break;
  134710. case 238: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  134711. {
  134712. assert( yymsp[-2].minor.yy203!=0 );
  134713. yymsp[-2].minor.yy203->pLast->pNext = yymsp[-1].minor.yy203;
  134714. yymsp[-2].minor.yy203->pLast = yymsp[-1].minor.yy203;
  134715. }
  134716. break;
  134717. case 239: /* trigger_cmd_list ::= trigger_cmd SEMI */
  134718. {
  134719. assert( yymsp[-1].minor.yy203!=0 );
  134720. yymsp[-1].minor.yy203->pLast = yymsp[-1].minor.yy203;
  134721. }
  134722. break;
  134723. case 240: /* trnm ::= nm DOT nm */
  134724. {
  134725. yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  134726. sqlite3ErrorMsg(pParse,
  134727. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  134728. "statements within triggers");
  134729. }
  134730. break;
  134731. case 241: /* tridxby ::= INDEXED BY nm */
  134732. {
  134733. sqlite3ErrorMsg(pParse,
  134734. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  134735. "within triggers");
  134736. }
  134737. break;
  134738. case 242: /* tridxby ::= NOT INDEXED */
  134739. {
  134740. sqlite3ErrorMsg(pParse,
  134741. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  134742. "within triggers");
  134743. }
  134744. break;
  134745. case 243: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  134746. {yylhsminor.yy203 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy322, yymsp[-1].minor.yy314, yymsp[-6].minor.yy4, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy336);}
  134747. yymsp[-7].minor.yy203 = yylhsminor.yy203;
  134748. break;
  134749. case 244: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select scanpt */
  134750. {yylhsminor.yy203 = sqlite3TriggerInsertStep(pParse->db,&yymsp[-3].minor.yy0,yymsp[-2].minor.yy384,yymsp[-1].minor.yy387,yymsp[-5].minor.yy4,yymsp[-6].minor.yy336,yymsp[0].minor.yy336);/*yylhsminor.yy203-overwrites-yymsp[-5].minor.yy4*/}
  134751. yymsp[-6].minor.yy203 = yylhsminor.yy203;
  134752. break;
  134753. case 245: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  134754. {yylhsminor.yy203 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy314, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy336);}
  134755. yymsp[-5].minor.yy203 = yylhsminor.yy203;
  134756. break;
  134757. case 246: /* trigger_cmd ::= scanpt select scanpt */
  134758. {yylhsminor.yy203 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy387, yymsp[-2].minor.yy336, yymsp[0].minor.yy336); /*yylhsminor.yy203-overwrites-yymsp[-1].minor.yy387*/}
  134759. yymsp[-2].minor.yy203 = yylhsminor.yy203;
  134760. break;
  134761. case 247: /* expr ::= RAISE LP IGNORE RP */
  134762. {
  134763. yymsp[-3].minor.yy314 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  134764. if( yymsp[-3].minor.yy314 ){
  134765. yymsp[-3].minor.yy314->affinity = OE_Ignore;
  134766. }
  134767. }
  134768. break;
  134769. case 248: /* expr ::= RAISE LP raisetype COMMA nm RP */
  134770. {
  134771. yymsp[-5].minor.yy314 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  134772. if( yymsp[-5].minor.yy314 ) {
  134773. yymsp[-5].minor.yy314->affinity = (char)yymsp[-3].minor.yy4;
  134774. }
  134775. }
  134776. break;
  134777. case 249: /* raisetype ::= ROLLBACK */
  134778. {yymsp[0].minor.yy4 = OE_Rollback;}
  134779. break;
  134780. case 251: /* raisetype ::= FAIL */
  134781. {yymsp[0].minor.yy4 = OE_Fail;}
  134782. break;
  134783. case 252: /* cmd ::= DROP TRIGGER ifexists fullname */
  134784. {
  134785. sqlite3DropTrigger(pParse,yymsp[0].minor.yy259,yymsp[-1].minor.yy4);
  134786. }
  134787. break;
  134788. case 253: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  134789. {
  134790. sqlite3Attach(pParse, yymsp[-3].minor.yy314, yymsp[-1].minor.yy314, yymsp[0].minor.yy314);
  134791. }
  134792. break;
  134793. case 254: /* cmd ::= DETACH database_kw_opt expr */
  134794. {
  134795. sqlite3Detach(pParse, yymsp[0].minor.yy314);
  134796. }
  134797. break;
  134798. case 257: /* cmd ::= REINDEX */
  134799. {sqlite3Reindex(pParse, 0, 0);}
  134800. break;
  134801. case 258: /* cmd ::= REINDEX nm dbnm */
  134802. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  134803. break;
  134804. case 259: /* cmd ::= ANALYZE */
  134805. {sqlite3Analyze(pParse, 0, 0);}
  134806. break;
  134807. case 260: /* cmd ::= ANALYZE nm dbnm */
  134808. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  134809. break;
  134810. case 261: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  134811. {
  134812. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy259,&yymsp[0].minor.yy0);
  134813. }
  134814. break;
  134815. case 262: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  134816. {
  134817. yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  134818. sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
  134819. }
  134820. break;
  134821. case 263: /* add_column_fullname ::= fullname */
  134822. {
  134823. disableLookaside(pParse);
  134824. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy259);
  134825. }
  134826. break;
  134827. case 264: /* cmd ::= create_vtab */
  134828. {sqlite3VtabFinishParse(pParse,0);}
  134829. break;
  134830. case 265: /* cmd ::= create_vtab LP vtabarglist RP */
  134831. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  134832. break;
  134833. case 266: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  134834. {
  134835. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy4);
  134836. }
  134837. break;
  134838. case 267: /* vtabarg ::= */
  134839. {sqlite3VtabArgInit(pParse);}
  134840. break;
  134841. case 268: /* vtabargtoken ::= ANY */
  134842. case 269: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==269);
  134843. case 270: /* lp ::= LP */ yytestcase(yyruleno==270);
  134844. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  134845. break;
  134846. case 271: /* with ::= WITH wqlist */
  134847. case 272: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==272);
  134848. { sqlite3WithPush(pParse, yymsp[0].minor.yy451, 1); }
  134849. break;
  134850. case 273: /* wqlist ::= nm eidlist_opt AS LP select RP */
  134851. {
  134852. yymsp[-5].minor.yy451 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy387); /*A-overwrites-X*/
  134853. }
  134854. break;
  134855. case 274: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  134856. {
  134857. yymsp[-7].minor.yy451 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy451, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].minor.yy387);
  134858. }
  134859. break;
  134860. default:
  134861. /* (275) input ::= cmdlist */ yytestcase(yyruleno==275);
  134862. /* (276) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==276);
  134863. /* (277) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=277);
  134864. /* (278) ecmd ::= SEMI */ yytestcase(yyruleno==278);
  134865. /* (279) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==279);
  134866. /* (280) explain ::= */ yytestcase(yyruleno==280);
  134867. /* (281) trans_opt ::= */ yytestcase(yyruleno==281);
  134868. /* (282) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==282);
  134869. /* (283) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==283);
  134870. /* (284) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==284);
  134871. /* (285) savepoint_opt ::= */ yytestcase(yyruleno==285);
  134872. /* (286) cmd ::= create_table create_table_args */ yytestcase(yyruleno==286);
  134873. /* (287) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==287);
  134874. /* (288) columnlist ::= columnname carglist */ yytestcase(yyruleno==288);
  134875. /* (289) nm ::= ID|INDEXED */ yytestcase(yyruleno==289);
  134876. /* (290) nm ::= STRING */ yytestcase(yyruleno==290);
  134877. /* (291) nm ::= JOIN_KW */ yytestcase(yyruleno==291);
  134878. /* (292) typetoken ::= typename */ yytestcase(yyruleno==292);
  134879. /* (293) typename ::= ID|STRING */ yytestcase(yyruleno==293);
  134880. /* (294) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=294);
  134881. /* (295) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=295);
  134882. /* (296) carglist ::= carglist ccons */ yytestcase(yyruleno==296);
  134883. /* (297) carglist ::= */ yytestcase(yyruleno==297);
  134884. /* (298) ccons ::= NULL onconf */ yytestcase(yyruleno==298);
  134885. /* (299) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==299);
  134886. /* (300) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==300);
  134887. /* (301) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=301);
  134888. /* (302) tconscomma ::= */ yytestcase(yyruleno==302);
  134889. /* (303) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=303);
  134890. /* (304) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=304);
  134891. /* (305) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=305);
  134892. /* (306) oneselect ::= values */ yytestcase(yyruleno==306);
  134893. /* (307) sclp ::= selcollist COMMA */ yytestcase(yyruleno==307);
  134894. /* (308) as ::= ID|STRING */ yytestcase(yyruleno==308);
  134895. /* (309) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=309);
  134896. /* (310) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==310);
  134897. /* (311) exprlist ::= nexprlist */ yytestcase(yyruleno==311);
  134898. /* (312) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=312);
  134899. /* (313) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=313);
  134900. /* (314) nmnum ::= ON */ yytestcase(yyruleno==314);
  134901. /* (315) nmnum ::= DELETE */ yytestcase(yyruleno==315);
  134902. /* (316) nmnum ::= DEFAULT */ yytestcase(yyruleno==316);
  134903. /* (317) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==317);
  134904. /* (318) foreach_clause ::= */ yytestcase(yyruleno==318);
  134905. /* (319) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==319);
  134906. /* (320) trnm ::= nm */ yytestcase(yyruleno==320);
  134907. /* (321) tridxby ::= */ yytestcase(yyruleno==321);
  134908. /* (322) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==322);
  134909. /* (323) database_kw_opt ::= */ yytestcase(yyruleno==323);
  134910. /* (324) kwcolumn_opt ::= */ yytestcase(yyruleno==324);
  134911. /* (325) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==325);
  134912. /* (326) vtabarglist ::= vtabarg */ yytestcase(yyruleno==326);
  134913. /* (327) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==327);
  134914. /* (328) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==328);
  134915. /* (329) anylist ::= */ yytestcase(yyruleno==329);
  134916. /* (330) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==330);
  134917. /* (331) anylist ::= anylist ANY */ yytestcase(yyruleno==331);
  134918. /* (332) with ::= */ yytestcase(yyruleno==332);
  134919. break;
  134920. /********** End reduce actions ************************************************/
  134921. };
  134922. assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  134923. yygoto = yyRuleInfo[yyruleno].lhs;
  134924. yysize = yyRuleInfo[yyruleno].nrhs;
  134925. yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
  134926. /* There are no SHIFTREDUCE actions on nonterminals because the table
  134927. ** generator has simplified them to pure REDUCE actions. */
  134928. assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
  134929. /* It is not possible for a REDUCE to be followed by an error */
  134930. assert( yyact!=YY_ERROR_ACTION );
  134931. yymsp += yysize+1;
  134932. yypParser->yytos = yymsp;
  134933. yymsp->stateno = (YYACTIONTYPE)yyact;
  134934. yymsp->major = (YYCODETYPE)yygoto;
  134935. yyTraceShift(yypParser, yyact, "... then shift");
  134936. }
  134937. /*
  134938. ** The following code executes when the parse fails
  134939. */
  134940. #ifndef YYNOERRORRECOVERY
  134941. static void yy_parse_failed(
  134942. yyParser *yypParser /* The parser */
  134943. ){
  134944. sqlite3ParserARG_FETCH;
  134945. #ifndef NDEBUG
  134946. if( yyTraceFILE ){
  134947. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  134948. }
  134949. #endif
  134950. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  134951. /* Here code is inserted which will be executed whenever the
  134952. ** parser fails */
  134953. /************ Begin %parse_failure code ***************************************/
  134954. /************ End %parse_failure code *****************************************/
  134955. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  134956. }
  134957. #endif /* YYNOERRORRECOVERY */
  134958. /*
  134959. ** The following code executes when a syntax error first occurs.
  134960. */
  134961. static void yy_syntax_error(
  134962. yyParser *yypParser, /* The parser */
  134963. int yymajor, /* The major type of the error token */
  134964. sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
  134965. ){
  134966. sqlite3ParserARG_FETCH;
  134967. #define TOKEN yyminor
  134968. /************ Begin %syntax_error code ****************************************/
  134969. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  134970. if( TOKEN.z[0] ){
  134971. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  134972. }else{
  134973. sqlite3ErrorMsg(pParse, "incomplete input");
  134974. }
  134975. /************ End %syntax_error code ******************************************/
  134976. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  134977. }
  134978. /*
  134979. ** The following is executed when the parser accepts
  134980. */
  134981. static void yy_accept(
  134982. yyParser *yypParser /* The parser */
  134983. ){
  134984. sqlite3ParserARG_FETCH;
  134985. #ifndef NDEBUG
  134986. if( yyTraceFILE ){
  134987. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  134988. }
  134989. #endif
  134990. #ifndef YYNOERRORRECOVERY
  134991. yypParser->yyerrcnt = -1;
  134992. #endif
  134993. assert( yypParser->yytos==yypParser->yystack );
  134994. /* Here code is inserted which will be executed whenever the
  134995. ** parser accepts */
  134996. /*********** Begin %parse_accept code *****************************************/
  134997. /*********** End %parse_accept code *******************************************/
  134998. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  134999. }
  135000. /* The main parser program.
  135001. ** The first argument is a pointer to a structure obtained from
  135002. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  135003. ** The second argument is the major token number. The third is
  135004. ** the minor token. The fourth optional argument is whatever the
  135005. ** user wants (and specified in the grammar) and is available for
  135006. ** use by the action routines.
  135007. **
  135008. ** Inputs:
  135009. ** <ul>
  135010. ** <li> A pointer to the parser (an opaque structure.)
  135011. ** <li> The major token number.
  135012. ** <li> The minor token number.
  135013. ** <li> An option argument of a grammar-specified type.
  135014. ** </ul>
  135015. **
  135016. ** Outputs:
  135017. ** None.
  135018. */
  135019. SQLITE_PRIVATE void sqlite3Parser(
  135020. void *yyp, /* The parser */
  135021. int yymajor, /* The major token code number */
  135022. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  135023. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  135024. ){
  135025. YYMINORTYPE yyminorunion;
  135026. unsigned int yyact; /* The parser action. */
  135027. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  135028. int yyendofinput; /* True if we are at the end of input */
  135029. #endif
  135030. #ifdef YYERRORSYMBOL
  135031. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  135032. #endif
  135033. yyParser *yypParser; /* The parser */
  135034. yypParser = (yyParser*)yyp;
  135035. assert( yypParser->yytos!=0 );
  135036. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  135037. yyendofinput = (yymajor==0);
  135038. #endif
  135039. sqlite3ParserARG_STORE;
  135040. #ifndef NDEBUG
  135041. if( yyTraceFILE ){
  135042. int stateno = yypParser->yytos->stateno;
  135043. if( stateno < YY_MIN_REDUCE ){
  135044. fprintf(yyTraceFILE,"%sInput '%s' in state %d\n",
  135045. yyTracePrompt,yyTokenName[yymajor],stateno);
  135046. }else{
  135047. fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  135048. yyTracePrompt,yyTokenName[yymajor],stateno-YY_MIN_REDUCE);
  135049. }
  135050. }
  135051. #endif
  135052. do{
  135053. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  135054. if( yyact >= YY_MIN_REDUCE ){
  135055. yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor,yyminor);
  135056. }else if( yyact <= YY_MAX_SHIFTREDUCE ){
  135057. yy_shift(yypParser,yyact,yymajor,yyminor);
  135058. #ifndef YYNOERRORRECOVERY
  135059. yypParser->yyerrcnt--;
  135060. #endif
  135061. yymajor = YYNOCODE;
  135062. }else if( yyact==YY_ACCEPT_ACTION ){
  135063. yypParser->yytos--;
  135064. yy_accept(yypParser);
  135065. return;
  135066. }else{
  135067. assert( yyact == YY_ERROR_ACTION );
  135068. yyminorunion.yy0 = yyminor;
  135069. #ifdef YYERRORSYMBOL
  135070. int yymx;
  135071. #endif
  135072. #ifndef NDEBUG
  135073. if( yyTraceFILE ){
  135074. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  135075. }
  135076. #endif
  135077. #ifdef YYERRORSYMBOL
  135078. /* A syntax error has occurred.
  135079. ** The response to an error depends upon whether or not the
  135080. ** grammar defines an error token "ERROR".
  135081. **
  135082. ** This is what we do if the grammar does define ERROR:
  135083. **
  135084. ** * Call the %syntax_error function.
  135085. **
  135086. ** * Begin popping the stack until we enter a state where
  135087. ** it is legal to shift the error symbol, then shift
  135088. ** the error symbol.
  135089. **
  135090. ** * Set the error count to three.
  135091. **
  135092. ** * Begin accepting and shifting new tokens. No new error
  135093. ** processing will occur until three tokens have been
  135094. ** shifted successfully.
  135095. **
  135096. */
  135097. if( yypParser->yyerrcnt<0 ){
  135098. yy_syntax_error(yypParser,yymajor,yyminor);
  135099. }
  135100. yymx = yypParser->yytos->major;
  135101. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  135102. #ifndef NDEBUG
  135103. if( yyTraceFILE ){
  135104. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  135105. yyTracePrompt,yyTokenName[yymajor]);
  135106. }
  135107. #endif
  135108. yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
  135109. yymajor = YYNOCODE;
  135110. }else{
  135111. while( yypParser->yytos >= yypParser->yystack
  135112. && yymx != YYERRORSYMBOL
  135113. && (yyact = yy_find_reduce_action(
  135114. yypParser->yytos->stateno,
  135115. YYERRORSYMBOL)) >= YY_MIN_REDUCE
  135116. ){
  135117. yy_pop_parser_stack(yypParser);
  135118. }
  135119. if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
  135120. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  135121. yy_parse_failed(yypParser);
  135122. #ifndef YYNOERRORRECOVERY
  135123. yypParser->yyerrcnt = -1;
  135124. #endif
  135125. yymajor = YYNOCODE;
  135126. }else if( yymx!=YYERRORSYMBOL ){
  135127. yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
  135128. }
  135129. }
  135130. yypParser->yyerrcnt = 3;
  135131. yyerrorhit = 1;
  135132. #elif defined(YYNOERRORRECOVERY)
  135133. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  135134. ** do any kind of error recovery. Instead, simply invoke the syntax
  135135. ** error routine and continue going as if nothing had happened.
  135136. **
  135137. ** Applications can set this macro (for example inside %include) if
  135138. ** they intend to abandon the parse upon the first syntax error seen.
  135139. */
  135140. yy_syntax_error(yypParser,yymajor, yyminor);
  135141. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  135142. yymajor = YYNOCODE;
  135143. #else /* YYERRORSYMBOL is not defined */
  135144. /* This is what we do if the grammar does not define ERROR:
  135145. **
  135146. ** * Report an error message, and throw away the input token.
  135147. **
  135148. ** * If the input token is $, then fail the parse.
  135149. **
  135150. ** As before, subsequent error messages are suppressed until
  135151. ** three input tokens have been successfully shifted.
  135152. */
  135153. if( yypParser->yyerrcnt<=0 ){
  135154. yy_syntax_error(yypParser,yymajor, yyminor);
  135155. }
  135156. yypParser->yyerrcnt = 3;
  135157. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  135158. if( yyendofinput ){
  135159. yy_parse_failed(yypParser);
  135160. #ifndef YYNOERRORRECOVERY
  135161. yypParser->yyerrcnt = -1;
  135162. #endif
  135163. }
  135164. yymajor = YYNOCODE;
  135165. #endif
  135166. }
  135167. }while( yymajor!=YYNOCODE && yypParser->yytos>yypParser->yystack );
  135168. #ifndef NDEBUG
  135169. if( yyTraceFILE ){
  135170. yyStackEntry *i;
  135171. char cDiv = '[';
  135172. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  135173. for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
  135174. fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
  135175. cDiv = ' ';
  135176. }
  135177. fprintf(yyTraceFILE,"]\n");
  135178. }
  135179. #endif
  135180. return;
  135181. }
  135182. /************** End of parse.c ***********************************************/
  135183. /************** Begin file tokenize.c ****************************************/
  135184. /*
  135185. ** 2001 September 15
  135186. **
  135187. ** The author disclaims copyright to this source code. In place of
  135188. ** a legal notice, here is a blessing:
  135189. **
  135190. ** May you do good and not evil.
  135191. ** May you find forgiveness for yourself and forgive others.
  135192. ** May you share freely, never taking more than you give.
  135193. **
  135194. *************************************************************************
  135195. ** An tokenizer for SQL
  135196. **
  135197. ** This file contains C code that splits an SQL input string up into
  135198. ** individual tokens and sends those tokens one-by-one over to the
  135199. ** parser for analysis.
  135200. */
  135201. /* #include "sqliteInt.h" */
  135202. /* #include <stdlib.h> */
  135203. /* Character classes for tokenizing
  135204. **
  135205. ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
  135206. ** using a lookup table, whereas a switch() directly on c uses a binary search.
  135207. ** The lookup table is much faster. To maximize speed, and to ensure that
  135208. ** a lookup table is used, all of the classes need to be small integers and
  135209. ** all of them need to be used within the switch.
  135210. */
  135211. #define CC_X 0 /* The letter 'x', or start of BLOB literal */
  135212. #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
  135213. #define CC_ID 2 /* unicode characters usable in IDs */
  135214. #define CC_DIGIT 3 /* Digits */
  135215. #define CC_DOLLAR 4 /* '$' */
  135216. #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
  135217. #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
  135218. #define CC_SPACE 7 /* Space characters */
  135219. #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
  135220. #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
  135221. #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
  135222. #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
  135223. #define CC_LT 12 /* '<'. Part of < or <= or <> */
  135224. #define CC_GT 13 /* '>'. Part of > or >= */
  135225. #define CC_EQ 14 /* '='. Part of = or == */
  135226. #define CC_BANG 15 /* '!'. Part of != */
  135227. #define CC_SLASH 16 /* '/'. / or c-style comment */
  135228. #define CC_LP 17 /* '(' */
  135229. #define CC_RP 18 /* ')' */
  135230. #define CC_SEMI 19 /* ';' */
  135231. #define CC_PLUS 20 /* '+' */
  135232. #define CC_STAR 21 /* '*' */
  135233. #define CC_PERCENT 22 /* '%' */
  135234. #define CC_COMMA 23 /* ',' */
  135235. #define CC_AND 24 /* '&' */
  135236. #define CC_TILDA 25 /* '~' */
  135237. #define CC_DOT 26 /* '.' */
  135238. #define CC_ILLEGAL 27 /* Illegal character */
  135239. static const unsigned char aiClass[] = {
  135240. #ifdef SQLITE_ASCII
  135241. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  135242. /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
  135243. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  135244. /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
  135245. /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
  135246. /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  135247. /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
  135248. /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  135249. /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
  135250. /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  135251. /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  135252. /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  135253. /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  135254. /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  135255. /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  135256. /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  135257. /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
  135258. #endif
  135259. #ifdef SQLITE_EBCDIC
  135260. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  135261. /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
  135262. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  135263. /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  135264. /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  135265. /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
  135266. /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
  135267. /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
  135268. /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
  135269. /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  135270. /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  135271. /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  135272. /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
  135273. /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  135274. /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  135275. /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  135276. /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
  135277. #endif
  135278. };
  135279. /*
  135280. ** The charMap() macro maps alphabetic characters (only) into their
  135281. ** lower-case ASCII equivalent. On ASCII machines, this is just
  135282. ** an upper-to-lower case map. On EBCDIC machines we also need
  135283. ** to adjust the encoding. The mapping is only valid for alphabetics
  135284. ** which are the only characters for which this feature is used.
  135285. **
  135286. ** Used by keywordhash.h
  135287. */
  135288. #ifdef SQLITE_ASCII
  135289. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  135290. #endif
  135291. #ifdef SQLITE_EBCDIC
  135292. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  135293. const unsigned char ebcdicToAscii[] = {
  135294. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  135295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  135296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  135297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  135298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  135299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  135300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  135301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  135302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  135303. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  135304. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  135305. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  135306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  135307. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  135308. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  135309. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  135310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  135311. };
  135312. #endif
  135313. /*
  135314. ** The sqlite3KeywordCode function looks up an identifier to determine if
  135315. ** it is a keyword. If it is a keyword, the token code of that keyword is
  135316. ** returned. If the input is not a keyword, TK_ID is returned.
  135317. **
  135318. ** The implementation of this routine was generated by a program,
  135319. ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
  135320. ** The output of the mkkeywordhash.c program is written into a file
  135321. ** named keywordhash.h and then included into this source file by
  135322. ** the #include below.
  135323. */
  135324. /************** Include keywordhash.h in the middle of tokenize.c ************/
  135325. /************** Begin file keywordhash.h *************************************/
  135326. /***** This file contains automatically generated code ******
  135327. **
  135328. ** The code in this file has been automatically generated by
  135329. **
  135330. ** sqlite/tool/mkkeywordhash.c
  135331. **
  135332. ** The code in this file implements a function that determines whether
  135333. ** or not a given identifier is really an SQL keyword. The same thing
  135334. ** might be implemented more directly using a hand-written hash table.
  135335. ** But by using this automatically generated code, the size of the code
  135336. ** is substantially reduced. This is important for embedded applications
  135337. ** on platforms with limited memory.
  135338. */
  135339. /* Hash score: 182 */
  135340. /* zKWText[] encodes 834 bytes of keyword text in 554 bytes */
  135341. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  135342. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  135343. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  135344. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  135345. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  135346. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  135347. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  135348. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  135349. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  135350. /* VACUUMVIEWINITIALLY */
  135351. static const char zKWText[553] = {
  135352. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  135353. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  135354. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  135355. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  135356. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  135357. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  135358. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  135359. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  135360. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  135361. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  135362. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  135363. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  135364. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  135365. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  135366. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  135367. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  135368. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  135369. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  135370. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  135371. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  135372. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  135373. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  135374. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  135375. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  135376. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  135377. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  135378. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  135379. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  135380. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  135381. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  135382. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  135383. };
  135384. /* aKWHash[i] is the hash value for the i-th keyword */
  135385. static const unsigned char aKWHash[127] = {
  135386. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  135387. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  135388. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  135389. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  135390. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  135391. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  135392. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  135393. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  135394. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  135395. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  135396. };
  135397. /* aKWNext[] forms the hash collision chain. If aKWHash[i]==0
  135398. ** then the i-th keyword has no more hash collisions. Otherwise,
  135399. ** the next keyword with the same hash is aKWHash[i]-1. */
  135400. static const unsigned char aKWNext[124] = {
  135401. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  135402. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  135403. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135404. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  135405. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  135406. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  135407. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  135408. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  135409. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  135410. 73, 83, 0, 35, 68, 0, 0,
  135411. };
  135412. /* aKWLen[i] is the length (in bytes) of the i-th keyword */
  135413. static const unsigned char aKWLen[124] = {
  135414. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  135415. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  135416. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  135417. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  135418. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  135419. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  135420. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  135421. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  135422. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  135423. 3, 5, 5, 6, 4, 9, 3,
  135424. };
  135425. /* aKWOffset[i] is the index into zKWText[] of the start of
  135426. ** the text for the i-th keyword. */
  135427. static const unsigned short int aKWOffset[124] = {
  135428. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  135429. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  135430. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  135431. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  135432. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  135433. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  135434. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  135435. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  135436. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  135437. 521, 524, 529, 534, 540, 544, 549,
  135438. };
  135439. /* aKWCode[i] is the parser symbol code for the i-th keyword */
  135440. static const unsigned char aKWCode[124] = {
  135441. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  135442. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  135443. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  135444. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  135445. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  135446. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  135447. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  135448. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  135449. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  135450. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  135451. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  135452. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  135453. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  135454. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  135455. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  135456. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  135457. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  135458. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  135459. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  135460. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  135461. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  135462. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  135463. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  135464. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  135465. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  135466. };
  135467. /* Check to see if z[0..n-1] is a keyword. If it is, write the
  135468. ** parser symbol code for that keyword into *pType. Always
  135469. ** return the integer n (the length of the token). */
  135470. static int keywordCode(const char *z, int n, int *pType){
  135471. int i, j;
  135472. const char *zKW;
  135473. if( n>=2 ){
  135474. i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  135475. for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
  135476. if( aKWLen[i]!=n ) continue;
  135477. j = 0;
  135478. zKW = &zKWText[aKWOffset[i]];
  135479. #ifdef SQLITE_ASCII
  135480. while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
  135481. #endif
  135482. #ifdef SQLITE_EBCDIC
  135483. while( j<n && toupper(z[j])==zKW[j] ){ j++; }
  135484. #endif
  135485. if( j<n ) continue;
  135486. testcase( i==0 ); /* REINDEX */
  135487. testcase( i==1 ); /* INDEXED */
  135488. testcase( i==2 ); /* INDEX */
  135489. testcase( i==3 ); /* DESC */
  135490. testcase( i==4 ); /* ESCAPE */
  135491. testcase( i==5 ); /* EACH */
  135492. testcase( i==6 ); /* CHECK */
  135493. testcase( i==7 ); /* KEY */
  135494. testcase( i==8 ); /* BEFORE */
  135495. testcase( i==9 ); /* FOREIGN */
  135496. testcase( i==10 ); /* FOR */
  135497. testcase( i==11 ); /* IGNORE */
  135498. testcase( i==12 ); /* REGEXP */
  135499. testcase( i==13 ); /* EXPLAIN */
  135500. testcase( i==14 ); /* INSTEAD */
  135501. testcase( i==15 ); /* ADD */
  135502. testcase( i==16 ); /* DATABASE */
  135503. testcase( i==17 ); /* AS */
  135504. testcase( i==18 ); /* SELECT */
  135505. testcase( i==19 ); /* TABLE */
  135506. testcase( i==20 ); /* LEFT */
  135507. testcase( i==21 ); /* THEN */
  135508. testcase( i==22 ); /* END */
  135509. testcase( i==23 ); /* DEFERRABLE */
  135510. testcase( i==24 ); /* ELSE */
  135511. testcase( i==25 ); /* EXCEPT */
  135512. testcase( i==26 ); /* TRANSACTION */
  135513. testcase( i==27 ); /* ACTION */
  135514. testcase( i==28 ); /* ON */
  135515. testcase( i==29 ); /* NATURAL */
  135516. testcase( i==30 ); /* ALTER */
  135517. testcase( i==31 ); /* RAISE */
  135518. testcase( i==32 ); /* EXCLUSIVE */
  135519. testcase( i==33 ); /* EXISTS */
  135520. testcase( i==34 ); /* SAVEPOINT */
  135521. testcase( i==35 ); /* INTERSECT */
  135522. testcase( i==36 ); /* TRIGGER */
  135523. testcase( i==37 ); /* REFERENCES */
  135524. testcase( i==38 ); /* CONSTRAINT */
  135525. testcase( i==39 ); /* INTO */
  135526. testcase( i==40 ); /* OFFSET */
  135527. testcase( i==41 ); /* OF */
  135528. testcase( i==42 ); /* SET */
  135529. testcase( i==43 ); /* TEMPORARY */
  135530. testcase( i==44 ); /* TEMP */
  135531. testcase( i==45 ); /* OR */
  135532. testcase( i==46 ); /* UNIQUE */
  135533. testcase( i==47 ); /* QUERY */
  135534. testcase( i==48 ); /* WITHOUT */
  135535. testcase( i==49 ); /* WITH */
  135536. testcase( i==50 ); /* OUTER */
  135537. testcase( i==51 ); /* RELEASE */
  135538. testcase( i==52 ); /* ATTACH */
  135539. testcase( i==53 ); /* HAVING */
  135540. testcase( i==54 ); /* GROUP */
  135541. testcase( i==55 ); /* UPDATE */
  135542. testcase( i==56 ); /* BEGIN */
  135543. testcase( i==57 ); /* INNER */
  135544. testcase( i==58 ); /* RECURSIVE */
  135545. testcase( i==59 ); /* BETWEEN */
  135546. testcase( i==60 ); /* NOTNULL */
  135547. testcase( i==61 ); /* NOT */
  135548. testcase( i==62 ); /* NO */
  135549. testcase( i==63 ); /* NULL */
  135550. testcase( i==64 ); /* LIKE */
  135551. testcase( i==65 ); /* CASCADE */
  135552. testcase( i==66 ); /* ASC */
  135553. testcase( i==67 ); /* DELETE */
  135554. testcase( i==68 ); /* CASE */
  135555. testcase( i==69 ); /* COLLATE */
  135556. testcase( i==70 ); /* CREATE */
  135557. testcase( i==71 ); /* CURRENT_DATE */
  135558. testcase( i==72 ); /* DETACH */
  135559. testcase( i==73 ); /* IMMEDIATE */
  135560. testcase( i==74 ); /* JOIN */
  135561. testcase( i==75 ); /* INSERT */
  135562. testcase( i==76 ); /* MATCH */
  135563. testcase( i==77 ); /* PLAN */
  135564. testcase( i==78 ); /* ANALYZE */
  135565. testcase( i==79 ); /* PRAGMA */
  135566. testcase( i==80 ); /* ABORT */
  135567. testcase( i==81 ); /* VALUES */
  135568. testcase( i==82 ); /* VIRTUAL */
  135569. testcase( i==83 ); /* LIMIT */
  135570. testcase( i==84 ); /* WHEN */
  135571. testcase( i==85 ); /* WHERE */
  135572. testcase( i==86 ); /* RENAME */
  135573. testcase( i==87 ); /* AFTER */
  135574. testcase( i==88 ); /* REPLACE */
  135575. testcase( i==89 ); /* AND */
  135576. testcase( i==90 ); /* DEFAULT */
  135577. testcase( i==91 ); /* AUTOINCREMENT */
  135578. testcase( i==92 ); /* TO */
  135579. testcase( i==93 ); /* IN */
  135580. testcase( i==94 ); /* CAST */
  135581. testcase( i==95 ); /* COLUMN */
  135582. testcase( i==96 ); /* COMMIT */
  135583. testcase( i==97 ); /* CONFLICT */
  135584. testcase( i==98 ); /* CROSS */
  135585. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  135586. testcase( i==100 ); /* CURRENT_TIME */
  135587. testcase( i==101 ); /* PRIMARY */
  135588. testcase( i==102 ); /* DEFERRED */
  135589. testcase( i==103 ); /* DISTINCT */
  135590. testcase( i==104 ); /* IS */
  135591. testcase( i==105 ); /* DROP */
  135592. testcase( i==106 ); /* FAIL */
  135593. testcase( i==107 ); /* FROM */
  135594. testcase( i==108 ); /* FULL */
  135595. testcase( i==109 ); /* GLOB */
  135596. testcase( i==110 ); /* BY */
  135597. testcase( i==111 ); /* IF */
  135598. testcase( i==112 ); /* ISNULL */
  135599. testcase( i==113 ); /* ORDER */
  135600. testcase( i==114 ); /* RESTRICT */
  135601. testcase( i==115 ); /* RIGHT */
  135602. testcase( i==116 ); /* ROLLBACK */
  135603. testcase( i==117 ); /* ROW */
  135604. testcase( i==118 ); /* UNION */
  135605. testcase( i==119 ); /* USING */
  135606. testcase( i==120 ); /* VACUUM */
  135607. testcase( i==121 ); /* VIEW */
  135608. testcase( i==122 ); /* INITIALLY */
  135609. testcase( i==123 ); /* ALL */
  135610. *pType = aKWCode[i];
  135611. break;
  135612. }
  135613. }
  135614. return n;
  135615. }
  135616. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  135617. int id = TK_ID;
  135618. keywordCode((char*)z, n, &id);
  135619. return id;
  135620. }
  135621. #define SQLITE_N_KEYWORD 124
  135622. /************** End of keywordhash.h *****************************************/
  135623. /************** Continuing where we left off in tokenize.c *******************/
  135624. /*
  135625. ** If X is a character that can be used in an identifier then
  135626. ** IdChar(X) will be true. Otherwise it is false.
  135627. **
  135628. ** For ASCII, any character with the high-order bit set is
  135629. ** allowed in an identifier. For 7-bit characters,
  135630. ** sqlite3IsIdChar[X] must be 1.
  135631. **
  135632. ** For EBCDIC, the rules are more complex but have the same
  135633. ** end result.
  135634. **
  135635. ** Ticket #1066. the SQL standard does not allow '$' in the
  135636. ** middle of identifiers. But many SQL implementations do.
  135637. ** SQLite will allow '$' in identifiers for compatibility.
  135638. ** But the feature is undocumented.
  135639. */
  135640. #ifdef SQLITE_ASCII
  135641. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  135642. #endif
  135643. #ifdef SQLITE_EBCDIC
  135644. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  135645. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  135646. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  135647. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  135648. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  135649. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  135650. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  135651. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  135652. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  135653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  135654. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  135655. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  135656. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  135657. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  135658. };
  135659. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  135660. #endif
  135661. /* Make the IdChar function accessible from ctime.c */
  135662. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  135663. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  135664. #endif
  135665. /*
  135666. ** Return the length (in bytes) of the token that begins at z[0].
  135667. ** Store the token type in *tokenType before returning.
  135668. */
  135669. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  135670. int i, c;
  135671. switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
  135672. ** of the token. See the comment on the CC_ defines
  135673. ** above. */
  135674. case CC_SPACE: {
  135675. testcase( z[0]==' ' );
  135676. testcase( z[0]=='\t' );
  135677. testcase( z[0]=='\n' );
  135678. testcase( z[0]=='\f' );
  135679. testcase( z[0]=='\r' );
  135680. for(i=1; sqlite3Isspace(z[i]); i++){}
  135681. *tokenType = TK_SPACE;
  135682. return i;
  135683. }
  135684. case CC_MINUS: {
  135685. if( z[1]=='-' ){
  135686. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  135687. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  135688. return i;
  135689. }
  135690. *tokenType = TK_MINUS;
  135691. return 1;
  135692. }
  135693. case CC_LP: {
  135694. *tokenType = TK_LP;
  135695. return 1;
  135696. }
  135697. case CC_RP: {
  135698. *tokenType = TK_RP;
  135699. return 1;
  135700. }
  135701. case CC_SEMI: {
  135702. *tokenType = TK_SEMI;
  135703. return 1;
  135704. }
  135705. case CC_PLUS: {
  135706. *tokenType = TK_PLUS;
  135707. return 1;
  135708. }
  135709. case CC_STAR: {
  135710. *tokenType = TK_STAR;
  135711. return 1;
  135712. }
  135713. case CC_SLASH: {
  135714. if( z[1]!='*' || z[2]==0 ){
  135715. *tokenType = TK_SLASH;
  135716. return 1;
  135717. }
  135718. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  135719. if( c ) i++;
  135720. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  135721. return i;
  135722. }
  135723. case CC_PERCENT: {
  135724. *tokenType = TK_REM;
  135725. return 1;
  135726. }
  135727. case CC_EQ: {
  135728. *tokenType = TK_EQ;
  135729. return 1 + (z[1]=='=');
  135730. }
  135731. case CC_LT: {
  135732. if( (c=z[1])=='=' ){
  135733. *tokenType = TK_LE;
  135734. return 2;
  135735. }else if( c=='>' ){
  135736. *tokenType = TK_NE;
  135737. return 2;
  135738. }else if( c=='<' ){
  135739. *tokenType = TK_LSHIFT;
  135740. return 2;
  135741. }else{
  135742. *tokenType = TK_LT;
  135743. return 1;
  135744. }
  135745. }
  135746. case CC_GT: {
  135747. if( (c=z[1])=='=' ){
  135748. *tokenType = TK_GE;
  135749. return 2;
  135750. }else if( c=='>' ){
  135751. *tokenType = TK_RSHIFT;
  135752. return 2;
  135753. }else{
  135754. *tokenType = TK_GT;
  135755. return 1;
  135756. }
  135757. }
  135758. case CC_BANG: {
  135759. if( z[1]!='=' ){
  135760. *tokenType = TK_ILLEGAL;
  135761. return 1;
  135762. }else{
  135763. *tokenType = TK_NE;
  135764. return 2;
  135765. }
  135766. }
  135767. case CC_PIPE: {
  135768. if( z[1]!='|' ){
  135769. *tokenType = TK_BITOR;
  135770. return 1;
  135771. }else{
  135772. *tokenType = TK_CONCAT;
  135773. return 2;
  135774. }
  135775. }
  135776. case CC_COMMA: {
  135777. *tokenType = TK_COMMA;
  135778. return 1;
  135779. }
  135780. case CC_AND: {
  135781. *tokenType = TK_BITAND;
  135782. return 1;
  135783. }
  135784. case CC_TILDA: {
  135785. *tokenType = TK_BITNOT;
  135786. return 1;
  135787. }
  135788. case CC_QUOTE: {
  135789. int delim = z[0];
  135790. testcase( delim=='`' );
  135791. testcase( delim=='\'' );
  135792. testcase( delim=='"' );
  135793. for(i=1; (c=z[i])!=0; i++){
  135794. if( c==delim ){
  135795. if( z[i+1]==delim ){
  135796. i++;
  135797. }else{
  135798. break;
  135799. }
  135800. }
  135801. }
  135802. if( c=='\'' ){
  135803. *tokenType = TK_STRING;
  135804. return i+1;
  135805. }else if( c!=0 ){
  135806. *tokenType = TK_ID;
  135807. return i+1;
  135808. }else{
  135809. *tokenType = TK_ILLEGAL;
  135810. return i;
  135811. }
  135812. }
  135813. case CC_DOT: {
  135814. #ifndef SQLITE_OMIT_FLOATING_POINT
  135815. if( !sqlite3Isdigit(z[1]) )
  135816. #endif
  135817. {
  135818. *tokenType = TK_DOT;
  135819. return 1;
  135820. }
  135821. /* If the next character is a digit, this is a floating point
  135822. ** number that begins with ".". Fall thru into the next case */
  135823. }
  135824. case CC_DIGIT: {
  135825. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  135826. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  135827. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  135828. testcase( z[0]=='9' );
  135829. *tokenType = TK_INTEGER;
  135830. #ifndef SQLITE_OMIT_HEX_INTEGER
  135831. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  135832. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  135833. return i;
  135834. }
  135835. #endif
  135836. for(i=0; sqlite3Isdigit(z[i]); i++){}
  135837. #ifndef SQLITE_OMIT_FLOATING_POINT
  135838. if( z[i]=='.' ){
  135839. i++;
  135840. while( sqlite3Isdigit(z[i]) ){ i++; }
  135841. *tokenType = TK_FLOAT;
  135842. }
  135843. if( (z[i]=='e' || z[i]=='E') &&
  135844. ( sqlite3Isdigit(z[i+1])
  135845. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  135846. )
  135847. ){
  135848. i += 2;
  135849. while( sqlite3Isdigit(z[i]) ){ i++; }
  135850. *tokenType = TK_FLOAT;
  135851. }
  135852. #endif
  135853. while( IdChar(z[i]) ){
  135854. *tokenType = TK_ILLEGAL;
  135855. i++;
  135856. }
  135857. return i;
  135858. }
  135859. case CC_QUOTE2: {
  135860. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  135861. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  135862. return i;
  135863. }
  135864. case CC_VARNUM: {
  135865. *tokenType = TK_VARIABLE;
  135866. for(i=1; sqlite3Isdigit(z[i]); i++){}
  135867. return i;
  135868. }
  135869. case CC_DOLLAR:
  135870. case CC_VARALPHA: {
  135871. int n = 0;
  135872. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  135873. testcase( z[0]==':' ); testcase( z[0]=='#' );
  135874. *tokenType = TK_VARIABLE;
  135875. for(i=1; (c=z[i])!=0; i++){
  135876. if( IdChar(c) ){
  135877. n++;
  135878. #ifndef SQLITE_OMIT_TCL_VARIABLE
  135879. }else if( c=='(' && n>0 ){
  135880. do{
  135881. i++;
  135882. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  135883. if( c==')' ){
  135884. i++;
  135885. }else{
  135886. *tokenType = TK_ILLEGAL;
  135887. }
  135888. break;
  135889. }else if( c==':' && z[i+1]==':' ){
  135890. i++;
  135891. #endif
  135892. }else{
  135893. break;
  135894. }
  135895. }
  135896. if( n==0 ) *tokenType = TK_ILLEGAL;
  135897. return i;
  135898. }
  135899. case CC_KYWD: {
  135900. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  135901. if( IdChar(z[i]) ){
  135902. /* This token started out using characters that can appear in keywords,
  135903. ** but z[i] is a character not allowed within keywords, so this must
  135904. ** be an identifier instead */
  135905. i++;
  135906. break;
  135907. }
  135908. *tokenType = TK_ID;
  135909. return keywordCode((char*)z, i, tokenType);
  135910. }
  135911. case CC_X: {
  135912. #ifndef SQLITE_OMIT_BLOB_LITERAL
  135913. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  135914. if( z[1]=='\'' ){
  135915. *tokenType = TK_BLOB;
  135916. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  135917. if( z[i]!='\'' || i%2 ){
  135918. *tokenType = TK_ILLEGAL;
  135919. while( z[i] && z[i]!='\'' ){ i++; }
  135920. }
  135921. if( z[i] ) i++;
  135922. return i;
  135923. }
  135924. #endif
  135925. /* If it is not a BLOB literal, then it must be an ID, since no
  135926. ** SQL keywords start with the letter 'x'. Fall through */
  135927. }
  135928. case CC_ID: {
  135929. i = 1;
  135930. break;
  135931. }
  135932. default: {
  135933. *tokenType = TK_ILLEGAL;
  135934. return 1;
  135935. }
  135936. }
  135937. while( IdChar(z[i]) ){ i++; }
  135938. *tokenType = TK_ID;
  135939. return i;
  135940. }
  135941. /*
  135942. ** Run the parser on the given SQL string. The parser structure is
  135943. ** passed in. An SQLITE_ status code is returned. If an error occurs
  135944. ** then an and attempt is made to write an error message into
  135945. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  135946. ** error message.
  135947. */
  135948. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  135949. int nErr = 0; /* Number of errors encountered */
  135950. void *pEngine; /* The LEMON-generated LALR(1) parser */
  135951. int n = 0; /* Length of the next token token */
  135952. int tokenType; /* type of the next token */
  135953. int lastTokenParsed = -1; /* type of the previous token */
  135954. sqlite3 *db = pParse->db; /* The database connection */
  135955. int mxSqlLen; /* Max length of an SQL string */
  135956. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  135957. yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
  135958. #endif
  135959. assert( zSql!=0 );
  135960. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  135961. if( db->nVdbeActive==0 ){
  135962. db->u1.isInterrupted = 0;
  135963. }
  135964. pParse->rc = SQLITE_OK;
  135965. pParse->zTail = zSql;
  135966. assert( pzErrMsg!=0 );
  135967. /* sqlite3ParserTrace(stdout, "parser: "); */
  135968. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  135969. pEngine = &sEngine;
  135970. sqlite3ParserInit(pEngine);
  135971. #else
  135972. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  135973. if( pEngine==0 ){
  135974. sqlite3OomFault(db);
  135975. return SQLITE_NOMEM_BKPT;
  135976. }
  135977. #endif
  135978. assert( pParse->pNewTable==0 );
  135979. assert( pParse->pNewTrigger==0 );
  135980. assert( pParse->nVar==0 );
  135981. assert( pParse->pVList==0 );
  135982. while( 1 ){
  135983. if( zSql[0]!=0 ){
  135984. n = sqlite3GetToken((u8*)zSql, &tokenType);
  135985. mxSqlLen -= n;
  135986. if( mxSqlLen<0 ){
  135987. pParse->rc = SQLITE_TOOBIG;
  135988. break;
  135989. }
  135990. }else{
  135991. /* Upon reaching the end of input, call the parser two more times
  135992. ** with tokens TK_SEMI and 0, in that order. */
  135993. if( lastTokenParsed==TK_SEMI ){
  135994. tokenType = 0;
  135995. }else if( lastTokenParsed==0 ){
  135996. break;
  135997. }else{
  135998. tokenType = TK_SEMI;
  135999. }
  136000. n = 0;
  136001. }
  136002. if( tokenType>=TK_SPACE ){
  136003. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  136004. if( db->u1.isInterrupted ){
  136005. pParse->rc = SQLITE_INTERRUPT;
  136006. break;
  136007. }
  136008. if( tokenType==TK_ILLEGAL ){
  136009. sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
  136010. break;
  136011. }
  136012. zSql += n;
  136013. }else{
  136014. pParse->sLastToken.z = zSql;
  136015. pParse->sLastToken.n = n;
  136016. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  136017. lastTokenParsed = tokenType;
  136018. zSql += n;
  136019. if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
  136020. }
  136021. }
  136022. assert( nErr==0 );
  136023. pParse->zTail = zSql;
  136024. #ifdef YYTRACKMAXSTACKDEPTH
  136025. sqlite3_mutex_enter(sqlite3MallocMutex());
  136026. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  136027. sqlite3ParserStackPeak(pEngine)
  136028. );
  136029. sqlite3_mutex_leave(sqlite3MallocMutex());
  136030. #endif /* YYDEBUG */
  136031. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  136032. sqlite3ParserFinalize(pEngine);
  136033. #else
  136034. sqlite3ParserFree(pEngine, sqlite3_free);
  136035. #endif
  136036. if( db->mallocFailed ){
  136037. pParse->rc = SQLITE_NOMEM_BKPT;
  136038. }
  136039. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  136040. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  136041. }
  136042. assert( pzErrMsg!=0 );
  136043. if( pParse->zErrMsg ){
  136044. *pzErrMsg = pParse->zErrMsg;
  136045. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  136046. pParse->zErrMsg = 0;
  136047. nErr++;
  136048. }
  136049. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  136050. sqlite3VdbeDelete(pParse->pVdbe);
  136051. pParse->pVdbe = 0;
  136052. }
  136053. #ifndef SQLITE_OMIT_SHARED_CACHE
  136054. if( pParse->nested==0 ){
  136055. sqlite3DbFree(db, pParse->aTableLock);
  136056. pParse->aTableLock = 0;
  136057. pParse->nTableLock = 0;
  136058. }
  136059. #endif
  136060. #ifndef SQLITE_OMIT_VIRTUALTABLE
  136061. sqlite3_free(pParse->apVtabLock);
  136062. #endif
  136063. if( !IN_DECLARE_VTAB ){
  136064. /* If the pParse->declareVtab flag is set, do not delete any table
  136065. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  136066. ** will take responsibility for freeing the Table structure.
  136067. */
  136068. sqlite3DeleteTable(db, pParse->pNewTable);
  136069. }
  136070. if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
  136071. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  136072. sqlite3DbFree(db, pParse->pVList);
  136073. while( pParse->pAinc ){
  136074. AutoincInfo *p = pParse->pAinc;
  136075. pParse->pAinc = p->pNext;
  136076. sqlite3DbFreeNN(db, p);
  136077. }
  136078. while( pParse->pZombieTab ){
  136079. Table *p = pParse->pZombieTab;
  136080. pParse->pZombieTab = p->pNextZombie;
  136081. sqlite3DeleteTable(db, p);
  136082. }
  136083. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  136084. return nErr;
  136085. }
  136086. /************** End of tokenize.c ********************************************/
  136087. /************** Begin file complete.c ****************************************/
  136088. /*
  136089. ** 2001 September 15
  136090. **
  136091. ** The author disclaims copyright to this source code. In place of
  136092. ** a legal notice, here is a blessing:
  136093. **
  136094. ** May you do good and not evil.
  136095. ** May you find forgiveness for yourself and forgive others.
  136096. ** May you share freely, never taking more than you give.
  136097. **
  136098. *************************************************************************
  136099. ** An tokenizer for SQL
  136100. **
  136101. ** This file contains C code that implements the sqlite3_complete() API.
  136102. ** This code used to be part of the tokenizer.c source file. But by
  136103. ** separating it out, the code will be automatically omitted from
  136104. ** static links that do not use it.
  136105. */
  136106. /* #include "sqliteInt.h" */
  136107. #ifndef SQLITE_OMIT_COMPLETE
  136108. /*
  136109. ** This is defined in tokenize.c. We just have to import the definition.
  136110. */
  136111. #ifndef SQLITE_AMALGAMATION
  136112. #ifdef SQLITE_ASCII
  136113. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  136114. #endif
  136115. #ifdef SQLITE_EBCDIC
  136116. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  136117. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  136118. #endif
  136119. #endif /* SQLITE_AMALGAMATION */
  136120. /*
  136121. ** Token types used by the sqlite3_complete() routine. See the header
  136122. ** comments on that procedure for additional information.
  136123. */
  136124. #define tkSEMI 0
  136125. #define tkWS 1
  136126. #define tkOTHER 2
  136127. #ifndef SQLITE_OMIT_TRIGGER
  136128. #define tkEXPLAIN 3
  136129. #define tkCREATE 4
  136130. #define tkTEMP 5
  136131. #define tkTRIGGER 6
  136132. #define tkEND 7
  136133. #endif
  136134. /*
  136135. ** Return TRUE if the given SQL string ends in a semicolon.
  136136. **
  136137. ** Special handling is require for CREATE TRIGGER statements.
  136138. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  136139. ** must end with ";END;".
  136140. **
  136141. ** This implementation uses a state machine with 8 states:
  136142. **
  136143. ** (0) INVALID We have not yet seen a non-whitespace character.
  136144. **
  136145. ** (1) START At the beginning or end of an SQL statement. This routine
  136146. ** returns 1 if it ends in the START state and 0 if it ends
  136147. ** in any other state.
  136148. **
  136149. ** (2) NORMAL We are in the middle of statement which ends with a single
  136150. ** semicolon.
  136151. **
  136152. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  136153. ** a statement.
  136154. **
  136155. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  136156. ** statement, possibly preceded by EXPLAIN and/or followed by
  136157. ** TEMP or TEMPORARY
  136158. **
  136159. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  136160. ** ended by a semicolon, the keyword END, and another semicolon.
  136161. **
  136162. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  136163. ** the end of a trigger definition.
  136164. **
  136165. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  136166. ** of a trigger definition.
  136167. **
  136168. ** Transitions between states above are determined by tokens extracted
  136169. ** from the input. The following tokens are significant:
  136170. **
  136171. ** (0) tkSEMI A semicolon.
  136172. ** (1) tkWS Whitespace.
  136173. ** (2) tkOTHER Any other SQL token.
  136174. ** (3) tkEXPLAIN The "explain" keyword.
  136175. ** (4) tkCREATE The "create" keyword.
  136176. ** (5) tkTEMP The "temp" or "temporary" keyword.
  136177. ** (6) tkTRIGGER The "trigger" keyword.
  136178. ** (7) tkEND The "end" keyword.
  136179. **
  136180. ** Whitespace never causes a state transition and is always ignored.
  136181. ** This means that a SQL string of all whitespace is invalid.
  136182. **
  136183. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  136184. ** to recognize the end of a trigger can be omitted. All we have to do
  136185. ** is look for a semicolon that is not part of an string or comment.
  136186. */
  136187. SQLITE_API int sqlite3_complete(const char *zSql){
  136188. u8 state = 0; /* Current state, using numbers defined in header comment */
  136189. u8 token; /* Value of the next token */
  136190. #ifndef SQLITE_OMIT_TRIGGER
  136191. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  136192. ** statement. This is the normal case.
  136193. */
  136194. static const u8 trans[8][8] = {
  136195. /* Token: */
  136196. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  136197. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  136198. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  136199. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  136200. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  136201. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  136202. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  136203. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  136204. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  136205. };
  136206. #else
  136207. /* If triggers are not supported by this compile then the statement machine
  136208. ** used to detect the end of a statement is much simpler
  136209. */
  136210. static const u8 trans[3][3] = {
  136211. /* Token: */
  136212. /* State: ** SEMI WS OTHER */
  136213. /* 0 INVALID: */ { 1, 0, 2, },
  136214. /* 1 START: */ { 1, 1, 2, },
  136215. /* 2 NORMAL: */ { 1, 2, 2, },
  136216. };
  136217. #endif /* SQLITE_OMIT_TRIGGER */
  136218. #ifdef SQLITE_ENABLE_API_ARMOR
  136219. if( zSql==0 ){
  136220. (void)SQLITE_MISUSE_BKPT;
  136221. return 0;
  136222. }
  136223. #endif
  136224. while( *zSql ){
  136225. switch( *zSql ){
  136226. case ';': { /* A semicolon */
  136227. token = tkSEMI;
  136228. break;
  136229. }
  136230. case ' ':
  136231. case '\r':
  136232. case '\t':
  136233. case '\n':
  136234. case '\f': { /* White space is ignored */
  136235. token = tkWS;
  136236. break;
  136237. }
  136238. case '/': { /* C-style comments */
  136239. if( zSql[1]!='*' ){
  136240. token = tkOTHER;
  136241. break;
  136242. }
  136243. zSql += 2;
  136244. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  136245. if( zSql[0]==0 ) return 0;
  136246. zSql++;
  136247. token = tkWS;
  136248. break;
  136249. }
  136250. case '-': { /* SQL-style comments from "--" to end of line */
  136251. if( zSql[1]!='-' ){
  136252. token = tkOTHER;
  136253. break;
  136254. }
  136255. while( *zSql && *zSql!='\n' ){ zSql++; }
  136256. if( *zSql==0 ) return state==1;
  136257. token = tkWS;
  136258. break;
  136259. }
  136260. case '[': { /* Microsoft-style identifiers in [...] */
  136261. zSql++;
  136262. while( *zSql && *zSql!=']' ){ zSql++; }
  136263. if( *zSql==0 ) return 0;
  136264. token = tkOTHER;
  136265. break;
  136266. }
  136267. case '`': /* Grave-accent quoted symbols used by MySQL */
  136268. case '"': /* single- and double-quoted strings */
  136269. case '\'': {
  136270. int c = *zSql;
  136271. zSql++;
  136272. while( *zSql && *zSql!=c ){ zSql++; }
  136273. if( *zSql==0 ) return 0;
  136274. token = tkOTHER;
  136275. break;
  136276. }
  136277. default: {
  136278. #ifdef SQLITE_EBCDIC
  136279. unsigned char c;
  136280. #endif
  136281. if( IdChar((u8)*zSql) ){
  136282. /* Keywords and unquoted identifiers */
  136283. int nId;
  136284. for(nId=1; IdChar(zSql[nId]); nId++){}
  136285. #ifdef SQLITE_OMIT_TRIGGER
  136286. token = tkOTHER;
  136287. #else
  136288. switch( *zSql ){
  136289. case 'c': case 'C': {
  136290. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  136291. token = tkCREATE;
  136292. }else{
  136293. token = tkOTHER;
  136294. }
  136295. break;
  136296. }
  136297. case 't': case 'T': {
  136298. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  136299. token = tkTRIGGER;
  136300. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  136301. token = tkTEMP;
  136302. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  136303. token = tkTEMP;
  136304. }else{
  136305. token = tkOTHER;
  136306. }
  136307. break;
  136308. }
  136309. case 'e': case 'E': {
  136310. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  136311. token = tkEND;
  136312. }else
  136313. #ifndef SQLITE_OMIT_EXPLAIN
  136314. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  136315. token = tkEXPLAIN;
  136316. }else
  136317. #endif
  136318. {
  136319. token = tkOTHER;
  136320. }
  136321. break;
  136322. }
  136323. default: {
  136324. token = tkOTHER;
  136325. break;
  136326. }
  136327. }
  136328. #endif /* SQLITE_OMIT_TRIGGER */
  136329. zSql += nId-1;
  136330. }else{
  136331. /* Operators and special symbols */
  136332. token = tkOTHER;
  136333. }
  136334. break;
  136335. }
  136336. }
  136337. state = trans[state][token];
  136338. zSql++;
  136339. }
  136340. return state==1;
  136341. }
  136342. #ifndef SQLITE_OMIT_UTF16
  136343. /*
  136344. ** This routine is the same as the sqlite3_complete() routine described
  136345. ** above, except that the parameter is required to be UTF-16 encoded, not
  136346. ** UTF-8.
  136347. */
  136348. SQLITE_API int sqlite3_complete16(const void *zSql){
  136349. sqlite3_value *pVal;
  136350. char const *zSql8;
  136351. int rc;
  136352. #ifndef SQLITE_OMIT_AUTOINIT
  136353. rc = sqlite3_initialize();
  136354. if( rc ) return rc;
  136355. #endif
  136356. pVal = sqlite3ValueNew(0);
  136357. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  136358. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  136359. if( zSql8 ){
  136360. rc = sqlite3_complete(zSql8);
  136361. }else{
  136362. rc = SQLITE_NOMEM_BKPT;
  136363. }
  136364. sqlite3ValueFree(pVal);
  136365. return rc & 0xff;
  136366. }
  136367. #endif /* SQLITE_OMIT_UTF16 */
  136368. #endif /* SQLITE_OMIT_COMPLETE */
  136369. /************** End of complete.c ********************************************/
  136370. /************** Begin file main.c ********************************************/
  136371. /*
  136372. ** 2001 September 15
  136373. **
  136374. ** The author disclaims copyright to this source code. In place of
  136375. ** a legal notice, here is a blessing:
  136376. **
  136377. ** May you do good and not evil.
  136378. ** May you find forgiveness for yourself and forgive others.
  136379. ** May you share freely, never taking more than you give.
  136380. **
  136381. *************************************************************************
  136382. ** Main file for the SQLite library. The routines in this file
  136383. ** implement the programmer interface to the library. Routines in
  136384. ** other files are for internal use by SQLite and should not be
  136385. ** accessed by users of the library.
  136386. */
  136387. /* #include "sqliteInt.h" */
  136388. #ifdef SQLITE_ENABLE_FTS3
  136389. /************** Include fts3.h in the middle of main.c ***********************/
  136390. /************** Begin file fts3.h ********************************************/
  136391. /*
  136392. ** 2006 Oct 10
  136393. **
  136394. ** The author disclaims copyright to this source code. In place of
  136395. ** a legal notice, here is a blessing:
  136396. **
  136397. ** May you do good and not evil.
  136398. ** May you find forgiveness for yourself and forgive others.
  136399. ** May you share freely, never taking more than you give.
  136400. **
  136401. ******************************************************************************
  136402. **
  136403. ** This header file is used by programs that want to link against the
  136404. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  136405. */
  136406. /* #include "sqlite3.h" */
  136407. #if 0
  136408. extern "C" {
  136409. #endif /* __cplusplus */
  136410. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  136411. #if 0
  136412. } /* extern "C" */
  136413. #endif /* __cplusplus */
  136414. /************** End of fts3.h ************************************************/
  136415. /************** Continuing where we left off in main.c ***********************/
  136416. #endif
  136417. #ifdef SQLITE_ENABLE_RTREE
  136418. /************** Include rtree.h in the middle of main.c **********************/
  136419. /************** Begin file rtree.h *******************************************/
  136420. /*
  136421. ** 2008 May 26
  136422. **
  136423. ** The author disclaims copyright to this source code. In place of
  136424. ** a legal notice, here is a blessing:
  136425. **
  136426. ** May you do good and not evil.
  136427. ** May you find forgiveness for yourself and forgive others.
  136428. ** May you share freely, never taking more than you give.
  136429. **
  136430. ******************************************************************************
  136431. **
  136432. ** This header file is used by programs that want to link against the
  136433. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  136434. */
  136435. /* #include "sqlite3.h" */
  136436. #ifdef SQLITE_OMIT_VIRTUALTABLE
  136437. # undef SQLITE_ENABLE_RTREE
  136438. #endif
  136439. #if 0
  136440. extern "C" {
  136441. #endif /* __cplusplus */
  136442. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  136443. #if 0
  136444. } /* extern "C" */
  136445. #endif /* __cplusplus */
  136446. /************** End of rtree.h ***********************************************/
  136447. /************** Continuing where we left off in main.c ***********************/
  136448. #endif
  136449. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  136450. /************** Include sqliteicu.h in the middle of main.c ******************/
  136451. /************** Begin file sqliteicu.h ***************************************/
  136452. /*
  136453. ** 2008 May 26
  136454. **
  136455. ** The author disclaims copyright to this source code. In place of
  136456. ** a legal notice, here is a blessing:
  136457. **
  136458. ** May you do good and not evil.
  136459. ** May you find forgiveness for yourself and forgive others.
  136460. ** May you share freely, never taking more than you give.
  136461. **
  136462. ******************************************************************************
  136463. **
  136464. ** This header file is used by programs that want to link against the
  136465. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  136466. */
  136467. /* #include "sqlite3.h" */
  136468. #if 0
  136469. extern "C" {
  136470. #endif /* __cplusplus */
  136471. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  136472. #if 0
  136473. } /* extern "C" */
  136474. #endif /* __cplusplus */
  136475. /************** End of sqliteicu.h *******************************************/
  136476. /************** Continuing where we left off in main.c ***********************/
  136477. #endif
  136478. #ifdef SQLITE_ENABLE_JSON1
  136479. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  136480. #endif
  136481. #ifdef SQLITE_ENABLE_STMTVTAB
  136482. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
  136483. #endif
  136484. #ifdef SQLITE_ENABLE_FTS5
  136485. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  136486. #endif
  136487. #ifndef SQLITE_AMALGAMATION
  136488. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  136489. ** contains the text of SQLITE_VERSION macro.
  136490. */
  136491. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  136492. #endif
  136493. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  136494. ** a pointer to the to the sqlite3_version[] string constant.
  136495. */
  136496. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  136497. /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
  136498. ** pointer to a string constant whose value is the same as the
  136499. ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
  136500. ** an edited copy of the amalgamation, then the last four characters of
  136501. ** the hash might be different from SQLITE_SOURCE_ID.
  136502. */
  136503. /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
  136504. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  136505. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  136506. */
  136507. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  136508. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  136509. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  136510. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  136511. */
  136512. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  136513. /*
  136514. ** When compiling the test fixture or with debugging enabled (on Win32),
  136515. ** this variable being set to non-zero will cause OSTRACE macros to emit
  136516. ** extra diagnostic information.
  136517. */
  136518. #ifdef SQLITE_HAVE_OS_TRACE
  136519. # ifndef SQLITE_DEBUG_OS_TRACE
  136520. # define SQLITE_DEBUG_OS_TRACE 0
  136521. # endif
  136522. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  136523. #endif
  136524. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  136525. /*
  136526. ** If the following function pointer is not NULL and if
  136527. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  136528. ** I/O active are written using this function. These messages
  136529. ** are intended for debugging activity only.
  136530. */
  136531. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  136532. #endif
  136533. /*
  136534. ** If the following global variable points to a string which is the
  136535. ** name of a directory, then that directory will be used to store
  136536. ** temporary files.
  136537. **
  136538. ** See also the "PRAGMA temp_store_directory" SQL command.
  136539. */
  136540. SQLITE_API char *sqlite3_temp_directory = 0;
  136541. /*
  136542. ** If the following global variable points to a string which is the
  136543. ** name of a directory, then that directory will be used to store
  136544. ** all database files specified with a relative pathname.
  136545. **
  136546. ** See also the "PRAGMA data_store_directory" SQL command.
  136547. */
  136548. SQLITE_API char *sqlite3_data_directory = 0;
  136549. /*
  136550. ** Initialize SQLite.
  136551. **
  136552. ** This routine must be called to initialize the memory allocation,
  136553. ** VFS, and mutex subsystems prior to doing any serious work with
  136554. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  136555. ** this routine will be called automatically by key routines such as
  136556. ** sqlite3_open().
  136557. **
  136558. ** This routine is a no-op except on its very first call for the process,
  136559. ** or for the first call after a call to sqlite3_shutdown.
  136560. **
  136561. ** The first thread to call this routine runs the initialization to
  136562. ** completion. If subsequent threads call this routine before the first
  136563. ** thread has finished the initialization process, then the subsequent
  136564. ** threads must block until the first thread finishes with the initialization.
  136565. **
  136566. ** The first thread might call this routine recursively. Recursive
  136567. ** calls to this routine should not block, of course. Otherwise the
  136568. ** initialization process would never complete.
  136569. **
  136570. ** Let X be the first thread to enter this routine. Let Y be some other
  136571. ** thread. Then while the initial invocation of this routine by X is
  136572. ** incomplete, it is required that:
  136573. **
  136574. ** * Calls to this routine from Y must block until the outer-most
  136575. ** call by X completes.
  136576. **
  136577. ** * Recursive calls to this routine from thread X return immediately
  136578. ** without blocking.
  136579. */
  136580. SQLITE_API int sqlite3_initialize(void){
  136581. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  136582. int rc; /* Result code */
  136583. #ifdef SQLITE_EXTRA_INIT
  136584. int bRunExtraInit = 0; /* Extra initialization needed */
  136585. #endif
  136586. #ifdef SQLITE_OMIT_WSD
  136587. rc = sqlite3_wsd_init(4096, 24);
  136588. if( rc!=SQLITE_OK ){
  136589. return rc;
  136590. }
  136591. #endif
  136592. /* If the following assert() fails on some obscure processor/compiler
  136593. ** combination, the work-around is to set the correct pointer
  136594. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  136595. assert( SQLITE_PTRSIZE==sizeof(char*) );
  136596. /* If SQLite is already completely initialized, then this call
  136597. ** to sqlite3_initialize() should be a no-op. But the initialization
  136598. ** must be complete. So isInit must not be set until the very end
  136599. ** of this routine.
  136600. */
  136601. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  136602. /* Make sure the mutex subsystem is initialized. If unable to
  136603. ** initialize the mutex subsystem, return early with the error.
  136604. ** If the system is so sick that we are unable to allocate a mutex,
  136605. ** there is not much SQLite is going to be able to do.
  136606. **
  136607. ** The mutex subsystem must take care of serializing its own
  136608. ** initialization.
  136609. */
  136610. rc = sqlite3MutexInit();
  136611. if( rc ) return rc;
  136612. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  136613. ** This operation is protected by the STATIC_MASTER mutex. Note that
  136614. ** MutexAlloc() is called for a static mutex prior to initializing the
  136615. ** malloc subsystem - this implies that the allocation of a static
  136616. ** mutex must not require support from the malloc subsystem.
  136617. */
  136618. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  136619. sqlite3_mutex_enter(pMaster);
  136620. sqlite3GlobalConfig.isMutexInit = 1;
  136621. if( !sqlite3GlobalConfig.isMallocInit ){
  136622. rc = sqlite3MallocInit();
  136623. }
  136624. if( rc==SQLITE_OK ){
  136625. sqlite3GlobalConfig.isMallocInit = 1;
  136626. if( !sqlite3GlobalConfig.pInitMutex ){
  136627. sqlite3GlobalConfig.pInitMutex =
  136628. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  136629. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  136630. rc = SQLITE_NOMEM_BKPT;
  136631. }
  136632. }
  136633. }
  136634. if( rc==SQLITE_OK ){
  136635. sqlite3GlobalConfig.nRefInitMutex++;
  136636. }
  136637. sqlite3_mutex_leave(pMaster);
  136638. /* If rc is not SQLITE_OK at this point, then either the malloc
  136639. ** subsystem could not be initialized or the system failed to allocate
  136640. ** the pInitMutex mutex. Return an error in either case. */
  136641. if( rc!=SQLITE_OK ){
  136642. return rc;
  136643. }
  136644. /* Do the rest of the initialization under the recursive mutex so
  136645. ** that we will be able to handle recursive calls into
  136646. ** sqlite3_initialize(). The recursive calls normally come through
  136647. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  136648. ** recursive calls might also be possible.
  136649. **
  136650. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  136651. ** to the xInit method, so the xInit method need not be threadsafe.
  136652. **
  136653. ** The following mutex is what serializes access to the appdef pcache xInit
  136654. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  136655. ** call to sqlite3PcacheInitialize().
  136656. */
  136657. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  136658. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  136659. sqlite3GlobalConfig.inProgress = 1;
  136660. #ifdef SQLITE_ENABLE_SQLLOG
  136661. {
  136662. extern void sqlite3_init_sqllog(void);
  136663. sqlite3_init_sqllog();
  136664. }
  136665. #endif
  136666. memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
  136667. sqlite3RegisterBuiltinFunctions();
  136668. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  136669. rc = sqlite3PcacheInitialize();
  136670. }
  136671. if( rc==SQLITE_OK ){
  136672. sqlite3GlobalConfig.isPCacheInit = 1;
  136673. rc = sqlite3OsInit();
  136674. }
  136675. #ifdef SQLITE_ENABLE_DESERIALIZE
  136676. if( rc==SQLITE_OK ){
  136677. rc = sqlite3MemdbInit();
  136678. }
  136679. #endif
  136680. if( rc==SQLITE_OK ){
  136681. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  136682. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  136683. sqlite3GlobalConfig.isInit = 1;
  136684. #ifdef SQLITE_EXTRA_INIT
  136685. bRunExtraInit = 1;
  136686. #endif
  136687. }
  136688. sqlite3GlobalConfig.inProgress = 0;
  136689. }
  136690. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  136691. /* Go back under the static mutex and clean up the recursive
  136692. ** mutex to prevent a resource leak.
  136693. */
  136694. sqlite3_mutex_enter(pMaster);
  136695. sqlite3GlobalConfig.nRefInitMutex--;
  136696. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  136697. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  136698. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  136699. sqlite3GlobalConfig.pInitMutex = 0;
  136700. }
  136701. sqlite3_mutex_leave(pMaster);
  136702. /* The following is just a sanity check to make sure SQLite has
  136703. ** been compiled correctly. It is important to run this code, but
  136704. ** we don't want to run it too often and soak up CPU cycles for no
  136705. ** reason. So we run it once during initialization.
  136706. */
  136707. #ifndef NDEBUG
  136708. #ifndef SQLITE_OMIT_FLOATING_POINT
  136709. /* This section of code's only "output" is via assert() statements. */
  136710. if( rc==SQLITE_OK ){
  136711. u64 x = (((u64)1)<<63)-1;
  136712. double y;
  136713. assert(sizeof(x)==8);
  136714. assert(sizeof(x)==sizeof(y));
  136715. memcpy(&y, &x, 8);
  136716. assert( sqlite3IsNaN(y) );
  136717. }
  136718. #endif
  136719. #endif
  136720. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  136721. ** compile-time option.
  136722. */
  136723. #ifdef SQLITE_EXTRA_INIT
  136724. if( bRunExtraInit ){
  136725. int SQLITE_EXTRA_INIT(const char*);
  136726. rc = SQLITE_EXTRA_INIT(0);
  136727. }
  136728. #endif
  136729. return rc;
  136730. }
  136731. /*
  136732. ** Undo the effects of sqlite3_initialize(). Must not be called while
  136733. ** there are outstanding database connections or memory allocations or
  136734. ** while any part of SQLite is otherwise in use in any thread. This
  136735. ** routine is not threadsafe. But it is safe to invoke this routine
  136736. ** on when SQLite is already shut down. If SQLite is already shut down
  136737. ** when this routine is invoked, then this routine is a harmless no-op.
  136738. */
  136739. SQLITE_API int sqlite3_shutdown(void){
  136740. #ifdef SQLITE_OMIT_WSD
  136741. int rc = sqlite3_wsd_init(4096, 24);
  136742. if( rc!=SQLITE_OK ){
  136743. return rc;
  136744. }
  136745. #endif
  136746. if( sqlite3GlobalConfig.isInit ){
  136747. #ifdef SQLITE_EXTRA_SHUTDOWN
  136748. void SQLITE_EXTRA_SHUTDOWN(void);
  136749. SQLITE_EXTRA_SHUTDOWN();
  136750. #endif
  136751. sqlite3_os_end();
  136752. sqlite3_reset_auto_extension();
  136753. sqlite3GlobalConfig.isInit = 0;
  136754. }
  136755. if( sqlite3GlobalConfig.isPCacheInit ){
  136756. sqlite3PcacheShutdown();
  136757. sqlite3GlobalConfig.isPCacheInit = 0;
  136758. }
  136759. if( sqlite3GlobalConfig.isMallocInit ){
  136760. sqlite3MallocEnd();
  136761. sqlite3GlobalConfig.isMallocInit = 0;
  136762. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  136763. /* The heap subsystem has now been shutdown and these values are supposed
  136764. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  136765. ** which would rely on that heap subsystem; therefore, make sure these
  136766. ** values cannot refer to heap memory that was just invalidated when the
  136767. ** heap subsystem was shutdown. This is only done if the current call to
  136768. ** this function resulted in the heap subsystem actually being shutdown.
  136769. */
  136770. sqlite3_data_directory = 0;
  136771. sqlite3_temp_directory = 0;
  136772. #endif
  136773. }
  136774. if( sqlite3GlobalConfig.isMutexInit ){
  136775. sqlite3MutexEnd();
  136776. sqlite3GlobalConfig.isMutexInit = 0;
  136777. }
  136778. return SQLITE_OK;
  136779. }
  136780. /*
  136781. ** This API allows applications to modify the global configuration of
  136782. ** the SQLite library at run-time.
  136783. **
  136784. ** This routine should only be called when there are no outstanding
  136785. ** database connections or memory allocations. This routine is not
  136786. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  136787. ** behavior.
  136788. */
  136789. SQLITE_API int sqlite3_config(int op, ...){
  136790. va_list ap;
  136791. int rc = SQLITE_OK;
  136792. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  136793. ** the SQLite library is in use. */
  136794. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  136795. va_start(ap, op);
  136796. switch( op ){
  136797. /* Mutex configuration options are only available in a threadsafe
  136798. ** compile.
  136799. */
  136800. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  136801. case SQLITE_CONFIG_SINGLETHREAD: {
  136802. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  136803. ** Single-thread. */
  136804. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  136805. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  136806. break;
  136807. }
  136808. #endif
  136809. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  136810. case SQLITE_CONFIG_MULTITHREAD: {
  136811. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  136812. ** Multi-thread. */
  136813. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  136814. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  136815. break;
  136816. }
  136817. #endif
  136818. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  136819. case SQLITE_CONFIG_SERIALIZED: {
  136820. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  136821. ** Serialized. */
  136822. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  136823. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  136824. break;
  136825. }
  136826. #endif
  136827. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  136828. case SQLITE_CONFIG_MUTEX: {
  136829. /* Specify an alternative mutex implementation */
  136830. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  136831. break;
  136832. }
  136833. #endif
  136834. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  136835. case SQLITE_CONFIG_GETMUTEX: {
  136836. /* Retrieve the current mutex implementation */
  136837. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  136838. break;
  136839. }
  136840. #endif
  136841. case SQLITE_CONFIG_MALLOC: {
  136842. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  136843. ** single argument which is a pointer to an instance of the
  136844. ** sqlite3_mem_methods structure. The argument specifies alternative
  136845. ** low-level memory allocation routines to be used in place of the memory
  136846. ** allocation routines built into SQLite. */
  136847. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  136848. break;
  136849. }
  136850. case SQLITE_CONFIG_GETMALLOC: {
  136851. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  136852. ** single argument which is a pointer to an instance of the
  136853. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  136854. ** filled with the currently defined memory allocation routines. */
  136855. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  136856. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  136857. break;
  136858. }
  136859. case SQLITE_CONFIG_MEMSTATUS: {
  136860. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  136861. ** single argument of type int, interpreted as a boolean, which enables
  136862. ** or disables the collection of memory allocation statistics. */
  136863. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  136864. break;
  136865. }
  136866. case SQLITE_CONFIG_SMALL_MALLOC: {
  136867. sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
  136868. break;
  136869. }
  136870. case SQLITE_CONFIG_PAGECACHE: {
  136871. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  136872. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  136873. ** the size of each page cache line (sz), and the number of cache lines
  136874. ** (N). */
  136875. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  136876. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  136877. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  136878. break;
  136879. }
  136880. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  136881. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  136882. ** a single parameter which is a pointer to an integer and writes into
  136883. ** that integer the number of extra bytes per page required for each page
  136884. ** in SQLITE_CONFIG_PAGECACHE. */
  136885. *va_arg(ap, int*) =
  136886. sqlite3HeaderSizeBtree() +
  136887. sqlite3HeaderSizePcache() +
  136888. sqlite3HeaderSizePcache1();
  136889. break;
  136890. }
  136891. case SQLITE_CONFIG_PCACHE: {
  136892. /* no-op */
  136893. break;
  136894. }
  136895. case SQLITE_CONFIG_GETPCACHE: {
  136896. /* now an error */
  136897. rc = SQLITE_ERROR;
  136898. break;
  136899. }
  136900. case SQLITE_CONFIG_PCACHE2: {
  136901. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  136902. ** single argument which is a pointer to an sqlite3_pcache_methods2
  136903. ** object. This object specifies the interface to a custom page cache
  136904. ** implementation. */
  136905. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  136906. break;
  136907. }
  136908. case SQLITE_CONFIG_GETPCACHE2: {
  136909. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  136910. ** single argument which is a pointer to an sqlite3_pcache_methods2
  136911. ** object. SQLite copies of the current page cache implementation into
  136912. ** that object. */
  136913. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  136914. sqlite3PCacheSetDefault();
  136915. }
  136916. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  136917. break;
  136918. }
  136919. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  136920. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  136921. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  136922. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  136923. case SQLITE_CONFIG_HEAP: {
  136924. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  136925. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  136926. ** number of bytes in the memory buffer, and the minimum allocation size.
  136927. */
  136928. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  136929. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  136930. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  136931. if( sqlite3GlobalConfig.mnReq<1 ){
  136932. sqlite3GlobalConfig.mnReq = 1;
  136933. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  136934. /* cap min request size at 2^12 */
  136935. sqlite3GlobalConfig.mnReq = (1<<12);
  136936. }
  136937. if( sqlite3GlobalConfig.pHeap==0 ){
  136938. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  136939. ** is NULL, then SQLite reverts to using its default memory allocator
  136940. ** (the system malloc() implementation), undoing any prior invocation of
  136941. ** SQLITE_CONFIG_MALLOC.
  136942. **
  136943. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  136944. ** revert to its default implementation when sqlite3_initialize() is run
  136945. */
  136946. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  136947. }else{
  136948. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  136949. ** alternative memory allocator is engaged to handle all of SQLites
  136950. ** memory allocation needs. */
  136951. #ifdef SQLITE_ENABLE_MEMSYS3
  136952. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  136953. #endif
  136954. #ifdef SQLITE_ENABLE_MEMSYS5
  136955. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  136956. #endif
  136957. }
  136958. break;
  136959. }
  136960. #endif
  136961. case SQLITE_CONFIG_LOOKASIDE: {
  136962. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  136963. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  136964. break;
  136965. }
  136966. /* Record a pointer to the logger function and its first argument.
  136967. ** The default is NULL. Logging is disabled if the function pointer is
  136968. ** NULL.
  136969. */
  136970. case SQLITE_CONFIG_LOG: {
  136971. /* MSVC is picky about pulling func ptrs from va lists.
  136972. ** http://support.microsoft.com/kb/47961
  136973. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  136974. */
  136975. typedef void(*LOGFUNC_t)(void*,int,const char*);
  136976. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  136977. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  136978. break;
  136979. }
  136980. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  136981. ** can be changed at start-time using the
  136982. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  136983. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  136984. */
  136985. case SQLITE_CONFIG_URI: {
  136986. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  136987. ** argument of type int. If non-zero, then URI handling is globally
  136988. ** enabled. If the parameter is zero, then URI handling is globally
  136989. ** disabled. */
  136990. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  136991. break;
  136992. }
  136993. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  136994. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  136995. ** option takes a single integer argument which is interpreted as a
  136996. ** boolean in order to enable or disable the use of covering indices for
  136997. ** full table scans in the query optimizer. */
  136998. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  136999. break;
  137000. }
  137001. #ifdef SQLITE_ENABLE_SQLLOG
  137002. case SQLITE_CONFIG_SQLLOG: {
  137003. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  137004. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  137005. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  137006. break;
  137007. }
  137008. #endif
  137009. case SQLITE_CONFIG_MMAP_SIZE: {
  137010. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  137011. ** integer (sqlite3_int64) values that are the default mmap size limit
  137012. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  137013. ** mmap size limit. */
  137014. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  137015. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  137016. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  137017. ** negative, then that argument is changed to its compile-time default.
  137018. **
  137019. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  137020. ** silently truncated if necessary so that it does not exceed the
  137021. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  137022. ** compile-time option.
  137023. */
  137024. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  137025. mxMmap = SQLITE_MAX_MMAP_SIZE;
  137026. }
  137027. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  137028. if( szMmap>mxMmap) szMmap = mxMmap;
  137029. sqlite3GlobalConfig.mxMmap = mxMmap;
  137030. sqlite3GlobalConfig.szMmap = szMmap;
  137031. break;
  137032. }
  137033. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  137034. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  137035. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  137036. ** unsigned integer value that specifies the maximum size of the created
  137037. ** heap. */
  137038. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  137039. break;
  137040. }
  137041. #endif
  137042. case SQLITE_CONFIG_PMASZ: {
  137043. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  137044. break;
  137045. }
  137046. case SQLITE_CONFIG_STMTJRNL_SPILL: {
  137047. sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
  137048. break;
  137049. }
  137050. default: {
  137051. rc = SQLITE_ERROR;
  137052. break;
  137053. }
  137054. }
  137055. va_end(ap);
  137056. return rc;
  137057. }
  137058. /*
  137059. ** Set up the lookaside buffers for a database connection.
  137060. ** Return SQLITE_OK on success.
  137061. ** If lookaside is already active, return SQLITE_BUSY.
  137062. **
  137063. ** The sz parameter is the number of bytes in each lookaside slot.
  137064. ** The cnt parameter is the number of slots. If pStart is NULL the
  137065. ** space for the lookaside memory is obtained from sqlite3_malloc().
  137066. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  137067. ** the lookaside memory.
  137068. */
  137069. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  137070. #ifndef SQLITE_OMIT_LOOKASIDE
  137071. void *pStart;
  137072. if( sqlite3LookasideUsed(db,0)>0 ){
  137073. return SQLITE_BUSY;
  137074. }
  137075. /* Free any existing lookaside buffer for this handle before
  137076. ** allocating a new one so we don't have to have space for
  137077. ** both at the same time.
  137078. */
  137079. if( db->lookaside.bMalloced ){
  137080. sqlite3_free(db->lookaside.pStart);
  137081. }
  137082. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  137083. ** than a pointer to be useful.
  137084. */
  137085. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  137086. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  137087. if( cnt<0 ) cnt = 0;
  137088. if( sz==0 || cnt==0 ){
  137089. sz = 0;
  137090. pStart = 0;
  137091. }else if( pBuf==0 ){
  137092. sqlite3BeginBenignMalloc();
  137093. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  137094. sqlite3EndBenignMalloc();
  137095. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  137096. }else{
  137097. pStart = pBuf;
  137098. }
  137099. db->lookaside.pStart = pStart;
  137100. db->lookaside.pInit = 0;
  137101. db->lookaside.pFree = 0;
  137102. db->lookaside.sz = (u16)sz;
  137103. if( pStart ){
  137104. int i;
  137105. LookasideSlot *p;
  137106. assert( sz > (int)sizeof(LookasideSlot*) );
  137107. db->lookaside.nSlot = cnt;
  137108. p = (LookasideSlot*)pStart;
  137109. for(i=cnt-1; i>=0; i--){
  137110. p->pNext = db->lookaside.pInit;
  137111. db->lookaside.pInit = p;
  137112. p = (LookasideSlot*)&((u8*)p)[sz];
  137113. }
  137114. db->lookaside.pEnd = p;
  137115. db->lookaside.bDisable = 0;
  137116. db->lookaside.bMalloced = pBuf==0 ?1:0;
  137117. }else{
  137118. db->lookaside.pStart = db;
  137119. db->lookaside.pEnd = db;
  137120. db->lookaside.bDisable = 1;
  137121. db->lookaside.bMalloced = 0;
  137122. db->lookaside.nSlot = 0;
  137123. }
  137124. #endif /* SQLITE_OMIT_LOOKASIDE */
  137125. return SQLITE_OK;
  137126. }
  137127. /*
  137128. ** Return the mutex associated with a database connection.
  137129. */
  137130. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  137131. #ifdef SQLITE_ENABLE_API_ARMOR
  137132. if( !sqlite3SafetyCheckOk(db) ){
  137133. (void)SQLITE_MISUSE_BKPT;
  137134. return 0;
  137135. }
  137136. #endif
  137137. return db->mutex;
  137138. }
  137139. /*
  137140. ** Free up as much memory as we can from the given database
  137141. ** connection.
  137142. */
  137143. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  137144. int i;
  137145. #ifdef SQLITE_ENABLE_API_ARMOR
  137146. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  137147. #endif
  137148. sqlite3_mutex_enter(db->mutex);
  137149. sqlite3BtreeEnterAll(db);
  137150. for(i=0; i<db->nDb; i++){
  137151. Btree *pBt = db->aDb[i].pBt;
  137152. if( pBt ){
  137153. Pager *pPager = sqlite3BtreePager(pBt);
  137154. sqlite3PagerShrink(pPager);
  137155. }
  137156. }
  137157. sqlite3BtreeLeaveAll(db);
  137158. sqlite3_mutex_leave(db->mutex);
  137159. return SQLITE_OK;
  137160. }
  137161. /*
  137162. ** Flush any dirty pages in the pager-cache for any attached database
  137163. ** to disk.
  137164. */
  137165. SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
  137166. int i;
  137167. int rc = SQLITE_OK;
  137168. int bSeenBusy = 0;
  137169. #ifdef SQLITE_ENABLE_API_ARMOR
  137170. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  137171. #endif
  137172. sqlite3_mutex_enter(db->mutex);
  137173. sqlite3BtreeEnterAll(db);
  137174. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  137175. Btree *pBt = db->aDb[i].pBt;
  137176. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  137177. Pager *pPager = sqlite3BtreePager(pBt);
  137178. rc = sqlite3PagerFlush(pPager);
  137179. if( rc==SQLITE_BUSY ){
  137180. bSeenBusy = 1;
  137181. rc = SQLITE_OK;
  137182. }
  137183. }
  137184. }
  137185. sqlite3BtreeLeaveAll(db);
  137186. sqlite3_mutex_leave(db->mutex);
  137187. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  137188. }
  137189. /*
  137190. ** Configuration settings for an individual database connection
  137191. */
  137192. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  137193. va_list ap;
  137194. int rc;
  137195. va_start(ap, op);
  137196. switch( op ){
  137197. case SQLITE_DBCONFIG_MAINDBNAME: {
  137198. /* IMP: R-06824-28531 */
  137199. /* IMP: R-36257-52125 */
  137200. db->aDb[0].zDbSName = va_arg(ap,char*);
  137201. rc = SQLITE_OK;
  137202. break;
  137203. }
  137204. case SQLITE_DBCONFIG_LOOKASIDE: {
  137205. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  137206. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  137207. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  137208. rc = setupLookaside(db, pBuf, sz, cnt);
  137209. break;
  137210. }
  137211. default: {
  137212. static const struct {
  137213. int op; /* The opcode */
  137214. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  137215. } aFlagOp[] = {
  137216. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  137217. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  137218. { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
  137219. { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
  137220. { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
  137221. { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
  137222. { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
  137223. };
  137224. unsigned int i;
  137225. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  137226. for(i=0; i<ArraySize(aFlagOp); i++){
  137227. if( aFlagOp[i].op==op ){
  137228. int onoff = va_arg(ap, int);
  137229. int *pRes = va_arg(ap, int*);
  137230. u32 oldFlags = db->flags;
  137231. if( onoff>0 ){
  137232. db->flags |= aFlagOp[i].mask;
  137233. }else if( onoff==0 ){
  137234. db->flags &= ~aFlagOp[i].mask;
  137235. }
  137236. if( oldFlags!=db->flags ){
  137237. sqlite3ExpirePreparedStatements(db);
  137238. }
  137239. if( pRes ){
  137240. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  137241. }
  137242. rc = SQLITE_OK;
  137243. break;
  137244. }
  137245. }
  137246. break;
  137247. }
  137248. }
  137249. va_end(ap);
  137250. return rc;
  137251. }
  137252. /*
  137253. ** Return true if the buffer z[0..n-1] contains all spaces.
  137254. */
  137255. static int allSpaces(const char *z, int n){
  137256. while( n>0 && z[n-1]==' ' ){ n--; }
  137257. return n==0;
  137258. }
  137259. /*
  137260. ** This is the default collating function named "BINARY" which is always
  137261. ** available.
  137262. **
  137263. ** If the padFlag argument is not NULL then space padding at the end
  137264. ** of strings is ignored. This implements the RTRIM collation.
  137265. */
  137266. static int binCollFunc(
  137267. void *padFlag,
  137268. int nKey1, const void *pKey1,
  137269. int nKey2, const void *pKey2
  137270. ){
  137271. int rc, n;
  137272. n = nKey1<nKey2 ? nKey1 : nKey2;
  137273. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  137274. ** strings byte by byte using the memcmp() function from the standard C
  137275. ** library. */
  137276. assert( pKey1 && pKey2 );
  137277. rc = memcmp(pKey1, pKey2, n);
  137278. if( rc==0 ){
  137279. if( padFlag
  137280. && allSpaces(((char*)pKey1)+n, nKey1-n)
  137281. && allSpaces(((char*)pKey2)+n, nKey2-n)
  137282. ){
  137283. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  137284. ** spaces at the end of either string do not change the result. In other
  137285. ** words, strings will compare equal to one another as long as they
  137286. ** differ only in the number of spaces at the end.
  137287. */
  137288. }else{
  137289. rc = nKey1 - nKey2;
  137290. }
  137291. }
  137292. return rc;
  137293. }
  137294. /*
  137295. ** Another built-in collating sequence: NOCASE.
  137296. **
  137297. ** This collating sequence is intended to be used for "case independent
  137298. ** comparison". SQLite's knowledge of upper and lower case equivalents
  137299. ** extends only to the 26 characters used in the English language.
  137300. **
  137301. ** At the moment there is only a UTF-8 implementation.
  137302. */
  137303. static int nocaseCollatingFunc(
  137304. void *NotUsed,
  137305. int nKey1, const void *pKey1,
  137306. int nKey2, const void *pKey2
  137307. ){
  137308. int r = sqlite3StrNICmp(
  137309. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  137310. UNUSED_PARAMETER(NotUsed);
  137311. if( 0==r ){
  137312. r = nKey1-nKey2;
  137313. }
  137314. return r;
  137315. }
  137316. /*
  137317. ** Return the ROWID of the most recent insert
  137318. */
  137319. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  137320. #ifdef SQLITE_ENABLE_API_ARMOR
  137321. if( !sqlite3SafetyCheckOk(db) ){
  137322. (void)SQLITE_MISUSE_BKPT;
  137323. return 0;
  137324. }
  137325. #endif
  137326. return db->lastRowid;
  137327. }
  137328. /*
  137329. ** Set the value returned by the sqlite3_last_insert_rowid() API function.
  137330. */
  137331. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
  137332. #ifdef SQLITE_ENABLE_API_ARMOR
  137333. if( !sqlite3SafetyCheckOk(db) ){
  137334. (void)SQLITE_MISUSE_BKPT;
  137335. return;
  137336. }
  137337. #endif
  137338. sqlite3_mutex_enter(db->mutex);
  137339. db->lastRowid = iRowid;
  137340. sqlite3_mutex_leave(db->mutex);
  137341. }
  137342. /*
  137343. ** Return the number of changes in the most recent call to sqlite3_exec().
  137344. */
  137345. SQLITE_API int sqlite3_changes(sqlite3 *db){
  137346. #ifdef SQLITE_ENABLE_API_ARMOR
  137347. if( !sqlite3SafetyCheckOk(db) ){
  137348. (void)SQLITE_MISUSE_BKPT;
  137349. return 0;
  137350. }
  137351. #endif
  137352. return db->nChange;
  137353. }
  137354. /*
  137355. ** Return the number of changes since the database handle was opened.
  137356. */
  137357. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  137358. #ifdef SQLITE_ENABLE_API_ARMOR
  137359. if( !sqlite3SafetyCheckOk(db) ){
  137360. (void)SQLITE_MISUSE_BKPT;
  137361. return 0;
  137362. }
  137363. #endif
  137364. return db->nTotalChange;
  137365. }
  137366. /*
  137367. ** Close all open savepoints. This function only manipulates fields of the
  137368. ** database handle object, it does not close any savepoints that may be open
  137369. ** at the b-tree/pager level.
  137370. */
  137371. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  137372. while( db->pSavepoint ){
  137373. Savepoint *pTmp = db->pSavepoint;
  137374. db->pSavepoint = pTmp->pNext;
  137375. sqlite3DbFree(db, pTmp);
  137376. }
  137377. db->nSavepoint = 0;
  137378. db->nStatement = 0;
  137379. db->isTransactionSavepoint = 0;
  137380. }
  137381. /*
  137382. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  137383. ** if this is not the last copy of the function, do not invoke it. Multiple
  137384. ** copies of a single function are created when create_function() is called
  137385. ** with SQLITE_ANY as the encoding.
  137386. */
  137387. static void functionDestroy(sqlite3 *db, FuncDef *p){
  137388. FuncDestructor *pDestructor = p->u.pDestructor;
  137389. if( pDestructor ){
  137390. pDestructor->nRef--;
  137391. if( pDestructor->nRef==0 ){
  137392. pDestructor->xDestroy(pDestructor->pUserData);
  137393. sqlite3DbFree(db, pDestructor);
  137394. }
  137395. }
  137396. }
  137397. /*
  137398. ** Disconnect all sqlite3_vtab objects that belong to database connection
  137399. ** db. This is called when db is being closed.
  137400. */
  137401. static void disconnectAllVtab(sqlite3 *db){
  137402. #ifndef SQLITE_OMIT_VIRTUALTABLE
  137403. int i;
  137404. HashElem *p;
  137405. sqlite3BtreeEnterAll(db);
  137406. for(i=0; i<db->nDb; i++){
  137407. Schema *pSchema = db->aDb[i].pSchema;
  137408. if( db->aDb[i].pSchema ){
  137409. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  137410. Table *pTab = (Table *)sqliteHashData(p);
  137411. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  137412. }
  137413. }
  137414. }
  137415. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  137416. Module *pMod = (Module *)sqliteHashData(p);
  137417. if( pMod->pEpoTab ){
  137418. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  137419. }
  137420. }
  137421. sqlite3VtabUnlockList(db);
  137422. sqlite3BtreeLeaveAll(db);
  137423. #else
  137424. UNUSED_PARAMETER(db);
  137425. #endif
  137426. }
  137427. /*
  137428. ** Return TRUE if database connection db has unfinalized prepared
  137429. ** statements or unfinished sqlite3_backup objects.
  137430. */
  137431. static int connectionIsBusy(sqlite3 *db){
  137432. int j;
  137433. assert( sqlite3_mutex_held(db->mutex) );
  137434. if( db->pVdbe ) return 1;
  137435. for(j=0; j<db->nDb; j++){
  137436. Btree *pBt = db->aDb[j].pBt;
  137437. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  137438. }
  137439. return 0;
  137440. }
  137441. /*
  137442. ** Close an existing SQLite database
  137443. */
  137444. static int sqlite3Close(sqlite3 *db, int forceZombie){
  137445. if( !db ){
  137446. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  137447. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  137448. return SQLITE_OK;
  137449. }
  137450. if( !sqlite3SafetyCheckSickOrOk(db) ){
  137451. return SQLITE_MISUSE_BKPT;
  137452. }
  137453. sqlite3_mutex_enter(db->mutex);
  137454. if( db->mTrace & SQLITE_TRACE_CLOSE ){
  137455. db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
  137456. }
  137457. /* Force xDisconnect calls on all virtual tables */
  137458. disconnectAllVtab(db);
  137459. /* If a transaction is open, the disconnectAllVtab() call above
  137460. ** will not have called the xDisconnect() method on any virtual
  137461. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  137462. ** call will do so. We need to do this before the check for active
  137463. ** SQL statements below, as the v-table implementation may be storing
  137464. ** some prepared statements internally.
  137465. */
  137466. sqlite3VtabRollback(db);
  137467. /* Legacy behavior (sqlite3_close() behavior) is to return
  137468. ** SQLITE_BUSY if the connection can not be closed immediately.
  137469. */
  137470. if( !forceZombie && connectionIsBusy(db) ){
  137471. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  137472. "statements or unfinished backups");
  137473. sqlite3_mutex_leave(db->mutex);
  137474. return SQLITE_BUSY;
  137475. }
  137476. #ifdef SQLITE_ENABLE_SQLLOG
  137477. if( sqlite3GlobalConfig.xSqllog ){
  137478. /* Closing the handle. Fourth parameter is passed the value 2. */
  137479. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  137480. }
  137481. #endif
  137482. /* Convert the connection into a zombie and then close it.
  137483. */
  137484. db->magic = SQLITE_MAGIC_ZOMBIE;
  137485. sqlite3LeaveMutexAndCloseZombie(db);
  137486. return SQLITE_OK;
  137487. }
  137488. /*
  137489. ** Two variations on the public interface for closing a database
  137490. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  137491. ** leaves the connection option if there are unfinalized prepared
  137492. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  137493. ** version forces the connection to become a zombie if there are
  137494. ** unclosed resources, and arranges for deallocation when the last
  137495. ** prepare statement or sqlite3_backup closes.
  137496. */
  137497. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  137498. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  137499. /*
  137500. ** Close the mutex on database connection db.
  137501. **
  137502. ** Furthermore, if database connection db is a zombie (meaning that there
  137503. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  137504. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  137505. ** finished, then free all resources.
  137506. */
  137507. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  137508. HashElem *i; /* Hash table iterator */
  137509. int j;
  137510. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  137511. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  137512. ** then just leave the mutex and return.
  137513. */
  137514. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  137515. sqlite3_mutex_leave(db->mutex);
  137516. return;
  137517. }
  137518. /* If we reach this point, it means that the database connection has
  137519. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  137520. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  137521. ** go ahead and free all resources.
  137522. */
  137523. /* If a transaction is open, roll it back. This also ensures that if
  137524. ** any database schemas have been modified by an uncommitted transaction
  137525. ** they are reset. And that the required b-tree mutex is held to make
  137526. ** the pager rollback and schema reset an atomic operation. */
  137527. sqlite3RollbackAll(db, SQLITE_OK);
  137528. /* Free any outstanding Savepoint structures. */
  137529. sqlite3CloseSavepoints(db);
  137530. /* Close all database connections */
  137531. for(j=0; j<db->nDb; j++){
  137532. struct Db *pDb = &db->aDb[j];
  137533. if( pDb->pBt ){
  137534. sqlite3BtreeClose(pDb->pBt);
  137535. pDb->pBt = 0;
  137536. if( j!=1 ){
  137537. pDb->pSchema = 0;
  137538. }
  137539. }
  137540. }
  137541. /* Clear the TEMP schema separately and last */
  137542. if( db->aDb[1].pSchema ){
  137543. sqlite3SchemaClear(db->aDb[1].pSchema);
  137544. }
  137545. sqlite3VtabUnlockList(db);
  137546. /* Free up the array of auxiliary databases */
  137547. sqlite3CollapseDatabaseArray(db);
  137548. assert( db->nDb<=2 );
  137549. assert( db->aDb==db->aDbStatic );
  137550. /* Tell the code in notify.c that the connection no longer holds any
  137551. ** locks and does not require any further unlock-notify callbacks.
  137552. */
  137553. sqlite3ConnectionClosed(db);
  137554. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  137555. FuncDef *pNext, *p;
  137556. p = sqliteHashData(i);
  137557. do{
  137558. functionDestroy(db, p);
  137559. pNext = p->pNext;
  137560. sqlite3DbFree(db, p);
  137561. p = pNext;
  137562. }while( p );
  137563. }
  137564. sqlite3HashClear(&db->aFunc);
  137565. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  137566. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  137567. /* Invoke any destructors registered for collation sequence user data. */
  137568. for(j=0; j<3; j++){
  137569. if( pColl[j].xDel ){
  137570. pColl[j].xDel(pColl[j].pUser);
  137571. }
  137572. }
  137573. sqlite3DbFree(db, pColl);
  137574. }
  137575. sqlite3HashClear(&db->aCollSeq);
  137576. #ifndef SQLITE_OMIT_VIRTUALTABLE
  137577. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  137578. Module *pMod = (Module *)sqliteHashData(i);
  137579. if( pMod->xDestroy ){
  137580. pMod->xDestroy(pMod->pAux);
  137581. }
  137582. sqlite3VtabEponymousTableClear(db, pMod);
  137583. sqlite3DbFree(db, pMod);
  137584. }
  137585. sqlite3HashClear(&db->aModule);
  137586. #endif
  137587. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  137588. sqlite3ValueFree(db->pErr);
  137589. sqlite3CloseExtensions(db);
  137590. #if SQLITE_USER_AUTHENTICATION
  137591. sqlite3_free(db->auth.zAuthUser);
  137592. sqlite3_free(db->auth.zAuthPW);
  137593. #endif
  137594. db->magic = SQLITE_MAGIC_ERROR;
  137595. /* The temp-database schema is allocated differently from the other schema
  137596. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  137597. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  137598. ** the same sqliteMalloc() as the one that allocates the database
  137599. ** structure?
  137600. */
  137601. sqlite3DbFree(db, db->aDb[1].pSchema);
  137602. sqlite3_mutex_leave(db->mutex);
  137603. db->magic = SQLITE_MAGIC_CLOSED;
  137604. sqlite3_mutex_free(db->mutex);
  137605. assert( sqlite3LookasideUsed(db,0)==0 );
  137606. if( db->lookaside.bMalloced ){
  137607. sqlite3_free(db->lookaside.pStart);
  137608. }
  137609. sqlite3_free(db);
  137610. }
  137611. /*
  137612. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  137613. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  137614. ** breaker") and made to return tripCode if there are any further
  137615. ** attempts to use that cursor. Read cursors remain open and valid
  137616. ** but are "saved" in case the table pages are moved around.
  137617. */
  137618. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  137619. int i;
  137620. int inTrans = 0;
  137621. int schemaChange;
  137622. assert( sqlite3_mutex_held(db->mutex) );
  137623. sqlite3BeginBenignMalloc();
  137624. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  137625. ** This is important in case the transaction being rolled back has
  137626. ** modified the database schema. If the b-tree mutexes are not taken
  137627. ** here, then another shared-cache connection might sneak in between
  137628. ** the database rollback and schema reset, which can cause false
  137629. ** corruption reports in some cases. */
  137630. sqlite3BtreeEnterAll(db);
  137631. schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
  137632. for(i=0; i<db->nDb; i++){
  137633. Btree *p = db->aDb[i].pBt;
  137634. if( p ){
  137635. if( sqlite3BtreeIsInTrans(p) ){
  137636. inTrans = 1;
  137637. }
  137638. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  137639. }
  137640. }
  137641. sqlite3VtabRollback(db);
  137642. sqlite3EndBenignMalloc();
  137643. if( (db->mDbFlags&DBFLAG_SchemaChange)!=0 && db->init.busy==0 ){
  137644. sqlite3ExpirePreparedStatements(db);
  137645. sqlite3ResetAllSchemasOfConnection(db);
  137646. }
  137647. sqlite3BtreeLeaveAll(db);
  137648. /* Any deferred constraint violations have now been resolved. */
  137649. db->nDeferredCons = 0;
  137650. db->nDeferredImmCons = 0;
  137651. db->flags &= ~SQLITE_DeferFKs;
  137652. /* If one has been configured, invoke the rollback-hook callback */
  137653. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  137654. db->xRollbackCallback(db->pRollbackArg);
  137655. }
  137656. }
  137657. /*
  137658. ** Return a static string containing the name corresponding to the error code
  137659. ** specified in the argument.
  137660. */
  137661. #if defined(SQLITE_NEED_ERR_NAME)
  137662. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  137663. const char *zName = 0;
  137664. int i, origRc = rc;
  137665. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  137666. switch( rc ){
  137667. case SQLITE_OK: zName = "SQLITE_OK"; break;
  137668. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  137669. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  137670. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  137671. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  137672. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  137673. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  137674. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  137675. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  137676. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  137677. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  137678. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  137679. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  137680. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  137681. case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
  137682. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  137683. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  137684. case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
  137685. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  137686. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  137687. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  137688. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  137689. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  137690. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  137691. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  137692. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  137693. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  137694. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  137695. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  137696. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  137697. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  137698. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  137699. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  137700. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  137701. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  137702. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  137703. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  137704. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  137705. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  137706. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  137707. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  137708. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  137709. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  137710. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  137711. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  137712. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  137713. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  137714. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  137715. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  137716. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  137717. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  137718. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  137719. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  137720. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  137721. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  137722. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  137723. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  137724. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  137725. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  137726. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  137727. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  137728. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  137729. case SQLITE_CONSTRAINT_FOREIGNKEY:
  137730. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  137731. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  137732. case SQLITE_CONSTRAINT_PRIMARYKEY:
  137733. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  137734. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  137735. case SQLITE_CONSTRAINT_COMMITHOOK:
  137736. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  137737. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  137738. case SQLITE_CONSTRAINT_FUNCTION:
  137739. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  137740. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  137741. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  137742. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  137743. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  137744. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  137745. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  137746. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  137747. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  137748. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  137749. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  137750. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  137751. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  137752. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  137753. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  137754. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  137755. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  137756. }
  137757. }
  137758. if( zName==0 ){
  137759. static char zBuf[50];
  137760. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  137761. zName = zBuf;
  137762. }
  137763. return zName;
  137764. }
  137765. #endif
  137766. /*
  137767. ** Return a static string that describes the kind of error specified in the
  137768. ** argument.
  137769. */
  137770. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  137771. static const char* const aMsg[] = {
  137772. /* SQLITE_OK */ "not an error",
  137773. /* SQLITE_ERROR */ "SQL logic error",
  137774. /* SQLITE_INTERNAL */ 0,
  137775. /* SQLITE_PERM */ "access permission denied",
  137776. /* SQLITE_ABORT */ "query aborted",
  137777. /* SQLITE_BUSY */ "database is locked",
  137778. /* SQLITE_LOCKED */ "database table is locked",
  137779. /* SQLITE_NOMEM */ "out of memory",
  137780. /* SQLITE_READONLY */ "attempt to write a readonly database",
  137781. /* SQLITE_INTERRUPT */ "interrupted",
  137782. /* SQLITE_IOERR */ "disk I/O error",
  137783. /* SQLITE_CORRUPT */ "database disk image is malformed",
  137784. /* SQLITE_NOTFOUND */ "unknown operation",
  137785. /* SQLITE_FULL */ "database or disk is full",
  137786. /* SQLITE_CANTOPEN */ "unable to open database file",
  137787. /* SQLITE_PROTOCOL */ "locking protocol",
  137788. /* SQLITE_EMPTY */ 0,
  137789. /* SQLITE_SCHEMA */ "database schema has changed",
  137790. /* SQLITE_TOOBIG */ "string or blob too big",
  137791. /* SQLITE_CONSTRAINT */ "constraint failed",
  137792. /* SQLITE_MISMATCH */ "datatype mismatch",
  137793. /* SQLITE_MISUSE */ "bad parameter or other API misuse",
  137794. #ifdef SQLITE_DISABLE_LFS
  137795. /* SQLITE_NOLFS */ "large file support is disabled",
  137796. #else
  137797. /* SQLITE_NOLFS */ 0,
  137798. #endif
  137799. /* SQLITE_AUTH */ "authorization denied",
  137800. /* SQLITE_FORMAT */ 0,
  137801. /* SQLITE_RANGE */ "column index out of range",
  137802. /* SQLITE_NOTADB */ "file is not a database",
  137803. /* SQLITE_NOTICE */ "notification message",
  137804. /* SQLITE_WARNING */ "warning message",
  137805. };
  137806. const char *zErr = "unknown error";
  137807. switch( rc ){
  137808. case SQLITE_ABORT_ROLLBACK: {
  137809. zErr = "abort due to ROLLBACK";
  137810. break;
  137811. }
  137812. case SQLITE_ROW: {
  137813. zErr = "another row available";
  137814. break;
  137815. }
  137816. case SQLITE_DONE: {
  137817. zErr = "no more rows available";
  137818. break;
  137819. }
  137820. default: {
  137821. rc &= 0xff;
  137822. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  137823. zErr = aMsg[rc];
  137824. }
  137825. break;
  137826. }
  137827. }
  137828. return zErr;
  137829. }
  137830. /*
  137831. ** This routine implements a busy callback that sleeps and tries
  137832. ** again until a timeout value is reached. The timeout value is
  137833. ** an integer number of milliseconds passed in as the first
  137834. ** argument.
  137835. **
  137836. ** Return non-zero to retry the lock. Return zero to stop trying
  137837. ** and cause SQLite to return SQLITE_BUSY.
  137838. */
  137839. static int sqliteDefaultBusyCallback(
  137840. void *ptr, /* Database connection */
  137841. int count, /* Number of times table has been busy */
  137842. sqlite3_file *pFile /* The file on which the lock occurred */
  137843. ){
  137844. #if SQLITE_OS_WIN || HAVE_USLEEP
  137845. /* This case is for systems that have support for sleeping for fractions of
  137846. ** a second. Examples: All windows systems, unix systems with usleep() */
  137847. static const u8 delays[] =
  137848. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  137849. static const u8 totals[] =
  137850. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  137851. # define NDELAY ArraySize(delays)
  137852. sqlite3 *db = (sqlite3 *)ptr;
  137853. int tmout = db->busyTimeout;
  137854. int delay, prior;
  137855. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  137856. if( sqlite3OsFileControl(pFile,SQLITE_FCNTL_LOCK_TIMEOUT,&tmout)==SQLITE_OK ){
  137857. if( count ){
  137858. tmout = 0;
  137859. sqlite3OsFileControl(pFile, SQLITE_FCNTL_LOCK_TIMEOUT, &tmout);
  137860. return 0;
  137861. }else{
  137862. return 1;
  137863. }
  137864. }
  137865. #else
  137866. UNUSED_PARAMETER(pFile);
  137867. #endif
  137868. assert( count>=0 );
  137869. if( count < NDELAY ){
  137870. delay = delays[count];
  137871. prior = totals[count];
  137872. }else{
  137873. delay = delays[NDELAY-1];
  137874. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  137875. }
  137876. if( prior + delay > tmout ){
  137877. delay = tmout - prior;
  137878. if( delay<=0 ) return 0;
  137879. }
  137880. sqlite3OsSleep(db->pVfs, delay*1000);
  137881. return 1;
  137882. #else
  137883. /* This case for unix systems that lack usleep() support. Sleeping
  137884. ** must be done in increments of whole seconds */
  137885. sqlite3 *db = (sqlite3 *)ptr;
  137886. int tmout = ((sqlite3 *)ptr)->busyTimeout;
  137887. UNUSED_PARAMETER(pFile);
  137888. if( (count+1)*1000 > tmout ){
  137889. return 0;
  137890. }
  137891. sqlite3OsSleep(db->pVfs, 1000000);
  137892. return 1;
  137893. #endif
  137894. }
  137895. /*
  137896. ** Invoke the given busy handler.
  137897. **
  137898. ** This routine is called when an operation failed to acquire a
  137899. ** lock on VFS file pFile.
  137900. **
  137901. ** If this routine returns non-zero, the lock is retried. If it
  137902. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  137903. */
  137904. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p, sqlite3_file *pFile){
  137905. int rc;
  137906. if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
  137907. if( p->bExtraFileArg ){
  137908. /* Add an extra parameter with the pFile pointer to the end of the
  137909. ** callback argument list */
  137910. int (*xTra)(void*,int,sqlite3_file*);
  137911. xTra = (int(*)(void*,int,sqlite3_file*))p->xBusyHandler;
  137912. rc = xTra(p->pBusyArg, p->nBusy, pFile);
  137913. }else{
  137914. /* Legacy style busy handler callback */
  137915. rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
  137916. }
  137917. if( rc==0 ){
  137918. p->nBusy = -1;
  137919. }else{
  137920. p->nBusy++;
  137921. }
  137922. return rc;
  137923. }
  137924. /*
  137925. ** This routine sets the busy callback for an Sqlite database to the
  137926. ** given callback function with the given argument.
  137927. */
  137928. SQLITE_API int sqlite3_busy_handler(
  137929. sqlite3 *db,
  137930. int (*xBusy)(void*,int),
  137931. void *pArg
  137932. ){
  137933. #ifdef SQLITE_ENABLE_API_ARMOR
  137934. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  137935. #endif
  137936. sqlite3_mutex_enter(db->mutex);
  137937. db->busyHandler.xBusyHandler = xBusy;
  137938. db->busyHandler.pBusyArg = pArg;
  137939. db->busyHandler.nBusy = 0;
  137940. db->busyHandler.bExtraFileArg = 0;
  137941. db->busyTimeout = 0;
  137942. sqlite3_mutex_leave(db->mutex);
  137943. return SQLITE_OK;
  137944. }
  137945. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  137946. /*
  137947. ** This routine sets the progress callback for an Sqlite database to the
  137948. ** given callback function with the given argument. The progress callback will
  137949. ** be invoked every nOps opcodes.
  137950. */
  137951. SQLITE_API void sqlite3_progress_handler(
  137952. sqlite3 *db,
  137953. int nOps,
  137954. int (*xProgress)(void*),
  137955. void *pArg
  137956. ){
  137957. #ifdef SQLITE_ENABLE_API_ARMOR
  137958. if( !sqlite3SafetyCheckOk(db) ){
  137959. (void)SQLITE_MISUSE_BKPT;
  137960. return;
  137961. }
  137962. #endif
  137963. sqlite3_mutex_enter(db->mutex);
  137964. if( nOps>0 ){
  137965. db->xProgress = xProgress;
  137966. db->nProgressOps = (unsigned)nOps;
  137967. db->pProgressArg = pArg;
  137968. }else{
  137969. db->xProgress = 0;
  137970. db->nProgressOps = 0;
  137971. db->pProgressArg = 0;
  137972. }
  137973. sqlite3_mutex_leave(db->mutex);
  137974. }
  137975. #endif
  137976. /*
  137977. ** This routine installs a default busy handler that waits for the
  137978. ** specified number of milliseconds before returning 0.
  137979. */
  137980. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  137981. #ifdef SQLITE_ENABLE_API_ARMOR
  137982. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  137983. #endif
  137984. if( ms>0 ){
  137985. sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
  137986. (void*)db);
  137987. db->busyTimeout = ms;
  137988. db->busyHandler.bExtraFileArg = 1;
  137989. }else{
  137990. sqlite3_busy_handler(db, 0, 0);
  137991. }
  137992. return SQLITE_OK;
  137993. }
  137994. /*
  137995. ** Cause any pending operation to stop at its earliest opportunity.
  137996. */
  137997. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  137998. #ifdef SQLITE_ENABLE_API_ARMOR
  137999. if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
  138000. (void)SQLITE_MISUSE_BKPT;
  138001. return;
  138002. }
  138003. #endif
  138004. db->u1.isInterrupted = 1;
  138005. }
  138006. /*
  138007. ** This function is exactly the same as sqlite3_create_function(), except
  138008. ** that it is designed to be called by internal code. The difference is
  138009. ** that if a malloc() fails in sqlite3_create_function(), an error code
  138010. ** is returned and the mallocFailed flag cleared.
  138011. */
  138012. SQLITE_PRIVATE int sqlite3CreateFunc(
  138013. sqlite3 *db,
  138014. const char *zFunctionName,
  138015. int nArg,
  138016. int enc,
  138017. void *pUserData,
  138018. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  138019. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  138020. void (*xFinal)(sqlite3_context*),
  138021. FuncDestructor *pDestructor
  138022. ){
  138023. FuncDef *p;
  138024. int nName;
  138025. int extraFlags;
  138026. assert( sqlite3_mutex_held(db->mutex) );
  138027. if( zFunctionName==0 ||
  138028. (xSFunc && (xFinal || xStep)) ||
  138029. (!xSFunc && (xFinal && !xStep)) ||
  138030. (!xSFunc && (!xFinal && xStep)) ||
  138031. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  138032. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  138033. return SQLITE_MISUSE_BKPT;
  138034. }
  138035. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  138036. extraFlags = enc & SQLITE_DETERMINISTIC;
  138037. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  138038. #ifndef SQLITE_OMIT_UTF16
  138039. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  138040. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  138041. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  138042. **
  138043. ** If SQLITE_ANY is specified, add three versions of the function
  138044. ** to the hash table.
  138045. */
  138046. if( enc==SQLITE_UTF16 ){
  138047. enc = SQLITE_UTF16NATIVE;
  138048. }else if( enc==SQLITE_ANY ){
  138049. int rc;
  138050. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  138051. pUserData, xSFunc, xStep, xFinal, pDestructor);
  138052. if( rc==SQLITE_OK ){
  138053. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  138054. pUserData, xSFunc, xStep, xFinal, pDestructor);
  138055. }
  138056. if( rc!=SQLITE_OK ){
  138057. return rc;
  138058. }
  138059. enc = SQLITE_UTF16BE;
  138060. }
  138061. #else
  138062. enc = SQLITE_UTF8;
  138063. #endif
  138064. /* Check if an existing function is being overridden or deleted. If so,
  138065. ** and there are active VMs, then return SQLITE_BUSY. If a function
  138066. ** is being overridden/deleted but there are no active VMs, allow the
  138067. ** operation to continue but invalidate all precompiled statements.
  138068. */
  138069. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
  138070. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  138071. if( db->nVdbeActive ){
  138072. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  138073. "unable to delete/modify user-function due to active statements");
  138074. assert( !db->mallocFailed );
  138075. return SQLITE_BUSY;
  138076. }else{
  138077. sqlite3ExpirePreparedStatements(db);
  138078. }
  138079. }
  138080. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
  138081. assert(p || db->mallocFailed);
  138082. if( !p ){
  138083. return SQLITE_NOMEM_BKPT;
  138084. }
  138085. /* If an older version of the function with a configured destructor is
  138086. ** being replaced invoke the destructor function here. */
  138087. functionDestroy(db, p);
  138088. if( pDestructor ){
  138089. pDestructor->nRef++;
  138090. }
  138091. p->u.pDestructor = pDestructor;
  138092. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  138093. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  138094. p->xSFunc = xSFunc ? xSFunc : xStep;
  138095. p->xFinalize = xFinal;
  138096. p->pUserData = pUserData;
  138097. p->nArg = (u16)nArg;
  138098. return SQLITE_OK;
  138099. }
  138100. /*
  138101. ** Create new user functions.
  138102. */
  138103. SQLITE_API int sqlite3_create_function(
  138104. sqlite3 *db,
  138105. const char *zFunc,
  138106. int nArg,
  138107. int enc,
  138108. void *p,
  138109. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  138110. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  138111. void (*xFinal)(sqlite3_context*)
  138112. ){
  138113. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
  138114. xFinal, 0);
  138115. }
  138116. SQLITE_API int sqlite3_create_function_v2(
  138117. sqlite3 *db,
  138118. const char *zFunc,
  138119. int nArg,
  138120. int enc,
  138121. void *p,
  138122. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  138123. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  138124. void (*xFinal)(sqlite3_context*),
  138125. void (*xDestroy)(void *)
  138126. ){
  138127. int rc = SQLITE_ERROR;
  138128. FuncDestructor *pArg = 0;
  138129. #ifdef SQLITE_ENABLE_API_ARMOR
  138130. if( !sqlite3SafetyCheckOk(db) ){
  138131. return SQLITE_MISUSE_BKPT;
  138132. }
  138133. #endif
  138134. sqlite3_mutex_enter(db->mutex);
  138135. if( xDestroy ){
  138136. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  138137. if( !pArg ){
  138138. xDestroy(p);
  138139. goto out;
  138140. }
  138141. pArg->xDestroy = xDestroy;
  138142. pArg->pUserData = p;
  138143. }
  138144. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
  138145. if( pArg && pArg->nRef==0 ){
  138146. assert( rc!=SQLITE_OK );
  138147. xDestroy(p);
  138148. sqlite3DbFree(db, pArg);
  138149. }
  138150. out:
  138151. rc = sqlite3ApiExit(db, rc);
  138152. sqlite3_mutex_leave(db->mutex);
  138153. return rc;
  138154. }
  138155. #ifndef SQLITE_OMIT_UTF16
  138156. SQLITE_API int sqlite3_create_function16(
  138157. sqlite3 *db,
  138158. const void *zFunctionName,
  138159. int nArg,
  138160. int eTextRep,
  138161. void *p,
  138162. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  138163. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  138164. void (*xFinal)(sqlite3_context*)
  138165. ){
  138166. int rc;
  138167. char *zFunc8;
  138168. #ifdef SQLITE_ENABLE_API_ARMOR
  138169. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  138170. #endif
  138171. sqlite3_mutex_enter(db->mutex);
  138172. assert( !db->mallocFailed );
  138173. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  138174. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
  138175. sqlite3DbFree(db, zFunc8);
  138176. rc = sqlite3ApiExit(db, rc);
  138177. sqlite3_mutex_leave(db->mutex);
  138178. return rc;
  138179. }
  138180. #endif
  138181. /*
  138182. ** Declare that a function has been overloaded by a virtual table.
  138183. **
  138184. ** If the function already exists as a regular global function, then
  138185. ** this routine is a no-op. If the function does not exist, then create
  138186. ** a new one that always throws a run-time error.
  138187. **
  138188. ** When virtual tables intend to provide an overloaded function, they
  138189. ** should call this routine to make sure the global function exists.
  138190. ** A global function must exist in order for name resolution to work
  138191. ** properly.
  138192. */
  138193. SQLITE_API int sqlite3_overload_function(
  138194. sqlite3 *db,
  138195. const char *zName,
  138196. int nArg
  138197. ){
  138198. int rc = SQLITE_OK;
  138199. #ifdef SQLITE_ENABLE_API_ARMOR
  138200. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  138201. return SQLITE_MISUSE_BKPT;
  138202. }
  138203. #endif
  138204. sqlite3_mutex_enter(db->mutex);
  138205. if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
  138206. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  138207. 0, sqlite3InvalidFunction, 0, 0, 0);
  138208. }
  138209. rc = sqlite3ApiExit(db, rc);
  138210. sqlite3_mutex_leave(db->mutex);
  138211. return rc;
  138212. }
  138213. #ifndef SQLITE_OMIT_TRACE
  138214. /*
  138215. ** Register a trace function. The pArg from the previously registered trace
  138216. ** is returned.
  138217. **
  138218. ** A NULL trace function means that no tracing is executes. A non-NULL
  138219. ** trace is a pointer to a function that is invoked at the start of each
  138220. ** SQL statement.
  138221. */
  138222. #ifndef SQLITE_OMIT_DEPRECATED
  138223. SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
  138224. void *pOld;
  138225. #ifdef SQLITE_ENABLE_API_ARMOR
  138226. if( !sqlite3SafetyCheckOk(db) ){
  138227. (void)SQLITE_MISUSE_BKPT;
  138228. return 0;
  138229. }
  138230. #endif
  138231. sqlite3_mutex_enter(db->mutex);
  138232. pOld = db->pTraceArg;
  138233. db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
  138234. db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
  138235. db->pTraceArg = pArg;
  138236. sqlite3_mutex_leave(db->mutex);
  138237. return pOld;
  138238. }
  138239. #endif /* SQLITE_OMIT_DEPRECATED */
  138240. /* Register a trace callback using the version-2 interface.
  138241. */
  138242. SQLITE_API int sqlite3_trace_v2(
  138243. sqlite3 *db, /* Trace this connection */
  138244. unsigned mTrace, /* Mask of events to be traced */
  138245. int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
  138246. void *pArg /* Context */
  138247. ){
  138248. #ifdef SQLITE_ENABLE_API_ARMOR
  138249. if( !sqlite3SafetyCheckOk(db) ){
  138250. return SQLITE_MISUSE_BKPT;
  138251. }
  138252. #endif
  138253. sqlite3_mutex_enter(db->mutex);
  138254. if( mTrace==0 ) xTrace = 0;
  138255. if( xTrace==0 ) mTrace = 0;
  138256. db->mTrace = mTrace;
  138257. db->xTrace = xTrace;
  138258. db->pTraceArg = pArg;
  138259. sqlite3_mutex_leave(db->mutex);
  138260. return SQLITE_OK;
  138261. }
  138262. #ifndef SQLITE_OMIT_DEPRECATED
  138263. /*
  138264. ** Register a profile function. The pArg from the previously registered
  138265. ** profile function is returned.
  138266. **
  138267. ** A NULL profile function means that no profiling is executes. A non-NULL
  138268. ** profile is a pointer to a function that is invoked at the conclusion of
  138269. ** each SQL statement that is run.
  138270. */
  138271. SQLITE_API void *sqlite3_profile(
  138272. sqlite3 *db,
  138273. void (*xProfile)(void*,const char*,sqlite_uint64),
  138274. void *pArg
  138275. ){
  138276. void *pOld;
  138277. #ifdef SQLITE_ENABLE_API_ARMOR
  138278. if( !sqlite3SafetyCheckOk(db) ){
  138279. (void)SQLITE_MISUSE_BKPT;
  138280. return 0;
  138281. }
  138282. #endif
  138283. sqlite3_mutex_enter(db->mutex);
  138284. pOld = db->pProfileArg;
  138285. db->xProfile = xProfile;
  138286. db->pProfileArg = pArg;
  138287. sqlite3_mutex_leave(db->mutex);
  138288. return pOld;
  138289. }
  138290. #endif /* SQLITE_OMIT_DEPRECATED */
  138291. #endif /* SQLITE_OMIT_TRACE */
  138292. /*
  138293. ** Register a function to be invoked when a transaction commits.
  138294. ** If the invoked function returns non-zero, then the commit becomes a
  138295. ** rollback.
  138296. */
  138297. SQLITE_API void *sqlite3_commit_hook(
  138298. sqlite3 *db, /* Attach the hook to this database */
  138299. int (*xCallback)(void*), /* Function to invoke on each commit */
  138300. void *pArg /* Argument to the function */
  138301. ){
  138302. void *pOld;
  138303. #ifdef SQLITE_ENABLE_API_ARMOR
  138304. if( !sqlite3SafetyCheckOk(db) ){
  138305. (void)SQLITE_MISUSE_BKPT;
  138306. return 0;
  138307. }
  138308. #endif
  138309. sqlite3_mutex_enter(db->mutex);
  138310. pOld = db->pCommitArg;
  138311. db->xCommitCallback = xCallback;
  138312. db->pCommitArg = pArg;
  138313. sqlite3_mutex_leave(db->mutex);
  138314. return pOld;
  138315. }
  138316. /*
  138317. ** Register a callback to be invoked each time a row is updated,
  138318. ** inserted or deleted using this database connection.
  138319. */
  138320. SQLITE_API void *sqlite3_update_hook(
  138321. sqlite3 *db, /* Attach the hook to this database */
  138322. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  138323. void *pArg /* Argument to the function */
  138324. ){
  138325. void *pRet;
  138326. #ifdef SQLITE_ENABLE_API_ARMOR
  138327. if( !sqlite3SafetyCheckOk(db) ){
  138328. (void)SQLITE_MISUSE_BKPT;
  138329. return 0;
  138330. }
  138331. #endif
  138332. sqlite3_mutex_enter(db->mutex);
  138333. pRet = db->pUpdateArg;
  138334. db->xUpdateCallback = xCallback;
  138335. db->pUpdateArg = pArg;
  138336. sqlite3_mutex_leave(db->mutex);
  138337. return pRet;
  138338. }
  138339. /*
  138340. ** Register a callback to be invoked each time a transaction is rolled
  138341. ** back by this database connection.
  138342. */
  138343. SQLITE_API void *sqlite3_rollback_hook(
  138344. sqlite3 *db, /* Attach the hook to this database */
  138345. void (*xCallback)(void*), /* Callback function */
  138346. void *pArg /* Argument to the function */
  138347. ){
  138348. void *pRet;
  138349. #ifdef SQLITE_ENABLE_API_ARMOR
  138350. if( !sqlite3SafetyCheckOk(db) ){
  138351. (void)SQLITE_MISUSE_BKPT;
  138352. return 0;
  138353. }
  138354. #endif
  138355. sqlite3_mutex_enter(db->mutex);
  138356. pRet = db->pRollbackArg;
  138357. db->xRollbackCallback = xCallback;
  138358. db->pRollbackArg = pArg;
  138359. sqlite3_mutex_leave(db->mutex);
  138360. return pRet;
  138361. }
  138362. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  138363. /*
  138364. ** Register a callback to be invoked each time a row is updated,
  138365. ** inserted or deleted using this database connection.
  138366. */
  138367. SQLITE_API void *sqlite3_preupdate_hook(
  138368. sqlite3 *db, /* Attach the hook to this database */
  138369. void(*xCallback)( /* Callback function */
  138370. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
  138371. void *pArg /* First callback argument */
  138372. ){
  138373. void *pRet;
  138374. sqlite3_mutex_enter(db->mutex);
  138375. pRet = db->pPreUpdateArg;
  138376. db->xPreUpdateCallback = xCallback;
  138377. db->pPreUpdateArg = pArg;
  138378. sqlite3_mutex_leave(db->mutex);
  138379. return pRet;
  138380. }
  138381. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  138382. #ifndef SQLITE_OMIT_WAL
  138383. /*
  138384. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  138385. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  138386. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  138387. ** wal_autocheckpoint()).
  138388. */
  138389. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  138390. void *pClientData, /* Argument */
  138391. sqlite3 *db, /* Connection */
  138392. const char *zDb, /* Database */
  138393. int nFrame /* Size of WAL */
  138394. ){
  138395. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  138396. sqlite3BeginBenignMalloc();
  138397. sqlite3_wal_checkpoint(db, zDb);
  138398. sqlite3EndBenignMalloc();
  138399. }
  138400. return SQLITE_OK;
  138401. }
  138402. #endif /* SQLITE_OMIT_WAL */
  138403. /*
  138404. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  138405. ** a database after committing a transaction if there are nFrame or
  138406. ** more frames in the log file. Passing zero or a negative value as the
  138407. ** nFrame parameter disables automatic checkpoints entirely.
  138408. **
  138409. ** The callback registered by this function replaces any existing callback
  138410. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  138411. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  138412. ** configured by this function.
  138413. */
  138414. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  138415. #ifdef SQLITE_OMIT_WAL
  138416. UNUSED_PARAMETER(db);
  138417. UNUSED_PARAMETER(nFrame);
  138418. #else
  138419. #ifdef SQLITE_ENABLE_API_ARMOR
  138420. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  138421. #endif
  138422. if( nFrame>0 ){
  138423. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  138424. }else{
  138425. sqlite3_wal_hook(db, 0, 0);
  138426. }
  138427. #endif
  138428. return SQLITE_OK;
  138429. }
  138430. /*
  138431. ** Register a callback to be invoked each time a transaction is written
  138432. ** into the write-ahead-log by this database connection.
  138433. */
  138434. SQLITE_API void *sqlite3_wal_hook(
  138435. sqlite3 *db, /* Attach the hook to this db handle */
  138436. int(*xCallback)(void *, sqlite3*, const char*, int),
  138437. void *pArg /* First argument passed to xCallback() */
  138438. ){
  138439. #ifndef SQLITE_OMIT_WAL
  138440. void *pRet;
  138441. #ifdef SQLITE_ENABLE_API_ARMOR
  138442. if( !sqlite3SafetyCheckOk(db) ){
  138443. (void)SQLITE_MISUSE_BKPT;
  138444. return 0;
  138445. }
  138446. #endif
  138447. sqlite3_mutex_enter(db->mutex);
  138448. pRet = db->pWalArg;
  138449. db->xWalCallback = xCallback;
  138450. db->pWalArg = pArg;
  138451. sqlite3_mutex_leave(db->mutex);
  138452. return pRet;
  138453. #else
  138454. return 0;
  138455. #endif
  138456. }
  138457. /*
  138458. ** Checkpoint database zDb.
  138459. */
  138460. SQLITE_API int sqlite3_wal_checkpoint_v2(
  138461. sqlite3 *db, /* Database handle */
  138462. const char *zDb, /* Name of attached database (or NULL) */
  138463. int eMode, /* SQLITE_CHECKPOINT_* value */
  138464. int *pnLog, /* OUT: Size of WAL log in frames */
  138465. int *pnCkpt /* OUT: Total number of frames checkpointed */
  138466. ){
  138467. #ifdef SQLITE_OMIT_WAL
  138468. return SQLITE_OK;
  138469. #else
  138470. int rc; /* Return code */
  138471. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  138472. #ifdef SQLITE_ENABLE_API_ARMOR
  138473. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  138474. #endif
  138475. /* Initialize the output variables to -1 in case an error occurs. */
  138476. if( pnLog ) *pnLog = -1;
  138477. if( pnCkpt ) *pnCkpt = -1;
  138478. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  138479. assert( SQLITE_CHECKPOINT_FULL==1 );
  138480. assert( SQLITE_CHECKPOINT_RESTART==2 );
  138481. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  138482. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  138483. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  138484. ** mode: */
  138485. return SQLITE_MISUSE;
  138486. }
  138487. sqlite3_mutex_enter(db->mutex);
  138488. if( zDb && zDb[0] ){
  138489. iDb = sqlite3FindDbName(db, zDb);
  138490. }
  138491. if( iDb<0 ){
  138492. rc = SQLITE_ERROR;
  138493. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  138494. }else{
  138495. db->busyHandler.nBusy = 0;
  138496. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  138497. sqlite3Error(db, rc);
  138498. }
  138499. rc = sqlite3ApiExit(db, rc);
  138500. /* If there are no active statements, clear the interrupt flag at this
  138501. ** point. */
  138502. if( db->nVdbeActive==0 ){
  138503. db->u1.isInterrupted = 0;
  138504. }
  138505. sqlite3_mutex_leave(db->mutex);
  138506. return rc;
  138507. #endif
  138508. }
  138509. /*
  138510. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  138511. ** to contains a zero-length string, all attached databases are
  138512. ** checkpointed.
  138513. */
  138514. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  138515. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  138516. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  138517. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  138518. }
  138519. #ifndef SQLITE_OMIT_WAL
  138520. /*
  138521. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  138522. ** not currently open in WAL mode.
  138523. **
  138524. ** If a transaction is open on the database being checkpointed, this
  138525. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  138526. ** an error occurs while running the checkpoint, an SQLite error code is
  138527. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  138528. **
  138529. ** The mutex on database handle db should be held by the caller. The mutex
  138530. ** associated with the specific b-tree being checkpointed is taken by
  138531. ** this function while the checkpoint is running.
  138532. **
  138533. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  138534. ** checkpointed. If an error is encountered it is returned immediately -
  138535. ** no attempt is made to checkpoint any remaining databases.
  138536. **
  138537. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
  138538. ** or TRUNCATE.
  138539. */
  138540. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  138541. int rc = SQLITE_OK; /* Return code */
  138542. int i; /* Used to iterate through attached dbs */
  138543. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  138544. assert( sqlite3_mutex_held(db->mutex) );
  138545. assert( !pnLog || *pnLog==-1 );
  138546. assert( !pnCkpt || *pnCkpt==-1 );
  138547. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  138548. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  138549. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  138550. pnLog = 0;
  138551. pnCkpt = 0;
  138552. if( rc==SQLITE_BUSY ){
  138553. bBusy = 1;
  138554. rc = SQLITE_OK;
  138555. }
  138556. }
  138557. }
  138558. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  138559. }
  138560. #endif /* SQLITE_OMIT_WAL */
  138561. /*
  138562. ** This function returns true if main-memory should be used instead of
  138563. ** a temporary file for transient pager files and statement journals.
  138564. ** The value returned depends on the value of db->temp_store (runtime
  138565. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  138566. ** following table describes the relationship between these two values
  138567. ** and this functions return value.
  138568. **
  138569. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  138570. ** ----------------- -------------- ------------------------------
  138571. ** 0 any file (return 0)
  138572. ** 1 1 file (return 0)
  138573. ** 1 2 memory (return 1)
  138574. ** 1 0 file (return 0)
  138575. ** 2 1 file (return 0)
  138576. ** 2 2 memory (return 1)
  138577. ** 2 0 memory (return 1)
  138578. ** 3 any memory (return 1)
  138579. */
  138580. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  138581. #if SQLITE_TEMP_STORE==1
  138582. return ( db->temp_store==2 );
  138583. #endif
  138584. #if SQLITE_TEMP_STORE==2
  138585. return ( db->temp_store!=1 );
  138586. #endif
  138587. #if SQLITE_TEMP_STORE==3
  138588. UNUSED_PARAMETER(db);
  138589. return 1;
  138590. #endif
  138591. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  138592. UNUSED_PARAMETER(db);
  138593. return 0;
  138594. #endif
  138595. }
  138596. /*
  138597. ** Return UTF-8 encoded English language explanation of the most recent
  138598. ** error.
  138599. */
  138600. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  138601. const char *z;
  138602. if( !db ){
  138603. return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  138604. }
  138605. if( !sqlite3SafetyCheckSickOrOk(db) ){
  138606. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  138607. }
  138608. sqlite3_mutex_enter(db->mutex);
  138609. if( db->mallocFailed ){
  138610. z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  138611. }else{
  138612. testcase( db->pErr==0 );
  138613. z = (char*)sqlite3_value_text(db->pErr);
  138614. assert( !db->mallocFailed );
  138615. if( z==0 ){
  138616. z = sqlite3ErrStr(db->errCode);
  138617. }
  138618. }
  138619. sqlite3_mutex_leave(db->mutex);
  138620. return z;
  138621. }
  138622. #ifndef SQLITE_OMIT_UTF16
  138623. /*
  138624. ** Return UTF-16 encoded English language explanation of the most recent
  138625. ** error.
  138626. */
  138627. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  138628. static const u16 outOfMem[] = {
  138629. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  138630. };
  138631. static const u16 misuse[] = {
  138632. 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
  138633. 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
  138634. 'm', 'i', 's', 'u', 's', 'e', 0
  138635. };
  138636. const void *z;
  138637. if( !db ){
  138638. return (void *)outOfMem;
  138639. }
  138640. if( !sqlite3SafetyCheckSickOrOk(db) ){
  138641. return (void *)misuse;
  138642. }
  138643. sqlite3_mutex_enter(db->mutex);
  138644. if( db->mallocFailed ){
  138645. z = (void *)outOfMem;
  138646. }else{
  138647. z = sqlite3_value_text16(db->pErr);
  138648. if( z==0 ){
  138649. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  138650. z = sqlite3_value_text16(db->pErr);
  138651. }
  138652. /* A malloc() may have failed within the call to sqlite3_value_text16()
  138653. ** above. If this is the case, then the db->mallocFailed flag needs to
  138654. ** be cleared before returning. Do this directly, instead of via
  138655. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  138656. */
  138657. sqlite3OomClear(db);
  138658. }
  138659. sqlite3_mutex_leave(db->mutex);
  138660. return z;
  138661. }
  138662. #endif /* SQLITE_OMIT_UTF16 */
  138663. /*
  138664. ** Return the most recent error code generated by an SQLite routine. If NULL is
  138665. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  138666. */
  138667. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  138668. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  138669. return SQLITE_MISUSE_BKPT;
  138670. }
  138671. if( !db || db->mallocFailed ){
  138672. return SQLITE_NOMEM_BKPT;
  138673. }
  138674. return db->errCode & db->errMask;
  138675. }
  138676. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  138677. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  138678. return SQLITE_MISUSE_BKPT;
  138679. }
  138680. if( !db || db->mallocFailed ){
  138681. return SQLITE_NOMEM_BKPT;
  138682. }
  138683. return db->errCode;
  138684. }
  138685. SQLITE_API int sqlite3_system_errno(sqlite3 *db){
  138686. return db ? db->iSysErrno : 0;
  138687. }
  138688. /*
  138689. ** Return a string that describes the kind of error specified in the
  138690. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  138691. ** function.
  138692. */
  138693. SQLITE_API const char *sqlite3_errstr(int rc){
  138694. return sqlite3ErrStr(rc);
  138695. }
  138696. /*
  138697. ** Create a new collating function for database "db". The name is zName
  138698. ** and the encoding is enc.
  138699. */
  138700. static int createCollation(
  138701. sqlite3* db,
  138702. const char *zName,
  138703. u8 enc,
  138704. void* pCtx,
  138705. int(*xCompare)(void*,int,const void*,int,const void*),
  138706. void(*xDel)(void*)
  138707. ){
  138708. CollSeq *pColl;
  138709. int enc2;
  138710. assert( sqlite3_mutex_held(db->mutex) );
  138711. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  138712. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  138713. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  138714. */
  138715. enc2 = enc;
  138716. testcase( enc2==SQLITE_UTF16 );
  138717. testcase( enc2==SQLITE_UTF16_ALIGNED );
  138718. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  138719. enc2 = SQLITE_UTF16NATIVE;
  138720. }
  138721. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  138722. return SQLITE_MISUSE_BKPT;
  138723. }
  138724. /* Check if this call is removing or replacing an existing collation
  138725. ** sequence. If so, and there are active VMs, return busy. If there
  138726. ** are no active VMs, invalidate any pre-compiled statements.
  138727. */
  138728. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  138729. if( pColl && pColl->xCmp ){
  138730. if( db->nVdbeActive ){
  138731. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  138732. "unable to delete/modify collation sequence due to active statements");
  138733. return SQLITE_BUSY;
  138734. }
  138735. sqlite3ExpirePreparedStatements(db);
  138736. /* If collation sequence pColl was created directly by a call to
  138737. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  138738. ** then any copies made by synthCollSeq() need to be invalidated.
  138739. ** Also, collation destructor - CollSeq.xDel() - function may need
  138740. ** to be called.
  138741. */
  138742. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  138743. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  138744. int j;
  138745. for(j=0; j<3; j++){
  138746. CollSeq *p = &aColl[j];
  138747. if( p->enc==pColl->enc ){
  138748. if( p->xDel ){
  138749. p->xDel(p->pUser);
  138750. }
  138751. p->xCmp = 0;
  138752. }
  138753. }
  138754. }
  138755. }
  138756. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  138757. if( pColl==0 ) return SQLITE_NOMEM_BKPT;
  138758. pColl->xCmp = xCompare;
  138759. pColl->pUser = pCtx;
  138760. pColl->xDel = xDel;
  138761. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  138762. sqlite3Error(db, SQLITE_OK);
  138763. return SQLITE_OK;
  138764. }
  138765. /*
  138766. ** This array defines hard upper bounds on limit values. The
  138767. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  138768. ** #defines in sqlite3.h.
  138769. */
  138770. static const int aHardLimit[] = {
  138771. SQLITE_MAX_LENGTH,
  138772. SQLITE_MAX_SQL_LENGTH,
  138773. SQLITE_MAX_COLUMN,
  138774. SQLITE_MAX_EXPR_DEPTH,
  138775. SQLITE_MAX_COMPOUND_SELECT,
  138776. SQLITE_MAX_VDBE_OP,
  138777. SQLITE_MAX_FUNCTION_ARG,
  138778. SQLITE_MAX_ATTACHED,
  138779. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  138780. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  138781. SQLITE_MAX_TRIGGER_DEPTH,
  138782. SQLITE_MAX_WORKER_THREADS,
  138783. };
  138784. /*
  138785. ** Make sure the hard limits are set to reasonable values
  138786. */
  138787. #if SQLITE_MAX_LENGTH<100
  138788. # error SQLITE_MAX_LENGTH must be at least 100
  138789. #endif
  138790. #if SQLITE_MAX_SQL_LENGTH<100
  138791. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  138792. #endif
  138793. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  138794. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  138795. #endif
  138796. #if SQLITE_MAX_COMPOUND_SELECT<2
  138797. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  138798. #endif
  138799. #if SQLITE_MAX_VDBE_OP<40
  138800. # error SQLITE_MAX_VDBE_OP must be at least 40
  138801. #endif
  138802. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
  138803. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
  138804. #endif
  138805. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  138806. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  138807. #endif
  138808. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  138809. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  138810. #endif
  138811. #if SQLITE_MAX_COLUMN>32767
  138812. # error SQLITE_MAX_COLUMN must not exceed 32767
  138813. #endif
  138814. #if SQLITE_MAX_TRIGGER_DEPTH<1
  138815. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  138816. #endif
  138817. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  138818. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  138819. #endif
  138820. /*
  138821. ** Change the value of a limit. Report the old value.
  138822. ** If an invalid limit index is supplied, report -1.
  138823. ** Make no changes but still report the old value if the
  138824. ** new limit is negative.
  138825. **
  138826. ** A new lower limit does not shrink existing constructs.
  138827. ** It merely prevents new constructs that exceed the limit
  138828. ** from forming.
  138829. */
  138830. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  138831. int oldLimit;
  138832. #ifdef SQLITE_ENABLE_API_ARMOR
  138833. if( !sqlite3SafetyCheckOk(db) ){
  138834. (void)SQLITE_MISUSE_BKPT;
  138835. return -1;
  138836. }
  138837. #endif
  138838. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  138839. ** there is a hard upper bound set at compile-time by a C preprocessor
  138840. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  138841. ** "_MAX_".)
  138842. */
  138843. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  138844. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  138845. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  138846. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  138847. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  138848. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  138849. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  138850. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  138851. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  138852. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  138853. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  138854. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  138855. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  138856. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  138857. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  138858. return -1;
  138859. }
  138860. oldLimit = db->aLimit[limitId];
  138861. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  138862. if( newLimit>aHardLimit[limitId] ){
  138863. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  138864. }
  138865. db->aLimit[limitId] = newLimit;
  138866. }
  138867. return oldLimit; /* IMP: R-53341-35419 */
  138868. }
  138869. /*
  138870. ** This function is used to parse both URIs and non-URI filenames passed by the
  138871. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  138872. ** URIs specified as part of ATTACH statements.
  138873. **
  138874. ** The first argument to this function is the name of the VFS to use (or
  138875. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  138876. ** query parameter. The second argument contains the URI (or non-URI filename)
  138877. ** itself. When this function is called the *pFlags variable should contain
  138878. ** the default flags to open the database handle with. The value stored in
  138879. ** *pFlags may be updated before returning if the URI filename contains
  138880. ** "cache=xxx" or "mode=xxx" query parameters.
  138881. **
  138882. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  138883. ** the VFS that should be used to open the database file. *pzFile is set to
  138884. ** point to a buffer containing the name of the file to open. It is the
  138885. ** responsibility of the caller to eventually call sqlite3_free() to release
  138886. ** this buffer.
  138887. **
  138888. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  138889. ** may be set to point to a buffer containing an English language error
  138890. ** message. It is the responsibility of the caller to eventually release
  138891. ** this buffer by calling sqlite3_free().
  138892. */
  138893. SQLITE_PRIVATE int sqlite3ParseUri(
  138894. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  138895. const char *zUri, /* Nul-terminated URI to parse */
  138896. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  138897. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  138898. char **pzFile, /* OUT: Filename component of URI */
  138899. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  138900. ){
  138901. int rc = SQLITE_OK;
  138902. unsigned int flags = *pFlags;
  138903. const char *zVfs = zDefaultVfs;
  138904. char *zFile;
  138905. char c;
  138906. int nUri = sqlite3Strlen30(zUri);
  138907. assert( *pzErrMsg==0 );
  138908. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  138909. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  138910. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  138911. ){
  138912. char *zOpt;
  138913. int eState; /* Parser state when parsing URI */
  138914. int iIn; /* Input character index */
  138915. int iOut = 0; /* Output character index */
  138916. u64 nByte = nUri+2; /* Bytes of space to allocate */
  138917. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  138918. ** method that there may be extra parameters following the file-name. */
  138919. flags |= SQLITE_OPEN_URI;
  138920. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  138921. zFile = sqlite3_malloc64(nByte);
  138922. if( !zFile ) return SQLITE_NOMEM_BKPT;
  138923. iIn = 5;
  138924. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  138925. if( strncmp(zUri+5, "///", 3)==0 ){
  138926. iIn = 7;
  138927. /* The following condition causes URIs with five leading / characters
  138928. ** like file://///host/path to be converted into UNCs like //host/path.
  138929. ** The correct URI for that UNC has only two or four leading / characters
  138930. ** file://host/path or file:////host/path. But 5 leading slashes is a
  138931. ** common error, we are told, so we handle it as a special case. */
  138932. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  138933. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  138934. iIn = 16;
  138935. }
  138936. #else
  138937. /* Discard the scheme and authority segments of the URI. */
  138938. if( zUri[5]=='/' && zUri[6]=='/' ){
  138939. iIn = 7;
  138940. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  138941. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  138942. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  138943. iIn-7, &zUri[7]);
  138944. rc = SQLITE_ERROR;
  138945. goto parse_uri_out;
  138946. }
  138947. }
  138948. #endif
  138949. /* Copy the filename and any query parameters into the zFile buffer.
  138950. ** Decode %HH escape codes along the way.
  138951. **
  138952. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  138953. ** on the parsing context. As follows:
  138954. **
  138955. ** 0: Parsing file-name.
  138956. ** 1: Parsing name section of a name=value query parameter.
  138957. ** 2: Parsing value section of a name=value query parameter.
  138958. */
  138959. eState = 0;
  138960. while( (c = zUri[iIn])!=0 && c!='#' ){
  138961. iIn++;
  138962. if( c=='%'
  138963. && sqlite3Isxdigit(zUri[iIn])
  138964. && sqlite3Isxdigit(zUri[iIn+1])
  138965. ){
  138966. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  138967. octet += sqlite3HexToInt(zUri[iIn++]);
  138968. assert( octet>=0 && octet<256 );
  138969. if( octet==0 ){
  138970. #ifndef SQLITE_ENABLE_URI_00_ERROR
  138971. /* This branch is taken when "%00" appears within the URI. In this
  138972. ** case we ignore all text in the remainder of the path, name or
  138973. ** value currently being parsed. So ignore the current character
  138974. ** and skip to the next "?", "=" or "&", as appropriate. */
  138975. while( (c = zUri[iIn])!=0 && c!='#'
  138976. && (eState!=0 || c!='?')
  138977. && (eState!=1 || (c!='=' && c!='&'))
  138978. && (eState!=2 || c!='&')
  138979. ){
  138980. iIn++;
  138981. }
  138982. continue;
  138983. #else
  138984. /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
  138985. *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
  138986. rc = SQLITE_ERROR;
  138987. goto parse_uri_out;
  138988. #endif
  138989. }
  138990. c = octet;
  138991. }else if( eState==1 && (c=='&' || c=='=') ){
  138992. if( zFile[iOut-1]==0 ){
  138993. /* An empty option name. Ignore this option altogether. */
  138994. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  138995. continue;
  138996. }
  138997. if( c=='&' ){
  138998. zFile[iOut++] = '\0';
  138999. }else{
  139000. eState = 2;
  139001. }
  139002. c = 0;
  139003. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  139004. c = 0;
  139005. eState = 1;
  139006. }
  139007. zFile[iOut++] = c;
  139008. }
  139009. if( eState==1 ) zFile[iOut++] = '\0';
  139010. zFile[iOut++] = '\0';
  139011. zFile[iOut++] = '\0';
  139012. /* Check if there were any options specified that should be interpreted
  139013. ** here. Options that are interpreted here include "vfs" and those that
  139014. ** correspond to flags that may be passed to the sqlite3_open_v2()
  139015. ** method. */
  139016. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  139017. while( zOpt[0] ){
  139018. int nOpt = sqlite3Strlen30(zOpt);
  139019. char *zVal = &zOpt[nOpt+1];
  139020. int nVal = sqlite3Strlen30(zVal);
  139021. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  139022. zVfs = zVal;
  139023. }else{
  139024. struct OpenMode {
  139025. const char *z;
  139026. int mode;
  139027. } *aMode = 0;
  139028. char *zModeType = 0;
  139029. int mask = 0;
  139030. int limit = 0;
  139031. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  139032. static struct OpenMode aCacheMode[] = {
  139033. { "shared", SQLITE_OPEN_SHAREDCACHE },
  139034. { "private", SQLITE_OPEN_PRIVATECACHE },
  139035. { 0, 0 }
  139036. };
  139037. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  139038. aMode = aCacheMode;
  139039. limit = mask;
  139040. zModeType = "cache";
  139041. }
  139042. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  139043. static struct OpenMode aOpenMode[] = {
  139044. { "ro", SQLITE_OPEN_READONLY },
  139045. { "rw", SQLITE_OPEN_READWRITE },
  139046. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  139047. { "memory", SQLITE_OPEN_MEMORY },
  139048. { 0, 0 }
  139049. };
  139050. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  139051. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  139052. aMode = aOpenMode;
  139053. limit = mask & flags;
  139054. zModeType = "access";
  139055. }
  139056. if( aMode ){
  139057. int i;
  139058. int mode = 0;
  139059. for(i=0; aMode[i].z; i++){
  139060. const char *z = aMode[i].z;
  139061. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  139062. mode = aMode[i].mode;
  139063. break;
  139064. }
  139065. }
  139066. if( mode==0 ){
  139067. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  139068. rc = SQLITE_ERROR;
  139069. goto parse_uri_out;
  139070. }
  139071. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  139072. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  139073. zModeType, zVal);
  139074. rc = SQLITE_PERM;
  139075. goto parse_uri_out;
  139076. }
  139077. flags = (flags & ~mask) | mode;
  139078. }
  139079. }
  139080. zOpt = &zVal[nVal+1];
  139081. }
  139082. }else{
  139083. zFile = sqlite3_malloc64(nUri+2);
  139084. if( !zFile ) return SQLITE_NOMEM_BKPT;
  139085. if( nUri ){
  139086. memcpy(zFile, zUri, nUri);
  139087. }
  139088. zFile[nUri] = '\0';
  139089. zFile[nUri+1] = '\0';
  139090. flags &= ~SQLITE_OPEN_URI;
  139091. }
  139092. *ppVfs = sqlite3_vfs_find(zVfs);
  139093. if( *ppVfs==0 ){
  139094. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  139095. rc = SQLITE_ERROR;
  139096. }
  139097. parse_uri_out:
  139098. if( rc!=SQLITE_OK ){
  139099. sqlite3_free(zFile);
  139100. zFile = 0;
  139101. }
  139102. *pFlags = flags;
  139103. *pzFile = zFile;
  139104. return rc;
  139105. }
  139106. /*
  139107. ** This routine does the work of opening a database on behalf of
  139108. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  139109. ** is UTF-8 encoded.
  139110. */
  139111. static int openDatabase(
  139112. const char *zFilename, /* Database filename UTF-8 encoded */
  139113. sqlite3 **ppDb, /* OUT: Returned database handle */
  139114. unsigned int flags, /* Operational flags */
  139115. const char *zVfs /* Name of the VFS to use */
  139116. ){
  139117. sqlite3 *db; /* Store allocated handle here */
  139118. int rc; /* Return code */
  139119. int isThreadsafe; /* True for threadsafe connections */
  139120. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  139121. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  139122. #ifdef SQLITE_ENABLE_API_ARMOR
  139123. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  139124. #endif
  139125. *ppDb = 0;
  139126. #ifndef SQLITE_OMIT_AUTOINIT
  139127. rc = sqlite3_initialize();
  139128. if( rc ) return rc;
  139129. #endif
  139130. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  139131. isThreadsafe = 0;
  139132. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  139133. isThreadsafe = 0;
  139134. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  139135. isThreadsafe = 1;
  139136. }else{
  139137. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  139138. }
  139139. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  139140. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  139141. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  139142. flags |= SQLITE_OPEN_SHAREDCACHE;
  139143. }
  139144. /* Remove harmful bits from the flags parameter
  139145. **
  139146. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  139147. ** dealt with in the previous code block. Besides these, the only
  139148. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  139149. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  139150. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  139151. ** off all other flags.
  139152. */
  139153. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  139154. SQLITE_OPEN_EXCLUSIVE |
  139155. SQLITE_OPEN_MAIN_DB |
  139156. SQLITE_OPEN_TEMP_DB |
  139157. SQLITE_OPEN_TRANSIENT_DB |
  139158. SQLITE_OPEN_MAIN_JOURNAL |
  139159. SQLITE_OPEN_TEMP_JOURNAL |
  139160. SQLITE_OPEN_SUBJOURNAL |
  139161. SQLITE_OPEN_MASTER_JOURNAL |
  139162. SQLITE_OPEN_NOMUTEX |
  139163. SQLITE_OPEN_FULLMUTEX |
  139164. SQLITE_OPEN_WAL
  139165. );
  139166. /* Allocate the sqlite data structure */
  139167. db = sqlite3MallocZero( sizeof(sqlite3) );
  139168. if( db==0 ) goto opendb_out;
  139169. if( isThreadsafe
  139170. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  139171. || sqlite3GlobalConfig.bCoreMutex
  139172. #endif
  139173. ){
  139174. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  139175. if( db->mutex==0 ){
  139176. sqlite3_free(db);
  139177. db = 0;
  139178. goto opendb_out;
  139179. }
  139180. if( isThreadsafe==0 ){
  139181. sqlite3MutexWarnOnContention(db->mutex);
  139182. }
  139183. }
  139184. sqlite3_mutex_enter(db->mutex);
  139185. db->errMask = 0xff;
  139186. db->nDb = 2;
  139187. db->magic = SQLITE_MAGIC_BUSY;
  139188. db->aDb = db->aDbStatic;
  139189. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  139190. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  139191. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  139192. db->autoCommit = 1;
  139193. db->nextAutovac = -1;
  139194. db->szMmap = sqlite3GlobalConfig.szMmap;
  139195. db->nextPagesize = 0;
  139196. db->nMaxSorterMmap = 0x7FFFFFFF;
  139197. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  139198. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  139199. | SQLITE_AutoIndex
  139200. #endif
  139201. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  139202. | SQLITE_CkptFullFSync
  139203. #endif
  139204. #if SQLITE_DEFAULT_FILE_FORMAT<4
  139205. | SQLITE_LegacyFileFmt
  139206. #endif
  139207. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  139208. | SQLITE_LoadExtension
  139209. #endif
  139210. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  139211. | SQLITE_RecTriggers
  139212. #endif
  139213. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  139214. | SQLITE_ForeignKeys
  139215. #endif
  139216. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  139217. | SQLITE_ReverseOrder
  139218. #endif
  139219. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  139220. | SQLITE_CellSizeCk
  139221. #endif
  139222. #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
  139223. | SQLITE_Fts3Tokenizer
  139224. #endif
  139225. #if defined(SQLITE_ENABLE_QPSG)
  139226. | SQLITE_EnableQPSG
  139227. #endif
  139228. ;
  139229. sqlite3HashInit(&db->aCollSeq);
  139230. #ifndef SQLITE_OMIT_VIRTUALTABLE
  139231. sqlite3HashInit(&db->aModule);
  139232. #endif
  139233. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  139234. ** and UTF-16, so add a version for each to avoid any unnecessary
  139235. ** conversions. The only error that can occur here is a malloc() failure.
  139236. **
  139237. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  139238. ** functions:
  139239. */
  139240. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  139241. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  139242. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  139243. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  139244. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  139245. if( db->mallocFailed ){
  139246. goto opendb_out;
  139247. }
  139248. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  139249. ** strings is BINARY.
  139250. */
  139251. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
  139252. assert( db->pDfltColl!=0 );
  139253. /* Parse the filename/URI argument
  139254. **
  139255. ** Only allow sensible combinations of bits in the flags argument.
  139256. ** Throw an error if any non-sense combination is used. If we
  139257. ** do not block illegal combinations here, it could trigger
  139258. ** assert() statements in deeper layers. Sensible combinations
  139259. ** are:
  139260. **
  139261. ** 1: SQLITE_OPEN_READONLY
  139262. ** 2: SQLITE_OPEN_READWRITE
  139263. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  139264. */
  139265. db->openFlags = flags;
  139266. assert( SQLITE_OPEN_READONLY == 0x01 );
  139267. assert( SQLITE_OPEN_READWRITE == 0x02 );
  139268. assert( SQLITE_OPEN_CREATE == 0x04 );
  139269. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  139270. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  139271. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  139272. if( ((1<<(flags&7)) & 0x46)==0 ){
  139273. rc = SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  139274. }else{
  139275. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  139276. }
  139277. if( rc!=SQLITE_OK ){
  139278. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  139279. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  139280. sqlite3_free(zErrMsg);
  139281. goto opendb_out;
  139282. }
  139283. /* Open the backend database driver */
  139284. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  139285. flags | SQLITE_OPEN_MAIN_DB);
  139286. if( rc!=SQLITE_OK ){
  139287. if( rc==SQLITE_IOERR_NOMEM ){
  139288. rc = SQLITE_NOMEM_BKPT;
  139289. }
  139290. sqlite3Error(db, rc);
  139291. goto opendb_out;
  139292. }
  139293. sqlite3BtreeEnter(db->aDb[0].pBt);
  139294. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  139295. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  139296. sqlite3BtreeLeave(db->aDb[0].pBt);
  139297. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  139298. /* The default safety_level for the main database is FULL; for the temp
  139299. ** database it is OFF. This matches the pager layer defaults.
  139300. */
  139301. db->aDb[0].zDbSName = "main";
  139302. db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  139303. db->aDb[1].zDbSName = "temp";
  139304. db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  139305. db->magic = SQLITE_MAGIC_OPEN;
  139306. if( db->mallocFailed ){
  139307. goto opendb_out;
  139308. }
  139309. /* Register all built-in functions, but do not attempt to read the
  139310. ** database schema yet. This is delayed until the first time the database
  139311. ** is accessed.
  139312. */
  139313. sqlite3Error(db, SQLITE_OK);
  139314. sqlite3RegisterPerConnectionBuiltinFunctions(db);
  139315. rc = sqlite3_errcode(db);
  139316. #ifdef SQLITE_ENABLE_FTS5
  139317. /* Register any built-in FTS5 module before loading the automatic
  139318. ** extensions. This allows automatic extensions to register FTS5
  139319. ** tokenizers and auxiliary functions. */
  139320. if( !db->mallocFailed && rc==SQLITE_OK ){
  139321. rc = sqlite3Fts5Init(db);
  139322. }
  139323. #endif
  139324. /* Load automatic extensions - extensions that have been registered
  139325. ** using the sqlite3_automatic_extension() API.
  139326. */
  139327. if( rc==SQLITE_OK ){
  139328. sqlite3AutoLoadExtensions(db);
  139329. rc = sqlite3_errcode(db);
  139330. if( rc!=SQLITE_OK ){
  139331. goto opendb_out;
  139332. }
  139333. }
  139334. #ifdef SQLITE_ENABLE_FTS1
  139335. if( !db->mallocFailed ){
  139336. extern int sqlite3Fts1Init(sqlite3*);
  139337. rc = sqlite3Fts1Init(db);
  139338. }
  139339. #endif
  139340. #ifdef SQLITE_ENABLE_FTS2
  139341. if( !db->mallocFailed && rc==SQLITE_OK ){
  139342. extern int sqlite3Fts2Init(sqlite3*);
  139343. rc = sqlite3Fts2Init(db);
  139344. }
  139345. #endif
  139346. #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
  139347. if( !db->mallocFailed && rc==SQLITE_OK ){
  139348. rc = sqlite3Fts3Init(db);
  139349. }
  139350. #endif
  139351. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  139352. if( !db->mallocFailed && rc==SQLITE_OK ){
  139353. rc = sqlite3IcuInit(db);
  139354. }
  139355. #endif
  139356. #ifdef SQLITE_ENABLE_RTREE
  139357. if( !db->mallocFailed && rc==SQLITE_OK){
  139358. rc = sqlite3RtreeInit(db);
  139359. }
  139360. #endif
  139361. #ifdef SQLITE_ENABLE_DBPAGE_VTAB
  139362. if( !db->mallocFailed && rc==SQLITE_OK){
  139363. rc = sqlite3DbpageRegister(db);
  139364. }
  139365. #endif
  139366. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  139367. if( !db->mallocFailed && rc==SQLITE_OK){
  139368. rc = sqlite3DbstatRegister(db);
  139369. }
  139370. #endif
  139371. #ifdef SQLITE_ENABLE_JSON1
  139372. if( !db->mallocFailed && rc==SQLITE_OK){
  139373. rc = sqlite3Json1Init(db);
  139374. }
  139375. #endif
  139376. #ifdef SQLITE_ENABLE_STMTVTAB
  139377. if( !db->mallocFailed && rc==SQLITE_OK){
  139378. rc = sqlite3StmtVtabInit(db);
  139379. }
  139380. #endif
  139381. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  139382. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  139383. ** mode. Doing nothing at all also makes NORMAL the default.
  139384. */
  139385. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  139386. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  139387. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  139388. SQLITE_DEFAULT_LOCKING_MODE);
  139389. #endif
  139390. if( rc ) sqlite3Error(db, rc);
  139391. /* Enable the lookaside-malloc subsystem */
  139392. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  139393. sqlite3GlobalConfig.nLookaside);
  139394. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  139395. opendb_out:
  139396. if( db ){
  139397. assert( db->mutex!=0 || isThreadsafe==0
  139398. || sqlite3GlobalConfig.bFullMutex==0 );
  139399. sqlite3_mutex_leave(db->mutex);
  139400. }
  139401. rc = sqlite3_errcode(db);
  139402. assert( db!=0 || rc==SQLITE_NOMEM );
  139403. if( rc==SQLITE_NOMEM ){
  139404. sqlite3_close(db);
  139405. db = 0;
  139406. }else if( rc!=SQLITE_OK ){
  139407. db->magic = SQLITE_MAGIC_SICK;
  139408. }
  139409. *ppDb = db;
  139410. #ifdef SQLITE_ENABLE_SQLLOG
  139411. if( sqlite3GlobalConfig.xSqllog ){
  139412. /* Opening a db handle. Fourth parameter is passed 0. */
  139413. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  139414. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  139415. }
  139416. #endif
  139417. #if defined(SQLITE_HAS_CODEC)
  139418. if( rc==SQLITE_OK ){
  139419. const char *zKey;
  139420. if( (zKey = sqlite3_uri_parameter(zOpen, "hexkey"))!=0 && zKey[0] ){
  139421. u8 iByte;
  139422. int i;
  139423. char zDecoded[40];
  139424. for(i=0, iByte=0; i<sizeof(zDecoded)*2 && sqlite3Isxdigit(zKey[i]); i++){
  139425. iByte = (iByte<<4) + sqlite3HexToInt(zKey[i]);
  139426. if( (i&1)!=0 ) zDecoded[i/2] = iByte;
  139427. }
  139428. sqlite3_key_v2(db, 0, zDecoded, i/2);
  139429. }else if( (zKey = sqlite3_uri_parameter(zOpen, "key"))!=0 ){
  139430. sqlite3_key_v2(db, 0, zKey, sqlite3Strlen30(zKey));
  139431. }
  139432. }
  139433. #endif
  139434. sqlite3_free(zOpen);
  139435. return rc & 0xff;
  139436. }
  139437. /*
  139438. ** Open a new database handle.
  139439. */
  139440. SQLITE_API int sqlite3_open(
  139441. const char *zFilename,
  139442. sqlite3 **ppDb
  139443. ){
  139444. return openDatabase(zFilename, ppDb,
  139445. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  139446. }
  139447. SQLITE_API int sqlite3_open_v2(
  139448. const char *filename, /* Database filename (UTF-8) */
  139449. sqlite3 **ppDb, /* OUT: SQLite db handle */
  139450. int flags, /* Flags */
  139451. const char *zVfs /* Name of VFS module to use */
  139452. ){
  139453. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  139454. }
  139455. #ifndef SQLITE_OMIT_UTF16
  139456. /*
  139457. ** Open a new database handle.
  139458. */
  139459. SQLITE_API int sqlite3_open16(
  139460. const void *zFilename,
  139461. sqlite3 **ppDb
  139462. ){
  139463. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  139464. sqlite3_value *pVal;
  139465. int rc;
  139466. #ifdef SQLITE_ENABLE_API_ARMOR
  139467. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  139468. #endif
  139469. *ppDb = 0;
  139470. #ifndef SQLITE_OMIT_AUTOINIT
  139471. rc = sqlite3_initialize();
  139472. if( rc ) return rc;
  139473. #endif
  139474. if( zFilename==0 ) zFilename = "\000\000";
  139475. pVal = sqlite3ValueNew(0);
  139476. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  139477. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  139478. if( zFilename8 ){
  139479. rc = openDatabase(zFilename8, ppDb,
  139480. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  139481. assert( *ppDb || rc==SQLITE_NOMEM );
  139482. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  139483. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  139484. }
  139485. }else{
  139486. rc = SQLITE_NOMEM_BKPT;
  139487. }
  139488. sqlite3ValueFree(pVal);
  139489. return rc & 0xff;
  139490. }
  139491. #endif /* SQLITE_OMIT_UTF16 */
  139492. /*
  139493. ** Register a new collation sequence with the database handle db.
  139494. */
  139495. SQLITE_API int sqlite3_create_collation(
  139496. sqlite3* db,
  139497. const char *zName,
  139498. int enc,
  139499. void* pCtx,
  139500. int(*xCompare)(void*,int,const void*,int,const void*)
  139501. ){
  139502. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  139503. }
  139504. /*
  139505. ** Register a new collation sequence with the database handle db.
  139506. */
  139507. SQLITE_API int sqlite3_create_collation_v2(
  139508. sqlite3* db,
  139509. const char *zName,
  139510. int enc,
  139511. void* pCtx,
  139512. int(*xCompare)(void*,int,const void*,int,const void*),
  139513. void(*xDel)(void*)
  139514. ){
  139515. int rc;
  139516. #ifdef SQLITE_ENABLE_API_ARMOR
  139517. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  139518. #endif
  139519. sqlite3_mutex_enter(db->mutex);
  139520. assert( !db->mallocFailed );
  139521. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  139522. rc = sqlite3ApiExit(db, rc);
  139523. sqlite3_mutex_leave(db->mutex);
  139524. return rc;
  139525. }
  139526. #ifndef SQLITE_OMIT_UTF16
  139527. /*
  139528. ** Register a new collation sequence with the database handle db.
  139529. */
  139530. SQLITE_API int sqlite3_create_collation16(
  139531. sqlite3* db,
  139532. const void *zName,
  139533. int enc,
  139534. void* pCtx,
  139535. int(*xCompare)(void*,int,const void*,int,const void*)
  139536. ){
  139537. int rc = SQLITE_OK;
  139538. char *zName8;
  139539. #ifdef SQLITE_ENABLE_API_ARMOR
  139540. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  139541. #endif
  139542. sqlite3_mutex_enter(db->mutex);
  139543. assert( !db->mallocFailed );
  139544. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  139545. if( zName8 ){
  139546. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  139547. sqlite3DbFree(db, zName8);
  139548. }
  139549. rc = sqlite3ApiExit(db, rc);
  139550. sqlite3_mutex_leave(db->mutex);
  139551. return rc;
  139552. }
  139553. #endif /* SQLITE_OMIT_UTF16 */
  139554. /*
  139555. ** Register a collation sequence factory callback with the database handle
  139556. ** db. Replace any previously installed collation sequence factory.
  139557. */
  139558. SQLITE_API int sqlite3_collation_needed(
  139559. sqlite3 *db,
  139560. void *pCollNeededArg,
  139561. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  139562. ){
  139563. #ifdef SQLITE_ENABLE_API_ARMOR
  139564. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  139565. #endif
  139566. sqlite3_mutex_enter(db->mutex);
  139567. db->xCollNeeded = xCollNeeded;
  139568. db->xCollNeeded16 = 0;
  139569. db->pCollNeededArg = pCollNeededArg;
  139570. sqlite3_mutex_leave(db->mutex);
  139571. return SQLITE_OK;
  139572. }
  139573. #ifndef SQLITE_OMIT_UTF16
  139574. /*
  139575. ** Register a collation sequence factory callback with the database handle
  139576. ** db. Replace any previously installed collation sequence factory.
  139577. */
  139578. SQLITE_API int sqlite3_collation_needed16(
  139579. sqlite3 *db,
  139580. void *pCollNeededArg,
  139581. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  139582. ){
  139583. #ifdef SQLITE_ENABLE_API_ARMOR
  139584. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  139585. #endif
  139586. sqlite3_mutex_enter(db->mutex);
  139587. db->xCollNeeded = 0;
  139588. db->xCollNeeded16 = xCollNeeded16;
  139589. db->pCollNeededArg = pCollNeededArg;
  139590. sqlite3_mutex_leave(db->mutex);
  139591. return SQLITE_OK;
  139592. }
  139593. #endif /* SQLITE_OMIT_UTF16 */
  139594. #ifndef SQLITE_OMIT_DEPRECATED
  139595. /*
  139596. ** This function is now an anachronism. It used to be used to recover from a
  139597. ** malloc() failure, but SQLite now does this automatically.
  139598. */
  139599. SQLITE_API int sqlite3_global_recover(void){
  139600. return SQLITE_OK;
  139601. }
  139602. #endif
  139603. /*
  139604. ** Test to see whether or not the database connection is in autocommit
  139605. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  139606. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  139607. ** by the next COMMIT or ROLLBACK.
  139608. */
  139609. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  139610. #ifdef SQLITE_ENABLE_API_ARMOR
  139611. if( !sqlite3SafetyCheckOk(db) ){
  139612. (void)SQLITE_MISUSE_BKPT;
  139613. return 0;
  139614. }
  139615. #endif
  139616. return db->autoCommit;
  139617. }
  139618. /*
  139619. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  139620. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
  139621. ** constants. They serve two purposes:
  139622. **
  139623. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  139624. ** to detect when version error conditions occurs.
  139625. **
  139626. ** 2. Invoke sqlite3_log() to provide the source code location where
  139627. ** a low-level error is first detected.
  139628. */
  139629. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){
  139630. sqlite3_log(iErr, "%s at line %d of [%.10s]",
  139631. zType, lineno, 20+sqlite3_sourceid());
  139632. return iErr;
  139633. }
  139634. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  139635. testcase( sqlite3GlobalConfig.xLog!=0 );
  139636. return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
  139637. }
  139638. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  139639. testcase( sqlite3GlobalConfig.xLog!=0 );
  139640. return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
  139641. }
  139642. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  139643. testcase( sqlite3GlobalConfig.xLog!=0 );
  139644. return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
  139645. }
  139646. #ifdef SQLITE_DEBUG
  139647. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
  139648. char zMsg[100];
  139649. sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
  139650. testcase( sqlite3GlobalConfig.xLog!=0 );
  139651. return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  139652. }
  139653. SQLITE_PRIVATE int sqlite3NomemError(int lineno){
  139654. testcase( sqlite3GlobalConfig.xLog!=0 );
  139655. return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
  139656. }
  139657. SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
  139658. testcase( sqlite3GlobalConfig.xLog!=0 );
  139659. return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
  139660. }
  139661. #endif
  139662. #ifndef SQLITE_OMIT_DEPRECATED
  139663. /*
  139664. ** This is a convenience routine that makes sure that all thread-specific
  139665. ** data for this thread has been deallocated.
  139666. **
  139667. ** SQLite no longer uses thread-specific data so this routine is now a
  139668. ** no-op. It is retained for historical compatibility.
  139669. */
  139670. SQLITE_API void sqlite3_thread_cleanup(void){
  139671. }
  139672. #endif
  139673. /*
  139674. ** Return meta information about a specific column of a database table.
  139675. ** See comment in sqlite3.h (sqlite.h.in) for details.
  139676. */
  139677. SQLITE_API int sqlite3_table_column_metadata(
  139678. sqlite3 *db, /* Connection handle */
  139679. const char *zDbName, /* Database name or NULL */
  139680. const char *zTableName, /* Table name */
  139681. const char *zColumnName, /* Column name */
  139682. char const **pzDataType, /* OUTPUT: Declared data type */
  139683. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  139684. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  139685. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  139686. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  139687. ){
  139688. int rc;
  139689. char *zErrMsg = 0;
  139690. Table *pTab = 0;
  139691. Column *pCol = 0;
  139692. int iCol = 0;
  139693. char const *zDataType = 0;
  139694. char const *zCollSeq = 0;
  139695. int notnull = 0;
  139696. int primarykey = 0;
  139697. int autoinc = 0;
  139698. #ifdef SQLITE_ENABLE_API_ARMOR
  139699. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  139700. return SQLITE_MISUSE_BKPT;
  139701. }
  139702. #endif
  139703. /* Ensure the database schema has been loaded */
  139704. sqlite3_mutex_enter(db->mutex);
  139705. sqlite3BtreeEnterAll(db);
  139706. rc = sqlite3Init(db, &zErrMsg);
  139707. if( SQLITE_OK!=rc ){
  139708. goto error_out;
  139709. }
  139710. /* Locate the table in question */
  139711. pTab = sqlite3FindTable(db, zTableName, zDbName);
  139712. if( !pTab || pTab->pSelect ){
  139713. pTab = 0;
  139714. goto error_out;
  139715. }
  139716. /* Find the column for which info is requested */
  139717. if( zColumnName==0 ){
  139718. /* Query for existance of table only */
  139719. }else{
  139720. for(iCol=0; iCol<pTab->nCol; iCol++){
  139721. pCol = &pTab->aCol[iCol];
  139722. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  139723. break;
  139724. }
  139725. }
  139726. if( iCol==pTab->nCol ){
  139727. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  139728. iCol = pTab->iPKey;
  139729. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  139730. }else{
  139731. pTab = 0;
  139732. goto error_out;
  139733. }
  139734. }
  139735. }
  139736. /* The following block stores the meta information that will be returned
  139737. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  139738. ** and autoinc. At this point there are two possibilities:
  139739. **
  139740. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  139741. ** and there is no explicitly declared IPK column.
  139742. **
  139743. ** 2. The table is not a view and the column name identified an
  139744. ** explicitly declared column. Copy meta information from *pCol.
  139745. */
  139746. if( pCol ){
  139747. zDataType = sqlite3ColumnType(pCol,0);
  139748. zCollSeq = pCol->zColl;
  139749. notnull = pCol->notNull!=0;
  139750. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  139751. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  139752. }else{
  139753. zDataType = "INTEGER";
  139754. primarykey = 1;
  139755. }
  139756. if( !zCollSeq ){
  139757. zCollSeq = sqlite3StrBINARY;
  139758. }
  139759. error_out:
  139760. sqlite3BtreeLeaveAll(db);
  139761. /* Whether the function call succeeded or failed, set the output parameters
  139762. ** to whatever their local counterparts contain. If an error did occur,
  139763. ** this has the effect of zeroing all output parameters.
  139764. */
  139765. if( pzDataType ) *pzDataType = zDataType;
  139766. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  139767. if( pNotNull ) *pNotNull = notnull;
  139768. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  139769. if( pAutoinc ) *pAutoinc = autoinc;
  139770. if( SQLITE_OK==rc && !pTab ){
  139771. sqlite3DbFree(db, zErrMsg);
  139772. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  139773. zColumnName);
  139774. rc = SQLITE_ERROR;
  139775. }
  139776. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  139777. sqlite3DbFree(db, zErrMsg);
  139778. rc = sqlite3ApiExit(db, rc);
  139779. sqlite3_mutex_leave(db->mutex);
  139780. return rc;
  139781. }
  139782. /*
  139783. ** Sleep for a little while. Return the amount of time slept.
  139784. */
  139785. SQLITE_API int sqlite3_sleep(int ms){
  139786. sqlite3_vfs *pVfs;
  139787. int rc;
  139788. pVfs = sqlite3_vfs_find(0);
  139789. if( pVfs==0 ) return 0;
  139790. /* This function works in milliseconds, but the underlying OsSleep()
  139791. ** API uses microseconds. Hence the 1000's.
  139792. */
  139793. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  139794. return rc;
  139795. }
  139796. /*
  139797. ** Enable or disable the extended result codes.
  139798. */
  139799. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  139800. #ifdef SQLITE_ENABLE_API_ARMOR
  139801. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  139802. #endif
  139803. sqlite3_mutex_enter(db->mutex);
  139804. db->errMask = onoff ? 0xffffffff : 0xff;
  139805. sqlite3_mutex_leave(db->mutex);
  139806. return SQLITE_OK;
  139807. }
  139808. /*
  139809. ** Invoke the xFileControl method on a particular database.
  139810. */
  139811. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  139812. int rc = SQLITE_ERROR;
  139813. Btree *pBtree;
  139814. #ifdef SQLITE_ENABLE_API_ARMOR
  139815. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  139816. #endif
  139817. sqlite3_mutex_enter(db->mutex);
  139818. pBtree = sqlite3DbNameToBtree(db, zDbName);
  139819. if( pBtree ){
  139820. Pager *pPager;
  139821. sqlite3_file *fd;
  139822. sqlite3BtreeEnter(pBtree);
  139823. pPager = sqlite3BtreePager(pBtree);
  139824. assert( pPager!=0 );
  139825. fd = sqlite3PagerFile(pPager);
  139826. assert( fd!=0 );
  139827. if( op==SQLITE_FCNTL_FILE_POINTER ){
  139828. *(sqlite3_file**)pArg = fd;
  139829. rc = SQLITE_OK;
  139830. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  139831. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  139832. rc = SQLITE_OK;
  139833. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  139834. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  139835. rc = SQLITE_OK;
  139836. }else{
  139837. rc = sqlite3OsFileControl(fd, op, pArg);
  139838. }
  139839. sqlite3BtreeLeave(pBtree);
  139840. }
  139841. sqlite3_mutex_leave(db->mutex);
  139842. return rc;
  139843. }
  139844. /*
  139845. ** Interface to the testing logic.
  139846. */
  139847. SQLITE_API int sqlite3_test_control(int op, ...){
  139848. int rc = 0;
  139849. #ifdef SQLITE_UNTESTABLE
  139850. UNUSED_PARAMETER(op);
  139851. #else
  139852. va_list ap;
  139853. va_start(ap, op);
  139854. switch( op ){
  139855. /*
  139856. ** Save the current state of the PRNG.
  139857. */
  139858. case SQLITE_TESTCTRL_PRNG_SAVE: {
  139859. sqlite3PrngSaveState();
  139860. break;
  139861. }
  139862. /*
  139863. ** Restore the state of the PRNG to the last state saved using
  139864. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  139865. ** this verb acts like PRNG_RESET.
  139866. */
  139867. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  139868. sqlite3PrngRestoreState();
  139869. break;
  139870. }
  139871. /*
  139872. ** Reset the PRNG back to its uninitialized state. The next call
  139873. ** to sqlite3_randomness() will reseed the PRNG using a single call
  139874. ** to the xRandomness method of the default VFS.
  139875. */
  139876. case SQLITE_TESTCTRL_PRNG_RESET: {
  139877. sqlite3_randomness(0,0);
  139878. break;
  139879. }
  139880. /*
  139881. ** sqlite3_test_control(BITVEC_TEST, size, program)
  139882. **
  139883. ** Run a test against a Bitvec object of size. The program argument
  139884. ** is an array of integers that defines the test. Return -1 on a
  139885. ** memory allocation error, 0 on success, or non-zero for an error.
  139886. ** See the sqlite3BitvecBuiltinTest() for additional information.
  139887. */
  139888. case SQLITE_TESTCTRL_BITVEC_TEST: {
  139889. int sz = va_arg(ap, int);
  139890. int *aProg = va_arg(ap, int*);
  139891. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  139892. break;
  139893. }
  139894. /*
  139895. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  139896. **
  139897. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  139898. ** if xCallback is not NULL.
  139899. **
  139900. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  139901. ** is called immediately after installing the new callback and the return
  139902. ** value from sqlite3FaultSim(0) becomes the return from
  139903. ** sqlite3_test_control().
  139904. */
  139905. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  139906. /* MSVC is picky about pulling func ptrs from va lists.
  139907. ** http://support.microsoft.com/kb/47961
  139908. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  139909. */
  139910. typedef int(*TESTCALLBACKFUNC_t)(int);
  139911. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  139912. rc = sqlite3FaultSim(0);
  139913. break;
  139914. }
  139915. /*
  139916. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  139917. **
  139918. ** Register hooks to call to indicate which malloc() failures
  139919. ** are benign.
  139920. */
  139921. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  139922. typedef void (*void_function)(void);
  139923. void_function xBenignBegin;
  139924. void_function xBenignEnd;
  139925. xBenignBegin = va_arg(ap, void_function);
  139926. xBenignEnd = va_arg(ap, void_function);
  139927. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  139928. break;
  139929. }
  139930. /*
  139931. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  139932. **
  139933. ** Set the PENDING byte to the value in the argument, if X>0.
  139934. ** Make no changes if X==0. Return the value of the pending byte
  139935. ** as it existing before this routine was called.
  139936. **
  139937. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  139938. ** an incompatible database file format. Changing the PENDING byte
  139939. ** while any database connection is open results in undefined and
  139940. ** deleterious behavior.
  139941. */
  139942. case SQLITE_TESTCTRL_PENDING_BYTE: {
  139943. rc = PENDING_BYTE;
  139944. #ifndef SQLITE_OMIT_WSD
  139945. {
  139946. unsigned int newVal = va_arg(ap, unsigned int);
  139947. if( newVal ) sqlite3PendingByte = newVal;
  139948. }
  139949. #endif
  139950. break;
  139951. }
  139952. /*
  139953. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  139954. **
  139955. ** This action provides a run-time test to see whether or not
  139956. ** assert() was enabled at compile-time. If X is true and assert()
  139957. ** is enabled, then the return value is true. If X is true and
  139958. ** assert() is disabled, then the return value is zero. If X is
  139959. ** false and assert() is enabled, then the assertion fires and the
  139960. ** process aborts. If X is false and assert() is disabled, then the
  139961. ** return value is zero.
  139962. */
  139963. case SQLITE_TESTCTRL_ASSERT: {
  139964. volatile int x = 0;
  139965. assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
  139966. rc = x;
  139967. break;
  139968. }
  139969. /*
  139970. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  139971. **
  139972. ** This action provides a run-time test to see how the ALWAYS and
  139973. ** NEVER macros were defined at compile-time.
  139974. **
  139975. ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
  139976. **
  139977. ** The recommended test is X==2. If the return value is 2, that means
  139978. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  139979. ** default setting. If the return value is 1, then ALWAYS() is either
  139980. ** hard-coded to true or else it asserts if its argument is false.
  139981. ** The first behavior (hard-coded to true) is the case if
  139982. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  139983. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  139984. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  139985. **
  139986. ** The run-time test procedure might look something like this:
  139987. **
  139988. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  139989. ** // ALWAYS() and NEVER() are no-op pass-through macros
  139990. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  139991. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  139992. ** }else{
  139993. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  139994. ** }
  139995. */
  139996. case SQLITE_TESTCTRL_ALWAYS: {
  139997. int x = va_arg(ap,int);
  139998. rc = x ? ALWAYS(x) : 0;
  139999. break;
  140000. }
  140001. /*
  140002. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  140003. **
  140004. ** The integer returned reveals the byte-order of the computer on which
  140005. ** SQLite is running:
  140006. **
  140007. ** 1 big-endian, determined at run-time
  140008. ** 10 little-endian, determined at run-time
  140009. ** 432101 big-endian, determined at compile-time
  140010. ** 123410 little-endian, determined at compile-time
  140011. */
  140012. case SQLITE_TESTCTRL_BYTEORDER: {
  140013. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  140014. break;
  140015. }
  140016. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  140017. **
  140018. ** Set the nReserve size to N for the main database on the database
  140019. ** connection db.
  140020. */
  140021. case SQLITE_TESTCTRL_RESERVE: {
  140022. sqlite3 *db = va_arg(ap, sqlite3*);
  140023. int x = va_arg(ap,int);
  140024. sqlite3_mutex_enter(db->mutex);
  140025. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  140026. sqlite3_mutex_leave(db->mutex);
  140027. break;
  140028. }
  140029. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  140030. **
  140031. ** Enable or disable various optimizations for testing purposes. The
  140032. ** argument N is a bitmask of optimizations to be disabled. For normal
  140033. ** operation N should be 0. The idea is that a test program (like the
  140034. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  140035. ** with various optimizations disabled to verify that the same answer
  140036. ** is obtained in every case.
  140037. */
  140038. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  140039. sqlite3 *db = va_arg(ap, sqlite3*);
  140040. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  140041. break;
  140042. }
  140043. #ifdef SQLITE_N_KEYWORD
  140044. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  140045. **
  140046. ** If zWord is a keyword recognized by the parser, then return the
  140047. ** number of keywords. Or if zWord is not a keyword, return 0.
  140048. **
  140049. ** This test feature is only available in the amalgamation since
  140050. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  140051. ** is built using separate source files.
  140052. */
  140053. case SQLITE_TESTCTRL_ISKEYWORD: {
  140054. const char *zWord = va_arg(ap, const char*);
  140055. int n = sqlite3Strlen30(zWord);
  140056. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  140057. break;
  140058. }
  140059. #endif
  140060. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  140061. **
  140062. ** If parameter onoff is non-zero, configure the wrappers so that all
  140063. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  140064. ** undo this setting.
  140065. */
  140066. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  140067. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  140068. break;
  140069. }
  140070. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  140071. **
  140072. ** Set or clear a flag that indicates that the database file is always well-
  140073. ** formed and never corrupt. This flag is clear by default, indicating that
  140074. ** database files might have arbitrary corruption. Setting the flag during
  140075. ** testing causes certain assert() statements in the code to be activated
  140076. ** that demonstrat invariants on well-formed database files.
  140077. */
  140078. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  140079. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  140080. break;
  140081. }
  140082. /* Set the threshold at which OP_Once counters reset back to zero.
  140083. ** By default this is 0x7ffffffe (over 2 billion), but that value is
  140084. ** too big to test in a reasonable amount of time, so this control is
  140085. ** provided to set a small and easily reachable reset value.
  140086. */
  140087. case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
  140088. sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
  140089. break;
  140090. }
  140091. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  140092. **
  140093. ** Set the VDBE coverage callback function to xCallback with context
  140094. ** pointer ptr.
  140095. */
  140096. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  140097. #ifdef SQLITE_VDBE_COVERAGE
  140098. typedef void (*branch_callback)(void*,int,u8,u8);
  140099. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  140100. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  140101. #endif
  140102. break;
  140103. }
  140104. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  140105. case SQLITE_TESTCTRL_SORTER_MMAP: {
  140106. sqlite3 *db = va_arg(ap, sqlite3*);
  140107. db->nMaxSorterMmap = va_arg(ap, int);
  140108. break;
  140109. }
  140110. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  140111. **
  140112. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  140113. ** not.
  140114. */
  140115. case SQLITE_TESTCTRL_ISINIT: {
  140116. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  140117. break;
  140118. }
  140119. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  140120. **
  140121. ** This test control is used to create imposter tables. "db" is a pointer
  140122. ** to the database connection. dbName is the database name (ex: "main" or
  140123. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  140124. ** or off. "tnum" is the root page of the b-tree to which the imposter
  140125. ** table should connect.
  140126. **
  140127. ** Enable imposter mode only when the schema has already been parsed. Then
  140128. ** run a single CREATE TABLE statement to construct the imposter table in
  140129. ** the parsed schema. Then turn imposter mode back off again.
  140130. **
  140131. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  140132. ** the schema to be reparsed the next time it is needed. This has the
  140133. ** effect of erasing all imposter tables.
  140134. */
  140135. case SQLITE_TESTCTRL_IMPOSTER: {
  140136. sqlite3 *db = va_arg(ap, sqlite3*);
  140137. sqlite3_mutex_enter(db->mutex);
  140138. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  140139. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  140140. db->init.newTnum = va_arg(ap,int);
  140141. if( db->init.busy==0 && db->init.newTnum>0 ){
  140142. sqlite3ResetAllSchemasOfConnection(db);
  140143. }
  140144. sqlite3_mutex_leave(db->mutex);
  140145. break;
  140146. }
  140147. #if defined(YYCOVERAGE)
  140148. /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
  140149. **
  140150. ** This test control (only available when SQLite is compiled with
  140151. ** -DYYCOVERAGE) writes a report onto "out" that shows all
  140152. ** state/lookahead combinations in the parser state machine
  140153. ** which are never exercised. If any state is missed, make the
  140154. ** return code SQLITE_ERROR.
  140155. */
  140156. case SQLITE_TESTCTRL_PARSER_COVERAGE: {
  140157. FILE *out = va_arg(ap, FILE*);
  140158. if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
  140159. break;
  140160. }
  140161. #endif /* defined(YYCOVERAGE) */
  140162. }
  140163. va_end(ap);
  140164. #endif /* SQLITE_UNTESTABLE */
  140165. return rc;
  140166. }
  140167. /*
  140168. ** This is a utility routine, useful to VFS implementations, that checks
  140169. ** to see if a database file was a URI that contained a specific query
  140170. ** parameter, and if so obtains the value of the query parameter.
  140171. **
  140172. ** The zFilename argument is the filename pointer passed into the xOpen()
  140173. ** method of a VFS implementation. The zParam argument is the name of the
  140174. ** query parameter we seek. This routine returns the value of the zParam
  140175. ** parameter if it exists. If the parameter does not exist, this routine
  140176. ** returns a NULL pointer.
  140177. */
  140178. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  140179. if( zFilename==0 || zParam==0 ) return 0;
  140180. zFilename += sqlite3Strlen30(zFilename) + 1;
  140181. while( zFilename[0] ){
  140182. int x = strcmp(zFilename, zParam);
  140183. zFilename += sqlite3Strlen30(zFilename) + 1;
  140184. if( x==0 ) return zFilename;
  140185. zFilename += sqlite3Strlen30(zFilename) + 1;
  140186. }
  140187. return 0;
  140188. }
  140189. /*
  140190. ** Return a boolean value for a query parameter.
  140191. */
  140192. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  140193. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  140194. bDflt = bDflt!=0;
  140195. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  140196. }
  140197. /*
  140198. ** Return a 64-bit integer value for a query parameter.
  140199. */
  140200. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  140201. const char *zFilename, /* Filename as passed to xOpen */
  140202. const char *zParam, /* URI parameter sought */
  140203. sqlite3_int64 bDflt /* return if parameter is missing */
  140204. ){
  140205. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  140206. sqlite3_int64 v;
  140207. if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
  140208. bDflt = v;
  140209. }
  140210. return bDflt;
  140211. }
  140212. /*
  140213. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  140214. */
  140215. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  140216. int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
  140217. return iDb<0 ? 0 : db->aDb[iDb].pBt;
  140218. }
  140219. /*
  140220. ** Return the filename of the database associated with a database
  140221. ** connection.
  140222. */
  140223. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  140224. Btree *pBt;
  140225. #ifdef SQLITE_ENABLE_API_ARMOR
  140226. if( !sqlite3SafetyCheckOk(db) ){
  140227. (void)SQLITE_MISUSE_BKPT;
  140228. return 0;
  140229. }
  140230. #endif
  140231. pBt = sqlite3DbNameToBtree(db, zDbName);
  140232. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  140233. }
  140234. /*
  140235. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  140236. ** no such database exists.
  140237. */
  140238. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  140239. Btree *pBt;
  140240. #ifdef SQLITE_ENABLE_API_ARMOR
  140241. if( !sqlite3SafetyCheckOk(db) ){
  140242. (void)SQLITE_MISUSE_BKPT;
  140243. return -1;
  140244. }
  140245. #endif
  140246. pBt = sqlite3DbNameToBtree(db, zDbName);
  140247. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  140248. }
  140249. #ifdef SQLITE_ENABLE_SNAPSHOT
  140250. /*
  140251. ** Obtain a snapshot handle for the snapshot of database zDb currently
  140252. ** being read by handle db.
  140253. */
  140254. SQLITE_API int sqlite3_snapshot_get(
  140255. sqlite3 *db,
  140256. const char *zDb,
  140257. sqlite3_snapshot **ppSnapshot
  140258. ){
  140259. int rc = SQLITE_ERROR;
  140260. #ifndef SQLITE_OMIT_WAL
  140261. #ifdef SQLITE_ENABLE_API_ARMOR
  140262. if( !sqlite3SafetyCheckOk(db) ){
  140263. return SQLITE_MISUSE_BKPT;
  140264. }
  140265. #endif
  140266. sqlite3_mutex_enter(db->mutex);
  140267. if( db->autoCommit==0 ){
  140268. int iDb = sqlite3FindDbName(db, zDb);
  140269. if( iDb==0 || iDb>1 ){
  140270. Btree *pBt = db->aDb[iDb].pBt;
  140271. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  140272. rc = sqlite3BtreeBeginTrans(pBt, 0);
  140273. if( rc==SQLITE_OK ){
  140274. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  140275. }
  140276. }
  140277. }
  140278. }
  140279. sqlite3_mutex_leave(db->mutex);
  140280. #endif /* SQLITE_OMIT_WAL */
  140281. return rc;
  140282. }
  140283. /*
  140284. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  140285. */
  140286. SQLITE_API int sqlite3_snapshot_open(
  140287. sqlite3 *db,
  140288. const char *zDb,
  140289. sqlite3_snapshot *pSnapshot
  140290. ){
  140291. int rc = SQLITE_ERROR;
  140292. #ifndef SQLITE_OMIT_WAL
  140293. #ifdef SQLITE_ENABLE_API_ARMOR
  140294. if( !sqlite3SafetyCheckOk(db) ){
  140295. return SQLITE_MISUSE_BKPT;
  140296. }
  140297. #endif
  140298. sqlite3_mutex_enter(db->mutex);
  140299. if( db->autoCommit==0 ){
  140300. int iDb;
  140301. iDb = sqlite3FindDbName(db, zDb);
  140302. if( iDb==0 || iDb>1 ){
  140303. Btree *pBt = db->aDb[iDb].pBt;
  140304. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  140305. rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
  140306. if( rc==SQLITE_OK ){
  140307. rc = sqlite3BtreeBeginTrans(pBt, 0);
  140308. sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
  140309. }
  140310. }
  140311. }
  140312. }
  140313. sqlite3_mutex_leave(db->mutex);
  140314. #endif /* SQLITE_OMIT_WAL */
  140315. return rc;
  140316. }
  140317. /*
  140318. ** Recover as many snapshots as possible from the wal file associated with
  140319. ** schema zDb of database db.
  140320. */
  140321. SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
  140322. int rc = SQLITE_ERROR;
  140323. int iDb;
  140324. #ifndef SQLITE_OMIT_WAL
  140325. #ifdef SQLITE_ENABLE_API_ARMOR
  140326. if( !sqlite3SafetyCheckOk(db) ){
  140327. return SQLITE_MISUSE_BKPT;
  140328. }
  140329. #endif
  140330. sqlite3_mutex_enter(db->mutex);
  140331. iDb = sqlite3FindDbName(db, zDb);
  140332. if( iDb==0 || iDb>1 ){
  140333. Btree *pBt = db->aDb[iDb].pBt;
  140334. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  140335. rc = sqlite3BtreeBeginTrans(pBt, 0);
  140336. if( rc==SQLITE_OK ){
  140337. rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
  140338. sqlite3BtreeCommit(pBt);
  140339. }
  140340. }
  140341. }
  140342. sqlite3_mutex_leave(db->mutex);
  140343. #endif /* SQLITE_OMIT_WAL */
  140344. return rc;
  140345. }
  140346. /*
  140347. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  140348. */
  140349. SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  140350. sqlite3_free(pSnapshot);
  140351. }
  140352. #endif /* SQLITE_ENABLE_SNAPSHOT */
  140353. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  140354. /*
  140355. ** Given the name of a compile-time option, return true if that option
  140356. ** was used and false if not.
  140357. **
  140358. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  140359. ** is not required for a match.
  140360. */
  140361. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  140362. int i, n;
  140363. int nOpt;
  140364. const char **azCompileOpt;
  140365. #if SQLITE_ENABLE_API_ARMOR
  140366. if( zOptName==0 ){
  140367. (void)SQLITE_MISUSE_BKPT;
  140368. return 0;
  140369. }
  140370. #endif
  140371. azCompileOpt = sqlite3CompileOptions(&nOpt);
  140372. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  140373. n = sqlite3Strlen30(zOptName);
  140374. /* Since nOpt is normally in single digits, a linear search is
  140375. ** adequate. No need for a binary search. */
  140376. for(i=0; i<nOpt; i++){
  140377. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  140378. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  140379. ){
  140380. return 1;
  140381. }
  140382. }
  140383. return 0;
  140384. }
  140385. /*
  140386. ** Return the N-th compile-time option string. If N is out of range,
  140387. ** return a NULL pointer.
  140388. */
  140389. SQLITE_API const char *sqlite3_compileoption_get(int N){
  140390. int nOpt;
  140391. const char **azCompileOpt;
  140392. azCompileOpt = sqlite3CompileOptions(&nOpt);
  140393. if( N>=0 && N<nOpt ){
  140394. return azCompileOpt[N];
  140395. }
  140396. return 0;
  140397. }
  140398. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  140399. /************** End of main.c ************************************************/
  140400. /************** Begin file notify.c ******************************************/
  140401. /*
  140402. ** 2009 March 3
  140403. **
  140404. ** The author disclaims copyright to this source code. In place of
  140405. ** a legal notice, here is a blessing:
  140406. **
  140407. ** May you do good and not evil.
  140408. ** May you find forgiveness for yourself and forgive others.
  140409. ** May you share freely, never taking more than you give.
  140410. **
  140411. *************************************************************************
  140412. **
  140413. ** This file contains the implementation of the sqlite3_unlock_notify()
  140414. ** API method and its associated functionality.
  140415. */
  140416. /* #include "sqliteInt.h" */
  140417. /* #include "btreeInt.h" */
  140418. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  140419. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  140420. /*
  140421. ** Public interfaces:
  140422. **
  140423. ** sqlite3ConnectionBlocked()
  140424. ** sqlite3ConnectionUnlocked()
  140425. ** sqlite3ConnectionClosed()
  140426. ** sqlite3_unlock_notify()
  140427. */
  140428. #define assertMutexHeld() \
  140429. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  140430. /*
  140431. ** Head of a linked list of all sqlite3 objects created by this process
  140432. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  140433. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  140434. ** mutex is held.
  140435. */
  140436. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  140437. #ifndef NDEBUG
  140438. /*
  140439. ** This function is a complex assert() that verifies the following
  140440. ** properties of the blocked connections list:
  140441. **
  140442. ** 1) Each entry in the list has a non-NULL value for either
  140443. ** pUnlockConnection or pBlockingConnection, or both.
  140444. **
  140445. ** 2) All entries in the list that share a common value for
  140446. ** xUnlockNotify are grouped together.
  140447. **
  140448. ** 3) If the argument db is not NULL, then none of the entries in the
  140449. ** blocked connections list have pUnlockConnection or pBlockingConnection
  140450. ** set to db. This is used when closing connection db.
  140451. */
  140452. static void checkListProperties(sqlite3 *db){
  140453. sqlite3 *p;
  140454. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  140455. int seen = 0;
  140456. sqlite3 *p2;
  140457. /* Verify property (1) */
  140458. assert( p->pUnlockConnection || p->pBlockingConnection );
  140459. /* Verify property (2) */
  140460. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  140461. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  140462. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  140463. assert( db==0 || p->pUnlockConnection!=db );
  140464. assert( db==0 || p->pBlockingConnection!=db );
  140465. }
  140466. }
  140467. }
  140468. #else
  140469. # define checkListProperties(x)
  140470. #endif
  140471. /*
  140472. ** Remove connection db from the blocked connections list. If connection
  140473. ** db is not currently a part of the list, this function is a no-op.
  140474. */
  140475. static void removeFromBlockedList(sqlite3 *db){
  140476. sqlite3 **pp;
  140477. assertMutexHeld();
  140478. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  140479. if( *pp==db ){
  140480. *pp = (*pp)->pNextBlocked;
  140481. break;
  140482. }
  140483. }
  140484. }
  140485. /*
  140486. ** Add connection db to the blocked connections list. It is assumed
  140487. ** that it is not already a part of the list.
  140488. */
  140489. static void addToBlockedList(sqlite3 *db){
  140490. sqlite3 **pp;
  140491. assertMutexHeld();
  140492. for(
  140493. pp=&sqlite3BlockedList;
  140494. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  140495. pp=&(*pp)->pNextBlocked
  140496. );
  140497. db->pNextBlocked = *pp;
  140498. *pp = db;
  140499. }
  140500. /*
  140501. ** Obtain the STATIC_MASTER mutex.
  140502. */
  140503. static void enterMutex(void){
  140504. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  140505. checkListProperties(0);
  140506. }
  140507. /*
  140508. ** Release the STATIC_MASTER mutex.
  140509. */
  140510. static void leaveMutex(void){
  140511. assertMutexHeld();
  140512. checkListProperties(0);
  140513. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  140514. }
  140515. /*
  140516. ** Register an unlock-notify callback.
  140517. **
  140518. ** This is called after connection "db" has attempted some operation
  140519. ** but has received an SQLITE_LOCKED error because another connection
  140520. ** (call it pOther) in the same process was busy using the same shared
  140521. ** cache. pOther is found by looking at db->pBlockingConnection.
  140522. **
  140523. ** If there is no blocking connection, the callback is invoked immediately,
  140524. ** before this routine returns.
  140525. **
  140526. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  140527. ** a deadlock.
  140528. **
  140529. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  140530. ** its locks.
  140531. **
  140532. ** Each call to this routine overrides any prior callbacks registered
  140533. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  140534. ** cancelled.
  140535. */
  140536. SQLITE_API int sqlite3_unlock_notify(
  140537. sqlite3 *db,
  140538. void (*xNotify)(void **, int),
  140539. void *pArg
  140540. ){
  140541. int rc = SQLITE_OK;
  140542. sqlite3_mutex_enter(db->mutex);
  140543. enterMutex();
  140544. if( xNotify==0 ){
  140545. removeFromBlockedList(db);
  140546. db->pBlockingConnection = 0;
  140547. db->pUnlockConnection = 0;
  140548. db->xUnlockNotify = 0;
  140549. db->pUnlockArg = 0;
  140550. }else if( 0==db->pBlockingConnection ){
  140551. /* The blocking transaction has been concluded. Or there never was a
  140552. ** blocking transaction. In either case, invoke the notify callback
  140553. ** immediately.
  140554. */
  140555. xNotify(&pArg, 1);
  140556. }else{
  140557. sqlite3 *p;
  140558. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  140559. if( p ){
  140560. rc = SQLITE_LOCKED; /* Deadlock detected. */
  140561. }else{
  140562. db->pUnlockConnection = db->pBlockingConnection;
  140563. db->xUnlockNotify = xNotify;
  140564. db->pUnlockArg = pArg;
  140565. removeFromBlockedList(db);
  140566. addToBlockedList(db);
  140567. }
  140568. }
  140569. leaveMutex();
  140570. assert( !db->mallocFailed );
  140571. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  140572. sqlite3_mutex_leave(db->mutex);
  140573. return rc;
  140574. }
  140575. /*
  140576. ** This function is called while stepping or preparing a statement
  140577. ** associated with connection db. The operation will return SQLITE_LOCKED
  140578. ** to the user because it requires a lock that will not be available
  140579. ** until connection pBlocker concludes its current transaction.
  140580. */
  140581. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  140582. enterMutex();
  140583. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  140584. addToBlockedList(db);
  140585. }
  140586. db->pBlockingConnection = pBlocker;
  140587. leaveMutex();
  140588. }
  140589. /*
  140590. ** This function is called when
  140591. ** the transaction opened by database db has just finished. Locks held
  140592. ** by database connection db have been released.
  140593. **
  140594. ** This function loops through each entry in the blocked connections
  140595. ** list and does the following:
  140596. **
  140597. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  140598. ** set to db, then set pBlockingConnection=0.
  140599. **
  140600. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  140601. ** set to db, then invoke the configured unlock-notify callback and
  140602. ** set pUnlockConnection=0.
  140603. **
  140604. ** 3) If the two steps above mean that pBlockingConnection==0 and
  140605. ** pUnlockConnection==0, remove the entry from the blocked connections
  140606. ** list.
  140607. */
  140608. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  140609. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  140610. int nArg = 0; /* Number of entries in aArg[] */
  140611. sqlite3 **pp; /* Iterator variable */
  140612. void **aArg; /* Arguments to the unlock callback */
  140613. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  140614. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  140615. aArg = aStatic;
  140616. enterMutex(); /* Enter STATIC_MASTER mutex */
  140617. /* This loop runs once for each entry in the blocked-connections list. */
  140618. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  140619. sqlite3 *p = *pp;
  140620. /* Step 1. */
  140621. if( p->pBlockingConnection==db ){
  140622. p->pBlockingConnection = 0;
  140623. }
  140624. /* Step 2. */
  140625. if( p->pUnlockConnection==db ){
  140626. assert( p->xUnlockNotify );
  140627. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  140628. xUnlockNotify(aArg, nArg);
  140629. nArg = 0;
  140630. }
  140631. sqlite3BeginBenignMalloc();
  140632. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  140633. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  140634. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  140635. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  140636. ){
  140637. /* The aArg[] array needs to grow. */
  140638. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  140639. if( pNew ){
  140640. memcpy(pNew, aArg, nArg*sizeof(void *));
  140641. sqlite3_free(aDyn);
  140642. aDyn = aArg = pNew;
  140643. }else{
  140644. /* This occurs when the array of context pointers that need to
  140645. ** be passed to the unlock-notify callback is larger than the
  140646. ** aStatic[] array allocated on the stack and the attempt to
  140647. ** allocate a larger array from the heap has failed.
  140648. **
  140649. ** This is a difficult situation to handle. Returning an error
  140650. ** code to the caller is insufficient, as even if an error code
  140651. ** is returned the transaction on connection db will still be
  140652. ** closed and the unlock-notify callbacks on blocked connections
  140653. ** will go unissued. This might cause the application to wait
  140654. ** indefinitely for an unlock-notify callback that will never
  140655. ** arrive.
  140656. **
  140657. ** Instead, invoke the unlock-notify callback with the context
  140658. ** array already accumulated. We can then clear the array and
  140659. ** begin accumulating any further context pointers without
  140660. ** requiring any dynamic allocation. This is sub-optimal because
  140661. ** it means that instead of one callback with a large array of
  140662. ** context pointers the application will receive two or more
  140663. ** callbacks with smaller arrays of context pointers, which will
  140664. ** reduce the applications ability to prioritize multiple
  140665. ** connections. But it is the best that can be done under the
  140666. ** circumstances.
  140667. */
  140668. xUnlockNotify(aArg, nArg);
  140669. nArg = 0;
  140670. }
  140671. }
  140672. sqlite3EndBenignMalloc();
  140673. aArg[nArg++] = p->pUnlockArg;
  140674. xUnlockNotify = p->xUnlockNotify;
  140675. p->pUnlockConnection = 0;
  140676. p->xUnlockNotify = 0;
  140677. p->pUnlockArg = 0;
  140678. }
  140679. /* Step 3. */
  140680. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  140681. /* Remove connection p from the blocked connections list. */
  140682. *pp = p->pNextBlocked;
  140683. p->pNextBlocked = 0;
  140684. }else{
  140685. pp = &p->pNextBlocked;
  140686. }
  140687. }
  140688. if( nArg!=0 ){
  140689. xUnlockNotify(aArg, nArg);
  140690. }
  140691. sqlite3_free(aDyn);
  140692. leaveMutex(); /* Leave STATIC_MASTER mutex */
  140693. }
  140694. /*
  140695. ** This is called when the database connection passed as an argument is
  140696. ** being closed. The connection is removed from the blocked list.
  140697. */
  140698. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  140699. sqlite3ConnectionUnlocked(db);
  140700. enterMutex();
  140701. removeFromBlockedList(db);
  140702. checkListProperties(db);
  140703. leaveMutex();
  140704. }
  140705. #endif
  140706. /************** End of notify.c **********************************************/
  140707. /************** Begin file fts3.c ********************************************/
  140708. /*
  140709. ** 2006 Oct 10
  140710. **
  140711. ** The author disclaims copyright to this source code. In place of
  140712. ** a legal notice, here is a blessing:
  140713. **
  140714. ** May you do good and not evil.
  140715. ** May you find forgiveness for yourself and forgive others.
  140716. ** May you share freely, never taking more than you give.
  140717. **
  140718. ******************************************************************************
  140719. **
  140720. ** This is an SQLite module implementing full-text search.
  140721. */
  140722. /*
  140723. ** The code in this file is only compiled if:
  140724. **
  140725. ** * The FTS3 module is being built as an extension
  140726. ** (in which case SQLITE_CORE is not defined), or
  140727. **
  140728. ** * The FTS3 module is being built into the core of
  140729. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  140730. */
  140731. /* The full-text index is stored in a series of b+tree (-like)
  140732. ** structures called segments which map terms to doclists. The
  140733. ** structures are like b+trees in layout, but are constructed from the
  140734. ** bottom up in optimal fashion and are not updatable. Since trees
  140735. ** are built from the bottom up, things will be described from the
  140736. ** bottom up.
  140737. **
  140738. **
  140739. **** Varints ****
  140740. ** The basic unit of encoding is a variable-length integer called a
  140741. ** varint. We encode variable-length integers in little-endian order
  140742. ** using seven bits * per byte as follows:
  140743. **
  140744. ** KEY:
  140745. ** A = 0xxxxxxx 7 bits of data and one flag bit
  140746. ** B = 1xxxxxxx 7 bits of data and one flag bit
  140747. **
  140748. ** 7 bits - A
  140749. ** 14 bits - BA
  140750. ** 21 bits - BBA
  140751. ** and so on.
  140752. **
  140753. ** This is similar in concept to how sqlite encodes "varints" but
  140754. ** the encoding is not the same. SQLite varints are big-endian
  140755. ** are are limited to 9 bytes in length whereas FTS3 varints are
  140756. ** little-endian and can be up to 10 bytes in length (in theory).
  140757. **
  140758. ** Example encodings:
  140759. **
  140760. ** 1: 0x01
  140761. ** 127: 0x7f
  140762. ** 128: 0x81 0x00
  140763. **
  140764. **
  140765. **** Document lists ****
  140766. ** A doclist (document list) holds a docid-sorted list of hits for a
  140767. ** given term. Doclists hold docids and associated token positions.
  140768. ** A docid is the unique integer identifier for a single document.
  140769. ** A position is the index of a word within the document. The first
  140770. ** word of the document has a position of 0.
  140771. **
  140772. ** FTS3 used to optionally store character offsets using a compile-time
  140773. ** option. But that functionality is no longer supported.
  140774. **
  140775. ** A doclist is stored like this:
  140776. **
  140777. ** array {
  140778. ** varint docid; (delta from previous doclist)
  140779. ** array { (position list for column 0)
  140780. ** varint position; (2 more than the delta from previous position)
  140781. ** }
  140782. ** array {
  140783. ** varint POS_COLUMN; (marks start of position list for new column)
  140784. ** varint column; (index of new column)
  140785. ** array {
  140786. ** varint position; (2 more than the delta from previous position)
  140787. ** }
  140788. ** }
  140789. ** varint POS_END; (marks end of positions for this document.
  140790. ** }
  140791. **
  140792. ** Here, array { X } means zero or more occurrences of X, adjacent in
  140793. ** memory. A "position" is an index of a token in the token stream
  140794. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  140795. ** in the same logical place as the position element, and act as sentinals
  140796. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  140797. ** The positions numbers are not stored literally but rather as two more
  140798. ** than the difference from the prior position, or the just the position plus
  140799. ** 2 for the first position. Example:
  140800. **
  140801. ** label: A B C D E F G H I J K
  140802. ** value: 123 5 9 1 1 14 35 0 234 72 0
  140803. **
  140804. ** The 123 value is the first docid. For column zero in this document
  140805. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  140806. ** at D signals the start of a new column; the 1 at E indicates that the
  140807. ** new column is column number 1. There are two positions at 12 and 45
  140808. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  140809. ** 234 at I is the delta to next docid (357). It has one position 70
  140810. ** (72-2) and then terminates with the 0 at K.
  140811. **
  140812. ** A "position-list" is the list of positions for multiple columns for
  140813. ** a single docid. A "column-list" is the set of positions for a single
  140814. ** column. Hence, a position-list consists of one or more column-lists,
  140815. ** a document record consists of a docid followed by a position-list and
  140816. ** a doclist consists of one or more document records.
  140817. **
  140818. ** A bare doclist omits the position information, becoming an
  140819. ** array of varint-encoded docids.
  140820. **
  140821. **** Segment leaf nodes ****
  140822. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  140823. ** nodes are written using LeafWriter, and read using LeafReader (to
  140824. ** iterate through a single leaf node's data) and LeavesReader (to
  140825. ** iterate through a segment's entire leaf layer). Leaf nodes have
  140826. ** the format:
  140827. **
  140828. ** varint iHeight; (height from leaf level, always 0)
  140829. ** varint nTerm; (length of first term)
  140830. ** char pTerm[nTerm]; (content of first term)
  140831. ** varint nDoclist; (length of term's associated doclist)
  140832. ** char pDoclist[nDoclist]; (content of doclist)
  140833. ** array {
  140834. ** (further terms are delta-encoded)
  140835. ** varint nPrefix; (length of prefix shared with previous term)
  140836. ** varint nSuffix; (length of unshared suffix)
  140837. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  140838. ** varint nDoclist; (length of term's associated doclist)
  140839. ** char pDoclist[nDoclist]; (content of doclist)
  140840. ** }
  140841. **
  140842. ** Here, array { X } means zero or more occurrences of X, adjacent in
  140843. ** memory.
  140844. **
  140845. ** Leaf nodes are broken into blocks which are stored contiguously in
  140846. ** the %_segments table in sorted order. This means that when the end
  140847. ** of a node is reached, the next term is in the node with the next
  140848. ** greater node id.
  140849. **
  140850. ** New data is spilled to a new leaf node when the current node
  140851. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  140852. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  140853. ** node (a leaf node with a single term and doclist). The goal of
  140854. ** these settings is to pack together groups of small doclists while
  140855. ** making it efficient to directly access large doclists. The
  140856. ** assumption is that large doclists represent terms which are more
  140857. ** likely to be query targets.
  140858. **
  140859. ** TODO(shess) It may be useful for blocking decisions to be more
  140860. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  140861. ** node rather than splitting into 2k and .5k nodes. My intuition is
  140862. ** that this might extend through 2x or 4x the pagesize.
  140863. **
  140864. **
  140865. **** Segment interior nodes ****
  140866. ** Segment interior nodes store blockids for subtree nodes and terms
  140867. ** to describe what data is stored by the each subtree. Interior
  140868. ** nodes are written using InteriorWriter, and read using
  140869. ** InteriorReader. InteriorWriters are created as needed when
  140870. ** SegmentWriter creates new leaf nodes, or when an interior node
  140871. ** itself grows too big and must be split. The format of interior
  140872. ** nodes:
  140873. **
  140874. ** varint iHeight; (height from leaf level, always >0)
  140875. ** varint iBlockid; (block id of node's leftmost subtree)
  140876. ** optional {
  140877. ** varint nTerm; (length of first term)
  140878. ** char pTerm[nTerm]; (content of first term)
  140879. ** array {
  140880. ** (further terms are delta-encoded)
  140881. ** varint nPrefix; (length of shared prefix with previous term)
  140882. ** varint nSuffix; (length of unshared suffix)
  140883. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  140884. ** }
  140885. ** }
  140886. **
  140887. ** Here, optional { X } means an optional element, while array { X }
  140888. ** means zero or more occurrences of X, adjacent in memory.
  140889. **
  140890. ** An interior node encodes n terms separating n+1 subtrees. The
  140891. ** subtree blocks are contiguous, so only the first subtree's blockid
  140892. ** is encoded. The subtree at iBlockid will contain all terms less
  140893. ** than the first term encoded (or all terms if no term is encoded).
  140894. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  140895. ** than pTerm[i+1], the subtree for that term will be rooted at
  140896. ** iBlockid+i. Interior nodes only store enough term data to
  140897. ** distinguish adjacent children (if the rightmost term of the left
  140898. ** child is "something", and the leftmost term of the right child is
  140899. ** "wicked", only "w" is stored).
  140900. **
  140901. ** New data is spilled to a new interior node at the same height when
  140902. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  140903. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  140904. ** interior nodes and making the tree too skinny. The interior nodes
  140905. ** at a given height are naturally tracked by interior nodes at
  140906. ** height+1, and so on.
  140907. **
  140908. **
  140909. **** Segment directory ****
  140910. ** The segment directory in table %_segdir stores meta-information for
  140911. ** merging and deleting segments, and also the root node of the
  140912. ** segment's tree.
  140913. **
  140914. ** The root node is the top node of the segment's tree after encoding
  140915. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  140916. ** This could be either a leaf node or an interior node. If the top
  140917. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  140918. ** and a new root interior node is generated (which should always fit
  140919. ** within ROOT_MAX because it only needs space for 2 varints, the
  140920. ** height and the blockid of the previous root).
  140921. **
  140922. ** The meta-information in the segment directory is:
  140923. ** level - segment level (see below)
  140924. ** idx - index within level
  140925. ** - (level,idx uniquely identify a segment)
  140926. ** start_block - first leaf node
  140927. ** leaves_end_block - last leaf node
  140928. ** end_block - last block (including interior nodes)
  140929. ** root - contents of root node
  140930. **
  140931. ** If the root node is a leaf node, then start_block,
  140932. ** leaves_end_block, and end_block are all 0.
  140933. **
  140934. **
  140935. **** Segment merging ****
  140936. ** To amortize update costs, segments are grouped into levels and
  140937. ** merged in batches. Each increase in level represents exponentially
  140938. ** more documents.
  140939. **
  140940. ** New documents (actually, document updates) are tokenized and
  140941. ** written individually (using LeafWriter) to a level 0 segment, with
  140942. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  140943. ** level 0 segments are merged into a single level 1 segment. Level 1
  140944. ** is populated like level 0, and eventually MERGE_COUNT level 1
  140945. ** segments are merged to a single level 2 segment (representing
  140946. ** MERGE_COUNT^2 updates), and so on.
  140947. **
  140948. ** A segment merge traverses all segments at a given level in
  140949. ** parallel, performing a straightforward sorted merge. Since segment
  140950. ** leaf nodes are written in to the %_segments table in order, this
  140951. ** merge traverses the underlying sqlite disk structures efficiently.
  140952. ** After the merge, all segment blocks from the merged level are
  140953. ** deleted.
  140954. **
  140955. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  140956. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  140957. ** very similar performance numbers to 16 on insertion, though they're
  140958. ** a tiny bit slower (perhaps due to more overhead in merge-time
  140959. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  140960. ** 16, 2 about 66% slower than 16.
  140961. **
  140962. ** At query time, high MERGE_COUNT increases the number of segments
  140963. ** which need to be scanned and merged. For instance, with 100k docs
  140964. ** inserted:
  140965. **
  140966. ** MERGE_COUNT segments
  140967. ** 16 25
  140968. ** 8 12
  140969. ** 4 10
  140970. ** 2 6
  140971. **
  140972. ** This appears to have only a moderate impact on queries for very
  140973. ** frequent terms (which are somewhat dominated by segment merge
  140974. ** costs), and infrequent and non-existent terms still seem to be fast
  140975. ** even with many segments.
  140976. **
  140977. ** TODO(shess) That said, it would be nice to have a better query-side
  140978. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  140979. ** optimizations to things like doclist merging will swing the sweet
  140980. ** spot around.
  140981. **
  140982. **
  140983. **
  140984. **** Handling of deletions and updates ****
  140985. ** Since we're using a segmented structure, with no docid-oriented
  140986. ** index into the term index, we clearly cannot simply update the term
  140987. ** index when a document is deleted or updated. For deletions, we
  140988. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  140989. ** we simply write the new doclist. Segment merges overwrite older
  140990. ** data for a particular docid with newer data, so deletes or updates
  140991. ** will eventually overtake the earlier data and knock it out. The
  140992. ** query logic likewise merges doclists so that newer data knocks out
  140993. ** older data.
  140994. */
  140995. /************** Include fts3Int.h in the middle of fts3.c ********************/
  140996. /************** Begin file fts3Int.h *****************************************/
  140997. /*
  140998. ** 2009 Nov 12
  140999. **
  141000. ** The author disclaims copyright to this source code. In place of
  141001. ** a legal notice, here is a blessing:
  141002. **
  141003. ** May you do good and not evil.
  141004. ** May you find forgiveness for yourself and forgive others.
  141005. ** May you share freely, never taking more than you give.
  141006. **
  141007. ******************************************************************************
  141008. **
  141009. */
  141010. #ifndef _FTSINT_H
  141011. #define _FTSINT_H
  141012. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  141013. # define NDEBUG 1
  141014. #endif
  141015. /* FTS3/FTS4 require virtual tables */
  141016. #ifdef SQLITE_OMIT_VIRTUALTABLE
  141017. # undef SQLITE_ENABLE_FTS3
  141018. # undef SQLITE_ENABLE_FTS4
  141019. #endif
  141020. /*
  141021. ** FTS4 is really an extension for FTS3. It is enabled using the
  141022. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  141023. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  141024. */
  141025. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  141026. # define SQLITE_ENABLE_FTS3
  141027. #endif
  141028. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  141029. /* If not building as part of the core, include sqlite3ext.h. */
  141030. #ifndef SQLITE_CORE
  141031. /* # include "sqlite3ext.h" */
  141032. SQLITE_EXTENSION_INIT3
  141033. #endif
  141034. /* #include "sqlite3.h" */
  141035. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  141036. /************** Begin file fts3_tokenizer.h **********************************/
  141037. /*
  141038. ** 2006 July 10
  141039. **
  141040. ** The author disclaims copyright to this source code.
  141041. **
  141042. *************************************************************************
  141043. ** Defines the interface to tokenizers used by fulltext-search. There
  141044. ** are three basic components:
  141045. **
  141046. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  141047. ** interface functions. This is essentially the class structure for
  141048. ** tokenizers.
  141049. **
  141050. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  141051. ** including customization information defined at creation time.
  141052. **
  141053. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  141054. ** tokens from a particular input.
  141055. */
  141056. #ifndef _FTS3_TOKENIZER_H_
  141057. #define _FTS3_TOKENIZER_H_
  141058. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  141059. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  141060. ** we will need a way to register the API consistently.
  141061. */
  141062. /* #include "sqlite3.h" */
  141063. /*
  141064. ** Structures used by the tokenizer interface. When a new tokenizer
  141065. ** implementation is registered, the caller provides a pointer to
  141066. ** an sqlite3_tokenizer_module containing pointers to the callback
  141067. ** functions that make up an implementation.
  141068. **
  141069. ** When an fts3 table is created, it passes any arguments passed to
  141070. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  141071. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  141072. ** implementation. The xCreate() function in turn returns an
  141073. ** sqlite3_tokenizer structure representing the specific tokenizer to
  141074. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  141075. **
  141076. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  141077. ** method is called. It returns an sqlite3_tokenizer_cursor object
  141078. ** that may be used to tokenize a specific input buffer based on
  141079. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  141080. ** object.
  141081. */
  141082. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  141083. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  141084. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  141085. struct sqlite3_tokenizer_module {
  141086. /*
  141087. ** Structure version. Should always be set to 0 or 1.
  141088. */
  141089. int iVersion;
  141090. /*
  141091. ** Create a new tokenizer. The values in the argv[] array are the
  141092. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  141093. ** TABLE statement that created the fts3 table. For example, if
  141094. ** the following SQL is executed:
  141095. **
  141096. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  141097. **
  141098. ** then argc is set to 2, and the argv[] array contains pointers
  141099. ** to the strings "arg1" and "arg2".
  141100. **
  141101. ** This method should return either SQLITE_OK (0), or an SQLite error
  141102. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  141103. ** to point at the newly created tokenizer structure. The generic
  141104. ** sqlite3_tokenizer.pModule variable should not be initialized by
  141105. ** this callback. The caller will do so.
  141106. */
  141107. int (*xCreate)(
  141108. int argc, /* Size of argv array */
  141109. const char *const*argv, /* Tokenizer argument strings */
  141110. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  141111. );
  141112. /*
  141113. ** Destroy an existing tokenizer. The fts3 module calls this method
  141114. ** exactly once for each successful call to xCreate().
  141115. */
  141116. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  141117. /*
  141118. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  141119. ** is responsible for ensuring that the input buffer remains valid
  141120. ** until the cursor is closed (using the xClose() method).
  141121. */
  141122. int (*xOpen)(
  141123. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  141124. const char *pInput, int nBytes, /* Input buffer */
  141125. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  141126. );
  141127. /*
  141128. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  141129. ** method exactly once for each successful call to xOpen().
  141130. */
  141131. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  141132. /*
  141133. ** Retrieve the next token from the tokenizer cursor pCursor. This
  141134. ** method should either return SQLITE_OK and set the values of the
  141135. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  141136. ** the end of the buffer has been reached, or an SQLite error code.
  141137. **
  141138. ** *ppToken should be set to point at a buffer containing the
  141139. ** normalized version of the token (i.e. after any case-folding and/or
  141140. ** stemming has been performed). *pnBytes should be set to the length
  141141. ** of this buffer in bytes. The input text that generated the token is
  141142. ** identified by the byte offsets returned in *piStartOffset and
  141143. ** *piEndOffset. *piStartOffset should be set to the index of the first
  141144. ** byte of the token in the input buffer. *piEndOffset should be set
  141145. ** to the index of the first byte just past the end of the token in
  141146. ** the input buffer.
  141147. **
  141148. ** The buffer *ppToken is set to point at is managed by the tokenizer
  141149. ** implementation. It is only required to be valid until the next call
  141150. ** to xNext() or xClose().
  141151. */
  141152. /* TODO(shess) current implementation requires pInput to be
  141153. ** nul-terminated. This should either be fixed, or pInput/nBytes
  141154. ** should be converted to zInput.
  141155. */
  141156. int (*xNext)(
  141157. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  141158. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  141159. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  141160. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  141161. int *piPosition /* OUT: Number of tokens returned before this one */
  141162. );
  141163. /***********************************************************************
  141164. ** Methods below this point are only available if iVersion>=1.
  141165. */
  141166. /*
  141167. ** Configure the language id of a tokenizer cursor.
  141168. */
  141169. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  141170. };
  141171. struct sqlite3_tokenizer {
  141172. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  141173. /* Tokenizer implementations will typically add additional fields */
  141174. };
  141175. struct sqlite3_tokenizer_cursor {
  141176. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  141177. /* Tokenizer implementations will typically add additional fields */
  141178. };
  141179. int fts3_global_term_cnt(int iTerm, int iCol);
  141180. int fts3_term_cnt(int iTerm, int iCol);
  141181. #endif /* _FTS3_TOKENIZER_H_ */
  141182. /************** End of fts3_tokenizer.h **************************************/
  141183. /************** Continuing where we left off in fts3Int.h ********************/
  141184. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  141185. /************** Begin file fts3_hash.h ***************************************/
  141186. /*
  141187. ** 2001 September 22
  141188. **
  141189. ** The author disclaims copyright to this source code. In place of
  141190. ** a legal notice, here is a blessing:
  141191. **
  141192. ** May you do good and not evil.
  141193. ** May you find forgiveness for yourself and forgive others.
  141194. ** May you share freely, never taking more than you give.
  141195. **
  141196. *************************************************************************
  141197. ** This is the header file for the generic hash-table implementation
  141198. ** used in SQLite. We've modified it slightly to serve as a standalone
  141199. ** hash table implementation for the full-text indexing module.
  141200. **
  141201. */
  141202. #ifndef _FTS3_HASH_H_
  141203. #define _FTS3_HASH_H_
  141204. /* Forward declarations of structures. */
  141205. typedef struct Fts3Hash Fts3Hash;
  141206. typedef struct Fts3HashElem Fts3HashElem;
  141207. /* A complete hash table is an instance of the following structure.
  141208. ** The internals of this structure are intended to be opaque -- client
  141209. ** code should not attempt to access or modify the fields of this structure
  141210. ** directly. Change this structure only by using the routines below.
  141211. ** However, many of the "procedures" and "functions" for modifying and
  141212. ** accessing this structure are really macros, so we can't really make
  141213. ** this structure opaque.
  141214. */
  141215. struct Fts3Hash {
  141216. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  141217. char copyKey; /* True if copy of key made on insert */
  141218. int count; /* Number of entries in this table */
  141219. Fts3HashElem *first; /* The first element of the array */
  141220. int htsize; /* Number of buckets in the hash table */
  141221. struct _fts3ht { /* the hash table */
  141222. int count; /* Number of entries with this hash */
  141223. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  141224. } *ht;
  141225. };
  141226. /* Each element in the hash table is an instance of the following
  141227. ** structure. All elements are stored on a single doubly-linked list.
  141228. **
  141229. ** Again, this structure is intended to be opaque, but it can't really
  141230. ** be opaque because it is used by macros.
  141231. */
  141232. struct Fts3HashElem {
  141233. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  141234. void *data; /* Data associated with this element */
  141235. void *pKey; int nKey; /* Key associated with this element */
  141236. };
  141237. /*
  141238. ** There are 2 different modes of operation for a hash table:
  141239. **
  141240. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  141241. ** (including the null-terminator, if any). Case
  141242. ** is respected in comparisons.
  141243. **
  141244. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  141245. ** memcmp() is used to compare keys.
  141246. **
  141247. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  141248. */
  141249. #define FTS3_HASH_STRING 1
  141250. #define FTS3_HASH_BINARY 2
  141251. /*
  141252. ** Access routines. To delete, insert a NULL pointer.
  141253. */
  141254. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  141255. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  141256. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  141257. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  141258. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  141259. /*
  141260. ** Shorthand for the functions above
  141261. */
  141262. #define fts3HashInit sqlite3Fts3HashInit
  141263. #define fts3HashInsert sqlite3Fts3HashInsert
  141264. #define fts3HashFind sqlite3Fts3HashFind
  141265. #define fts3HashClear sqlite3Fts3HashClear
  141266. #define fts3HashFindElem sqlite3Fts3HashFindElem
  141267. /*
  141268. ** Macros for looping over all elements of a hash table. The idiom is
  141269. ** like this:
  141270. **
  141271. ** Fts3Hash h;
  141272. ** Fts3HashElem *p;
  141273. ** ...
  141274. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  141275. ** SomeStructure *pData = fts3HashData(p);
  141276. ** // do something with pData
  141277. ** }
  141278. */
  141279. #define fts3HashFirst(H) ((H)->first)
  141280. #define fts3HashNext(E) ((E)->next)
  141281. #define fts3HashData(E) ((E)->data)
  141282. #define fts3HashKey(E) ((E)->pKey)
  141283. #define fts3HashKeysize(E) ((E)->nKey)
  141284. /*
  141285. ** Number of entries in a hash table
  141286. */
  141287. #define fts3HashCount(H) ((H)->count)
  141288. #endif /* _FTS3_HASH_H_ */
  141289. /************** End of fts3_hash.h *******************************************/
  141290. /************** Continuing where we left off in fts3Int.h ********************/
  141291. /*
  141292. ** This constant determines the maximum depth of an FTS expression tree
  141293. ** that the library will create and use. FTS uses recursion to perform
  141294. ** various operations on the query tree, so the disadvantage of a large
  141295. ** limit is that it may allow very large queries to use large amounts
  141296. ** of stack space (perhaps causing a stack overflow).
  141297. */
  141298. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  141299. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  141300. #endif
  141301. /*
  141302. ** This constant controls how often segments are merged. Once there are
  141303. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  141304. ** segment of level N+1.
  141305. */
  141306. #define FTS3_MERGE_COUNT 16
  141307. /*
  141308. ** This is the maximum amount of data (in bytes) to store in the
  141309. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  141310. ** populated as documents are inserted/updated/deleted in a transaction
  141311. ** and used to create a new segment when the transaction is committed.
  141312. ** However if this limit is reached midway through a transaction, a new
  141313. ** segment is created and the hash table cleared immediately.
  141314. */
  141315. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  141316. /*
  141317. ** Macro to return the number of elements in an array. SQLite has a
  141318. ** similar macro called ArraySize(). Use a different name to avoid
  141319. ** a collision when building an amalgamation with built-in FTS3.
  141320. */
  141321. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  141322. #ifndef MIN
  141323. # define MIN(x,y) ((x)<(y)?(x):(y))
  141324. #endif
  141325. #ifndef MAX
  141326. # define MAX(x,y) ((x)>(y)?(x):(y))
  141327. #endif
  141328. /*
  141329. ** Maximum length of a varint encoded integer. The varint format is different
  141330. ** from that used by SQLite, so the maximum length is 10, not 9.
  141331. */
  141332. #define FTS3_VARINT_MAX 10
  141333. /*
  141334. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  141335. ** in the document set and zero or more prefix indexes. All indexes are stored
  141336. ** as one or more b+-trees in the %_segments and %_segdir tables.
  141337. **
  141338. ** It is possible to determine which index a b+-tree belongs to based on the
  141339. ** value stored in the "%_segdir.level" column. Given this value L, the index
  141340. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  141341. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  141342. ** between 1024 and 2047 to index 1, and so on.
  141343. **
  141344. ** It is considered impossible for an index to use more than 1024 levels. In
  141345. ** theory though this may happen, but only after at least
  141346. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  141347. */
  141348. #define FTS3_SEGDIR_MAXLEVEL 1024
  141349. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  141350. /*
  141351. ** The testcase() macro is only used by the amalgamation. If undefined,
  141352. ** make it a no-op.
  141353. */
  141354. #ifndef testcase
  141355. # define testcase(X)
  141356. #endif
  141357. /*
  141358. ** Terminator values for position-lists and column-lists.
  141359. */
  141360. #define POS_COLUMN (1) /* Column-list terminator */
  141361. #define POS_END (0) /* Position-list terminator */
  141362. /*
  141363. ** This section provides definitions to allow the
  141364. ** FTS3 extension to be compiled outside of the
  141365. ** amalgamation.
  141366. */
  141367. #ifndef SQLITE_AMALGAMATION
  141368. /*
  141369. ** Macros indicating that conditional expressions are always true or
  141370. ** false.
  141371. */
  141372. #ifdef SQLITE_COVERAGE_TEST
  141373. # define ALWAYS(x) (1)
  141374. # define NEVER(X) (0)
  141375. #elif defined(SQLITE_DEBUG)
  141376. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  141377. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  141378. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  141379. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  141380. #else
  141381. # define ALWAYS(x) (x)
  141382. # define NEVER(x) (x)
  141383. #endif
  141384. /*
  141385. ** Internal types used by SQLite.
  141386. */
  141387. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  141388. typedef short int i16; /* 2-byte (or larger) signed integer */
  141389. typedef unsigned int u32; /* 4-byte unsigned integer */
  141390. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  141391. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  141392. /*
  141393. ** Macro used to suppress compiler warnings for unused parameters.
  141394. */
  141395. #define UNUSED_PARAMETER(x) (void)(x)
  141396. /*
  141397. ** Activate assert() only if SQLITE_TEST is enabled.
  141398. */
  141399. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  141400. # define NDEBUG 1
  141401. #endif
  141402. /*
  141403. ** The TESTONLY macro is used to enclose variable declarations or
  141404. ** other bits of code that are needed to support the arguments
  141405. ** within testcase() and assert() macros.
  141406. */
  141407. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  141408. # define TESTONLY(X) X
  141409. #else
  141410. # define TESTONLY(X)
  141411. #endif
  141412. #endif /* SQLITE_AMALGAMATION */
  141413. #ifdef SQLITE_DEBUG
  141414. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  141415. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  141416. #else
  141417. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  141418. #endif
  141419. typedef struct Fts3Table Fts3Table;
  141420. typedef struct Fts3Cursor Fts3Cursor;
  141421. typedef struct Fts3Expr Fts3Expr;
  141422. typedef struct Fts3Phrase Fts3Phrase;
  141423. typedef struct Fts3PhraseToken Fts3PhraseToken;
  141424. typedef struct Fts3Doclist Fts3Doclist;
  141425. typedef struct Fts3SegFilter Fts3SegFilter;
  141426. typedef struct Fts3DeferredToken Fts3DeferredToken;
  141427. typedef struct Fts3SegReader Fts3SegReader;
  141428. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  141429. typedef struct MatchinfoBuffer MatchinfoBuffer;
  141430. /*
  141431. ** A connection to a fulltext index is an instance of the following
  141432. ** structure. The xCreate and xConnect methods create an instance
  141433. ** of this structure and xDestroy and xDisconnect free that instance.
  141434. ** All other methods receive a pointer to the structure as one of their
  141435. ** arguments.
  141436. */
  141437. struct Fts3Table {
  141438. sqlite3_vtab base; /* Base class used by SQLite core */
  141439. sqlite3 *db; /* The database connection */
  141440. const char *zDb; /* logical database name */
  141441. const char *zName; /* virtual table name */
  141442. int nColumn; /* number of named columns in virtual table */
  141443. char **azColumn; /* column names. malloced */
  141444. u8 *abNotindexed; /* True for 'notindexed' columns */
  141445. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  141446. char *zContentTbl; /* content=xxx option, or NULL */
  141447. char *zLanguageid; /* languageid=xxx option, or NULL */
  141448. int nAutoincrmerge; /* Value configured by 'automerge' */
  141449. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  141450. /* Precompiled statements used by the implementation. Each of these
  141451. ** statements is run and reset within a single virtual table API call.
  141452. */
  141453. sqlite3_stmt *aStmt[40];
  141454. sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
  141455. char *zReadExprlist;
  141456. char *zWriteExprlist;
  141457. int nNodeSize; /* Soft limit for node size */
  141458. u8 bFts4; /* True for FTS4, false for FTS3 */
  141459. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  141460. u8 bHasDocsize; /* True if %_docsize table exists */
  141461. u8 bDescIdx; /* True if doclists are in reverse order */
  141462. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  141463. int nPgsz; /* Page size for host database */
  141464. char *zSegmentsTbl; /* Name of %_segments table */
  141465. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  141466. /*
  141467. ** The following array of hash tables is used to buffer pending index
  141468. ** updates during transactions. All pending updates buffered at any one
  141469. ** time must share a common language-id (see the FTS4 langid= feature).
  141470. ** The current language id is stored in variable iPrevLangid.
  141471. **
  141472. ** A single FTS4 table may have multiple full-text indexes. For each index
  141473. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  141474. ** terms that appear in the document set. Each subsequent index in aIndex[]
  141475. ** is an index of prefixes of a specific length.
  141476. **
  141477. ** Variable nPendingData contains an estimate the memory consumed by the
  141478. ** pending data structures, including hash table overhead, but not including
  141479. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  141480. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  141481. ** recently inserted record.
  141482. */
  141483. int nIndex; /* Size of aIndex[] */
  141484. struct Fts3Index {
  141485. int nPrefix; /* Prefix length (0 for main terms index) */
  141486. Fts3Hash hPending; /* Pending terms table for this index */
  141487. } *aIndex;
  141488. int nMaxPendingData; /* Max pending data before flush to disk */
  141489. int nPendingData; /* Current bytes of pending data */
  141490. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  141491. int iPrevLangid; /* Langid of recently inserted document */
  141492. int bPrevDelete; /* True if last operation was a delete */
  141493. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  141494. /* State variables used for validating that the transaction control
  141495. ** methods of the virtual table are called at appropriate times. These
  141496. ** values do not contribute to FTS functionality; they are used for
  141497. ** verifying the operation of the SQLite core.
  141498. */
  141499. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  141500. int mxSavepoint; /* Largest valid xSavepoint integer */
  141501. #endif
  141502. #ifdef SQLITE_TEST
  141503. /* True to disable the incremental doclist optimization. This is controled
  141504. ** by special insert command 'test-no-incr-doclist'. */
  141505. int bNoIncrDoclist;
  141506. #endif
  141507. };
  141508. /*
  141509. ** When the core wants to read from the virtual table, it creates a
  141510. ** virtual table cursor (an instance of the following structure) using
  141511. ** the xOpen method. Cursors are destroyed using the xClose method.
  141512. */
  141513. struct Fts3Cursor {
  141514. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  141515. i16 eSearch; /* Search strategy (see below) */
  141516. u8 isEof; /* True if at End Of Results */
  141517. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  141518. u8 bSeekStmt; /* True if pStmt is a seek */
  141519. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  141520. Fts3Expr *pExpr; /* Parsed MATCH query string */
  141521. int iLangid; /* Language being queried for */
  141522. int nPhrase; /* Number of matchable phrases in query */
  141523. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  141524. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  141525. char *pNextId; /* Pointer into the body of aDoclist */
  141526. char *aDoclist; /* List of docids for full-text queries */
  141527. int nDoclist; /* Size of buffer at aDoclist */
  141528. u8 bDesc; /* True to sort in descending order */
  141529. int eEvalmode; /* An FTS3_EVAL_XX constant */
  141530. int nRowAvg; /* Average size of database rows, in pages */
  141531. sqlite3_int64 nDoc; /* Documents in table */
  141532. i64 iMinDocid; /* Minimum docid to return */
  141533. i64 iMaxDocid; /* Maximum docid to return */
  141534. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  141535. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  141536. };
  141537. #define FTS3_EVAL_FILTER 0
  141538. #define FTS3_EVAL_NEXT 1
  141539. #define FTS3_EVAL_MATCHINFO 2
  141540. /*
  141541. ** The Fts3Cursor.eSearch member is always set to one of the following.
  141542. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  141543. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  141544. ** of the column to be searched. For example, in
  141545. **
  141546. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  141547. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  141548. **
  141549. ** Because the LHS of the MATCH operator is 2nd column "b",
  141550. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  141551. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  141552. ** indicating that all columns should be searched,
  141553. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  141554. */
  141555. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  141556. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  141557. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  141558. /*
  141559. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  141560. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  141561. ** above. The upper 16-bits contain a combination of the following
  141562. ** bits, used to describe extra constraints on full-text searches.
  141563. */
  141564. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  141565. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  141566. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  141567. struct Fts3Doclist {
  141568. char *aAll; /* Array containing doclist (or NULL) */
  141569. int nAll; /* Size of a[] in bytes */
  141570. char *pNextDocid; /* Pointer to next docid */
  141571. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  141572. int bFreeList; /* True if pList should be sqlite3_free()d */
  141573. char *pList; /* Pointer to position list following iDocid */
  141574. int nList; /* Length of position list */
  141575. };
  141576. /*
  141577. ** A "phrase" is a sequence of one or more tokens that must match in
  141578. ** sequence. A single token is the base case and the most common case.
  141579. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  141580. ** nToken will be the number of tokens in the string.
  141581. */
  141582. struct Fts3PhraseToken {
  141583. char *z; /* Text of the token */
  141584. int n; /* Number of bytes in buffer z */
  141585. int isPrefix; /* True if token ends with a "*" character */
  141586. int bFirst; /* True if token must appear at position 0 */
  141587. /* Variables above this point are populated when the expression is
  141588. ** parsed (by code in fts3_expr.c). Below this point the variables are
  141589. ** used when evaluating the expression. */
  141590. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  141591. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  141592. };
  141593. struct Fts3Phrase {
  141594. /* Cache of doclist for this phrase. */
  141595. Fts3Doclist doclist;
  141596. int bIncr; /* True if doclist is loaded incrementally */
  141597. int iDoclistToken;
  141598. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  141599. ** OR condition. */
  141600. char *pOrPoslist;
  141601. i64 iOrDocid;
  141602. /* Variables below this point are populated by fts3_expr.c when parsing
  141603. ** a MATCH expression. Everything above is part of the evaluation phase.
  141604. */
  141605. int nToken; /* Number of tokens in the phrase */
  141606. int iColumn; /* Index of column this phrase must match */
  141607. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  141608. };
  141609. /*
  141610. ** A tree of these objects forms the RHS of a MATCH operator.
  141611. **
  141612. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  141613. ** points to a malloced buffer, size nDoclist bytes, containing the results
  141614. ** of this phrase query in FTS3 doclist format. As usual, the initial
  141615. ** "Length" field found in doclists stored on disk is omitted from this
  141616. ** buffer.
  141617. **
  141618. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  141619. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  141620. ** where nCol is the number of columns in the queried FTS table. The array
  141621. ** is populated as follows:
  141622. **
  141623. ** aMI[iCol*3 + 0] = Undefined
  141624. ** aMI[iCol*3 + 1] = Number of occurrences
  141625. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  141626. **
  141627. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  141628. ** when the expression node is.
  141629. */
  141630. struct Fts3Expr {
  141631. int eType; /* One of the FTSQUERY_XXX values defined below */
  141632. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  141633. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  141634. Fts3Expr *pLeft; /* Left operand */
  141635. Fts3Expr *pRight; /* Right operand */
  141636. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  141637. /* The following are used by the fts3_eval.c module. */
  141638. sqlite3_int64 iDocid; /* Current docid */
  141639. u8 bEof; /* True this expression is at EOF already */
  141640. u8 bStart; /* True if iDocid is valid */
  141641. u8 bDeferred; /* True if this expression is entirely deferred */
  141642. /* The following are used by the fts3_snippet.c module. */
  141643. int iPhrase; /* Index of this phrase in matchinfo() results */
  141644. u32 *aMI; /* See above */
  141645. };
  141646. /*
  141647. ** Candidate values for Fts3Query.eType. Note that the order of the first
  141648. ** four values is in order of precedence when parsing expressions. For
  141649. ** example, the following:
  141650. **
  141651. ** "a OR b AND c NOT d NEAR e"
  141652. **
  141653. ** is equivalent to:
  141654. **
  141655. ** "a OR (b AND (c NOT (d NEAR e)))"
  141656. */
  141657. #define FTSQUERY_NEAR 1
  141658. #define FTSQUERY_NOT 2
  141659. #define FTSQUERY_AND 3
  141660. #define FTSQUERY_OR 4
  141661. #define FTSQUERY_PHRASE 5
  141662. /* fts3_write.c */
  141663. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  141664. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  141665. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  141666. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  141667. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  141668. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  141669. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  141670. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  141671. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  141672. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  141673. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  141674. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  141675. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  141676. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  141677. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  141678. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  141679. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  141680. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  141681. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  141682. #else
  141683. # define sqlite3Fts3FreeDeferredTokens(x)
  141684. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  141685. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  141686. # define sqlite3Fts3FreeDeferredDoclists(x)
  141687. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  141688. #endif
  141689. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  141690. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  141691. /* Special values interpreted by sqlite3SegReaderCursor() */
  141692. #define FTS3_SEGCURSOR_PENDING -1
  141693. #define FTS3_SEGCURSOR_ALL -2
  141694. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  141695. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  141696. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  141697. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  141698. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  141699. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  141700. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  141701. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  141702. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  141703. #define FTS3_SEGMENT_PREFIX 0x00000008
  141704. #define FTS3_SEGMENT_SCAN 0x00000010
  141705. #define FTS3_SEGMENT_FIRST 0x00000020
  141706. /* Type passed as 4th argument to SegmentReaderIterate() */
  141707. struct Fts3SegFilter {
  141708. const char *zTerm;
  141709. int nTerm;
  141710. int iCol;
  141711. int flags;
  141712. };
  141713. struct Fts3MultiSegReader {
  141714. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  141715. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  141716. int nSegment; /* Size of apSegment array */
  141717. int nAdvance; /* How many seg-readers to advance */
  141718. Fts3SegFilter *pFilter; /* Pointer to filter object */
  141719. char *aBuffer; /* Buffer to merge doclists in */
  141720. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  141721. int iColFilter; /* If >=0, filter for this column */
  141722. int bRestart;
  141723. /* Used by fts3.c only. */
  141724. int nCost; /* Cost of running iterator */
  141725. int bLookup; /* True if a lookup of a single entry. */
  141726. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  141727. char *zTerm; /* Pointer to term buffer */
  141728. int nTerm; /* Size of zTerm in bytes */
  141729. char *aDoclist; /* Pointer to doclist buffer */
  141730. int nDoclist; /* Size of aDoclist[] in bytes */
  141731. };
  141732. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  141733. #define fts3GetVarint32(p, piVal) ( \
  141734. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  141735. )
  141736. /* fts3.c */
  141737. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  141738. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  141739. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  141740. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  141741. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  141742. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  141743. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  141744. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  141745. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  141746. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  141747. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  141748. /* fts3_tokenizer.c */
  141749. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  141750. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  141751. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  141752. sqlite3_tokenizer **, char **
  141753. );
  141754. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  141755. /* fts3_snippet.c */
  141756. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  141757. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  141758. const char *, const char *, int, int
  141759. );
  141760. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  141761. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  141762. /* fts3_expr.c */
  141763. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  141764. char **, int, int, int, const char *, int, Fts3Expr **, char **
  141765. );
  141766. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  141767. #ifdef SQLITE_TEST
  141768. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  141769. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  141770. #endif
  141771. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  141772. sqlite3_tokenizer_cursor **
  141773. );
  141774. /* fts3_aux.c */
  141775. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  141776. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  141777. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  141778. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  141779. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  141780. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  141781. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  141782. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  141783. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  141784. /* fts3_tokenize_vtab.c */
  141785. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  141786. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  141787. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  141788. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  141789. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  141790. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  141791. #endif
  141792. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  141793. #endif /* _FTSINT_H */
  141794. /************** End of fts3Int.h *********************************************/
  141795. /************** Continuing where we left off in fts3.c ***********************/
  141796. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  141797. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  141798. # define SQLITE_CORE 1
  141799. #endif
  141800. /* #include <assert.h> */
  141801. /* #include <stdlib.h> */
  141802. /* #include <stddef.h> */
  141803. /* #include <stdio.h> */
  141804. /* #include <string.h> */
  141805. /* #include <stdarg.h> */
  141806. /* #include "fts3.h" */
  141807. #ifndef SQLITE_CORE
  141808. /* # include "sqlite3ext.h" */
  141809. SQLITE_EXTENSION_INIT1
  141810. #endif
  141811. static int fts3EvalNext(Fts3Cursor *pCsr);
  141812. static int fts3EvalStart(Fts3Cursor *pCsr);
  141813. static int fts3TermSegReaderCursor(
  141814. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  141815. #ifndef SQLITE_AMALGAMATION
  141816. # if defined(SQLITE_DEBUG)
  141817. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  141818. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  141819. # endif
  141820. #endif
  141821. /*
  141822. ** Write a 64-bit variable-length integer to memory starting at p[0].
  141823. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  141824. ** The number of bytes written is returned.
  141825. */
  141826. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  141827. unsigned char *q = (unsigned char *) p;
  141828. sqlite_uint64 vu = v;
  141829. do{
  141830. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  141831. vu >>= 7;
  141832. }while( vu!=0 );
  141833. q[-1] &= 0x7f; /* turn off high bit in final byte */
  141834. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  141835. return (int) (q - (unsigned char *)p);
  141836. }
  141837. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  141838. v = (v & mask1) | ( (*ptr++) << shift ); \
  141839. if( (v & mask2)==0 ){ var = v; return ret; }
  141840. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  141841. v = (*ptr++); \
  141842. if( (v & mask2)==0 ){ var = v; return ret; }
  141843. /*
  141844. ** Read a 64-bit variable-length integer from memory starting at p[0].
  141845. ** Return the number of bytes read, or 0 on error.
  141846. ** The value is stored in *v.
  141847. */
  141848. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
  141849. const unsigned char *p = (const unsigned char*)pBuf;
  141850. const unsigned char *pStart = p;
  141851. u32 a;
  141852. u64 b;
  141853. int shift;
  141854. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  141855. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  141856. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  141857. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  141858. b = (a & 0x0FFFFFFF );
  141859. for(shift=28; shift<=63; shift+=7){
  141860. u64 c = *p++;
  141861. b += (c&0x7F) << shift;
  141862. if( (c & 0x80)==0 ) break;
  141863. }
  141864. *v = b;
  141865. return (int)(p - pStart);
  141866. }
  141867. /*
  141868. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
  141869. ** a non-negative 32-bit integer before it is returned.
  141870. */
  141871. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  141872. u32 a;
  141873. #ifndef fts3GetVarint32
  141874. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  141875. #else
  141876. a = (*p++);
  141877. assert( a & 0x80 );
  141878. #endif
  141879. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  141880. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  141881. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  141882. a = (a & 0x0FFFFFFF );
  141883. *pi = (int)(a | ((u32)(*p & 0x07) << 28));
  141884. assert( 0==(a & 0x80000000) );
  141885. assert( *pi>=0 );
  141886. return 5;
  141887. }
  141888. /*
  141889. ** Return the number of bytes required to encode v as a varint
  141890. */
  141891. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  141892. int i = 0;
  141893. do{
  141894. i++;
  141895. v >>= 7;
  141896. }while( v!=0 );
  141897. return i;
  141898. }
  141899. /*
  141900. ** Convert an SQL-style quoted string into a normal string by removing
  141901. ** the quote characters. The conversion is done in-place. If the
  141902. ** input does not begin with a quote character, then this routine
  141903. ** is a no-op.
  141904. **
  141905. ** Examples:
  141906. **
  141907. ** "abc" becomes abc
  141908. ** 'xyz' becomes xyz
  141909. ** [pqr] becomes pqr
  141910. ** `mno` becomes mno
  141911. **
  141912. */
  141913. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  141914. char quote; /* Quote character (if any ) */
  141915. quote = z[0];
  141916. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  141917. int iIn = 1; /* Index of next byte to read from input */
  141918. int iOut = 0; /* Index of next byte to write to output */
  141919. /* If the first byte was a '[', then the close-quote character is a ']' */
  141920. if( quote=='[' ) quote = ']';
  141921. while( z[iIn] ){
  141922. if( z[iIn]==quote ){
  141923. if( z[iIn+1]!=quote ) break;
  141924. z[iOut++] = quote;
  141925. iIn += 2;
  141926. }else{
  141927. z[iOut++] = z[iIn++];
  141928. }
  141929. }
  141930. z[iOut] = '\0';
  141931. }
  141932. }
  141933. /*
  141934. ** Read a single varint from the doclist at *pp and advance *pp to point
  141935. ** to the first byte past the end of the varint. Add the value of the varint
  141936. ** to *pVal.
  141937. */
  141938. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  141939. sqlite3_int64 iVal;
  141940. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  141941. *pVal += iVal;
  141942. }
  141943. /*
  141944. ** When this function is called, *pp points to the first byte following a
  141945. ** varint that is part of a doclist (or position-list, or any other list
  141946. ** of varints). This function moves *pp to point to the start of that varint,
  141947. ** and sets *pVal by the varint value.
  141948. **
  141949. ** Argument pStart points to the first byte of the doclist that the
  141950. ** varint is part of.
  141951. */
  141952. static void fts3GetReverseVarint(
  141953. char **pp,
  141954. char *pStart,
  141955. sqlite3_int64 *pVal
  141956. ){
  141957. sqlite3_int64 iVal;
  141958. char *p;
  141959. /* Pointer p now points at the first byte past the varint we are
  141960. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  141961. ** clear on character p[-1]. */
  141962. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  141963. p++;
  141964. *pp = p;
  141965. sqlite3Fts3GetVarint(p, &iVal);
  141966. *pVal = iVal;
  141967. }
  141968. /*
  141969. ** The xDisconnect() virtual table method.
  141970. */
  141971. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  141972. Fts3Table *p = (Fts3Table *)pVtab;
  141973. int i;
  141974. assert( p->nPendingData==0 );
  141975. assert( p->pSegments==0 );
  141976. /* Free any prepared statements held */
  141977. sqlite3_finalize(p->pSeekStmt);
  141978. for(i=0; i<SizeofArray(p->aStmt); i++){
  141979. sqlite3_finalize(p->aStmt[i]);
  141980. }
  141981. sqlite3_free(p->zSegmentsTbl);
  141982. sqlite3_free(p->zReadExprlist);
  141983. sqlite3_free(p->zWriteExprlist);
  141984. sqlite3_free(p->zContentTbl);
  141985. sqlite3_free(p->zLanguageid);
  141986. /* Invoke the tokenizer destructor to free the tokenizer. */
  141987. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  141988. sqlite3_free(p);
  141989. return SQLITE_OK;
  141990. }
  141991. /*
  141992. ** Write an error message into *pzErr
  141993. */
  141994. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  141995. va_list ap;
  141996. sqlite3_free(*pzErr);
  141997. va_start(ap, zFormat);
  141998. *pzErr = sqlite3_vmprintf(zFormat, ap);
  141999. va_end(ap);
  142000. }
  142001. /*
  142002. ** Construct one or more SQL statements from the format string given
  142003. ** and then evaluate those statements. The success code is written
  142004. ** into *pRc.
  142005. **
  142006. ** If *pRc is initially non-zero then this routine is a no-op.
  142007. */
  142008. static void fts3DbExec(
  142009. int *pRc, /* Success code */
  142010. sqlite3 *db, /* Database in which to run SQL */
  142011. const char *zFormat, /* Format string for SQL */
  142012. ... /* Arguments to the format string */
  142013. ){
  142014. va_list ap;
  142015. char *zSql;
  142016. if( *pRc ) return;
  142017. va_start(ap, zFormat);
  142018. zSql = sqlite3_vmprintf(zFormat, ap);
  142019. va_end(ap);
  142020. if( zSql==0 ){
  142021. *pRc = SQLITE_NOMEM;
  142022. }else{
  142023. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  142024. sqlite3_free(zSql);
  142025. }
  142026. }
  142027. /*
  142028. ** The xDestroy() virtual table method.
  142029. */
  142030. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  142031. Fts3Table *p = (Fts3Table *)pVtab;
  142032. int rc = SQLITE_OK; /* Return code */
  142033. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  142034. sqlite3 *db = p->db; /* Database handle */
  142035. /* Drop the shadow tables */
  142036. if( p->zContentTbl==0 ){
  142037. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  142038. }
  142039. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  142040. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  142041. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  142042. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  142043. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  142044. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  142045. ** Otherwise, return an SQLite error code.
  142046. */
  142047. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  142048. }
  142049. /*
  142050. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  142051. ** passed as the first argument. This is done as part of the xConnect()
  142052. ** and xCreate() methods.
  142053. **
  142054. ** If *pRc is non-zero when this function is called, it is a no-op.
  142055. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  142056. ** before returning.
  142057. */
  142058. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  142059. if( *pRc==SQLITE_OK ){
  142060. int i; /* Iterator variable */
  142061. int rc; /* Return code */
  142062. char *zSql; /* SQL statement passed to declare_vtab() */
  142063. char *zCols; /* List of user defined columns */
  142064. const char *zLanguageid;
  142065. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  142066. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  142067. /* Create a list of user columns for the virtual table */
  142068. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  142069. for(i=1; zCols && i<p->nColumn; i++){
  142070. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  142071. }
  142072. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  142073. zSql = sqlite3_mprintf(
  142074. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  142075. zCols, p->zName, zLanguageid
  142076. );
  142077. if( !zCols || !zSql ){
  142078. rc = SQLITE_NOMEM;
  142079. }else{
  142080. rc = sqlite3_declare_vtab(p->db, zSql);
  142081. }
  142082. sqlite3_free(zSql);
  142083. sqlite3_free(zCols);
  142084. *pRc = rc;
  142085. }
  142086. }
  142087. /*
  142088. ** Create the %_stat table if it does not already exist.
  142089. */
  142090. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  142091. fts3DbExec(pRc, p->db,
  142092. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  142093. "(id INTEGER PRIMARY KEY, value BLOB);",
  142094. p->zDb, p->zName
  142095. );
  142096. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  142097. }
  142098. /*
  142099. ** Create the backing store tables (%_content, %_segments and %_segdir)
  142100. ** required by the FTS3 table passed as the only argument. This is done
  142101. ** as part of the vtab xCreate() method.
  142102. **
  142103. ** If the p->bHasDocsize boolean is true (indicating that this is an
  142104. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  142105. ** %_stat tables required by FTS4.
  142106. */
  142107. static int fts3CreateTables(Fts3Table *p){
  142108. int rc = SQLITE_OK; /* Return code */
  142109. int i; /* Iterator variable */
  142110. sqlite3 *db = p->db; /* The database connection */
  142111. if( p->zContentTbl==0 ){
  142112. const char *zLanguageid = p->zLanguageid;
  142113. char *zContentCols; /* Columns of %_content table */
  142114. /* Create a list of user columns for the content table */
  142115. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  142116. for(i=0; zContentCols && i<p->nColumn; i++){
  142117. char *z = p->azColumn[i];
  142118. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  142119. }
  142120. if( zLanguageid && zContentCols ){
  142121. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  142122. }
  142123. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  142124. /* Create the content table */
  142125. fts3DbExec(&rc, db,
  142126. "CREATE TABLE %Q.'%q_content'(%s)",
  142127. p->zDb, p->zName, zContentCols
  142128. );
  142129. sqlite3_free(zContentCols);
  142130. }
  142131. /* Create other tables */
  142132. fts3DbExec(&rc, db,
  142133. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  142134. p->zDb, p->zName
  142135. );
  142136. fts3DbExec(&rc, db,
  142137. "CREATE TABLE %Q.'%q_segdir'("
  142138. "level INTEGER,"
  142139. "idx INTEGER,"
  142140. "start_block INTEGER,"
  142141. "leaves_end_block INTEGER,"
  142142. "end_block INTEGER,"
  142143. "root BLOB,"
  142144. "PRIMARY KEY(level, idx)"
  142145. ");",
  142146. p->zDb, p->zName
  142147. );
  142148. if( p->bHasDocsize ){
  142149. fts3DbExec(&rc, db,
  142150. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  142151. p->zDb, p->zName
  142152. );
  142153. }
  142154. assert( p->bHasStat==p->bFts4 );
  142155. if( p->bHasStat ){
  142156. sqlite3Fts3CreateStatTable(&rc, p);
  142157. }
  142158. return rc;
  142159. }
  142160. /*
  142161. ** Store the current database page-size in bytes in p->nPgsz.
  142162. **
  142163. ** If *pRc is non-zero when this function is called, it is a no-op.
  142164. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  142165. ** before returning.
  142166. */
  142167. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  142168. if( *pRc==SQLITE_OK ){
  142169. int rc; /* Return code */
  142170. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  142171. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  142172. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  142173. if( !zSql ){
  142174. rc = SQLITE_NOMEM;
  142175. }else{
  142176. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  142177. if( rc==SQLITE_OK ){
  142178. sqlite3_step(pStmt);
  142179. p->nPgsz = sqlite3_column_int(pStmt, 0);
  142180. rc = sqlite3_finalize(pStmt);
  142181. }else if( rc==SQLITE_AUTH ){
  142182. p->nPgsz = 1024;
  142183. rc = SQLITE_OK;
  142184. }
  142185. }
  142186. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  142187. sqlite3_free(zSql);
  142188. *pRc = rc;
  142189. }
  142190. }
  142191. /*
  142192. ** "Special" FTS4 arguments are column specifications of the following form:
  142193. **
  142194. ** <key> = <value>
  142195. **
  142196. ** There may not be whitespace surrounding the "=" character. The <value>
  142197. ** term may be quoted, but the <key> may not.
  142198. */
  142199. static int fts3IsSpecialColumn(
  142200. const char *z,
  142201. int *pnKey,
  142202. char **pzValue
  142203. ){
  142204. char *zValue;
  142205. const char *zCsr = z;
  142206. while( *zCsr!='=' ){
  142207. if( *zCsr=='\0' ) return 0;
  142208. zCsr++;
  142209. }
  142210. *pnKey = (int)(zCsr-z);
  142211. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  142212. if( zValue ){
  142213. sqlite3Fts3Dequote(zValue);
  142214. }
  142215. *pzValue = zValue;
  142216. return 1;
  142217. }
  142218. /*
  142219. ** Append the output of a printf() style formatting to an existing string.
  142220. */
  142221. static void fts3Appendf(
  142222. int *pRc, /* IN/OUT: Error code */
  142223. char **pz, /* IN/OUT: Pointer to string buffer */
  142224. const char *zFormat, /* Printf format string to append */
  142225. ... /* Arguments for printf format string */
  142226. ){
  142227. if( *pRc==SQLITE_OK ){
  142228. va_list ap;
  142229. char *z;
  142230. va_start(ap, zFormat);
  142231. z = sqlite3_vmprintf(zFormat, ap);
  142232. va_end(ap);
  142233. if( z && *pz ){
  142234. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  142235. sqlite3_free(z);
  142236. z = z2;
  142237. }
  142238. if( z==0 ) *pRc = SQLITE_NOMEM;
  142239. sqlite3_free(*pz);
  142240. *pz = z;
  142241. }
  142242. }
  142243. /*
  142244. ** Return a copy of input string zInput enclosed in double-quotes (") and
  142245. ** with all double quote characters escaped. For example:
  142246. **
  142247. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  142248. **
  142249. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  142250. ** is the callers responsibility to call sqlite3_free() to release this
  142251. ** memory.
  142252. */
  142253. static char *fts3QuoteId(char const *zInput){
  142254. int nRet;
  142255. char *zRet;
  142256. nRet = 2 + (int)strlen(zInput)*2 + 1;
  142257. zRet = sqlite3_malloc(nRet);
  142258. if( zRet ){
  142259. int i;
  142260. char *z = zRet;
  142261. *(z++) = '"';
  142262. for(i=0; zInput[i]; i++){
  142263. if( zInput[i]=='"' ) *(z++) = '"';
  142264. *(z++) = zInput[i];
  142265. }
  142266. *(z++) = '"';
  142267. *(z++) = '\0';
  142268. }
  142269. return zRet;
  142270. }
  142271. /*
  142272. ** Return a list of comma separated SQL expressions and a FROM clause that
  142273. ** could be used in a SELECT statement such as the following:
  142274. **
  142275. ** SELECT <list of expressions> FROM %_content AS x ...
  142276. **
  142277. ** to return the docid, followed by each column of text data in order
  142278. ** from left to write. If parameter zFunc is not NULL, then instead of
  142279. ** being returned directly each column of text data is passed to an SQL
  142280. ** function named zFunc first. For example, if zFunc is "unzip" and the
  142281. ** table has the three user-defined columns "a", "b", and "c", the following
  142282. ** string is returned:
  142283. **
  142284. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  142285. **
  142286. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  142287. ** is the responsibility of the caller to eventually free it.
  142288. **
  142289. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  142290. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  142291. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  142292. ** no error occurs, *pRc is left unmodified.
  142293. */
  142294. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  142295. char *zRet = 0;
  142296. char *zFree = 0;
  142297. char *zFunction;
  142298. int i;
  142299. if( p->zContentTbl==0 ){
  142300. if( !zFunc ){
  142301. zFunction = "";
  142302. }else{
  142303. zFree = zFunction = fts3QuoteId(zFunc);
  142304. }
  142305. fts3Appendf(pRc, &zRet, "docid");
  142306. for(i=0; i<p->nColumn; i++){
  142307. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  142308. }
  142309. if( p->zLanguageid ){
  142310. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  142311. }
  142312. sqlite3_free(zFree);
  142313. }else{
  142314. fts3Appendf(pRc, &zRet, "rowid");
  142315. for(i=0; i<p->nColumn; i++){
  142316. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  142317. }
  142318. if( p->zLanguageid ){
  142319. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  142320. }
  142321. }
  142322. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  142323. p->zDb,
  142324. (p->zContentTbl ? p->zContentTbl : p->zName),
  142325. (p->zContentTbl ? "" : "_content")
  142326. );
  142327. return zRet;
  142328. }
  142329. /*
  142330. ** Return a list of N comma separated question marks, where N is the number
  142331. ** of columns in the %_content table (one for the docid plus one for each
  142332. ** user-defined text column).
  142333. **
  142334. ** If argument zFunc is not NULL, then all but the first question mark
  142335. ** is preceded by zFunc and an open bracket, and followed by a closed
  142336. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  142337. ** user-defined text columns, the following string is returned:
  142338. **
  142339. ** "?, zip(?), zip(?), zip(?)"
  142340. **
  142341. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  142342. ** is the responsibility of the caller to eventually free it.
  142343. **
  142344. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  142345. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  142346. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  142347. ** no error occurs, *pRc is left unmodified.
  142348. */
  142349. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  142350. char *zRet = 0;
  142351. char *zFree = 0;
  142352. char *zFunction;
  142353. int i;
  142354. if( !zFunc ){
  142355. zFunction = "";
  142356. }else{
  142357. zFree = zFunction = fts3QuoteId(zFunc);
  142358. }
  142359. fts3Appendf(pRc, &zRet, "?");
  142360. for(i=0; i<p->nColumn; i++){
  142361. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  142362. }
  142363. if( p->zLanguageid ){
  142364. fts3Appendf(pRc, &zRet, ", ?");
  142365. }
  142366. sqlite3_free(zFree);
  142367. return zRet;
  142368. }
  142369. /*
  142370. ** This function interprets the string at (*pp) as a non-negative integer
  142371. ** value. It reads the integer and sets *pnOut to the value read, then
  142372. ** sets *pp to point to the byte immediately following the last byte of
  142373. ** the integer value.
  142374. **
  142375. ** Only decimal digits ('0'..'9') may be part of an integer value.
  142376. **
  142377. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  142378. ** the output value undefined. Otherwise SQLITE_OK is returned.
  142379. **
  142380. ** This function is used when parsing the "prefix=" FTS4 parameter.
  142381. */
  142382. static int fts3GobbleInt(const char **pp, int *pnOut){
  142383. const int MAX_NPREFIX = 10000000;
  142384. const char *p; /* Iterator pointer */
  142385. int nInt = 0; /* Output value */
  142386. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  142387. nInt = nInt * 10 + (p[0] - '0');
  142388. if( nInt>MAX_NPREFIX ){
  142389. nInt = 0;
  142390. break;
  142391. }
  142392. }
  142393. if( p==*pp ) return SQLITE_ERROR;
  142394. *pnOut = nInt;
  142395. *pp = p;
  142396. return SQLITE_OK;
  142397. }
  142398. /*
  142399. ** This function is called to allocate an array of Fts3Index structures
  142400. ** representing the indexes maintained by the current FTS table. FTS tables
  142401. ** always maintain the main "terms" index, but may also maintain one or
  142402. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  142403. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  142404. **
  142405. ** Argument zParam is passed the value of the "prefix=" option if one was
  142406. ** specified, or NULL otherwise.
  142407. **
  142408. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  142409. ** the allocated array. *pnIndex is set to the number of elements in the
  142410. ** array. If an error does occur, an SQLite error code is returned.
  142411. **
  142412. ** Regardless of whether or not an error is returned, it is the responsibility
  142413. ** of the caller to call sqlite3_free() on the output array to free it.
  142414. */
  142415. static int fts3PrefixParameter(
  142416. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  142417. int *pnIndex, /* OUT: size of *apIndex[] array */
  142418. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  142419. ){
  142420. struct Fts3Index *aIndex; /* Allocated array */
  142421. int nIndex = 1; /* Number of entries in array */
  142422. if( zParam && zParam[0] ){
  142423. const char *p;
  142424. nIndex++;
  142425. for(p=zParam; *p; p++){
  142426. if( *p==',' ) nIndex++;
  142427. }
  142428. }
  142429. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  142430. *apIndex = aIndex;
  142431. if( !aIndex ){
  142432. return SQLITE_NOMEM;
  142433. }
  142434. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  142435. if( zParam ){
  142436. const char *p = zParam;
  142437. int i;
  142438. for(i=1; i<nIndex; i++){
  142439. int nPrefix = 0;
  142440. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  142441. assert( nPrefix>=0 );
  142442. if( nPrefix==0 ){
  142443. nIndex--;
  142444. i--;
  142445. }else{
  142446. aIndex[i].nPrefix = nPrefix;
  142447. }
  142448. p++;
  142449. }
  142450. }
  142451. *pnIndex = nIndex;
  142452. return SQLITE_OK;
  142453. }
  142454. /*
  142455. ** This function is called when initializing an FTS4 table that uses the
  142456. ** content=xxx option. It determines the number of and names of the columns
  142457. ** of the new FTS4 table.
  142458. **
  142459. ** The third argument passed to this function is the value passed to the
  142460. ** config=xxx option (i.e. "xxx"). This function queries the database for
  142461. ** a table of that name. If found, the output variables are populated
  142462. ** as follows:
  142463. **
  142464. ** *pnCol: Set to the number of columns table xxx has,
  142465. **
  142466. ** *pnStr: Set to the total amount of space required to store a copy
  142467. ** of each columns name, including the nul-terminator.
  142468. **
  142469. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  142470. ** the name of the corresponding column in table xxx. The array
  142471. ** and its contents are allocated using a single allocation. It
  142472. ** is the responsibility of the caller to free this allocation
  142473. ** by eventually passing the *pazCol value to sqlite3_free().
  142474. **
  142475. ** If the table cannot be found, an error code is returned and the output
  142476. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  142477. ** returned (and the output variables are undefined).
  142478. */
  142479. static int fts3ContentColumns(
  142480. sqlite3 *db, /* Database handle */
  142481. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  142482. const char *zTbl, /* Name of content table */
  142483. const char ***pazCol, /* OUT: Malloc'd array of column names */
  142484. int *pnCol, /* OUT: Size of array *pazCol */
  142485. int *pnStr, /* OUT: Bytes of string content */
  142486. char **pzErr /* OUT: error message */
  142487. ){
  142488. int rc = SQLITE_OK; /* Return code */
  142489. char *zSql; /* "SELECT *" statement on zTbl */
  142490. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  142491. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  142492. if( !zSql ){
  142493. rc = SQLITE_NOMEM;
  142494. }else{
  142495. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  142496. if( rc!=SQLITE_OK ){
  142497. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  142498. }
  142499. }
  142500. sqlite3_free(zSql);
  142501. if( rc==SQLITE_OK ){
  142502. const char **azCol; /* Output array */
  142503. int nStr = 0; /* Size of all column names (incl. 0x00) */
  142504. int nCol; /* Number of table columns */
  142505. int i; /* Used to iterate through columns */
  142506. /* Loop through the returned columns. Set nStr to the number of bytes of
  142507. ** space required to store a copy of each column name, including the
  142508. ** nul-terminator byte. */
  142509. nCol = sqlite3_column_count(pStmt);
  142510. for(i=0; i<nCol; i++){
  142511. const char *zCol = sqlite3_column_name(pStmt, i);
  142512. nStr += (int)strlen(zCol) + 1;
  142513. }
  142514. /* Allocate and populate the array to return. */
  142515. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  142516. if( azCol==0 ){
  142517. rc = SQLITE_NOMEM;
  142518. }else{
  142519. char *p = (char *)&azCol[nCol];
  142520. for(i=0; i<nCol; i++){
  142521. const char *zCol = sqlite3_column_name(pStmt, i);
  142522. int n = (int)strlen(zCol)+1;
  142523. memcpy(p, zCol, n);
  142524. azCol[i] = p;
  142525. p += n;
  142526. }
  142527. }
  142528. sqlite3_finalize(pStmt);
  142529. /* Set the output variables. */
  142530. *pnCol = nCol;
  142531. *pnStr = nStr;
  142532. *pazCol = azCol;
  142533. }
  142534. return rc;
  142535. }
  142536. /*
  142537. ** This function is the implementation of both the xConnect and xCreate
  142538. ** methods of the FTS3 virtual table.
  142539. **
  142540. ** The argv[] array contains the following:
  142541. **
  142542. ** argv[0] -> module name ("fts3" or "fts4")
  142543. ** argv[1] -> database name
  142544. ** argv[2] -> table name
  142545. ** argv[...] -> "column name" and other module argument fields.
  142546. */
  142547. static int fts3InitVtab(
  142548. int isCreate, /* True for xCreate, false for xConnect */
  142549. sqlite3 *db, /* The SQLite database connection */
  142550. void *pAux, /* Hash table containing tokenizers */
  142551. int argc, /* Number of elements in argv array */
  142552. const char * const *argv, /* xCreate/xConnect argument array */
  142553. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  142554. char **pzErr /* Write any error message here */
  142555. ){
  142556. Fts3Hash *pHash = (Fts3Hash *)pAux;
  142557. Fts3Table *p = 0; /* Pointer to allocated vtab */
  142558. int rc = SQLITE_OK; /* Return code */
  142559. int i; /* Iterator variable */
  142560. int nByte; /* Size of allocation used for *p */
  142561. int iCol; /* Column index */
  142562. int nString = 0; /* Bytes required to hold all column names */
  142563. int nCol = 0; /* Number of columns in the FTS table */
  142564. char *zCsr; /* Space for holding column names */
  142565. int nDb; /* Bytes required to hold database name */
  142566. int nName; /* Bytes required to hold table name */
  142567. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  142568. const char **aCol; /* Array of column names */
  142569. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  142570. int nIndex = 0; /* Size of aIndex[] array */
  142571. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  142572. /* The results of parsing supported FTS4 key=value options: */
  142573. int bNoDocsize = 0; /* True to omit %_docsize table */
  142574. int bDescIdx = 0; /* True to store descending indexes */
  142575. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  142576. char *zCompress = 0; /* compress=? parameter (or NULL) */
  142577. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  142578. char *zContent = 0; /* content=? parameter (or NULL) */
  142579. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  142580. char **azNotindexed = 0; /* The set of notindexed= columns */
  142581. int nNotindexed = 0; /* Size of azNotindexed[] array */
  142582. assert( strlen(argv[0])==4 );
  142583. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  142584. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  142585. );
  142586. nDb = (int)strlen(argv[1]) + 1;
  142587. nName = (int)strlen(argv[2]) + 1;
  142588. nByte = sizeof(const char *) * (argc-2);
  142589. aCol = (const char **)sqlite3_malloc(nByte);
  142590. if( aCol ){
  142591. memset((void*)aCol, 0, nByte);
  142592. azNotindexed = (char **)sqlite3_malloc(nByte);
  142593. }
  142594. if( azNotindexed ){
  142595. memset(azNotindexed, 0, nByte);
  142596. }
  142597. if( !aCol || !azNotindexed ){
  142598. rc = SQLITE_NOMEM;
  142599. goto fts3_init_out;
  142600. }
  142601. /* Loop through all of the arguments passed by the user to the FTS3/4
  142602. ** module (i.e. all the column names and special arguments). This loop
  142603. ** does the following:
  142604. **
  142605. ** + Figures out the number of columns the FTSX table will have, and
  142606. ** the number of bytes of space that must be allocated to store copies
  142607. ** of the column names.
  142608. **
  142609. ** + If there is a tokenizer specification included in the arguments,
  142610. ** initializes the tokenizer pTokenizer.
  142611. */
  142612. for(i=3; rc==SQLITE_OK && i<argc; i++){
  142613. char const *z = argv[i];
  142614. int nKey;
  142615. char *zVal;
  142616. /* Check if this is a tokenizer specification */
  142617. if( !pTokenizer
  142618. && strlen(z)>8
  142619. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  142620. && 0==sqlite3Fts3IsIdChar(z[8])
  142621. ){
  142622. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  142623. }
  142624. /* Check if it is an FTS4 special argument. */
  142625. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  142626. struct Fts4Option {
  142627. const char *zOpt;
  142628. int nOpt;
  142629. } aFts4Opt[] = {
  142630. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  142631. { "prefix", 6 }, /* 1 -> PREFIX */
  142632. { "compress", 8 }, /* 2 -> COMPRESS */
  142633. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  142634. { "order", 5 }, /* 4 -> ORDER */
  142635. { "content", 7 }, /* 5 -> CONTENT */
  142636. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  142637. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  142638. };
  142639. int iOpt;
  142640. if( !zVal ){
  142641. rc = SQLITE_NOMEM;
  142642. }else{
  142643. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  142644. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  142645. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  142646. break;
  142647. }
  142648. }
  142649. switch( iOpt ){
  142650. case 0: /* MATCHINFO */
  142651. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  142652. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  142653. rc = SQLITE_ERROR;
  142654. }
  142655. bNoDocsize = 1;
  142656. break;
  142657. case 1: /* PREFIX */
  142658. sqlite3_free(zPrefix);
  142659. zPrefix = zVal;
  142660. zVal = 0;
  142661. break;
  142662. case 2: /* COMPRESS */
  142663. sqlite3_free(zCompress);
  142664. zCompress = zVal;
  142665. zVal = 0;
  142666. break;
  142667. case 3: /* UNCOMPRESS */
  142668. sqlite3_free(zUncompress);
  142669. zUncompress = zVal;
  142670. zVal = 0;
  142671. break;
  142672. case 4: /* ORDER */
  142673. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  142674. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  142675. ){
  142676. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  142677. rc = SQLITE_ERROR;
  142678. }
  142679. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  142680. break;
  142681. case 5: /* CONTENT */
  142682. sqlite3_free(zContent);
  142683. zContent = zVal;
  142684. zVal = 0;
  142685. break;
  142686. case 6: /* LANGUAGEID */
  142687. assert( iOpt==6 );
  142688. sqlite3_free(zLanguageid);
  142689. zLanguageid = zVal;
  142690. zVal = 0;
  142691. break;
  142692. case 7: /* NOTINDEXED */
  142693. azNotindexed[nNotindexed++] = zVal;
  142694. zVal = 0;
  142695. break;
  142696. default:
  142697. assert( iOpt==SizeofArray(aFts4Opt) );
  142698. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  142699. rc = SQLITE_ERROR;
  142700. break;
  142701. }
  142702. sqlite3_free(zVal);
  142703. }
  142704. }
  142705. /* Otherwise, the argument is a column name. */
  142706. else {
  142707. nString += (int)(strlen(z) + 1);
  142708. aCol[nCol++] = z;
  142709. }
  142710. }
  142711. /* If a content=xxx option was specified, the following:
  142712. **
  142713. ** 1. Ignore any compress= and uncompress= options.
  142714. **
  142715. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  142716. ** TABLE statement, use all columns from the content table.
  142717. */
  142718. if( rc==SQLITE_OK && zContent ){
  142719. sqlite3_free(zCompress);
  142720. sqlite3_free(zUncompress);
  142721. zCompress = 0;
  142722. zUncompress = 0;
  142723. if( nCol==0 ){
  142724. sqlite3_free((void*)aCol);
  142725. aCol = 0;
  142726. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  142727. /* If a languageid= option was specified, remove the language id
  142728. ** column from the aCol[] array. */
  142729. if( rc==SQLITE_OK && zLanguageid ){
  142730. int j;
  142731. for(j=0; j<nCol; j++){
  142732. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  142733. int k;
  142734. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  142735. nCol--;
  142736. break;
  142737. }
  142738. }
  142739. }
  142740. }
  142741. }
  142742. if( rc!=SQLITE_OK ) goto fts3_init_out;
  142743. if( nCol==0 ){
  142744. assert( nString==0 );
  142745. aCol[0] = "content";
  142746. nString = 8;
  142747. nCol = 1;
  142748. }
  142749. if( pTokenizer==0 ){
  142750. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  142751. if( rc!=SQLITE_OK ) goto fts3_init_out;
  142752. }
  142753. assert( pTokenizer );
  142754. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  142755. if( rc==SQLITE_ERROR ){
  142756. assert( zPrefix );
  142757. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  142758. }
  142759. if( rc!=SQLITE_OK ) goto fts3_init_out;
  142760. /* Allocate and populate the Fts3Table structure. */
  142761. nByte = sizeof(Fts3Table) + /* Fts3Table */
  142762. nCol * sizeof(char *) + /* azColumn */
  142763. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  142764. nCol * sizeof(u8) + /* abNotindexed */
  142765. nName + /* zName */
  142766. nDb + /* zDb */
  142767. nString; /* Space for azColumn strings */
  142768. p = (Fts3Table*)sqlite3_malloc(nByte);
  142769. if( p==0 ){
  142770. rc = SQLITE_NOMEM;
  142771. goto fts3_init_out;
  142772. }
  142773. memset(p, 0, nByte);
  142774. p->db = db;
  142775. p->nColumn = nCol;
  142776. p->nPendingData = 0;
  142777. p->azColumn = (char **)&p[1];
  142778. p->pTokenizer = pTokenizer;
  142779. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  142780. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  142781. p->bHasStat = (u8)isFts4;
  142782. p->bFts4 = (u8)isFts4;
  142783. p->bDescIdx = (u8)bDescIdx;
  142784. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  142785. p->zContentTbl = zContent;
  142786. p->zLanguageid = zLanguageid;
  142787. zContent = 0;
  142788. zLanguageid = 0;
  142789. TESTONLY( p->inTransaction = -1 );
  142790. TESTONLY( p->mxSavepoint = -1 );
  142791. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  142792. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  142793. p->nIndex = nIndex;
  142794. for(i=0; i<nIndex; i++){
  142795. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  142796. }
  142797. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  142798. /* Fill in the zName and zDb fields of the vtab structure. */
  142799. zCsr = (char *)&p->abNotindexed[nCol];
  142800. p->zName = zCsr;
  142801. memcpy(zCsr, argv[2], nName);
  142802. zCsr += nName;
  142803. p->zDb = zCsr;
  142804. memcpy(zCsr, argv[1], nDb);
  142805. zCsr += nDb;
  142806. /* Fill in the azColumn array */
  142807. for(iCol=0; iCol<nCol; iCol++){
  142808. char *z;
  142809. int n = 0;
  142810. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  142811. if( n>0 ){
  142812. memcpy(zCsr, z, n);
  142813. }
  142814. zCsr[n] = '\0';
  142815. sqlite3Fts3Dequote(zCsr);
  142816. p->azColumn[iCol] = zCsr;
  142817. zCsr += n+1;
  142818. assert( zCsr <= &((char *)p)[nByte] );
  142819. }
  142820. /* Fill in the abNotindexed array */
  142821. for(iCol=0; iCol<nCol; iCol++){
  142822. int n = (int)strlen(p->azColumn[iCol]);
  142823. for(i=0; i<nNotindexed; i++){
  142824. char *zNot = azNotindexed[i];
  142825. if( zNot && n==(int)strlen(zNot)
  142826. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  142827. ){
  142828. p->abNotindexed[iCol] = 1;
  142829. sqlite3_free(zNot);
  142830. azNotindexed[i] = 0;
  142831. }
  142832. }
  142833. }
  142834. for(i=0; i<nNotindexed; i++){
  142835. if( azNotindexed[i] ){
  142836. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  142837. rc = SQLITE_ERROR;
  142838. }
  142839. }
  142840. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  142841. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  142842. rc = SQLITE_ERROR;
  142843. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  142844. }
  142845. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  142846. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  142847. if( rc!=SQLITE_OK ) goto fts3_init_out;
  142848. /* If this is an xCreate call, create the underlying tables in the
  142849. ** database. TODO: For xConnect(), it could verify that said tables exist.
  142850. */
  142851. if( isCreate ){
  142852. rc = fts3CreateTables(p);
  142853. }
  142854. /* Check to see if a legacy fts3 table has been "upgraded" by the
  142855. ** addition of a %_stat table so that it can use incremental merge.
  142856. */
  142857. if( !isFts4 && !isCreate ){
  142858. p->bHasStat = 2;
  142859. }
  142860. /* Figure out the page-size for the database. This is required in order to
  142861. ** estimate the cost of loading large doclists from the database. */
  142862. fts3DatabasePageSize(&rc, p);
  142863. p->nNodeSize = p->nPgsz-35;
  142864. /* Declare the table schema to SQLite. */
  142865. fts3DeclareVtab(&rc, p);
  142866. fts3_init_out:
  142867. sqlite3_free(zPrefix);
  142868. sqlite3_free(aIndex);
  142869. sqlite3_free(zCompress);
  142870. sqlite3_free(zUncompress);
  142871. sqlite3_free(zContent);
  142872. sqlite3_free(zLanguageid);
  142873. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  142874. sqlite3_free((void *)aCol);
  142875. sqlite3_free((void *)azNotindexed);
  142876. if( rc!=SQLITE_OK ){
  142877. if( p ){
  142878. fts3DisconnectMethod((sqlite3_vtab *)p);
  142879. }else if( pTokenizer ){
  142880. pTokenizer->pModule->xDestroy(pTokenizer);
  142881. }
  142882. }else{
  142883. assert( p->pSegments==0 );
  142884. *ppVTab = &p->base;
  142885. }
  142886. return rc;
  142887. }
  142888. /*
  142889. ** The xConnect() and xCreate() methods for the virtual table. All the
  142890. ** work is done in function fts3InitVtab().
  142891. */
  142892. static int fts3ConnectMethod(
  142893. sqlite3 *db, /* Database connection */
  142894. void *pAux, /* Pointer to tokenizer hash table */
  142895. int argc, /* Number of elements in argv array */
  142896. const char * const *argv, /* xCreate/xConnect argument array */
  142897. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  142898. char **pzErr /* OUT: sqlite3_malloc'd error message */
  142899. ){
  142900. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  142901. }
  142902. static int fts3CreateMethod(
  142903. sqlite3 *db, /* Database connection */
  142904. void *pAux, /* Pointer to tokenizer hash table */
  142905. int argc, /* Number of elements in argv array */
  142906. const char * const *argv, /* xCreate/xConnect argument array */
  142907. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  142908. char **pzErr /* OUT: sqlite3_malloc'd error message */
  142909. ){
  142910. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  142911. }
  142912. /*
  142913. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  142914. ** extension is currently being used by a version of SQLite too old to
  142915. ** support estimatedRows. In that case this function is a no-op.
  142916. */
  142917. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  142918. #if SQLITE_VERSION_NUMBER>=3008002
  142919. if( sqlite3_libversion_number()>=3008002 ){
  142920. pIdxInfo->estimatedRows = nRow;
  142921. }
  142922. #endif
  142923. }
  142924. /*
  142925. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  142926. ** extension is currently being used by a version of SQLite too old to
  142927. ** support index-info flags. In that case this function is a no-op.
  142928. */
  142929. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  142930. #if SQLITE_VERSION_NUMBER>=3008012
  142931. if( sqlite3_libversion_number()>=3008012 ){
  142932. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  142933. }
  142934. #endif
  142935. }
  142936. /*
  142937. ** Implementation of the xBestIndex method for FTS3 tables. There
  142938. ** are three possible strategies, in order of preference:
  142939. **
  142940. ** 1. Direct lookup by rowid or docid.
  142941. ** 2. Full-text search using a MATCH operator on a non-docid column.
  142942. ** 3. Linear scan of %_content table.
  142943. */
  142944. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  142945. Fts3Table *p = (Fts3Table *)pVTab;
  142946. int i; /* Iterator variable */
  142947. int iCons = -1; /* Index of constraint to use */
  142948. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  142949. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  142950. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  142951. int iIdx;
  142952. /* By default use a full table scan. This is an expensive option,
  142953. ** so search through the constraints to see if a more efficient
  142954. ** strategy is possible.
  142955. */
  142956. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  142957. pInfo->estimatedCost = 5000000;
  142958. for(i=0; i<pInfo->nConstraint; i++){
  142959. int bDocid; /* True if this constraint is on docid */
  142960. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  142961. if( pCons->usable==0 ){
  142962. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  142963. /* There exists an unusable MATCH constraint. This means that if
  142964. ** the planner does elect to use the results of this call as part
  142965. ** of the overall query plan the user will see an "unable to use
  142966. ** function MATCH in the requested context" error. To discourage
  142967. ** this, return a very high cost here. */
  142968. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  142969. pInfo->estimatedCost = 1e50;
  142970. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  142971. return SQLITE_OK;
  142972. }
  142973. continue;
  142974. }
  142975. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  142976. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  142977. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  142978. pInfo->idxNum = FTS3_DOCID_SEARCH;
  142979. pInfo->estimatedCost = 1.0;
  142980. iCons = i;
  142981. }
  142982. /* A MATCH constraint. Use a full-text search.
  142983. **
  142984. ** If there is more than one MATCH constraint available, use the first
  142985. ** one encountered. If there is both a MATCH constraint and a direct
  142986. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  142987. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  142988. ** it would lead to an "unable to use function MATCH in the requested
  142989. ** context" error.
  142990. */
  142991. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  142992. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  142993. ){
  142994. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  142995. pInfo->estimatedCost = 2.0;
  142996. iCons = i;
  142997. }
  142998. /* Equality constraint on the langid column */
  142999. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  143000. && pCons->iColumn==p->nColumn + 2
  143001. ){
  143002. iLangidCons = i;
  143003. }
  143004. if( bDocid ){
  143005. switch( pCons->op ){
  143006. case SQLITE_INDEX_CONSTRAINT_GE:
  143007. case SQLITE_INDEX_CONSTRAINT_GT:
  143008. iDocidGe = i;
  143009. break;
  143010. case SQLITE_INDEX_CONSTRAINT_LE:
  143011. case SQLITE_INDEX_CONSTRAINT_LT:
  143012. iDocidLe = i;
  143013. break;
  143014. }
  143015. }
  143016. }
  143017. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  143018. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  143019. iIdx = 1;
  143020. if( iCons>=0 ){
  143021. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  143022. pInfo->aConstraintUsage[iCons].omit = 1;
  143023. }
  143024. if( iLangidCons>=0 ){
  143025. pInfo->idxNum |= FTS3_HAVE_LANGID;
  143026. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  143027. }
  143028. if( iDocidGe>=0 ){
  143029. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  143030. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  143031. }
  143032. if( iDocidLe>=0 ){
  143033. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  143034. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  143035. }
  143036. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  143037. ** docid) order. Both ascending and descending are possible.
  143038. */
  143039. if( pInfo->nOrderBy==1 ){
  143040. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  143041. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  143042. if( pOrder->desc ){
  143043. pInfo->idxStr = "DESC";
  143044. }else{
  143045. pInfo->idxStr = "ASC";
  143046. }
  143047. pInfo->orderByConsumed = 1;
  143048. }
  143049. }
  143050. assert( p->pSegments==0 );
  143051. return SQLITE_OK;
  143052. }
  143053. /*
  143054. ** Implementation of xOpen method.
  143055. */
  143056. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  143057. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  143058. UNUSED_PARAMETER(pVTab);
  143059. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  143060. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  143061. ** if the allocation fails, return SQLITE_NOMEM.
  143062. */
  143063. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  143064. if( !pCsr ){
  143065. return SQLITE_NOMEM;
  143066. }
  143067. memset(pCsr, 0, sizeof(Fts3Cursor));
  143068. return SQLITE_OK;
  143069. }
  143070. /*
  143071. ** Finalize the statement handle at pCsr->pStmt.
  143072. **
  143073. ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
  143074. ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
  143075. ** pointer there instead of finalizing it.
  143076. */
  143077. static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
  143078. if( pCsr->bSeekStmt ){
  143079. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  143080. if( p->pSeekStmt==0 ){
  143081. p->pSeekStmt = pCsr->pStmt;
  143082. sqlite3_reset(pCsr->pStmt);
  143083. pCsr->pStmt = 0;
  143084. }
  143085. pCsr->bSeekStmt = 0;
  143086. }
  143087. sqlite3_finalize(pCsr->pStmt);
  143088. }
  143089. /*
  143090. ** Free all resources currently held by the cursor passed as the only
  143091. ** argument.
  143092. */
  143093. static void fts3ClearCursor(Fts3Cursor *pCsr){
  143094. fts3CursorFinalizeStmt(pCsr);
  143095. sqlite3Fts3FreeDeferredTokens(pCsr);
  143096. sqlite3_free(pCsr->aDoclist);
  143097. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  143098. sqlite3Fts3ExprFree(pCsr->pExpr);
  143099. memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  143100. }
  143101. /*
  143102. ** Close the cursor. For additional information see the documentation
  143103. ** on the xClose method of the virtual table interface.
  143104. */
  143105. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  143106. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  143107. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  143108. fts3ClearCursor(pCsr);
  143109. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  143110. sqlite3_free(pCsr);
  143111. return SQLITE_OK;
  143112. }
  143113. /*
  143114. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  143115. ** compose and prepare an SQL statement of the form:
  143116. **
  143117. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  143118. **
  143119. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  143120. ** it. If an error occurs, return an SQLite error code.
  143121. */
  143122. static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
  143123. int rc = SQLITE_OK;
  143124. if( pCsr->pStmt==0 ){
  143125. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  143126. char *zSql;
  143127. if( p->pSeekStmt ){
  143128. pCsr->pStmt = p->pSeekStmt;
  143129. p->pSeekStmt = 0;
  143130. }else{
  143131. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  143132. if( !zSql ) return SQLITE_NOMEM;
  143133. rc = sqlite3_prepare_v3(p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  143134. sqlite3_free(zSql);
  143135. }
  143136. if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
  143137. }
  143138. return rc;
  143139. }
  143140. /*
  143141. ** Position the pCsr->pStmt statement so that it is on the row
  143142. ** of the %_content table that contains the last match. Return
  143143. ** SQLITE_OK on success.
  143144. */
  143145. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  143146. int rc = SQLITE_OK;
  143147. if( pCsr->isRequireSeek ){
  143148. rc = fts3CursorSeekStmt(pCsr);
  143149. if( rc==SQLITE_OK ){
  143150. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  143151. pCsr->isRequireSeek = 0;
  143152. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  143153. return SQLITE_OK;
  143154. }else{
  143155. rc = sqlite3_reset(pCsr->pStmt);
  143156. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  143157. /* If no row was found and no error has occurred, then the %_content
  143158. ** table is missing a row that is present in the full-text index.
  143159. ** The data structures are corrupt. */
  143160. rc = FTS_CORRUPT_VTAB;
  143161. pCsr->isEof = 1;
  143162. }
  143163. }
  143164. }
  143165. }
  143166. if( rc!=SQLITE_OK && pContext ){
  143167. sqlite3_result_error_code(pContext, rc);
  143168. }
  143169. return rc;
  143170. }
  143171. /*
  143172. ** This function is used to process a single interior node when searching
  143173. ** a b-tree for a term or term prefix. The node data is passed to this
  143174. ** function via the zNode/nNode parameters. The term to search for is
  143175. ** passed in zTerm/nTerm.
  143176. **
  143177. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  143178. ** of the child node that heads the sub-tree that may contain the term.
  143179. **
  143180. ** If piLast is not NULL, then *piLast is set to the right-most child node
  143181. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  143182. ** a prefix.
  143183. **
  143184. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  143185. */
  143186. static int fts3ScanInteriorNode(
  143187. const char *zTerm, /* Term to select leaves for */
  143188. int nTerm, /* Size of term zTerm in bytes */
  143189. const char *zNode, /* Buffer containing segment interior node */
  143190. int nNode, /* Size of buffer at zNode */
  143191. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  143192. sqlite3_int64 *piLast /* OUT: Selected child node */
  143193. ){
  143194. int rc = SQLITE_OK; /* Return code */
  143195. const char *zCsr = zNode; /* Cursor to iterate through node */
  143196. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  143197. char *zBuffer = 0; /* Buffer to load terms into */
  143198. int nAlloc = 0; /* Size of allocated buffer */
  143199. int isFirstTerm = 1; /* True when processing first term on page */
  143200. sqlite3_int64 iChild; /* Block id of child node to descend to */
  143201. /* Skip over the 'height' varint that occurs at the start of every
  143202. ** interior node. Then load the blockid of the left-child of the b-tree
  143203. ** node into variable iChild.
  143204. **
  143205. ** Even if the data structure on disk is corrupted, this (reading two
  143206. ** varints from the buffer) does not risk an overread. If zNode is a
  143207. ** root node, then the buffer comes from a SELECT statement. SQLite does
  143208. ** not make this guarantee explicitly, but in practice there are always
  143209. ** either more than 20 bytes of allocated space following the nNode bytes of
  143210. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  143211. ** table, then there are always 20 bytes of zeroed padding following the
  143212. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  143213. */
  143214. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  143215. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  143216. if( zCsr>zEnd ){
  143217. return FTS_CORRUPT_VTAB;
  143218. }
  143219. while( zCsr<zEnd && (piFirst || piLast) ){
  143220. int cmp; /* memcmp() result */
  143221. int nSuffix; /* Size of term suffix */
  143222. int nPrefix = 0; /* Size of term prefix */
  143223. int nBuffer; /* Total term size */
  143224. /* Load the next term on the node into zBuffer. Use realloc() to expand
  143225. ** the size of zBuffer if required. */
  143226. if( !isFirstTerm ){
  143227. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  143228. }
  143229. isFirstTerm = 0;
  143230. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  143231. assert( nPrefix>=0 && nSuffix>=0 );
  143232. if( &zCsr[nSuffix]>zEnd ){
  143233. rc = FTS_CORRUPT_VTAB;
  143234. goto finish_scan;
  143235. }
  143236. if( nPrefix+nSuffix>nAlloc ){
  143237. char *zNew;
  143238. nAlloc = (nPrefix+nSuffix) * 2;
  143239. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  143240. if( !zNew ){
  143241. rc = SQLITE_NOMEM;
  143242. goto finish_scan;
  143243. }
  143244. zBuffer = zNew;
  143245. }
  143246. assert( zBuffer );
  143247. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  143248. nBuffer = nPrefix + nSuffix;
  143249. zCsr += nSuffix;
  143250. /* Compare the term we are searching for with the term just loaded from
  143251. ** the interior node. If the specified term is greater than or equal
  143252. ** to the term from the interior node, then all terms on the sub-tree
  143253. ** headed by node iChild are smaller than zTerm. No need to search
  143254. ** iChild.
  143255. **
  143256. ** If the interior node term is larger than the specified term, then
  143257. ** the tree headed by iChild may contain the specified term.
  143258. */
  143259. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  143260. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  143261. *piFirst = iChild;
  143262. piFirst = 0;
  143263. }
  143264. if( piLast && cmp<0 ){
  143265. *piLast = iChild;
  143266. piLast = 0;
  143267. }
  143268. iChild++;
  143269. };
  143270. if( piFirst ) *piFirst = iChild;
  143271. if( piLast ) *piLast = iChild;
  143272. finish_scan:
  143273. sqlite3_free(zBuffer);
  143274. return rc;
  143275. }
  143276. /*
  143277. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  143278. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  143279. ** contains a term. This function searches the sub-tree headed by the zNode
  143280. ** node for the range of leaf nodes that may contain the specified term
  143281. ** or terms for which the specified term is a prefix.
  143282. **
  143283. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  143284. ** left-most leaf node in the tree that may contain the specified term.
  143285. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  143286. ** right-most leaf node that may contain a term for which the specified
  143287. ** term is a prefix.
  143288. **
  143289. ** It is possible that the range of returned leaf nodes does not contain
  143290. ** the specified term or any terms for which it is a prefix. However, if the
  143291. ** segment does contain any such terms, they are stored within the identified
  143292. ** range. Because this function only inspects interior segment nodes (and
  143293. ** never loads leaf nodes into memory), it is not possible to be sure.
  143294. **
  143295. ** If an error occurs, an error code other than SQLITE_OK is returned.
  143296. */
  143297. static int fts3SelectLeaf(
  143298. Fts3Table *p, /* Virtual table handle */
  143299. const char *zTerm, /* Term to select leaves for */
  143300. int nTerm, /* Size of term zTerm in bytes */
  143301. const char *zNode, /* Buffer containing segment interior node */
  143302. int nNode, /* Size of buffer at zNode */
  143303. sqlite3_int64 *piLeaf, /* Selected leaf node */
  143304. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  143305. ){
  143306. int rc = SQLITE_OK; /* Return code */
  143307. int iHeight; /* Height of this node in tree */
  143308. assert( piLeaf || piLeaf2 );
  143309. fts3GetVarint32(zNode, &iHeight);
  143310. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  143311. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  143312. if( rc==SQLITE_OK && iHeight>1 ){
  143313. char *zBlob = 0; /* Blob read from %_segments table */
  143314. int nBlob = 0; /* Size of zBlob in bytes */
  143315. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  143316. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  143317. if( rc==SQLITE_OK ){
  143318. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  143319. }
  143320. sqlite3_free(zBlob);
  143321. piLeaf = 0;
  143322. zBlob = 0;
  143323. }
  143324. if( rc==SQLITE_OK ){
  143325. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  143326. }
  143327. if( rc==SQLITE_OK ){
  143328. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  143329. }
  143330. sqlite3_free(zBlob);
  143331. }
  143332. return rc;
  143333. }
  143334. /*
  143335. ** This function is used to create delta-encoded serialized lists of FTS3
  143336. ** varints. Each call to this function appends a single varint to a list.
  143337. */
  143338. static void fts3PutDeltaVarint(
  143339. char **pp, /* IN/OUT: Output pointer */
  143340. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  143341. sqlite3_int64 iVal /* Write this value to the list */
  143342. ){
  143343. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  143344. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  143345. *piPrev = iVal;
  143346. }
  143347. /*
  143348. ** When this function is called, *ppPoslist is assumed to point to the
  143349. ** start of a position-list. After it returns, *ppPoslist points to the
  143350. ** first byte after the position-list.
  143351. **
  143352. ** A position list is list of positions (delta encoded) and columns for
  143353. ** a single document record of a doclist. So, in other words, this
  143354. ** routine advances *ppPoslist so that it points to the next docid in
  143355. ** the doclist, or to the first byte past the end of the doclist.
  143356. **
  143357. ** If pp is not NULL, then the contents of the position list are copied
  143358. ** to *pp. *pp is set to point to the first byte past the last byte copied
  143359. ** before this function returns.
  143360. */
  143361. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  143362. char *pEnd = *ppPoslist;
  143363. char c = 0;
  143364. /* The end of a position list is marked by a zero encoded as an FTS3
  143365. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  143366. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  143367. ** of some other, multi-byte, value.
  143368. **
  143369. ** The following while-loop moves pEnd to point to the first byte that is not
  143370. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  143371. ** pEnd once more so that it points to the byte immediately following the
  143372. ** last byte in the position-list.
  143373. */
  143374. while( *pEnd | c ){
  143375. c = *pEnd++ & 0x80;
  143376. testcase( c!=0 && (*pEnd)==0 );
  143377. }
  143378. pEnd++; /* Advance past the POS_END terminator byte */
  143379. if( pp ){
  143380. int n = (int)(pEnd - *ppPoslist);
  143381. char *p = *pp;
  143382. memcpy(p, *ppPoslist, n);
  143383. p += n;
  143384. *pp = p;
  143385. }
  143386. *ppPoslist = pEnd;
  143387. }
  143388. /*
  143389. ** When this function is called, *ppPoslist is assumed to point to the
  143390. ** start of a column-list. After it returns, *ppPoslist points to the
  143391. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  143392. **
  143393. ** A column-list is list of delta-encoded positions for a single column
  143394. ** within a single document within a doclist.
  143395. **
  143396. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  143397. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  143398. ** the POS_COLUMN or POS_END that terminates the column-list.
  143399. **
  143400. ** If pp is not NULL, then the contents of the column-list are copied
  143401. ** to *pp. *pp is set to point to the first byte past the last byte copied
  143402. ** before this function returns. The POS_COLUMN or POS_END terminator
  143403. ** is not copied into *pp.
  143404. */
  143405. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  143406. char *pEnd = *ppPoslist;
  143407. char c = 0;
  143408. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  143409. ** not part of a multi-byte varint.
  143410. */
  143411. while( 0xFE & (*pEnd | c) ){
  143412. c = *pEnd++ & 0x80;
  143413. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  143414. }
  143415. if( pp ){
  143416. int n = (int)(pEnd - *ppPoslist);
  143417. char *p = *pp;
  143418. memcpy(p, *ppPoslist, n);
  143419. p += n;
  143420. *pp = p;
  143421. }
  143422. *ppPoslist = pEnd;
  143423. }
  143424. /*
  143425. ** Value used to signify the end of an position-list. This is safe because
  143426. ** it is not possible to have a document with 2^31 terms.
  143427. */
  143428. #define POSITION_LIST_END 0x7fffffff
  143429. /*
  143430. ** This function is used to help parse position-lists. When this function is
  143431. ** called, *pp may point to the start of the next varint in the position-list
  143432. ** being parsed, or it may point to 1 byte past the end of the position-list
  143433. ** (in which case **pp will be a terminator bytes POS_END (0) or
  143434. ** (1)).
  143435. **
  143436. ** If *pp points past the end of the current position-list, set *pi to
  143437. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  143438. ** increment the current value of *pi by the value read, and set *pp to
  143439. ** point to the next value before returning.
  143440. **
  143441. ** Before calling this routine *pi must be initialized to the value of
  143442. ** the previous position, or zero if we are reading the first position
  143443. ** in the position-list. Because positions are delta-encoded, the value
  143444. ** of the previous position is needed in order to compute the value of
  143445. ** the next position.
  143446. */
  143447. static void fts3ReadNextPos(
  143448. char **pp, /* IN/OUT: Pointer into position-list buffer */
  143449. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  143450. ){
  143451. if( (**pp)&0xFE ){
  143452. fts3GetDeltaVarint(pp, pi);
  143453. *pi -= 2;
  143454. }else{
  143455. *pi = POSITION_LIST_END;
  143456. }
  143457. }
  143458. /*
  143459. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  143460. ** the value of iCol encoded as a varint to *pp. This will start a new
  143461. ** column list.
  143462. **
  143463. ** Set *pp to point to the byte just after the last byte written before
  143464. ** returning (do not modify it if iCol==0). Return the total number of bytes
  143465. ** written (0 if iCol==0).
  143466. */
  143467. static int fts3PutColNumber(char **pp, int iCol){
  143468. int n = 0; /* Number of bytes written */
  143469. if( iCol ){
  143470. char *p = *pp; /* Output pointer */
  143471. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  143472. *p = 0x01;
  143473. *pp = &p[n];
  143474. }
  143475. return n;
  143476. }
  143477. /*
  143478. ** Compute the union of two position lists. The output written
  143479. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  143480. ** order and with any duplicates removed. All pointers are
  143481. ** updated appropriately. The caller is responsible for insuring
  143482. ** that there is enough space in *pp to hold the complete output.
  143483. */
  143484. static void fts3PoslistMerge(
  143485. char **pp, /* Output buffer */
  143486. char **pp1, /* Left input list */
  143487. char **pp2 /* Right input list */
  143488. ){
  143489. char *p = *pp;
  143490. char *p1 = *pp1;
  143491. char *p2 = *pp2;
  143492. while( *p1 || *p2 ){
  143493. int iCol1; /* The current column index in pp1 */
  143494. int iCol2; /* The current column index in pp2 */
  143495. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  143496. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  143497. else iCol1 = 0;
  143498. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  143499. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  143500. else iCol2 = 0;
  143501. if( iCol1==iCol2 ){
  143502. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  143503. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  143504. sqlite3_int64 iPrev = 0;
  143505. int n = fts3PutColNumber(&p, iCol1);
  143506. p1 += n;
  143507. p2 += n;
  143508. /* At this point, both p1 and p2 point to the start of column-lists
  143509. ** for the same column (the column with index iCol1 and iCol2).
  143510. ** A column-list is a list of non-negative delta-encoded varints, each
  143511. ** incremented by 2 before being stored. Each list is terminated by a
  143512. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  143513. ** and writes the results to buffer p. p is left pointing to the byte
  143514. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  143515. ** written to the output.
  143516. */
  143517. fts3GetDeltaVarint(&p1, &i1);
  143518. fts3GetDeltaVarint(&p2, &i2);
  143519. do {
  143520. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  143521. iPrev -= 2;
  143522. if( i1==i2 ){
  143523. fts3ReadNextPos(&p1, &i1);
  143524. fts3ReadNextPos(&p2, &i2);
  143525. }else if( i1<i2 ){
  143526. fts3ReadNextPos(&p1, &i1);
  143527. }else{
  143528. fts3ReadNextPos(&p2, &i2);
  143529. }
  143530. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  143531. }else if( iCol1<iCol2 ){
  143532. p1 += fts3PutColNumber(&p, iCol1);
  143533. fts3ColumnlistCopy(&p, &p1);
  143534. }else{
  143535. p2 += fts3PutColNumber(&p, iCol2);
  143536. fts3ColumnlistCopy(&p, &p2);
  143537. }
  143538. }
  143539. *p++ = POS_END;
  143540. *pp = p;
  143541. *pp1 = p1 + 1;
  143542. *pp2 = p2 + 1;
  143543. }
  143544. /*
  143545. ** This function is used to merge two position lists into one. When it is
  143546. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  143547. ** the part of a doclist that follows each document id. For example, if a row
  143548. ** contains:
  143549. **
  143550. ** 'a b c'|'x y z'|'a b b a'
  143551. **
  143552. ** Then the position list for this row for token 'b' would consist of:
  143553. **
  143554. ** 0x02 0x01 0x02 0x03 0x03 0x00
  143555. **
  143556. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  143557. ** byte following the 0x00 terminator of their respective position lists.
  143558. **
  143559. ** If isSaveLeft is 0, an entry is added to the output position list for
  143560. ** each position in *pp2 for which there exists one or more positions in
  143561. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  143562. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  143563. ** slots before it.
  143564. **
  143565. ** e.g. nToken==1 searches for adjacent positions.
  143566. */
  143567. static int fts3PoslistPhraseMerge(
  143568. char **pp, /* IN/OUT: Preallocated output buffer */
  143569. int nToken, /* Maximum difference in token positions */
  143570. int isSaveLeft, /* Save the left position */
  143571. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  143572. char **pp1, /* IN/OUT: Left input list */
  143573. char **pp2 /* IN/OUT: Right input list */
  143574. ){
  143575. char *p = *pp;
  143576. char *p1 = *pp1;
  143577. char *p2 = *pp2;
  143578. int iCol1 = 0;
  143579. int iCol2 = 0;
  143580. /* Never set both isSaveLeft and isExact for the same invocation. */
  143581. assert( isSaveLeft==0 || isExact==0 );
  143582. assert( p!=0 && *p1!=0 && *p2!=0 );
  143583. if( *p1==POS_COLUMN ){
  143584. p1++;
  143585. p1 += fts3GetVarint32(p1, &iCol1);
  143586. }
  143587. if( *p2==POS_COLUMN ){
  143588. p2++;
  143589. p2 += fts3GetVarint32(p2, &iCol2);
  143590. }
  143591. while( 1 ){
  143592. if( iCol1==iCol2 ){
  143593. char *pSave = p;
  143594. sqlite3_int64 iPrev = 0;
  143595. sqlite3_int64 iPos1 = 0;
  143596. sqlite3_int64 iPos2 = 0;
  143597. if( iCol1 ){
  143598. *p++ = POS_COLUMN;
  143599. p += sqlite3Fts3PutVarint(p, iCol1);
  143600. }
  143601. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  143602. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  143603. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  143604. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  143605. while( 1 ){
  143606. if( iPos2==iPos1+nToken
  143607. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  143608. ){
  143609. sqlite3_int64 iSave;
  143610. iSave = isSaveLeft ? iPos1 : iPos2;
  143611. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  143612. pSave = 0;
  143613. assert( p );
  143614. }
  143615. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  143616. if( (*p2&0xFE)==0 ) break;
  143617. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  143618. }else{
  143619. if( (*p1&0xFE)==0 ) break;
  143620. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  143621. }
  143622. }
  143623. if( pSave ){
  143624. assert( pp && p );
  143625. p = pSave;
  143626. }
  143627. fts3ColumnlistCopy(0, &p1);
  143628. fts3ColumnlistCopy(0, &p2);
  143629. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  143630. if( 0==*p1 || 0==*p2 ) break;
  143631. p1++;
  143632. p1 += fts3GetVarint32(p1, &iCol1);
  143633. p2++;
  143634. p2 += fts3GetVarint32(p2, &iCol2);
  143635. }
  143636. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  143637. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  143638. ** end of the position list, or the 0x01 that precedes the next
  143639. ** column-number in the position list.
  143640. */
  143641. else if( iCol1<iCol2 ){
  143642. fts3ColumnlistCopy(0, &p1);
  143643. if( 0==*p1 ) break;
  143644. p1++;
  143645. p1 += fts3GetVarint32(p1, &iCol1);
  143646. }else{
  143647. fts3ColumnlistCopy(0, &p2);
  143648. if( 0==*p2 ) break;
  143649. p2++;
  143650. p2 += fts3GetVarint32(p2, &iCol2);
  143651. }
  143652. }
  143653. fts3PoslistCopy(0, &p2);
  143654. fts3PoslistCopy(0, &p1);
  143655. *pp1 = p1;
  143656. *pp2 = p2;
  143657. if( *pp==p ){
  143658. return 0;
  143659. }
  143660. *p++ = 0x00;
  143661. *pp = p;
  143662. return 1;
  143663. }
  143664. /*
  143665. ** Merge two position-lists as required by the NEAR operator. The argument
  143666. ** position lists correspond to the left and right phrases of an expression
  143667. ** like:
  143668. **
  143669. ** "phrase 1" NEAR "phrase number 2"
  143670. **
  143671. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  143672. ** expression and *pp2 to the right. As usual, the indexes in the position
  143673. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  143674. ** in the example above).
  143675. **
  143676. ** The output position list - written to *pp - is a copy of *pp2 with those
  143677. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  143678. */
  143679. static int fts3PoslistNearMerge(
  143680. char **pp, /* Output buffer */
  143681. char *aTmp, /* Temporary buffer space */
  143682. int nRight, /* Maximum difference in token positions */
  143683. int nLeft, /* Maximum difference in token positions */
  143684. char **pp1, /* IN/OUT: Left input list */
  143685. char **pp2 /* IN/OUT: Right input list */
  143686. ){
  143687. char *p1 = *pp1;
  143688. char *p2 = *pp2;
  143689. char *pTmp1 = aTmp;
  143690. char *pTmp2;
  143691. char *aTmp2;
  143692. int res = 1;
  143693. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  143694. aTmp2 = pTmp2 = pTmp1;
  143695. *pp1 = p1;
  143696. *pp2 = p2;
  143697. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  143698. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  143699. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  143700. }else if( pTmp1!=aTmp ){
  143701. fts3PoslistCopy(pp, &aTmp);
  143702. }else if( pTmp2!=aTmp2 ){
  143703. fts3PoslistCopy(pp, &aTmp2);
  143704. }else{
  143705. res = 0;
  143706. }
  143707. return res;
  143708. }
  143709. /*
  143710. ** An instance of this function is used to merge together the (potentially
  143711. ** large number of) doclists for each term that matches a prefix query.
  143712. ** See function fts3TermSelectMerge() for details.
  143713. */
  143714. typedef struct TermSelect TermSelect;
  143715. struct TermSelect {
  143716. char *aaOutput[16]; /* Malloc'd output buffers */
  143717. int anOutput[16]; /* Size each output buffer in bytes */
  143718. };
  143719. /*
  143720. ** This function is used to read a single varint from a buffer. Parameter
  143721. ** pEnd points 1 byte past the end of the buffer. When this function is
  143722. ** called, if *pp points to pEnd or greater, then the end of the buffer
  143723. ** has been reached. In this case *pp is set to 0 and the function returns.
  143724. **
  143725. ** If *pp does not point to or past pEnd, then a single varint is read
  143726. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  143727. **
  143728. ** If bDescIdx is false, the value read is added to *pVal before returning.
  143729. ** If it is true, the value read is subtracted from *pVal before this
  143730. ** function returns.
  143731. */
  143732. static void fts3GetDeltaVarint3(
  143733. char **pp, /* IN/OUT: Point to read varint from */
  143734. char *pEnd, /* End of buffer */
  143735. int bDescIdx, /* True if docids are descending */
  143736. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  143737. ){
  143738. if( *pp>=pEnd ){
  143739. *pp = 0;
  143740. }else{
  143741. sqlite3_int64 iVal;
  143742. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  143743. if( bDescIdx ){
  143744. *pVal -= iVal;
  143745. }else{
  143746. *pVal += iVal;
  143747. }
  143748. }
  143749. }
  143750. /*
  143751. ** This function is used to write a single varint to a buffer. The varint
  143752. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  143753. ** end of the value written.
  143754. **
  143755. ** If *pbFirst is zero when this function is called, the value written to
  143756. ** the buffer is that of parameter iVal.
  143757. **
  143758. ** If *pbFirst is non-zero when this function is called, then the value
  143759. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  143760. ** (if bDescIdx is non-zero).
  143761. **
  143762. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  143763. ** to the value of parameter iVal.
  143764. */
  143765. static void fts3PutDeltaVarint3(
  143766. char **pp, /* IN/OUT: Output pointer */
  143767. int bDescIdx, /* True for descending docids */
  143768. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  143769. int *pbFirst, /* IN/OUT: True after first int written */
  143770. sqlite3_int64 iVal /* Write this value to the list */
  143771. ){
  143772. sqlite3_int64 iWrite;
  143773. if( bDescIdx==0 || *pbFirst==0 ){
  143774. iWrite = iVal - *piPrev;
  143775. }else{
  143776. iWrite = *piPrev - iVal;
  143777. }
  143778. assert( *pbFirst || *piPrev==0 );
  143779. assert( *pbFirst==0 || iWrite>0 );
  143780. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  143781. *piPrev = iVal;
  143782. *pbFirst = 1;
  143783. }
  143784. /*
  143785. ** This macro is used by various functions that merge doclists. The two
  143786. ** arguments are 64-bit docid values. If the value of the stack variable
  143787. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  143788. ** Otherwise, (i2-i1).
  143789. **
  143790. ** Using this makes it easier to write code that can merge doclists that are
  143791. ** sorted in either ascending or descending order.
  143792. */
  143793. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  143794. /*
  143795. ** This function does an "OR" merge of two doclists (output contains all
  143796. ** positions contained in either argument doclist). If the docids in the
  143797. ** input doclists are sorted in ascending order, parameter bDescDoclist
  143798. ** should be false. If they are sorted in ascending order, it should be
  143799. ** passed a non-zero value.
  143800. **
  143801. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  143802. ** containing the output doclist and SQLITE_OK is returned. In this case
  143803. ** *pnOut is set to the number of bytes in the output doclist.
  143804. **
  143805. ** If an error occurs, an SQLite error code is returned. The output values
  143806. ** are undefined in this case.
  143807. */
  143808. static int fts3DoclistOrMerge(
  143809. int bDescDoclist, /* True if arguments are desc */
  143810. char *a1, int n1, /* First doclist */
  143811. char *a2, int n2, /* Second doclist */
  143812. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  143813. ){
  143814. sqlite3_int64 i1 = 0;
  143815. sqlite3_int64 i2 = 0;
  143816. sqlite3_int64 iPrev = 0;
  143817. char *pEnd1 = &a1[n1];
  143818. char *pEnd2 = &a2[n2];
  143819. char *p1 = a1;
  143820. char *p2 = a2;
  143821. char *p;
  143822. char *aOut;
  143823. int bFirstOut = 0;
  143824. *paOut = 0;
  143825. *pnOut = 0;
  143826. /* Allocate space for the output. Both the input and output doclists
  143827. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  143828. ** then the first docid in each list is simply encoded as a varint. For
  143829. ** each subsequent docid, the varint stored is the difference between the
  143830. ** current and previous docid (a positive number - since the list is in
  143831. ** ascending order).
  143832. **
  143833. ** The first docid written to the output is therefore encoded using the
  143834. ** same number of bytes as it is in whichever of the input lists it is
  143835. ** read from. And each subsequent docid read from the same input list
  143836. ** consumes either the same or less bytes as it did in the input (since
  143837. ** the difference between it and the previous value in the output must
  143838. ** be a positive value less than or equal to the delta value read from
  143839. ** the input list). The same argument applies to all but the first docid
  143840. ** read from the 'other' list. And to the contents of all position lists
  143841. ** that will be copied and merged from the input to the output.
  143842. **
  143843. ** However, if the first docid copied to the output is a negative number,
  143844. ** then the encoding of the first docid from the 'other' input list may
  143845. ** be larger in the output than it was in the input (since the delta value
  143846. ** may be a larger positive integer than the actual docid).
  143847. **
  143848. ** The space required to store the output is therefore the sum of the
  143849. ** sizes of the two inputs, plus enough space for exactly one of the input
  143850. ** docids to grow.
  143851. **
  143852. ** A symetric argument may be made if the doclists are in descending
  143853. ** order.
  143854. */
  143855. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  143856. if( !aOut ) return SQLITE_NOMEM;
  143857. p = aOut;
  143858. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  143859. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  143860. while( p1 || p2 ){
  143861. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  143862. if( p2 && p1 && iDiff==0 ){
  143863. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  143864. fts3PoslistMerge(&p, &p1, &p2);
  143865. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  143866. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  143867. }else if( !p2 || (p1 && iDiff<0) ){
  143868. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  143869. fts3PoslistCopy(&p, &p1);
  143870. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  143871. }else{
  143872. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  143873. fts3PoslistCopy(&p, &p2);
  143874. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  143875. }
  143876. }
  143877. *paOut = aOut;
  143878. *pnOut = (int)(p-aOut);
  143879. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  143880. return SQLITE_OK;
  143881. }
  143882. /*
  143883. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  143884. ** the output contains a copy of each position from the right-hand input
  143885. ** doclist for which there is a position in the left-hand input doclist
  143886. ** exactly nDist tokens before it.
  143887. **
  143888. ** If the docids in the input doclists are sorted in ascending order,
  143889. ** parameter bDescDoclist should be false. If they are sorted in ascending
  143890. ** order, it should be passed a non-zero value.
  143891. **
  143892. ** The right-hand input doclist is overwritten by this function.
  143893. */
  143894. static int fts3DoclistPhraseMerge(
  143895. int bDescDoclist, /* True if arguments are desc */
  143896. int nDist, /* Distance from left to right (1=adjacent) */
  143897. char *aLeft, int nLeft, /* Left doclist */
  143898. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  143899. ){
  143900. sqlite3_int64 i1 = 0;
  143901. sqlite3_int64 i2 = 0;
  143902. sqlite3_int64 iPrev = 0;
  143903. char *aRight = *paRight;
  143904. char *pEnd1 = &aLeft[nLeft];
  143905. char *pEnd2 = &aRight[*pnRight];
  143906. char *p1 = aLeft;
  143907. char *p2 = aRight;
  143908. char *p;
  143909. int bFirstOut = 0;
  143910. char *aOut;
  143911. assert( nDist>0 );
  143912. if( bDescDoclist ){
  143913. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  143914. if( aOut==0 ) return SQLITE_NOMEM;
  143915. }else{
  143916. aOut = aRight;
  143917. }
  143918. p = aOut;
  143919. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  143920. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  143921. while( p1 && p2 ){
  143922. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  143923. if( iDiff==0 ){
  143924. char *pSave = p;
  143925. sqlite3_int64 iPrevSave = iPrev;
  143926. int bFirstOutSave = bFirstOut;
  143927. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  143928. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  143929. p = pSave;
  143930. iPrev = iPrevSave;
  143931. bFirstOut = bFirstOutSave;
  143932. }
  143933. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  143934. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  143935. }else if( iDiff<0 ){
  143936. fts3PoslistCopy(0, &p1);
  143937. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  143938. }else{
  143939. fts3PoslistCopy(0, &p2);
  143940. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  143941. }
  143942. }
  143943. *pnRight = (int)(p - aOut);
  143944. if( bDescDoclist ){
  143945. sqlite3_free(aRight);
  143946. *paRight = aOut;
  143947. }
  143948. return SQLITE_OK;
  143949. }
  143950. /*
  143951. ** Argument pList points to a position list nList bytes in size. This
  143952. ** function checks to see if the position list contains any entries for
  143953. ** a token in position 0 (of any column). If so, it writes argument iDelta
  143954. ** to the output buffer pOut, followed by a position list consisting only
  143955. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  143956. ** The value returned is the number of bytes written to pOut (if any).
  143957. */
  143958. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  143959. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  143960. char *pList, /* Position list (no 0x00 term) */
  143961. int nList, /* Size of pList in bytes */
  143962. char *pOut /* Write output here */
  143963. ){
  143964. int nOut = 0;
  143965. int bWritten = 0; /* True once iDelta has been written */
  143966. char *p = pList;
  143967. char *pEnd = &pList[nList];
  143968. if( *p!=0x01 ){
  143969. if( *p==0x02 ){
  143970. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  143971. pOut[nOut++] = 0x02;
  143972. bWritten = 1;
  143973. }
  143974. fts3ColumnlistCopy(0, &p);
  143975. }
  143976. while( p<pEnd ){
  143977. sqlite3_int64 iCol;
  143978. p++;
  143979. p += sqlite3Fts3GetVarint(p, &iCol);
  143980. if( *p==0x02 ){
  143981. if( bWritten==0 ){
  143982. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  143983. bWritten = 1;
  143984. }
  143985. pOut[nOut++] = 0x01;
  143986. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  143987. pOut[nOut++] = 0x02;
  143988. }
  143989. fts3ColumnlistCopy(0, &p);
  143990. }
  143991. if( bWritten ){
  143992. pOut[nOut++] = 0x00;
  143993. }
  143994. return nOut;
  143995. }
  143996. /*
  143997. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  143998. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  143999. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  144000. **
  144001. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  144002. ** the responsibility of the caller to free any doclists left in the
  144003. ** TermSelect.aaOutput[] array.
  144004. */
  144005. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  144006. char *aOut = 0;
  144007. int nOut = 0;
  144008. int i;
  144009. /* Loop through the doclists in the aaOutput[] array. Merge them all
  144010. ** into a single doclist.
  144011. */
  144012. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  144013. if( pTS->aaOutput[i] ){
  144014. if( !aOut ){
  144015. aOut = pTS->aaOutput[i];
  144016. nOut = pTS->anOutput[i];
  144017. pTS->aaOutput[i] = 0;
  144018. }else{
  144019. int nNew;
  144020. char *aNew;
  144021. int rc = fts3DoclistOrMerge(p->bDescIdx,
  144022. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  144023. );
  144024. if( rc!=SQLITE_OK ){
  144025. sqlite3_free(aOut);
  144026. return rc;
  144027. }
  144028. sqlite3_free(pTS->aaOutput[i]);
  144029. sqlite3_free(aOut);
  144030. pTS->aaOutput[i] = 0;
  144031. aOut = aNew;
  144032. nOut = nNew;
  144033. }
  144034. }
  144035. }
  144036. pTS->aaOutput[0] = aOut;
  144037. pTS->anOutput[0] = nOut;
  144038. return SQLITE_OK;
  144039. }
  144040. /*
  144041. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  144042. ** as the first argument. The merge is an "OR" merge (see function
  144043. ** fts3DoclistOrMerge() for details).
  144044. **
  144045. ** This function is called with the doclist for each term that matches
  144046. ** a queried prefix. It merges all these doclists into one, the doclist
  144047. ** for the specified prefix. Since there can be a very large number of
  144048. ** doclists to merge, the merging is done pair-wise using the TermSelect
  144049. ** object.
  144050. **
  144051. ** This function returns SQLITE_OK if the merge is successful, or an
  144052. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  144053. */
  144054. static int fts3TermSelectMerge(
  144055. Fts3Table *p, /* FTS table handle */
  144056. TermSelect *pTS, /* TermSelect object to merge into */
  144057. char *aDoclist, /* Pointer to doclist */
  144058. int nDoclist /* Size of aDoclist in bytes */
  144059. ){
  144060. if( pTS->aaOutput[0]==0 ){
  144061. /* If this is the first term selected, copy the doclist to the output
  144062. ** buffer using memcpy().
  144063. **
  144064. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  144065. ** allocation. This is so as to ensure that the buffer is big enough
  144066. ** to hold the current doclist AND'd with any other doclist. If the
  144067. ** doclists are stored in order=ASC order, this padding would not be
  144068. ** required (since the size of [doclistA AND doclistB] is always less
  144069. ** than or equal to the size of [doclistA] in that case). But this is
  144070. ** not true for order=DESC. For example, a doclist containing (1, -1)
  144071. ** may be smaller than (-1), as in the first example the -1 may be stored
  144072. ** as a single-byte delta, whereas in the second it must be stored as a
  144073. ** FTS3_VARINT_MAX byte varint.
  144074. **
  144075. ** Similar padding is added in the fts3DoclistOrMerge() function.
  144076. */
  144077. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  144078. pTS->anOutput[0] = nDoclist;
  144079. if( pTS->aaOutput[0] ){
  144080. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  144081. }else{
  144082. return SQLITE_NOMEM;
  144083. }
  144084. }else{
  144085. char *aMerge = aDoclist;
  144086. int nMerge = nDoclist;
  144087. int iOut;
  144088. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  144089. if( pTS->aaOutput[iOut]==0 ){
  144090. assert( iOut>0 );
  144091. pTS->aaOutput[iOut] = aMerge;
  144092. pTS->anOutput[iOut] = nMerge;
  144093. break;
  144094. }else{
  144095. char *aNew;
  144096. int nNew;
  144097. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  144098. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  144099. );
  144100. if( rc!=SQLITE_OK ){
  144101. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  144102. return rc;
  144103. }
  144104. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  144105. sqlite3_free(pTS->aaOutput[iOut]);
  144106. pTS->aaOutput[iOut] = 0;
  144107. aMerge = aNew;
  144108. nMerge = nNew;
  144109. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  144110. pTS->aaOutput[iOut] = aMerge;
  144111. pTS->anOutput[iOut] = nMerge;
  144112. }
  144113. }
  144114. }
  144115. }
  144116. return SQLITE_OK;
  144117. }
  144118. /*
  144119. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  144120. */
  144121. static int fts3SegReaderCursorAppend(
  144122. Fts3MultiSegReader *pCsr,
  144123. Fts3SegReader *pNew
  144124. ){
  144125. if( (pCsr->nSegment%16)==0 ){
  144126. Fts3SegReader **apNew;
  144127. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  144128. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  144129. if( !apNew ){
  144130. sqlite3Fts3SegReaderFree(pNew);
  144131. return SQLITE_NOMEM;
  144132. }
  144133. pCsr->apSegment = apNew;
  144134. }
  144135. pCsr->apSegment[pCsr->nSegment++] = pNew;
  144136. return SQLITE_OK;
  144137. }
  144138. /*
  144139. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  144140. ** 8th argument.
  144141. **
  144142. ** This function returns SQLITE_OK if successful, or an SQLite error code
  144143. ** otherwise.
  144144. */
  144145. static int fts3SegReaderCursor(
  144146. Fts3Table *p, /* FTS3 table handle */
  144147. int iLangid, /* Language id */
  144148. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  144149. int iLevel, /* Level of segments to scan */
  144150. const char *zTerm, /* Term to query for */
  144151. int nTerm, /* Size of zTerm in bytes */
  144152. int isPrefix, /* True for a prefix search */
  144153. int isScan, /* True to scan from zTerm to EOF */
  144154. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  144155. ){
  144156. int rc = SQLITE_OK; /* Error code */
  144157. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  144158. int rc2; /* Result of sqlite3_reset() */
  144159. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  144160. ** for the pending-terms. If this is a scan, then this call must be being
  144161. ** made by an fts4aux module, not an FTS table. In this case calling
  144162. ** Fts3SegReaderPending might segfault, as the data structures used by
  144163. ** fts4aux are not completely populated. So it's easiest to filter these
  144164. ** calls out here. */
  144165. if( iLevel<0 && p->aIndex ){
  144166. Fts3SegReader *pSeg = 0;
  144167. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  144168. if( rc==SQLITE_OK && pSeg ){
  144169. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  144170. }
  144171. }
  144172. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  144173. if( rc==SQLITE_OK ){
  144174. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  144175. }
  144176. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  144177. Fts3SegReader *pSeg = 0;
  144178. /* Read the values returned by the SELECT into local variables. */
  144179. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  144180. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  144181. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  144182. int nRoot = sqlite3_column_bytes(pStmt, 4);
  144183. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  144184. /* If zTerm is not NULL, and this segment is not stored entirely on its
  144185. ** root node, the range of leaves scanned can be reduced. Do this. */
  144186. if( iStartBlock && zTerm ){
  144187. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  144188. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  144189. if( rc!=SQLITE_OK ) goto finished;
  144190. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  144191. }
  144192. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  144193. (isPrefix==0 && isScan==0),
  144194. iStartBlock, iLeavesEndBlock,
  144195. iEndBlock, zRoot, nRoot, &pSeg
  144196. );
  144197. if( rc!=SQLITE_OK ) goto finished;
  144198. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  144199. }
  144200. }
  144201. finished:
  144202. rc2 = sqlite3_reset(pStmt);
  144203. if( rc==SQLITE_DONE ) rc = rc2;
  144204. return rc;
  144205. }
  144206. /*
  144207. ** Set up a cursor object for iterating through a full-text index or a
  144208. ** single level therein.
  144209. */
  144210. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  144211. Fts3Table *p, /* FTS3 table handle */
  144212. int iLangid, /* Language-id to search */
  144213. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  144214. int iLevel, /* Level of segments to scan */
  144215. const char *zTerm, /* Term to query for */
  144216. int nTerm, /* Size of zTerm in bytes */
  144217. int isPrefix, /* True for a prefix search */
  144218. int isScan, /* True to scan from zTerm to EOF */
  144219. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  144220. ){
  144221. assert( iIndex>=0 && iIndex<p->nIndex );
  144222. assert( iLevel==FTS3_SEGCURSOR_ALL
  144223. || iLevel==FTS3_SEGCURSOR_PENDING
  144224. || iLevel>=0
  144225. );
  144226. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  144227. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  144228. assert( isPrefix==0 || isScan==0 );
  144229. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  144230. return fts3SegReaderCursor(
  144231. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  144232. );
  144233. }
  144234. /*
  144235. ** In addition to its current configuration, have the Fts3MultiSegReader
  144236. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  144237. **
  144238. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  144239. */
  144240. static int fts3SegReaderCursorAddZero(
  144241. Fts3Table *p, /* FTS virtual table handle */
  144242. int iLangid,
  144243. const char *zTerm, /* Term to scan doclist of */
  144244. int nTerm, /* Number of bytes in zTerm */
  144245. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  144246. ){
  144247. return fts3SegReaderCursor(p,
  144248. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  144249. );
  144250. }
  144251. /*
  144252. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  144253. ** if isPrefix is true, to scan the doclist for all terms for which
  144254. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  144255. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  144256. ** an SQLite error code.
  144257. **
  144258. ** It is the responsibility of the caller to free this object by eventually
  144259. ** passing it to fts3SegReaderCursorFree()
  144260. **
  144261. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  144262. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  144263. */
  144264. static int fts3TermSegReaderCursor(
  144265. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  144266. const char *zTerm, /* Term to query for */
  144267. int nTerm, /* Size of zTerm in bytes */
  144268. int isPrefix, /* True for a prefix search */
  144269. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  144270. ){
  144271. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  144272. int rc = SQLITE_NOMEM; /* Return code */
  144273. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  144274. if( pSegcsr ){
  144275. int i;
  144276. int bFound = 0; /* True once an index has been found */
  144277. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  144278. if( isPrefix ){
  144279. for(i=1; bFound==0 && i<p->nIndex; i++){
  144280. if( p->aIndex[i].nPrefix==nTerm ){
  144281. bFound = 1;
  144282. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  144283. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  144284. );
  144285. pSegcsr->bLookup = 1;
  144286. }
  144287. }
  144288. for(i=1; bFound==0 && i<p->nIndex; i++){
  144289. if( p->aIndex[i].nPrefix==nTerm+1 ){
  144290. bFound = 1;
  144291. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  144292. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  144293. );
  144294. if( rc==SQLITE_OK ){
  144295. rc = fts3SegReaderCursorAddZero(
  144296. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  144297. );
  144298. }
  144299. }
  144300. }
  144301. }
  144302. if( bFound==0 ){
  144303. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  144304. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  144305. );
  144306. pSegcsr->bLookup = !isPrefix;
  144307. }
  144308. }
  144309. *ppSegcsr = pSegcsr;
  144310. return rc;
  144311. }
  144312. /*
  144313. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  144314. */
  144315. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  144316. sqlite3Fts3SegReaderFinish(pSegcsr);
  144317. sqlite3_free(pSegcsr);
  144318. }
  144319. /*
  144320. ** This function retrieves the doclist for the specified term (or term
  144321. ** prefix) from the database.
  144322. */
  144323. static int fts3TermSelect(
  144324. Fts3Table *p, /* Virtual table handle */
  144325. Fts3PhraseToken *pTok, /* Token to query for */
  144326. int iColumn, /* Column to query (or -ve for all columns) */
  144327. int *pnOut, /* OUT: Size of buffer at *ppOut */
  144328. char **ppOut /* OUT: Malloced result buffer */
  144329. ){
  144330. int rc; /* Return code */
  144331. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  144332. TermSelect tsc; /* Object for pair-wise doclist merging */
  144333. Fts3SegFilter filter; /* Segment term filter configuration */
  144334. pSegcsr = pTok->pSegcsr;
  144335. memset(&tsc, 0, sizeof(TermSelect));
  144336. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  144337. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  144338. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  144339. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  144340. filter.iCol = iColumn;
  144341. filter.zTerm = pTok->z;
  144342. filter.nTerm = pTok->n;
  144343. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  144344. while( SQLITE_OK==rc
  144345. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  144346. ){
  144347. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  144348. }
  144349. if( rc==SQLITE_OK ){
  144350. rc = fts3TermSelectFinishMerge(p, &tsc);
  144351. }
  144352. if( rc==SQLITE_OK ){
  144353. *ppOut = tsc.aaOutput[0];
  144354. *pnOut = tsc.anOutput[0];
  144355. }else{
  144356. int i;
  144357. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  144358. sqlite3_free(tsc.aaOutput[i]);
  144359. }
  144360. }
  144361. fts3SegReaderCursorFree(pSegcsr);
  144362. pTok->pSegcsr = 0;
  144363. return rc;
  144364. }
  144365. /*
  144366. ** This function counts the total number of docids in the doclist stored
  144367. ** in buffer aList[], size nList bytes.
  144368. **
  144369. ** If the isPoslist argument is true, then it is assumed that the doclist
  144370. ** contains a position-list following each docid. Otherwise, it is assumed
  144371. ** that the doclist is simply a list of docids stored as delta encoded
  144372. ** varints.
  144373. */
  144374. static int fts3DoclistCountDocids(char *aList, int nList){
  144375. int nDoc = 0; /* Return value */
  144376. if( aList ){
  144377. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  144378. char *p = aList; /* Cursor */
  144379. while( p<aEnd ){
  144380. nDoc++;
  144381. while( (*p++)&0x80 ); /* Skip docid varint */
  144382. fts3PoslistCopy(0, &p); /* Skip over position list */
  144383. }
  144384. }
  144385. return nDoc;
  144386. }
  144387. /*
  144388. ** Advance the cursor to the next row in the %_content table that
  144389. ** matches the search criteria. For a MATCH search, this will be
  144390. ** the next row that matches. For a full-table scan, this will be
  144391. ** simply the next row in the %_content table. For a docid lookup,
  144392. ** this routine simply sets the EOF flag.
  144393. **
  144394. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  144395. ** even if we reach end-of-file. The fts3EofMethod() will be called
  144396. ** subsequently to determine whether or not an EOF was hit.
  144397. */
  144398. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  144399. int rc;
  144400. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  144401. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  144402. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  144403. pCsr->isEof = 1;
  144404. rc = sqlite3_reset(pCsr->pStmt);
  144405. }else{
  144406. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  144407. rc = SQLITE_OK;
  144408. }
  144409. }else{
  144410. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  144411. }
  144412. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  144413. return rc;
  144414. }
  144415. /*
  144416. ** The following are copied from sqliteInt.h.
  144417. **
  144418. ** Constants for the largest and smallest possible 64-bit signed integers.
  144419. ** These macros are designed to work correctly on both 32-bit and 64-bit
  144420. ** compilers.
  144421. */
  144422. #ifndef SQLITE_AMALGAMATION
  144423. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  144424. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  144425. #endif
  144426. /*
  144427. ** If the numeric type of argument pVal is "integer", then return it
  144428. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  144429. ** the second parameter, iDefault.
  144430. */
  144431. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  144432. if( pVal ){
  144433. int eType = sqlite3_value_numeric_type(pVal);
  144434. if( eType==SQLITE_INTEGER ){
  144435. return sqlite3_value_int64(pVal);
  144436. }
  144437. }
  144438. return iDefault;
  144439. }
  144440. /*
  144441. ** This is the xFilter interface for the virtual table. See
  144442. ** the virtual table xFilter method documentation for additional
  144443. ** information.
  144444. **
  144445. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  144446. ** the %_content table.
  144447. **
  144448. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  144449. ** in the %_content table.
  144450. **
  144451. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  144452. ** column on the left-hand side of the MATCH operator is column
  144453. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  144454. ** side of the MATCH operator.
  144455. */
  144456. static int fts3FilterMethod(
  144457. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  144458. int idxNum, /* Strategy index */
  144459. const char *idxStr, /* Unused */
  144460. int nVal, /* Number of elements in apVal */
  144461. sqlite3_value **apVal /* Arguments for the indexing scheme */
  144462. ){
  144463. int rc = SQLITE_OK;
  144464. char *zSql; /* SQL statement used to access %_content */
  144465. int eSearch;
  144466. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  144467. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  144468. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  144469. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  144470. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  144471. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  144472. int iIdx;
  144473. UNUSED_PARAMETER(idxStr);
  144474. UNUSED_PARAMETER(nVal);
  144475. eSearch = (idxNum & 0x0000FFFF);
  144476. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  144477. assert( p->pSegments==0 );
  144478. /* Collect arguments into local variables */
  144479. iIdx = 0;
  144480. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  144481. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  144482. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  144483. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  144484. assert( iIdx==nVal );
  144485. /* In case the cursor has been used before, clear it now. */
  144486. fts3ClearCursor(pCsr);
  144487. /* Set the lower and upper bounds on docids to return */
  144488. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  144489. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  144490. if( idxStr ){
  144491. pCsr->bDesc = (idxStr[0]=='D');
  144492. }else{
  144493. pCsr->bDesc = p->bDescIdx;
  144494. }
  144495. pCsr->eSearch = (i16)eSearch;
  144496. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  144497. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  144498. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  144499. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  144500. return SQLITE_NOMEM;
  144501. }
  144502. pCsr->iLangid = 0;
  144503. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  144504. assert( p->base.zErrMsg==0 );
  144505. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  144506. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  144507. &p->base.zErrMsg
  144508. );
  144509. if( rc!=SQLITE_OK ){
  144510. return rc;
  144511. }
  144512. rc = fts3EvalStart(pCsr);
  144513. sqlite3Fts3SegmentsClose(p);
  144514. if( rc!=SQLITE_OK ) return rc;
  144515. pCsr->pNextId = pCsr->aDoclist;
  144516. pCsr->iPrevId = 0;
  144517. }
  144518. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  144519. ** statement loops through all rows of the %_content table. For a
  144520. ** full-text query or docid lookup, the statement retrieves a single
  144521. ** row by docid.
  144522. */
  144523. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  144524. if( pDocidGe || pDocidLe ){
  144525. zSql = sqlite3_mprintf(
  144526. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  144527. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  144528. (pCsr->bDesc ? "DESC" : "ASC")
  144529. );
  144530. }else{
  144531. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  144532. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  144533. );
  144534. }
  144535. if( zSql ){
  144536. rc = sqlite3_prepare_v3(p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0);
  144537. sqlite3_free(zSql);
  144538. }else{
  144539. rc = SQLITE_NOMEM;
  144540. }
  144541. }else if( eSearch==FTS3_DOCID_SEARCH ){
  144542. rc = fts3CursorSeekStmt(pCsr);
  144543. if( rc==SQLITE_OK ){
  144544. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  144545. }
  144546. }
  144547. if( rc!=SQLITE_OK ) return rc;
  144548. return fts3NextMethod(pCursor);
  144549. }
  144550. /*
  144551. ** This is the xEof method of the virtual table. SQLite calls this
  144552. ** routine to find out if it has reached the end of a result set.
  144553. */
  144554. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  144555. Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
  144556. if( pCsr->isEof ){
  144557. fts3ClearCursor(pCsr);
  144558. pCsr->isEof = 1;
  144559. }
  144560. return pCsr->isEof;
  144561. }
  144562. /*
  144563. ** This is the xRowid method. The SQLite core calls this routine to
  144564. ** retrieve the rowid for the current row of the result set. fts3
  144565. ** exposes %_content.docid as the rowid for the virtual table. The
  144566. ** rowid should be written to *pRowid.
  144567. */
  144568. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  144569. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  144570. *pRowid = pCsr->iPrevId;
  144571. return SQLITE_OK;
  144572. }
  144573. /*
  144574. ** This is the xColumn method, called by SQLite to request a value from
  144575. ** the row that the supplied cursor currently points to.
  144576. **
  144577. ** If:
  144578. **
  144579. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  144580. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  144581. ** (iCol == p->nColumn+1) -> Docid column
  144582. ** (iCol == p->nColumn+2) -> Langid column
  144583. */
  144584. static int fts3ColumnMethod(
  144585. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  144586. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  144587. int iCol /* Index of column to read value from */
  144588. ){
  144589. int rc = SQLITE_OK; /* Return Code */
  144590. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  144591. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  144592. /* The column value supplied by SQLite must be in range. */
  144593. assert( iCol>=0 && iCol<=p->nColumn+2 );
  144594. switch( iCol-p->nColumn ){
  144595. case 0:
  144596. /* The special 'table-name' column */
  144597. sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
  144598. break;
  144599. case 1:
  144600. /* The docid column */
  144601. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  144602. break;
  144603. case 2:
  144604. if( pCsr->pExpr ){
  144605. sqlite3_result_int64(pCtx, pCsr->iLangid);
  144606. break;
  144607. }else if( p->zLanguageid==0 ){
  144608. sqlite3_result_int(pCtx, 0);
  144609. break;
  144610. }else{
  144611. iCol = p->nColumn;
  144612. /* fall-through */
  144613. }
  144614. default:
  144615. /* A user column. Or, if this is a full-table scan, possibly the
  144616. ** language-id column. Seek the cursor. */
  144617. rc = fts3CursorSeek(0, pCsr);
  144618. if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
  144619. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  144620. }
  144621. break;
  144622. }
  144623. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  144624. return rc;
  144625. }
  144626. /*
  144627. ** This function is the implementation of the xUpdate callback used by
  144628. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  144629. ** inserted, updated or deleted.
  144630. */
  144631. static int fts3UpdateMethod(
  144632. sqlite3_vtab *pVtab, /* Virtual table handle */
  144633. int nArg, /* Size of argument array */
  144634. sqlite3_value **apVal, /* Array of arguments */
  144635. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  144636. ){
  144637. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  144638. }
  144639. /*
  144640. ** Implementation of xSync() method. Flush the contents of the pending-terms
  144641. ** hash-table to the database.
  144642. */
  144643. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  144644. /* Following an incremental-merge operation, assuming that the input
  144645. ** segments are not completely consumed (the usual case), they are updated
  144646. ** in place to remove the entries that have already been merged. This
  144647. ** involves updating the leaf block that contains the smallest unmerged
  144648. ** entry and each block (if any) between the leaf and the root node. So
  144649. ** if the height of the input segment b-trees is N, and input segments
  144650. ** are merged eight at a time, updating the input segments at the end
  144651. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  144652. ** small - often between 0 and 2. So the overhead of the incremental
  144653. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  144654. ** dwarfing the actual productive work accomplished, the incremental merge
  144655. ** is only attempted if it will write at least 64 leaf blocks. Hence
  144656. ** nMinMerge.
  144657. **
  144658. ** Of course, updating the input segments also involves deleting a bunch
  144659. ** of blocks from the segments table. But this is not considered overhead
  144660. ** as it would also be required by a crisis-merge that used the same input
  144661. ** segments.
  144662. */
  144663. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  144664. Fts3Table *p = (Fts3Table*)pVtab;
  144665. int rc;
  144666. i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
  144667. rc = sqlite3Fts3PendingTermsFlush(p);
  144668. if( rc==SQLITE_OK
  144669. && p->nLeafAdd>(nMinMerge/16)
  144670. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  144671. ){
  144672. int mxLevel = 0; /* Maximum relative level value in db */
  144673. int A; /* Incr-merge parameter A */
  144674. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  144675. assert( rc==SQLITE_OK || mxLevel==0 );
  144676. A = p->nLeafAdd * mxLevel;
  144677. A += (A/2);
  144678. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  144679. }
  144680. sqlite3Fts3SegmentsClose(p);
  144681. sqlite3_set_last_insert_rowid(p->db, iLastRowid);
  144682. return rc;
  144683. }
  144684. /*
  144685. ** If it is currently unknown whether or not the FTS table has an %_stat
  144686. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  144687. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  144688. ** if an error occurs.
  144689. */
  144690. static int fts3SetHasStat(Fts3Table *p){
  144691. int rc = SQLITE_OK;
  144692. if( p->bHasStat==2 ){
  144693. char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
  144694. if( zTbl ){
  144695. int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
  144696. sqlite3_free(zTbl);
  144697. p->bHasStat = (res==SQLITE_OK);
  144698. }else{
  144699. rc = SQLITE_NOMEM;
  144700. }
  144701. }
  144702. return rc;
  144703. }
  144704. /*
  144705. ** Implementation of xBegin() method.
  144706. */
  144707. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  144708. Fts3Table *p = (Fts3Table*)pVtab;
  144709. UNUSED_PARAMETER(pVtab);
  144710. assert( p->pSegments==0 );
  144711. assert( p->nPendingData==0 );
  144712. assert( p->inTransaction!=1 );
  144713. TESTONLY( p->inTransaction = 1 );
  144714. TESTONLY( p->mxSavepoint = -1; );
  144715. p->nLeafAdd = 0;
  144716. return fts3SetHasStat(p);
  144717. }
  144718. /*
  144719. ** Implementation of xCommit() method. This is a no-op. The contents of
  144720. ** the pending-terms hash-table have already been flushed into the database
  144721. ** by fts3SyncMethod().
  144722. */
  144723. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  144724. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  144725. UNUSED_PARAMETER(pVtab);
  144726. assert( p->nPendingData==0 );
  144727. assert( p->inTransaction!=0 );
  144728. assert( p->pSegments==0 );
  144729. TESTONLY( p->inTransaction = 0 );
  144730. TESTONLY( p->mxSavepoint = -1; );
  144731. return SQLITE_OK;
  144732. }
  144733. /*
  144734. ** Implementation of xRollback(). Discard the contents of the pending-terms
  144735. ** hash-table. Any changes made to the database are reverted by SQLite.
  144736. */
  144737. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  144738. Fts3Table *p = (Fts3Table*)pVtab;
  144739. sqlite3Fts3PendingTermsClear(p);
  144740. assert( p->inTransaction!=0 );
  144741. TESTONLY( p->inTransaction = 0 );
  144742. TESTONLY( p->mxSavepoint = -1; );
  144743. return SQLITE_OK;
  144744. }
  144745. /*
  144746. ** When called, *ppPoslist must point to the byte immediately following the
  144747. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  144748. ** moves *ppPoslist so that it instead points to the first byte of the
  144749. ** same position list.
  144750. */
  144751. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  144752. char *p = &(*ppPoslist)[-2];
  144753. char c = 0;
  144754. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  144755. while( p>pStart && (c=*p--)==0 );
  144756. /* Search backwards for a varint with value zero (the end of the previous
  144757. ** poslist). This is an 0x00 byte preceded by some byte that does not
  144758. ** have the 0x80 bit set. */
  144759. while( p>pStart && (*p & 0x80) | c ){
  144760. c = *p--;
  144761. }
  144762. assert( p==pStart || c==0 );
  144763. /* At this point p points to that preceding byte without the 0x80 bit
  144764. ** set. So to find the start of the poslist, skip forward 2 bytes then
  144765. ** over a varint.
  144766. **
  144767. ** Normally. The other case is that p==pStart and the poslist to return
  144768. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  144769. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  144770. ** is required for cases where the first byte of a doclist and the
  144771. ** doclist is empty. For example, if the first docid is 10, a doclist
  144772. ** that begins with:
  144773. **
  144774. ** 0x0A 0x00 <next docid delta varint>
  144775. */
  144776. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  144777. while( *p++&0x80 );
  144778. *ppPoslist = p;
  144779. }
  144780. /*
  144781. ** Helper function used by the implementation of the overloaded snippet(),
  144782. ** offsets() and optimize() SQL functions.
  144783. **
  144784. ** If the value passed as the third argument is a blob of size
  144785. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  144786. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  144787. ** message is written to context pContext and SQLITE_ERROR returned. The
  144788. ** string passed via zFunc is used as part of the error message.
  144789. */
  144790. static int fts3FunctionArg(
  144791. sqlite3_context *pContext, /* SQL function call context */
  144792. const char *zFunc, /* Function name */
  144793. sqlite3_value *pVal, /* argv[0] passed to function */
  144794. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  144795. ){
  144796. int rc;
  144797. *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
  144798. if( (*ppCsr)!=0 ){
  144799. rc = SQLITE_OK;
  144800. }else{
  144801. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  144802. sqlite3_result_error(pContext, zErr, -1);
  144803. sqlite3_free(zErr);
  144804. rc = SQLITE_ERROR;
  144805. }
  144806. return rc;
  144807. }
  144808. /*
  144809. ** Implementation of the snippet() function for FTS3
  144810. */
  144811. static void fts3SnippetFunc(
  144812. sqlite3_context *pContext, /* SQLite function call context */
  144813. int nVal, /* Size of apVal[] array */
  144814. sqlite3_value **apVal /* Array of arguments */
  144815. ){
  144816. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  144817. const char *zStart = "<b>";
  144818. const char *zEnd = "</b>";
  144819. const char *zEllipsis = "<b>...</b>";
  144820. int iCol = -1;
  144821. int nToken = 15; /* Default number of tokens in snippet */
  144822. /* There must be at least one argument passed to this function (otherwise
  144823. ** the non-overloaded version would have been called instead of this one).
  144824. */
  144825. assert( nVal>=1 );
  144826. if( nVal>6 ){
  144827. sqlite3_result_error(pContext,
  144828. "wrong number of arguments to function snippet()", -1);
  144829. return;
  144830. }
  144831. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  144832. switch( nVal ){
  144833. case 6: nToken = sqlite3_value_int(apVal[5]);
  144834. case 5: iCol = sqlite3_value_int(apVal[4]);
  144835. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  144836. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  144837. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  144838. }
  144839. if( !zEllipsis || !zEnd || !zStart ){
  144840. sqlite3_result_error_nomem(pContext);
  144841. }else if( nToken==0 ){
  144842. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  144843. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  144844. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  144845. }
  144846. }
  144847. /*
  144848. ** Implementation of the offsets() function for FTS3
  144849. */
  144850. static void fts3OffsetsFunc(
  144851. sqlite3_context *pContext, /* SQLite function call context */
  144852. int nVal, /* Size of argument array */
  144853. sqlite3_value **apVal /* Array of arguments */
  144854. ){
  144855. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  144856. UNUSED_PARAMETER(nVal);
  144857. assert( nVal==1 );
  144858. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  144859. assert( pCsr );
  144860. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  144861. sqlite3Fts3Offsets(pContext, pCsr);
  144862. }
  144863. }
  144864. /*
  144865. ** Implementation of the special optimize() function for FTS3. This
  144866. ** function merges all segments in the database to a single segment.
  144867. ** Example usage is:
  144868. **
  144869. ** SELECT optimize(t) FROM t LIMIT 1;
  144870. **
  144871. ** where 't' is the name of an FTS3 table.
  144872. */
  144873. static void fts3OptimizeFunc(
  144874. sqlite3_context *pContext, /* SQLite function call context */
  144875. int nVal, /* Size of argument array */
  144876. sqlite3_value **apVal /* Array of arguments */
  144877. ){
  144878. int rc; /* Return code */
  144879. Fts3Table *p; /* Virtual table handle */
  144880. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  144881. UNUSED_PARAMETER(nVal);
  144882. assert( nVal==1 );
  144883. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  144884. p = (Fts3Table *)pCursor->base.pVtab;
  144885. assert( p );
  144886. rc = sqlite3Fts3Optimize(p);
  144887. switch( rc ){
  144888. case SQLITE_OK:
  144889. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  144890. break;
  144891. case SQLITE_DONE:
  144892. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  144893. break;
  144894. default:
  144895. sqlite3_result_error_code(pContext, rc);
  144896. break;
  144897. }
  144898. }
  144899. /*
  144900. ** Implementation of the matchinfo() function for FTS3
  144901. */
  144902. static void fts3MatchinfoFunc(
  144903. sqlite3_context *pContext, /* SQLite function call context */
  144904. int nVal, /* Size of argument array */
  144905. sqlite3_value **apVal /* Array of arguments */
  144906. ){
  144907. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  144908. assert( nVal==1 || nVal==2 );
  144909. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  144910. const char *zArg = 0;
  144911. if( nVal>1 ){
  144912. zArg = (const char *)sqlite3_value_text(apVal[1]);
  144913. }
  144914. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  144915. }
  144916. }
  144917. /*
  144918. ** This routine implements the xFindFunction method for the FTS3
  144919. ** virtual table.
  144920. */
  144921. static int fts3FindFunctionMethod(
  144922. sqlite3_vtab *pVtab, /* Virtual table handle */
  144923. int nArg, /* Number of SQL function arguments */
  144924. const char *zName, /* Name of SQL function */
  144925. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  144926. void **ppArg /* Unused */
  144927. ){
  144928. struct Overloaded {
  144929. const char *zName;
  144930. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  144931. } aOverload[] = {
  144932. { "snippet", fts3SnippetFunc },
  144933. { "offsets", fts3OffsetsFunc },
  144934. { "optimize", fts3OptimizeFunc },
  144935. { "matchinfo", fts3MatchinfoFunc },
  144936. };
  144937. int i; /* Iterator variable */
  144938. UNUSED_PARAMETER(pVtab);
  144939. UNUSED_PARAMETER(nArg);
  144940. UNUSED_PARAMETER(ppArg);
  144941. for(i=0; i<SizeofArray(aOverload); i++){
  144942. if( strcmp(zName, aOverload[i].zName)==0 ){
  144943. *pxFunc = aOverload[i].xFunc;
  144944. return 1;
  144945. }
  144946. }
  144947. /* No function of the specified name was found. Return 0. */
  144948. return 0;
  144949. }
  144950. /*
  144951. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  144952. */
  144953. static int fts3RenameMethod(
  144954. sqlite3_vtab *pVtab, /* Virtual table handle */
  144955. const char *zName /* New name of table */
  144956. ){
  144957. Fts3Table *p = (Fts3Table *)pVtab;
  144958. sqlite3 *db = p->db; /* Database connection */
  144959. int rc; /* Return Code */
  144960. /* At this point it must be known if the %_stat table exists or not.
  144961. ** So bHasStat may not be 2. */
  144962. rc = fts3SetHasStat(p);
  144963. /* As it happens, the pending terms table is always empty here. This is
  144964. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  144965. ** always opens a savepoint transaction. And the xSavepoint() method
  144966. ** flushes the pending terms table. But leave the (no-op) call to
  144967. ** PendingTermsFlush() in in case that changes.
  144968. */
  144969. assert( p->nPendingData==0 );
  144970. if( rc==SQLITE_OK ){
  144971. rc = sqlite3Fts3PendingTermsFlush(p);
  144972. }
  144973. if( p->zContentTbl==0 ){
  144974. fts3DbExec(&rc, db,
  144975. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  144976. p->zDb, p->zName, zName
  144977. );
  144978. }
  144979. if( p->bHasDocsize ){
  144980. fts3DbExec(&rc, db,
  144981. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  144982. p->zDb, p->zName, zName
  144983. );
  144984. }
  144985. if( p->bHasStat ){
  144986. fts3DbExec(&rc, db,
  144987. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  144988. p->zDb, p->zName, zName
  144989. );
  144990. }
  144991. fts3DbExec(&rc, db,
  144992. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  144993. p->zDb, p->zName, zName
  144994. );
  144995. fts3DbExec(&rc, db,
  144996. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  144997. p->zDb, p->zName, zName
  144998. );
  144999. return rc;
  145000. }
  145001. /*
  145002. ** The xSavepoint() method.
  145003. **
  145004. ** Flush the contents of the pending-terms table to disk.
  145005. */
  145006. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  145007. int rc = SQLITE_OK;
  145008. UNUSED_PARAMETER(iSavepoint);
  145009. assert( ((Fts3Table *)pVtab)->inTransaction );
  145010. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  145011. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  145012. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  145013. rc = fts3SyncMethod(pVtab);
  145014. }
  145015. return rc;
  145016. }
  145017. /*
  145018. ** The xRelease() method.
  145019. **
  145020. ** This is a no-op.
  145021. */
  145022. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  145023. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  145024. UNUSED_PARAMETER(iSavepoint);
  145025. UNUSED_PARAMETER(pVtab);
  145026. assert( p->inTransaction );
  145027. assert( p->mxSavepoint >= iSavepoint );
  145028. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  145029. return SQLITE_OK;
  145030. }
  145031. /*
  145032. ** The xRollbackTo() method.
  145033. **
  145034. ** Discard the contents of the pending terms table.
  145035. */
  145036. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  145037. Fts3Table *p = (Fts3Table*)pVtab;
  145038. UNUSED_PARAMETER(iSavepoint);
  145039. assert( p->inTransaction );
  145040. assert( p->mxSavepoint >= iSavepoint );
  145041. TESTONLY( p->mxSavepoint = iSavepoint );
  145042. sqlite3Fts3PendingTermsClear(p);
  145043. return SQLITE_OK;
  145044. }
  145045. static const sqlite3_module fts3Module = {
  145046. /* iVersion */ 2,
  145047. /* xCreate */ fts3CreateMethod,
  145048. /* xConnect */ fts3ConnectMethod,
  145049. /* xBestIndex */ fts3BestIndexMethod,
  145050. /* xDisconnect */ fts3DisconnectMethod,
  145051. /* xDestroy */ fts3DestroyMethod,
  145052. /* xOpen */ fts3OpenMethod,
  145053. /* xClose */ fts3CloseMethod,
  145054. /* xFilter */ fts3FilterMethod,
  145055. /* xNext */ fts3NextMethod,
  145056. /* xEof */ fts3EofMethod,
  145057. /* xColumn */ fts3ColumnMethod,
  145058. /* xRowid */ fts3RowidMethod,
  145059. /* xUpdate */ fts3UpdateMethod,
  145060. /* xBegin */ fts3BeginMethod,
  145061. /* xSync */ fts3SyncMethod,
  145062. /* xCommit */ fts3CommitMethod,
  145063. /* xRollback */ fts3RollbackMethod,
  145064. /* xFindFunction */ fts3FindFunctionMethod,
  145065. /* xRename */ fts3RenameMethod,
  145066. /* xSavepoint */ fts3SavepointMethod,
  145067. /* xRelease */ fts3ReleaseMethod,
  145068. /* xRollbackTo */ fts3RollbackToMethod,
  145069. };
  145070. /*
  145071. ** This function is registered as the module destructor (called when an
  145072. ** FTS3 enabled database connection is closed). It frees the memory
  145073. ** allocated for the tokenizer hash table.
  145074. */
  145075. static void hashDestroy(void *p){
  145076. Fts3Hash *pHash = (Fts3Hash *)p;
  145077. sqlite3Fts3HashClear(pHash);
  145078. sqlite3_free(pHash);
  145079. }
  145080. /*
  145081. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  145082. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  145083. ** respectively. The following three forward declarations are for functions
  145084. ** declared in these files used to retrieve the respective implementations.
  145085. **
  145086. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  145087. ** to by the argument to point to the "simple" tokenizer implementation.
  145088. ** And so on.
  145089. */
  145090. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  145091. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  145092. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  145093. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  145094. #endif
  145095. #ifdef SQLITE_ENABLE_ICU
  145096. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  145097. #endif
  145098. /*
  145099. ** Initialize the fts3 extension. If this extension is built as part
  145100. ** of the sqlite library, then this function is called directly by
  145101. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  145102. ** function is called by the sqlite3_extension_init() entry point.
  145103. */
  145104. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  145105. int rc = SQLITE_OK;
  145106. Fts3Hash *pHash = 0;
  145107. const sqlite3_tokenizer_module *pSimple = 0;
  145108. const sqlite3_tokenizer_module *pPorter = 0;
  145109. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  145110. const sqlite3_tokenizer_module *pUnicode = 0;
  145111. #endif
  145112. #ifdef SQLITE_ENABLE_ICU
  145113. const sqlite3_tokenizer_module *pIcu = 0;
  145114. sqlite3Fts3IcuTokenizerModule(&pIcu);
  145115. #endif
  145116. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  145117. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  145118. #endif
  145119. #ifdef SQLITE_TEST
  145120. rc = sqlite3Fts3InitTerm(db);
  145121. if( rc!=SQLITE_OK ) return rc;
  145122. #endif
  145123. rc = sqlite3Fts3InitAux(db);
  145124. if( rc!=SQLITE_OK ) return rc;
  145125. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  145126. sqlite3Fts3PorterTokenizerModule(&pPorter);
  145127. /* Allocate and initialize the hash-table used to store tokenizers. */
  145128. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  145129. if( !pHash ){
  145130. rc = SQLITE_NOMEM;
  145131. }else{
  145132. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  145133. }
  145134. /* Load the built-in tokenizers into the hash table */
  145135. if( rc==SQLITE_OK ){
  145136. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  145137. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  145138. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  145139. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  145140. #endif
  145141. #ifdef SQLITE_ENABLE_ICU
  145142. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  145143. #endif
  145144. ){
  145145. rc = SQLITE_NOMEM;
  145146. }
  145147. }
  145148. #ifdef SQLITE_TEST
  145149. if( rc==SQLITE_OK ){
  145150. rc = sqlite3Fts3ExprInitTestInterface(db);
  145151. }
  145152. #endif
  145153. /* Create the virtual table wrapper around the hash-table and overload
  145154. ** the four scalar functions. If this is successful, register the
  145155. ** module with sqlite.
  145156. */
  145157. if( SQLITE_OK==rc
  145158. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  145159. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  145160. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  145161. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  145162. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  145163. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  145164. ){
  145165. rc = sqlite3_create_module_v2(
  145166. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  145167. );
  145168. if( rc==SQLITE_OK ){
  145169. rc = sqlite3_create_module_v2(
  145170. db, "fts4", &fts3Module, (void *)pHash, 0
  145171. );
  145172. }
  145173. if( rc==SQLITE_OK ){
  145174. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  145175. }
  145176. return rc;
  145177. }
  145178. /* An error has occurred. Delete the hash table and return the error code. */
  145179. assert( rc!=SQLITE_OK );
  145180. if( pHash ){
  145181. sqlite3Fts3HashClear(pHash);
  145182. sqlite3_free(pHash);
  145183. }
  145184. return rc;
  145185. }
  145186. /*
  145187. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  145188. ** by pExpr.
  145189. **
  145190. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  145191. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  145192. ** Fts3SegReader objects internally to provide an interface to seek or scan
  145193. ** within the union of all segments of a b-tree. Hence the name.
  145194. **
  145195. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  145196. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  145197. ** there exists prefix b-tree of the right length) then it may be traversed
  145198. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  145199. ** doclist and then traversed.
  145200. */
  145201. static void fts3EvalAllocateReaders(
  145202. Fts3Cursor *pCsr, /* FTS cursor handle */
  145203. Fts3Expr *pExpr, /* Allocate readers for this expression */
  145204. int *pnToken, /* OUT: Total number of tokens in phrase. */
  145205. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  145206. int *pRc /* IN/OUT: Error code */
  145207. ){
  145208. if( pExpr && SQLITE_OK==*pRc ){
  145209. if( pExpr->eType==FTSQUERY_PHRASE ){
  145210. int i;
  145211. int nToken = pExpr->pPhrase->nToken;
  145212. *pnToken += nToken;
  145213. for(i=0; i<nToken; i++){
  145214. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  145215. int rc = fts3TermSegReaderCursor(pCsr,
  145216. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  145217. );
  145218. if( rc!=SQLITE_OK ){
  145219. *pRc = rc;
  145220. return;
  145221. }
  145222. }
  145223. assert( pExpr->pPhrase->iDoclistToken==0 );
  145224. pExpr->pPhrase->iDoclistToken = -1;
  145225. }else{
  145226. *pnOr += (pExpr->eType==FTSQUERY_OR);
  145227. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  145228. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  145229. }
  145230. }
  145231. }
  145232. /*
  145233. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  145234. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  145235. **
  145236. ** This function assumes that pList points to a buffer allocated using
  145237. ** sqlite3_malloc(). This function takes responsibility for eventually
  145238. ** freeing the buffer.
  145239. **
  145240. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  145241. */
  145242. static int fts3EvalPhraseMergeToken(
  145243. Fts3Table *pTab, /* FTS Table pointer */
  145244. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  145245. int iToken, /* Token pList/nList corresponds to */
  145246. char *pList, /* Pointer to doclist */
  145247. int nList /* Number of bytes in pList */
  145248. ){
  145249. int rc = SQLITE_OK;
  145250. assert( iToken!=p->iDoclistToken );
  145251. if( pList==0 ){
  145252. sqlite3_free(p->doclist.aAll);
  145253. p->doclist.aAll = 0;
  145254. p->doclist.nAll = 0;
  145255. }
  145256. else if( p->iDoclistToken<0 ){
  145257. p->doclist.aAll = pList;
  145258. p->doclist.nAll = nList;
  145259. }
  145260. else if( p->doclist.aAll==0 ){
  145261. sqlite3_free(pList);
  145262. }
  145263. else {
  145264. char *pLeft;
  145265. char *pRight;
  145266. int nLeft;
  145267. int nRight;
  145268. int nDiff;
  145269. if( p->iDoclistToken<iToken ){
  145270. pLeft = p->doclist.aAll;
  145271. nLeft = p->doclist.nAll;
  145272. pRight = pList;
  145273. nRight = nList;
  145274. nDiff = iToken - p->iDoclistToken;
  145275. }else{
  145276. pRight = p->doclist.aAll;
  145277. nRight = p->doclist.nAll;
  145278. pLeft = pList;
  145279. nLeft = nList;
  145280. nDiff = p->iDoclistToken - iToken;
  145281. }
  145282. rc = fts3DoclistPhraseMerge(
  145283. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  145284. );
  145285. sqlite3_free(pLeft);
  145286. p->doclist.aAll = pRight;
  145287. p->doclist.nAll = nRight;
  145288. }
  145289. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  145290. return rc;
  145291. }
  145292. /*
  145293. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  145294. ** does not take deferred tokens into account.
  145295. **
  145296. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  145297. */
  145298. static int fts3EvalPhraseLoad(
  145299. Fts3Cursor *pCsr, /* FTS Cursor handle */
  145300. Fts3Phrase *p /* Phrase object */
  145301. ){
  145302. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  145303. int iToken;
  145304. int rc = SQLITE_OK;
  145305. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  145306. Fts3PhraseToken *pToken = &p->aToken[iToken];
  145307. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  145308. if( pToken->pSegcsr ){
  145309. int nThis = 0;
  145310. char *pThis = 0;
  145311. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  145312. if( rc==SQLITE_OK ){
  145313. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  145314. }
  145315. }
  145316. assert( pToken->pSegcsr==0 );
  145317. }
  145318. return rc;
  145319. }
  145320. /*
  145321. ** This function is called on each phrase after the position lists for
  145322. ** any deferred tokens have been loaded into memory. It updates the phrases
  145323. ** current position list to include only those positions that are really
  145324. ** instances of the phrase (after considering deferred tokens). If this
  145325. ** means that the phrase does not appear in the current row, doclist.pList
  145326. ** and doclist.nList are both zeroed.
  145327. **
  145328. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  145329. */
  145330. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  145331. int iToken; /* Used to iterate through phrase tokens */
  145332. char *aPoslist = 0; /* Position list for deferred tokens */
  145333. int nPoslist = 0; /* Number of bytes in aPoslist */
  145334. int iPrev = -1; /* Token number of previous deferred token */
  145335. assert( pPhrase->doclist.bFreeList==0 );
  145336. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  145337. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  145338. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  145339. if( pDeferred ){
  145340. char *pList;
  145341. int nList;
  145342. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  145343. if( rc!=SQLITE_OK ) return rc;
  145344. if( pList==0 ){
  145345. sqlite3_free(aPoslist);
  145346. pPhrase->doclist.pList = 0;
  145347. pPhrase->doclist.nList = 0;
  145348. return SQLITE_OK;
  145349. }else if( aPoslist==0 ){
  145350. aPoslist = pList;
  145351. nPoslist = nList;
  145352. }else{
  145353. char *aOut = pList;
  145354. char *p1 = aPoslist;
  145355. char *p2 = aOut;
  145356. assert( iPrev>=0 );
  145357. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  145358. sqlite3_free(aPoslist);
  145359. aPoslist = pList;
  145360. nPoslist = (int)(aOut - aPoslist);
  145361. if( nPoslist==0 ){
  145362. sqlite3_free(aPoslist);
  145363. pPhrase->doclist.pList = 0;
  145364. pPhrase->doclist.nList = 0;
  145365. return SQLITE_OK;
  145366. }
  145367. }
  145368. iPrev = iToken;
  145369. }
  145370. }
  145371. if( iPrev>=0 ){
  145372. int nMaxUndeferred = pPhrase->iDoclistToken;
  145373. if( nMaxUndeferred<0 ){
  145374. pPhrase->doclist.pList = aPoslist;
  145375. pPhrase->doclist.nList = nPoslist;
  145376. pPhrase->doclist.iDocid = pCsr->iPrevId;
  145377. pPhrase->doclist.bFreeList = 1;
  145378. }else{
  145379. int nDistance;
  145380. char *p1;
  145381. char *p2;
  145382. char *aOut;
  145383. if( nMaxUndeferred>iPrev ){
  145384. p1 = aPoslist;
  145385. p2 = pPhrase->doclist.pList;
  145386. nDistance = nMaxUndeferred - iPrev;
  145387. }else{
  145388. p1 = pPhrase->doclist.pList;
  145389. p2 = aPoslist;
  145390. nDistance = iPrev - nMaxUndeferred;
  145391. }
  145392. aOut = (char *)sqlite3_malloc(nPoslist+8);
  145393. if( !aOut ){
  145394. sqlite3_free(aPoslist);
  145395. return SQLITE_NOMEM;
  145396. }
  145397. pPhrase->doclist.pList = aOut;
  145398. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  145399. pPhrase->doclist.bFreeList = 1;
  145400. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  145401. }else{
  145402. sqlite3_free(aOut);
  145403. pPhrase->doclist.pList = 0;
  145404. pPhrase->doclist.nList = 0;
  145405. }
  145406. sqlite3_free(aPoslist);
  145407. }
  145408. }
  145409. return SQLITE_OK;
  145410. }
  145411. /*
  145412. ** Maximum number of tokens a phrase may have to be considered for the
  145413. ** incremental doclists strategy.
  145414. */
  145415. #define MAX_INCR_PHRASE_TOKENS 4
  145416. /*
  145417. ** This function is called for each Fts3Phrase in a full-text query
  145418. ** expression to initialize the mechanism for returning rows. Once this
  145419. ** function has been called successfully on an Fts3Phrase, it may be
  145420. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  145421. **
  145422. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  145423. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  145424. ** memory within this call.
  145425. **
  145426. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  145427. */
  145428. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  145429. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  145430. int rc = SQLITE_OK; /* Error code */
  145431. int i;
  145432. /* Determine if doclists may be loaded from disk incrementally. This is
  145433. ** possible if the bOptOk argument is true, the FTS doclists will be
  145434. ** scanned in forward order, and the phrase consists of
  145435. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  145436. ** tokens or prefix tokens that cannot use a prefix-index. */
  145437. int bHaveIncr = 0;
  145438. int bIncrOk = (bOptOk
  145439. && pCsr->bDesc==pTab->bDescIdx
  145440. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  145441. #ifdef SQLITE_TEST
  145442. && pTab->bNoIncrDoclist==0
  145443. #endif
  145444. );
  145445. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  145446. Fts3PhraseToken *pToken = &p->aToken[i];
  145447. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  145448. bIncrOk = 0;
  145449. }
  145450. if( pToken->pSegcsr ) bHaveIncr = 1;
  145451. }
  145452. if( bIncrOk && bHaveIncr ){
  145453. /* Use the incremental approach. */
  145454. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  145455. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  145456. Fts3PhraseToken *pToken = &p->aToken[i];
  145457. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  145458. if( pSegcsr ){
  145459. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  145460. }
  145461. }
  145462. p->bIncr = 1;
  145463. }else{
  145464. /* Load the full doclist for the phrase into memory. */
  145465. rc = fts3EvalPhraseLoad(pCsr, p);
  145466. p->bIncr = 0;
  145467. }
  145468. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  145469. return rc;
  145470. }
  145471. /*
  145472. ** This function is used to iterate backwards (from the end to start)
  145473. ** through doclists. It is used by this module to iterate through phrase
  145474. ** doclists in reverse and by the fts3_write.c module to iterate through
  145475. ** pending-terms lists when writing to databases with "order=desc".
  145476. **
  145477. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  145478. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  145479. ** function iterates from the end of the doclist to the beginning.
  145480. */
  145481. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  145482. int bDescIdx, /* True if the doclist is desc */
  145483. char *aDoclist, /* Pointer to entire doclist */
  145484. int nDoclist, /* Length of aDoclist in bytes */
  145485. char **ppIter, /* IN/OUT: Iterator pointer */
  145486. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  145487. int *pnList, /* OUT: List length pointer */
  145488. u8 *pbEof /* OUT: End-of-file flag */
  145489. ){
  145490. char *p = *ppIter;
  145491. assert( nDoclist>0 );
  145492. assert( *pbEof==0 );
  145493. assert( p || *piDocid==0 );
  145494. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  145495. if( p==0 ){
  145496. sqlite3_int64 iDocid = 0;
  145497. char *pNext = 0;
  145498. char *pDocid = aDoclist;
  145499. char *pEnd = &aDoclist[nDoclist];
  145500. int iMul = 1;
  145501. while( pDocid<pEnd ){
  145502. sqlite3_int64 iDelta;
  145503. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  145504. iDocid += (iMul * iDelta);
  145505. pNext = pDocid;
  145506. fts3PoslistCopy(0, &pDocid);
  145507. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  145508. iMul = (bDescIdx ? -1 : 1);
  145509. }
  145510. *pnList = (int)(pEnd - pNext);
  145511. *ppIter = pNext;
  145512. *piDocid = iDocid;
  145513. }else{
  145514. int iMul = (bDescIdx ? -1 : 1);
  145515. sqlite3_int64 iDelta;
  145516. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  145517. *piDocid -= (iMul * iDelta);
  145518. if( p==aDoclist ){
  145519. *pbEof = 1;
  145520. }else{
  145521. char *pSave = p;
  145522. fts3ReversePoslist(aDoclist, &p);
  145523. *pnList = (int)(pSave - p);
  145524. }
  145525. *ppIter = p;
  145526. }
  145527. }
  145528. /*
  145529. ** Iterate forwards through a doclist.
  145530. */
  145531. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  145532. int bDescIdx, /* True if the doclist is desc */
  145533. char *aDoclist, /* Pointer to entire doclist */
  145534. int nDoclist, /* Length of aDoclist in bytes */
  145535. char **ppIter, /* IN/OUT: Iterator pointer */
  145536. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  145537. u8 *pbEof /* OUT: End-of-file flag */
  145538. ){
  145539. char *p = *ppIter;
  145540. assert( nDoclist>0 );
  145541. assert( *pbEof==0 );
  145542. assert( p || *piDocid==0 );
  145543. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  145544. if( p==0 ){
  145545. p = aDoclist;
  145546. p += sqlite3Fts3GetVarint(p, piDocid);
  145547. }else{
  145548. fts3PoslistCopy(0, &p);
  145549. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  145550. if( p>=&aDoclist[nDoclist] ){
  145551. *pbEof = 1;
  145552. }else{
  145553. sqlite3_int64 iVar;
  145554. p += sqlite3Fts3GetVarint(p, &iVar);
  145555. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  145556. }
  145557. }
  145558. *ppIter = p;
  145559. }
  145560. /*
  145561. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  145562. ** to true if EOF is reached.
  145563. */
  145564. static void fts3EvalDlPhraseNext(
  145565. Fts3Table *pTab,
  145566. Fts3Doclist *pDL,
  145567. u8 *pbEof
  145568. ){
  145569. char *pIter; /* Used to iterate through aAll */
  145570. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  145571. if( pDL->pNextDocid ){
  145572. pIter = pDL->pNextDocid;
  145573. }else{
  145574. pIter = pDL->aAll;
  145575. }
  145576. if( pIter>=pEnd ){
  145577. /* We have already reached the end of this doclist. EOF. */
  145578. *pbEof = 1;
  145579. }else{
  145580. sqlite3_int64 iDelta;
  145581. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  145582. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  145583. pDL->iDocid += iDelta;
  145584. }else{
  145585. pDL->iDocid -= iDelta;
  145586. }
  145587. pDL->pList = pIter;
  145588. fts3PoslistCopy(0, &pIter);
  145589. pDL->nList = (int)(pIter - pDL->pList);
  145590. /* pIter now points just past the 0x00 that terminates the position-
  145591. ** list for document pDL->iDocid. However, if this position-list was
  145592. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  145593. ** point to the start of the next docid value. The following line deals
  145594. ** with this case by advancing pIter past the zero-padding added by
  145595. ** fts3EvalNearTrim(). */
  145596. while( pIter<pEnd && *pIter==0 ) pIter++;
  145597. pDL->pNextDocid = pIter;
  145598. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  145599. *pbEof = 0;
  145600. }
  145601. }
  145602. /*
  145603. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  145604. */
  145605. typedef struct TokenDoclist TokenDoclist;
  145606. struct TokenDoclist {
  145607. int bIgnore;
  145608. sqlite3_int64 iDocid;
  145609. char *pList;
  145610. int nList;
  145611. };
  145612. /*
  145613. ** Token pToken is an incrementally loaded token that is part of a
  145614. ** multi-token phrase. Advance it to the next matching document in the
  145615. ** database and populate output variable *p with the details of the new
  145616. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  145617. **
  145618. ** If an error occurs, return an SQLite error code. Otherwise, return
  145619. ** SQLITE_OK.
  145620. */
  145621. static int incrPhraseTokenNext(
  145622. Fts3Table *pTab, /* Virtual table handle */
  145623. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  145624. int iToken, /* Specific token to advance */
  145625. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  145626. u8 *pbEof /* OUT: True if iterator is at EOF */
  145627. ){
  145628. int rc = SQLITE_OK;
  145629. if( pPhrase->iDoclistToken==iToken ){
  145630. assert( p->bIgnore==0 );
  145631. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  145632. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  145633. p->pList = pPhrase->doclist.pList;
  145634. p->nList = pPhrase->doclist.nList;
  145635. p->iDocid = pPhrase->doclist.iDocid;
  145636. }else{
  145637. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  145638. assert( pToken->pDeferred==0 );
  145639. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  145640. if( pToken->pSegcsr ){
  145641. assert( p->bIgnore==0 );
  145642. rc = sqlite3Fts3MsrIncrNext(
  145643. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  145644. );
  145645. if( p->pList==0 ) *pbEof = 1;
  145646. }else{
  145647. p->bIgnore = 1;
  145648. }
  145649. }
  145650. return rc;
  145651. }
  145652. /*
  145653. ** The phrase iterator passed as the second argument:
  145654. **
  145655. ** * features at least one token that uses an incremental doclist, and
  145656. **
  145657. ** * does not contain any deferred tokens.
  145658. **
  145659. ** Advance it to the next matching documnent in the database and populate
  145660. ** the Fts3Doclist.pList and nList fields.
  145661. **
  145662. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  145663. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  145664. ** successfully advanced, *pbEof is set to 0.
  145665. **
  145666. ** If an error occurs, return an SQLite error code. Otherwise, return
  145667. ** SQLITE_OK.
  145668. */
  145669. static int fts3EvalIncrPhraseNext(
  145670. Fts3Cursor *pCsr, /* FTS Cursor handle */
  145671. Fts3Phrase *p, /* Phrase object to advance to next docid */
  145672. u8 *pbEof /* OUT: Set to 1 if EOF */
  145673. ){
  145674. int rc = SQLITE_OK;
  145675. Fts3Doclist *pDL = &p->doclist;
  145676. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  145677. u8 bEof = 0;
  145678. /* This is only called if it is guaranteed that the phrase has at least
  145679. ** one incremental token. In which case the bIncr flag is set. */
  145680. assert( p->bIncr==1 );
  145681. if( p->nToken==1 ){
  145682. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  145683. &pDL->iDocid, &pDL->pList, &pDL->nList
  145684. );
  145685. if( pDL->pList==0 ) bEof = 1;
  145686. }else{
  145687. int bDescDoclist = pCsr->bDesc;
  145688. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  145689. memset(a, 0, sizeof(a));
  145690. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  145691. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  145692. while( bEof==0 ){
  145693. int bMaxSet = 0;
  145694. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  145695. int i; /* Used to iterate through tokens */
  145696. /* Advance the iterator for each token in the phrase once. */
  145697. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  145698. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  145699. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  145700. iMax = a[i].iDocid;
  145701. bMaxSet = 1;
  145702. }
  145703. }
  145704. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  145705. assert( rc!=SQLITE_OK || bMaxSet );
  145706. /* Keep advancing iterators until they all point to the same document */
  145707. for(i=0; i<p->nToken; i++){
  145708. while( rc==SQLITE_OK && bEof==0
  145709. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  145710. ){
  145711. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  145712. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  145713. iMax = a[i].iDocid;
  145714. i = 0;
  145715. }
  145716. }
  145717. }
  145718. /* Check if the current entries really are a phrase match */
  145719. if( bEof==0 ){
  145720. int nList = 0;
  145721. int nByte = a[p->nToken-1].nList;
  145722. char *aDoclist = sqlite3_malloc(nByte+1);
  145723. if( !aDoclist ) return SQLITE_NOMEM;
  145724. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  145725. for(i=0; i<(p->nToken-1); i++){
  145726. if( a[i].bIgnore==0 ){
  145727. char *pL = a[i].pList;
  145728. char *pR = aDoclist;
  145729. char *pOut = aDoclist;
  145730. int nDist = p->nToken-1-i;
  145731. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  145732. if( res==0 ) break;
  145733. nList = (int)(pOut - aDoclist);
  145734. }
  145735. }
  145736. if( i==(p->nToken-1) ){
  145737. pDL->iDocid = iMax;
  145738. pDL->pList = aDoclist;
  145739. pDL->nList = nList;
  145740. pDL->bFreeList = 1;
  145741. break;
  145742. }
  145743. sqlite3_free(aDoclist);
  145744. }
  145745. }
  145746. }
  145747. *pbEof = bEof;
  145748. return rc;
  145749. }
  145750. /*
  145751. ** Attempt to move the phrase iterator to point to the next matching docid.
  145752. ** If an error occurs, return an SQLite error code. Otherwise, return
  145753. ** SQLITE_OK.
  145754. **
  145755. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  145756. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  145757. ** successfully advanced, *pbEof is set to 0.
  145758. */
  145759. static int fts3EvalPhraseNext(
  145760. Fts3Cursor *pCsr, /* FTS Cursor handle */
  145761. Fts3Phrase *p, /* Phrase object to advance to next docid */
  145762. u8 *pbEof /* OUT: Set to 1 if EOF */
  145763. ){
  145764. int rc = SQLITE_OK;
  145765. Fts3Doclist *pDL = &p->doclist;
  145766. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  145767. if( p->bIncr ){
  145768. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  145769. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  145770. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  145771. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  145772. );
  145773. pDL->pList = pDL->pNextDocid;
  145774. }else{
  145775. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  145776. }
  145777. return rc;
  145778. }
  145779. /*
  145780. **
  145781. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  145782. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  145783. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  145784. ** expressions for which all descendent tokens are deferred.
  145785. **
  145786. ** If parameter bOptOk is zero, then it is guaranteed that the
  145787. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  145788. ** each phrase in the expression (subject to deferred token processing).
  145789. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  145790. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  145791. **
  145792. ** If an error occurs within this function, *pRc is set to an SQLite error
  145793. ** code before returning.
  145794. */
  145795. static void fts3EvalStartReaders(
  145796. Fts3Cursor *pCsr, /* FTS Cursor handle */
  145797. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  145798. int *pRc /* IN/OUT: Error code */
  145799. ){
  145800. if( pExpr && SQLITE_OK==*pRc ){
  145801. if( pExpr->eType==FTSQUERY_PHRASE ){
  145802. int nToken = pExpr->pPhrase->nToken;
  145803. if( nToken ){
  145804. int i;
  145805. for(i=0; i<nToken; i++){
  145806. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  145807. }
  145808. pExpr->bDeferred = (i==nToken);
  145809. }
  145810. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  145811. }else{
  145812. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  145813. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  145814. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  145815. }
  145816. }
  145817. }
  145818. /*
  145819. ** An array of the following structures is assembled as part of the process
  145820. ** of selecting tokens to defer before the query starts executing (as part
  145821. ** of the xFilter() method). There is one element in the array for each
  145822. ** token in the FTS expression.
  145823. **
  145824. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  145825. ** to phrases that are connected only by AND and NEAR operators (not OR or
  145826. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  145827. ** separately. The root of a tokens AND/NEAR cluster is stored in
  145828. ** Fts3TokenAndCost.pRoot.
  145829. */
  145830. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  145831. struct Fts3TokenAndCost {
  145832. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  145833. int iToken; /* Position of token in phrase */
  145834. Fts3PhraseToken *pToken; /* The token itself */
  145835. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  145836. int nOvfl; /* Number of overflow pages to load doclist */
  145837. int iCol; /* The column the token must match */
  145838. };
  145839. /*
  145840. ** This function is used to populate an allocated Fts3TokenAndCost array.
  145841. **
  145842. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  145843. ** Otherwise, if an error occurs during execution, *pRc is set to an
  145844. ** SQLite error code.
  145845. */
  145846. static void fts3EvalTokenCosts(
  145847. Fts3Cursor *pCsr, /* FTS Cursor handle */
  145848. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  145849. Fts3Expr *pExpr, /* Expression to consider */
  145850. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  145851. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  145852. int *pRc /* IN/OUT: Error code */
  145853. ){
  145854. if( *pRc==SQLITE_OK ){
  145855. if( pExpr->eType==FTSQUERY_PHRASE ){
  145856. Fts3Phrase *pPhrase = pExpr->pPhrase;
  145857. int i;
  145858. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  145859. Fts3TokenAndCost *pTC = (*ppTC)++;
  145860. pTC->pPhrase = pPhrase;
  145861. pTC->iToken = i;
  145862. pTC->pRoot = pRoot;
  145863. pTC->pToken = &pPhrase->aToken[i];
  145864. pTC->iCol = pPhrase->iColumn;
  145865. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  145866. }
  145867. }else if( pExpr->eType!=FTSQUERY_NOT ){
  145868. assert( pExpr->eType==FTSQUERY_OR
  145869. || pExpr->eType==FTSQUERY_AND
  145870. || pExpr->eType==FTSQUERY_NEAR
  145871. );
  145872. assert( pExpr->pLeft && pExpr->pRight );
  145873. if( pExpr->eType==FTSQUERY_OR ){
  145874. pRoot = pExpr->pLeft;
  145875. **ppOr = pRoot;
  145876. (*ppOr)++;
  145877. }
  145878. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  145879. if( pExpr->eType==FTSQUERY_OR ){
  145880. pRoot = pExpr->pRight;
  145881. **ppOr = pRoot;
  145882. (*ppOr)++;
  145883. }
  145884. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  145885. }
  145886. }
  145887. }
  145888. /*
  145889. ** Determine the average document (row) size in pages. If successful,
  145890. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  145891. ** an SQLite error code.
  145892. **
  145893. ** The average document size in pages is calculated by first calculating
  145894. ** determining the average size in bytes, B. If B is less than the amount
  145895. ** of data that will fit on a single leaf page of an intkey table in
  145896. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  145897. ** the number of overflow pages consumed by a record B bytes in size.
  145898. */
  145899. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  145900. int rc = SQLITE_OK;
  145901. if( pCsr->nRowAvg==0 ){
  145902. /* The average document size, which is required to calculate the cost
  145903. ** of each doclist, has not yet been determined. Read the required
  145904. ** data from the %_stat table to calculate it.
  145905. **
  145906. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  145907. ** varints, where nCol is the number of columns in the FTS3 table.
  145908. ** The first varint is the number of documents currently stored in
  145909. ** the table. The following nCol varints contain the total amount of
  145910. ** data stored in all rows of each column of the table, from left
  145911. ** to right.
  145912. */
  145913. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  145914. sqlite3_stmt *pStmt;
  145915. sqlite3_int64 nDoc = 0;
  145916. sqlite3_int64 nByte = 0;
  145917. const char *pEnd;
  145918. const char *a;
  145919. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  145920. if( rc!=SQLITE_OK ) return rc;
  145921. a = sqlite3_column_blob(pStmt, 0);
  145922. assert( a );
  145923. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  145924. a += sqlite3Fts3GetVarint(a, &nDoc);
  145925. while( a<pEnd ){
  145926. a += sqlite3Fts3GetVarint(a, &nByte);
  145927. }
  145928. if( nDoc==0 || nByte==0 ){
  145929. sqlite3_reset(pStmt);
  145930. return FTS_CORRUPT_VTAB;
  145931. }
  145932. pCsr->nDoc = nDoc;
  145933. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  145934. assert( pCsr->nRowAvg>0 );
  145935. rc = sqlite3_reset(pStmt);
  145936. }
  145937. *pnPage = pCsr->nRowAvg;
  145938. return rc;
  145939. }
  145940. /*
  145941. ** This function is called to select the tokens (if any) that will be
  145942. ** deferred. The array aTC[] has already been populated when this is
  145943. ** called.
  145944. **
  145945. ** This function is called once for each AND/NEAR cluster in the
  145946. ** expression. Each invocation determines which tokens to defer within
  145947. ** the cluster with root node pRoot. See comments above the definition
  145948. ** of struct Fts3TokenAndCost for more details.
  145949. **
  145950. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  145951. ** called on each token to defer. Otherwise, an SQLite error code is
  145952. ** returned.
  145953. */
  145954. static int fts3EvalSelectDeferred(
  145955. Fts3Cursor *pCsr, /* FTS Cursor handle */
  145956. Fts3Expr *pRoot, /* Consider tokens with this root node */
  145957. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  145958. int nTC /* Number of entries in aTC[] */
  145959. ){
  145960. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  145961. int nDocSize = 0; /* Number of pages per doc loaded */
  145962. int rc = SQLITE_OK; /* Return code */
  145963. int ii; /* Iterator variable for various purposes */
  145964. int nOvfl = 0; /* Total overflow pages used by doclists */
  145965. int nToken = 0; /* Total number of tokens in cluster */
  145966. int nMinEst = 0; /* The minimum count for any phrase so far. */
  145967. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  145968. /* Tokens are never deferred for FTS tables created using the content=xxx
  145969. ** option. The reason being that it is not guaranteed that the content
  145970. ** table actually contains the same data as the index. To prevent this from
  145971. ** causing any problems, the deferred token optimization is completely
  145972. ** disabled for content=xxx tables. */
  145973. if( pTab->zContentTbl ){
  145974. return SQLITE_OK;
  145975. }
  145976. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  145977. ** associated with the tokens spill onto overflow pages, or if there is
  145978. ** only 1 token, exit early. No tokens to defer in this case. */
  145979. for(ii=0; ii<nTC; ii++){
  145980. if( aTC[ii].pRoot==pRoot ){
  145981. nOvfl += aTC[ii].nOvfl;
  145982. nToken++;
  145983. }
  145984. }
  145985. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  145986. /* Obtain the average docsize (in pages). */
  145987. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  145988. assert( rc!=SQLITE_OK || nDocSize>0 );
  145989. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  145990. ** of the number of overflow pages that will be loaded by the pager layer
  145991. ** to retrieve the entire doclist for the token from the full-text index.
  145992. ** Load the doclists for tokens that are either:
  145993. **
  145994. ** a. The cheapest token in the entire query (i.e. the one visited by the
  145995. ** first iteration of this loop), or
  145996. **
  145997. ** b. Part of a multi-token phrase.
  145998. **
  145999. ** After each token doclist is loaded, merge it with the others from the
  146000. ** same phrase and count the number of documents that the merged doclist
  146001. ** contains. Set variable "nMinEst" to the smallest number of documents in
  146002. ** any phrase doclist for which 1 or more token doclists have been loaded.
  146003. ** Let nOther be the number of other phrases for which it is certain that
  146004. ** one or more tokens will not be deferred.
  146005. **
  146006. ** Then, for each token, defer it if loading the doclist would result in
  146007. ** loading N or more overflow pages into memory, where N is computed as:
  146008. **
  146009. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  146010. */
  146011. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  146012. int iTC; /* Used to iterate through aTC[] array. */
  146013. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  146014. /* Set pTC to point to the cheapest remaining token. */
  146015. for(iTC=0; iTC<nTC; iTC++){
  146016. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  146017. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  146018. ){
  146019. pTC = &aTC[iTC];
  146020. }
  146021. }
  146022. assert( pTC );
  146023. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  146024. /* The number of overflow pages to load for this (and therefore all
  146025. ** subsequent) tokens is greater than the estimated number of pages
  146026. ** that will be loaded if all subsequent tokens are deferred.
  146027. */
  146028. Fts3PhraseToken *pToken = pTC->pToken;
  146029. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  146030. fts3SegReaderCursorFree(pToken->pSegcsr);
  146031. pToken->pSegcsr = 0;
  146032. }else{
  146033. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  146034. ** for-loop. Except, limit the value to 2^24 to prevent it from
  146035. ** overflowing the 32-bit integer it is stored in. */
  146036. if( ii<12 ) nLoad4 = nLoad4*4;
  146037. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  146038. /* Either this is the cheapest token in the entire query, or it is
  146039. ** part of a multi-token phrase. Either way, the entire doclist will
  146040. ** (eventually) be loaded into memory. It may as well be now. */
  146041. Fts3PhraseToken *pToken = pTC->pToken;
  146042. int nList = 0;
  146043. char *pList = 0;
  146044. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  146045. assert( rc==SQLITE_OK || pList==0 );
  146046. if( rc==SQLITE_OK ){
  146047. rc = fts3EvalPhraseMergeToken(
  146048. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  146049. );
  146050. }
  146051. if( rc==SQLITE_OK ){
  146052. int nCount;
  146053. nCount = fts3DoclistCountDocids(
  146054. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  146055. );
  146056. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  146057. }
  146058. }
  146059. }
  146060. pTC->pToken = 0;
  146061. }
  146062. return rc;
  146063. }
  146064. /*
  146065. ** This function is called from within the xFilter method. It initializes
  146066. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  146067. ** the results of a query, the caller does:
  146068. **
  146069. ** fts3EvalStart(pCsr);
  146070. ** while( 1 ){
  146071. ** fts3EvalNext(pCsr);
  146072. ** if( pCsr->bEof ) break;
  146073. ** ... return row pCsr->iPrevId to the caller ...
  146074. ** }
  146075. */
  146076. static int fts3EvalStart(Fts3Cursor *pCsr){
  146077. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  146078. int rc = SQLITE_OK;
  146079. int nToken = 0;
  146080. int nOr = 0;
  146081. /* Allocate a MultiSegReader for each token in the expression. */
  146082. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  146083. /* Determine which, if any, tokens in the expression should be deferred. */
  146084. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  146085. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  146086. Fts3TokenAndCost *aTC;
  146087. Fts3Expr **apOr;
  146088. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  146089. sizeof(Fts3TokenAndCost) * nToken
  146090. + sizeof(Fts3Expr *) * nOr * 2
  146091. );
  146092. apOr = (Fts3Expr **)&aTC[nToken];
  146093. if( !aTC ){
  146094. rc = SQLITE_NOMEM;
  146095. }else{
  146096. int ii;
  146097. Fts3TokenAndCost *pTC = aTC;
  146098. Fts3Expr **ppOr = apOr;
  146099. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  146100. nToken = (int)(pTC-aTC);
  146101. nOr = (int)(ppOr-apOr);
  146102. if( rc==SQLITE_OK ){
  146103. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  146104. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  146105. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  146106. }
  146107. }
  146108. sqlite3_free(aTC);
  146109. }
  146110. }
  146111. #endif
  146112. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  146113. return rc;
  146114. }
  146115. /*
  146116. ** Invalidate the current position list for phrase pPhrase.
  146117. */
  146118. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  146119. if( pPhrase->doclist.bFreeList ){
  146120. sqlite3_free(pPhrase->doclist.pList);
  146121. }
  146122. pPhrase->doclist.pList = 0;
  146123. pPhrase->doclist.nList = 0;
  146124. pPhrase->doclist.bFreeList = 0;
  146125. }
  146126. /*
  146127. ** This function is called to edit the position list associated with
  146128. ** the phrase object passed as the fifth argument according to a NEAR
  146129. ** condition. For example:
  146130. **
  146131. ** abc NEAR/5 "def ghi"
  146132. **
  146133. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  146134. ** the example above). When this function is called, *paPoslist points to
  146135. ** the position list, and *pnToken is the number of phrase tokens in, the
  146136. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  146137. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  146138. ** the position list associated with phrase "abc".
  146139. **
  146140. ** All positions in the pPhrase position list that are not sufficiently
  146141. ** close to a position in the *paPoslist position list are removed. If this
  146142. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  146143. **
  146144. ** Before returning, *paPoslist is set to point to the position lsit
  146145. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  146146. ** pPhrase.
  146147. */
  146148. static int fts3EvalNearTrim(
  146149. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  146150. char *aTmp, /* Temporary space to use */
  146151. char **paPoslist, /* IN/OUT: Position list */
  146152. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  146153. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  146154. ){
  146155. int nParam1 = nNear + pPhrase->nToken;
  146156. int nParam2 = nNear + *pnToken;
  146157. int nNew;
  146158. char *p2;
  146159. char *pOut;
  146160. int res;
  146161. assert( pPhrase->doclist.pList );
  146162. p2 = pOut = pPhrase->doclist.pList;
  146163. res = fts3PoslistNearMerge(
  146164. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  146165. );
  146166. if( res ){
  146167. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  146168. assert( pPhrase->doclist.pList[nNew]=='\0' );
  146169. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  146170. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  146171. pPhrase->doclist.nList = nNew;
  146172. *paPoslist = pPhrase->doclist.pList;
  146173. *pnToken = pPhrase->nToken;
  146174. }
  146175. return res;
  146176. }
  146177. /*
  146178. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  146179. ** Otherwise, it advances the expression passed as the second argument to
  146180. ** point to the next matching row in the database. Expressions iterate through
  146181. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  146182. ** or descending if it is non-zero.
  146183. **
  146184. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  146185. ** successful, the following variables in pExpr are set:
  146186. **
  146187. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  146188. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  146189. **
  146190. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  146191. ** at EOF, then the following variables are populated with the position list
  146192. ** for the phrase for the visited row:
  146193. **
  146194. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  146195. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  146196. **
  146197. ** It says above that this function advances the expression to the next
  146198. ** matching row. This is usually true, but there are the following exceptions:
  146199. **
  146200. ** 1. Deferred tokens are not taken into account. If a phrase consists
  146201. ** entirely of deferred tokens, it is assumed to match every row in
  146202. ** the db. In this case the position-list is not populated at all.
  146203. **
  146204. ** Or, if a phrase contains one or more deferred tokens and one or
  146205. ** more non-deferred tokens, then the expression is advanced to the
  146206. ** next possible match, considering only non-deferred tokens. In other
  146207. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  146208. ** is advanced to the next row that contains an instance of "A * C",
  146209. ** where "*" may match any single token. The position list in this case
  146210. ** is populated as for "A * C" before returning.
  146211. **
  146212. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  146213. ** advanced to point to the next row that matches "x AND y".
  146214. **
  146215. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  146216. ** really a match, taking into account deferred tokens and NEAR operators.
  146217. */
  146218. static void fts3EvalNextRow(
  146219. Fts3Cursor *pCsr, /* FTS Cursor handle */
  146220. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  146221. int *pRc /* IN/OUT: Error code */
  146222. ){
  146223. if( *pRc==SQLITE_OK ){
  146224. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  146225. assert( pExpr->bEof==0 );
  146226. pExpr->bStart = 1;
  146227. switch( pExpr->eType ){
  146228. case FTSQUERY_NEAR:
  146229. case FTSQUERY_AND: {
  146230. Fts3Expr *pLeft = pExpr->pLeft;
  146231. Fts3Expr *pRight = pExpr->pRight;
  146232. assert( !pLeft->bDeferred || !pRight->bDeferred );
  146233. if( pLeft->bDeferred ){
  146234. /* LHS is entirely deferred. So we assume it matches every row.
  146235. ** Advance the RHS iterator to find the next row visited. */
  146236. fts3EvalNextRow(pCsr, pRight, pRc);
  146237. pExpr->iDocid = pRight->iDocid;
  146238. pExpr->bEof = pRight->bEof;
  146239. }else if( pRight->bDeferred ){
  146240. /* RHS is entirely deferred. So we assume it matches every row.
  146241. ** Advance the LHS iterator to find the next row visited. */
  146242. fts3EvalNextRow(pCsr, pLeft, pRc);
  146243. pExpr->iDocid = pLeft->iDocid;
  146244. pExpr->bEof = pLeft->bEof;
  146245. }else{
  146246. /* Neither the RHS or LHS are deferred. */
  146247. fts3EvalNextRow(pCsr, pLeft, pRc);
  146248. fts3EvalNextRow(pCsr, pRight, pRc);
  146249. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  146250. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  146251. if( iDiff==0 ) break;
  146252. if( iDiff<0 ){
  146253. fts3EvalNextRow(pCsr, pLeft, pRc);
  146254. }else{
  146255. fts3EvalNextRow(pCsr, pRight, pRc);
  146256. }
  146257. }
  146258. pExpr->iDocid = pLeft->iDocid;
  146259. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  146260. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  146261. assert( pRight->eType==FTSQUERY_PHRASE );
  146262. if( pRight->pPhrase->doclist.aAll ){
  146263. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  146264. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  146265. memset(pDl->pList, 0, pDl->nList);
  146266. fts3EvalNextRow(pCsr, pRight, pRc);
  146267. }
  146268. }
  146269. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  146270. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  146271. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  146272. memset(pDl->pList, 0, pDl->nList);
  146273. fts3EvalNextRow(pCsr, pLeft, pRc);
  146274. }
  146275. }
  146276. }
  146277. }
  146278. break;
  146279. }
  146280. case FTSQUERY_OR: {
  146281. Fts3Expr *pLeft = pExpr->pLeft;
  146282. Fts3Expr *pRight = pExpr->pRight;
  146283. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  146284. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  146285. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  146286. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  146287. fts3EvalNextRow(pCsr, pLeft, pRc);
  146288. }else if( pLeft->bEof || iCmp>0 ){
  146289. fts3EvalNextRow(pCsr, pRight, pRc);
  146290. }else{
  146291. fts3EvalNextRow(pCsr, pLeft, pRc);
  146292. fts3EvalNextRow(pCsr, pRight, pRc);
  146293. }
  146294. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  146295. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  146296. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  146297. pExpr->iDocid = pLeft->iDocid;
  146298. }else{
  146299. pExpr->iDocid = pRight->iDocid;
  146300. }
  146301. break;
  146302. }
  146303. case FTSQUERY_NOT: {
  146304. Fts3Expr *pLeft = pExpr->pLeft;
  146305. Fts3Expr *pRight = pExpr->pRight;
  146306. if( pRight->bStart==0 ){
  146307. fts3EvalNextRow(pCsr, pRight, pRc);
  146308. assert( *pRc!=SQLITE_OK || pRight->bStart );
  146309. }
  146310. fts3EvalNextRow(pCsr, pLeft, pRc);
  146311. if( pLeft->bEof==0 ){
  146312. while( !*pRc
  146313. && !pRight->bEof
  146314. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  146315. ){
  146316. fts3EvalNextRow(pCsr, pRight, pRc);
  146317. }
  146318. }
  146319. pExpr->iDocid = pLeft->iDocid;
  146320. pExpr->bEof = pLeft->bEof;
  146321. break;
  146322. }
  146323. default: {
  146324. Fts3Phrase *pPhrase = pExpr->pPhrase;
  146325. fts3EvalInvalidatePoslist(pPhrase);
  146326. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  146327. pExpr->iDocid = pPhrase->doclist.iDocid;
  146328. break;
  146329. }
  146330. }
  146331. }
  146332. }
  146333. /*
  146334. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  146335. ** cluster, then this function returns 1 immediately.
  146336. **
  146337. ** Otherwise, it checks if the current row really does match the NEAR
  146338. ** expression, using the data currently stored in the position lists
  146339. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  146340. **
  146341. ** If the current row is a match, the position list associated with each
  146342. ** phrase in the NEAR expression is edited in place to contain only those
  146343. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  146344. ** constraints. In this case it returns 1. If the NEAR expression does not
  146345. ** match the current row, 0 is returned. The position lists may or may not
  146346. ** be edited if 0 is returned.
  146347. */
  146348. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  146349. int res = 1;
  146350. /* The following block runs if pExpr is the root of a NEAR query.
  146351. ** For example, the query:
  146352. **
  146353. ** "w" NEAR "x" NEAR "y" NEAR "z"
  146354. **
  146355. ** which is represented in tree form as:
  146356. **
  146357. ** |
  146358. ** +--NEAR--+ <-- root of NEAR query
  146359. ** | |
  146360. ** +--NEAR--+ "z"
  146361. ** | |
  146362. ** +--NEAR--+ "y"
  146363. ** | |
  146364. ** "w" "x"
  146365. **
  146366. ** The right-hand child of a NEAR node is always a phrase. The
  146367. ** left-hand child may be either a phrase or a NEAR node. There are
  146368. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  146369. */
  146370. if( *pRc==SQLITE_OK
  146371. && pExpr->eType==FTSQUERY_NEAR
  146372. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  146373. ){
  146374. Fts3Expr *p;
  146375. int nTmp = 0; /* Bytes of temp space */
  146376. char *aTmp; /* Temp space for PoslistNearMerge() */
  146377. /* Allocate temporary working space. */
  146378. for(p=pExpr; p->pLeft; p=p->pLeft){
  146379. assert( p->pRight->pPhrase->doclist.nList>0 );
  146380. nTmp += p->pRight->pPhrase->doclist.nList;
  146381. }
  146382. nTmp += p->pPhrase->doclist.nList;
  146383. aTmp = sqlite3_malloc(nTmp*2);
  146384. if( !aTmp ){
  146385. *pRc = SQLITE_NOMEM;
  146386. res = 0;
  146387. }else{
  146388. char *aPoslist = p->pPhrase->doclist.pList;
  146389. int nToken = p->pPhrase->nToken;
  146390. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  146391. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  146392. int nNear = p->nNear;
  146393. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  146394. }
  146395. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  146396. nToken = pExpr->pRight->pPhrase->nToken;
  146397. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  146398. int nNear;
  146399. Fts3Phrase *pPhrase;
  146400. assert( p->pParent && p->pParent->pLeft==p );
  146401. nNear = p->pParent->nNear;
  146402. pPhrase = (
  146403. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  146404. );
  146405. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  146406. }
  146407. }
  146408. sqlite3_free(aTmp);
  146409. }
  146410. return res;
  146411. }
  146412. /*
  146413. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  146414. ** Assuming no error occurs or has occurred, It returns non-zero if the
  146415. ** expression passed as the second argument matches the row that pCsr
  146416. ** currently points to, or zero if it does not.
  146417. **
  146418. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  146419. ** If an error occurs during execution of this function, *pRc is set to
  146420. ** the appropriate SQLite error code. In this case the returned value is
  146421. ** undefined.
  146422. */
  146423. static int fts3EvalTestExpr(
  146424. Fts3Cursor *pCsr, /* FTS cursor handle */
  146425. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  146426. int *pRc /* IN/OUT: Error code */
  146427. ){
  146428. int bHit = 1; /* Return value */
  146429. if( *pRc==SQLITE_OK ){
  146430. switch( pExpr->eType ){
  146431. case FTSQUERY_NEAR:
  146432. case FTSQUERY_AND:
  146433. bHit = (
  146434. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  146435. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  146436. && fts3EvalNearTest(pExpr, pRc)
  146437. );
  146438. /* If the NEAR expression does not match any rows, zero the doclist for
  146439. ** all phrases involved in the NEAR. This is because the snippet(),
  146440. ** offsets() and matchinfo() functions are not supposed to recognize
  146441. ** any instances of phrases that are part of unmatched NEAR queries.
  146442. ** For example if this expression:
  146443. **
  146444. ** ... MATCH 'a OR (b NEAR c)'
  146445. **
  146446. ** is matched against a row containing:
  146447. **
  146448. ** 'a b d e'
  146449. **
  146450. ** then any snippet() should ony highlight the "a" term, not the "b"
  146451. ** (as "b" is part of a non-matching NEAR clause).
  146452. */
  146453. if( bHit==0
  146454. && pExpr->eType==FTSQUERY_NEAR
  146455. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  146456. ){
  146457. Fts3Expr *p;
  146458. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  146459. if( p->pRight->iDocid==pCsr->iPrevId ){
  146460. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  146461. }
  146462. }
  146463. if( p->iDocid==pCsr->iPrevId ){
  146464. fts3EvalInvalidatePoslist(p->pPhrase);
  146465. }
  146466. }
  146467. break;
  146468. case FTSQUERY_OR: {
  146469. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  146470. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  146471. bHit = bHit1 || bHit2;
  146472. break;
  146473. }
  146474. case FTSQUERY_NOT:
  146475. bHit = (
  146476. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  146477. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  146478. );
  146479. break;
  146480. default: {
  146481. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  146482. if( pCsr->pDeferred
  146483. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  146484. ){
  146485. Fts3Phrase *pPhrase = pExpr->pPhrase;
  146486. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  146487. if( pExpr->bDeferred ){
  146488. fts3EvalInvalidatePoslist(pPhrase);
  146489. }
  146490. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  146491. bHit = (pPhrase->doclist.pList!=0);
  146492. pExpr->iDocid = pCsr->iPrevId;
  146493. }else
  146494. #endif
  146495. {
  146496. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  146497. }
  146498. break;
  146499. }
  146500. }
  146501. }
  146502. return bHit;
  146503. }
  146504. /*
  146505. ** This function is called as the second part of each xNext operation when
  146506. ** iterating through the results of a full-text query. At this point the
  146507. ** cursor points to a row that matches the query expression, with the
  146508. ** following caveats:
  146509. **
  146510. ** * Up until this point, "NEAR" operators in the expression have been
  146511. ** treated as "AND".
  146512. **
  146513. ** * Deferred tokens have not yet been considered.
  146514. **
  146515. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  146516. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  146517. ** operators and deferred tokens the current row is still a match for the
  146518. ** expression. It returns 1 if both of the following are true:
  146519. **
  146520. ** 1. *pRc is SQLITE_OK when this function returns, and
  146521. **
  146522. ** 2. After scanning the current FTS table row for the deferred tokens,
  146523. ** it is determined that the row does *not* match the query.
  146524. **
  146525. ** Or, if no error occurs and it seems the current row does match the FTS
  146526. ** query, return 0.
  146527. */
  146528. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  146529. int rc = *pRc;
  146530. int bMiss = 0;
  146531. if( rc==SQLITE_OK ){
  146532. /* If there are one or more deferred tokens, load the current row into
  146533. ** memory and scan it to determine the position list for each deferred
  146534. ** token. Then, see if this row is really a match, considering deferred
  146535. ** tokens and NEAR operators (neither of which were taken into account
  146536. ** earlier, by fts3EvalNextRow()).
  146537. */
  146538. if( pCsr->pDeferred ){
  146539. rc = fts3CursorSeek(0, pCsr);
  146540. if( rc==SQLITE_OK ){
  146541. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  146542. }
  146543. }
  146544. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  146545. /* Free the position-lists accumulated for each deferred token above. */
  146546. sqlite3Fts3FreeDeferredDoclists(pCsr);
  146547. *pRc = rc;
  146548. }
  146549. return (rc==SQLITE_OK && bMiss);
  146550. }
  146551. /*
  146552. ** Advance to the next document that matches the FTS expression in
  146553. ** Fts3Cursor.pExpr.
  146554. */
  146555. static int fts3EvalNext(Fts3Cursor *pCsr){
  146556. int rc = SQLITE_OK; /* Return Code */
  146557. Fts3Expr *pExpr = pCsr->pExpr;
  146558. assert( pCsr->isEof==0 );
  146559. if( pExpr==0 ){
  146560. pCsr->isEof = 1;
  146561. }else{
  146562. do {
  146563. if( pCsr->isRequireSeek==0 ){
  146564. sqlite3_reset(pCsr->pStmt);
  146565. }
  146566. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  146567. fts3EvalNextRow(pCsr, pExpr, &rc);
  146568. pCsr->isEof = pExpr->bEof;
  146569. pCsr->isRequireSeek = 1;
  146570. pCsr->isMatchinfoNeeded = 1;
  146571. pCsr->iPrevId = pExpr->iDocid;
  146572. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  146573. }
  146574. /* Check if the cursor is past the end of the docid range specified
  146575. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  146576. if( rc==SQLITE_OK && (
  146577. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  146578. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  146579. )){
  146580. pCsr->isEof = 1;
  146581. }
  146582. return rc;
  146583. }
  146584. /*
  146585. ** Restart interation for expression pExpr so that the next call to
  146586. ** fts3EvalNext() visits the first row. Do not allow incremental
  146587. ** loading or merging of phrase doclists for this iteration.
  146588. **
  146589. ** If *pRc is other than SQLITE_OK when this function is called, it is
  146590. ** a no-op. If an error occurs within this function, *pRc is set to an
  146591. ** SQLite error code before returning.
  146592. */
  146593. static void fts3EvalRestart(
  146594. Fts3Cursor *pCsr,
  146595. Fts3Expr *pExpr,
  146596. int *pRc
  146597. ){
  146598. if( pExpr && *pRc==SQLITE_OK ){
  146599. Fts3Phrase *pPhrase = pExpr->pPhrase;
  146600. if( pPhrase ){
  146601. fts3EvalInvalidatePoslist(pPhrase);
  146602. if( pPhrase->bIncr ){
  146603. int i;
  146604. for(i=0; i<pPhrase->nToken; i++){
  146605. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  146606. assert( pToken->pDeferred==0 );
  146607. if( pToken->pSegcsr ){
  146608. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  146609. }
  146610. }
  146611. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  146612. }
  146613. pPhrase->doclist.pNextDocid = 0;
  146614. pPhrase->doclist.iDocid = 0;
  146615. pPhrase->pOrPoslist = 0;
  146616. }
  146617. pExpr->iDocid = 0;
  146618. pExpr->bEof = 0;
  146619. pExpr->bStart = 0;
  146620. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  146621. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  146622. }
  146623. }
  146624. /*
  146625. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  146626. ** expression rooted at pExpr, the cursor iterates through all rows matched
  146627. ** by pExpr, calling this function for each row. This function increments
  146628. ** the values in Fts3Expr.aMI[] according to the position-list currently
  146629. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  146630. ** expression nodes.
  146631. */
  146632. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  146633. if( pExpr ){
  146634. Fts3Phrase *pPhrase = pExpr->pPhrase;
  146635. if( pPhrase && pPhrase->doclist.pList ){
  146636. int iCol = 0;
  146637. char *p = pPhrase->doclist.pList;
  146638. assert( *p );
  146639. while( 1 ){
  146640. u8 c = 0;
  146641. int iCnt = 0;
  146642. while( 0xFE & (*p | c) ){
  146643. if( (c&0x80)==0 ) iCnt++;
  146644. c = *p++ & 0x80;
  146645. }
  146646. /* aMI[iCol*3 + 1] = Number of occurrences
  146647. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  146648. */
  146649. pExpr->aMI[iCol*3 + 1] += iCnt;
  146650. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  146651. if( *p==0x00 ) break;
  146652. p++;
  146653. p += fts3GetVarint32(p, &iCol);
  146654. }
  146655. }
  146656. fts3EvalUpdateCounts(pExpr->pLeft);
  146657. fts3EvalUpdateCounts(pExpr->pRight);
  146658. }
  146659. }
  146660. /*
  146661. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  146662. **
  146663. ** If it is not already allocated and populated, this function allocates and
  146664. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  146665. ** of a NEAR expression, then it also allocates and populates the same array
  146666. ** for all other phrases that are part of the NEAR expression.
  146667. **
  146668. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  146669. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  146670. */
  146671. static int fts3EvalGatherStats(
  146672. Fts3Cursor *pCsr, /* Cursor object */
  146673. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  146674. ){
  146675. int rc = SQLITE_OK; /* Return code */
  146676. assert( pExpr->eType==FTSQUERY_PHRASE );
  146677. if( pExpr->aMI==0 ){
  146678. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  146679. Fts3Expr *pRoot; /* Root of NEAR expression */
  146680. Fts3Expr *p; /* Iterator used for several purposes */
  146681. sqlite3_int64 iPrevId = pCsr->iPrevId;
  146682. sqlite3_int64 iDocid;
  146683. u8 bEof;
  146684. /* Find the root of the NEAR expression */
  146685. pRoot = pExpr;
  146686. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  146687. pRoot = pRoot->pParent;
  146688. }
  146689. iDocid = pRoot->iDocid;
  146690. bEof = pRoot->bEof;
  146691. assert( pRoot->bStart );
  146692. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  146693. for(p=pRoot; p; p=p->pLeft){
  146694. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  146695. assert( pE->aMI==0 );
  146696. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  146697. if( !pE->aMI ) return SQLITE_NOMEM;
  146698. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  146699. }
  146700. fts3EvalRestart(pCsr, pRoot, &rc);
  146701. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  146702. do {
  146703. /* Ensure the %_content statement is reset. */
  146704. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  146705. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  146706. /* Advance to the next document */
  146707. fts3EvalNextRow(pCsr, pRoot, &rc);
  146708. pCsr->isEof = pRoot->bEof;
  146709. pCsr->isRequireSeek = 1;
  146710. pCsr->isMatchinfoNeeded = 1;
  146711. pCsr->iPrevId = pRoot->iDocid;
  146712. }while( pCsr->isEof==0
  146713. && pRoot->eType==FTSQUERY_NEAR
  146714. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  146715. );
  146716. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  146717. fts3EvalUpdateCounts(pRoot);
  146718. }
  146719. }
  146720. pCsr->isEof = 0;
  146721. pCsr->iPrevId = iPrevId;
  146722. if( bEof ){
  146723. pRoot->bEof = bEof;
  146724. }else{
  146725. /* Caution: pRoot may iterate through docids in ascending or descending
  146726. ** order. For this reason, even though it seems more defensive, the
  146727. ** do loop can not be written:
  146728. **
  146729. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  146730. */
  146731. fts3EvalRestart(pCsr, pRoot, &rc);
  146732. do {
  146733. fts3EvalNextRow(pCsr, pRoot, &rc);
  146734. assert( pRoot->bEof==0 );
  146735. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  146736. }
  146737. }
  146738. return rc;
  146739. }
  146740. /*
  146741. ** This function is used by the matchinfo() module to query a phrase
  146742. ** expression node for the following information:
  146743. **
  146744. ** 1. The total number of occurrences of the phrase in each column of
  146745. ** the FTS table (considering all rows), and
  146746. **
  146747. ** 2. For each column, the number of rows in the table for which the
  146748. ** column contains at least one instance of the phrase.
  146749. **
  146750. ** If no error occurs, SQLITE_OK is returned and the values for each column
  146751. ** written into the array aiOut as follows:
  146752. **
  146753. ** aiOut[iCol*3 + 1] = Number of occurrences
  146754. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  146755. **
  146756. ** Caveats:
  146757. **
  146758. ** * If a phrase consists entirely of deferred tokens, then all output
  146759. ** values are set to the number of documents in the table. In other
  146760. ** words we assume that very common tokens occur exactly once in each
  146761. ** column of each row of the table.
  146762. **
  146763. ** * If a phrase contains some deferred tokens (and some non-deferred
  146764. ** tokens), count the potential occurrence identified by considering
  146765. ** the non-deferred tokens instead of actual phrase occurrences.
  146766. **
  146767. ** * If the phrase is part of a NEAR expression, then only phrase instances
  146768. ** that meet the NEAR constraint are included in the counts.
  146769. */
  146770. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  146771. Fts3Cursor *pCsr, /* FTS cursor handle */
  146772. Fts3Expr *pExpr, /* Phrase expression */
  146773. u32 *aiOut /* Array to write results into (see above) */
  146774. ){
  146775. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  146776. int rc = SQLITE_OK;
  146777. int iCol;
  146778. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  146779. assert( pCsr->nDoc>0 );
  146780. for(iCol=0; iCol<pTab->nColumn; iCol++){
  146781. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  146782. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  146783. }
  146784. }else{
  146785. rc = fts3EvalGatherStats(pCsr, pExpr);
  146786. if( rc==SQLITE_OK ){
  146787. assert( pExpr->aMI );
  146788. for(iCol=0; iCol<pTab->nColumn; iCol++){
  146789. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  146790. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  146791. }
  146792. }
  146793. }
  146794. return rc;
  146795. }
  146796. /*
  146797. ** The expression pExpr passed as the second argument to this function
  146798. ** must be of type FTSQUERY_PHRASE.
  146799. **
  146800. ** The returned value is either NULL or a pointer to a buffer containing
  146801. ** a position-list indicating the occurrences of the phrase in column iCol
  146802. ** of the current row.
  146803. **
  146804. ** More specifically, the returned buffer contains 1 varint for each
  146805. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  146806. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  146807. ** if the requested column contains "a b X c d X X" and the position-list
  146808. ** for 'X' is requested, the buffer returned may contain:
  146809. **
  146810. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  146811. **
  146812. ** This function works regardless of whether or not the phrase is deferred,
  146813. ** incremental, or neither.
  146814. */
  146815. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  146816. Fts3Cursor *pCsr, /* FTS3 cursor object */
  146817. Fts3Expr *pExpr, /* Phrase to return doclist for */
  146818. int iCol, /* Column to return position list for */
  146819. char **ppOut /* OUT: Pointer to position list */
  146820. ){
  146821. Fts3Phrase *pPhrase = pExpr->pPhrase;
  146822. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  146823. char *pIter;
  146824. int iThis;
  146825. sqlite3_int64 iDocid;
  146826. /* If this phrase is applies specifically to some column other than
  146827. ** column iCol, return a NULL pointer. */
  146828. *ppOut = 0;
  146829. assert( iCol>=0 && iCol<pTab->nColumn );
  146830. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  146831. return SQLITE_OK;
  146832. }
  146833. iDocid = pExpr->iDocid;
  146834. pIter = pPhrase->doclist.pList;
  146835. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  146836. int rc = SQLITE_OK;
  146837. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  146838. int bOr = 0;
  146839. u8 bTreeEof = 0;
  146840. Fts3Expr *p; /* Used to iterate from pExpr to root */
  146841. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  146842. int bMatch;
  146843. /* Check if this phrase descends from an OR expression node. If not,
  146844. ** return NULL. Otherwise, the entry that corresponds to docid
  146845. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  146846. ** tree that the node is part of has been marked as EOF, but the node
  146847. ** itself is not EOF, then it may point to an earlier entry. */
  146848. pNear = pExpr;
  146849. for(p=pExpr->pParent; p; p=p->pParent){
  146850. if( p->eType==FTSQUERY_OR ) bOr = 1;
  146851. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  146852. if( p->bEof ) bTreeEof = 1;
  146853. }
  146854. if( bOr==0 ) return SQLITE_OK;
  146855. /* This is the descendent of an OR node. In this case we cannot use
  146856. ** an incremental phrase. Load the entire doclist for the phrase
  146857. ** into memory in this case. */
  146858. if( pPhrase->bIncr ){
  146859. int bEofSave = pNear->bEof;
  146860. fts3EvalRestart(pCsr, pNear, &rc);
  146861. while( rc==SQLITE_OK && !pNear->bEof ){
  146862. fts3EvalNextRow(pCsr, pNear, &rc);
  146863. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  146864. }
  146865. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  146866. }
  146867. if( bTreeEof ){
  146868. while( rc==SQLITE_OK && !pNear->bEof ){
  146869. fts3EvalNextRow(pCsr, pNear, &rc);
  146870. }
  146871. }
  146872. if( rc!=SQLITE_OK ) return rc;
  146873. bMatch = 1;
  146874. for(p=pNear; p; p=p->pLeft){
  146875. u8 bEof = 0;
  146876. Fts3Expr *pTest = p;
  146877. Fts3Phrase *pPh;
  146878. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  146879. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  146880. assert( pTest->eType==FTSQUERY_PHRASE );
  146881. pPh = pTest->pPhrase;
  146882. pIter = pPh->pOrPoslist;
  146883. iDocid = pPh->iOrDocid;
  146884. if( pCsr->bDesc==bDescDoclist ){
  146885. bEof = !pPh->doclist.nAll ||
  146886. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  146887. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  146888. sqlite3Fts3DoclistNext(
  146889. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  146890. &pIter, &iDocid, &bEof
  146891. );
  146892. }
  146893. }else{
  146894. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  146895. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  146896. int dummy;
  146897. sqlite3Fts3DoclistPrev(
  146898. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  146899. &pIter, &iDocid, &dummy, &bEof
  146900. );
  146901. }
  146902. }
  146903. pPh->pOrPoslist = pIter;
  146904. pPh->iOrDocid = iDocid;
  146905. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  146906. }
  146907. if( bMatch ){
  146908. pIter = pPhrase->pOrPoslist;
  146909. }else{
  146910. pIter = 0;
  146911. }
  146912. }
  146913. if( pIter==0 ) return SQLITE_OK;
  146914. if( *pIter==0x01 ){
  146915. pIter++;
  146916. pIter += fts3GetVarint32(pIter, &iThis);
  146917. }else{
  146918. iThis = 0;
  146919. }
  146920. while( iThis<iCol ){
  146921. fts3ColumnlistCopy(0, &pIter);
  146922. if( *pIter==0x00 ) return SQLITE_OK;
  146923. pIter++;
  146924. pIter += fts3GetVarint32(pIter, &iThis);
  146925. }
  146926. if( *pIter==0x00 ){
  146927. pIter = 0;
  146928. }
  146929. *ppOut = ((iCol==iThis)?pIter:0);
  146930. return SQLITE_OK;
  146931. }
  146932. /*
  146933. ** Free all components of the Fts3Phrase structure that were allocated by
  146934. ** the eval module. Specifically, this means to free:
  146935. **
  146936. ** * the contents of pPhrase->doclist, and
  146937. ** * any Fts3MultiSegReader objects held by phrase tokens.
  146938. */
  146939. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  146940. if( pPhrase ){
  146941. int i;
  146942. sqlite3_free(pPhrase->doclist.aAll);
  146943. fts3EvalInvalidatePoslist(pPhrase);
  146944. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  146945. for(i=0; i<pPhrase->nToken; i++){
  146946. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  146947. pPhrase->aToken[i].pSegcsr = 0;
  146948. }
  146949. }
  146950. }
  146951. /*
  146952. ** Return SQLITE_CORRUPT_VTAB.
  146953. */
  146954. #ifdef SQLITE_DEBUG
  146955. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  146956. return SQLITE_CORRUPT_VTAB;
  146957. }
  146958. #endif
  146959. #if !SQLITE_CORE
  146960. /*
  146961. ** Initialize API pointer table, if required.
  146962. */
  146963. #ifdef _WIN32
  146964. __declspec(dllexport)
  146965. #endif
  146966. SQLITE_API int sqlite3_fts3_init(
  146967. sqlite3 *db,
  146968. char **pzErrMsg,
  146969. const sqlite3_api_routines *pApi
  146970. ){
  146971. SQLITE_EXTENSION_INIT2(pApi)
  146972. return sqlite3Fts3Init(db);
  146973. }
  146974. #endif
  146975. #endif
  146976. /************** End of fts3.c ************************************************/
  146977. /************** Begin file fts3_aux.c ****************************************/
  146978. /*
  146979. ** 2011 Jan 27
  146980. **
  146981. ** The author disclaims copyright to this source code. In place of
  146982. ** a legal notice, here is a blessing:
  146983. **
  146984. ** May you do good and not evil.
  146985. ** May you find forgiveness for yourself and forgive others.
  146986. ** May you share freely, never taking more than you give.
  146987. **
  146988. ******************************************************************************
  146989. **
  146990. */
  146991. /* #include "fts3Int.h" */
  146992. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  146993. /* #include <string.h> */
  146994. /* #include <assert.h> */
  146995. typedef struct Fts3auxTable Fts3auxTable;
  146996. typedef struct Fts3auxCursor Fts3auxCursor;
  146997. struct Fts3auxTable {
  146998. sqlite3_vtab base; /* Base class used by SQLite core */
  146999. Fts3Table *pFts3Tab;
  147000. };
  147001. struct Fts3auxCursor {
  147002. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  147003. Fts3MultiSegReader csr; /* Must be right after "base" */
  147004. Fts3SegFilter filter;
  147005. char *zStop;
  147006. int nStop; /* Byte-length of string zStop */
  147007. int iLangid; /* Language id to query */
  147008. int isEof; /* True if cursor is at EOF */
  147009. sqlite3_int64 iRowid; /* Current rowid */
  147010. int iCol; /* Current value of 'col' column */
  147011. int nStat; /* Size of aStat[] array */
  147012. struct Fts3auxColstats {
  147013. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  147014. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  147015. } *aStat;
  147016. };
  147017. /*
  147018. ** Schema of the terms table.
  147019. */
  147020. #define FTS3_AUX_SCHEMA \
  147021. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  147022. /*
  147023. ** This function does all the work for both the xConnect and xCreate methods.
  147024. ** These tables have no persistent representation of their own, so xConnect
  147025. ** and xCreate are identical operations.
  147026. */
  147027. static int fts3auxConnectMethod(
  147028. sqlite3 *db, /* Database connection */
  147029. void *pUnused, /* Unused */
  147030. int argc, /* Number of elements in argv array */
  147031. const char * const *argv, /* xCreate/xConnect argument array */
  147032. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  147033. char **pzErr /* OUT: sqlite3_malloc'd error message */
  147034. ){
  147035. char const *zDb; /* Name of database (e.g. "main") */
  147036. char const *zFts3; /* Name of fts3 table */
  147037. int nDb; /* Result of strlen(zDb) */
  147038. int nFts3; /* Result of strlen(zFts3) */
  147039. int nByte; /* Bytes of space to allocate here */
  147040. int rc; /* value returned by declare_vtab() */
  147041. Fts3auxTable *p; /* Virtual table object to return */
  147042. UNUSED_PARAMETER(pUnused);
  147043. /* The user should invoke this in one of two forms:
  147044. **
  147045. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  147046. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  147047. */
  147048. if( argc!=4 && argc!=5 ) goto bad_args;
  147049. zDb = argv[1];
  147050. nDb = (int)strlen(zDb);
  147051. if( argc==5 ){
  147052. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  147053. zDb = argv[3];
  147054. nDb = (int)strlen(zDb);
  147055. zFts3 = argv[4];
  147056. }else{
  147057. goto bad_args;
  147058. }
  147059. }else{
  147060. zFts3 = argv[3];
  147061. }
  147062. nFts3 = (int)strlen(zFts3);
  147063. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  147064. if( rc!=SQLITE_OK ) return rc;
  147065. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  147066. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  147067. if( !p ) return SQLITE_NOMEM;
  147068. memset(p, 0, nByte);
  147069. p->pFts3Tab = (Fts3Table *)&p[1];
  147070. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  147071. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  147072. p->pFts3Tab->db = db;
  147073. p->pFts3Tab->nIndex = 1;
  147074. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  147075. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  147076. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  147077. *ppVtab = (sqlite3_vtab *)p;
  147078. return SQLITE_OK;
  147079. bad_args:
  147080. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  147081. return SQLITE_ERROR;
  147082. }
  147083. /*
  147084. ** This function does the work for both the xDisconnect and xDestroy methods.
  147085. ** These tables have no persistent representation of their own, so xDisconnect
  147086. ** and xDestroy are identical operations.
  147087. */
  147088. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  147089. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  147090. Fts3Table *pFts3 = p->pFts3Tab;
  147091. int i;
  147092. /* Free any prepared statements held */
  147093. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  147094. sqlite3_finalize(pFts3->aStmt[i]);
  147095. }
  147096. sqlite3_free(pFts3->zSegmentsTbl);
  147097. sqlite3_free(p);
  147098. return SQLITE_OK;
  147099. }
  147100. #define FTS4AUX_EQ_CONSTRAINT 1
  147101. #define FTS4AUX_GE_CONSTRAINT 2
  147102. #define FTS4AUX_LE_CONSTRAINT 4
  147103. /*
  147104. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  147105. */
  147106. static int fts3auxBestIndexMethod(
  147107. sqlite3_vtab *pVTab,
  147108. sqlite3_index_info *pInfo
  147109. ){
  147110. int i;
  147111. int iEq = -1;
  147112. int iGe = -1;
  147113. int iLe = -1;
  147114. int iLangid = -1;
  147115. int iNext = 1; /* Next free argvIndex value */
  147116. UNUSED_PARAMETER(pVTab);
  147117. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  147118. if( pInfo->nOrderBy==1
  147119. && pInfo->aOrderBy[0].iColumn==0
  147120. && pInfo->aOrderBy[0].desc==0
  147121. ){
  147122. pInfo->orderByConsumed = 1;
  147123. }
  147124. /* Search for equality and range constraints on the "term" column.
  147125. ** And equality constraints on the hidden "languageid" column. */
  147126. for(i=0; i<pInfo->nConstraint; i++){
  147127. if( pInfo->aConstraint[i].usable ){
  147128. int op = pInfo->aConstraint[i].op;
  147129. int iCol = pInfo->aConstraint[i].iColumn;
  147130. if( iCol==0 ){
  147131. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  147132. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  147133. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  147134. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  147135. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  147136. }
  147137. if( iCol==4 ){
  147138. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  147139. }
  147140. }
  147141. }
  147142. if( iEq>=0 ){
  147143. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  147144. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  147145. pInfo->estimatedCost = 5;
  147146. }else{
  147147. pInfo->idxNum = 0;
  147148. pInfo->estimatedCost = 20000;
  147149. if( iGe>=0 ){
  147150. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  147151. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  147152. pInfo->estimatedCost /= 2;
  147153. }
  147154. if( iLe>=0 ){
  147155. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  147156. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  147157. pInfo->estimatedCost /= 2;
  147158. }
  147159. }
  147160. if( iLangid>=0 ){
  147161. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  147162. pInfo->estimatedCost--;
  147163. }
  147164. return SQLITE_OK;
  147165. }
  147166. /*
  147167. ** xOpen - Open a cursor.
  147168. */
  147169. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  147170. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  147171. UNUSED_PARAMETER(pVTab);
  147172. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  147173. if( !pCsr ) return SQLITE_NOMEM;
  147174. memset(pCsr, 0, sizeof(Fts3auxCursor));
  147175. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  147176. return SQLITE_OK;
  147177. }
  147178. /*
  147179. ** xClose - Close a cursor.
  147180. */
  147181. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  147182. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  147183. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  147184. sqlite3Fts3SegmentsClose(pFts3);
  147185. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  147186. sqlite3_free((void *)pCsr->filter.zTerm);
  147187. sqlite3_free(pCsr->zStop);
  147188. sqlite3_free(pCsr->aStat);
  147189. sqlite3_free(pCsr);
  147190. return SQLITE_OK;
  147191. }
  147192. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  147193. if( nSize>pCsr->nStat ){
  147194. struct Fts3auxColstats *aNew;
  147195. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  147196. sizeof(struct Fts3auxColstats) * nSize
  147197. );
  147198. if( aNew==0 ) return SQLITE_NOMEM;
  147199. memset(&aNew[pCsr->nStat], 0,
  147200. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  147201. );
  147202. pCsr->aStat = aNew;
  147203. pCsr->nStat = nSize;
  147204. }
  147205. return SQLITE_OK;
  147206. }
  147207. /*
  147208. ** xNext - Advance the cursor to the next row, if any.
  147209. */
  147210. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  147211. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  147212. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  147213. int rc;
  147214. /* Increment our pretend rowid value. */
  147215. pCsr->iRowid++;
  147216. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  147217. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  147218. }
  147219. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  147220. if( rc==SQLITE_ROW ){
  147221. int i = 0;
  147222. int nDoclist = pCsr->csr.nDoclist;
  147223. char *aDoclist = pCsr->csr.aDoclist;
  147224. int iCol;
  147225. int eState = 0;
  147226. if( pCsr->zStop ){
  147227. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  147228. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  147229. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  147230. pCsr->isEof = 1;
  147231. return SQLITE_OK;
  147232. }
  147233. }
  147234. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  147235. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  147236. iCol = 0;
  147237. while( i<nDoclist ){
  147238. sqlite3_int64 v = 0;
  147239. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  147240. switch( eState ){
  147241. /* State 0. In this state the integer just read was a docid. */
  147242. case 0:
  147243. pCsr->aStat[0].nDoc++;
  147244. eState = 1;
  147245. iCol = 0;
  147246. break;
  147247. /* State 1. In this state we are expecting either a 1, indicating
  147248. ** that the following integer will be a column number, or the
  147249. ** start of a position list for column 0.
  147250. **
  147251. ** The only difference between state 1 and state 2 is that if the
  147252. ** integer encountered in state 1 is not 0 or 1, then we need to
  147253. ** increment the column 0 "nDoc" count for this term.
  147254. */
  147255. case 1:
  147256. assert( iCol==0 );
  147257. if( v>1 ){
  147258. pCsr->aStat[1].nDoc++;
  147259. }
  147260. eState = 2;
  147261. /* fall through */
  147262. case 2:
  147263. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  147264. eState = 0;
  147265. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  147266. eState = 3;
  147267. }else{ /* 2 or greater. A position. */
  147268. pCsr->aStat[iCol+1].nOcc++;
  147269. pCsr->aStat[0].nOcc++;
  147270. }
  147271. break;
  147272. /* State 3. The integer just read is a column number. */
  147273. default: assert( eState==3 );
  147274. iCol = (int)v;
  147275. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  147276. pCsr->aStat[iCol+1].nDoc++;
  147277. eState = 2;
  147278. break;
  147279. }
  147280. }
  147281. pCsr->iCol = 0;
  147282. rc = SQLITE_OK;
  147283. }else{
  147284. pCsr->isEof = 1;
  147285. }
  147286. return rc;
  147287. }
  147288. /*
  147289. ** xFilter - Initialize a cursor to point at the start of its data.
  147290. */
  147291. static int fts3auxFilterMethod(
  147292. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  147293. int idxNum, /* Strategy index */
  147294. const char *idxStr, /* Unused */
  147295. int nVal, /* Number of elements in apVal */
  147296. sqlite3_value **apVal /* Arguments for the indexing scheme */
  147297. ){
  147298. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  147299. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  147300. int rc;
  147301. int isScan = 0;
  147302. int iLangVal = 0; /* Language id to query */
  147303. int iEq = -1; /* Index of term=? value in apVal */
  147304. int iGe = -1; /* Index of term>=? value in apVal */
  147305. int iLe = -1; /* Index of term<=? value in apVal */
  147306. int iLangid = -1; /* Index of languageid=? value in apVal */
  147307. int iNext = 0;
  147308. UNUSED_PARAMETER(nVal);
  147309. UNUSED_PARAMETER(idxStr);
  147310. assert( idxStr==0 );
  147311. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  147312. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  147313. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  147314. );
  147315. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  147316. iEq = iNext++;
  147317. }else{
  147318. isScan = 1;
  147319. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  147320. iGe = iNext++;
  147321. }
  147322. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  147323. iLe = iNext++;
  147324. }
  147325. }
  147326. if( iNext<nVal ){
  147327. iLangid = iNext++;
  147328. }
  147329. /* In case this cursor is being reused, close and zero it. */
  147330. testcase(pCsr->filter.zTerm);
  147331. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  147332. sqlite3_free((void *)pCsr->filter.zTerm);
  147333. sqlite3_free(pCsr->aStat);
  147334. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  147335. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  147336. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  147337. if( iEq>=0 || iGe>=0 ){
  147338. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  147339. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  147340. if( zStr ){
  147341. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  147342. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  147343. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  147344. }
  147345. }
  147346. if( iLe>=0 ){
  147347. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  147348. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  147349. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  147350. }
  147351. if( iLangid>=0 ){
  147352. iLangVal = sqlite3_value_int(apVal[iLangid]);
  147353. /* If the user specified a negative value for the languageid, use zero
  147354. ** instead. This works, as the "languageid=?" constraint will also
  147355. ** be tested by the VDBE layer. The test will always be false (since
  147356. ** this module will not return a row with a negative languageid), and
  147357. ** so the overall query will return zero rows. */
  147358. if( iLangVal<0 ) iLangVal = 0;
  147359. }
  147360. pCsr->iLangid = iLangVal;
  147361. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  147362. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  147363. );
  147364. if( rc==SQLITE_OK ){
  147365. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  147366. }
  147367. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  147368. return rc;
  147369. }
  147370. /*
  147371. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  147372. */
  147373. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  147374. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  147375. return pCsr->isEof;
  147376. }
  147377. /*
  147378. ** xColumn - Return a column value.
  147379. */
  147380. static int fts3auxColumnMethod(
  147381. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  147382. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  147383. int iCol /* Index of column to read value from */
  147384. ){
  147385. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  147386. assert( p->isEof==0 );
  147387. switch( iCol ){
  147388. case 0: /* term */
  147389. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  147390. break;
  147391. case 1: /* col */
  147392. if( p->iCol ){
  147393. sqlite3_result_int(pCtx, p->iCol-1);
  147394. }else{
  147395. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  147396. }
  147397. break;
  147398. case 2: /* documents */
  147399. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  147400. break;
  147401. case 3: /* occurrences */
  147402. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  147403. break;
  147404. default: /* languageid */
  147405. assert( iCol==4 );
  147406. sqlite3_result_int(pCtx, p->iLangid);
  147407. break;
  147408. }
  147409. return SQLITE_OK;
  147410. }
  147411. /*
  147412. ** xRowid - Return the current rowid for the cursor.
  147413. */
  147414. static int fts3auxRowidMethod(
  147415. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  147416. sqlite_int64 *pRowid /* OUT: Rowid value */
  147417. ){
  147418. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  147419. *pRowid = pCsr->iRowid;
  147420. return SQLITE_OK;
  147421. }
  147422. /*
  147423. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  147424. ** if successful or an error code if sqlite3_create_module() fails.
  147425. */
  147426. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  147427. static const sqlite3_module fts3aux_module = {
  147428. 0, /* iVersion */
  147429. fts3auxConnectMethod, /* xCreate */
  147430. fts3auxConnectMethod, /* xConnect */
  147431. fts3auxBestIndexMethod, /* xBestIndex */
  147432. fts3auxDisconnectMethod, /* xDisconnect */
  147433. fts3auxDisconnectMethod, /* xDestroy */
  147434. fts3auxOpenMethod, /* xOpen */
  147435. fts3auxCloseMethod, /* xClose */
  147436. fts3auxFilterMethod, /* xFilter */
  147437. fts3auxNextMethod, /* xNext */
  147438. fts3auxEofMethod, /* xEof */
  147439. fts3auxColumnMethod, /* xColumn */
  147440. fts3auxRowidMethod, /* xRowid */
  147441. 0, /* xUpdate */
  147442. 0, /* xBegin */
  147443. 0, /* xSync */
  147444. 0, /* xCommit */
  147445. 0, /* xRollback */
  147446. 0, /* xFindFunction */
  147447. 0, /* xRename */
  147448. 0, /* xSavepoint */
  147449. 0, /* xRelease */
  147450. 0 /* xRollbackTo */
  147451. };
  147452. int rc; /* Return code */
  147453. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  147454. return rc;
  147455. }
  147456. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  147457. /************** End of fts3_aux.c ********************************************/
  147458. /************** Begin file fts3_expr.c ***************************************/
  147459. /*
  147460. ** 2008 Nov 28
  147461. **
  147462. ** The author disclaims copyright to this source code. In place of
  147463. ** a legal notice, here is a blessing:
  147464. **
  147465. ** May you do good and not evil.
  147466. ** May you find forgiveness for yourself and forgive others.
  147467. ** May you share freely, never taking more than you give.
  147468. **
  147469. ******************************************************************************
  147470. **
  147471. ** This module contains code that implements a parser for fts3 query strings
  147472. ** (the right-hand argument to the MATCH operator). Because the supported
  147473. ** syntax is relatively simple, the whole tokenizer/parser system is
  147474. ** hand-coded.
  147475. */
  147476. /* #include "fts3Int.h" */
  147477. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  147478. /*
  147479. ** By default, this module parses the legacy syntax that has been
  147480. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  147481. ** is defined, then it uses the new syntax. The differences between
  147482. ** the new and the old syntaxes are:
  147483. **
  147484. ** a) The new syntax supports parenthesis. The old does not.
  147485. **
  147486. ** b) The new syntax supports the AND and NOT operators. The old does not.
  147487. **
  147488. ** c) The old syntax supports the "-" token qualifier. This is not
  147489. ** supported by the new syntax (it is replaced by the NOT operator).
  147490. **
  147491. ** d) When using the old syntax, the OR operator has a greater precedence
  147492. ** than an implicit AND. When using the new, both implicity and explicit
  147493. ** AND operators have a higher precedence than OR.
  147494. **
  147495. ** If compiled with SQLITE_TEST defined, then this module exports the
  147496. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  147497. ** to zero causes the module to use the old syntax. If it is set to
  147498. ** non-zero the new syntax is activated. This is so both syntaxes can
  147499. ** be tested using a single build of testfixture.
  147500. **
  147501. ** The following describes the syntax supported by the fts3 MATCH
  147502. ** operator in a similar format to that used by the lemon parser
  147503. ** generator. This module does not use actually lemon, it uses a
  147504. ** custom parser.
  147505. **
  147506. ** query ::= andexpr (OR andexpr)*.
  147507. **
  147508. ** andexpr ::= notexpr (AND? notexpr)*.
  147509. **
  147510. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  147511. ** notexpr ::= LP query RP.
  147512. **
  147513. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  147514. **
  147515. ** distance_opt ::= .
  147516. ** distance_opt ::= / INTEGER.
  147517. **
  147518. ** phrase ::= TOKEN.
  147519. ** phrase ::= COLUMN:TOKEN.
  147520. ** phrase ::= "TOKEN TOKEN TOKEN...".
  147521. */
  147522. #ifdef SQLITE_TEST
  147523. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  147524. #else
  147525. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  147526. # define sqlite3_fts3_enable_parentheses 1
  147527. # else
  147528. # define sqlite3_fts3_enable_parentheses 0
  147529. # endif
  147530. #endif
  147531. /*
  147532. ** Default span for NEAR operators.
  147533. */
  147534. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  147535. /* #include <string.h> */
  147536. /* #include <assert.h> */
  147537. /*
  147538. ** isNot:
  147539. ** This variable is used by function getNextNode(). When getNextNode() is
  147540. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  147541. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  147542. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  147543. ** zero.
  147544. */
  147545. typedef struct ParseContext ParseContext;
  147546. struct ParseContext {
  147547. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  147548. int iLangid; /* Language id used with tokenizer */
  147549. const char **azCol; /* Array of column names for fts3 table */
  147550. int bFts4; /* True to allow FTS4-only syntax */
  147551. int nCol; /* Number of entries in azCol[] */
  147552. int iDefaultCol; /* Default column to query */
  147553. int isNot; /* True if getNextNode() sees a unary - */
  147554. sqlite3_context *pCtx; /* Write error message here */
  147555. int nNest; /* Number of nested brackets */
  147556. };
  147557. /*
  147558. ** This function is equivalent to the standard isspace() function.
  147559. **
  147560. ** The standard isspace() can be awkward to use safely, because although it
  147561. ** is defined to accept an argument of type int, its behavior when passed
  147562. ** an integer that falls outside of the range of the unsigned char type
  147563. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  147564. ** is defined to accept an argument of type char, and always returns 0 for
  147565. ** any values that fall outside of the range of the unsigned char type (i.e.
  147566. ** negative values).
  147567. */
  147568. static int fts3isspace(char c){
  147569. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  147570. }
  147571. /*
  147572. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  147573. ** zero the memory before returning a pointer to it. If unsuccessful,
  147574. ** return NULL.
  147575. */
  147576. static void *fts3MallocZero(int nByte){
  147577. void *pRet = sqlite3_malloc(nByte);
  147578. if( pRet ) memset(pRet, 0, nByte);
  147579. return pRet;
  147580. }
  147581. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  147582. sqlite3_tokenizer *pTokenizer,
  147583. int iLangid,
  147584. const char *z,
  147585. int n,
  147586. sqlite3_tokenizer_cursor **ppCsr
  147587. ){
  147588. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  147589. sqlite3_tokenizer_cursor *pCsr = 0;
  147590. int rc;
  147591. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  147592. assert( rc==SQLITE_OK || pCsr==0 );
  147593. if( rc==SQLITE_OK ){
  147594. pCsr->pTokenizer = pTokenizer;
  147595. if( pModule->iVersion>=1 ){
  147596. rc = pModule->xLanguageid(pCsr, iLangid);
  147597. if( rc!=SQLITE_OK ){
  147598. pModule->xClose(pCsr);
  147599. pCsr = 0;
  147600. }
  147601. }
  147602. }
  147603. *ppCsr = pCsr;
  147604. return rc;
  147605. }
  147606. /*
  147607. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  147608. ** call fts3ExprParse(). So this forward declaration is required.
  147609. */
  147610. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  147611. /*
  147612. ** Extract the next token from buffer z (length n) using the tokenizer
  147613. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  147614. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  147615. ** single token and set *ppExpr to point to it. If the end of the buffer is
  147616. ** reached before a token is found, set *ppExpr to zero. It is the
  147617. ** responsibility of the caller to eventually deallocate the allocated
  147618. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  147619. **
  147620. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  147621. ** fails.
  147622. */
  147623. static int getNextToken(
  147624. ParseContext *pParse, /* fts3 query parse context */
  147625. int iCol, /* Value for Fts3Phrase.iColumn */
  147626. const char *z, int n, /* Input string */
  147627. Fts3Expr **ppExpr, /* OUT: expression */
  147628. int *pnConsumed /* OUT: Number of bytes consumed */
  147629. ){
  147630. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  147631. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  147632. int rc;
  147633. sqlite3_tokenizer_cursor *pCursor;
  147634. Fts3Expr *pRet = 0;
  147635. int i = 0;
  147636. /* Set variable i to the maximum number of bytes of input to tokenize. */
  147637. for(i=0; i<n; i++){
  147638. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  147639. if( z[i]=='"' ) break;
  147640. }
  147641. *pnConsumed = i;
  147642. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  147643. if( rc==SQLITE_OK ){
  147644. const char *zToken;
  147645. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  147646. int nByte; /* total space to allocate */
  147647. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  147648. if( rc==SQLITE_OK ){
  147649. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  147650. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  147651. if( !pRet ){
  147652. rc = SQLITE_NOMEM;
  147653. }else{
  147654. pRet->eType = FTSQUERY_PHRASE;
  147655. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  147656. pRet->pPhrase->nToken = 1;
  147657. pRet->pPhrase->iColumn = iCol;
  147658. pRet->pPhrase->aToken[0].n = nToken;
  147659. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  147660. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  147661. if( iEnd<n && z[iEnd]=='*' ){
  147662. pRet->pPhrase->aToken[0].isPrefix = 1;
  147663. iEnd++;
  147664. }
  147665. while( 1 ){
  147666. if( !sqlite3_fts3_enable_parentheses
  147667. && iStart>0 && z[iStart-1]=='-'
  147668. ){
  147669. pParse->isNot = 1;
  147670. iStart--;
  147671. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  147672. pRet->pPhrase->aToken[0].bFirst = 1;
  147673. iStart--;
  147674. }else{
  147675. break;
  147676. }
  147677. }
  147678. }
  147679. *pnConsumed = iEnd;
  147680. }else if( i && rc==SQLITE_DONE ){
  147681. rc = SQLITE_OK;
  147682. }
  147683. pModule->xClose(pCursor);
  147684. }
  147685. *ppExpr = pRet;
  147686. return rc;
  147687. }
  147688. /*
  147689. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  147690. ** then free the old allocation.
  147691. */
  147692. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  147693. void *pRet = sqlite3_realloc(pOrig, nNew);
  147694. if( !pRet ){
  147695. sqlite3_free(pOrig);
  147696. }
  147697. return pRet;
  147698. }
  147699. /*
  147700. ** Buffer zInput, length nInput, contains the contents of a quoted string
  147701. ** that appeared as part of an fts3 query expression. Neither quote character
  147702. ** is included in the buffer. This function attempts to tokenize the entire
  147703. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  147704. ** containing the results.
  147705. **
  147706. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  147707. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  147708. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  147709. ** to 0.
  147710. */
  147711. static int getNextString(
  147712. ParseContext *pParse, /* fts3 query parse context */
  147713. const char *zInput, int nInput, /* Input string */
  147714. Fts3Expr **ppExpr /* OUT: expression */
  147715. ){
  147716. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  147717. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  147718. int rc;
  147719. Fts3Expr *p = 0;
  147720. sqlite3_tokenizer_cursor *pCursor = 0;
  147721. char *zTemp = 0;
  147722. int nTemp = 0;
  147723. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  147724. int nToken = 0;
  147725. /* The final Fts3Expr data structure, including the Fts3Phrase,
  147726. ** Fts3PhraseToken structures token buffers are all stored as a single
  147727. ** allocation so that the expression can be freed with a single call to
  147728. ** sqlite3_free(). Setting this up requires a two pass approach.
  147729. **
  147730. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  147731. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  147732. ** to assemble data in two dynamic buffers:
  147733. **
  147734. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  147735. ** structure, followed by the array of Fts3PhraseToken
  147736. ** structures. This pass only populates the Fts3PhraseToken array.
  147737. **
  147738. ** Buffer zTemp: Contains copies of all tokens.
  147739. **
  147740. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  147741. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  147742. ** structures.
  147743. */
  147744. rc = sqlite3Fts3OpenTokenizer(
  147745. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  147746. if( rc==SQLITE_OK ){
  147747. int ii;
  147748. for(ii=0; rc==SQLITE_OK; ii++){
  147749. const char *zByte;
  147750. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  147751. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  147752. if( rc==SQLITE_OK ){
  147753. Fts3PhraseToken *pToken;
  147754. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  147755. if( !p ) goto no_mem;
  147756. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  147757. if( !zTemp ) goto no_mem;
  147758. assert( nToken==ii );
  147759. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  147760. memset(pToken, 0, sizeof(Fts3PhraseToken));
  147761. memcpy(&zTemp[nTemp], zByte, nByte);
  147762. nTemp += nByte;
  147763. pToken->n = nByte;
  147764. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  147765. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  147766. nToken = ii+1;
  147767. }
  147768. }
  147769. pModule->xClose(pCursor);
  147770. pCursor = 0;
  147771. }
  147772. if( rc==SQLITE_DONE ){
  147773. int jj;
  147774. char *zBuf = 0;
  147775. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  147776. if( !p ) goto no_mem;
  147777. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  147778. p->eType = FTSQUERY_PHRASE;
  147779. p->pPhrase = (Fts3Phrase *)&p[1];
  147780. p->pPhrase->iColumn = pParse->iDefaultCol;
  147781. p->pPhrase->nToken = nToken;
  147782. zBuf = (char *)&p->pPhrase->aToken[nToken];
  147783. if( zTemp ){
  147784. memcpy(zBuf, zTemp, nTemp);
  147785. sqlite3_free(zTemp);
  147786. }else{
  147787. assert( nTemp==0 );
  147788. }
  147789. for(jj=0; jj<p->pPhrase->nToken; jj++){
  147790. p->pPhrase->aToken[jj].z = zBuf;
  147791. zBuf += p->pPhrase->aToken[jj].n;
  147792. }
  147793. rc = SQLITE_OK;
  147794. }
  147795. *ppExpr = p;
  147796. return rc;
  147797. no_mem:
  147798. if( pCursor ){
  147799. pModule->xClose(pCursor);
  147800. }
  147801. sqlite3_free(zTemp);
  147802. sqlite3_free(p);
  147803. *ppExpr = 0;
  147804. return SQLITE_NOMEM;
  147805. }
  147806. /*
  147807. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  147808. ** structure, or set to 0 if the end of the input buffer is reached.
  147809. **
  147810. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  147811. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  147812. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  147813. */
  147814. static int getNextNode(
  147815. ParseContext *pParse, /* fts3 query parse context */
  147816. const char *z, int n, /* Input string */
  147817. Fts3Expr **ppExpr, /* OUT: expression */
  147818. int *pnConsumed /* OUT: Number of bytes consumed */
  147819. ){
  147820. static const struct Fts3Keyword {
  147821. char *z; /* Keyword text */
  147822. unsigned char n; /* Length of the keyword */
  147823. unsigned char parenOnly; /* Only valid in paren mode */
  147824. unsigned char eType; /* Keyword code */
  147825. } aKeyword[] = {
  147826. { "OR" , 2, 0, FTSQUERY_OR },
  147827. { "AND", 3, 1, FTSQUERY_AND },
  147828. { "NOT", 3, 1, FTSQUERY_NOT },
  147829. { "NEAR", 4, 0, FTSQUERY_NEAR }
  147830. };
  147831. int ii;
  147832. int iCol;
  147833. int iColLen;
  147834. int rc;
  147835. Fts3Expr *pRet = 0;
  147836. const char *zInput = z;
  147837. int nInput = n;
  147838. pParse->isNot = 0;
  147839. /* Skip over any whitespace before checking for a keyword, an open or
  147840. ** close bracket, or a quoted string.
  147841. */
  147842. while( nInput>0 && fts3isspace(*zInput) ){
  147843. nInput--;
  147844. zInput++;
  147845. }
  147846. if( nInput==0 ){
  147847. return SQLITE_DONE;
  147848. }
  147849. /* See if we are dealing with a keyword. */
  147850. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  147851. const struct Fts3Keyword *pKey = &aKeyword[ii];
  147852. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  147853. continue;
  147854. }
  147855. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  147856. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  147857. int nKey = pKey->n;
  147858. char cNext;
  147859. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  147860. if( pKey->eType==FTSQUERY_NEAR ){
  147861. assert( nKey==4 );
  147862. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  147863. nNear = 0;
  147864. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  147865. nNear = nNear * 10 + (zInput[nKey] - '0');
  147866. }
  147867. }
  147868. }
  147869. /* At this point this is probably a keyword. But for that to be true,
  147870. ** the next byte must contain either whitespace, an open or close
  147871. ** parenthesis, a quote character, or EOF.
  147872. */
  147873. cNext = zInput[nKey];
  147874. if( fts3isspace(cNext)
  147875. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  147876. ){
  147877. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  147878. if( !pRet ){
  147879. return SQLITE_NOMEM;
  147880. }
  147881. pRet->eType = pKey->eType;
  147882. pRet->nNear = nNear;
  147883. *ppExpr = pRet;
  147884. *pnConsumed = (int)((zInput - z) + nKey);
  147885. return SQLITE_OK;
  147886. }
  147887. /* Turns out that wasn't a keyword after all. This happens if the
  147888. ** user has supplied a token such as "ORacle". Continue.
  147889. */
  147890. }
  147891. }
  147892. /* See if we are dealing with a quoted phrase. If this is the case, then
  147893. ** search for the closing quote and pass the whole string to getNextString()
  147894. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  147895. ** a quote character embedded in a string.
  147896. */
  147897. if( *zInput=='"' ){
  147898. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  147899. *pnConsumed = (int)((zInput - z) + ii + 1);
  147900. if( ii==nInput ){
  147901. return SQLITE_ERROR;
  147902. }
  147903. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  147904. }
  147905. if( sqlite3_fts3_enable_parentheses ){
  147906. if( *zInput=='(' ){
  147907. int nConsumed = 0;
  147908. pParse->nNest++;
  147909. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  147910. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  147911. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  147912. return rc;
  147913. }else if( *zInput==')' ){
  147914. pParse->nNest--;
  147915. *pnConsumed = (int)((zInput - z) + 1);
  147916. *ppExpr = 0;
  147917. return SQLITE_DONE;
  147918. }
  147919. }
  147920. /* If control flows to this point, this must be a regular token, or
  147921. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  147922. ** interface. Before doing so, figure out if there is an explicit
  147923. ** column specifier for the token.
  147924. **
  147925. ** TODO: Strangely, it is not possible to associate a column specifier
  147926. ** with a quoted phrase, only with a single token. Not sure if this was
  147927. ** an implementation artifact or an intentional decision when fts3 was
  147928. ** first implemented. Whichever it was, this module duplicates the
  147929. ** limitation.
  147930. */
  147931. iCol = pParse->iDefaultCol;
  147932. iColLen = 0;
  147933. for(ii=0; ii<pParse->nCol; ii++){
  147934. const char *zStr = pParse->azCol[ii];
  147935. int nStr = (int)strlen(zStr);
  147936. if( nInput>nStr && zInput[nStr]==':'
  147937. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  147938. ){
  147939. iCol = ii;
  147940. iColLen = (int)((zInput - z) + nStr + 1);
  147941. break;
  147942. }
  147943. }
  147944. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  147945. *pnConsumed += iColLen;
  147946. return rc;
  147947. }
  147948. /*
  147949. ** The argument is an Fts3Expr structure for a binary operator (any type
  147950. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  147951. ** precedence of the operator. Lower values have a higher precedence (i.e.
  147952. ** group more tightly). For example, in the C language, the == operator
  147953. ** groups more tightly than ||, and would therefore have a higher precedence.
  147954. **
  147955. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  147956. ** is defined), the order of the operators in precedence from highest to
  147957. ** lowest is:
  147958. **
  147959. ** NEAR
  147960. ** NOT
  147961. ** AND (including implicit ANDs)
  147962. ** OR
  147963. **
  147964. ** Note that when using the old query syntax, the OR operator has a higher
  147965. ** precedence than the AND operator.
  147966. */
  147967. static int opPrecedence(Fts3Expr *p){
  147968. assert( p->eType!=FTSQUERY_PHRASE );
  147969. if( sqlite3_fts3_enable_parentheses ){
  147970. return p->eType;
  147971. }else if( p->eType==FTSQUERY_NEAR ){
  147972. return 1;
  147973. }else if( p->eType==FTSQUERY_OR ){
  147974. return 2;
  147975. }
  147976. assert( p->eType==FTSQUERY_AND );
  147977. return 3;
  147978. }
  147979. /*
  147980. ** Argument ppHead contains a pointer to the current head of a query
  147981. ** expression tree being parsed. pPrev is the expression node most recently
  147982. ** inserted into the tree. This function adds pNew, which is always a binary
  147983. ** operator node, into the expression tree based on the relative precedence
  147984. ** of pNew and the existing nodes of the tree. This may result in the head
  147985. ** of the tree changing, in which case *ppHead is set to the new root node.
  147986. */
  147987. static void insertBinaryOperator(
  147988. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  147989. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  147990. Fts3Expr *pNew /* New binary node to insert into expression tree */
  147991. ){
  147992. Fts3Expr *pSplit = pPrev;
  147993. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  147994. pSplit = pSplit->pParent;
  147995. }
  147996. if( pSplit->pParent ){
  147997. assert( pSplit->pParent->pRight==pSplit );
  147998. pSplit->pParent->pRight = pNew;
  147999. pNew->pParent = pSplit->pParent;
  148000. }else{
  148001. *ppHead = pNew;
  148002. }
  148003. pNew->pLeft = pSplit;
  148004. pSplit->pParent = pNew;
  148005. }
  148006. /*
  148007. ** Parse the fts3 query expression found in buffer z, length n. This function
  148008. ** returns either when the end of the buffer is reached or an unmatched
  148009. ** closing bracket - ')' - is encountered.
  148010. **
  148011. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  148012. ** parsed form of the expression and *pnConsumed is set to the number of
  148013. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  148014. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  148015. */
  148016. static int fts3ExprParse(
  148017. ParseContext *pParse, /* fts3 query parse context */
  148018. const char *z, int n, /* Text of MATCH query */
  148019. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  148020. int *pnConsumed /* OUT: Number of bytes consumed */
  148021. ){
  148022. Fts3Expr *pRet = 0;
  148023. Fts3Expr *pPrev = 0;
  148024. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  148025. int nIn = n;
  148026. const char *zIn = z;
  148027. int rc = SQLITE_OK;
  148028. int isRequirePhrase = 1;
  148029. while( rc==SQLITE_OK ){
  148030. Fts3Expr *p = 0;
  148031. int nByte = 0;
  148032. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  148033. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  148034. if( rc==SQLITE_OK ){
  148035. if( p ){
  148036. int isPhrase;
  148037. if( !sqlite3_fts3_enable_parentheses
  148038. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  148039. ){
  148040. /* Create an implicit NOT operator. */
  148041. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  148042. if( !pNot ){
  148043. sqlite3Fts3ExprFree(p);
  148044. rc = SQLITE_NOMEM;
  148045. goto exprparse_out;
  148046. }
  148047. pNot->eType = FTSQUERY_NOT;
  148048. pNot->pRight = p;
  148049. p->pParent = pNot;
  148050. if( pNotBranch ){
  148051. pNot->pLeft = pNotBranch;
  148052. pNotBranch->pParent = pNot;
  148053. }
  148054. pNotBranch = pNot;
  148055. p = pPrev;
  148056. }else{
  148057. int eType = p->eType;
  148058. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  148059. /* The isRequirePhrase variable is set to true if a phrase or
  148060. ** an expression contained in parenthesis is required. If a
  148061. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  148062. ** isRequirePhrase is set, this is a syntax error.
  148063. */
  148064. if( !isPhrase && isRequirePhrase ){
  148065. sqlite3Fts3ExprFree(p);
  148066. rc = SQLITE_ERROR;
  148067. goto exprparse_out;
  148068. }
  148069. if( isPhrase && !isRequirePhrase ){
  148070. /* Insert an implicit AND operator. */
  148071. Fts3Expr *pAnd;
  148072. assert( pRet && pPrev );
  148073. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  148074. if( !pAnd ){
  148075. sqlite3Fts3ExprFree(p);
  148076. rc = SQLITE_NOMEM;
  148077. goto exprparse_out;
  148078. }
  148079. pAnd->eType = FTSQUERY_AND;
  148080. insertBinaryOperator(&pRet, pPrev, pAnd);
  148081. pPrev = pAnd;
  148082. }
  148083. /* This test catches attempts to make either operand of a NEAR
  148084. ** operator something other than a phrase. For example, either of
  148085. ** the following:
  148086. **
  148087. ** (bracketed expression) NEAR phrase
  148088. ** phrase NEAR (bracketed expression)
  148089. **
  148090. ** Return an error in either case.
  148091. */
  148092. if( pPrev && (
  148093. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  148094. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  148095. )){
  148096. sqlite3Fts3ExprFree(p);
  148097. rc = SQLITE_ERROR;
  148098. goto exprparse_out;
  148099. }
  148100. if( isPhrase ){
  148101. if( pRet ){
  148102. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  148103. pPrev->pRight = p;
  148104. p->pParent = pPrev;
  148105. }else{
  148106. pRet = p;
  148107. }
  148108. }else{
  148109. insertBinaryOperator(&pRet, pPrev, p);
  148110. }
  148111. isRequirePhrase = !isPhrase;
  148112. }
  148113. pPrev = p;
  148114. }
  148115. assert( nByte>0 );
  148116. }
  148117. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  148118. nIn -= nByte;
  148119. zIn += nByte;
  148120. }
  148121. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  148122. rc = SQLITE_ERROR;
  148123. }
  148124. if( rc==SQLITE_DONE ){
  148125. rc = SQLITE_OK;
  148126. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  148127. if( !pRet ){
  148128. rc = SQLITE_ERROR;
  148129. }else{
  148130. Fts3Expr *pIter = pNotBranch;
  148131. while( pIter->pLeft ){
  148132. pIter = pIter->pLeft;
  148133. }
  148134. pIter->pLeft = pRet;
  148135. pRet->pParent = pIter;
  148136. pRet = pNotBranch;
  148137. }
  148138. }
  148139. }
  148140. *pnConsumed = n - nIn;
  148141. exprparse_out:
  148142. if( rc!=SQLITE_OK ){
  148143. sqlite3Fts3ExprFree(pRet);
  148144. sqlite3Fts3ExprFree(pNotBranch);
  148145. pRet = 0;
  148146. }
  148147. *ppExpr = pRet;
  148148. return rc;
  148149. }
  148150. /*
  148151. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  148152. ** as the only argument is more than nMaxDepth.
  148153. */
  148154. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  148155. int rc = SQLITE_OK;
  148156. if( p ){
  148157. if( nMaxDepth<0 ){
  148158. rc = SQLITE_TOOBIG;
  148159. }else{
  148160. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  148161. if( rc==SQLITE_OK ){
  148162. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  148163. }
  148164. }
  148165. }
  148166. return rc;
  148167. }
  148168. /*
  148169. ** This function attempts to transform the expression tree at (*pp) to
  148170. ** an equivalent but more balanced form. The tree is modified in place.
  148171. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  148172. ** new root expression node.
  148173. **
  148174. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  148175. **
  148176. ** Otherwise, if an error occurs, an SQLite error code is returned and
  148177. ** expression (*pp) freed.
  148178. */
  148179. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  148180. int rc = SQLITE_OK; /* Return code */
  148181. Fts3Expr *pRoot = *pp; /* Initial root node */
  148182. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  148183. int eType = pRoot->eType; /* Type of node in this tree */
  148184. if( nMaxDepth==0 ){
  148185. rc = SQLITE_ERROR;
  148186. }
  148187. if( rc==SQLITE_OK ){
  148188. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  148189. Fts3Expr **apLeaf;
  148190. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  148191. if( 0==apLeaf ){
  148192. rc = SQLITE_NOMEM;
  148193. }else{
  148194. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  148195. }
  148196. if( rc==SQLITE_OK ){
  148197. int i;
  148198. Fts3Expr *p;
  148199. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  148200. for(p=pRoot; p->eType==eType; p=p->pLeft){
  148201. assert( p->pParent==0 || p->pParent->pLeft==p );
  148202. assert( p->pLeft && p->pRight );
  148203. }
  148204. /* This loop runs once for each leaf in the tree of eType nodes. */
  148205. while( 1 ){
  148206. int iLvl;
  148207. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  148208. assert( pParent==0 || pParent->pLeft==p );
  148209. p->pParent = 0;
  148210. if( pParent ){
  148211. pParent->pLeft = 0;
  148212. }else{
  148213. pRoot = 0;
  148214. }
  148215. rc = fts3ExprBalance(&p, nMaxDepth-1);
  148216. if( rc!=SQLITE_OK ) break;
  148217. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  148218. if( apLeaf[iLvl]==0 ){
  148219. apLeaf[iLvl] = p;
  148220. p = 0;
  148221. }else{
  148222. assert( pFree );
  148223. pFree->pLeft = apLeaf[iLvl];
  148224. pFree->pRight = p;
  148225. pFree->pLeft->pParent = pFree;
  148226. pFree->pRight->pParent = pFree;
  148227. p = pFree;
  148228. pFree = pFree->pParent;
  148229. p->pParent = 0;
  148230. apLeaf[iLvl] = 0;
  148231. }
  148232. }
  148233. if( p ){
  148234. sqlite3Fts3ExprFree(p);
  148235. rc = SQLITE_TOOBIG;
  148236. break;
  148237. }
  148238. /* If that was the last leaf node, break out of the loop */
  148239. if( pParent==0 ) break;
  148240. /* Set $p to point to the next leaf in the tree of eType nodes */
  148241. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  148242. /* Remove pParent from the original tree. */
  148243. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  148244. pParent->pRight->pParent = pParent->pParent;
  148245. if( pParent->pParent ){
  148246. pParent->pParent->pLeft = pParent->pRight;
  148247. }else{
  148248. assert( pParent==pRoot );
  148249. pRoot = pParent->pRight;
  148250. }
  148251. /* Link pParent into the free node list. It will be used as an
  148252. ** internal node of the new tree. */
  148253. pParent->pParent = pFree;
  148254. pFree = pParent;
  148255. }
  148256. if( rc==SQLITE_OK ){
  148257. p = 0;
  148258. for(i=0; i<nMaxDepth; i++){
  148259. if( apLeaf[i] ){
  148260. if( p==0 ){
  148261. p = apLeaf[i];
  148262. p->pParent = 0;
  148263. }else{
  148264. assert( pFree!=0 );
  148265. pFree->pRight = p;
  148266. pFree->pLeft = apLeaf[i];
  148267. pFree->pLeft->pParent = pFree;
  148268. pFree->pRight->pParent = pFree;
  148269. p = pFree;
  148270. pFree = pFree->pParent;
  148271. p->pParent = 0;
  148272. }
  148273. }
  148274. }
  148275. pRoot = p;
  148276. }else{
  148277. /* An error occurred. Delete the contents of the apLeaf[] array
  148278. ** and pFree list. Everything else is cleaned up by the call to
  148279. ** sqlite3Fts3ExprFree(pRoot) below. */
  148280. Fts3Expr *pDel;
  148281. for(i=0; i<nMaxDepth; i++){
  148282. sqlite3Fts3ExprFree(apLeaf[i]);
  148283. }
  148284. while( (pDel=pFree)!=0 ){
  148285. pFree = pDel->pParent;
  148286. sqlite3_free(pDel);
  148287. }
  148288. }
  148289. assert( pFree==0 );
  148290. sqlite3_free( apLeaf );
  148291. }
  148292. }else if( eType==FTSQUERY_NOT ){
  148293. Fts3Expr *pLeft = pRoot->pLeft;
  148294. Fts3Expr *pRight = pRoot->pRight;
  148295. pRoot->pLeft = 0;
  148296. pRoot->pRight = 0;
  148297. pLeft->pParent = 0;
  148298. pRight->pParent = 0;
  148299. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  148300. if( rc==SQLITE_OK ){
  148301. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  148302. }
  148303. if( rc!=SQLITE_OK ){
  148304. sqlite3Fts3ExprFree(pRight);
  148305. sqlite3Fts3ExprFree(pLeft);
  148306. }else{
  148307. assert( pLeft && pRight );
  148308. pRoot->pLeft = pLeft;
  148309. pLeft->pParent = pRoot;
  148310. pRoot->pRight = pRight;
  148311. pRight->pParent = pRoot;
  148312. }
  148313. }
  148314. }
  148315. if( rc!=SQLITE_OK ){
  148316. sqlite3Fts3ExprFree(pRoot);
  148317. pRoot = 0;
  148318. }
  148319. *pp = pRoot;
  148320. return rc;
  148321. }
  148322. /*
  148323. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  148324. ** differences:
  148325. **
  148326. ** 1. It does not do expression rebalancing.
  148327. ** 2. It does not check that the expression does not exceed the
  148328. ** maximum allowable depth.
  148329. ** 3. Even if it fails, *ppExpr may still be set to point to an
  148330. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  148331. ** in this case.
  148332. */
  148333. static int fts3ExprParseUnbalanced(
  148334. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  148335. int iLangid, /* Language id for tokenizer */
  148336. char **azCol, /* Array of column names for fts3 table */
  148337. int bFts4, /* True to allow FTS4-only syntax */
  148338. int nCol, /* Number of entries in azCol[] */
  148339. int iDefaultCol, /* Default column to query */
  148340. const char *z, int n, /* Text of MATCH query */
  148341. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  148342. ){
  148343. int nParsed;
  148344. int rc;
  148345. ParseContext sParse;
  148346. memset(&sParse, 0, sizeof(ParseContext));
  148347. sParse.pTokenizer = pTokenizer;
  148348. sParse.iLangid = iLangid;
  148349. sParse.azCol = (const char **)azCol;
  148350. sParse.nCol = nCol;
  148351. sParse.iDefaultCol = iDefaultCol;
  148352. sParse.bFts4 = bFts4;
  148353. if( z==0 ){
  148354. *ppExpr = 0;
  148355. return SQLITE_OK;
  148356. }
  148357. if( n<0 ){
  148358. n = (int)strlen(z);
  148359. }
  148360. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  148361. assert( rc==SQLITE_OK || *ppExpr==0 );
  148362. /* Check for mismatched parenthesis */
  148363. if( rc==SQLITE_OK && sParse.nNest ){
  148364. rc = SQLITE_ERROR;
  148365. }
  148366. return rc;
  148367. }
  148368. /*
  148369. ** Parameters z and n contain a pointer to and length of a buffer containing
  148370. ** an fts3 query expression, respectively. This function attempts to parse the
  148371. ** query expression and create a tree of Fts3Expr structures representing the
  148372. ** parsed expression. If successful, *ppExpr is set to point to the head
  148373. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  148374. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  148375. ** error) is returned and *ppExpr is set to 0.
  148376. **
  148377. ** If parameter n is a negative number, then z is assumed to point to a
  148378. ** nul-terminated string and the length is determined using strlen().
  148379. **
  148380. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  148381. ** use to normalize query tokens while parsing the expression. The azCol[]
  148382. ** array, which is assumed to contain nCol entries, should contain the names
  148383. ** of each column in the target fts3 table, in order from left to right.
  148384. ** Column names must be nul-terminated strings.
  148385. **
  148386. ** The iDefaultCol parameter should be passed the index of the table column
  148387. ** that appears on the left-hand-side of the MATCH operator (the default
  148388. ** column to match against for tokens for which a column name is not explicitly
  148389. ** specified as part of the query string), or -1 if tokens may by default
  148390. ** match any table column.
  148391. */
  148392. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  148393. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  148394. int iLangid, /* Language id for tokenizer */
  148395. char **azCol, /* Array of column names for fts3 table */
  148396. int bFts4, /* True to allow FTS4-only syntax */
  148397. int nCol, /* Number of entries in azCol[] */
  148398. int iDefaultCol, /* Default column to query */
  148399. const char *z, int n, /* Text of MATCH query */
  148400. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  148401. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  148402. ){
  148403. int rc = fts3ExprParseUnbalanced(
  148404. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  148405. );
  148406. /* Rebalance the expression. And check that its depth does not exceed
  148407. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  148408. if( rc==SQLITE_OK && *ppExpr ){
  148409. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  148410. if( rc==SQLITE_OK ){
  148411. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  148412. }
  148413. }
  148414. if( rc!=SQLITE_OK ){
  148415. sqlite3Fts3ExprFree(*ppExpr);
  148416. *ppExpr = 0;
  148417. if( rc==SQLITE_TOOBIG ){
  148418. sqlite3Fts3ErrMsg(pzErr,
  148419. "FTS expression tree is too large (maximum depth %d)",
  148420. SQLITE_FTS3_MAX_EXPR_DEPTH
  148421. );
  148422. rc = SQLITE_ERROR;
  148423. }else if( rc==SQLITE_ERROR ){
  148424. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  148425. }
  148426. }
  148427. return rc;
  148428. }
  148429. /*
  148430. ** Free a single node of an expression tree.
  148431. */
  148432. static void fts3FreeExprNode(Fts3Expr *p){
  148433. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  148434. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  148435. sqlite3_free(p->aMI);
  148436. sqlite3_free(p);
  148437. }
  148438. /*
  148439. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  148440. **
  148441. ** This function would be simpler if it recursively called itself. But
  148442. ** that would mean passing a sufficiently large expression to ExprParse()
  148443. ** could cause a stack overflow.
  148444. */
  148445. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  148446. Fts3Expr *p;
  148447. assert( pDel==0 || pDel->pParent==0 );
  148448. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  148449. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  148450. }
  148451. while( p ){
  148452. Fts3Expr *pParent = p->pParent;
  148453. fts3FreeExprNode(p);
  148454. if( pParent && p==pParent->pLeft && pParent->pRight ){
  148455. p = pParent->pRight;
  148456. while( p && (p->pLeft || p->pRight) ){
  148457. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  148458. p = (p->pLeft ? p->pLeft : p->pRight);
  148459. }
  148460. }else{
  148461. p = pParent;
  148462. }
  148463. }
  148464. }
  148465. /****************************************************************************
  148466. *****************************************************************************
  148467. ** Everything after this point is just test code.
  148468. */
  148469. #ifdef SQLITE_TEST
  148470. /* #include <stdio.h> */
  148471. /*
  148472. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  148473. */
  148474. static int queryTestTokenizer(
  148475. sqlite3 *db,
  148476. const char *zName,
  148477. const sqlite3_tokenizer_module **pp
  148478. ){
  148479. int rc;
  148480. sqlite3_stmt *pStmt;
  148481. const char zSql[] = "SELECT fts3_tokenizer(?)";
  148482. *pp = 0;
  148483. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  148484. if( rc!=SQLITE_OK ){
  148485. return rc;
  148486. }
  148487. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  148488. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  148489. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  148490. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  148491. }
  148492. }
  148493. return sqlite3_finalize(pStmt);
  148494. }
  148495. /*
  148496. ** Return a pointer to a buffer containing a text representation of the
  148497. ** expression passed as the first argument. The buffer is obtained from
  148498. ** sqlite3_malloc(). It is the responsibility of the caller to use
  148499. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  148500. ** NULL is returned.
  148501. **
  148502. ** If the second argument is not NULL, then its contents are prepended to
  148503. ** the returned expression text and then freed using sqlite3_free().
  148504. */
  148505. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  148506. if( pExpr==0 ){
  148507. return sqlite3_mprintf("");
  148508. }
  148509. switch( pExpr->eType ){
  148510. case FTSQUERY_PHRASE: {
  148511. Fts3Phrase *pPhrase = pExpr->pPhrase;
  148512. int i;
  148513. zBuf = sqlite3_mprintf(
  148514. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  148515. for(i=0; zBuf && i<pPhrase->nToken; i++){
  148516. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  148517. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  148518. (pPhrase->aToken[i].isPrefix?"+":"")
  148519. );
  148520. }
  148521. return zBuf;
  148522. }
  148523. case FTSQUERY_NEAR:
  148524. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  148525. break;
  148526. case FTSQUERY_NOT:
  148527. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  148528. break;
  148529. case FTSQUERY_AND:
  148530. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  148531. break;
  148532. case FTSQUERY_OR:
  148533. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  148534. break;
  148535. }
  148536. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  148537. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  148538. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  148539. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  148540. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  148541. return zBuf;
  148542. }
  148543. /*
  148544. ** This is the implementation of a scalar SQL function used to test the
  148545. ** expression parser. It should be called as follows:
  148546. **
  148547. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  148548. **
  148549. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  148550. ** to parse the query expression (see README.tokenizers). The second argument
  148551. ** is the query expression to parse. Each subsequent argument is the name
  148552. ** of a column of the fts3 table that the query expression may refer to.
  148553. ** For example:
  148554. **
  148555. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  148556. */
  148557. static void fts3ExprTest(
  148558. sqlite3_context *context,
  148559. int argc,
  148560. sqlite3_value **argv
  148561. ){
  148562. sqlite3_tokenizer_module const *pModule = 0;
  148563. sqlite3_tokenizer *pTokenizer = 0;
  148564. int rc;
  148565. char **azCol = 0;
  148566. const char *zExpr;
  148567. int nExpr;
  148568. int nCol;
  148569. int ii;
  148570. Fts3Expr *pExpr;
  148571. char *zBuf = 0;
  148572. sqlite3 *db = sqlite3_context_db_handle(context);
  148573. if( argc<3 ){
  148574. sqlite3_result_error(context,
  148575. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  148576. );
  148577. return;
  148578. }
  148579. rc = queryTestTokenizer(db,
  148580. (const char *)sqlite3_value_text(argv[0]), &pModule);
  148581. if( rc==SQLITE_NOMEM ){
  148582. sqlite3_result_error_nomem(context);
  148583. goto exprtest_out;
  148584. }else if( !pModule ){
  148585. sqlite3_result_error(context, "No such tokenizer module", -1);
  148586. goto exprtest_out;
  148587. }
  148588. rc = pModule->xCreate(0, 0, &pTokenizer);
  148589. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  148590. if( rc==SQLITE_NOMEM ){
  148591. sqlite3_result_error_nomem(context);
  148592. goto exprtest_out;
  148593. }
  148594. pTokenizer->pModule = pModule;
  148595. zExpr = (const char *)sqlite3_value_text(argv[1]);
  148596. nExpr = sqlite3_value_bytes(argv[1]);
  148597. nCol = argc-2;
  148598. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  148599. if( !azCol ){
  148600. sqlite3_result_error_nomem(context);
  148601. goto exprtest_out;
  148602. }
  148603. for(ii=0; ii<nCol; ii++){
  148604. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  148605. }
  148606. if( sqlite3_user_data(context) ){
  148607. char *zDummy = 0;
  148608. rc = sqlite3Fts3ExprParse(
  148609. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  148610. );
  148611. assert( rc==SQLITE_OK || pExpr==0 );
  148612. sqlite3_free(zDummy);
  148613. }else{
  148614. rc = fts3ExprParseUnbalanced(
  148615. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  148616. );
  148617. }
  148618. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  148619. sqlite3Fts3ExprFree(pExpr);
  148620. sqlite3_result_error(context, "Error parsing expression", -1);
  148621. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  148622. sqlite3_result_error_nomem(context);
  148623. }else{
  148624. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  148625. sqlite3_free(zBuf);
  148626. }
  148627. sqlite3Fts3ExprFree(pExpr);
  148628. exprtest_out:
  148629. if( pModule && pTokenizer ){
  148630. rc = pModule->xDestroy(pTokenizer);
  148631. }
  148632. sqlite3_free(azCol);
  148633. }
  148634. /*
  148635. ** Register the query expression parser test function fts3_exprtest()
  148636. ** with database connection db.
  148637. */
  148638. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  148639. int rc = sqlite3_create_function(
  148640. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  148641. );
  148642. if( rc==SQLITE_OK ){
  148643. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  148644. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  148645. );
  148646. }
  148647. return rc;
  148648. }
  148649. #endif
  148650. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  148651. /************** End of fts3_expr.c *******************************************/
  148652. /************** Begin file fts3_hash.c ***************************************/
  148653. /*
  148654. ** 2001 September 22
  148655. **
  148656. ** The author disclaims copyright to this source code. In place of
  148657. ** a legal notice, here is a blessing:
  148658. **
  148659. ** May you do good and not evil.
  148660. ** May you find forgiveness for yourself and forgive others.
  148661. ** May you share freely, never taking more than you give.
  148662. **
  148663. *************************************************************************
  148664. ** This is the implementation of generic hash-tables used in SQLite.
  148665. ** We've modified it slightly to serve as a standalone hash table
  148666. ** implementation for the full-text indexing module.
  148667. */
  148668. /*
  148669. ** The code in this file is only compiled if:
  148670. **
  148671. ** * The FTS3 module is being built as an extension
  148672. ** (in which case SQLITE_CORE is not defined), or
  148673. **
  148674. ** * The FTS3 module is being built into the core of
  148675. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  148676. */
  148677. /* #include "fts3Int.h" */
  148678. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  148679. /* #include <assert.h> */
  148680. /* #include <stdlib.h> */
  148681. /* #include <string.h> */
  148682. /* #include "fts3_hash.h" */
  148683. /*
  148684. ** Malloc and Free functions
  148685. */
  148686. static void *fts3HashMalloc(int n){
  148687. void *p = sqlite3_malloc(n);
  148688. if( p ){
  148689. memset(p, 0, n);
  148690. }
  148691. return p;
  148692. }
  148693. static void fts3HashFree(void *p){
  148694. sqlite3_free(p);
  148695. }
  148696. /* Turn bulk memory into a hash table object by initializing the
  148697. ** fields of the Hash structure.
  148698. **
  148699. ** "pNew" is a pointer to the hash table that is to be initialized.
  148700. ** keyClass is one of the constants
  148701. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  148702. ** determines what kind of key the hash table will use. "copyKey" is
  148703. ** true if the hash table should make its own private copy of keys and
  148704. ** false if it should just use the supplied pointer.
  148705. */
  148706. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  148707. assert( pNew!=0 );
  148708. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  148709. pNew->keyClass = keyClass;
  148710. pNew->copyKey = copyKey;
  148711. pNew->first = 0;
  148712. pNew->count = 0;
  148713. pNew->htsize = 0;
  148714. pNew->ht = 0;
  148715. }
  148716. /* Remove all entries from a hash table. Reclaim all memory.
  148717. ** Call this routine to delete a hash table or to reset a hash table
  148718. ** to the empty state.
  148719. */
  148720. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  148721. Fts3HashElem *elem; /* For looping over all elements of the table */
  148722. assert( pH!=0 );
  148723. elem = pH->first;
  148724. pH->first = 0;
  148725. fts3HashFree(pH->ht);
  148726. pH->ht = 0;
  148727. pH->htsize = 0;
  148728. while( elem ){
  148729. Fts3HashElem *next_elem = elem->next;
  148730. if( pH->copyKey && elem->pKey ){
  148731. fts3HashFree(elem->pKey);
  148732. }
  148733. fts3HashFree(elem);
  148734. elem = next_elem;
  148735. }
  148736. pH->count = 0;
  148737. }
  148738. /*
  148739. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  148740. */
  148741. static int fts3StrHash(const void *pKey, int nKey){
  148742. const char *z = (const char *)pKey;
  148743. unsigned h = 0;
  148744. if( nKey<=0 ) nKey = (int) strlen(z);
  148745. while( nKey > 0 ){
  148746. h = (h<<3) ^ h ^ *z++;
  148747. nKey--;
  148748. }
  148749. return (int)(h & 0x7fffffff);
  148750. }
  148751. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  148752. if( n1!=n2 ) return 1;
  148753. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  148754. }
  148755. /*
  148756. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  148757. */
  148758. static int fts3BinHash(const void *pKey, int nKey){
  148759. int h = 0;
  148760. const char *z = (const char *)pKey;
  148761. while( nKey-- > 0 ){
  148762. h = (h<<3) ^ h ^ *(z++);
  148763. }
  148764. return h & 0x7fffffff;
  148765. }
  148766. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  148767. if( n1!=n2 ) return 1;
  148768. return memcmp(pKey1,pKey2,n1);
  148769. }
  148770. /*
  148771. ** Return a pointer to the appropriate hash function given the key class.
  148772. **
  148773. ** The C syntax in this function definition may be unfamilar to some
  148774. ** programmers, so we provide the following additional explanation:
  148775. **
  148776. ** The name of the function is "ftsHashFunction". The function takes a
  148777. ** single parameter "keyClass". The return value of ftsHashFunction()
  148778. ** is a pointer to another function. Specifically, the return value
  148779. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  148780. ** with types "const void*" and "int" and returns an "int".
  148781. */
  148782. static int (*ftsHashFunction(int keyClass))(const void*,int){
  148783. if( keyClass==FTS3_HASH_STRING ){
  148784. return &fts3StrHash;
  148785. }else{
  148786. assert( keyClass==FTS3_HASH_BINARY );
  148787. return &fts3BinHash;
  148788. }
  148789. }
  148790. /*
  148791. ** Return a pointer to the appropriate hash function given the key class.
  148792. **
  148793. ** For help in interpreted the obscure C code in the function definition,
  148794. ** see the header comment on the previous function.
  148795. */
  148796. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  148797. if( keyClass==FTS3_HASH_STRING ){
  148798. return &fts3StrCompare;
  148799. }else{
  148800. assert( keyClass==FTS3_HASH_BINARY );
  148801. return &fts3BinCompare;
  148802. }
  148803. }
  148804. /* Link an element into the hash table
  148805. */
  148806. static void fts3HashInsertElement(
  148807. Fts3Hash *pH, /* The complete hash table */
  148808. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  148809. Fts3HashElem *pNew /* The element to be inserted */
  148810. ){
  148811. Fts3HashElem *pHead; /* First element already in pEntry */
  148812. pHead = pEntry->chain;
  148813. if( pHead ){
  148814. pNew->next = pHead;
  148815. pNew->prev = pHead->prev;
  148816. if( pHead->prev ){ pHead->prev->next = pNew; }
  148817. else { pH->first = pNew; }
  148818. pHead->prev = pNew;
  148819. }else{
  148820. pNew->next = pH->first;
  148821. if( pH->first ){ pH->first->prev = pNew; }
  148822. pNew->prev = 0;
  148823. pH->first = pNew;
  148824. }
  148825. pEntry->count++;
  148826. pEntry->chain = pNew;
  148827. }
  148828. /* Resize the hash table so that it cantains "new_size" buckets.
  148829. ** "new_size" must be a power of 2. The hash table might fail
  148830. ** to resize if sqliteMalloc() fails.
  148831. **
  148832. ** Return non-zero if a memory allocation error occurs.
  148833. */
  148834. static int fts3Rehash(Fts3Hash *pH, int new_size){
  148835. struct _fts3ht *new_ht; /* The new hash table */
  148836. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  148837. int (*xHash)(const void*,int); /* The hash function */
  148838. assert( (new_size & (new_size-1))==0 );
  148839. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  148840. if( new_ht==0 ) return 1;
  148841. fts3HashFree(pH->ht);
  148842. pH->ht = new_ht;
  148843. pH->htsize = new_size;
  148844. xHash = ftsHashFunction(pH->keyClass);
  148845. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  148846. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  148847. next_elem = elem->next;
  148848. fts3HashInsertElement(pH, &new_ht[h], elem);
  148849. }
  148850. return 0;
  148851. }
  148852. /* This function (for internal use only) locates an element in an
  148853. ** hash table that matches the given key. The hash for this key has
  148854. ** already been computed and is passed as the 4th parameter.
  148855. */
  148856. static Fts3HashElem *fts3FindElementByHash(
  148857. const Fts3Hash *pH, /* The pH to be searched */
  148858. const void *pKey, /* The key we are searching for */
  148859. int nKey,
  148860. int h /* The hash for this key. */
  148861. ){
  148862. Fts3HashElem *elem; /* Used to loop thru the element list */
  148863. int count; /* Number of elements left to test */
  148864. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  148865. if( pH->ht ){
  148866. struct _fts3ht *pEntry = &pH->ht[h];
  148867. elem = pEntry->chain;
  148868. count = pEntry->count;
  148869. xCompare = ftsCompareFunction(pH->keyClass);
  148870. while( count-- && elem ){
  148871. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  148872. return elem;
  148873. }
  148874. elem = elem->next;
  148875. }
  148876. }
  148877. return 0;
  148878. }
  148879. /* Remove a single entry from the hash table given a pointer to that
  148880. ** element and a hash on the element's key.
  148881. */
  148882. static void fts3RemoveElementByHash(
  148883. Fts3Hash *pH, /* The pH containing "elem" */
  148884. Fts3HashElem* elem, /* The element to be removed from the pH */
  148885. int h /* Hash value for the element */
  148886. ){
  148887. struct _fts3ht *pEntry;
  148888. if( elem->prev ){
  148889. elem->prev->next = elem->next;
  148890. }else{
  148891. pH->first = elem->next;
  148892. }
  148893. if( elem->next ){
  148894. elem->next->prev = elem->prev;
  148895. }
  148896. pEntry = &pH->ht[h];
  148897. if( pEntry->chain==elem ){
  148898. pEntry->chain = elem->next;
  148899. }
  148900. pEntry->count--;
  148901. if( pEntry->count<=0 ){
  148902. pEntry->chain = 0;
  148903. }
  148904. if( pH->copyKey && elem->pKey ){
  148905. fts3HashFree(elem->pKey);
  148906. }
  148907. fts3HashFree( elem );
  148908. pH->count--;
  148909. if( pH->count<=0 ){
  148910. assert( pH->first==0 );
  148911. assert( pH->count==0 );
  148912. fts3HashClear(pH);
  148913. }
  148914. }
  148915. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  148916. const Fts3Hash *pH,
  148917. const void *pKey,
  148918. int nKey
  148919. ){
  148920. int h; /* A hash on key */
  148921. int (*xHash)(const void*,int); /* The hash function */
  148922. if( pH==0 || pH->ht==0 ) return 0;
  148923. xHash = ftsHashFunction(pH->keyClass);
  148924. assert( xHash!=0 );
  148925. h = (*xHash)(pKey,nKey);
  148926. assert( (pH->htsize & (pH->htsize-1))==0 );
  148927. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  148928. }
  148929. /*
  148930. ** Attempt to locate an element of the hash table pH with a key
  148931. ** that matches pKey,nKey. Return the data for this element if it is
  148932. ** found, or NULL if there is no match.
  148933. */
  148934. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  148935. Fts3HashElem *pElem; /* The element that matches key (if any) */
  148936. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  148937. return pElem ? pElem->data : 0;
  148938. }
  148939. /* Insert an element into the hash table pH. The key is pKey,nKey
  148940. ** and the data is "data".
  148941. **
  148942. ** If no element exists with a matching key, then a new
  148943. ** element is created. A copy of the key is made if the copyKey
  148944. ** flag is set. NULL is returned.
  148945. **
  148946. ** If another element already exists with the same key, then the
  148947. ** new data replaces the old data and the old data is returned.
  148948. ** The key is not copied in this instance. If a malloc fails, then
  148949. ** the new data is returned and the hash table is unchanged.
  148950. **
  148951. ** If the "data" parameter to this function is NULL, then the
  148952. ** element corresponding to "key" is removed from the hash table.
  148953. */
  148954. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  148955. Fts3Hash *pH, /* The hash table to insert into */
  148956. const void *pKey, /* The key */
  148957. int nKey, /* Number of bytes in the key */
  148958. void *data /* The data */
  148959. ){
  148960. int hraw; /* Raw hash value of the key */
  148961. int h; /* the hash of the key modulo hash table size */
  148962. Fts3HashElem *elem; /* Used to loop thru the element list */
  148963. Fts3HashElem *new_elem; /* New element added to the pH */
  148964. int (*xHash)(const void*,int); /* The hash function */
  148965. assert( pH!=0 );
  148966. xHash = ftsHashFunction(pH->keyClass);
  148967. assert( xHash!=0 );
  148968. hraw = (*xHash)(pKey, nKey);
  148969. assert( (pH->htsize & (pH->htsize-1))==0 );
  148970. h = hraw & (pH->htsize-1);
  148971. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  148972. if( elem ){
  148973. void *old_data = elem->data;
  148974. if( data==0 ){
  148975. fts3RemoveElementByHash(pH,elem,h);
  148976. }else{
  148977. elem->data = data;
  148978. }
  148979. return old_data;
  148980. }
  148981. if( data==0 ) return 0;
  148982. if( (pH->htsize==0 && fts3Rehash(pH,8))
  148983. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  148984. ){
  148985. pH->count = 0;
  148986. return data;
  148987. }
  148988. assert( pH->htsize>0 );
  148989. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  148990. if( new_elem==0 ) return data;
  148991. if( pH->copyKey && pKey!=0 ){
  148992. new_elem->pKey = fts3HashMalloc( nKey );
  148993. if( new_elem->pKey==0 ){
  148994. fts3HashFree(new_elem);
  148995. return data;
  148996. }
  148997. memcpy((void*)new_elem->pKey, pKey, nKey);
  148998. }else{
  148999. new_elem->pKey = (void*)pKey;
  149000. }
  149001. new_elem->nKey = nKey;
  149002. pH->count++;
  149003. assert( pH->htsize>0 );
  149004. assert( (pH->htsize & (pH->htsize-1))==0 );
  149005. h = hraw & (pH->htsize-1);
  149006. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  149007. new_elem->data = data;
  149008. return 0;
  149009. }
  149010. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  149011. /************** End of fts3_hash.c *******************************************/
  149012. /************** Begin file fts3_porter.c *************************************/
  149013. /*
  149014. ** 2006 September 30
  149015. **
  149016. ** The author disclaims copyright to this source code. In place of
  149017. ** a legal notice, here is a blessing:
  149018. **
  149019. ** May you do good and not evil.
  149020. ** May you find forgiveness for yourself and forgive others.
  149021. ** May you share freely, never taking more than you give.
  149022. **
  149023. *************************************************************************
  149024. ** Implementation of the full-text-search tokenizer that implements
  149025. ** a Porter stemmer.
  149026. */
  149027. /*
  149028. ** The code in this file is only compiled if:
  149029. **
  149030. ** * The FTS3 module is being built as an extension
  149031. ** (in which case SQLITE_CORE is not defined), or
  149032. **
  149033. ** * The FTS3 module is being built into the core of
  149034. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  149035. */
  149036. /* #include "fts3Int.h" */
  149037. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  149038. /* #include <assert.h> */
  149039. /* #include <stdlib.h> */
  149040. /* #include <stdio.h> */
  149041. /* #include <string.h> */
  149042. /* #include "fts3_tokenizer.h" */
  149043. /*
  149044. ** Class derived from sqlite3_tokenizer
  149045. */
  149046. typedef struct porter_tokenizer {
  149047. sqlite3_tokenizer base; /* Base class */
  149048. } porter_tokenizer;
  149049. /*
  149050. ** Class derived from sqlite3_tokenizer_cursor
  149051. */
  149052. typedef struct porter_tokenizer_cursor {
  149053. sqlite3_tokenizer_cursor base;
  149054. const char *zInput; /* input we are tokenizing */
  149055. int nInput; /* size of the input */
  149056. int iOffset; /* current position in zInput */
  149057. int iToken; /* index of next token to be returned */
  149058. char *zToken; /* storage for current token */
  149059. int nAllocated; /* space allocated to zToken buffer */
  149060. } porter_tokenizer_cursor;
  149061. /*
  149062. ** Create a new tokenizer instance.
  149063. */
  149064. static int porterCreate(
  149065. int argc, const char * const *argv,
  149066. sqlite3_tokenizer **ppTokenizer
  149067. ){
  149068. porter_tokenizer *t;
  149069. UNUSED_PARAMETER(argc);
  149070. UNUSED_PARAMETER(argv);
  149071. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  149072. if( t==NULL ) return SQLITE_NOMEM;
  149073. memset(t, 0, sizeof(*t));
  149074. *ppTokenizer = &t->base;
  149075. return SQLITE_OK;
  149076. }
  149077. /*
  149078. ** Destroy a tokenizer
  149079. */
  149080. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  149081. sqlite3_free(pTokenizer);
  149082. return SQLITE_OK;
  149083. }
  149084. /*
  149085. ** Prepare to begin tokenizing a particular string. The input
  149086. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  149087. ** used to incrementally tokenize this string is returned in
  149088. ** *ppCursor.
  149089. */
  149090. static int porterOpen(
  149091. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  149092. const char *zInput, int nInput, /* String to be tokenized */
  149093. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  149094. ){
  149095. porter_tokenizer_cursor *c;
  149096. UNUSED_PARAMETER(pTokenizer);
  149097. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  149098. if( c==NULL ) return SQLITE_NOMEM;
  149099. c->zInput = zInput;
  149100. if( zInput==0 ){
  149101. c->nInput = 0;
  149102. }else if( nInput<0 ){
  149103. c->nInput = (int)strlen(zInput);
  149104. }else{
  149105. c->nInput = nInput;
  149106. }
  149107. c->iOffset = 0; /* start tokenizing at the beginning */
  149108. c->iToken = 0;
  149109. c->zToken = NULL; /* no space allocated, yet. */
  149110. c->nAllocated = 0;
  149111. *ppCursor = &c->base;
  149112. return SQLITE_OK;
  149113. }
  149114. /*
  149115. ** Close a tokenization cursor previously opened by a call to
  149116. ** porterOpen() above.
  149117. */
  149118. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  149119. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  149120. sqlite3_free(c->zToken);
  149121. sqlite3_free(c);
  149122. return SQLITE_OK;
  149123. }
  149124. /*
  149125. ** Vowel or consonant
  149126. */
  149127. static const char cType[] = {
  149128. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  149129. 1, 1, 1, 2, 1
  149130. };
  149131. /*
  149132. ** isConsonant() and isVowel() determine if their first character in
  149133. ** the string they point to is a consonant or a vowel, according
  149134. ** to Porter ruls.
  149135. **
  149136. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  149137. ** 'Y' is a consonant unless it follows another consonant,
  149138. ** in which case it is a vowel.
  149139. **
  149140. ** In these routine, the letters are in reverse order. So the 'y' rule
  149141. ** is that 'y' is a consonant unless it is followed by another
  149142. ** consonent.
  149143. */
  149144. static int isVowel(const char*);
  149145. static int isConsonant(const char *z){
  149146. int j;
  149147. char x = *z;
  149148. if( x==0 ) return 0;
  149149. assert( x>='a' && x<='z' );
  149150. j = cType[x-'a'];
  149151. if( j<2 ) return j;
  149152. return z[1]==0 || isVowel(z + 1);
  149153. }
  149154. static int isVowel(const char *z){
  149155. int j;
  149156. char x = *z;
  149157. if( x==0 ) return 0;
  149158. assert( x>='a' && x<='z' );
  149159. j = cType[x-'a'];
  149160. if( j<2 ) return 1-j;
  149161. return isConsonant(z + 1);
  149162. }
  149163. /*
  149164. ** Let any sequence of one or more vowels be represented by V and let
  149165. ** C be sequence of one or more consonants. Then every word can be
  149166. ** represented as:
  149167. **
  149168. ** [C] (VC){m} [V]
  149169. **
  149170. ** In prose: A word is an optional consonant followed by zero or
  149171. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  149172. ** number of vowel consonant pairs. This routine computes the value
  149173. ** of m for the first i bytes of a word.
  149174. **
  149175. ** Return true if the m-value for z is 1 or more. In other words,
  149176. ** return true if z contains at least one vowel that is followed
  149177. ** by a consonant.
  149178. **
  149179. ** In this routine z[] is in reverse order. So we are really looking
  149180. ** for an instance of a consonant followed by a vowel.
  149181. */
  149182. static int m_gt_0(const char *z){
  149183. while( isVowel(z) ){ z++; }
  149184. if( *z==0 ) return 0;
  149185. while( isConsonant(z) ){ z++; }
  149186. return *z!=0;
  149187. }
  149188. /* Like mgt0 above except we are looking for a value of m which is
  149189. ** exactly 1
  149190. */
  149191. static int m_eq_1(const char *z){
  149192. while( isVowel(z) ){ z++; }
  149193. if( *z==0 ) return 0;
  149194. while( isConsonant(z) ){ z++; }
  149195. if( *z==0 ) return 0;
  149196. while( isVowel(z) ){ z++; }
  149197. if( *z==0 ) return 1;
  149198. while( isConsonant(z) ){ z++; }
  149199. return *z==0;
  149200. }
  149201. /* Like mgt0 above except we are looking for a value of m>1 instead
  149202. ** or m>0
  149203. */
  149204. static int m_gt_1(const char *z){
  149205. while( isVowel(z) ){ z++; }
  149206. if( *z==0 ) return 0;
  149207. while( isConsonant(z) ){ z++; }
  149208. if( *z==0 ) return 0;
  149209. while( isVowel(z) ){ z++; }
  149210. if( *z==0 ) return 0;
  149211. while( isConsonant(z) ){ z++; }
  149212. return *z!=0;
  149213. }
  149214. /*
  149215. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  149216. */
  149217. static int hasVowel(const char *z){
  149218. while( isConsonant(z) ){ z++; }
  149219. return *z!=0;
  149220. }
  149221. /*
  149222. ** Return TRUE if the word ends in a double consonant.
  149223. **
  149224. ** The text is reversed here. So we are really looking at
  149225. ** the first two characters of z[].
  149226. */
  149227. static int doubleConsonant(const char *z){
  149228. return isConsonant(z) && z[0]==z[1];
  149229. }
  149230. /*
  149231. ** Return TRUE if the word ends with three letters which
  149232. ** are consonant-vowel-consonent and where the final consonant
  149233. ** is not 'w', 'x', or 'y'.
  149234. **
  149235. ** The word is reversed here. So we are really checking the
  149236. ** first three letters and the first one cannot be in [wxy].
  149237. */
  149238. static int star_oh(const char *z){
  149239. return
  149240. isConsonant(z) &&
  149241. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  149242. isVowel(z+1) &&
  149243. isConsonant(z+2);
  149244. }
  149245. /*
  149246. ** If the word ends with zFrom and xCond() is true for the stem
  149247. ** of the word that preceeds the zFrom ending, then change the
  149248. ** ending to zTo.
  149249. **
  149250. ** The input word *pz and zFrom are both in reverse order. zTo
  149251. ** is in normal order.
  149252. **
  149253. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  149254. ** match. Not that TRUE is returned even if xCond() fails and
  149255. ** no substitution occurs.
  149256. */
  149257. static int stem(
  149258. char **pz, /* The word being stemmed (Reversed) */
  149259. const char *zFrom, /* If the ending matches this... (Reversed) */
  149260. const char *zTo, /* ... change the ending to this (not reversed) */
  149261. int (*xCond)(const char*) /* Condition that must be true */
  149262. ){
  149263. char *z = *pz;
  149264. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  149265. if( *zFrom!=0 ) return 0;
  149266. if( xCond && !xCond(z) ) return 1;
  149267. while( *zTo ){
  149268. *(--z) = *(zTo++);
  149269. }
  149270. *pz = z;
  149271. return 1;
  149272. }
  149273. /*
  149274. ** This is the fallback stemmer used when the porter stemmer is
  149275. ** inappropriate. The input word is copied into the output with
  149276. ** US-ASCII case folding. If the input word is too long (more
  149277. ** than 20 bytes if it contains no digits or more than 6 bytes if
  149278. ** it contains digits) then word is truncated to 20 or 6 bytes
  149279. ** by taking 10 or 3 bytes from the beginning and end.
  149280. */
  149281. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  149282. int i, mx, j;
  149283. int hasDigit = 0;
  149284. for(i=0; i<nIn; i++){
  149285. char c = zIn[i];
  149286. if( c>='A' && c<='Z' ){
  149287. zOut[i] = c - 'A' + 'a';
  149288. }else{
  149289. if( c>='0' && c<='9' ) hasDigit = 1;
  149290. zOut[i] = c;
  149291. }
  149292. }
  149293. mx = hasDigit ? 3 : 10;
  149294. if( nIn>mx*2 ){
  149295. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  149296. zOut[j] = zOut[i];
  149297. }
  149298. i = j;
  149299. }
  149300. zOut[i] = 0;
  149301. *pnOut = i;
  149302. }
  149303. /*
  149304. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  149305. ** zOut is at least big enough to hold nIn bytes. Write the actual
  149306. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  149307. **
  149308. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  149309. ** are converted to lower case. Upper-case UTF characters are
  149310. ** unchanged.
  149311. **
  149312. ** Words that are longer than about 20 bytes are stemmed by retaining
  149313. ** a few bytes from the beginning and the end of the word. If the
  149314. ** word contains digits, 3 bytes are taken from the beginning and
  149315. ** 3 bytes from the end. For long words without digits, 10 bytes
  149316. ** are taken from each end. US-ASCII case folding still applies.
  149317. **
  149318. ** If the input word contains not digits but does characters not
  149319. ** in [a-zA-Z] then no stemming is attempted and this routine just
  149320. ** copies the input into the input into the output with US-ASCII
  149321. ** case folding.
  149322. **
  149323. ** Stemming never increases the length of the word. So there is
  149324. ** no chance of overflowing the zOut buffer.
  149325. */
  149326. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  149327. int i, j;
  149328. char zReverse[28];
  149329. char *z, *z2;
  149330. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  149331. /* The word is too big or too small for the porter stemmer.
  149332. ** Fallback to the copy stemmer */
  149333. copy_stemmer(zIn, nIn, zOut, pnOut);
  149334. return;
  149335. }
  149336. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  149337. char c = zIn[i];
  149338. if( c>='A' && c<='Z' ){
  149339. zReverse[j] = c + 'a' - 'A';
  149340. }else if( c>='a' && c<='z' ){
  149341. zReverse[j] = c;
  149342. }else{
  149343. /* The use of a character not in [a-zA-Z] means that we fallback
  149344. ** to the copy stemmer */
  149345. copy_stemmer(zIn, nIn, zOut, pnOut);
  149346. return;
  149347. }
  149348. }
  149349. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  149350. z = &zReverse[j+1];
  149351. /* Step 1a */
  149352. if( z[0]=='s' ){
  149353. if(
  149354. !stem(&z, "sess", "ss", 0) &&
  149355. !stem(&z, "sei", "i", 0) &&
  149356. !stem(&z, "ss", "ss", 0)
  149357. ){
  149358. z++;
  149359. }
  149360. }
  149361. /* Step 1b */
  149362. z2 = z;
  149363. if( stem(&z, "dee", "ee", m_gt_0) ){
  149364. /* Do nothing. The work was all in the test */
  149365. }else if(
  149366. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  149367. && z!=z2
  149368. ){
  149369. if( stem(&z, "ta", "ate", 0) ||
  149370. stem(&z, "lb", "ble", 0) ||
  149371. stem(&z, "zi", "ize", 0) ){
  149372. /* Do nothing. The work was all in the test */
  149373. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  149374. z++;
  149375. }else if( m_eq_1(z) && star_oh(z) ){
  149376. *(--z) = 'e';
  149377. }
  149378. }
  149379. /* Step 1c */
  149380. if( z[0]=='y' && hasVowel(z+1) ){
  149381. z[0] = 'i';
  149382. }
  149383. /* Step 2 */
  149384. switch( z[1] ){
  149385. case 'a':
  149386. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  149387. stem(&z, "lanoit", "tion", m_gt_0);
  149388. }
  149389. break;
  149390. case 'c':
  149391. if( !stem(&z, "icne", "ence", m_gt_0) ){
  149392. stem(&z, "icna", "ance", m_gt_0);
  149393. }
  149394. break;
  149395. case 'e':
  149396. stem(&z, "rezi", "ize", m_gt_0);
  149397. break;
  149398. case 'g':
  149399. stem(&z, "igol", "log", m_gt_0);
  149400. break;
  149401. case 'l':
  149402. if( !stem(&z, "ilb", "ble", m_gt_0)
  149403. && !stem(&z, "illa", "al", m_gt_0)
  149404. && !stem(&z, "iltne", "ent", m_gt_0)
  149405. && !stem(&z, "ile", "e", m_gt_0)
  149406. ){
  149407. stem(&z, "ilsuo", "ous", m_gt_0);
  149408. }
  149409. break;
  149410. case 'o':
  149411. if( !stem(&z, "noitazi", "ize", m_gt_0)
  149412. && !stem(&z, "noita", "ate", m_gt_0)
  149413. ){
  149414. stem(&z, "rota", "ate", m_gt_0);
  149415. }
  149416. break;
  149417. case 's':
  149418. if( !stem(&z, "msila", "al", m_gt_0)
  149419. && !stem(&z, "ssenevi", "ive", m_gt_0)
  149420. && !stem(&z, "ssenluf", "ful", m_gt_0)
  149421. ){
  149422. stem(&z, "ssensuo", "ous", m_gt_0);
  149423. }
  149424. break;
  149425. case 't':
  149426. if( !stem(&z, "itila", "al", m_gt_0)
  149427. && !stem(&z, "itivi", "ive", m_gt_0)
  149428. ){
  149429. stem(&z, "itilib", "ble", m_gt_0);
  149430. }
  149431. break;
  149432. }
  149433. /* Step 3 */
  149434. switch( z[0] ){
  149435. case 'e':
  149436. if( !stem(&z, "etaci", "ic", m_gt_0)
  149437. && !stem(&z, "evita", "", m_gt_0)
  149438. ){
  149439. stem(&z, "ezila", "al", m_gt_0);
  149440. }
  149441. break;
  149442. case 'i':
  149443. stem(&z, "itici", "ic", m_gt_0);
  149444. break;
  149445. case 'l':
  149446. if( !stem(&z, "laci", "ic", m_gt_0) ){
  149447. stem(&z, "luf", "", m_gt_0);
  149448. }
  149449. break;
  149450. case 's':
  149451. stem(&z, "ssen", "", m_gt_0);
  149452. break;
  149453. }
  149454. /* Step 4 */
  149455. switch( z[1] ){
  149456. case 'a':
  149457. if( z[0]=='l' && m_gt_1(z+2) ){
  149458. z += 2;
  149459. }
  149460. break;
  149461. case 'c':
  149462. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  149463. z += 4;
  149464. }
  149465. break;
  149466. case 'e':
  149467. if( z[0]=='r' && m_gt_1(z+2) ){
  149468. z += 2;
  149469. }
  149470. break;
  149471. case 'i':
  149472. if( z[0]=='c' && m_gt_1(z+2) ){
  149473. z += 2;
  149474. }
  149475. break;
  149476. case 'l':
  149477. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  149478. z += 4;
  149479. }
  149480. break;
  149481. case 'n':
  149482. if( z[0]=='t' ){
  149483. if( z[2]=='a' ){
  149484. if( m_gt_1(z+3) ){
  149485. z += 3;
  149486. }
  149487. }else if( z[2]=='e' ){
  149488. if( !stem(&z, "tneme", "", m_gt_1)
  149489. && !stem(&z, "tnem", "", m_gt_1)
  149490. ){
  149491. stem(&z, "tne", "", m_gt_1);
  149492. }
  149493. }
  149494. }
  149495. break;
  149496. case 'o':
  149497. if( z[0]=='u' ){
  149498. if( m_gt_1(z+2) ){
  149499. z += 2;
  149500. }
  149501. }else if( z[3]=='s' || z[3]=='t' ){
  149502. stem(&z, "noi", "", m_gt_1);
  149503. }
  149504. break;
  149505. case 's':
  149506. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  149507. z += 3;
  149508. }
  149509. break;
  149510. case 't':
  149511. if( !stem(&z, "eta", "", m_gt_1) ){
  149512. stem(&z, "iti", "", m_gt_1);
  149513. }
  149514. break;
  149515. case 'u':
  149516. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  149517. z += 3;
  149518. }
  149519. break;
  149520. case 'v':
  149521. case 'z':
  149522. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  149523. z += 3;
  149524. }
  149525. break;
  149526. }
  149527. /* Step 5a */
  149528. if( z[0]=='e' ){
  149529. if( m_gt_1(z+1) ){
  149530. z++;
  149531. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  149532. z++;
  149533. }
  149534. }
  149535. /* Step 5b */
  149536. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  149537. z++;
  149538. }
  149539. /* z[] is now the stemmed word in reverse order. Flip it back
  149540. ** around into forward order and return.
  149541. */
  149542. *pnOut = i = (int)strlen(z);
  149543. zOut[i] = 0;
  149544. while( *z ){
  149545. zOut[--i] = *(z++);
  149546. }
  149547. }
  149548. /*
  149549. ** Characters that can be part of a token. We assume any character
  149550. ** whose value is greater than 0x80 (any UTF character) can be
  149551. ** part of a token. In other words, delimiters all must have
  149552. ** values of 0x7f or lower.
  149553. */
  149554. static const char porterIdChar[] = {
  149555. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  149556. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  149557. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  149558. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  149559. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  149560. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  149561. };
  149562. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  149563. /*
  149564. ** Extract the next token from a tokenization cursor. The cursor must
  149565. ** have been opened by a prior call to porterOpen().
  149566. */
  149567. static int porterNext(
  149568. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  149569. const char **pzToken, /* OUT: *pzToken is the token text */
  149570. int *pnBytes, /* OUT: Number of bytes in token */
  149571. int *piStartOffset, /* OUT: Starting offset of token */
  149572. int *piEndOffset, /* OUT: Ending offset of token */
  149573. int *piPosition /* OUT: Position integer of token */
  149574. ){
  149575. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  149576. const char *z = c->zInput;
  149577. while( c->iOffset<c->nInput ){
  149578. int iStartOffset, ch;
  149579. /* Scan past delimiter characters */
  149580. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  149581. c->iOffset++;
  149582. }
  149583. /* Count non-delimiter characters. */
  149584. iStartOffset = c->iOffset;
  149585. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  149586. c->iOffset++;
  149587. }
  149588. if( c->iOffset>iStartOffset ){
  149589. int n = c->iOffset-iStartOffset;
  149590. if( n>c->nAllocated ){
  149591. char *pNew;
  149592. c->nAllocated = n+20;
  149593. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  149594. if( !pNew ) return SQLITE_NOMEM;
  149595. c->zToken = pNew;
  149596. }
  149597. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  149598. *pzToken = c->zToken;
  149599. *piStartOffset = iStartOffset;
  149600. *piEndOffset = c->iOffset;
  149601. *piPosition = c->iToken++;
  149602. return SQLITE_OK;
  149603. }
  149604. }
  149605. return SQLITE_DONE;
  149606. }
  149607. /*
  149608. ** The set of routines that implement the porter-stemmer tokenizer
  149609. */
  149610. static const sqlite3_tokenizer_module porterTokenizerModule = {
  149611. 0,
  149612. porterCreate,
  149613. porterDestroy,
  149614. porterOpen,
  149615. porterClose,
  149616. porterNext,
  149617. 0
  149618. };
  149619. /*
  149620. ** Allocate a new porter tokenizer. Return a pointer to the new
  149621. ** tokenizer in *ppModule
  149622. */
  149623. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  149624. sqlite3_tokenizer_module const**ppModule
  149625. ){
  149626. *ppModule = &porterTokenizerModule;
  149627. }
  149628. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  149629. /************** End of fts3_porter.c *****************************************/
  149630. /************** Begin file fts3_tokenizer.c **********************************/
  149631. /*
  149632. ** 2007 June 22
  149633. **
  149634. ** The author disclaims copyright to this source code. In place of
  149635. ** a legal notice, here is a blessing:
  149636. **
  149637. ** May you do good and not evil.
  149638. ** May you find forgiveness for yourself and forgive others.
  149639. ** May you share freely, never taking more than you give.
  149640. **
  149641. ******************************************************************************
  149642. **
  149643. ** This is part of an SQLite module implementing full-text search.
  149644. ** This particular file implements the generic tokenizer interface.
  149645. */
  149646. /*
  149647. ** The code in this file is only compiled if:
  149648. **
  149649. ** * The FTS3 module is being built as an extension
  149650. ** (in which case SQLITE_CORE is not defined), or
  149651. **
  149652. ** * The FTS3 module is being built into the core of
  149653. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  149654. */
  149655. /* #include "fts3Int.h" */
  149656. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  149657. /* #include <assert.h> */
  149658. /* #include <string.h> */
  149659. /*
  149660. ** Return true if the two-argument version of fts3_tokenizer()
  149661. ** has been activated via a prior call to sqlite3_db_config(db,
  149662. ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
  149663. */
  149664. static int fts3TokenizerEnabled(sqlite3_context *context){
  149665. sqlite3 *db = sqlite3_context_db_handle(context);
  149666. int isEnabled = 0;
  149667. sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
  149668. return isEnabled;
  149669. }
  149670. /*
  149671. ** Implementation of the SQL scalar function for accessing the underlying
  149672. ** hash table. This function may be called as follows:
  149673. **
  149674. ** SELECT <function-name>(<key-name>);
  149675. ** SELECT <function-name>(<key-name>, <pointer>);
  149676. **
  149677. ** where <function-name> is the name passed as the second argument
  149678. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  149679. **
  149680. ** If the <pointer> argument is specified, it must be a blob value
  149681. ** containing a pointer to be stored as the hash data corresponding
  149682. ** to the string <key-name>. If <pointer> is not specified, then
  149683. ** the string <key-name> must already exist in the has table. Otherwise,
  149684. ** an error is returned.
  149685. **
  149686. ** Whether or not the <pointer> argument is specified, the value returned
  149687. ** is a blob containing the pointer stored as the hash data corresponding
  149688. ** to string <key-name> (after the hash-table is updated, if applicable).
  149689. */
  149690. static void fts3TokenizerFunc(
  149691. sqlite3_context *context,
  149692. int argc,
  149693. sqlite3_value **argv
  149694. ){
  149695. Fts3Hash *pHash;
  149696. void *pPtr = 0;
  149697. const unsigned char *zName;
  149698. int nName;
  149699. assert( argc==1 || argc==2 );
  149700. pHash = (Fts3Hash *)sqlite3_user_data(context);
  149701. zName = sqlite3_value_text(argv[0]);
  149702. nName = sqlite3_value_bytes(argv[0])+1;
  149703. if( argc==2 ){
  149704. if( fts3TokenizerEnabled(context) ){
  149705. void *pOld;
  149706. int n = sqlite3_value_bytes(argv[1]);
  149707. if( zName==0 || n!=sizeof(pPtr) ){
  149708. sqlite3_result_error(context, "argument type mismatch", -1);
  149709. return;
  149710. }
  149711. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  149712. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  149713. if( pOld==pPtr ){
  149714. sqlite3_result_error(context, "out of memory", -1);
  149715. }
  149716. }else{
  149717. sqlite3_result_error(context, "fts3tokenize disabled", -1);
  149718. return;
  149719. }
  149720. }else{
  149721. if( zName ){
  149722. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  149723. }
  149724. if( !pPtr ){
  149725. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  149726. sqlite3_result_error(context, zErr, -1);
  149727. sqlite3_free(zErr);
  149728. return;
  149729. }
  149730. }
  149731. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  149732. }
  149733. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  149734. static const char isFtsIdChar[] = {
  149735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  149736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  149737. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  149738. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  149739. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  149740. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  149741. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  149742. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  149743. };
  149744. return (c&0x80 || isFtsIdChar[(int)(c)]);
  149745. }
  149746. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  149747. const char *z1;
  149748. const char *z2 = 0;
  149749. /* Find the start of the next token. */
  149750. z1 = zStr;
  149751. while( z2==0 ){
  149752. char c = *z1;
  149753. switch( c ){
  149754. case '\0': return 0; /* No more tokens here */
  149755. case '\'':
  149756. case '"':
  149757. case '`': {
  149758. z2 = z1;
  149759. while( *++z2 && (*z2!=c || *++z2==c) );
  149760. break;
  149761. }
  149762. case '[':
  149763. z2 = &z1[1];
  149764. while( *z2 && z2[0]!=']' ) z2++;
  149765. if( *z2 ) z2++;
  149766. break;
  149767. default:
  149768. if( sqlite3Fts3IsIdChar(*z1) ){
  149769. z2 = &z1[1];
  149770. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  149771. }else{
  149772. z1++;
  149773. }
  149774. }
  149775. }
  149776. *pn = (int)(z2-z1);
  149777. return z1;
  149778. }
  149779. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  149780. Fts3Hash *pHash, /* Tokenizer hash table */
  149781. const char *zArg, /* Tokenizer name */
  149782. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  149783. char **pzErr /* OUT: Set to malloced error message */
  149784. ){
  149785. int rc;
  149786. char *z = (char *)zArg;
  149787. int n = 0;
  149788. char *zCopy;
  149789. char *zEnd; /* Pointer to nul-term of zCopy */
  149790. sqlite3_tokenizer_module *m;
  149791. zCopy = sqlite3_mprintf("%s", zArg);
  149792. if( !zCopy ) return SQLITE_NOMEM;
  149793. zEnd = &zCopy[strlen(zCopy)];
  149794. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  149795. if( z==0 ){
  149796. assert( n==0 );
  149797. z = zCopy;
  149798. }
  149799. z[n] = '\0';
  149800. sqlite3Fts3Dequote(z);
  149801. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  149802. if( !m ){
  149803. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  149804. rc = SQLITE_ERROR;
  149805. }else{
  149806. char const **aArg = 0;
  149807. int iArg = 0;
  149808. z = &z[n+1];
  149809. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  149810. int nNew = sizeof(char *)*(iArg+1);
  149811. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  149812. if( !aNew ){
  149813. sqlite3_free(zCopy);
  149814. sqlite3_free((void *)aArg);
  149815. return SQLITE_NOMEM;
  149816. }
  149817. aArg = aNew;
  149818. aArg[iArg++] = z;
  149819. z[n] = '\0';
  149820. sqlite3Fts3Dequote(z);
  149821. z = &z[n+1];
  149822. }
  149823. rc = m->xCreate(iArg, aArg, ppTok);
  149824. assert( rc!=SQLITE_OK || *ppTok );
  149825. if( rc!=SQLITE_OK ){
  149826. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  149827. }else{
  149828. (*ppTok)->pModule = m;
  149829. }
  149830. sqlite3_free((void *)aArg);
  149831. }
  149832. sqlite3_free(zCopy);
  149833. return rc;
  149834. }
  149835. #ifdef SQLITE_TEST
  149836. #if defined(INCLUDE_SQLITE_TCL_H)
  149837. # include "sqlite_tcl.h"
  149838. #else
  149839. # include "tcl.h"
  149840. #endif
  149841. /* #include <string.h> */
  149842. /*
  149843. ** Implementation of a special SQL scalar function for testing tokenizers
  149844. ** designed to be used in concert with the Tcl testing framework. This
  149845. ** function must be called with two or more arguments:
  149846. **
  149847. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  149848. **
  149849. ** where <function-name> is the name passed as the second argument
  149850. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  149851. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  149852. **
  149853. ** The return value is a string that may be interpreted as a Tcl
  149854. ** list. For each token in the <input-string>, three elements are
  149855. ** added to the returned list. The first is the token position, the
  149856. ** second is the token text (folded, stemmed, etc.) and the third is the
  149857. ** substring of <input-string> associated with the token. For example,
  149858. ** using the built-in "simple" tokenizer:
  149859. **
  149860. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  149861. **
  149862. ** will return the string:
  149863. **
  149864. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  149865. **
  149866. */
  149867. static void testFunc(
  149868. sqlite3_context *context,
  149869. int argc,
  149870. sqlite3_value **argv
  149871. ){
  149872. Fts3Hash *pHash;
  149873. sqlite3_tokenizer_module *p;
  149874. sqlite3_tokenizer *pTokenizer = 0;
  149875. sqlite3_tokenizer_cursor *pCsr = 0;
  149876. const char *zErr = 0;
  149877. const char *zName;
  149878. int nName;
  149879. const char *zInput;
  149880. int nInput;
  149881. const char *azArg[64];
  149882. const char *zToken;
  149883. int nToken = 0;
  149884. int iStart = 0;
  149885. int iEnd = 0;
  149886. int iPos = 0;
  149887. int i;
  149888. Tcl_Obj *pRet;
  149889. if( argc<2 ){
  149890. sqlite3_result_error(context, "insufficient arguments", -1);
  149891. return;
  149892. }
  149893. nName = sqlite3_value_bytes(argv[0]);
  149894. zName = (const char *)sqlite3_value_text(argv[0]);
  149895. nInput = sqlite3_value_bytes(argv[argc-1]);
  149896. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  149897. pHash = (Fts3Hash *)sqlite3_user_data(context);
  149898. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  149899. if( !p ){
  149900. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  149901. sqlite3_result_error(context, zErr2, -1);
  149902. sqlite3_free(zErr2);
  149903. return;
  149904. }
  149905. pRet = Tcl_NewObj();
  149906. Tcl_IncrRefCount(pRet);
  149907. for(i=1; i<argc-1; i++){
  149908. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  149909. }
  149910. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  149911. zErr = "error in xCreate()";
  149912. goto finish;
  149913. }
  149914. pTokenizer->pModule = p;
  149915. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  149916. zErr = "error in xOpen()";
  149917. goto finish;
  149918. }
  149919. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  149920. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  149921. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  149922. zToken = &zInput[iStart];
  149923. nToken = iEnd-iStart;
  149924. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  149925. }
  149926. if( SQLITE_OK!=p->xClose(pCsr) ){
  149927. zErr = "error in xClose()";
  149928. goto finish;
  149929. }
  149930. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  149931. zErr = "error in xDestroy()";
  149932. goto finish;
  149933. }
  149934. finish:
  149935. if( zErr ){
  149936. sqlite3_result_error(context, zErr, -1);
  149937. }else{
  149938. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  149939. }
  149940. Tcl_DecrRefCount(pRet);
  149941. }
  149942. static
  149943. int registerTokenizer(
  149944. sqlite3 *db,
  149945. char *zName,
  149946. const sqlite3_tokenizer_module *p
  149947. ){
  149948. int rc;
  149949. sqlite3_stmt *pStmt;
  149950. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  149951. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  149952. if( rc!=SQLITE_OK ){
  149953. return rc;
  149954. }
  149955. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  149956. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  149957. sqlite3_step(pStmt);
  149958. return sqlite3_finalize(pStmt);
  149959. }
  149960. static
  149961. int queryTokenizer(
  149962. sqlite3 *db,
  149963. char *zName,
  149964. const sqlite3_tokenizer_module **pp
  149965. ){
  149966. int rc;
  149967. sqlite3_stmt *pStmt;
  149968. const char zSql[] = "SELECT fts3_tokenizer(?)";
  149969. *pp = 0;
  149970. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  149971. if( rc!=SQLITE_OK ){
  149972. return rc;
  149973. }
  149974. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  149975. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  149976. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  149977. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  149978. }
  149979. }
  149980. return sqlite3_finalize(pStmt);
  149981. }
  149982. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  149983. /*
  149984. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  149985. ** This function is used for testing only, it is not included in the
  149986. ** build unless SQLITE_TEST is defined.
  149987. **
  149988. ** The purpose of this is to test that the fts3_tokenizer() function
  149989. ** can be used as designed by the C-code in the queryTokenizer and
  149990. ** registerTokenizer() functions above. These two functions are repeated
  149991. ** in the README.tokenizer file as an example, so it is important to
  149992. ** test them.
  149993. **
  149994. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  149995. ** function with no arguments. An assert() will fail if a problem is
  149996. ** detected. i.e.:
  149997. **
  149998. ** SELECT fts3_tokenizer_internal_test();
  149999. **
  150000. */
  150001. static void intTestFunc(
  150002. sqlite3_context *context,
  150003. int argc,
  150004. sqlite3_value **argv
  150005. ){
  150006. int rc;
  150007. const sqlite3_tokenizer_module *p1;
  150008. const sqlite3_tokenizer_module *p2;
  150009. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  150010. UNUSED_PARAMETER(argc);
  150011. UNUSED_PARAMETER(argv);
  150012. /* Test the query function */
  150013. sqlite3Fts3SimpleTokenizerModule(&p1);
  150014. rc = queryTokenizer(db, "simple", &p2);
  150015. assert( rc==SQLITE_OK );
  150016. assert( p1==p2 );
  150017. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  150018. assert( rc==SQLITE_ERROR );
  150019. assert( p2==0 );
  150020. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  150021. /* Test the storage function */
  150022. if( fts3TokenizerEnabled(context) ){
  150023. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  150024. assert( rc==SQLITE_OK );
  150025. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  150026. assert( rc==SQLITE_OK );
  150027. assert( p2==p1 );
  150028. }
  150029. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  150030. }
  150031. #endif
  150032. /*
  150033. ** Set up SQL objects in database db used to access the contents of
  150034. ** the hash table pointed to by argument pHash. The hash table must
  150035. ** been initialized to use string keys, and to take a private copy
  150036. ** of the key when a value is inserted. i.e. by a call similar to:
  150037. **
  150038. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  150039. **
  150040. ** This function adds a scalar function (see header comment above
  150041. ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
  150042. ** defined at compilation time, a temporary virtual table (see header
  150043. ** comment above struct HashTableVtab) to the database schema. Both
  150044. ** provide read/write access to the contents of *pHash.
  150045. **
  150046. ** The third argument to this function, zName, is used as the name
  150047. ** of both the scalar and, if created, the virtual table.
  150048. */
  150049. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  150050. sqlite3 *db,
  150051. Fts3Hash *pHash,
  150052. const char *zName
  150053. ){
  150054. int rc = SQLITE_OK;
  150055. void *p = (void *)pHash;
  150056. const int any = SQLITE_ANY;
  150057. #ifdef SQLITE_TEST
  150058. char *zTest = 0;
  150059. char *zTest2 = 0;
  150060. void *pdb = (void *)db;
  150061. zTest = sqlite3_mprintf("%s_test", zName);
  150062. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  150063. if( !zTest || !zTest2 ){
  150064. rc = SQLITE_NOMEM;
  150065. }
  150066. #endif
  150067. if( SQLITE_OK==rc ){
  150068. rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
  150069. }
  150070. if( SQLITE_OK==rc ){
  150071. rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
  150072. }
  150073. #ifdef SQLITE_TEST
  150074. if( SQLITE_OK==rc ){
  150075. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  150076. }
  150077. if( SQLITE_OK==rc ){
  150078. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  150079. }
  150080. #endif
  150081. #ifdef SQLITE_TEST
  150082. sqlite3_free(zTest);
  150083. sqlite3_free(zTest2);
  150084. #endif
  150085. return rc;
  150086. }
  150087. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  150088. /************** End of fts3_tokenizer.c **************************************/
  150089. /************** Begin file fts3_tokenizer1.c *********************************/
  150090. /*
  150091. ** 2006 Oct 10
  150092. **
  150093. ** The author disclaims copyright to this source code. In place of
  150094. ** a legal notice, here is a blessing:
  150095. **
  150096. ** May you do good and not evil.
  150097. ** May you find forgiveness for yourself and forgive others.
  150098. ** May you share freely, never taking more than you give.
  150099. **
  150100. ******************************************************************************
  150101. **
  150102. ** Implementation of the "simple" full-text-search tokenizer.
  150103. */
  150104. /*
  150105. ** The code in this file is only compiled if:
  150106. **
  150107. ** * The FTS3 module is being built as an extension
  150108. ** (in which case SQLITE_CORE is not defined), or
  150109. **
  150110. ** * The FTS3 module is being built into the core of
  150111. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  150112. */
  150113. /* #include "fts3Int.h" */
  150114. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  150115. /* #include <assert.h> */
  150116. /* #include <stdlib.h> */
  150117. /* #include <stdio.h> */
  150118. /* #include <string.h> */
  150119. /* #include "fts3_tokenizer.h" */
  150120. typedef struct simple_tokenizer {
  150121. sqlite3_tokenizer base;
  150122. char delim[128]; /* flag ASCII delimiters */
  150123. } simple_tokenizer;
  150124. typedef struct simple_tokenizer_cursor {
  150125. sqlite3_tokenizer_cursor base;
  150126. const char *pInput; /* input we are tokenizing */
  150127. int nBytes; /* size of the input */
  150128. int iOffset; /* current position in pInput */
  150129. int iToken; /* index of next token to be returned */
  150130. char *pToken; /* storage for current token */
  150131. int nTokenAllocated; /* space allocated to zToken buffer */
  150132. } simple_tokenizer_cursor;
  150133. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  150134. return c<0x80 && t->delim[c];
  150135. }
  150136. static int fts3_isalnum(int x){
  150137. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  150138. }
  150139. /*
  150140. ** Create a new tokenizer instance.
  150141. */
  150142. static int simpleCreate(
  150143. int argc, const char * const *argv,
  150144. sqlite3_tokenizer **ppTokenizer
  150145. ){
  150146. simple_tokenizer *t;
  150147. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  150148. if( t==NULL ) return SQLITE_NOMEM;
  150149. memset(t, 0, sizeof(*t));
  150150. /* TODO(shess) Delimiters need to remain the same from run to run,
  150151. ** else we need to reindex. One solution would be a meta-table to
  150152. ** track such information in the database, then we'd only want this
  150153. ** information on the initial create.
  150154. */
  150155. if( argc>1 ){
  150156. int i, n = (int)strlen(argv[1]);
  150157. for(i=0; i<n; i++){
  150158. unsigned char ch = argv[1][i];
  150159. /* We explicitly don't support UTF-8 delimiters for now. */
  150160. if( ch>=0x80 ){
  150161. sqlite3_free(t);
  150162. return SQLITE_ERROR;
  150163. }
  150164. t->delim[ch] = 1;
  150165. }
  150166. } else {
  150167. /* Mark non-alphanumeric ASCII characters as delimiters */
  150168. int i;
  150169. for(i=1; i<0x80; i++){
  150170. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  150171. }
  150172. }
  150173. *ppTokenizer = &t->base;
  150174. return SQLITE_OK;
  150175. }
  150176. /*
  150177. ** Destroy a tokenizer
  150178. */
  150179. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  150180. sqlite3_free(pTokenizer);
  150181. return SQLITE_OK;
  150182. }
  150183. /*
  150184. ** Prepare to begin tokenizing a particular string. The input
  150185. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  150186. ** used to incrementally tokenize this string is returned in
  150187. ** *ppCursor.
  150188. */
  150189. static int simpleOpen(
  150190. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  150191. const char *pInput, int nBytes, /* String to be tokenized */
  150192. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  150193. ){
  150194. simple_tokenizer_cursor *c;
  150195. UNUSED_PARAMETER(pTokenizer);
  150196. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  150197. if( c==NULL ) return SQLITE_NOMEM;
  150198. c->pInput = pInput;
  150199. if( pInput==0 ){
  150200. c->nBytes = 0;
  150201. }else if( nBytes<0 ){
  150202. c->nBytes = (int)strlen(pInput);
  150203. }else{
  150204. c->nBytes = nBytes;
  150205. }
  150206. c->iOffset = 0; /* start tokenizing at the beginning */
  150207. c->iToken = 0;
  150208. c->pToken = NULL; /* no space allocated, yet. */
  150209. c->nTokenAllocated = 0;
  150210. *ppCursor = &c->base;
  150211. return SQLITE_OK;
  150212. }
  150213. /*
  150214. ** Close a tokenization cursor previously opened by a call to
  150215. ** simpleOpen() above.
  150216. */
  150217. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  150218. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  150219. sqlite3_free(c->pToken);
  150220. sqlite3_free(c);
  150221. return SQLITE_OK;
  150222. }
  150223. /*
  150224. ** Extract the next token from a tokenization cursor. The cursor must
  150225. ** have been opened by a prior call to simpleOpen().
  150226. */
  150227. static int simpleNext(
  150228. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  150229. const char **ppToken, /* OUT: *ppToken is the token text */
  150230. int *pnBytes, /* OUT: Number of bytes in token */
  150231. int *piStartOffset, /* OUT: Starting offset of token */
  150232. int *piEndOffset, /* OUT: Ending offset of token */
  150233. int *piPosition /* OUT: Position integer of token */
  150234. ){
  150235. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  150236. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  150237. unsigned char *p = (unsigned char *)c->pInput;
  150238. while( c->iOffset<c->nBytes ){
  150239. int iStartOffset;
  150240. /* Scan past delimiter characters */
  150241. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  150242. c->iOffset++;
  150243. }
  150244. /* Count non-delimiter characters. */
  150245. iStartOffset = c->iOffset;
  150246. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  150247. c->iOffset++;
  150248. }
  150249. if( c->iOffset>iStartOffset ){
  150250. int i, n = c->iOffset-iStartOffset;
  150251. if( n>c->nTokenAllocated ){
  150252. char *pNew;
  150253. c->nTokenAllocated = n+20;
  150254. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  150255. if( !pNew ) return SQLITE_NOMEM;
  150256. c->pToken = pNew;
  150257. }
  150258. for(i=0; i<n; i++){
  150259. /* TODO(shess) This needs expansion to handle UTF-8
  150260. ** case-insensitivity.
  150261. */
  150262. unsigned char ch = p[iStartOffset+i];
  150263. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  150264. }
  150265. *ppToken = c->pToken;
  150266. *pnBytes = n;
  150267. *piStartOffset = iStartOffset;
  150268. *piEndOffset = c->iOffset;
  150269. *piPosition = c->iToken++;
  150270. return SQLITE_OK;
  150271. }
  150272. }
  150273. return SQLITE_DONE;
  150274. }
  150275. /*
  150276. ** The set of routines that implement the simple tokenizer
  150277. */
  150278. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  150279. 0,
  150280. simpleCreate,
  150281. simpleDestroy,
  150282. simpleOpen,
  150283. simpleClose,
  150284. simpleNext,
  150285. 0,
  150286. };
  150287. /*
  150288. ** Allocate a new simple tokenizer. Return a pointer to the new
  150289. ** tokenizer in *ppModule
  150290. */
  150291. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  150292. sqlite3_tokenizer_module const**ppModule
  150293. ){
  150294. *ppModule = &simpleTokenizerModule;
  150295. }
  150296. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  150297. /************** End of fts3_tokenizer1.c *************************************/
  150298. /************** Begin file fts3_tokenize_vtab.c ******************************/
  150299. /*
  150300. ** 2013 Apr 22
  150301. **
  150302. ** The author disclaims copyright to this source code. In place of
  150303. ** a legal notice, here is a blessing:
  150304. **
  150305. ** May you do good and not evil.
  150306. ** May you find forgiveness for yourself and forgive others.
  150307. ** May you share freely, never taking more than you give.
  150308. **
  150309. ******************************************************************************
  150310. **
  150311. ** This file contains code for the "fts3tokenize" virtual table module.
  150312. ** An fts3tokenize virtual table is created as follows:
  150313. **
  150314. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  150315. ** <tokenizer-name>, <arg-1>, ...
  150316. ** );
  150317. **
  150318. ** The table created has the following schema:
  150319. **
  150320. ** CREATE TABLE <tbl>(input, token, start, end, position)
  150321. **
  150322. ** When queried, the query must include a WHERE clause of type:
  150323. **
  150324. ** input = <string>
  150325. **
  150326. ** The virtual table module tokenizes this <string>, using the FTS3
  150327. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  150328. ** statement and returns one row for each token in the result. With
  150329. ** fields set as follows:
  150330. **
  150331. ** input: Always set to a copy of <string>
  150332. ** token: A token from the input.
  150333. ** start: Byte offset of the token within the input <string>.
  150334. ** end: Byte offset of the byte immediately following the end of the
  150335. ** token within the input string.
  150336. ** pos: Token offset of token within input.
  150337. **
  150338. */
  150339. /* #include "fts3Int.h" */
  150340. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  150341. /* #include <string.h> */
  150342. /* #include <assert.h> */
  150343. typedef struct Fts3tokTable Fts3tokTable;
  150344. typedef struct Fts3tokCursor Fts3tokCursor;
  150345. /*
  150346. ** Virtual table structure.
  150347. */
  150348. struct Fts3tokTable {
  150349. sqlite3_vtab base; /* Base class used by SQLite core */
  150350. const sqlite3_tokenizer_module *pMod;
  150351. sqlite3_tokenizer *pTok;
  150352. };
  150353. /*
  150354. ** Virtual table cursor structure.
  150355. */
  150356. struct Fts3tokCursor {
  150357. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  150358. char *zInput; /* Input string */
  150359. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  150360. int iRowid; /* Current 'rowid' value */
  150361. const char *zToken; /* Current 'token' value */
  150362. int nToken; /* Size of zToken in bytes */
  150363. int iStart; /* Current 'start' value */
  150364. int iEnd; /* Current 'end' value */
  150365. int iPos; /* Current 'pos' value */
  150366. };
  150367. /*
  150368. ** Query FTS for the tokenizer implementation named zName.
  150369. */
  150370. static int fts3tokQueryTokenizer(
  150371. Fts3Hash *pHash,
  150372. const char *zName,
  150373. const sqlite3_tokenizer_module **pp,
  150374. char **pzErr
  150375. ){
  150376. sqlite3_tokenizer_module *p;
  150377. int nName = (int)strlen(zName);
  150378. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  150379. if( !p ){
  150380. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  150381. return SQLITE_ERROR;
  150382. }
  150383. *pp = p;
  150384. return SQLITE_OK;
  150385. }
  150386. /*
  150387. ** The second argument, argv[], is an array of pointers to nul-terminated
  150388. ** strings. This function makes a copy of the array and strings into a
  150389. ** single block of memory. It then dequotes any of the strings that appear
  150390. ** to be quoted.
  150391. **
  150392. ** If successful, output parameter *pazDequote is set to point at the
  150393. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  150394. ** responsible for eventually calling sqlite3_free() to free the array
  150395. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  150396. ** The final value of *pazDequote is undefined in this case.
  150397. */
  150398. static int fts3tokDequoteArray(
  150399. int argc, /* Number of elements in argv[] */
  150400. const char * const *argv, /* Input array */
  150401. char ***pazDequote /* Output array */
  150402. ){
  150403. int rc = SQLITE_OK; /* Return code */
  150404. if( argc==0 ){
  150405. *pazDequote = 0;
  150406. }else{
  150407. int i;
  150408. int nByte = 0;
  150409. char **azDequote;
  150410. for(i=0; i<argc; i++){
  150411. nByte += (int)(strlen(argv[i]) + 1);
  150412. }
  150413. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  150414. if( azDequote==0 ){
  150415. rc = SQLITE_NOMEM;
  150416. }else{
  150417. char *pSpace = (char *)&azDequote[argc];
  150418. for(i=0; i<argc; i++){
  150419. int n = (int)strlen(argv[i]);
  150420. azDequote[i] = pSpace;
  150421. memcpy(pSpace, argv[i], n+1);
  150422. sqlite3Fts3Dequote(pSpace);
  150423. pSpace += (n+1);
  150424. }
  150425. }
  150426. }
  150427. return rc;
  150428. }
  150429. /*
  150430. ** Schema of the tokenizer table.
  150431. */
  150432. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  150433. /*
  150434. ** This function does all the work for both the xConnect and xCreate methods.
  150435. ** These tables have no persistent representation of their own, so xConnect
  150436. ** and xCreate are identical operations.
  150437. **
  150438. ** argv[0]: module name
  150439. ** argv[1]: database name
  150440. ** argv[2]: table name
  150441. ** argv[3]: first argument (tokenizer name)
  150442. */
  150443. static int fts3tokConnectMethod(
  150444. sqlite3 *db, /* Database connection */
  150445. void *pHash, /* Hash table of tokenizers */
  150446. int argc, /* Number of elements in argv array */
  150447. const char * const *argv, /* xCreate/xConnect argument array */
  150448. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  150449. char **pzErr /* OUT: sqlite3_malloc'd error message */
  150450. ){
  150451. Fts3tokTable *pTab = 0;
  150452. const sqlite3_tokenizer_module *pMod = 0;
  150453. sqlite3_tokenizer *pTok = 0;
  150454. int rc;
  150455. char **azDequote = 0;
  150456. int nDequote;
  150457. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  150458. if( rc!=SQLITE_OK ) return rc;
  150459. nDequote = argc-3;
  150460. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  150461. if( rc==SQLITE_OK ){
  150462. const char *zModule;
  150463. if( nDequote<1 ){
  150464. zModule = "simple";
  150465. }else{
  150466. zModule = azDequote[0];
  150467. }
  150468. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  150469. }
  150470. assert( (rc==SQLITE_OK)==(pMod!=0) );
  150471. if( rc==SQLITE_OK ){
  150472. const char * const *azArg = (const char * const *)&azDequote[1];
  150473. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  150474. }
  150475. if( rc==SQLITE_OK ){
  150476. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  150477. if( pTab==0 ){
  150478. rc = SQLITE_NOMEM;
  150479. }
  150480. }
  150481. if( rc==SQLITE_OK ){
  150482. memset(pTab, 0, sizeof(Fts3tokTable));
  150483. pTab->pMod = pMod;
  150484. pTab->pTok = pTok;
  150485. *ppVtab = &pTab->base;
  150486. }else{
  150487. if( pTok ){
  150488. pMod->xDestroy(pTok);
  150489. }
  150490. }
  150491. sqlite3_free(azDequote);
  150492. return rc;
  150493. }
  150494. /*
  150495. ** This function does the work for both the xDisconnect and xDestroy methods.
  150496. ** These tables have no persistent representation of their own, so xDisconnect
  150497. ** and xDestroy are identical operations.
  150498. */
  150499. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  150500. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  150501. pTab->pMod->xDestroy(pTab->pTok);
  150502. sqlite3_free(pTab);
  150503. return SQLITE_OK;
  150504. }
  150505. /*
  150506. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  150507. */
  150508. static int fts3tokBestIndexMethod(
  150509. sqlite3_vtab *pVTab,
  150510. sqlite3_index_info *pInfo
  150511. ){
  150512. int i;
  150513. UNUSED_PARAMETER(pVTab);
  150514. for(i=0; i<pInfo->nConstraint; i++){
  150515. if( pInfo->aConstraint[i].usable
  150516. && pInfo->aConstraint[i].iColumn==0
  150517. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  150518. ){
  150519. pInfo->idxNum = 1;
  150520. pInfo->aConstraintUsage[i].argvIndex = 1;
  150521. pInfo->aConstraintUsage[i].omit = 1;
  150522. pInfo->estimatedCost = 1;
  150523. return SQLITE_OK;
  150524. }
  150525. }
  150526. pInfo->idxNum = 0;
  150527. assert( pInfo->estimatedCost>1000000.0 );
  150528. return SQLITE_OK;
  150529. }
  150530. /*
  150531. ** xOpen - Open a cursor.
  150532. */
  150533. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  150534. Fts3tokCursor *pCsr;
  150535. UNUSED_PARAMETER(pVTab);
  150536. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  150537. if( pCsr==0 ){
  150538. return SQLITE_NOMEM;
  150539. }
  150540. memset(pCsr, 0, sizeof(Fts3tokCursor));
  150541. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  150542. return SQLITE_OK;
  150543. }
  150544. /*
  150545. ** Reset the tokenizer cursor passed as the only argument. As if it had
  150546. ** just been returned by fts3tokOpenMethod().
  150547. */
  150548. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  150549. if( pCsr->pCsr ){
  150550. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  150551. pTab->pMod->xClose(pCsr->pCsr);
  150552. pCsr->pCsr = 0;
  150553. }
  150554. sqlite3_free(pCsr->zInput);
  150555. pCsr->zInput = 0;
  150556. pCsr->zToken = 0;
  150557. pCsr->nToken = 0;
  150558. pCsr->iStart = 0;
  150559. pCsr->iEnd = 0;
  150560. pCsr->iPos = 0;
  150561. pCsr->iRowid = 0;
  150562. }
  150563. /*
  150564. ** xClose - Close a cursor.
  150565. */
  150566. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  150567. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  150568. fts3tokResetCursor(pCsr);
  150569. sqlite3_free(pCsr);
  150570. return SQLITE_OK;
  150571. }
  150572. /*
  150573. ** xNext - Advance the cursor to the next row, if any.
  150574. */
  150575. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  150576. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  150577. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  150578. int rc; /* Return code */
  150579. pCsr->iRowid++;
  150580. rc = pTab->pMod->xNext(pCsr->pCsr,
  150581. &pCsr->zToken, &pCsr->nToken,
  150582. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  150583. );
  150584. if( rc!=SQLITE_OK ){
  150585. fts3tokResetCursor(pCsr);
  150586. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  150587. }
  150588. return rc;
  150589. }
  150590. /*
  150591. ** xFilter - Initialize a cursor to point at the start of its data.
  150592. */
  150593. static int fts3tokFilterMethod(
  150594. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  150595. int idxNum, /* Strategy index */
  150596. const char *idxStr, /* Unused */
  150597. int nVal, /* Number of elements in apVal */
  150598. sqlite3_value **apVal /* Arguments for the indexing scheme */
  150599. ){
  150600. int rc = SQLITE_ERROR;
  150601. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  150602. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  150603. UNUSED_PARAMETER(idxStr);
  150604. UNUSED_PARAMETER(nVal);
  150605. fts3tokResetCursor(pCsr);
  150606. if( idxNum==1 ){
  150607. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  150608. int nByte = sqlite3_value_bytes(apVal[0]);
  150609. pCsr->zInput = sqlite3_malloc(nByte+1);
  150610. if( pCsr->zInput==0 ){
  150611. rc = SQLITE_NOMEM;
  150612. }else{
  150613. memcpy(pCsr->zInput, zByte, nByte);
  150614. pCsr->zInput[nByte] = 0;
  150615. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  150616. if( rc==SQLITE_OK ){
  150617. pCsr->pCsr->pTokenizer = pTab->pTok;
  150618. }
  150619. }
  150620. }
  150621. if( rc!=SQLITE_OK ) return rc;
  150622. return fts3tokNextMethod(pCursor);
  150623. }
  150624. /*
  150625. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  150626. */
  150627. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  150628. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  150629. return (pCsr->zToken==0);
  150630. }
  150631. /*
  150632. ** xColumn - Return a column value.
  150633. */
  150634. static int fts3tokColumnMethod(
  150635. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  150636. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  150637. int iCol /* Index of column to read value from */
  150638. ){
  150639. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  150640. /* CREATE TABLE x(input, token, start, end, position) */
  150641. switch( iCol ){
  150642. case 0:
  150643. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  150644. break;
  150645. case 1:
  150646. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  150647. break;
  150648. case 2:
  150649. sqlite3_result_int(pCtx, pCsr->iStart);
  150650. break;
  150651. case 3:
  150652. sqlite3_result_int(pCtx, pCsr->iEnd);
  150653. break;
  150654. default:
  150655. assert( iCol==4 );
  150656. sqlite3_result_int(pCtx, pCsr->iPos);
  150657. break;
  150658. }
  150659. return SQLITE_OK;
  150660. }
  150661. /*
  150662. ** xRowid - Return the current rowid for the cursor.
  150663. */
  150664. static int fts3tokRowidMethod(
  150665. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  150666. sqlite_int64 *pRowid /* OUT: Rowid value */
  150667. ){
  150668. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  150669. *pRowid = (sqlite3_int64)pCsr->iRowid;
  150670. return SQLITE_OK;
  150671. }
  150672. /*
  150673. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  150674. ** if successful or an error code if sqlite3_create_module() fails.
  150675. */
  150676. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  150677. static const sqlite3_module fts3tok_module = {
  150678. 0, /* iVersion */
  150679. fts3tokConnectMethod, /* xCreate */
  150680. fts3tokConnectMethod, /* xConnect */
  150681. fts3tokBestIndexMethod, /* xBestIndex */
  150682. fts3tokDisconnectMethod, /* xDisconnect */
  150683. fts3tokDisconnectMethod, /* xDestroy */
  150684. fts3tokOpenMethod, /* xOpen */
  150685. fts3tokCloseMethod, /* xClose */
  150686. fts3tokFilterMethod, /* xFilter */
  150687. fts3tokNextMethod, /* xNext */
  150688. fts3tokEofMethod, /* xEof */
  150689. fts3tokColumnMethod, /* xColumn */
  150690. fts3tokRowidMethod, /* xRowid */
  150691. 0, /* xUpdate */
  150692. 0, /* xBegin */
  150693. 0, /* xSync */
  150694. 0, /* xCommit */
  150695. 0, /* xRollback */
  150696. 0, /* xFindFunction */
  150697. 0, /* xRename */
  150698. 0, /* xSavepoint */
  150699. 0, /* xRelease */
  150700. 0 /* xRollbackTo */
  150701. };
  150702. int rc; /* Return code */
  150703. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  150704. return rc;
  150705. }
  150706. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  150707. /************** End of fts3_tokenize_vtab.c **********************************/
  150708. /************** Begin file fts3_write.c **************************************/
  150709. /*
  150710. ** 2009 Oct 23
  150711. **
  150712. ** The author disclaims copyright to this source code. In place of
  150713. ** a legal notice, here is a blessing:
  150714. **
  150715. ** May you do good and not evil.
  150716. ** May you find forgiveness for yourself and forgive others.
  150717. ** May you share freely, never taking more than you give.
  150718. **
  150719. ******************************************************************************
  150720. **
  150721. ** This file is part of the SQLite FTS3 extension module. Specifically,
  150722. ** this file contains code to insert, update and delete rows from FTS3
  150723. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  150724. ** of the sub-routines used to merge segments are also used by the query
  150725. ** code in fts3.c.
  150726. */
  150727. /* #include "fts3Int.h" */
  150728. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  150729. /* #include <string.h> */
  150730. /* #include <assert.h> */
  150731. /* #include <stdlib.h> */
  150732. #define FTS_MAX_APPENDABLE_HEIGHT 16
  150733. /*
  150734. ** When full-text index nodes are loaded from disk, the buffer that they
  150735. ** are loaded into has the following number of bytes of padding at the end
  150736. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  150737. ** of 920 bytes is allocated for it.
  150738. **
  150739. ** This means that if we have a pointer into a buffer containing node data,
  150740. ** it is always safe to read up to two varints from it without risking an
  150741. ** overread, even if the node data is corrupted.
  150742. */
  150743. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  150744. /*
  150745. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  150746. ** memory incrementally instead of all at once. This can be a big performance
  150747. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  150748. ** method before retrieving all query results (as may happen, for example,
  150749. ** if a query has a LIMIT clause).
  150750. **
  150751. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  150752. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  150753. ** The code is written so that the hard lower-limit for each of these values
  150754. ** is 1. Clearly such small values would be inefficient, but can be useful
  150755. ** for testing purposes.
  150756. **
  150757. ** If this module is built with SQLITE_TEST defined, these constants may
  150758. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  150759. ** a Tcl interface to read and write the values.
  150760. */
  150761. #ifdef SQLITE_TEST
  150762. int test_fts3_node_chunksize = (4*1024);
  150763. int test_fts3_node_chunk_threshold = (4*1024)*4;
  150764. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  150765. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  150766. #else
  150767. # define FTS3_NODE_CHUNKSIZE (4*1024)
  150768. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  150769. #endif
  150770. /*
  150771. ** The two values that may be meaningfully bound to the :1 parameter in
  150772. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  150773. */
  150774. #define FTS_STAT_DOCTOTAL 0
  150775. #define FTS_STAT_INCRMERGEHINT 1
  150776. #define FTS_STAT_AUTOINCRMERGE 2
  150777. /*
  150778. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  150779. ** and incremental merge operation that takes place. This is used for
  150780. ** debugging FTS only, it should not usually be turned on in production
  150781. ** systems.
  150782. */
  150783. #ifdef FTS3_LOG_MERGES
  150784. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  150785. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  150786. }
  150787. #else
  150788. #define fts3LogMerge(x, y)
  150789. #endif
  150790. typedef struct PendingList PendingList;
  150791. typedef struct SegmentNode SegmentNode;
  150792. typedef struct SegmentWriter SegmentWriter;
  150793. /*
  150794. ** An instance of the following data structure is used to build doclists
  150795. ** incrementally. See function fts3PendingListAppend() for details.
  150796. */
  150797. struct PendingList {
  150798. int nData;
  150799. char *aData;
  150800. int nSpace;
  150801. sqlite3_int64 iLastDocid;
  150802. sqlite3_int64 iLastCol;
  150803. sqlite3_int64 iLastPos;
  150804. };
  150805. /*
  150806. ** Each cursor has a (possibly empty) linked list of the following objects.
  150807. */
  150808. struct Fts3DeferredToken {
  150809. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  150810. int iCol; /* Column token must occur in */
  150811. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  150812. PendingList *pList; /* Doclist is assembled here */
  150813. };
  150814. /*
  150815. ** An instance of this structure is used to iterate through the terms on
  150816. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  150817. ** this structure are only manipulated by code in this file, opaque handles
  150818. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  150819. ** terms when querying the full-text index. See functions:
  150820. **
  150821. ** sqlite3Fts3SegReaderNew()
  150822. ** sqlite3Fts3SegReaderFree()
  150823. ** sqlite3Fts3SegReaderIterate()
  150824. **
  150825. ** Methods used to manipulate Fts3SegReader structures:
  150826. **
  150827. ** fts3SegReaderNext()
  150828. ** fts3SegReaderFirstDocid()
  150829. ** fts3SegReaderNextDocid()
  150830. */
  150831. struct Fts3SegReader {
  150832. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  150833. u8 bLookup; /* True for a lookup only */
  150834. u8 rootOnly; /* True for a root-only reader */
  150835. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  150836. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  150837. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  150838. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  150839. char *aNode; /* Pointer to node data (or NULL) */
  150840. int nNode; /* Size of buffer at aNode (or 0) */
  150841. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  150842. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  150843. Fts3HashElem **ppNextElem;
  150844. /* Variables set by fts3SegReaderNext(). These may be read directly
  150845. ** by the caller. They are valid from the time SegmentReaderNew() returns
  150846. ** until SegmentReaderNext() returns something other than SQLITE_OK
  150847. ** (i.e. SQLITE_DONE).
  150848. */
  150849. int nTerm; /* Number of bytes in current term */
  150850. char *zTerm; /* Pointer to current term */
  150851. int nTermAlloc; /* Allocated size of zTerm buffer */
  150852. char *aDoclist; /* Pointer to doclist of current entry */
  150853. int nDoclist; /* Size of doclist in current entry */
  150854. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  150855. ** through the current doclist (aDoclist/nDoclist).
  150856. */
  150857. char *pOffsetList;
  150858. int nOffsetList; /* For descending pending seg-readers only */
  150859. sqlite3_int64 iDocid;
  150860. };
  150861. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  150862. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  150863. /*
  150864. ** An instance of this structure is used to create a segment b-tree in the
  150865. ** database. The internal details of this type are only accessed by the
  150866. ** following functions:
  150867. **
  150868. ** fts3SegWriterAdd()
  150869. ** fts3SegWriterFlush()
  150870. ** fts3SegWriterFree()
  150871. */
  150872. struct SegmentWriter {
  150873. SegmentNode *pTree; /* Pointer to interior tree structure */
  150874. sqlite3_int64 iFirst; /* First slot in %_segments written */
  150875. sqlite3_int64 iFree; /* Next free slot in %_segments */
  150876. char *zTerm; /* Pointer to previous term buffer */
  150877. int nTerm; /* Number of bytes in zTerm */
  150878. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  150879. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  150880. int nSize; /* Size of allocation at aData */
  150881. int nData; /* Bytes of data in aData */
  150882. char *aData; /* Pointer to block from malloc() */
  150883. i64 nLeafData; /* Number of bytes of leaf data written */
  150884. };
  150885. /*
  150886. ** Type SegmentNode is used by the following three functions to create
  150887. ** the interior part of the segment b+-tree structures (everything except
  150888. ** the leaf nodes). These functions and type are only ever used by code
  150889. ** within the fts3SegWriterXXX() family of functions described above.
  150890. **
  150891. ** fts3NodeAddTerm()
  150892. ** fts3NodeWrite()
  150893. ** fts3NodeFree()
  150894. **
  150895. ** When a b+tree is written to the database (either as a result of a merge
  150896. ** or the pending-terms table being flushed), leaves are written into the
  150897. ** database file as soon as they are completely populated. The interior of
  150898. ** the tree is assembled in memory and written out only once all leaves have
  150899. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  150900. ** very large, meaning that the interior of the tree consumes relatively
  150901. ** little memory.
  150902. */
  150903. struct SegmentNode {
  150904. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  150905. SegmentNode *pRight; /* Pointer to right-sibling */
  150906. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  150907. int nEntry; /* Number of terms written to node so far */
  150908. char *zTerm; /* Pointer to previous term buffer */
  150909. int nTerm; /* Number of bytes in zTerm */
  150910. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  150911. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  150912. int nData; /* Bytes of valid data so far */
  150913. char *aData; /* Node data */
  150914. };
  150915. /*
  150916. ** Valid values for the second argument to fts3SqlStmt().
  150917. */
  150918. #define SQL_DELETE_CONTENT 0
  150919. #define SQL_IS_EMPTY 1
  150920. #define SQL_DELETE_ALL_CONTENT 2
  150921. #define SQL_DELETE_ALL_SEGMENTS 3
  150922. #define SQL_DELETE_ALL_SEGDIR 4
  150923. #define SQL_DELETE_ALL_DOCSIZE 5
  150924. #define SQL_DELETE_ALL_STAT 6
  150925. #define SQL_SELECT_CONTENT_BY_ROWID 7
  150926. #define SQL_NEXT_SEGMENT_INDEX 8
  150927. #define SQL_INSERT_SEGMENTS 9
  150928. #define SQL_NEXT_SEGMENTS_ID 10
  150929. #define SQL_INSERT_SEGDIR 11
  150930. #define SQL_SELECT_LEVEL 12
  150931. #define SQL_SELECT_LEVEL_RANGE 13
  150932. #define SQL_SELECT_LEVEL_COUNT 14
  150933. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  150934. #define SQL_DELETE_SEGDIR_LEVEL 16
  150935. #define SQL_DELETE_SEGMENTS_RANGE 17
  150936. #define SQL_CONTENT_INSERT 18
  150937. #define SQL_DELETE_DOCSIZE 19
  150938. #define SQL_REPLACE_DOCSIZE 20
  150939. #define SQL_SELECT_DOCSIZE 21
  150940. #define SQL_SELECT_STAT 22
  150941. #define SQL_REPLACE_STAT 23
  150942. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  150943. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  150944. #define SQL_DELETE_SEGDIR_RANGE 26
  150945. #define SQL_SELECT_ALL_LANGID 27
  150946. #define SQL_FIND_MERGE_LEVEL 28
  150947. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  150948. #define SQL_DELETE_SEGDIR_ENTRY 30
  150949. #define SQL_SHIFT_SEGDIR_ENTRY 31
  150950. #define SQL_SELECT_SEGDIR 32
  150951. #define SQL_CHOMP_SEGDIR 33
  150952. #define SQL_SEGMENT_IS_APPENDABLE 34
  150953. #define SQL_SELECT_INDEXES 35
  150954. #define SQL_SELECT_MXLEVEL 36
  150955. #define SQL_SELECT_LEVEL_RANGE2 37
  150956. #define SQL_UPDATE_LEVEL_IDX 38
  150957. #define SQL_UPDATE_LEVEL 39
  150958. /*
  150959. ** This function is used to obtain an SQLite prepared statement handle
  150960. ** for the statement identified by the second argument. If successful,
  150961. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  150962. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  150963. **
  150964. ** If argument apVal is not NULL, then it must point to an array with
  150965. ** at least as many entries as the requested statement has bound
  150966. ** parameters. The values are bound to the statements parameters before
  150967. ** returning.
  150968. */
  150969. static int fts3SqlStmt(
  150970. Fts3Table *p, /* Virtual table handle */
  150971. int eStmt, /* One of the SQL_XXX constants above */
  150972. sqlite3_stmt **pp, /* OUT: Statement handle */
  150973. sqlite3_value **apVal /* Values to bind to statement */
  150974. ){
  150975. const char *azSql[] = {
  150976. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  150977. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  150978. /* 2 */ "DELETE FROM %Q.'%q_content'",
  150979. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  150980. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  150981. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  150982. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  150983. /* 7 */ "SELECT %s WHERE rowid=?",
  150984. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  150985. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  150986. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  150987. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  150988. /* Return segments in order from oldest to newest.*/
  150989. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  150990. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  150991. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  150992. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  150993. "ORDER BY level DESC, idx ASC",
  150994. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  150995. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  150996. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  150997. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  150998. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  150999. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  151000. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  151001. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  151002. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  151003. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  151004. /* 24 */ "",
  151005. /* 25 */ "",
  151006. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  151007. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  151008. /* This statement is used to determine which level to read the input from
  151009. ** when performing an incremental merge. It returns the absolute level number
  151010. ** of the oldest level in the db that contains at least ? segments. Or,
  151011. ** if no level in the FTS index contains more than ? segments, the statement
  151012. ** returns zero rows. */
  151013. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  151014. " GROUP BY level HAVING cnt>=?"
  151015. " ORDER BY (level %% 1024) ASC LIMIT 1",
  151016. /* Estimate the upper limit on the number of leaf nodes in a new segment
  151017. ** created by merging the oldest :2 segments from absolute level :1. See
  151018. ** function sqlite3Fts3Incrmerge() for details. */
  151019. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  151020. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  151021. /* SQL_DELETE_SEGDIR_ENTRY
  151022. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  151023. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  151024. /* SQL_SHIFT_SEGDIR_ENTRY
  151025. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  151026. ** to :1. */
  151027. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  151028. /* SQL_SELECT_SEGDIR
  151029. ** Read a single entry from the %_segdir table. The entry from absolute
  151030. ** level :1 with index value :2. */
  151031. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  151032. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  151033. /* SQL_CHOMP_SEGDIR
  151034. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  151035. ** entry located on absolute level :3 with index :4. */
  151036. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  151037. "WHERE level = ? AND idx = ?",
  151038. /* SQL_SEGMENT_IS_APPENDABLE
  151039. ** Return a single row if the segment with end_block=? is appendable. Or
  151040. ** no rows otherwise. */
  151041. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  151042. /* SQL_SELECT_INDEXES
  151043. ** Return the list of valid segment indexes for absolute level ? */
  151044. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  151045. /* SQL_SELECT_MXLEVEL
  151046. ** Return the largest relative level in the FTS index or indexes. */
  151047. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  151048. /* Return segments in order from oldest to newest.*/
  151049. /* 37 */ "SELECT level, idx, end_block "
  151050. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  151051. "ORDER BY level DESC, idx ASC",
  151052. /* Update statements used while promoting segments */
  151053. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  151054. "WHERE level=? AND idx=?",
  151055. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  151056. };
  151057. int rc = SQLITE_OK;
  151058. sqlite3_stmt *pStmt;
  151059. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  151060. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  151061. pStmt = p->aStmt[eStmt];
  151062. if( !pStmt ){
  151063. char *zSql;
  151064. if( eStmt==SQL_CONTENT_INSERT ){
  151065. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  151066. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  151067. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  151068. }else{
  151069. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  151070. }
  151071. if( !zSql ){
  151072. rc = SQLITE_NOMEM;
  151073. }else{
  151074. rc = sqlite3_prepare_v3(p->db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
  151075. &pStmt, NULL);
  151076. sqlite3_free(zSql);
  151077. assert( rc==SQLITE_OK || pStmt==0 );
  151078. p->aStmt[eStmt] = pStmt;
  151079. }
  151080. }
  151081. if( apVal ){
  151082. int i;
  151083. int nParam = sqlite3_bind_parameter_count(pStmt);
  151084. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  151085. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  151086. }
  151087. }
  151088. *pp = pStmt;
  151089. return rc;
  151090. }
  151091. static int fts3SelectDocsize(
  151092. Fts3Table *pTab, /* FTS3 table handle */
  151093. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  151094. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  151095. ){
  151096. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  151097. int rc; /* Return code */
  151098. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  151099. if( rc==SQLITE_OK ){
  151100. sqlite3_bind_int64(pStmt, 1, iDocid);
  151101. rc = sqlite3_step(pStmt);
  151102. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  151103. rc = sqlite3_reset(pStmt);
  151104. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  151105. pStmt = 0;
  151106. }else{
  151107. rc = SQLITE_OK;
  151108. }
  151109. }
  151110. *ppStmt = pStmt;
  151111. return rc;
  151112. }
  151113. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  151114. Fts3Table *pTab, /* Fts3 table handle */
  151115. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  151116. ){
  151117. sqlite3_stmt *pStmt = 0;
  151118. int rc;
  151119. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  151120. if( rc==SQLITE_OK ){
  151121. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  151122. if( sqlite3_step(pStmt)!=SQLITE_ROW
  151123. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  151124. ){
  151125. rc = sqlite3_reset(pStmt);
  151126. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  151127. pStmt = 0;
  151128. }
  151129. }
  151130. *ppStmt = pStmt;
  151131. return rc;
  151132. }
  151133. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  151134. Fts3Table *pTab, /* Fts3 table handle */
  151135. sqlite3_int64 iDocid, /* Docid to read size data for */
  151136. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  151137. ){
  151138. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  151139. }
  151140. /*
  151141. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  151142. ** array apVal[] to the SQL statement identified by eStmt, the statement
  151143. ** is executed.
  151144. **
  151145. ** Returns SQLITE_OK if the statement is successfully executed, or an
  151146. ** SQLite error code otherwise.
  151147. */
  151148. static void fts3SqlExec(
  151149. int *pRC, /* Result code */
  151150. Fts3Table *p, /* The FTS3 table */
  151151. int eStmt, /* Index of statement to evaluate */
  151152. sqlite3_value **apVal /* Parameters to bind */
  151153. ){
  151154. sqlite3_stmt *pStmt;
  151155. int rc;
  151156. if( *pRC ) return;
  151157. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  151158. if( rc==SQLITE_OK ){
  151159. sqlite3_step(pStmt);
  151160. rc = sqlite3_reset(pStmt);
  151161. }
  151162. *pRC = rc;
  151163. }
  151164. /*
  151165. ** This function ensures that the caller has obtained an exclusive
  151166. ** shared-cache table-lock on the %_segdir table. This is required before
  151167. ** writing data to the fts3 table. If this lock is not acquired first, then
  151168. ** the caller may end up attempting to take this lock as part of committing
  151169. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  151170. ** LOCKED_SHAREDCACHEto a COMMIT command.
  151171. **
  151172. ** It is best to avoid this because if FTS3 returns any error when
  151173. ** committing a transaction, the whole transaction will be rolled back.
  151174. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  151175. ** It can still happen if the user locks the underlying tables directly
  151176. ** instead of accessing them via FTS.
  151177. */
  151178. static int fts3Writelock(Fts3Table *p){
  151179. int rc = SQLITE_OK;
  151180. if( p->nPendingData==0 ){
  151181. sqlite3_stmt *pStmt;
  151182. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  151183. if( rc==SQLITE_OK ){
  151184. sqlite3_bind_null(pStmt, 1);
  151185. sqlite3_step(pStmt);
  151186. rc = sqlite3_reset(pStmt);
  151187. }
  151188. }
  151189. return rc;
  151190. }
  151191. /*
  151192. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  151193. ** Within each language id, a separate index is maintained to store the
  151194. ** document terms, and each configured prefix size (configured the FTS
  151195. ** "prefix=" option). And each index consists of multiple levels ("relative
  151196. ** levels").
  151197. **
  151198. ** All three of these values (the language id, the specific index and the
  151199. ** level within the index) are encoded in 64-bit integer values stored
  151200. ** in the %_segdir table on disk. This function is used to convert three
  151201. ** separate component values into the single 64-bit integer value that
  151202. ** can be used to query the %_segdir table.
  151203. **
  151204. ** Specifically, each language-id/index combination is allocated 1024
  151205. ** 64-bit integer level values ("absolute levels"). The main terms index
  151206. ** for language-id 0 is allocate values 0-1023. The first prefix index
  151207. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  151208. ** Language 1 indexes are allocated immediately following language 0.
  151209. **
  151210. ** So, for a system with nPrefix prefix indexes configured, the block of
  151211. ** absolute levels that corresponds to language-id iLangid and index
  151212. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  151213. */
  151214. static sqlite3_int64 getAbsoluteLevel(
  151215. Fts3Table *p, /* FTS3 table handle */
  151216. int iLangid, /* Language id */
  151217. int iIndex, /* Index in p->aIndex[] */
  151218. int iLevel /* Level of segments */
  151219. ){
  151220. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  151221. assert( iLangid>=0 );
  151222. assert( p->nIndex>0 );
  151223. assert( iIndex>=0 && iIndex<p->nIndex );
  151224. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  151225. return iBase + iLevel;
  151226. }
  151227. /*
  151228. ** Set *ppStmt to a statement handle that may be used to iterate through
  151229. ** all rows in the %_segdir table, from oldest to newest. If successful,
  151230. ** return SQLITE_OK. If an error occurs while preparing the statement,
  151231. ** return an SQLite error code.
  151232. **
  151233. ** There is only ever one instance of this SQL statement compiled for
  151234. ** each FTS3 table.
  151235. **
  151236. ** The statement returns the following columns from the %_segdir table:
  151237. **
  151238. ** 0: idx
  151239. ** 1: start_block
  151240. ** 2: leaves_end_block
  151241. ** 3: end_block
  151242. ** 4: root
  151243. */
  151244. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  151245. Fts3Table *p, /* FTS3 table */
  151246. int iLangid, /* Language being queried */
  151247. int iIndex, /* Index for p->aIndex[] */
  151248. int iLevel, /* Level to select (relative level) */
  151249. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  151250. ){
  151251. int rc;
  151252. sqlite3_stmt *pStmt = 0;
  151253. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  151254. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  151255. assert( iIndex>=0 && iIndex<p->nIndex );
  151256. if( iLevel<0 ){
  151257. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  151258. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  151259. if( rc==SQLITE_OK ){
  151260. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  151261. sqlite3_bind_int64(pStmt, 2,
  151262. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  151263. );
  151264. }
  151265. }else{
  151266. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  151267. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  151268. if( rc==SQLITE_OK ){
  151269. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  151270. }
  151271. }
  151272. *ppStmt = pStmt;
  151273. return rc;
  151274. }
  151275. /*
  151276. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  151277. ** if successful, or an SQLite error code otherwise.
  151278. **
  151279. ** This function also serves to allocate the PendingList structure itself.
  151280. ** For example, to create a new PendingList structure containing two
  151281. ** varints:
  151282. **
  151283. ** PendingList *p = 0;
  151284. ** fts3PendingListAppendVarint(&p, 1);
  151285. ** fts3PendingListAppendVarint(&p, 2);
  151286. */
  151287. static int fts3PendingListAppendVarint(
  151288. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  151289. sqlite3_int64 i /* Value to append to data */
  151290. ){
  151291. PendingList *p = *pp;
  151292. /* Allocate or grow the PendingList as required. */
  151293. if( !p ){
  151294. p = sqlite3_malloc(sizeof(*p) + 100);
  151295. if( !p ){
  151296. return SQLITE_NOMEM;
  151297. }
  151298. p->nSpace = 100;
  151299. p->aData = (char *)&p[1];
  151300. p->nData = 0;
  151301. }
  151302. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  151303. int nNew = p->nSpace * 2;
  151304. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  151305. if( !p ){
  151306. sqlite3_free(*pp);
  151307. *pp = 0;
  151308. return SQLITE_NOMEM;
  151309. }
  151310. p->nSpace = nNew;
  151311. p->aData = (char *)&p[1];
  151312. }
  151313. /* Append the new serialized varint to the end of the list. */
  151314. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  151315. p->aData[p->nData] = '\0';
  151316. *pp = p;
  151317. return SQLITE_OK;
  151318. }
  151319. /*
  151320. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  151321. ** is returned if the structure is sqlite3_realloced as part of adding
  151322. ** the entry. Otherwise, zero.
  151323. **
  151324. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  151325. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  151326. ** it is set to SQLITE_OK.
  151327. */
  151328. static int fts3PendingListAppend(
  151329. PendingList **pp, /* IN/OUT: PendingList structure */
  151330. sqlite3_int64 iDocid, /* Docid for entry to add */
  151331. sqlite3_int64 iCol, /* Column for entry to add */
  151332. sqlite3_int64 iPos, /* Position of term for entry to add */
  151333. int *pRc /* OUT: Return code */
  151334. ){
  151335. PendingList *p = *pp;
  151336. int rc = SQLITE_OK;
  151337. assert( !p || p->iLastDocid<=iDocid );
  151338. if( !p || p->iLastDocid!=iDocid ){
  151339. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  151340. if( p ){
  151341. assert( p->nData<p->nSpace );
  151342. assert( p->aData[p->nData]==0 );
  151343. p->nData++;
  151344. }
  151345. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  151346. goto pendinglistappend_out;
  151347. }
  151348. p->iLastCol = -1;
  151349. p->iLastPos = 0;
  151350. p->iLastDocid = iDocid;
  151351. }
  151352. if( iCol>0 && p->iLastCol!=iCol ){
  151353. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  151354. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  151355. ){
  151356. goto pendinglistappend_out;
  151357. }
  151358. p->iLastCol = iCol;
  151359. p->iLastPos = 0;
  151360. }
  151361. if( iCol>=0 ){
  151362. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  151363. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  151364. if( rc==SQLITE_OK ){
  151365. p->iLastPos = iPos;
  151366. }
  151367. }
  151368. pendinglistappend_out:
  151369. *pRc = rc;
  151370. if( p!=*pp ){
  151371. *pp = p;
  151372. return 1;
  151373. }
  151374. return 0;
  151375. }
  151376. /*
  151377. ** Free a PendingList object allocated by fts3PendingListAppend().
  151378. */
  151379. static void fts3PendingListDelete(PendingList *pList){
  151380. sqlite3_free(pList);
  151381. }
  151382. /*
  151383. ** Add an entry to one of the pending-terms hash tables.
  151384. */
  151385. static int fts3PendingTermsAddOne(
  151386. Fts3Table *p,
  151387. int iCol,
  151388. int iPos,
  151389. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  151390. const char *zToken,
  151391. int nToken
  151392. ){
  151393. PendingList *pList;
  151394. int rc = SQLITE_OK;
  151395. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  151396. if( pList ){
  151397. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  151398. }
  151399. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  151400. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  151401. /* Malloc failed while inserting the new entry. This can only
  151402. ** happen if there was no previous entry for this token.
  151403. */
  151404. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  151405. sqlite3_free(pList);
  151406. rc = SQLITE_NOMEM;
  151407. }
  151408. }
  151409. if( rc==SQLITE_OK ){
  151410. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  151411. }
  151412. return rc;
  151413. }
  151414. /*
  151415. ** Tokenize the nul-terminated string zText and add all tokens to the
  151416. ** pending-terms hash-table. The docid used is that currently stored in
  151417. ** p->iPrevDocid, and the column is specified by argument iCol.
  151418. **
  151419. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  151420. */
  151421. static int fts3PendingTermsAdd(
  151422. Fts3Table *p, /* Table into which text will be inserted */
  151423. int iLangid, /* Language id to use */
  151424. const char *zText, /* Text of document to be inserted */
  151425. int iCol, /* Column into which text is being inserted */
  151426. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  151427. ){
  151428. int rc;
  151429. int iStart = 0;
  151430. int iEnd = 0;
  151431. int iPos = 0;
  151432. int nWord = 0;
  151433. char const *zToken;
  151434. int nToken = 0;
  151435. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  151436. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  151437. sqlite3_tokenizer_cursor *pCsr;
  151438. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  151439. const char**,int*,int*,int*,int*);
  151440. assert( pTokenizer && pModule );
  151441. /* If the user has inserted a NULL value, this function may be called with
  151442. ** zText==0. In this case, add zero token entries to the hash table and
  151443. ** return early. */
  151444. if( zText==0 ){
  151445. *pnWord = 0;
  151446. return SQLITE_OK;
  151447. }
  151448. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  151449. if( rc!=SQLITE_OK ){
  151450. return rc;
  151451. }
  151452. xNext = pModule->xNext;
  151453. while( SQLITE_OK==rc
  151454. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  151455. ){
  151456. int i;
  151457. if( iPos>=nWord ) nWord = iPos+1;
  151458. /* Positions cannot be negative; we use -1 as a terminator internally.
  151459. ** Tokens must have a non-zero length.
  151460. */
  151461. if( iPos<0 || !zToken || nToken<=0 ){
  151462. rc = SQLITE_ERROR;
  151463. break;
  151464. }
  151465. /* Add the term to the terms index */
  151466. rc = fts3PendingTermsAddOne(
  151467. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  151468. );
  151469. /* Add the term to each of the prefix indexes that it is not too
  151470. ** short for. */
  151471. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  151472. struct Fts3Index *pIndex = &p->aIndex[i];
  151473. if( nToken<pIndex->nPrefix ) continue;
  151474. rc = fts3PendingTermsAddOne(
  151475. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  151476. );
  151477. }
  151478. }
  151479. pModule->xClose(pCsr);
  151480. *pnWord += nWord;
  151481. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  151482. }
  151483. /*
  151484. ** Calling this function indicates that subsequent calls to
  151485. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  151486. ** contents of the document with docid iDocid.
  151487. */
  151488. static int fts3PendingTermsDocid(
  151489. Fts3Table *p, /* Full-text table handle */
  151490. int bDelete, /* True if this op is a delete */
  151491. int iLangid, /* Language id of row being written */
  151492. sqlite_int64 iDocid /* Docid of row being written */
  151493. ){
  151494. assert( iLangid>=0 );
  151495. assert( bDelete==1 || bDelete==0 );
  151496. /* TODO(shess) Explore whether partially flushing the buffer on
  151497. ** forced-flush would provide better performance. I suspect that if
  151498. ** we ordered the doclists by size and flushed the largest until the
  151499. ** buffer was half empty, that would let the less frequent terms
  151500. ** generate longer doclists.
  151501. */
  151502. if( iDocid<p->iPrevDocid
  151503. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  151504. || p->iPrevLangid!=iLangid
  151505. || p->nPendingData>p->nMaxPendingData
  151506. ){
  151507. int rc = sqlite3Fts3PendingTermsFlush(p);
  151508. if( rc!=SQLITE_OK ) return rc;
  151509. }
  151510. p->iPrevDocid = iDocid;
  151511. p->iPrevLangid = iLangid;
  151512. p->bPrevDelete = bDelete;
  151513. return SQLITE_OK;
  151514. }
  151515. /*
  151516. ** Discard the contents of the pending-terms hash tables.
  151517. */
  151518. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  151519. int i;
  151520. for(i=0; i<p->nIndex; i++){
  151521. Fts3HashElem *pElem;
  151522. Fts3Hash *pHash = &p->aIndex[i].hPending;
  151523. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  151524. PendingList *pList = (PendingList *)fts3HashData(pElem);
  151525. fts3PendingListDelete(pList);
  151526. }
  151527. fts3HashClear(pHash);
  151528. }
  151529. p->nPendingData = 0;
  151530. }
  151531. /*
  151532. ** This function is called by the xUpdate() method as part of an INSERT
  151533. ** operation. It adds entries for each term in the new record to the
  151534. ** pendingTerms hash table.
  151535. **
  151536. ** Argument apVal is the same as the similarly named argument passed to
  151537. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  151538. */
  151539. static int fts3InsertTerms(
  151540. Fts3Table *p,
  151541. int iLangid,
  151542. sqlite3_value **apVal,
  151543. u32 *aSz
  151544. ){
  151545. int i; /* Iterator variable */
  151546. for(i=2; i<p->nColumn+2; i++){
  151547. int iCol = i-2;
  151548. if( p->abNotindexed[iCol]==0 ){
  151549. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  151550. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  151551. if( rc!=SQLITE_OK ){
  151552. return rc;
  151553. }
  151554. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  151555. }
  151556. }
  151557. return SQLITE_OK;
  151558. }
  151559. /*
  151560. ** This function is called by the xUpdate() method for an INSERT operation.
  151561. ** The apVal parameter is passed a copy of the apVal argument passed by
  151562. ** SQLite to the xUpdate() method. i.e:
  151563. **
  151564. ** apVal[0] Not used for INSERT.
  151565. ** apVal[1] rowid
  151566. ** apVal[2] Left-most user-defined column
  151567. ** ...
  151568. ** apVal[p->nColumn+1] Right-most user-defined column
  151569. ** apVal[p->nColumn+2] Hidden column with same name as table
  151570. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  151571. ** apVal[p->nColumn+4] Hidden languageid column
  151572. */
  151573. static int fts3InsertData(
  151574. Fts3Table *p, /* Full-text table */
  151575. sqlite3_value **apVal, /* Array of values to insert */
  151576. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  151577. ){
  151578. int rc; /* Return code */
  151579. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  151580. if( p->zContentTbl ){
  151581. sqlite3_value *pRowid = apVal[p->nColumn+3];
  151582. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  151583. pRowid = apVal[1];
  151584. }
  151585. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  151586. return SQLITE_CONSTRAINT;
  151587. }
  151588. *piDocid = sqlite3_value_int64(pRowid);
  151589. return SQLITE_OK;
  151590. }
  151591. /* Locate the statement handle used to insert data into the %_content
  151592. ** table. The SQL for this statement is:
  151593. **
  151594. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  151595. **
  151596. ** The statement features N '?' variables, where N is the number of user
  151597. ** defined columns in the FTS3 table, plus one for the docid field.
  151598. */
  151599. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  151600. if( rc==SQLITE_OK && p->zLanguageid ){
  151601. rc = sqlite3_bind_int(
  151602. pContentInsert, p->nColumn+2,
  151603. sqlite3_value_int(apVal[p->nColumn+4])
  151604. );
  151605. }
  151606. if( rc!=SQLITE_OK ) return rc;
  151607. /* There is a quirk here. The users INSERT statement may have specified
  151608. ** a value for the "rowid" field, for the "docid" field, or for both.
  151609. ** Which is a problem, since "rowid" and "docid" are aliases for the
  151610. ** same value. For example:
  151611. **
  151612. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  151613. **
  151614. ** In FTS3, this is an error. It is an error to specify non-NULL values
  151615. ** for both docid and some other rowid alias.
  151616. */
  151617. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  151618. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  151619. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  151620. ){
  151621. /* A rowid/docid conflict. */
  151622. return SQLITE_ERROR;
  151623. }
  151624. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  151625. if( rc!=SQLITE_OK ) return rc;
  151626. }
  151627. /* Execute the statement to insert the record. Set *piDocid to the
  151628. ** new docid value.
  151629. */
  151630. sqlite3_step(pContentInsert);
  151631. rc = sqlite3_reset(pContentInsert);
  151632. *piDocid = sqlite3_last_insert_rowid(p->db);
  151633. return rc;
  151634. }
  151635. /*
  151636. ** Remove all data from the FTS3 table. Clear the hash table containing
  151637. ** pending terms.
  151638. */
  151639. static int fts3DeleteAll(Fts3Table *p, int bContent){
  151640. int rc = SQLITE_OK; /* Return code */
  151641. /* Discard the contents of the pending-terms hash table. */
  151642. sqlite3Fts3PendingTermsClear(p);
  151643. /* Delete everything from the shadow tables. Except, leave %_content as
  151644. ** is if bContent is false. */
  151645. assert( p->zContentTbl==0 || bContent==0 );
  151646. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  151647. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  151648. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  151649. if( p->bHasDocsize ){
  151650. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  151651. }
  151652. if( p->bHasStat ){
  151653. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  151654. }
  151655. return rc;
  151656. }
  151657. /*
  151658. **
  151659. */
  151660. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  151661. int iLangid = 0;
  151662. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  151663. return iLangid;
  151664. }
  151665. /*
  151666. ** The first element in the apVal[] array is assumed to contain the docid
  151667. ** (an integer) of a row about to be deleted. Remove all terms from the
  151668. ** full-text index.
  151669. */
  151670. static void fts3DeleteTerms(
  151671. int *pRC, /* Result code */
  151672. Fts3Table *p, /* The FTS table to delete from */
  151673. sqlite3_value *pRowid, /* The docid to be deleted */
  151674. u32 *aSz, /* Sizes of deleted document written here */
  151675. int *pbFound /* OUT: Set to true if row really does exist */
  151676. ){
  151677. int rc;
  151678. sqlite3_stmt *pSelect;
  151679. assert( *pbFound==0 );
  151680. if( *pRC ) return;
  151681. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  151682. if( rc==SQLITE_OK ){
  151683. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  151684. int i;
  151685. int iLangid = langidFromSelect(p, pSelect);
  151686. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  151687. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  151688. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  151689. int iCol = i-1;
  151690. if( p->abNotindexed[iCol]==0 ){
  151691. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  151692. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  151693. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  151694. }
  151695. }
  151696. if( rc!=SQLITE_OK ){
  151697. sqlite3_reset(pSelect);
  151698. *pRC = rc;
  151699. return;
  151700. }
  151701. *pbFound = 1;
  151702. }
  151703. rc = sqlite3_reset(pSelect);
  151704. }else{
  151705. sqlite3_reset(pSelect);
  151706. }
  151707. *pRC = rc;
  151708. }
  151709. /*
  151710. ** Forward declaration to account for the circular dependency between
  151711. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  151712. */
  151713. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  151714. /*
  151715. ** This function allocates a new level iLevel index in the segdir table.
  151716. ** Usually, indexes are allocated within a level sequentially starting
  151717. ** with 0, so the allocated index is one greater than the value returned
  151718. ** by:
  151719. **
  151720. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  151721. **
  151722. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  151723. ** level, they are merged into a single level (iLevel+1) segment and the
  151724. ** allocated index is 0.
  151725. **
  151726. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  151727. ** returned. Otherwise, an SQLite error code is returned.
  151728. */
  151729. static int fts3AllocateSegdirIdx(
  151730. Fts3Table *p,
  151731. int iLangid, /* Language id */
  151732. int iIndex, /* Index for p->aIndex */
  151733. int iLevel,
  151734. int *piIdx
  151735. ){
  151736. int rc; /* Return Code */
  151737. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  151738. int iNext = 0; /* Result of query pNextIdx */
  151739. assert( iLangid>=0 );
  151740. assert( p->nIndex>=1 );
  151741. /* Set variable iNext to the next available segdir index at level iLevel. */
  151742. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  151743. if( rc==SQLITE_OK ){
  151744. sqlite3_bind_int64(
  151745. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  151746. );
  151747. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  151748. iNext = sqlite3_column_int(pNextIdx, 0);
  151749. }
  151750. rc = sqlite3_reset(pNextIdx);
  151751. }
  151752. if( rc==SQLITE_OK ){
  151753. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  151754. ** full, merge all segments in level iLevel into a single iLevel+1
  151755. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  151756. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  151757. */
  151758. if( iNext>=FTS3_MERGE_COUNT ){
  151759. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  151760. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  151761. *piIdx = 0;
  151762. }else{
  151763. *piIdx = iNext;
  151764. }
  151765. }
  151766. return rc;
  151767. }
  151768. /*
  151769. ** The %_segments table is declared as follows:
  151770. **
  151771. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  151772. **
  151773. ** This function reads data from a single row of the %_segments table. The
  151774. ** specific row is identified by the iBlockid parameter. If paBlob is not
  151775. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  151776. ** with the contents of the blob stored in the "block" column of the
  151777. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  151778. ** to the size of the blob in bytes before returning.
  151779. **
  151780. ** If an error occurs, or the table does not contain the specified row,
  151781. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  151782. ** paBlob is non-NULL, then it is the responsibility of the caller to
  151783. ** eventually free the returned buffer.
  151784. **
  151785. ** This function may leave an open sqlite3_blob* handle in the
  151786. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  151787. ** to this function. The handle may be closed by calling the
  151788. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  151789. ** performance improvement, but the blob handle should always be closed
  151790. ** before control is returned to the user (to prevent a lock being held
  151791. ** on the database file for longer than necessary). Thus, any virtual table
  151792. ** method (xFilter etc.) that may directly or indirectly call this function
  151793. ** must call sqlite3Fts3SegmentsClose() before returning.
  151794. */
  151795. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  151796. Fts3Table *p, /* FTS3 table handle */
  151797. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  151798. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  151799. int *pnBlob, /* OUT: Size of blob data */
  151800. int *pnLoad /* OUT: Bytes actually loaded */
  151801. ){
  151802. int rc; /* Return code */
  151803. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  151804. assert( pnBlob );
  151805. if( p->pSegments ){
  151806. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  151807. }else{
  151808. if( 0==p->zSegmentsTbl ){
  151809. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  151810. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  151811. }
  151812. rc = sqlite3_blob_open(
  151813. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  151814. );
  151815. }
  151816. if( rc==SQLITE_OK ){
  151817. int nByte = sqlite3_blob_bytes(p->pSegments);
  151818. *pnBlob = nByte;
  151819. if( paBlob ){
  151820. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  151821. if( !aByte ){
  151822. rc = SQLITE_NOMEM;
  151823. }else{
  151824. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  151825. nByte = FTS3_NODE_CHUNKSIZE;
  151826. *pnLoad = nByte;
  151827. }
  151828. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  151829. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  151830. if( rc!=SQLITE_OK ){
  151831. sqlite3_free(aByte);
  151832. aByte = 0;
  151833. }
  151834. }
  151835. *paBlob = aByte;
  151836. }
  151837. }
  151838. return rc;
  151839. }
  151840. /*
  151841. ** Close the blob handle at p->pSegments, if it is open. See comments above
  151842. ** the sqlite3Fts3ReadBlock() function for details.
  151843. */
  151844. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  151845. sqlite3_blob_close(p->pSegments);
  151846. p->pSegments = 0;
  151847. }
  151848. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  151849. int nRead; /* Number of bytes to read */
  151850. int rc; /* Return code */
  151851. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  151852. rc = sqlite3_blob_read(
  151853. pReader->pBlob,
  151854. &pReader->aNode[pReader->nPopulate],
  151855. nRead,
  151856. pReader->nPopulate
  151857. );
  151858. if( rc==SQLITE_OK ){
  151859. pReader->nPopulate += nRead;
  151860. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  151861. if( pReader->nPopulate==pReader->nNode ){
  151862. sqlite3_blob_close(pReader->pBlob);
  151863. pReader->pBlob = 0;
  151864. pReader->nPopulate = 0;
  151865. }
  151866. }
  151867. return rc;
  151868. }
  151869. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  151870. int rc = SQLITE_OK;
  151871. assert( !pReader->pBlob
  151872. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  151873. );
  151874. while( pReader->pBlob && rc==SQLITE_OK
  151875. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  151876. ){
  151877. rc = fts3SegReaderIncrRead(pReader);
  151878. }
  151879. return rc;
  151880. }
  151881. /*
  151882. ** Set an Fts3SegReader cursor to point at EOF.
  151883. */
  151884. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  151885. if( !fts3SegReaderIsRootOnly(pSeg) ){
  151886. sqlite3_free(pSeg->aNode);
  151887. sqlite3_blob_close(pSeg->pBlob);
  151888. pSeg->pBlob = 0;
  151889. }
  151890. pSeg->aNode = 0;
  151891. }
  151892. /*
  151893. ** Move the iterator passed as the first argument to the next term in the
  151894. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  151895. ** SQLITE_DONE. Otherwise, an SQLite error code.
  151896. */
  151897. static int fts3SegReaderNext(
  151898. Fts3Table *p,
  151899. Fts3SegReader *pReader,
  151900. int bIncr
  151901. ){
  151902. int rc; /* Return code of various sub-routines */
  151903. char *pNext; /* Cursor variable */
  151904. int nPrefix; /* Number of bytes in term prefix */
  151905. int nSuffix; /* Number of bytes in term suffix */
  151906. if( !pReader->aDoclist ){
  151907. pNext = pReader->aNode;
  151908. }else{
  151909. pNext = &pReader->aDoclist[pReader->nDoclist];
  151910. }
  151911. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  151912. if( fts3SegReaderIsPending(pReader) ){
  151913. Fts3HashElem *pElem = *(pReader->ppNextElem);
  151914. sqlite3_free(pReader->aNode);
  151915. pReader->aNode = 0;
  151916. if( pElem ){
  151917. char *aCopy;
  151918. PendingList *pList = (PendingList *)fts3HashData(pElem);
  151919. int nCopy = pList->nData+1;
  151920. pReader->zTerm = (char *)fts3HashKey(pElem);
  151921. pReader->nTerm = fts3HashKeysize(pElem);
  151922. aCopy = (char*)sqlite3_malloc(nCopy);
  151923. if( !aCopy ) return SQLITE_NOMEM;
  151924. memcpy(aCopy, pList->aData, nCopy);
  151925. pReader->nNode = pReader->nDoclist = nCopy;
  151926. pReader->aNode = pReader->aDoclist = aCopy;
  151927. pReader->ppNextElem++;
  151928. assert( pReader->aNode );
  151929. }
  151930. return SQLITE_OK;
  151931. }
  151932. fts3SegReaderSetEof(pReader);
  151933. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  151934. ** blocks have already been traversed. */
  151935. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  151936. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  151937. return SQLITE_OK;
  151938. }
  151939. rc = sqlite3Fts3ReadBlock(
  151940. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  151941. (bIncr ? &pReader->nPopulate : 0)
  151942. );
  151943. if( rc!=SQLITE_OK ) return rc;
  151944. assert( pReader->pBlob==0 );
  151945. if( bIncr && pReader->nPopulate<pReader->nNode ){
  151946. pReader->pBlob = p->pSegments;
  151947. p->pSegments = 0;
  151948. }
  151949. pNext = pReader->aNode;
  151950. }
  151951. assert( !fts3SegReaderIsPending(pReader) );
  151952. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  151953. if( rc!=SQLITE_OK ) return rc;
  151954. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  151955. ** safe (no risk of overread) even if the node data is corrupted. */
  151956. pNext += fts3GetVarint32(pNext, &nPrefix);
  151957. pNext += fts3GetVarint32(pNext, &nSuffix);
  151958. if( nPrefix<0 || nSuffix<=0
  151959. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  151960. ){
  151961. return FTS_CORRUPT_VTAB;
  151962. }
  151963. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  151964. int nNew = (nPrefix+nSuffix)*2;
  151965. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  151966. if( !zNew ){
  151967. return SQLITE_NOMEM;
  151968. }
  151969. pReader->zTerm = zNew;
  151970. pReader->nTermAlloc = nNew;
  151971. }
  151972. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  151973. if( rc!=SQLITE_OK ) return rc;
  151974. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  151975. pReader->nTerm = nPrefix+nSuffix;
  151976. pNext += nSuffix;
  151977. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  151978. pReader->aDoclist = pNext;
  151979. pReader->pOffsetList = 0;
  151980. /* Check that the doclist does not appear to extend past the end of the
  151981. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  151982. ** of these statements is untrue, then the data structure is corrupt.
  151983. */
  151984. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  151985. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  151986. ){
  151987. return FTS_CORRUPT_VTAB;
  151988. }
  151989. return SQLITE_OK;
  151990. }
  151991. /*
  151992. ** Set the SegReader to point to the first docid in the doclist associated
  151993. ** with the current term.
  151994. */
  151995. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  151996. int rc = SQLITE_OK;
  151997. assert( pReader->aDoclist );
  151998. assert( !pReader->pOffsetList );
  151999. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  152000. u8 bEof = 0;
  152001. pReader->iDocid = 0;
  152002. pReader->nOffsetList = 0;
  152003. sqlite3Fts3DoclistPrev(0,
  152004. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  152005. &pReader->iDocid, &pReader->nOffsetList, &bEof
  152006. );
  152007. }else{
  152008. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  152009. if( rc==SQLITE_OK ){
  152010. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  152011. pReader->pOffsetList = &pReader->aDoclist[n];
  152012. }
  152013. }
  152014. return rc;
  152015. }
  152016. /*
  152017. ** Advance the SegReader to point to the next docid in the doclist
  152018. ** associated with the current term.
  152019. **
  152020. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  152021. ** *ppOffsetList is set to point to the first column-offset list
  152022. ** in the doclist entry (i.e. immediately past the docid varint).
  152023. ** *pnOffsetList is set to the length of the set of column-offset
  152024. ** lists, not including the nul-terminator byte. For example:
  152025. */
  152026. static int fts3SegReaderNextDocid(
  152027. Fts3Table *pTab,
  152028. Fts3SegReader *pReader, /* Reader to advance to next docid */
  152029. char **ppOffsetList, /* OUT: Pointer to current position-list */
  152030. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  152031. ){
  152032. int rc = SQLITE_OK;
  152033. char *p = pReader->pOffsetList;
  152034. char c = 0;
  152035. assert( p );
  152036. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  152037. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  152038. ** Pending-terms doclists are always built up in ascending order, so
  152039. ** we have to iterate through them backwards here. */
  152040. u8 bEof = 0;
  152041. if( ppOffsetList ){
  152042. *ppOffsetList = pReader->pOffsetList;
  152043. *pnOffsetList = pReader->nOffsetList - 1;
  152044. }
  152045. sqlite3Fts3DoclistPrev(0,
  152046. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  152047. &pReader->nOffsetList, &bEof
  152048. );
  152049. if( bEof ){
  152050. pReader->pOffsetList = 0;
  152051. }else{
  152052. pReader->pOffsetList = p;
  152053. }
  152054. }else{
  152055. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  152056. /* Pointer p currently points at the first byte of an offset list. The
  152057. ** following block advances it to point one byte past the end of
  152058. ** the same offset list. */
  152059. while( 1 ){
  152060. /* The following line of code (and the "p++" below the while() loop) is
  152061. ** normally all that is required to move pointer p to the desired
  152062. ** position. The exception is if this node is being loaded from disk
  152063. ** incrementally and pointer "p" now points to the first byte past
  152064. ** the populated part of pReader->aNode[].
  152065. */
  152066. while( *p | c ) c = *p++ & 0x80;
  152067. assert( *p==0 );
  152068. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  152069. rc = fts3SegReaderIncrRead(pReader);
  152070. if( rc!=SQLITE_OK ) return rc;
  152071. }
  152072. p++;
  152073. /* If required, populate the output variables with a pointer to and the
  152074. ** size of the previous offset-list.
  152075. */
  152076. if( ppOffsetList ){
  152077. *ppOffsetList = pReader->pOffsetList;
  152078. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  152079. }
  152080. /* List may have been edited in place by fts3EvalNearTrim() */
  152081. while( p<pEnd && *p==0 ) p++;
  152082. /* If there are no more entries in the doclist, set pOffsetList to
  152083. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  152084. ** Fts3SegReader.pOffsetList to point to the next offset list before
  152085. ** returning.
  152086. */
  152087. if( p>=pEnd ){
  152088. pReader->pOffsetList = 0;
  152089. }else{
  152090. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  152091. if( rc==SQLITE_OK ){
  152092. sqlite3_int64 iDelta;
  152093. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  152094. if( pTab->bDescIdx ){
  152095. pReader->iDocid -= iDelta;
  152096. }else{
  152097. pReader->iDocid += iDelta;
  152098. }
  152099. }
  152100. }
  152101. }
  152102. return SQLITE_OK;
  152103. }
  152104. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  152105. Fts3Cursor *pCsr,
  152106. Fts3MultiSegReader *pMsr,
  152107. int *pnOvfl
  152108. ){
  152109. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  152110. int nOvfl = 0;
  152111. int ii;
  152112. int rc = SQLITE_OK;
  152113. int pgsz = p->nPgsz;
  152114. assert( p->bFts4 );
  152115. assert( pgsz>0 );
  152116. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  152117. Fts3SegReader *pReader = pMsr->apSegment[ii];
  152118. if( !fts3SegReaderIsPending(pReader)
  152119. && !fts3SegReaderIsRootOnly(pReader)
  152120. ){
  152121. sqlite3_int64 jj;
  152122. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  152123. int nBlob;
  152124. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  152125. if( rc!=SQLITE_OK ) break;
  152126. if( (nBlob+35)>pgsz ){
  152127. nOvfl += (nBlob + 34)/pgsz;
  152128. }
  152129. }
  152130. }
  152131. }
  152132. *pnOvfl = nOvfl;
  152133. return rc;
  152134. }
  152135. /*
  152136. ** Free all allocations associated with the iterator passed as the
  152137. ** second argument.
  152138. */
  152139. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  152140. if( pReader ){
  152141. if( !fts3SegReaderIsPending(pReader) ){
  152142. sqlite3_free(pReader->zTerm);
  152143. }
  152144. if( !fts3SegReaderIsRootOnly(pReader) ){
  152145. sqlite3_free(pReader->aNode);
  152146. }
  152147. sqlite3_blob_close(pReader->pBlob);
  152148. }
  152149. sqlite3_free(pReader);
  152150. }
  152151. /*
  152152. ** Allocate a new SegReader object.
  152153. */
  152154. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  152155. int iAge, /* Segment "age". */
  152156. int bLookup, /* True for a lookup only */
  152157. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  152158. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  152159. sqlite3_int64 iEndBlock, /* Final block of segment */
  152160. const char *zRoot, /* Buffer containing root node */
  152161. int nRoot, /* Size of buffer containing root node */
  152162. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  152163. ){
  152164. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  152165. int nExtra = 0; /* Bytes to allocate segment root node */
  152166. assert( iStartLeaf<=iEndLeaf );
  152167. if( iStartLeaf==0 ){
  152168. nExtra = nRoot + FTS3_NODE_PADDING;
  152169. }
  152170. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  152171. if( !pReader ){
  152172. return SQLITE_NOMEM;
  152173. }
  152174. memset(pReader, 0, sizeof(Fts3SegReader));
  152175. pReader->iIdx = iAge;
  152176. pReader->bLookup = bLookup!=0;
  152177. pReader->iStartBlock = iStartLeaf;
  152178. pReader->iLeafEndBlock = iEndLeaf;
  152179. pReader->iEndBlock = iEndBlock;
  152180. if( nExtra ){
  152181. /* The entire segment is stored in the root node. */
  152182. pReader->aNode = (char *)&pReader[1];
  152183. pReader->rootOnly = 1;
  152184. pReader->nNode = nRoot;
  152185. memcpy(pReader->aNode, zRoot, nRoot);
  152186. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  152187. }else{
  152188. pReader->iCurrentBlock = iStartLeaf-1;
  152189. }
  152190. *ppReader = pReader;
  152191. return SQLITE_OK;
  152192. }
  152193. /*
  152194. ** This is a comparison function used as a qsort() callback when sorting
  152195. ** an array of pending terms by term. This occurs as part of flushing
  152196. ** the contents of the pending-terms hash table to the database.
  152197. */
  152198. static int SQLITE_CDECL fts3CompareElemByTerm(
  152199. const void *lhs,
  152200. const void *rhs
  152201. ){
  152202. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  152203. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  152204. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  152205. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  152206. int n = (n1<n2 ? n1 : n2);
  152207. int c = memcmp(z1, z2, n);
  152208. if( c==0 ){
  152209. c = n1 - n2;
  152210. }
  152211. return c;
  152212. }
  152213. /*
  152214. ** This function is used to allocate an Fts3SegReader that iterates through
  152215. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  152216. **
  152217. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  152218. ** through each term in the pending-terms table. Or, if isPrefixIter is
  152219. ** non-zero, it iterates through each term and its prefixes. For example, if
  152220. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  152221. ** "firebird", then the iterator visits the following 'terms' (in the order
  152222. ** shown):
  152223. **
  152224. ** f fi fir fire fireb firebi firebir firebird
  152225. ** m my mys mysq mysql
  152226. ** s sq sql sqli sqlit sqlite
  152227. **
  152228. ** Whereas if isPrefixIter is zero, the terms visited are:
  152229. **
  152230. ** firebird mysql sqlite
  152231. */
  152232. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  152233. Fts3Table *p, /* Virtual table handle */
  152234. int iIndex, /* Index for p->aIndex */
  152235. const char *zTerm, /* Term to search for */
  152236. int nTerm, /* Size of buffer zTerm */
  152237. int bPrefix, /* True for a prefix iterator */
  152238. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  152239. ){
  152240. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  152241. Fts3HashElem *pE; /* Iterator variable */
  152242. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  152243. int nElem = 0; /* Size of array at aElem */
  152244. int rc = SQLITE_OK; /* Return Code */
  152245. Fts3Hash *pHash;
  152246. pHash = &p->aIndex[iIndex].hPending;
  152247. if( bPrefix ){
  152248. int nAlloc = 0; /* Size of allocated array at aElem */
  152249. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  152250. char *zKey = (char *)fts3HashKey(pE);
  152251. int nKey = fts3HashKeysize(pE);
  152252. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  152253. if( nElem==nAlloc ){
  152254. Fts3HashElem **aElem2;
  152255. nAlloc += 16;
  152256. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  152257. aElem, nAlloc*sizeof(Fts3HashElem *)
  152258. );
  152259. if( !aElem2 ){
  152260. rc = SQLITE_NOMEM;
  152261. nElem = 0;
  152262. break;
  152263. }
  152264. aElem = aElem2;
  152265. }
  152266. aElem[nElem++] = pE;
  152267. }
  152268. }
  152269. /* If more than one term matches the prefix, sort the Fts3HashElem
  152270. ** objects in term order using qsort(). This uses the same comparison
  152271. ** callback as is used when flushing terms to disk.
  152272. */
  152273. if( nElem>1 ){
  152274. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  152275. }
  152276. }else{
  152277. /* The query is a simple term lookup that matches at most one term in
  152278. ** the index. All that is required is a straight hash-lookup.
  152279. **
  152280. ** Because the stack address of pE may be accessed via the aElem pointer
  152281. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  152282. ** within this entire function, not just this "else{...}" block.
  152283. */
  152284. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  152285. if( pE ){
  152286. aElem = &pE;
  152287. nElem = 1;
  152288. }
  152289. }
  152290. if( nElem>0 ){
  152291. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  152292. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  152293. if( !pReader ){
  152294. rc = SQLITE_NOMEM;
  152295. }else{
  152296. memset(pReader, 0, nByte);
  152297. pReader->iIdx = 0x7FFFFFFF;
  152298. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  152299. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  152300. }
  152301. }
  152302. if( bPrefix ){
  152303. sqlite3_free(aElem);
  152304. }
  152305. *ppReader = pReader;
  152306. return rc;
  152307. }
  152308. /*
  152309. ** Compare the entries pointed to by two Fts3SegReader structures.
  152310. ** Comparison is as follows:
  152311. **
  152312. ** 1) EOF is greater than not EOF.
  152313. **
  152314. ** 2) The current terms (if any) are compared using memcmp(). If one
  152315. ** term is a prefix of another, the longer term is considered the
  152316. ** larger.
  152317. **
  152318. ** 3) By segment age. An older segment is considered larger.
  152319. */
  152320. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  152321. int rc;
  152322. if( pLhs->aNode && pRhs->aNode ){
  152323. int rc2 = pLhs->nTerm - pRhs->nTerm;
  152324. if( rc2<0 ){
  152325. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  152326. }else{
  152327. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  152328. }
  152329. if( rc==0 ){
  152330. rc = rc2;
  152331. }
  152332. }else{
  152333. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  152334. }
  152335. if( rc==0 ){
  152336. rc = pRhs->iIdx - pLhs->iIdx;
  152337. }
  152338. assert( rc!=0 );
  152339. return rc;
  152340. }
  152341. /*
  152342. ** A different comparison function for SegReader structures. In this
  152343. ** version, it is assumed that each SegReader points to an entry in
  152344. ** a doclist for identical terms. Comparison is made as follows:
  152345. **
  152346. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  152347. **
  152348. ** 2) By current docid.
  152349. **
  152350. ** 3) By segment age. An older segment is considered larger.
  152351. */
  152352. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  152353. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  152354. if( rc==0 ){
  152355. if( pLhs->iDocid==pRhs->iDocid ){
  152356. rc = pRhs->iIdx - pLhs->iIdx;
  152357. }else{
  152358. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  152359. }
  152360. }
  152361. assert( pLhs->aNode && pRhs->aNode );
  152362. return rc;
  152363. }
  152364. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  152365. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  152366. if( rc==0 ){
  152367. if( pLhs->iDocid==pRhs->iDocid ){
  152368. rc = pRhs->iIdx - pLhs->iIdx;
  152369. }else{
  152370. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  152371. }
  152372. }
  152373. assert( pLhs->aNode && pRhs->aNode );
  152374. return rc;
  152375. }
  152376. /*
  152377. ** Compare the term that the Fts3SegReader object passed as the first argument
  152378. ** points to with the term specified by arguments zTerm and nTerm.
  152379. **
  152380. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  152381. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  152382. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  152383. */
  152384. static int fts3SegReaderTermCmp(
  152385. Fts3SegReader *pSeg, /* Segment reader object */
  152386. const char *zTerm, /* Term to compare to */
  152387. int nTerm /* Size of term zTerm in bytes */
  152388. ){
  152389. int res = 0;
  152390. if( pSeg->aNode ){
  152391. if( pSeg->nTerm>nTerm ){
  152392. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  152393. }else{
  152394. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  152395. }
  152396. if( res==0 ){
  152397. res = pSeg->nTerm-nTerm;
  152398. }
  152399. }
  152400. return res;
  152401. }
  152402. /*
  152403. ** Argument apSegment is an array of nSegment elements. It is known that
  152404. ** the final (nSegment-nSuspect) members are already in sorted order
  152405. ** (according to the comparison function provided). This function shuffles
  152406. ** the array around until all entries are in sorted order.
  152407. */
  152408. static void fts3SegReaderSort(
  152409. Fts3SegReader **apSegment, /* Array to sort entries of */
  152410. int nSegment, /* Size of apSegment array */
  152411. int nSuspect, /* Unsorted entry count */
  152412. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  152413. ){
  152414. int i; /* Iterator variable */
  152415. assert( nSuspect<=nSegment );
  152416. if( nSuspect==nSegment ) nSuspect--;
  152417. for(i=nSuspect-1; i>=0; i--){
  152418. int j;
  152419. for(j=i; j<(nSegment-1); j++){
  152420. Fts3SegReader *pTmp;
  152421. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  152422. pTmp = apSegment[j+1];
  152423. apSegment[j+1] = apSegment[j];
  152424. apSegment[j] = pTmp;
  152425. }
  152426. }
  152427. #ifndef NDEBUG
  152428. /* Check that the list really is sorted now. */
  152429. for(i=0; i<(nSuspect-1); i++){
  152430. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  152431. }
  152432. #endif
  152433. }
  152434. /*
  152435. ** Insert a record into the %_segments table.
  152436. */
  152437. static int fts3WriteSegment(
  152438. Fts3Table *p, /* Virtual table handle */
  152439. sqlite3_int64 iBlock, /* Block id for new block */
  152440. char *z, /* Pointer to buffer containing block data */
  152441. int n /* Size of buffer z in bytes */
  152442. ){
  152443. sqlite3_stmt *pStmt;
  152444. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  152445. if( rc==SQLITE_OK ){
  152446. sqlite3_bind_int64(pStmt, 1, iBlock);
  152447. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  152448. sqlite3_step(pStmt);
  152449. rc = sqlite3_reset(pStmt);
  152450. sqlite3_bind_null(pStmt, 2);
  152451. }
  152452. return rc;
  152453. }
  152454. /*
  152455. ** Find the largest relative level number in the table. If successful, set
  152456. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  152457. ** set *pnMax to zero and return an SQLite error code.
  152458. */
  152459. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  152460. int rc;
  152461. int mxLevel = 0;
  152462. sqlite3_stmt *pStmt = 0;
  152463. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  152464. if( rc==SQLITE_OK ){
  152465. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  152466. mxLevel = sqlite3_column_int(pStmt, 0);
  152467. }
  152468. rc = sqlite3_reset(pStmt);
  152469. }
  152470. *pnMax = mxLevel;
  152471. return rc;
  152472. }
  152473. /*
  152474. ** Insert a record into the %_segdir table.
  152475. */
  152476. static int fts3WriteSegdir(
  152477. Fts3Table *p, /* Virtual table handle */
  152478. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  152479. int iIdx, /* Value for "idx" field */
  152480. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  152481. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  152482. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  152483. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  152484. char *zRoot, /* Blob value for "root" field */
  152485. int nRoot /* Number of bytes in buffer zRoot */
  152486. ){
  152487. sqlite3_stmt *pStmt;
  152488. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  152489. if( rc==SQLITE_OK ){
  152490. sqlite3_bind_int64(pStmt, 1, iLevel);
  152491. sqlite3_bind_int(pStmt, 2, iIdx);
  152492. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  152493. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  152494. if( nLeafData==0 ){
  152495. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  152496. }else{
  152497. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  152498. if( !zEnd ) return SQLITE_NOMEM;
  152499. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  152500. }
  152501. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  152502. sqlite3_step(pStmt);
  152503. rc = sqlite3_reset(pStmt);
  152504. sqlite3_bind_null(pStmt, 6);
  152505. }
  152506. return rc;
  152507. }
  152508. /*
  152509. ** Return the size of the common prefix (if any) shared by zPrev and
  152510. ** zNext, in bytes. For example,
  152511. **
  152512. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  152513. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  152514. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  152515. */
  152516. static int fts3PrefixCompress(
  152517. const char *zPrev, /* Buffer containing previous term */
  152518. int nPrev, /* Size of buffer zPrev in bytes */
  152519. const char *zNext, /* Buffer containing next term */
  152520. int nNext /* Size of buffer zNext in bytes */
  152521. ){
  152522. int n;
  152523. UNUSED_PARAMETER(nNext);
  152524. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  152525. return n;
  152526. }
  152527. /*
  152528. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  152529. ** (according to memcmp) than the previous term.
  152530. */
  152531. static int fts3NodeAddTerm(
  152532. Fts3Table *p, /* Virtual table handle */
  152533. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  152534. int isCopyTerm, /* True if zTerm/nTerm is transient */
  152535. const char *zTerm, /* Pointer to buffer containing term */
  152536. int nTerm /* Size of term in bytes */
  152537. ){
  152538. SegmentNode *pTree = *ppTree;
  152539. int rc;
  152540. SegmentNode *pNew;
  152541. /* First try to append the term to the current node. Return early if
  152542. ** this is possible.
  152543. */
  152544. if( pTree ){
  152545. int nData = pTree->nData; /* Current size of node in bytes */
  152546. int nReq = nData; /* Required space after adding zTerm */
  152547. int nPrefix; /* Number of bytes of prefix compression */
  152548. int nSuffix; /* Suffix length */
  152549. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  152550. nSuffix = nTerm-nPrefix;
  152551. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  152552. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  152553. if( nReq>p->nNodeSize ){
  152554. /* An unusual case: this is the first term to be added to the node
  152555. ** and the static node buffer (p->nNodeSize bytes) is not large
  152556. ** enough. Use a separately malloced buffer instead This wastes
  152557. ** p->nNodeSize bytes, but since this scenario only comes about when
  152558. ** the database contain two terms that share a prefix of almost 2KB,
  152559. ** this is not expected to be a serious problem.
  152560. */
  152561. assert( pTree->aData==(char *)&pTree[1] );
  152562. pTree->aData = (char *)sqlite3_malloc(nReq);
  152563. if( !pTree->aData ){
  152564. return SQLITE_NOMEM;
  152565. }
  152566. }
  152567. if( pTree->zTerm ){
  152568. /* There is no prefix-length field for first term in a node */
  152569. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  152570. }
  152571. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  152572. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  152573. pTree->nData = nData + nSuffix;
  152574. pTree->nEntry++;
  152575. if( isCopyTerm ){
  152576. if( pTree->nMalloc<nTerm ){
  152577. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  152578. if( !zNew ){
  152579. return SQLITE_NOMEM;
  152580. }
  152581. pTree->nMalloc = nTerm*2;
  152582. pTree->zMalloc = zNew;
  152583. }
  152584. pTree->zTerm = pTree->zMalloc;
  152585. memcpy(pTree->zTerm, zTerm, nTerm);
  152586. pTree->nTerm = nTerm;
  152587. }else{
  152588. pTree->zTerm = (char *)zTerm;
  152589. pTree->nTerm = nTerm;
  152590. }
  152591. return SQLITE_OK;
  152592. }
  152593. }
  152594. /* If control flows to here, it was not possible to append zTerm to the
  152595. ** current node. Create a new node (a right-sibling of the current node).
  152596. ** If this is the first node in the tree, the term is added to it.
  152597. **
  152598. ** Otherwise, the term is not added to the new node, it is left empty for
  152599. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  152600. ** has no parent, one is created here.
  152601. */
  152602. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  152603. if( !pNew ){
  152604. return SQLITE_NOMEM;
  152605. }
  152606. memset(pNew, 0, sizeof(SegmentNode));
  152607. pNew->nData = 1 + FTS3_VARINT_MAX;
  152608. pNew->aData = (char *)&pNew[1];
  152609. if( pTree ){
  152610. SegmentNode *pParent = pTree->pParent;
  152611. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  152612. if( pTree->pParent==0 ){
  152613. pTree->pParent = pParent;
  152614. }
  152615. pTree->pRight = pNew;
  152616. pNew->pLeftmost = pTree->pLeftmost;
  152617. pNew->pParent = pParent;
  152618. pNew->zMalloc = pTree->zMalloc;
  152619. pNew->nMalloc = pTree->nMalloc;
  152620. pTree->zMalloc = 0;
  152621. }else{
  152622. pNew->pLeftmost = pNew;
  152623. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  152624. }
  152625. *ppTree = pNew;
  152626. return rc;
  152627. }
  152628. /*
  152629. ** Helper function for fts3NodeWrite().
  152630. */
  152631. static int fts3TreeFinishNode(
  152632. SegmentNode *pTree,
  152633. int iHeight,
  152634. sqlite3_int64 iLeftChild
  152635. ){
  152636. int nStart;
  152637. assert( iHeight>=1 && iHeight<128 );
  152638. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  152639. pTree->aData[nStart] = (char)iHeight;
  152640. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  152641. return nStart;
  152642. }
  152643. /*
  152644. ** Write the buffer for the segment node pTree and all of its peers to the
  152645. ** database. Then call this function recursively to write the parent of
  152646. ** pTree and its peers to the database.
  152647. **
  152648. ** Except, if pTree is a root node, do not write it to the database. Instead,
  152649. ** set output variables *paRoot and *pnRoot to contain the root node.
  152650. **
  152651. ** If successful, SQLITE_OK is returned and output variable *piLast is
  152652. ** set to the largest blockid written to the database (or zero if no
  152653. ** blocks were written to the db). Otherwise, an SQLite error code is
  152654. ** returned.
  152655. */
  152656. static int fts3NodeWrite(
  152657. Fts3Table *p, /* Virtual table handle */
  152658. SegmentNode *pTree, /* SegmentNode handle */
  152659. int iHeight, /* Height of this node in tree */
  152660. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  152661. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  152662. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  152663. char **paRoot, /* OUT: Data for root node */
  152664. int *pnRoot /* OUT: Size of root node in bytes */
  152665. ){
  152666. int rc = SQLITE_OK;
  152667. if( !pTree->pParent ){
  152668. /* Root node of the tree. */
  152669. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  152670. *piLast = iFree-1;
  152671. *pnRoot = pTree->nData - nStart;
  152672. *paRoot = &pTree->aData[nStart];
  152673. }else{
  152674. SegmentNode *pIter;
  152675. sqlite3_int64 iNextFree = iFree;
  152676. sqlite3_int64 iNextLeaf = iLeaf;
  152677. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  152678. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  152679. int nWrite = pIter->nData - nStart;
  152680. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  152681. iNextFree++;
  152682. iNextLeaf += (pIter->nEntry+1);
  152683. }
  152684. if( rc==SQLITE_OK ){
  152685. assert( iNextLeaf==iFree );
  152686. rc = fts3NodeWrite(
  152687. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  152688. );
  152689. }
  152690. }
  152691. return rc;
  152692. }
  152693. /*
  152694. ** Free all memory allocations associated with the tree pTree.
  152695. */
  152696. static void fts3NodeFree(SegmentNode *pTree){
  152697. if( pTree ){
  152698. SegmentNode *p = pTree->pLeftmost;
  152699. fts3NodeFree(p->pParent);
  152700. while( p ){
  152701. SegmentNode *pRight = p->pRight;
  152702. if( p->aData!=(char *)&p[1] ){
  152703. sqlite3_free(p->aData);
  152704. }
  152705. assert( pRight==0 || p->zMalloc==0 );
  152706. sqlite3_free(p->zMalloc);
  152707. sqlite3_free(p);
  152708. p = pRight;
  152709. }
  152710. }
  152711. }
  152712. /*
  152713. ** Add a term to the segment being constructed by the SegmentWriter object
  152714. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  152715. ** be passed NULL. This function will allocate a new SegmentWriter object
  152716. ** and return it via the input/output variable *ppWriter in this case.
  152717. **
  152718. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  152719. */
  152720. static int fts3SegWriterAdd(
  152721. Fts3Table *p, /* Virtual table handle */
  152722. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  152723. int isCopyTerm, /* True if buffer zTerm must be copied */
  152724. const char *zTerm, /* Pointer to buffer containing term */
  152725. int nTerm, /* Size of term in bytes */
  152726. const char *aDoclist, /* Pointer to buffer containing doclist */
  152727. int nDoclist /* Size of doclist in bytes */
  152728. ){
  152729. int nPrefix; /* Size of term prefix in bytes */
  152730. int nSuffix; /* Size of term suffix in bytes */
  152731. int nReq; /* Number of bytes required on leaf page */
  152732. int nData;
  152733. SegmentWriter *pWriter = *ppWriter;
  152734. if( !pWriter ){
  152735. int rc;
  152736. sqlite3_stmt *pStmt;
  152737. /* Allocate the SegmentWriter structure */
  152738. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  152739. if( !pWriter ) return SQLITE_NOMEM;
  152740. memset(pWriter, 0, sizeof(SegmentWriter));
  152741. *ppWriter = pWriter;
  152742. /* Allocate a buffer in which to accumulate data */
  152743. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  152744. if( !pWriter->aData ) return SQLITE_NOMEM;
  152745. pWriter->nSize = p->nNodeSize;
  152746. /* Find the next free blockid in the %_segments table */
  152747. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  152748. if( rc!=SQLITE_OK ) return rc;
  152749. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  152750. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  152751. pWriter->iFirst = pWriter->iFree;
  152752. }
  152753. rc = sqlite3_reset(pStmt);
  152754. if( rc!=SQLITE_OK ) return rc;
  152755. }
  152756. nData = pWriter->nData;
  152757. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  152758. nSuffix = nTerm-nPrefix;
  152759. /* Figure out how many bytes are required by this new entry */
  152760. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  152761. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  152762. nSuffix + /* Term suffix */
  152763. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  152764. nDoclist; /* Doclist data */
  152765. if( nData>0 && nData+nReq>p->nNodeSize ){
  152766. int rc;
  152767. /* The current leaf node is full. Write it out to the database. */
  152768. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  152769. if( rc!=SQLITE_OK ) return rc;
  152770. p->nLeafAdd++;
  152771. /* Add the current term to the interior node tree. The term added to
  152772. ** the interior tree must:
  152773. **
  152774. ** a) be greater than the largest term on the leaf node just written
  152775. ** to the database (still available in pWriter->zTerm), and
  152776. **
  152777. ** b) be less than or equal to the term about to be added to the new
  152778. ** leaf node (zTerm/nTerm).
  152779. **
  152780. ** In other words, it must be the prefix of zTerm 1 byte longer than
  152781. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  152782. */
  152783. assert( nPrefix<nTerm );
  152784. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  152785. if( rc!=SQLITE_OK ) return rc;
  152786. nData = 0;
  152787. pWriter->nTerm = 0;
  152788. nPrefix = 0;
  152789. nSuffix = nTerm;
  152790. nReq = 1 + /* varint containing prefix size */
  152791. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  152792. nTerm + /* Term suffix */
  152793. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  152794. nDoclist; /* Doclist data */
  152795. }
  152796. /* Increase the total number of bytes written to account for the new entry. */
  152797. pWriter->nLeafData += nReq;
  152798. /* If the buffer currently allocated is too small for this entry, realloc
  152799. ** the buffer to make it large enough.
  152800. */
  152801. if( nReq>pWriter->nSize ){
  152802. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  152803. if( !aNew ) return SQLITE_NOMEM;
  152804. pWriter->aData = aNew;
  152805. pWriter->nSize = nReq;
  152806. }
  152807. assert( nData+nReq<=pWriter->nSize );
  152808. /* Append the prefix-compressed term and doclist to the buffer. */
  152809. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  152810. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  152811. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  152812. nData += nSuffix;
  152813. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  152814. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  152815. pWriter->nData = nData + nDoclist;
  152816. /* Save the current term so that it can be used to prefix-compress the next.
  152817. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  152818. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  152819. ** store a copy of the pointer.
  152820. */
  152821. if( isCopyTerm ){
  152822. if( nTerm>pWriter->nMalloc ){
  152823. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  152824. if( !zNew ){
  152825. return SQLITE_NOMEM;
  152826. }
  152827. pWriter->nMalloc = nTerm*2;
  152828. pWriter->zMalloc = zNew;
  152829. pWriter->zTerm = zNew;
  152830. }
  152831. assert( pWriter->zTerm==pWriter->zMalloc );
  152832. memcpy(pWriter->zTerm, zTerm, nTerm);
  152833. }else{
  152834. pWriter->zTerm = (char *)zTerm;
  152835. }
  152836. pWriter->nTerm = nTerm;
  152837. return SQLITE_OK;
  152838. }
  152839. /*
  152840. ** Flush all data associated with the SegmentWriter object pWriter to the
  152841. ** database. This function must be called after all terms have been added
  152842. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  152843. ** returned. Otherwise, an SQLite error code.
  152844. */
  152845. static int fts3SegWriterFlush(
  152846. Fts3Table *p, /* Virtual table handle */
  152847. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  152848. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  152849. int iIdx /* Value for 'idx' column of %_segdir */
  152850. ){
  152851. int rc; /* Return code */
  152852. if( pWriter->pTree ){
  152853. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  152854. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  152855. char *zRoot = NULL; /* Pointer to buffer containing root node */
  152856. int nRoot = 0; /* Size of buffer zRoot */
  152857. iLastLeaf = pWriter->iFree;
  152858. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  152859. if( rc==SQLITE_OK ){
  152860. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  152861. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  152862. }
  152863. if( rc==SQLITE_OK ){
  152864. rc = fts3WriteSegdir(p, iLevel, iIdx,
  152865. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  152866. }
  152867. }else{
  152868. /* The entire tree fits on the root node. Write it to the segdir table. */
  152869. rc = fts3WriteSegdir(p, iLevel, iIdx,
  152870. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  152871. }
  152872. p->nLeafAdd++;
  152873. return rc;
  152874. }
  152875. /*
  152876. ** Release all memory held by the SegmentWriter object passed as the
  152877. ** first argument.
  152878. */
  152879. static void fts3SegWriterFree(SegmentWriter *pWriter){
  152880. if( pWriter ){
  152881. sqlite3_free(pWriter->aData);
  152882. sqlite3_free(pWriter->zMalloc);
  152883. fts3NodeFree(pWriter->pTree);
  152884. sqlite3_free(pWriter);
  152885. }
  152886. }
  152887. /*
  152888. ** The first value in the apVal[] array is assumed to contain an integer.
  152889. ** This function tests if there exist any documents with docid values that
  152890. ** are different from that integer. i.e. if deleting the document with docid
  152891. ** pRowid would mean the FTS3 table were empty.
  152892. **
  152893. ** If successful, *pisEmpty is set to true if the table is empty except for
  152894. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  152895. ** error occurs, an SQLite error code is returned.
  152896. */
  152897. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  152898. sqlite3_stmt *pStmt;
  152899. int rc;
  152900. if( p->zContentTbl ){
  152901. /* If using the content=xxx option, assume the table is never empty */
  152902. *pisEmpty = 0;
  152903. rc = SQLITE_OK;
  152904. }else{
  152905. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  152906. if( rc==SQLITE_OK ){
  152907. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  152908. *pisEmpty = sqlite3_column_int(pStmt, 0);
  152909. }
  152910. rc = sqlite3_reset(pStmt);
  152911. }
  152912. }
  152913. return rc;
  152914. }
  152915. /*
  152916. ** Set *pnMax to the largest segment level in the database for the index
  152917. ** iIndex.
  152918. **
  152919. ** Segment levels are stored in the 'level' column of the %_segdir table.
  152920. **
  152921. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  152922. */
  152923. static int fts3SegmentMaxLevel(
  152924. Fts3Table *p,
  152925. int iLangid,
  152926. int iIndex,
  152927. sqlite3_int64 *pnMax
  152928. ){
  152929. sqlite3_stmt *pStmt;
  152930. int rc;
  152931. assert( iIndex>=0 && iIndex<p->nIndex );
  152932. /* Set pStmt to the compiled version of:
  152933. **
  152934. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  152935. **
  152936. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  152937. */
  152938. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  152939. if( rc!=SQLITE_OK ) return rc;
  152940. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  152941. sqlite3_bind_int64(pStmt, 2,
  152942. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  152943. );
  152944. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  152945. *pnMax = sqlite3_column_int64(pStmt, 0);
  152946. }
  152947. return sqlite3_reset(pStmt);
  152948. }
  152949. /*
  152950. ** iAbsLevel is an absolute level that may be assumed to exist within
  152951. ** the database. This function checks if it is the largest level number
  152952. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  152953. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  152954. ** is returned. If an error occurs, an error code is returned and the
  152955. ** final value of *pbMax is undefined.
  152956. */
  152957. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  152958. /* Set pStmt to the compiled version of:
  152959. **
  152960. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  152961. **
  152962. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  152963. */
  152964. sqlite3_stmt *pStmt;
  152965. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  152966. if( rc!=SQLITE_OK ) return rc;
  152967. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  152968. sqlite3_bind_int64(pStmt, 2,
  152969. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  152970. );
  152971. *pbMax = 0;
  152972. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  152973. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  152974. }
  152975. return sqlite3_reset(pStmt);
  152976. }
  152977. /*
  152978. ** Delete all entries in the %_segments table associated with the segment
  152979. ** opened with seg-reader pSeg. This function does not affect the contents
  152980. ** of the %_segdir table.
  152981. */
  152982. static int fts3DeleteSegment(
  152983. Fts3Table *p, /* FTS table handle */
  152984. Fts3SegReader *pSeg /* Segment to delete */
  152985. ){
  152986. int rc = SQLITE_OK; /* Return code */
  152987. if( pSeg->iStartBlock ){
  152988. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  152989. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  152990. if( rc==SQLITE_OK ){
  152991. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  152992. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  152993. sqlite3_step(pDelete);
  152994. rc = sqlite3_reset(pDelete);
  152995. }
  152996. }
  152997. return rc;
  152998. }
  152999. /*
  153000. ** This function is used after merging multiple segments into a single large
  153001. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  153002. ** it:
  153003. **
  153004. ** 1) Deletes all %_segments entries for the segments associated with
  153005. ** each of the SegReader objects in the array passed as the third
  153006. ** argument, and
  153007. **
  153008. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  153009. ** entries regardless of level if (iLevel<0).
  153010. **
  153011. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  153012. */
  153013. static int fts3DeleteSegdir(
  153014. Fts3Table *p, /* Virtual table handle */
  153015. int iLangid, /* Language id */
  153016. int iIndex, /* Index for p->aIndex */
  153017. int iLevel, /* Level of %_segdir entries to delete */
  153018. Fts3SegReader **apSegment, /* Array of SegReader objects */
  153019. int nReader /* Size of array apSegment */
  153020. ){
  153021. int rc = SQLITE_OK; /* Return Code */
  153022. int i; /* Iterator variable */
  153023. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  153024. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  153025. rc = fts3DeleteSegment(p, apSegment[i]);
  153026. }
  153027. if( rc!=SQLITE_OK ){
  153028. return rc;
  153029. }
  153030. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  153031. if( iLevel==FTS3_SEGCURSOR_ALL ){
  153032. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  153033. if( rc==SQLITE_OK ){
  153034. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  153035. sqlite3_bind_int64(pDelete, 2,
  153036. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  153037. );
  153038. }
  153039. }else{
  153040. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  153041. if( rc==SQLITE_OK ){
  153042. sqlite3_bind_int64(
  153043. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  153044. );
  153045. }
  153046. }
  153047. if( rc==SQLITE_OK ){
  153048. sqlite3_step(pDelete);
  153049. rc = sqlite3_reset(pDelete);
  153050. }
  153051. return rc;
  153052. }
  153053. /*
  153054. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  153055. ** a position list that may (or may not) feature multiple columns. This
  153056. ** function adjusts the pointer *ppList and the length *pnList so that they
  153057. ** identify the subset of the position list that corresponds to column iCol.
  153058. **
  153059. ** If there are no entries in the input position list for column iCol, then
  153060. ** *pnList is set to zero before returning.
  153061. **
  153062. ** If parameter bZero is non-zero, then any part of the input list following
  153063. ** the end of the output list is zeroed before returning.
  153064. */
  153065. static void fts3ColumnFilter(
  153066. int iCol, /* Column to filter on */
  153067. int bZero, /* Zero out anything following *ppList */
  153068. char **ppList, /* IN/OUT: Pointer to position list */
  153069. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  153070. ){
  153071. char *pList = *ppList;
  153072. int nList = *pnList;
  153073. char *pEnd = &pList[nList];
  153074. int iCurrent = 0;
  153075. char *p = pList;
  153076. assert( iCol>=0 );
  153077. while( 1 ){
  153078. char c = 0;
  153079. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  153080. if( iCol==iCurrent ){
  153081. nList = (int)(p - pList);
  153082. break;
  153083. }
  153084. nList -= (int)(p - pList);
  153085. pList = p;
  153086. if( nList==0 ){
  153087. break;
  153088. }
  153089. p = &pList[1];
  153090. p += fts3GetVarint32(p, &iCurrent);
  153091. }
  153092. if( bZero && &pList[nList]!=pEnd ){
  153093. memset(&pList[nList], 0, pEnd - &pList[nList]);
  153094. }
  153095. *ppList = pList;
  153096. *pnList = nList;
  153097. }
  153098. /*
  153099. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  153100. ** existing data). Grow the buffer if required.
  153101. **
  153102. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  153103. ** trying to resize the buffer, return SQLITE_NOMEM.
  153104. */
  153105. static int fts3MsrBufferData(
  153106. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  153107. char *pList,
  153108. int nList
  153109. ){
  153110. if( nList>pMsr->nBuffer ){
  153111. char *pNew;
  153112. pMsr->nBuffer = nList*2;
  153113. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  153114. if( !pNew ) return SQLITE_NOMEM;
  153115. pMsr->aBuffer = pNew;
  153116. }
  153117. memcpy(pMsr->aBuffer, pList, nList);
  153118. return SQLITE_OK;
  153119. }
  153120. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  153121. Fts3Table *p, /* Virtual table handle */
  153122. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  153123. sqlite3_int64 *piDocid, /* OUT: Docid value */
  153124. char **paPoslist, /* OUT: Pointer to position list */
  153125. int *pnPoslist /* OUT: Size of position list in bytes */
  153126. ){
  153127. int nMerge = pMsr->nAdvance;
  153128. Fts3SegReader **apSegment = pMsr->apSegment;
  153129. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  153130. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  153131. );
  153132. if( nMerge==0 ){
  153133. *paPoslist = 0;
  153134. return SQLITE_OK;
  153135. }
  153136. while( 1 ){
  153137. Fts3SegReader *pSeg;
  153138. pSeg = pMsr->apSegment[0];
  153139. if( pSeg->pOffsetList==0 ){
  153140. *paPoslist = 0;
  153141. break;
  153142. }else{
  153143. int rc;
  153144. char *pList;
  153145. int nList;
  153146. int j;
  153147. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  153148. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  153149. j = 1;
  153150. while( rc==SQLITE_OK
  153151. && j<nMerge
  153152. && apSegment[j]->pOffsetList
  153153. && apSegment[j]->iDocid==iDocid
  153154. ){
  153155. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  153156. j++;
  153157. }
  153158. if( rc!=SQLITE_OK ) return rc;
  153159. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  153160. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  153161. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  153162. if( rc!=SQLITE_OK ) return rc;
  153163. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  153164. pList = pMsr->aBuffer;
  153165. }
  153166. if( pMsr->iColFilter>=0 ){
  153167. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  153168. }
  153169. if( nList>0 ){
  153170. *paPoslist = pList;
  153171. *piDocid = iDocid;
  153172. *pnPoslist = nList;
  153173. break;
  153174. }
  153175. }
  153176. }
  153177. return SQLITE_OK;
  153178. }
  153179. static int fts3SegReaderStart(
  153180. Fts3Table *p, /* Virtual table handle */
  153181. Fts3MultiSegReader *pCsr, /* Cursor object */
  153182. const char *zTerm, /* Term searched for (or NULL) */
  153183. int nTerm /* Length of zTerm in bytes */
  153184. ){
  153185. int i;
  153186. int nSeg = pCsr->nSegment;
  153187. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  153188. ** for, then advance each segment iterator until it points to a term of
  153189. ** equal or greater value than the specified term. This prevents many
  153190. ** unnecessary merge/sort operations for the case where single segment
  153191. ** b-tree leaf nodes contain more than one term.
  153192. */
  153193. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  153194. int res = 0;
  153195. Fts3SegReader *pSeg = pCsr->apSegment[i];
  153196. do {
  153197. int rc = fts3SegReaderNext(p, pSeg, 0);
  153198. if( rc!=SQLITE_OK ) return rc;
  153199. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  153200. if( pSeg->bLookup && res!=0 ){
  153201. fts3SegReaderSetEof(pSeg);
  153202. }
  153203. }
  153204. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  153205. return SQLITE_OK;
  153206. }
  153207. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  153208. Fts3Table *p, /* Virtual table handle */
  153209. Fts3MultiSegReader *pCsr, /* Cursor object */
  153210. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  153211. ){
  153212. pCsr->pFilter = pFilter;
  153213. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  153214. }
  153215. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  153216. Fts3Table *p, /* Virtual table handle */
  153217. Fts3MultiSegReader *pCsr, /* Cursor object */
  153218. int iCol, /* Column to match on. */
  153219. const char *zTerm, /* Term to iterate through a doclist for */
  153220. int nTerm /* Number of bytes in zTerm */
  153221. ){
  153222. int i;
  153223. int rc;
  153224. int nSegment = pCsr->nSegment;
  153225. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  153226. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  153227. );
  153228. assert( pCsr->pFilter==0 );
  153229. assert( zTerm && nTerm>0 );
  153230. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  153231. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  153232. if( rc!=SQLITE_OK ) return rc;
  153233. /* Determine how many of the segments actually point to zTerm/nTerm. */
  153234. for(i=0; i<nSegment; i++){
  153235. Fts3SegReader *pSeg = pCsr->apSegment[i];
  153236. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  153237. break;
  153238. }
  153239. }
  153240. pCsr->nAdvance = i;
  153241. /* Advance each of the segments to point to the first docid. */
  153242. for(i=0; i<pCsr->nAdvance; i++){
  153243. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  153244. if( rc!=SQLITE_OK ) return rc;
  153245. }
  153246. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  153247. assert( iCol<0 || iCol<p->nColumn );
  153248. pCsr->iColFilter = iCol;
  153249. return SQLITE_OK;
  153250. }
  153251. /*
  153252. ** This function is called on a MultiSegReader that has been started using
  153253. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  153254. ** have been made. Calling this function puts the MultiSegReader in such
  153255. ** a state that if the next two calls are:
  153256. **
  153257. ** sqlite3Fts3SegReaderStart()
  153258. ** sqlite3Fts3SegReaderStep()
  153259. **
  153260. ** then the entire doclist for the term is available in
  153261. ** MultiSegReader.aDoclist/nDoclist.
  153262. */
  153263. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  153264. int i; /* Used to iterate through segment-readers */
  153265. assert( pCsr->zTerm==0 );
  153266. assert( pCsr->nTerm==0 );
  153267. assert( pCsr->aDoclist==0 );
  153268. assert( pCsr->nDoclist==0 );
  153269. pCsr->nAdvance = 0;
  153270. pCsr->bRestart = 1;
  153271. for(i=0; i<pCsr->nSegment; i++){
  153272. pCsr->apSegment[i]->pOffsetList = 0;
  153273. pCsr->apSegment[i]->nOffsetList = 0;
  153274. pCsr->apSegment[i]->iDocid = 0;
  153275. }
  153276. return SQLITE_OK;
  153277. }
  153278. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  153279. Fts3Table *p, /* Virtual table handle */
  153280. Fts3MultiSegReader *pCsr /* Cursor object */
  153281. ){
  153282. int rc = SQLITE_OK;
  153283. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  153284. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  153285. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  153286. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  153287. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  153288. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  153289. Fts3SegReader **apSegment = pCsr->apSegment;
  153290. int nSegment = pCsr->nSegment;
  153291. Fts3SegFilter *pFilter = pCsr->pFilter;
  153292. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  153293. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  153294. );
  153295. if( pCsr->nSegment==0 ) return SQLITE_OK;
  153296. do {
  153297. int nMerge;
  153298. int i;
  153299. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  153300. ** forward. Then sort the list in order of current term again.
  153301. */
  153302. for(i=0; i<pCsr->nAdvance; i++){
  153303. Fts3SegReader *pSeg = apSegment[i];
  153304. if( pSeg->bLookup ){
  153305. fts3SegReaderSetEof(pSeg);
  153306. }else{
  153307. rc = fts3SegReaderNext(p, pSeg, 0);
  153308. }
  153309. if( rc!=SQLITE_OK ) return rc;
  153310. }
  153311. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  153312. pCsr->nAdvance = 0;
  153313. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  153314. assert( rc==SQLITE_OK );
  153315. if( apSegment[0]->aNode==0 ) break;
  153316. pCsr->nTerm = apSegment[0]->nTerm;
  153317. pCsr->zTerm = apSegment[0]->zTerm;
  153318. /* If this is a prefix-search, and if the term that apSegment[0] points
  153319. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  153320. ** required callbacks have been made. In this case exit early.
  153321. **
  153322. ** Similarly, if this is a search for an exact match, and the first term
  153323. ** of segment apSegment[0] is not a match, exit early.
  153324. */
  153325. if( pFilter->zTerm && !isScan ){
  153326. if( pCsr->nTerm<pFilter->nTerm
  153327. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  153328. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  153329. ){
  153330. break;
  153331. }
  153332. }
  153333. nMerge = 1;
  153334. while( nMerge<nSegment
  153335. && apSegment[nMerge]->aNode
  153336. && apSegment[nMerge]->nTerm==pCsr->nTerm
  153337. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  153338. ){
  153339. nMerge++;
  153340. }
  153341. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  153342. if( nMerge==1
  153343. && !isIgnoreEmpty
  153344. && !isFirst
  153345. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  153346. ){
  153347. pCsr->nDoclist = apSegment[0]->nDoclist;
  153348. if( fts3SegReaderIsPending(apSegment[0]) ){
  153349. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  153350. pCsr->aDoclist = pCsr->aBuffer;
  153351. }else{
  153352. pCsr->aDoclist = apSegment[0]->aDoclist;
  153353. }
  153354. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  153355. }else{
  153356. int nDoclist = 0; /* Size of doclist */
  153357. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  153358. /* The current term of the first nMerge entries in the array
  153359. ** of Fts3SegReader objects is the same. The doclists must be merged
  153360. ** and a single term returned with the merged doclist.
  153361. */
  153362. for(i=0; i<nMerge; i++){
  153363. fts3SegReaderFirstDocid(p, apSegment[i]);
  153364. }
  153365. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  153366. while( apSegment[0]->pOffsetList ){
  153367. int j; /* Number of segments that share a docid */
  153368. char *pList = 0;
  153369. int nList = 0;
  153370. int nByte;
  153371. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  153372. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  153373. j = 1;
  153374. while( j<nMerge
  153375. && apSegment[j]->pOffsetList
  153376. && apSegment[j]->iDocid==iDocid
  153377. ){
  153378. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  153379. j++;
  153380. }
  153381. if( isColFilter ){
  153382. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  153383. }
  153384. if( !isIgnoreEmpty || nList>0 ){
  153385. /* Calculate the 'docid' delta value to write into the merged
  153386. ** doclist. */
  153387. sqlite3_int64 iDelta;
  153388. if( p->bDescIdx && nDoclist>0 ){
  153389. iDelta = iPrev - iDocid;
  153390. }else{
  153391. iDelta = iDocid - iPrev;
  153392. }
  153393. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  153394. assert( nDoclist>0 || iDelta==iDocid );
  153395. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  153396. if( nDoclist+nByte>pCsr->nBuffer ){
  153397. char *aNew;
  153398. pCsr->nBuffer = (nDoclist+nByte)*2;
  153399. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  153400. if( !aNew ){
  153401. return SQLITE_NOMEM;
  153402. }
  153403. pCsr->aBuffer = aNew;
  153404. }
  153405. if( isFirst ){
  153406. char *a = &pCsr->aBuffer[nDoclist];
  153407. int nWrite;
  153408. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  153409. if( nWrite ){
  153410. iPrev = iDocid;
  153411. nDoclist += nWrite;
  153412. }
  153413. }else{
  153414. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  153415. iPrev = iDocid;
  153416. if( isRequirePos ){
  153417. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  153418. nDoclist += nList;
  153419. pCsr->aBuffer[nDoclist++] = '\0';
  153420. }
  153421. }
  153422. }
  153423. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  153424. }
  153425. if( nDoclist>0 ){
  153426. pCsr->aDoclist = pCsr->aBuffer;
  153427. pCsr->nDoclist = nDoclist;
  153428. rc = SQLITE_ROW;
  153429. }
  153430. }
  153431. pCsr->nAdvance = nMerge;
  153432. }while( rc==SQLITE_OK );
  153433. return rc;
  153434. }
  153435. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  153436. Fts3MultiSegReader *pCsr /* Cursor object */
  153437. ){
  153438. if( pCsr ){
  153439. int i;
  153440. for(i=0; i<pCsr->nSegment; i++){
  153441. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  153442. }
  153443. sqlite3_free(pCsr->apSegment);
  153444. sqlite3_free(pCsr->aBuffer);
  153445. pCsr->nSegment = 0;
  153446. pCsr->apSegment = 0;
  153447. pCsr->aBuffer = 0;
  153448. }
  153449. }
  153450. /*
  153451. ** Decode the "end_block" field, selected by column iCol of the SELECT
  153452. ** statement passed as the first argument.
  153453. **
  153454. ** The "end_block" field may contain either an integer, or a text field
  153455. ** containing the text representation of two non-negative integers separated
  153456. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  153457. ** to the integer value and *pnByte to zero before returning. In the second,
  153458. ** set *piEndBlock to the first value and *pnByte to the second.
  153459. */
  153460. static void fts3ReadEndBlockField(
  153461. sqlite3_stmt *pStmt,
  153462. int iCol,
  153463. i64 *piEndBlock,
  153464. i64 *pnByte
  153465. ){
  153466. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  153467. if( zText ){
  153468. int i;
  153469. int iMul = 1;
  153470. i64 iVal = 0;
  153471. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  153472. iVal = iVal*10 + (zText[i] - '0');
  153473. }
  153474. *piEndBlock = iVal;
  153475. while( zText[i]==' ' ) i++;
  153476. iVal = 0;
  153477. if( zText[i]=='-' ){
  153478. i++;
  153479. iMul = -1;
  153480. }
  153481. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  153482. iVal = iVal*10 + (zText[i] - '0');
  153483. }
  153484. *pnByte = (iVal * (i64)iMul);
  153485. }
  153486. }
  153487. /*
  153488. ** A segment of size nByte bytes has just been written to absolute level
  153489. ** iAbsLevel. Promote any segments that should be promoted as a result.
  153490. */
  153491. static int fts3PromoteSegments(
  153492. Fts3Table *p, /* FTS table handle */
  153493. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  153494. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  153495. ){
  153496. int rc = SQLITE_OK;
  153497. sqlite3_stmt *pRange;
  153498. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  153499. if( rc==SQLITE_OK ){
  153500. int bOk = 0;
  153501. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  153502. i64 nLimit = (nByte*3)/2;
  153503. /* Loop through all entries in the %_segdir table corresponding to
  153504. ** segments in this index on levels greater than iAbsLevel. If there is
  153505. ** at least one such segment, and it is possible to determine that all
  153506. ** such segments are smaller than nLimit bytes in size, they will be
  153507. ** promoted to level iAbsLevel. */
  153508. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  153509. sqlite3_bind_int64(pRange, 2, iLast);
  153510. while( SQLITE_ROW==sqlite3_step(pRange) ){
  153511. i64 nSize = 0, dummy;
  153512. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  153513. if( nSize<=0 || nSize>nLimit ){
  153514. /* If nSize==0, then the %_segdir.end_block field does not not
  153515. ** contain a size value. This happens if it was written by an
  153516. ** old version of FTS. In this case it is not possible to determine
  153517. ** the size of the segment, and so segment promotion does not
  153518. ** take place. */
  153519. bOk = 0;
  153520. break;
  153521. }
  153522. bOk = 1;
  153523. }
  153524. rc = sqlite3_reset(pRange);
  153525. if( bOk ){
  153526. int iIdx = 0;
  153527. sqlite3_stmt *pUpdate1 = 0;
  153528. sqlite3_stmt *pUpdate2 = 0;
  153529. if( rc==SQLITE_OK ){
  153530. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  153531. }
  153532. if( rc==SQLITE_OK ){
  153533. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  153534. }
  153535. if( rc==SQLITE_OK ){
  153536. /* Loop through all %_segdir entries for segments in this index with
  153537. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  153538. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  153539. ** oldest segment in the range, 1 for the next oldest, and so on.
  153540. **
  153541. ** In other words, move all segments being promoted to level -1,
  153542. ** setting the "idx" fields as appropriate to keep them in the same
  153543. ** order. The contents of level -1 (which is never used, except
  153544. ** transiently here), will be moved back to level iAbsLevel below. */
  153545. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  153546. while( SQLITE_ROW==sqlite3_step(pRange) ){
  153547. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  153548. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  153549. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  153550. sqlite3_step(pUpdate1);
  153551. rc = sqlite3_reset(pUpdate1);
  153552. if( rc!=SQLITE_OK ){
  153553. sqlite3_reset(pRange);
  153554. break;
  153555. }
  153556. }
  153557. }
  153558. if( rc==SQLITE_OK ){
  153559. rc = sqlite3_reset(pRange);
  153560. }
  153561. /* Move level -1 to level iAbsLevel */
  153562. if( rc==SQLITE_OK ){
  153563. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  153564. sqlite3_step(pUpdate2);
  153565. rc = sqlite3_reset(pUpdate2);
  153566. }
  153567. }
  153568. }
  153569. return rc;
  153570. }
  153571. /*
  153572. ** Merge all level iLevel segments in the database into a single
  153573. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  153574. ** single segment with a level equal to the numerically largest level
  153575. ** currently present in the database.
  153576. **
  153577. ** If this function is called with iLevel<0, but there is only one
  153578. ** segment in the database, SQLITE_DONE is returned immediately.
  153579. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  153580. ** an SQLite error code is returned.
  153581. */
  153582. static int fts3SegmentMerge(
  153583. Fts3Table *p,
  153584. int iLangid, /* Language id to merge */
  153585. int iIndex, /* Index in p->aIndex[] to merge */
  153586. int iLevel /* Level to merge */
  153587. ){
  153588. int rc; /* Return code */
  153589. int iIdx = 0; /* Index of new segment */
  153590. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  153591. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  153592. Fts3SegFilter filter; /* Segment term filter condition */
  153593. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  153594. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  153595. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  153596. assert( iLevel==FTS3_SEGCURSOR_ALL
  153597. || iLevel==FTS3_SEGCURSOR_PENDING
  153598. || iLevel>=0
  153599. );
  153600. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  153601. assert( iIndex>=0 && iIndex<p->nIndex );
  153602. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  153603. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  153604. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  153605. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  153606. if( rc!=SQLITE_OK ) goto finished;
  153607. }
  153608. if( iLevel==FTS3_SEGCURSOR_ALL ){
  153609. /* This call is to merge all segments in the database to a single
  153610. ** segment. The level of the new segment is equal to the numerically
  153611. ** greatest segment level currently present in the database for this
  153612. ** index. The idx of the new segment is always 0. */
  153613. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  153614. rc = SQLITE_DONE;
  153615. goto finished;
  153616. }
  153617. iNewLevel = iMaxLevel;
  153618. bIgnoreEmpty = 1;
  153619. }else{
  153620. /* This call is to merge all segments at level iLevel. find the next
  153621. ** available segment index at level iLevel+1. The call to
  153622. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  153623. ** a single iLevel+2 segment if necessary. */
  153624. assert( FTS3_SEGCURSOR_PENDING==-1 );
  153625. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  153626. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  153627. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  153628. }
  153629. if( rc!=SQLITE_OK ) goto finished;
  153630. assert( csr.nSegment>0 );
  153631. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  153632. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  153633. memset(&filter, 0, sizeof(Fts3SegFilter));
  153634. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  153635. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  153636. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  153637. while( SQLITE_OK==rc ){
  153638. rc = sqlite3Fts3SegReaderStep(p, &csr);
  153639. if( rc!=SQLITE_ROW ) break;
  153640. rc = fts3SegWriterAdd(p, &pWriter, 1,
  153641. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  153642. }
  153643. if( rc!=SQLITE_OK ) goto finished;
  153644. assert( pWriter || bIgnoreEmpty );
  153645. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  153646. rc = fts3DeleteSegdir(
  153647. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  153648. );
  153649. if( rc!=SQLITE_OK ) goto finished;
  153650. }
  153651. if( pWriter ){
  153652. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  153653. if( rc==SQLITE_OK ){
  153654. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  153655. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  153656. }
  153657. }
  153658. }
  153659. finished:
  153660. fts3SegWriterFree(pWriter);
  153661. sqlite3Fts3SegReaderFinish(&csr);
  153662. return rc;
  153663. }
  153664. /*
  153665. ** Flush the contents of pendingTerms to level 0 segments.
  153666. */
  153667. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  153668. int rc = SQLITE_OK;
  153669. int i;
  153670. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  153671. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  153672. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  153673. }
  153674. sqlite3Fts3PendingTermsClear(p);
  153675. /* Determine the auto-incr-merge setting if unknown. If enabled,
  153676. ** estimate the number of leaf blocks of content to be written
  153677. */
  153678. if( rc==SQLITE_OK && p->bHasStat
  153679. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  153680. ){
  153681. sqlite3_stmt *pStmt = 0;
  153682. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  153683. if( rc==SQLITE_OK ){
  153684. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  153685. rc = sqlite3_step(pStmt);
  153686. if( rc==SQLITE_ROW ){
  153687. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  153688. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  153689. }else if( rc==SQLITE_DONE ){
  153690. p->nAutoincrmerge = 0;
  153691. }
  153692. rc = sqlite3_reset(pStmt);
  153693. }
  153694. }
  153695. return rc;
  153696. }
  153697. /*
  153698. ** Encode N integers as varints into a blob.
  153699. */
  153700. static void fts3EncodeIntArray(
  153701. int N, /* The number of integers to encode */
  153702. u32 *a, /* The integer values */
  153703. char *zBuf, /* Write the BLOB here */
  153704. int *pNBuf /* Write number of bytes if zBuf[] used here */
  153705. ){
  153706. int i, j;
  153707. for(i=j=0; i<N; i++){
  153708. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  153709. }
  153710. *pNBuf = j;
  153711. }
  153712. /*
  153713. ** Decode a blob of varints into N integers
  153714. */
  153715. static void fts3DecodeIntArray(
  153716. int N, /* The number of integers to decode */
  153717. u32 *a, /* Write the integer values */
  153718. const char *zBuf, /* The BLOB containing the varints */
  153719. int nBuf /* size of the BLOB */
  153720. ){
  153721. int i, j;
  153722. UNUSED_PARAMETER(nBuf);
  153723. for(i=j=0; i<N; i++){
  153724. sqlite3_int64 x;
  153725. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  153726. assert(j<=nBuf);
  153727. a[i] = (u32)(x & 0xffffffff);
  153728. }
  153729. }
  153730. /*
  153731. ** Insert the sizes (in tokens) for each column of the document
  153732. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  153733. ** a blob of varints.
  153734. */
  153735. static void fts3InsertDocsize(
  153736. int *pRC, /* Result code */
  153737. Fts3Table *p, /* Table into which to insert */
  153738. u32 *aSz /* Sizes of each column, in tokens */
  153739. ){
  153740. char *pBlob; /* The BLOB encoding of the document size */
  153741. int nBlob; /* Number of bytes in the BLOB */
  153742. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  153743. int rc; /* Result code from subfunctions */
  153744. if( *pRC ) return;
  153745. pBlob = sqlite3_malloc( 10*p->nColumn );
  153746. if( pBlob==0 ){
  153747. *pRC = SQLITE_NOMEM;
  153748. return;
  153749. }
  153750. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  153751. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  153752. if( rc ){
  153753. sqlite3_free(pBlob);
  153754. *pRC = rc;
  153755. return;
  153756. }
  153757. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  153758. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  153759. sqlite3_step(pStmt);
  153760. *pRC = sqlite3_reset(pStmt);
  153761. }
  153762. /*
  153763. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  153764. ** where N is the number of user defined columns in the fts3 table plus
  153765. ** two. If nCol is the number of user defined columns, then values of the
  153766. ** varints are set as follows:
  153767. **
  153768. ** Varint 0: Total number of rows in the table.
  153769. **
  153770. ** Varint 1..nCol: For each column, the total number of tokens stored in
  153771. ** the column for all rows of the table.
  153772. **
  153773. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  153774. ** columns of all rows of the table.
  153775. **
  153776. */
  153777. static void fts3UpdateDocTotals(
  153778. int *pRC, /* The result code */
  153779. Fts3Table *p, /* Table being updated */
  153780. u32 *aSzIns, /* Size increases */
  153781. u32 *aSzDel, /* Size decreases */
  153782. int nChng /* Change in the number of documents */
  153783. ){
  153784. char *pBlob; /* Storage for BLOB written into %_stat */
  153785. int nBlob; /* Size of BLOB written into %_stat */
  153786. u32 *a; /* Array of integers that becomes the BLOB */
  153787. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  153788. int i; /* Loop counter */
  153789. int rc; /* Result code from subfunctions */
  153790. const int nStat = p->nColumn+2;
  153791. if( *pRC ) return;
  153792. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  153793. if( a==0 ){
  153794. *pRC = SQLITE_NOMEM;
  153795. return;
  153796. }
  153797. pBlob = (char*)&a[nStat];
  153798. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  153799. if( rc ){
  153800. sqlite3_free(a);
  153801. *pRC = rc;
  153802. return;
  153803. }
  153804. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  153805. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  153806. fts3DecodeIntArray(nStat, a,
  153807. sqlite3_column_blob(pStmt, 0),
  153808. sqlite3_column_bytes(pStmt, 0));
  153809. }else{
  153810. memset(a, 0, sizeof(u32)*(nStat) );
  153811. }
  153812. rc = sqlite3_reset(pStmt);
  153813. if( rc!=SQLITE_OK ){
  153814. sqlite3_free(a);
  153815. *pRC = rc;
  153816. return;
  153817. }
  153818. if( nChng<0 && a[0]<(u32)(-nChng) ){
  153819. a[0] = 0;
  153820. }else{
  153821. a[0] += nChng;
  153822. }
  153823. for(i=0; i<p->nColumn+1; i++){
  153824. u32 x = a[i+1];
  153825. if( x+aSzIns[i] < aSzDel[i] ){
  153826. x = 0;
  153827. }else{
  153828. x = x + aSzIns[i] - aSzDel[i];
  153829. }
  153830. a[i+1] = x;
  153831. }
  153832. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  153833. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  153834. if( rc ){
  153835. sqlite3_free(a);
  153836. *pRC = rc;
  153837. return;
  153838. }
  153839. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  153840. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  153841. sqlite3_step(pStmt);
  153842. *pRC = sqlite3_reset(pStmt);
  153843. sqlite3_bind_null(pStmt, 2);
  153844. sqlite3_free(a);
  153845. }
  153846. /*
  153847. ** Merge the entire database so that there is one segment for each
  153848. ** iIndex/iLangid combination.
  153849. */
  153850. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  153851. int bSeenDone = 0;
  153852. int rc;
  153853. sqlite3_stmt *pAllLangid = 0;
  153854. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  153855. if( rc==SQLITE_OK ){
  153856. int rc2;
  153857. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  153858. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  153859. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  153860. int i;
  153861. int iLangid = sqlite3_column_int(pAllLangid, 0);
  153862. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  153863. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  153864. if( rc==SQLITE_DONE ){
  153865. bSeenDone = 1;
  153866. rc = SQLITE_OK;
  153867. }
  153868. }
  153869. }
  153870. rc2 = sqlite3_reset(pAllLangid);
  153871. if( rc==SQLITE_OK ) rc = rc2;
  153872. }
  153873. sqlite3Fts3SegmentsClose(p);
  153874. sqlite3Fts3PendingTermsClear(p);
  153875. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  153876. }
  153877. /*
  153878. ** This function is called when the user executes the following statement:
  153879. **
  153880. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  153881. **
  153882. ** The entire FTS index is discarded and rebuilt. If the table is one
  153883. ** created using the content=xxx option, then the new index is based on
  153884. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  153885. ** on the contents of the %_content table.
  153886. */
  153887. static int fts3DoRebuild(Fts3Table *p){
  153888. int rc; /* Return Code */
  153889. rc = fts3DeleteAll(p, 0);
  153890. if( rc==SQLITE_OK ){
  153891. u32 *aSz = 0;
  153892. u32 *aSzIns = 0;
  153893. u32 *aSzDel = 0;
  153894. sqlite3_stmt *pStmt = 0;
  153895. int nEntry = 0;
  153896. /* Compose and prepare an SQL statement to loop through the content table */
  153897. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  153898. if( !zSql ){
  153899. rc = SQLITE_NOMEM;
  153900. }else{
  153901. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  153902. sqlite3_free(zSql);
  153903. }
  153904. if( rc==SQLITE_OK ){
  153905. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  153906. aSz = (u32 *)sqlite3_malloc(nByte);
  153907. if( aSz==0 ){
  153908. rc = SQLITE_NOMEM;
  153909. }else{
  153910. memset(aSz, 0, nByte);
  153911. aSzIns = &aSz[p->nColumn+1];
  153912. aSzDel = &aSzIns[p->nColumn+1];
  153913. }
  153914. }
  153915. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  153916. int iCol;
  153917. int iLangid = langidFromSelect(p, pStmt);
  153918. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  153919. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  153920. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  153921. if( p->abNotindexed[iCol]==0 ){
  153922. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  153923. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  153924. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  153925. }
  153926. }
  153927. if( p->bHasDocsize ){
  153928. fts3InsertDocsize(&rc, p, aSz);
  153929. }
  153930. if( rc!=SQLITE_OK ){
  153931. sqlite3_finalize(pStmt);
  153932. pStmt = 0;
  153933. }else{
  153934. nEntry++;
  153935. for(iCol=0; iCol<=p->nColumn; iCol++){
  153936. aSzIns[iCol] += aSz[iCol];
  153937. }
  153938. }
  153939. }
  153940. if( p->bFts4 ){
  153941. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  153942. }
  153943. sqlite3_free(aSz);
  153944. if( pStmt ){
  153945. int rc2 = sqlite3_finalize(pStmt);
  153946. if( rc==SQLITE_OK ){
  153947. rc = rc2;
  153948. }
  153949. }
  153950. }
  153951. return rc;
  153952. }
  153953. /*
  153954. ** This function opens a cursor used to read the input data for an
  153955. ** incremental merge operation. Specifically, it opens a cursor to scan
  153956. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  153957. ** level iAbsLevel.
  153958. */
  153959. static int fts3IncrmergeCsr(
  153960. Fts3Table *p, /* FTS3 table handle */
  153961. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  153962. int nSeg, /* Number of segments to merge */
  153963. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  153964. ){
  153965. int rc; /* Return Code */
  153966. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  153967. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  153968. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  153969. memset(pCsr, 0, sizeof(*pCsr));
  153970. nByte = sizeof(Fts3SegReader *) * nSeg;
  153971. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  153972. if( pCsr->apSegment==0 ){
  153973. rc = SQLITE_NOMEM;
  153974. }else{
  153975. memset(pCsr->apSegment, 0, nByte);
  153976. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  153977. }
  153978. if( rc==SQLITE_OK ){
  153979. int i;
  153980. int rc2;
  153981. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  153982. assert( pCsr->nSegment==0 );
  153983. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  153984. rc = sqlite3Fts3SegReaderNew(i, 0,
  153985. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  153986. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  153987. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  153988. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  153989. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  153990. &pCsr->apSegment[i]
  153991. );
  153992. pCsr->nSegment++;
  153993. }
  153994. rc2 = sqlite3_reset(pStmt);
  153995. if( rc==SQLITE_OK ) rc = rc2;
  153996. }
  153997. return rc;
  153998. }
  153999. typedef struct IncrmergeWriter IncrmergeWriter;
  154000. typedef struct NodeWriter NodeWriter;
  154001. typedef struct Blob Blob;
  154002. typedef struct NodeReader NodeReader;
  154003. /*
  154004. ** An instance of the following structure is used as a dynamic buffer
  154005. ** to build up nodes or other blobs of data in.
  154006. **
  154007. ** The function blobGrowBuffer() is used to extend the allocation.
  154008. */
  154009. struct Blob {
  154010. char *a; /* Pointer to allocation */
  154011. int n; /* Number of valid bytes of data in a[] */
  154012. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  154013. };
  154014. /*
  154015. ** This structure is used to build up buffers containing segment b-tree
  154016. ** nodes (blocks).
  154017. */
  154018. struct NodeWriter {
  154019. sqlite3_int64 iBlock; /* Current block id */
  154020. Blob key; /* Last key written to the current block */
  154021. Blob block; /* Current block image */
  154022. };
  154023. /*
  154024. ** An object of this type contains the state required to create or append
  154025. ** to an appendable b-tree segment.
  154026. */
  154027. struct IncrmergeWriter {
  154028. int nLeafEst; /* Space allocated for leaf blocks */
  154029. int nWork; /* Number of leaf pages flushed */
  154030. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  154031. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  154032. sqlite3_int64 iStart; /* Block number of first allocated block */
  154033. sqlite3_int64 iEnd; /* Block number of last allocated block */
  154034. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  154035. u8 bNoLeafData; /* If true, store 0 for segment size */
  154036. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  154037. };
  154038. /*
  154039. ** An object of the following type is used to read data from a single
  154040. ** FTS segment node. See the following functions:
  154041. **
  154042. ** nodeReaderInit()
  154043. ** nodeReaderNext()
  154044. ** nodeReaderRelease()
  154045. */
  154046. struct NodeReader {
  154047. const char *aNode;
  154048. int nNode;
  154049. int iOff; /* Current offset within aNode[] */
  154050. /* Output variables. Containing the current node entry. */
  154051. sqlite3_int64 iChild; /* Pointer to child node */
  154052. Blob term; /* Current term */
  154053. const char *aDoclist; /* Pointer to doclist */
  154054. int nDoclist; /* Size of doclist in bytes */
  154055. };
  154056. /*
  154057. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  154058. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  154059. ** bytes in size, extend (realloc) it to be so.
  154060. **
  154061. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  154062. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  154063. ** to reflect the new size of the pBlob->a[] buffer.
  154064. */
  154065. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  154066. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  154067. int nAlloc = nMin;
  154068. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  154069. if( a ){
  154070. pBlob->nAlloc = nAlloc;
  154071. pBlob->a = a;
  154072. }else{
  154073. *pRc = SQLITE_NOMEM;
  154074. }
  154075. }
  154076. }
  154077. /*
  154078. ** Attempt to advance the node-reader object passed as the first argument to
  154079. ** the next entry on the node.
  154080. **
  154081. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  154082. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  154083. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  154084. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  154085. ** variables for the new entry.
  154086. */
  154087. static int nodeReaderNext(NodeReader *p){
  154088. int bFirst = (p->term.n==0); /* True for first term on the node */
  154089. int nPrefix = 0; /* Bytes to copy from previous term */
  154090. int nSuffix = 0; /* Bytes to append to the prefix */
  154091. int rc = SQLITE_OK; /* Return code */
  154092. assert( p->aNode );
  154093. if( p->iChild && bFirst==0 ) p->iChild++;
  154094. if( p->iOff>=p->nNode ){
  154095. /* EOF */
  154096. p->aNode = 0;
  154097. }else{
  154098. if( bFirst==0 ){
  154099. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  154100. }
  154101. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  154102. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  154103. if( rc==SQLITE_OK ){
  154104. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  154105. p->term.n = nPrefix+nSuffix;
  154106. p->iOff += nSuffix;
  154107. if( p->iChild==0 ){
  154108. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  154109. p->aDoclist = &p->aNode[p->iOff];
  154110. p->iOff += p->nDoclist;
  154111. }
  154112. }
  154113. }
  154114. assert( p->iOff<=p->nNode );
  154115. return rc;
  154116. }
  154117. /*
  154118. ** Release all dynamic resources held by node-reader object *p.
  154119. */
  154120. static void nodeReaderRelease(NodeReader *p){
  154121. sqlite3_free(p->term.a);
  154122. }
  154123. /*
  154124. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  154125. **
  154126. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  154127. ** point to the first entry on the node (if any). Otherwise, an SQLite
  154128. ** error code is returned.
  154129. */
  154130. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  154131. memset(p, 0, sizeof(NodeReader));
  154132. p->aNode = aNode;
  154133. p->nNode = nNode;
  154134. /* Figure out if this is a leaf or an internal node. */
  154135. if( p->aNode[0] ){
  154136. /* An internal node. */
  154137. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  154138. }else{
  154139. p->iOff = 1;
  154140. }
  154141. return nodeReaderNext(p);
  154142. }
  154143. /*
  154144. ** This function is called while writing an FTS segment each time a leaf o
  154145. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  154146. ** to be greater than the largest key on the node just written, but smaller
  154147. ** than or equal to the first key that will be written to the next leaf
  154148. ** node.
  154149. **
  154150. ** The block id of the leaf node just written to disk may be found in
  154151. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  154152. */
  154153. static int fts3IncrmergePush(
  154154. Fts3Table *p, /* Fts3 table handle */
  154155. IncrmergeWriter *pWriter, /* Writer object */
  154156. const char *zTerm, /* Term to write to internal node */
  154157. int nTerm /* Bytes at zTerm */
  154158. ){
  154159. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  154160. int iLayer;
  154161. assert( nTerm>0 );
  154162. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  154163. sqlite3_int64 iNextPtr = 0;
  154164. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  154165. int rc = SQLITE_OK;
  154166. int nPrefix;
  154167. int nSuffix;
  154168. int nSpace;
  154169. /* Figure out how much space the key will consume if it is written to
  154170. ** the current node of layer iLayer. Due to the prefix compression,
  154171. ** the space required changes depending on which node the key is to
  154172. ** be added to. */
  154173. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  154174. nSuffix = nTerm - nPrefix;
  154175. nSpace = sqlite3Fts3VarintLen(nPrefix);
  154176. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  154177. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  154178. /* If the current node of layer iLayer contains zero keys, or if adding
  154179. ** the key to it will not cause it to grow to larger than nNodeSize
  154180. ** bytes in size, write the key here. */
  154181. Blob *pBlk = &pNode->block;
  154182. if( pBlk->n==0 ){
  154183. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  154184. if( rc==SQLITE_OK ){
  154185. pBlk->a[0] = (char)iLayer;
  154186. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  154187. }
  154188. }
  154189. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  154190. blobGrowBuffer(&pNode->key, nTerm, &rc);
  154191. if( rc==SQLITE_OK ){
  154192. if( pNode->key.n ){
  154193. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  154194. }
  154195. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  154196. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  154197. pBlk->n += nSuffix;
  154198. memcpy(pNode->key.a, zTerm, nTerm);
  154199. pNode->key.n = nTerm;
  154200. }
  154201. }else{
  154202. /* Otherwise, flush the current node of layer iLayer to disk.
  154203. ** Then allocate a new, empty sibling node. The key will be written
  154204. ** into the parent of this node. */
  154205. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  154206. assert( pNode->block.nAlloc>=p->nNodeSize );
  154207. pNode->block.a[0] = (char)iLayer;
  154208. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  154209. iNextPtr = pNode->iBlock;
  154210. pNode->iBlock++;
  154211. pNode->key.n = 0;
  154212. }
  154213. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  154214. iPtr = iNextPtr;
  154215. }
  154216. assert( 0 );
  154217. return 0;
  154218. }
  154219. /*
  154220. ** Append a term and (optionally) doclist to the FTS segment node currently
  154221. ** stored in blob *pNode. The node need not contain any terms, but the
  154222. ** header must be written before this function is called.
  154223. **
  154224. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  154225. ** followed by the left-hand-child varint for an internal node.
  154226. **
  154227. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  154228. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  154229. ** node, both aDoclist and nDoclist must be passed 0.
  154230. **
  154231. ** If the size of the value in blob pPrev is zero, then this is the first
  154232. ** term written to the node. Otherwise, pPrev contains a copy of the
  154233. ** previous term. Before this function returns, it is updated to contain a
  154234. ** copy of zTerm/nTerm.
  154235. **
  154236. ** It is assumed that the buffer associated with pNode is already large
  154237. ** enough to accommodate the new entry. The buffer associated with pPrev
  154238. ** is extended by this function if requrired.
  154239. **
  154240. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  154241. ** returned. Otherwise, SQLITE_OK.
  154242. */
  154243. static int fts3AppendToNode(
  154244. Blob *pNode, /* Current node image to append to */
  154245. Blob *pPrev, /* Buffer containing previous term written */
  154246. const char *zTerm, /* New term to write */
  154247. int nTerm, /* Size of zTerm in bytes */
  154248. const char *aDoclist, /* Doclist (or NULL) to write */
  154249. int nDoclist /* Size of aDoclist in bytes */
  154250. ){
  154251. int rc = SQLITE_OK; /* Return code */
  154252. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  154253. int nPrefix; /* Size of term prefix in bytes */
  154254. int nSuffix; /* Size of term suffix in bytes */
  154255. /* Node must have already been started. There must be a doclist for a
  154256. ** leaf node, and there must not be a doclist for an internal node. */
  154257. assert( pNode->n>0 );
  154258. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  154259. blobGrowBuffer(pPrev, nTerm, &rc);
  154260. if( rc!=SQLITE_OK ) return rc;
  154261. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  154262. nSuffix = nTerm - nPrefix;
  154263. memcpy(pPrev->a, zTerm, nTerm);
  154264. pPrev->n = nTerm;
  154265. if( bFirst==0 ){
  154266. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  154267. }
  154268. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  154269. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  154270. pNode->n += nSuffix;
  154271. if( aDoclist ){
  154272. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  154273. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  154274. pNode->n += nDoclist;
  154275. }
  154276. assert( pNode->n<=pNode->nAlloc );
  154277. return SQLITE_OK;
  154278. }
  154279. /*
  154280. ** Append the current term and doclist pointed to by cursor pCsr to the
  154281. ** appendable b-tree segment opened for writing by pWriter.
  154282. **
  154283. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  154284. */
  154285. static int fts3IncrmergeAppend(
  154286. Fts3Table *p, /* Fts3 table handle */
  154287. IncrmergeWriter *pWriter, /* Writer object */
  154288. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  154289. ){
  154290. const char *zTerm = pCsr->zTerm;
  154291. int nTerm = pCsr->nTerm;
  154292. const char *aDoclist = pCsr->aDoclist;
  154293. int nDoclist = pCsr->nDoclist;
  154294. int rc = SQLITE_OK; /* Return code */
  154295. int nSpace; /* Total space in bytes required on leaf */
  154296. int nPrefix; /* Size of prefix shared with previous term */
  154297. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  154298. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  154299. pLeaf = &pWriter->aNodeWriter[0];
  154300. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  154301. nSuffix = nTerm - nPrefix;
  154302. nSpace = sqlite3Fts3VarintLen(nPrefix);
  154303. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  154304. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  154305. /* If the current block is not empty, and if adding this term/doclist
  154306. ** to the current block would make it larger than Fts3Table.nNodeSize
  154307. ** bytes, write this block out to the database. */
  154308. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  154309. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  154310. pWriter->nWork++;
  154311. /* Add the current term to the parent node. The term added to the
  154312. ** parent must:
  154313. **
  154314. ** a) be greater than the largest term on the leaf node just written
  154315. ** to the database (still available in pLeaf->key), and
  154316. **
  154317. ** b) be less than or equal to the term about to be added to the new
  154318. ** leaf node (zTerm/nTerm).
  154319. **
  154320. ** In other words, it must be the prefix of zTerm 1 byte longer than
  154321. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  154322. */
  154323. if( rc==SQLITE_OK ){
  154324. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  154325. }
  154326. /* Advance to the next output block */
  154327. pLeaf->iBlock++;
  154328. pLeaf->key.n = 0;
  154329. pLeaf->block.n = 0;
  154330. nSuffix = nTerm;
  154331. nSpace = 1;
  154332. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  154333. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  154334. }
  154335. pWriter->nLeafData += nSpace;
  154336. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  154337. if( rc==SQLITE_OK ){
  154338. if( pLeaf->block.n==0 ){
  154339. pLeaf->block.n = 1;
  154340. pLeaf->block.a[0] = '\0';
  154341. }
  154342. rc = fts3AppendToNode(
  154343. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  154344. );
  154345. }
  154346. return rc;
  154347. }
  154348. /*
  154349. ** This function is called to release all dynamic resources held by the
  154350. ** merge-writer object pWriter, and if no error has occurred, to flush
  154351. ** all outstanding node buffers held by pWriter to disk.
  154352. **
  154353. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  154354. ** is made to write any data to disk. Instead, this function serves only
  154355. ** to release outstanding resources.
  154356. **
  154357. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  154358. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  154359. ** returning.
  154360. */
  154361. static void fts3IncrmergeRelease(
  154362. Fts3Table *p, /* FTS3 table handle */
  154363. IncrmergeWriter *pWriter, /* Merge-writer object */
  154364. int *pRc /* IN/OUT: Error code */
  154365. ){
  154366. int i; /* Used to iterate through non-root layers */
  154367. int iRoot; /* Index of root in pWriter->aNodeWriter */
  154368. NodeWriter *pRoot; /* NodeWriter for root node */
  154369. int rc = *pRc; /* Error code */
  154370. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  154371. ** root node. If the segment fits entirely on a single leaf node, iRoot
  154372. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  154373. ** will be 1. And so on. */
  154374. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  154375. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  154376. if( pNode->block.n>0 ) break;
  154377. assert( *pRc || pNode->block.nAlloc==0 );
  154378. assert( *pRc || pNode->key.nAlloc==0 );
  154379. sqlite3_free(pNode->block.a);
  154380. sqlite3_free(pNode->key.a);
  154381. }
  154382. /* Empty output segment. This is a no-op. */
  154383. if( iRoot<0 ) return;
  154384. /* The entire output segment fits on a single node. Normally, this means
  154385. ** the node would be stored as a blob in the "root" column of the %_segdir
  154386. ** table. However, this is not permitted in this case. The problem is that
  154387. ** space has already been reserved in the %_segments table, and so the
  154388. ** start_block and end_block fields of the %_segdir table must be populated.
  154389. ** And, by design or by accident, released versions of FTS cannot handle
  154390. ** segments that fit entirely on the root node with start_block!=0.
  154391. **
  154392. ** Instead, create a synthetic root node that contains nothing but a
  154393. ** pointer to the single content node. So that the segment consists of a
  154394. ** single leaf and a single interior (root) node.
  154395. **
  154396. ** Todo: Better might be to defer allocating space in the %_segments
  154397. ** table until we are sure it is needed.
  154398. */
  154399. if( iRoot==0 ){
  154400. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  154401. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  154402. if( rc==SQLITE_OK ){
  154403. pBlock->a[0] = 0x01;
  154404. pBlock->n = 1 + sqlite3Fts3PutVarint(
  154405. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  154406. );
  154407. }
  154408. iRoot = 1;
  154409. }
  154410. pRoot = &pWriter->aNodeWriter[iRoot];
  154411. /* Flush all currently outstanding nodes to disk. */
  154412. for(i=0; i<iRoot; i++){
  154413. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  154414. if( pNode->block.n>0 && rc==SQLITE_OK ){
  154415. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  154416. }
  154417. sqlite3_free(pNode->block.a);
  154418. sqlite3_free(pNode->key.a);
  154419. }
  154420. /* Write the %_segdir record. */
  154421. if( rc==SQLITE_OK ){
  154422. rc = fts3WriteSegdir(p,
  154423. pWriter->iAbsLevel+1, /* level */
  154424. pWriter->iIdx, /* idx */
  154425. pWriter->iStart, /* start_block */
  154426. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  154427. pWriter->iEnd, /* end_block */
  154428. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  154429. pRoot->block.a, pRoot->block.n /* root */
  154430. );
  154431. }
  154432. sqlite3_free(pRoot->block.a);
  154433. sqlite3_free(pRoot->key.a);
  154434. *pRc = rc;
  154435. }
  154436. /*
  154437. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  154438. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  154439. ** the other, it is considered to be smaller than the other.
  154440. **
  154441. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  154442. ** if it is greater.
  154443. */
  154444. static int fts3TermCmp(
  154445. const char *zLhs, int nLhs, /* LHS of comparison */
  154446. const char *zRhs, int nRhs /* RHS of comparison */
  154447. ){
  154448. int nCmp = MIN(nLhs, nRhs);
  154449. int res;
  154450. res = memcmp(zLhs, zRhs, nCmp);
  154451. if( res==0 ) res = nLhs - nRhs;
  154452. return res;
  154453. }
  154454. /*
  154455. ** Query to see if the entry in the %_segments table with blockid iEnd is
  154456. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  154457. ** returning. Otherwise, set *pbRes to 0.
  154458. **
  154459. ** Or, if an error occurs while querying the database, return an SQLite
  154460. ** error code. The final value of *pbRes is undefined in this case.
  154461. **
  154462. ** This is used to test if a segment is an "appendable" segment. If it
  154463. ** is, then a NULL entry has been inserted into the %_segments table
  154464. ** with blockid %_segdir.end_block.
  154465. */
  154466. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  154467. int bRes = 0; /* Result to set *pbRes to */
  154468. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  154469. int rc; /* Return code */
  154470. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  154471. if( rc==SQLITE_OK ){
  154472. sqlite3_bind_int64(pCheck, 1, iEnd);
  154473. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  154474. rc = sqlite3_reset(pCheck);
  154475. }
  154476. *pbRes = bRes;
  154477. return rc;
  154478. }
  154479. /*
  154480. ** This function is called when initializing an incremental-merge operation.
  154481. ** It checks if the existing segment with index value iIdx at absolute level
  154482. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  154483. ** merge-writer object *pWriter is initialized to write to it.
  154484. **
  154485. ** An existing segment can be appended to by an incremental merge if:
  154486. **
  154487. ** * It was initially created as an appendable segment (with all required
  154488. ** space pre-allocated), and
  154489. **
  154490. ** * The first key read from the input (arguments zKey and nKey) is
  154491. ** greater than the largest key currently stored in the potential
  154492. ** output segment.
  154493. */
  154494. static int fts3IncrmergeLoad(
  154495. Fts3Table *p, /* Fts3 table handle */
  154496. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  154497. int iIdx, /* Index of candidate output segment */
  154498. const char *zKey, /* First key to write */
  154499. int nKey, /* Number of bytes in nKey */
  154500. IncrmergeWriter *pWriter /* Populate this object */
  154501. ){
  154502. int rc; /* Return code */
  154503. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  154504. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  154505. if( rc==SQLITE_OK ){
  154506. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  154507. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  154508. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  154509. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  154510. int nRoot = 0; /* Size of aRoot[] in bytes */
  154511. int rc2; /* Return code from sqlite3_reset() */
  154512. int bAppendable = 0; /* Set to true if segment is appendable */
  154513. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  154514. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  154515. sqlite3_bind_int(pSelect, 2, iIdx);
  154516. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  154517. iStart = sqlite3_column_int64(pSelect, 1);
  154518. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  154519. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  154520. if( pWriter->nLeafData<0 ){
  154521. pWriter->nLeafData = pWriter->nLeafData * -1;
  154522. }
  154523. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  154524. nRoot = sqlite3_column_bytes(pSelect, 4);
  154525. aRoot = sqlite3_column_blob(pSelect, 4);
  154526. }else{
  154527. return sqlite3_reset(pSelect);
  154528. }
  154529. /* Check for the zero-length marker in the %_segments table */
  154530. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  154531. /* Check that zKey/nKey is larger than the largest key the candidate */
  154532. if( rc==SQLITE_OK && bAppendable ){
  154533. char *aLeaf = 0;
  154534. int nLeaf = 0;
  154535. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  154536. if( rc==SQLITE_OK ){
  154537. NodeReader reader;
  154538. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  154539. rc==SQLITE_OK && reader.aNode;
  154540. rc = nodeReaderNext(&reader)
  154541. ){
  154542. assert( reader.aNode );
  154543. }
  154544. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  154545. bAppendable = 0;
  154546. }
  154547. nodeReaderRelease(&reader);
  154548. }
  154549. sqlite3_free(aLeaf);
  154550. }
  154551. if( rc==SQLITE_OK && bAppendable ){
  154552. /* It is possible to append to this segment. Set up the IncrmergeWriter
  154553. ** object to do so. */
  154554. int i;
  154555. int nHeight = (int)aRoot[0];
  154556. NodeWriter *pNode;
  154557. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  154558. pWriter->iStart = iStart;
  154559. pWriter->iEnd = iEnd;
  154560. pWriter->iAbsLevel = iAbsLevel;
  154561. pWriter->iIdx = iIdx;
  154562. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  154563. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  154564. }
  154565. pNode = &pWriter->aNodeWriter[nHeight];
  154566. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  154567. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  154568. if( rc==SQLITE_OK ){
  154569. memcpy(pNode->block.a, aRoot, nRoot);
  154570. pNode->block.n = nRoot;
  154571. }
  154572. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  154573. NodeReader reader;
  154574. pNode = &pWriter->aNodeWriter[i];
  154575. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  154576. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  154577. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  154578. if( rc==SQLITE_OK ){
  154579. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  154580. pNode->key.n = reader.term.n;
  154581. if( i>0 ){
  154582. char *aBlock = 0;
  154583. int nBlock = 0;
  154584. pNode = &pWriter->aNodeWriter[i-1];
  154585. pNode->iBlock = reader.iChild;
  154586. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  154587. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  154588. if( rc==SQLITE_OK ){
  154589. memcpy(pNode->block.a, aBlock, nBlock);
  154590. pNode->block.n = nBlock;
  154591. }
  154592. sqlite3_free(aBlock);
  154593. }
  154594. }
  154595. nodeReaderRelease(&reader);
  154596. }
  154597. }
  154598. rc2 = sqlite3_reset(pSelect);
  154599. if( rc==SQLITE_OK ) rc = rc2;
  154600. }
  154601. return rc;
  154602. }
  154603. /*
  154604. ** Determine the largest segment index value that exists within absolute
  154605. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  154606. ** one before returning SQLITE_OK. Or, if there are no segments at all
  154607. ** within level iAbsLevel, set *piIdx to zero.
  154608. **
  154609. ** If an error occurs, return an SQLite error code. The final value of
  154610. ** *piIdx is undefined in this case.
  154611. */
  154612. static int fts3IncrmergeOutputIdx(
  154613. Fts3Table *p, /* FTS Table handle */
  154614. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  154615. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  154616. ){
  154617. int rc;
  154618. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  154619. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  154620. if( rc==SQLITE_OK ){
  154621. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  154622. sqlite3_step(pOutputIdx);
  154623. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  154624. rc = sqlite3_reset(pOutputIdx);
  154625. }
  154626. return rc;
  154627. }
  154628. /*
  154629. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  154630. ** with idx value iIdx.
  154631. **
  154632. ** In the %_segdir table, a segment is defined by the values in three
  154633. ** columns:
  154634. **
  154635. ** start_block
  154636. ** leaves_end_block
  154637. ** end_block
  154638. **
  154639. ** When an appendable segment is allocated, it is estimated that the
  154640. ** maximum number of leaf blocks that may be required is the sum of the
  154641. ** number of leaf blocks consumed by the input segments, plus the number
  154642. ** of input segments, multiplied by two. This value is stored in stack
  154643. ** variable nLeafEst.
  154644. **
  154645. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  154646. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  154647. ** array of leaf nodes starts at the first block allocated. The array
  154648. ** of interior nodes that are parents of the leaf nodes start at block
  154649. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  154650. **
  154651. ** In the actual code below, the value "16" is replaced with the
  154652. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  154653. */
  154654. static int fts3IncrmergeWriter(
  154655. Fts3Table *p, /* Fts3 table handle */
  154656. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  154657. int iIdx, /* Index of new output segment */
  154658. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  154659. IncrmergeWriter *pWriter /* Populate this object */
  154660. ){
  154661. int rc; /* Return Code */
  154662. int i; /* Iterator variable */
  154663. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  154664. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  154665. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  154666. /* Calculate nLeafEst. */
  154667. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  154668. if( rc==SQLITE_OK ){
  154669. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  154670. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  154671. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  154672. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  154673. }
  154674. rc = sqlite3_reset(pLeafEst);
  154675. }
  154676. if( rc!=SQLITE_OK ) return rc;
  154677. /* Calculate the first block to use in the output segment */
  154678. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  154679. if( rc==SQLITE_OK ){
  154680. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  154681. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  154682. pWriter->iEnd = pWriter->iStart - 1;
  154683. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  154684. }
  154685. rc = sqlite3_reset(pFirstBlock);
  154686. }
  154687. if( rc!=SQLITE_OK ) return rc;
  154688. /* Insert the marker in the %_segments table to make sure nobody tries
  154689. ** to steal the space just allocated. This is also used to identify
  154690. ** appendable segments. */
  154691. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  154692. if( rc!=SQLITE_OK ) return rc;
  154693. pWriter->iAbsLevel = iAbsLevel;
  154694. pWriter->nLeafEst = nLeafEst;
  154695. pWriter->iIdx = iIdx;
  154696. /* Set up the array of NodeWriter objects */
  154697. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  154698. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  154699. }
  154700. return SQLITE_OK;
  154701. }
  154702. /*
  154703. ** Remove an entry from the %_segdir table. This involves running the
  154704. ** following two statements:
  154705. **
  154706. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  154707. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  154708. **
  154709. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  154710. ** statement ensures that the remaining segments have contiguously allocated
  154711. ** idx values.
  154712. */
  154713. static int fts3RemoveSegdirEntry(
  154714. Fts3Table *p, /* FTS3 table handle */
  154715. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  154716. int iIdx /* Index of %_segdir entry to delete */
  154717. ){
  154718. int rc; /* Return code */
  154719. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  154720. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  154721. if( rc==SQLITE_OK ){
  154722. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  154723. sqlite3_bind_int(pDelete, 2, iIdx);
  154724. sqlite3_step(pDelete);
  154725. rc = sqlite3_reset(pDelete);
  154726. }
  154727. return rc;
  154728. }
  154729. /*
  154730. ** One or more segments have just been removed from absolute level iAbsLevel.
  154731. ** Update the 'idx' values of the remaining segments in the level so that
  154732. ** the idx values are a contiguous sequence starting from 0.
  154733. */
  154734. static int fts3RepackSegdirLevel(
  154735. Fts3Table *p, /* FTS3 table handle */
  154736. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  154737. ){
  154738. int rc; /* Return code */
  154739. int *aIdx = 0; /* Array of remaining idx values */
  154740. int nIdx = 0; /* Valid entries in aIdx[] */
  154741. int nAlloc = 0; /* Allocated size of aIdx[] */
  154742. int i; /* Iterator variable */
  154743. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  154744. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  154745. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  154746. if( rc==SQLITE_OK ){
  154747. int rc2;
  154748. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  154749. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  154750. if( nIdx>=nAlloc ){
  154751. int *aNew;
  154752. nAlloc += 16;
  154753. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  154754. if( !aNew ){
  154755. rc = SQLITE_NOMEM;
  154756. break;
  154757. }
  154758. aIdx = aNew;
  154759. }
  154760. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  154761. }
  154762. rc2 = sqlite3_reset(pSelect);
  154763. if( rc==SQLITE_OK ) rc = rc2;
  154764. }
  154765. if( rc==SQLITE_OK ){
  154766. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  154767. }
  154768. if( rc==SQLITE_OK ){
  154769. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  154770. }
  154771. assert( p->bIgnoreSavepoint==0 );
  154772. p->bIgnoreSavepoint = 1;
  154773. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  154774. if( aIdx[i]!=i ){
  154775. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  154776. sqlite3_bind_int(pUpdate, 1, i);
  154777. sqlite3_step(pUpdate);
  154778. rc = sqlite3_reset(pUpdate);
  154779. }
  154780. }
  154781. p->bIgnoreSavepoint = 0;
  154782. sqlite3_free(aIdx);
  154783. return rc;
  154784. }
  154785. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  154786. pNode->a[0] = (char)iHeight;
  154787. if( iChild ){
  154788. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  154789. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  154790. }else{
  154791. assert( pNode->nAlloc>=1 );
  154792. pNode->n = 1;
  154793. }
  154794. }
  154795. /*
  154796. ** The first two arguments are a pointer to and the size of a segment b-tree
  154797. ** node. The node may be a leaf or an internal node.
  154798. **
  154799. ** This function creates a new node image in blob object *pNew by copying
  154800. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  154801. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  154802. */
  154803. static int fts3TruncateNode(
  154804. const char *aNode, /* Current node image */
  154805. int nNode, /* Size of aNode in bytes */
  154806. Blob *pNew, /* OUT: Write new node image here */
  154807. const char *zTerm, /* Omit all terms smaller than this */
  154808. int nTerm, /* Size of zTerm in bytes */
  154809. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  154810. ){
  154811. NodeReader reader; /* Reader object */
  154812. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  154813. int rc = SQLITE_OK; /* Return code */
  154814. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  154815. /* Allocate required output space */
  154816. blobGrowBuffer(pNew, nNode, &rc);
  154817. if( rc!=SQLITE_OK ) return rc;
  154818. pNew->n = 0;
  154819. /* Populate new node buffer */
  154820. for(rc = nodeReaderInit(&reader, aNode, nNode);
  154821. rc==SQLITE_OK && reader.aNode;
  154822. rc = nodeReaderNext(&reader)
  154823. ){
  154824. if( pNew->n==0 ){
  154825. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  154826. if( res<0 || (bLeaf==0 && res==0) ) continue;
  154827. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  154828. *piBlock = reader.iChild;
  154829. }
  154830. rc = fts3AppendToNode(
  154831. pNew, &prev, reader.term.a, reader.term.n,
  154832. reader.aDoclist, reader.nDoclist
  154833. );
  154834. if( rc!=SQLITE_OK ) break;
  154835. }
  154836. if( pNew->n==0 ){
  154837. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  154838. *piBlock = reader.iChild;
  154839. }
  154840. assert( pNew->n<=pNew->nAlloc );
  154841. nodeReaderRelease(&reader);
  154842. sqlite3_free(prev.a);
  154843. return rc;
  154844. }
  154845. /*
  154846. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  154847. ** level iAbsLevel. This may involve deleting entries from the %_segments
  154848. ** table, and modifying existing entries in both the %_segments and %_segdir
  154849. ** tables.
  154850. **
  154851. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  154852. ** SQLite error code otherwise.
  154853. */
  154854. static int fts3TruncateSegment(
  154855. Fts3Table *p, /* FTS3 table handle */
  154856. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  154857. int iIdx, /* Index within level of segment to modify */
  154858. const char *zTerm, /* Remove terms smaller than this */
  154859. int nTerm /* Number of bytes in buffer zTerm */
  154860. ){
  154861. int rc = SQLITE_OK; /* Return code */
  154862. Blob root = {0,0,0}; /* New root page image */
  154863. Blob block = {0,0,0}; /* Buffer used for any other block */
  154864. sqlite3_int64 iBlock = 0; /* Block id */
  154865. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  154866. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  154867. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  154868. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  154869. if( rc==SQLITE_OK ){
  154870. int rc2; /* sqlite3_reset() return code */
  154871. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  154872. sqlite3_bind_int(pFetch, 2, iIdx);
  154873. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  154874. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  154875. int nRoot = sqlite3_column_bytes(pFetch, 4);
  154876. iOldStart = sqlite3_column_int64(pFetch, 1);
  154877. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  154878. }
  154879. rc2 = sqlite3_reset(pFetch);
  154880. if( rc==SQLITE_OK ) rc = rc2;
  154881. }
  154882. while( rc==SQLITE_OK && iBlock ){
  154883. char *aBlock = 0;
  154884. int nBlock = 0;
  154885. iNewStart = iBlock;
  154886. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  154887. if( rc==SQLITE_OK ){
  154888. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  154889. }
  154890. if( rc==SQLITE_OK ){
  154891. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  154892. }
  154893. sqlite3_free(aBlock);
  154894. }
  154895. /* Variable iNewStart now contains the first valid leaf node. */
  154896. if( rc==SQLITE_OK && iNewStart ){
  154897. sqlite3_stmt *pDel = 0;
  154898. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  154899. if( rc==SQLITE_OK ){
  154900. sqlite3_bind_int64(pDel, 1, iOldStart);
  154901. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  154902. sqlite3_step(pDel);
  154903. rc = sqlite3_reset(pDel);
  154904. }
  154905. }
  154906. if( rc==SQLITE_OK ){
  154907. sqlite3_stmt *pChomp = 0;
  154908. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  154909. if( rc==SQLITE_OK ){
  154910. sqlite3_bind_int64(pChomp, 1, iNewStart);
  154911. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  154912. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  154913. sqlite3_bind_int(pChomp, 4, iIdx);
  154914. sqlite3_step(pChomp);
  154915. rc = sqlite3_reset(pChomp);
  154916. sqlite3_bind_null(pChomp, 2);
  154917. }
  154918. }
  154919. sqlite3_free(root.a);
  154920. sqlite3_free(block.a);
  154921. return rc;
  154922. }
  154923. /*
  154924. ** This function is called after an incrmental-merge operation has run to
  154925. ** merge (or partially merge) two or more segments from absolute level
  154926. ** iAbsLevel.
  154927. **
  154928. ** Each input segment is either removed from the db completely (if all of
  154929. ** its data was copied to the output segment by the incrmerge operation)
  154930. ** or modified in place so that it no longer contains those entries that
  154931. ** have been duplicated in the output segment.
  154932. */
  154933. static int fts3IncrmergeChomp(
  154934. Fts3Table *p, /* FTS table handle */
  154935. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  154936. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  154937. int *pnRem /* Number of segments not deleted */
  154938. ){
  154939. int i;
  154940. int nRem = 0;
  154941. int rc = SQLITE_OK;
  154942. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  154943. Fts3SegReader *pSeg = 0;
  154944. int j;
  154945. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  154946. ** somewhere in the pCsr->apSegment[] array. */
  154947. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  154948. pSeg = pCsr->apSegment[j];
  154949. if( pSeg->iIdx==i ) break;
  154950. }
  154951. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  154952. if( pSeg->aNode==0 ){
  154953. /* Seg-reader is at EOF. Remove the entire input segment. */
  154954. rc = fts3DeleteSegment(p, pSeg);
  154955. if( rc==SQLITE_OK ){
  154956. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  154957. }
  154958. *pnRem = 0;
  154959. }else{
  154960. /* The incremental merge did not copy all the data from this
  154961. ** segment to the upper level. The segment is modified in place
  154962. ** so that it contains no keys smaller than zTerm/nTerm. */
  154963. const char *zTerm = pSeg->zTerm;
  154964. int nTerm = pSeg->nTerm;
  154965. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  154966. nRem++;
  154967. }
  154968. }
  154969. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  154970. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  154971. }
  154972. *pnRem = nRem;
  154973. return rc;
  154974. }
  154975. /*
  154976. ** Store an incr-merge hint in the database.
  154977. */
  154978. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  154979. sqlite3_stmt *pReplace = 0;
  154980. int rc; /* Return code */
  154981. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  154982. if( rc==SQLITE_OK ){
  154983. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  154984. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  154985. sqlite3_step(pReplace);
  154986. rc = sqlite3_reset(pReplace);
  154987. sqlite3_bind_null(pReplace, 2);
  154988. }
  154989. return rc;
  154990. }
  154991. /*
  154992. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  154993. ** exists, is stored in the rowid==1 row of the %_stat table.
  154994. **
  154995. ** If successful, populate blob *pHint with the value read from the %_stat
  154996. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  154997. ** SQLite error code.
  154998. */
  154999. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  155000. sqlite3_stmt *pSelect = 0;
  155001. int rc;
  155002. pHint->n = 0;
  155003. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  155004. if( rc==SQLITE_OK ){
  155005. int rc2;
  155006. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  155007. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  155008. const char *aHint = sqlite3_column_blob(pSelect, 0);
  155009. int nHint = sqlite3_column_bytes(pSelect, 0);
  155010. if( aHint ){
  155011. blobGrowBuffer(pHint, nHint, &rc);
  155012. if( rc==SQLITE_OK ){
  155013. memcpy(pHint->a, aHint, nHint);
  155014. pHint->n = nHint;
  155015. }
  155016. }
  155017. }
  155018. rc2 = sqlite3_reset(pSelect);
  155019. if( rc==SQLITE_OK ) rc = rc2;
  155020. }
  155021. return rc;
  155022. }
  155023. /*
  155024. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  155025. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  155026. ** consists of two varints, the absolute level number of the input segments
  155027. ** and the number of input segments.
  155028. **
  155029. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  155030. ** set *pRc to an SQLite error code before returning.
  155031. */
  155032. static void fts3IncrmergeHintPush(
  155033. Blob *pHint, /* Hint blob to append to */
  155034. i64 iAbsLevel, /* First varint to store in hint */
  155035. int nInput, /* Second varint to store in hint */
  155036. int *pRc /* IN/OUT: Error code */
  155037. ){
  155038. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  155039. if( *pRc==SQLITE_OK ){
  155040. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  155041. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  155042. }
  155043. }
  155044. /*
  155045. ** Read the last entry (most recently pushed) from the hint blob *pHint
  155046. ** and then remove the entry. Write the two values read to *piAbsLevel and
  155047. ** *pnInput before returning.
  155048. **
  155049. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  155050. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  155051. */
  155052. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  155053. const int nHint = pHint->n;
  155054. int i;
  155055. i = pHint->n-2;
  155056. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  155057. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  155058. pHint->n = i;
  155059. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  155060. i += fts3GetVarint32(&pHint->a[i], pnInput);
  155061. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  155062. return SQLITE_OK;
  155063. }
  155064. /*
  155065. ** Attempt an incremental merge that writes nMerge leaf blocks.
  155066. **
  155067. ** Incremental merges happen nMin segments at a time. The segments
  155068. ** to be merged are the nMin oldest segments (the ones with the smallest
  155069. ** values for the _segdir.idx field) in the highest level that contains
  155070. ** at least nMin segments. Multiple merges might occur in an attempt to
  155071. ** write the quota of nMerge leaf blocks.
  155072. */
  155073. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  155074. int rc; /* Return code */
  155075. int nRem = nMerge; /* Number of leaf pages yet to be written */
  155076. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  155077. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  155078. IncrmergeWriter *pWriter; /* Writer object */
  155079. int nSeg = 0; /* Number of input segments */
  155080. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  155081. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  155082. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  155083. /* Allocate space for the cursor, filter and writer objects */
  155084. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  155085. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  155086. if( !pWriter ) return SQLITE_NOMEM;
  155087. pFilter = (Fts3SegFilter *)&pWriter[1];
  155088. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  155089. rc = fts3IncrmergeHintLoad(p, &hint);
  155090. while( rc==SQLITE_OK && nRem>0 ){
  155091. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  155092. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  155093. int bUseHint = 0; /* True if attempting to append */
  155094. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  155095. /* Search the %_segdir table for the absolute level with the smallest
  155096. ** relative level number that contains at least nMin segments, if any.
  155097. ** If one is found, set iAbsLevel to the absolute level number and
  155098. ** nSeg to nMin. If no level with at least nMin segments can be found,
  155099. ** set nSeg to -1.
  155100. */
  155101. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  155102. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  155103. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  155104. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  155105. nSeg = sqlite3_column_int(pFindLevel, 1);
  155106. assert( nSeg>=2 );
  155107. }else{
  155108. nSeg = -1;
  155109. }
  155110. rc = sqlite3_reset(pFindLevel);
  155111. /* If the hint read from the %_stat table is not empty, check if the
  155112. ** last entry in it specifies a relative level smaller than or equal
  155113. ** to the level identified by the block above (if any). If so, this
  155114. ** iteration of the loop will work on merging at the hinted level.
  155115. */
  155116. if( rc==SQLITE_OK && hint.n ){
  155117. int nHint = hint.n;
  155118. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  155119. int nHintSeg = 0; /* Hint number of segments */
  155120. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  155121. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  155122. iAbsLevel = iHintAbsLevel;
  155123. nSeg = nHintSeg;
  155124. bUseHint = 1;
  155125. bDirtyHint = 1;
  155126. }else{
  155127. /* This undoes the effect of the HintPop() above - so that no entry
  155128. ** is removed from the hint blob. */
  155129. hint.n = nHint;
  155130. }
  155131. }
  155132. /* If nSeg is less that zero, then there is no level with at least
  155133. ** nMin segments and no hint in the %_stat table. No work to do.
  155134. ** Exit early in this case. */
  155135. if( nSeg<0 ) break;
  155136. /* Open a cursor to iterate through the contents of the oldest nSeg
  155137. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  155138. ** the 'hint' parameters, it is possible that there are less than nSeg
  155139. ** segments available in level iAbsLevel. In this case, no work is
  155140. ** done on iAbsLevel - fall through to the next iteration of the loop
  155141. ** to start work on some other level. */
  155142. memset(pWriter, 0, nAlloc);
  155143. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  155144. if( rc==SQLITE_OK ){
  155145. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  155146. assert( bUseHint==1 || bUseHint==0 );
  155147. if( iIdx==0 || (bUseHint && iIdx==1) ){
  155148. int bIgnore = 0;
  155149. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  155150. if( bIgnore ){
  155151. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  155152. }
  155153. }
  155154. }
  155155. if( rc==SQLITE_OK ){
  155156. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  155157. }
  155158. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  155159. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  155160. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  155161. ){
  155162. if( bUseHint && iIdx>0 ){
  155163. const char *zKey = pCsr->zTerm;
  155164. int nKey = pCsr->nTerm;
  155165. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  155166. }else{
  155167. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  155168. }
  155169. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  155170. fts3LogMerge(nSeg, iAbsLevel);
  155171. do {
  155172. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  155173. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  155174. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  155175. }while( rc==SQLITE_ROW );
  155176. /* Update or delete the input segments */
  155177. if( rc==SQLITE_OK ){
  155178. nRem -= (1 + pWriter->nWork);
  155179. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  155180. if( nSeg!=0 ){
  155181. bDirtyHint = 1;
  155182. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  155183. }
  155184. }
  155185. }
  155186. if( nSeg!=0 ){
  155187. pWriter->nLeafData = pWriter->nLeafData * -1;
  155188. }
  155189. fts3IncrmergeRelease(p, pWriter, &rc);
  155190. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  155191. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  155192. }
  155193. }
  155194. sqlite3Fts3SegReaderFinish(pCsr);
  155195. }
  155196. /* Write the hint values into the %_stat table for the next incr-merger */
  155197. if( bDirtyHint && rc==SQLITE_OK ){
  155198. rc = fts3IncrmergeHintStore(p, &hint);
  155199. }
  155200. sqlite3_free(pWriter);
  155201. sqlite3_free(hint.a);
  155202. return rc;
  155203. }
  155204. /*
  155205. ** Convert the text beginning at *pz into an integer and return
  155206. ** its value. Advance *pz to point to the first character past
  155207. ** the integer.
  155208. **
  155209. ** This function used for parameters to merge= and incrmerge=
  155210. ** commands.
  155211. */
  155212. static int fts3Getint(const char **pz){
  155213. const char *z = *pz;
  155214. int i = 0;
  155215. while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
  155216. *pz = z;
  155217. return i;
  155218. }
  155219. /*
  155220. ** Process statements of the form:
  155221. **
  155222. ** INSERT INTO table(table) VALUES('merge=A,B');
  155223. **
  155224. ** A and B are integers that decode to be the number of leaf pages
  155225. ** written for the merge, and the minimum number of segments on a level
  155226. ** before it will be selected for a merge, respectively.
  155227. */
  155228. static int fts3DoIncrmerge(
  155229. Fts3Table *p, /* FTS3 table handle */
  155230. const char *zParam /* Nul-terminated string containing "A,B" */
  155231. ){
  155232. int rc;
  155233. int nMin = (FTS3_MERGE_COUNT / 2);
  155234. int nMerge = 0;
  155235. const char *z = zParam;
  155236. /* Read the first integer value */
  155237. nMerge = fts3Getint(&z);
  155238. /* If the first integer value is followed by a ',', read the second
  155239. ** integer value. */
  155240. if( z[0]==',' && z[1]!='\0' ){
  155241. z++;
  155242. nMin = fts3Getint(&z);
  155243. }
  155244. if( z[0]!='\0' || nMin<2 ){
  155245. rc = SQLITE_ERROR;
  155246. }else{
  155247. rc = SQLITE_OK;
  155248. if( !p->bHasStat ){
  155249. assert( p->bFts4==0 );
  155250. sqlite3Fts3CreateStatTable(&rc, p);
  155251. }
  155252. if( rc==SQLITE_OK ){
  155253. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  155254. }
  155255. sqlite3Fts3SegmentsClose(p);
  155256. }
  155257. return rc;
  155258. }
  155259. /*
  155260. ** Process statements of the form:
  155261. **
  155262. ** INSERT INTO table(table) VALUES('automerge=X');
  155263. **
  155264. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  155265. ** turn it on. The setting is persistent.
  155266. */
  155267. static int fts3DoAutoincrmerge(
  155268. Fts3Table *p, /* FTS3 table handle */
  155269. const char *zParam /* Nul-terminated string containing boolean */
  155270. ){
  155271. int rc = SQLITE_OK;
  155272. sqlite3_stmt *pStmt = 0;
  155273. p->nAutoincrmerge = fts3Getint(&zParam);
  155274. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  155275. p->nAutoincrmerge = 8;
  155276. }
  155277. if( !p->bHasStat ){
  155278. assert( p->bFts4==0 );
  155279. sqlite3Fts3CreateStatTable(&rc, p);
  155280. if( rc ) return rc;
  155281. }
  155282. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  155283. if( rc ) return rc;
  155284. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  155285. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  155286. sqlite3_step(pStmt);
  155287. rc = sqlite3_reset(pStmt);
  155288. return rc;
  155289. }
  155290. /*
  155291. ** Return a 64-bit checksum for the FTS index entry specified by the
  155292. ** arguments to this function.
  155293. */
  155294. static u64 fts3ChecksumEntry(
  155295. const char *zTerm, /* Pointer to buffer containing term */
  155296. int nTerm, /* Size of zTerm in bytes */
  155297. int iLangid, /* Language id for current row */
  155298. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  155299. i64 iDocid, /* Docid for current row. */
  155300. int iCol, /* Column number */
  155301. int iPos /* Position */
  155302. ){
  155303. int i;
  155304. u64 ret = (u64)iDocid;
  155305. ret += (ret<<3) + iLangid;
  155306. ret += (ret<<3) + iIndex;
  155307. ret += (ret<<3) + iCol;
  155308. ret += (ret<<3) + iPos;
  155309. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  155310. return ret;
  155311. }
  155312. /*
  155313. ** Return a checksum of all entries in the FTS index that correspond to
  155314. ** language id iLangid. The checksum is calculated by XORing the checksums
  155315. ** of each individual entry (see fts3ChecksumEntry()) together.
  155316. **
  155317. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  155318. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  155319. ** return value is undefined in this case.
  155320. */
  155321. static u64 fts3ChecksumIndex(
  155322. Fts3Table *p, /* FTS3 table handle */
  155323. int iLangid, /* Language id to return cksum for */
  155324. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  155325. int *pRc /* OUT: Return code */
  155326. ){
  155327. Fts3SegFilter filter;
  155328. Fts3MultiSegReader csr;
  155329. int rc;
  155330. u64 cksum = 0;
  155331. assert( *pRc==SQLITE_OK );
  155332. memset(&filter, 0, sizeof(filter));
  155333. memset(&csr, 0, sizeof(csr));
  155334. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  155335. filter.flags |= FTS3_SEGMENT_SCAN;
  155336. rc = sqlite3Fts3SegReaderCursor(
  155337. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  155338. );
  155339. if( rc==SQLITE_OK ){
  155340. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  155341. }
  155342. if( rc==SQLITE_OK ){
  155343. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  155344. char *pCsr = csr.aDoclist;
  155345. char *pEnd = &pCsr[csr.nDoclist];
  155346. i64 iDocid = 0;
  155347. i64 iCol = 0;
  155348. i64 iPos = 0;
  155349. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  155350. while( pCsr<pEnd ){
  155351. i64 iVal = 0;
  155352. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  155353. if( pCsr<pEnd ){
  155354. if( iVal==0 || iVal==1 ){
  155355. iCol = 0;
  155356. iPos = 0;
  155357. if( iVal ){
  155358. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  155359. }else{
  155360. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  155361. iDocid += iVal;
  155362. }
  155363. }else{
  155364. iPos += (iVal - 2);
  155365. cksum = cksum ^ fts3ChecksumEntry(
  155366. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  155367. (int)iCol, (int)iPos
  155368. );
  155369. }
  155370. }
  155371. }
  155372. }
  155373. }
  155374. sqlite3Fts3SegReaderFinish(&csr);
  155375. *pRc = rc;
  155376. return cksum;
  155377. }
  155378. /*
  155379. ** Check if the contents of the FTS index match the current contents of the
  155380. ** content table. If no error occurs and the contents do match, set *pbOk
  155381. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  155382. ** to false before returning.
  155383. **
  155384. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  155385. ** code. The final value of *pbOk is undefined in this case.
  155386. */
  155387. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  155388. int rc = SQLITE_OK; /* Return code */
  155389. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  155390. u64 cksum2 = 0; /* Checksum based on %_content contents */
  155391. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  155392. /* This block calculates the checksum according to the FTS index. */
  155393. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  155394. if( rc==SQLITE_OK ){
  155395. int rc2;
  155396. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  155397. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  155398. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  155399. int iLangid = sqlite3_column_int(pAllLangid, 0);
  155400. int i;
  155401. for(i=0; i<p->nIndex; i++){
  155402. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  155403. }
  155404. }
  155405. rc2 = sqlite3_reset(pAllLangid);
  155406. if( rc==SQLITE_OK ) rc = rc2;
  155407. }
  155408. /* This block calculates the checksum according to the %_content table */
  155409. if( rc==SQLITE_OK ){
  155410. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  155411. sqlite3_stmt *pStmt = 0;
  155412. char *zSql;
  155413. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  155414. if( !zSql ){
  155415. rc = SQLITE_NOMEM;
  155416. }else{
  155417. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  155418. sqlite3_free(zSql);
  155419. }
  155420. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  155421. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  155422. int iLang = langidFromSelect(p, pStmt);
  155423. int iCol;
  155424. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  155425. if( p->abNotindexed[iCol]==0 ){
  155426. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  155427. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  155428. sqlite3_tokenizer_cursor *pT = 0;
  155429. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  155430. while( rc==SQLITE_OK ){
  155431. char const *zToken; /* Buffer containing token */
  155432. int nToken = 0; /* Number of bytes in token */
  155433. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  155434. int iPos = 0; /* Position of token in zText */
  155435. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  155436. if( rc==SQLITE_OK ){
  155437. int i;
  155438. cksum2 = cksum2 ^ fts3ChecksumEntry(
  155439. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  155440. );
  155441. for(i=1; i<p->nIndex; i++){
  155442. if( p->aIndex[i].nPrefix<=nToken ){
  155443. cksum2 = cksum2 ^ fts3ChecksumEntry(
  155444. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  155445. );
  155446. }
  155447. }
  155448. }
  155449. }
  155450. if( pT ) pModule->xClose(pT);
  155451. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  155452. }
  155453. }
  155454. }
  155455. sqlite3_finalize(pStmt);
  155456. }
  155457. *pbOk = (cksum1==cksum2);
  155458. return rc;
  155459. }
  155460. /*
  155461. ** Run the integrity-check. If no error occurs and the current contents of
  155462. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  155463. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  155464. **
  155465. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  155466. ** error code.
  155467. **
  155468. ** The integrity-check works as follows. For each token and indexed token
  155469. ** prefix in the document set, a 64-bit checksum is calculated (by code
  155470. ** in fts3ChecksumEntry()) based on the following:
  155471. **
  155472. ** + The index number (0 for the main index, 1 for the first prefix
  155473. ** index etc.),
  155474. ** + The token (or token prefix) text itself,
  155475. ** + The language-id of the row it appears in,
  155476. ** + The docid of the row it appears in,
  155477. ** + The column it appears in, and
  155478. ** + The tokens position within that column.
  155479. **
  155480. ** The checksums for all entries in the index are XORed together to create
  155481. ** a single checksum for the entire index.
  155482. **
  155483. ** The integrity-check code calculates the same checksum in two ways:
  155484. **
  155485. ** 1. By scanning the contents of the FTS index, and
  155486. ** 2. By scanning and tokenizing the content table.
  155487. **
  155488. ** If the two checksums are identical, the integrity-check is deemed to have
  155489. ** passed.
  155490. */
  155491. static int fts3DoIntegrityCheck(
  155492. Fts3Table *p /* FTS3 table handle */
  155493. ){
  155494. int rc;
  155495. int bOk = 0;
  155496. rc = fts3IntegrityCheck(p, &bOk);
  155497. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  155498. return rc;
  155499. }
  155500. /*
  155501. ** Handle a 'special' INSERT of the form:
  155502. **
  155503. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  155504. **
  155505. ** Argument pVal contains the result of <expr>. Currently the only
  155506. ** meaningful value to insert is the text 'optimize'.
  155507. */
  155508. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  155509. int rc; /* Return Code */
  155510. const char *zVal = (const char *)sqlite3_value_text(pVal);
  155511. int nVal = sqlite3_value_bytes(pVal);
  155512. if( !zVal ){
  155513. return SQLITE_NOMEM;
  155514. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  155515. rc = fts3DoOptimize(p, 0);
  155516. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  155517. rc = fts3DoRebuild(p);
  155518. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  155519. rc = fts3DoIntegrityCheck(p);
  155520. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  155521. rc = fts3DoIncrmerge(p, &zVal[6]);
  155522. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  155523. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  155524. #ifdef SQLITE_TEST
  155525. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  155526. p->nNodeSize = atoi(&zVal[9]);
  155527. rc = SQLITE_OK;
  155528. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  155529. p->nMaxPendingData = atoi(&zVal[11]);
  155530. rc = SQLITE_OK;
  155531. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  155532. p->bNoIncrDoclist = atoi(&zVal[21]);
  155533. rc = SQLITE_OK;
  155534. #endif
  155535. }else{
  155536. rc = SQLITE_ERROR;
  155537. }
  155538. return rc;
  155539. }
  155540. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  155541. /*
  155542. ** Delete all cached deferred doclists. Deferred doclists are cached
  155543. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  155544. */
  155545. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  155546. Fts3DeferredToken *pDef;
  155547. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  155548. fts3PendingListDelete(pDef->pList);
  155549. pDef->pList = 0;
  155550. }
  155551. }
  155552. /*
  155553. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  155554. ** this list using sqlite3Fts3DeferToken().
  155555. */
  155556. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  155557. Fts3DeferredToken *pDef;
  155558. Fts3DeferredToken *pNext;
  155559. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  155560. pNext = pDef->pNext;
  155561. fts3PendingListDelete(pDef->pList);
  155562. sqlite3_free(pDef);
  155563. }
  155564. pCsr->pDeferred = 0;
  155565. }
  155566. /*
  155567. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  155568. ** based on the row that pCsr currently points to.
  155569. **
  155570. ** A deferred-doclist is like any other doclist with position information
  155571. ** included, except that it only contains entries for a single row of the
  155572. ** table, not for all rows.
  155573. */
  155574. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  155575. int rc = SQLITE_OK; /* Return code */
  155576. if( pCsr->pDeferred ){
  155577. int i; /* Used to iterate through table columns */
  155578. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  155579. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  155580. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  155581. sqlite3_tokenizer *pT = p->pTokenizer;
  155582. sqlite3_tokenizer_module const *pModule = pT->pModule;
  155583. assert( pCsr->isRequireSeek==0 );
  155584. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  155585. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  155586. if( p->abNotindexed[i]==0 ){
  155587. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  155588. sqlite3_tokenizer_cursor *pTC = 0;
  155589. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  155590. while( rc==SQLITE_OK ){
  155591. char const *zToken; /* Buffer containing token */
  155592. int nToken = 0; /* Number of bytes in token */
  155593. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  155594. int iPos = 0; /* Position of token in zText */
  155595. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  155596. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  155597. Fts3PhraseToken *pPT = pDef->pToken;
  155598. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  155599. && (pPT->bFirst==0 || iPos==0)
  155600. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  155601. && (0==memcmp(zToken, pPT->z, pPT->n))
  155602. ){
  155603. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  155604. }
  155605. }
  155606. }
  155607. if( pTC ) pModule->xClose(pTC);
  155608. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  155609. }
  155610. }
  155611. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  155612. if( pDef->pList ){
  155613. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  155614. }
  155615. }
  155616. }
  155617. return rc;
  155618. }
  155619. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  155620. Fts3DeferredToken *p,
  155621. char **ppData,
  155622. int *pnData
  155623. ){
  155624. char *pRet;
  155625. int nSkip;
  155626. sqlite3_int64 dummy;
  155627. *ppData = 0;
  155628. *pnData = 0;
  155629. if( p->pList==0 ){
  155630. return SQLITE_OK;
  155631. }
  155632. pRet = (char *)sqlite3_malloc(p->pList->nData);
  155633. if( !pRet ) return SQLITE_NOMEM;
  155634. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  155635. *pnData = p->pList->nData - nSkip;
  155636. *ppData = pRet;
  155637. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  155638. return SQLITE_OK;
  155639. }
  155640. /*
  155641. ** Add an entry for token pToken to the pCsr->pDeferred list.
  155642. */
  155643. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  155644. Fts3Cursor *pCsr, /* Fts3 table cursor */
  155645. Fts3PhraseToken *pToken, /* Token to defer */
  155646. int iCol /* Column that token must appear in (or -1) */
  155647. ){
  155648. Fts3DeferredToken *pDeferred;
  155649. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  155650. if( !pDeferred ){
  155651. return SQLITE_NOMEM;
  155652. }
  155653. memset(pDeferred, 0, sizeof(*pDeferred));
  155654. pDeferred->pToken = pToken;
  155655. pDeferred->pNext = pCsr->pDeferred;
  155656. pDeferred->iCol = iCol;
  155657. pCsr->pDeferred = pDeferred;
  155658. assert( pToken->pDeferred==0 );
  155659. pToken->pDeferred = pDeferred;
  155660. return SQLITE_OK;
  155661. }
  155662. #endif
  155663. /*
  155664. ** SQLite value pRowid contains the rowid of a row that may or may not be
  155665. ** present in the FTS3 table. If it is, delete it and adjust the contents
  155666. ** of subsiduary data structures accordingly.
  155667. */
  155668. static int fts3DeleteByRowid(
  155669. Fts3Table *p,
  155670. sqlite3_value *pRowid,
  155671. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  155672. u32 *aSzDel
  155673. ){
  155674. int rc = SQLITE_OK; /* Return code */
  155675. int bFound = 0; /* True if *pRowid really is in the table */
  155676. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  155677. if( bFound && rc==SQLITE_OK ){
  155678. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  155679. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  155680. if( rc==SQLITE_OK ){
  155681. if( isEmpty ){
  155682. /* Deleting this row means the whole table is empty. In this case
  155683. ** delete the contents of all three tables and throw away any
  155684. ** data in the pendingTerms hash table. */
  155685. rc = fts3DeleteAll(p, 1);
  155686. *pnChng = 0;
  155687. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  155688. }else{
  155689. *pnChng = *pnChng - 1;
  155690. if( p->zContentTbl==0 ){
  155691. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  155692. }
  155693. if( p->bHasDocsize ){
  155694. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  155695. }
  155696. }
  155697. }
  155698. }
  155699. return rc;
  155700. }
  155701. /*
  155702. ** This function does the work for the xUpdate method of FTS3 virtual
  155703. ** tables. The schema of the virtual table being:
  155704. **
  155705. ** CREATE TABLE <table name>(
  155706. ** <user columns>,
  155707. ** <table name> HIDDEN,
  155708. ** docid HIDDEN,
  155709. ** <langid> HIDDEN
  155710. ** );
  155711. **
  155712. **
  155713. */
  155714. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  155715. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  155716. int nArg, /* Size of argument array */
  155717. sqlite3_value **apVal, /* Array of arguments */
  155718. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  155719. ){
  155720. Fts3Table *p = (Fts3Table *)pVtab;
  155721. int rc = SQLITE_OK; /* Return Code */
  155722. u32 *aSzIns = 0; /* Sizes of inserted documents */
  155723. u32 *aSzDel = 0; /* Sizes of deleted documents */
  155724. int nChng = 0; /* Net change in number of documents */
  155725. int bInsertDone = 0;
  155726. /* At this point it must be known if the %_stat table exists or not.
  155727. ** So bHasStat may not be 2. */
  155728. assert( p->bHasStat==0 || p->bHasStat==1 );
  155729. assert( p->pSegments==0 );
  155730. assert(
  155731. nArg==1 /* DELETE operations */
  155732. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  155733. );
  155734. /* Check for a "special" INSERT operation. One of the form:
  155735. **
  155736. ** INSERT INTO xyz(xyz) VALUES('command');
  155737. */
  155738. if( nArg>1
  155739. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  155740. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  155741. ){
  155742. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  155743. goto update_out;
  155744. }
  155745. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  155746. rc = SQLITE_CONSTRAINT;
  155747. goto update_out;
  155748. }
  155749. /* Allocate space to hold the change in document sizes */
  155750. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  155751. if( aSzDel==0 ){
  155752. rc = SQLITE_NOMEM;
  155753. goto update_out;
  155754. }
  155755. aSzIns = &aSzDel[p->nColumn+1];
  155756. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  155757. rc = fts3Writelock(p);
  155758. if( rc!=SQLITE_OK ) goto update_out;
  155759. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  155760. ** value, then this operation requires constraint handling.
  155761. **
  155762. ** If the on-conflict mode is REPLACE, this means that the existing row
  155763. ** should be deleted from the database before inserting the new row. Or,
  155764. ** if the on-conflict mode is other than REPLACE, then this method must
  155765. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  155766. ** modify the database file.
  155767. */
  155768. if( nArg>1 && p->zContentTbl==0 ){
  155769. /* Find the value object that holds the new rowid value. */
  155770. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  155771. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  155772. pNewRowid = apVal[1];
  155773. }
  155774. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  155775. sqlite3_value_type(apVal[0])==SQLITE_NULL
  155776. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  155777. )){
  155778. /* The new rowid is not NULL (in this case the rowid will be
  155779. ** automatically assigned and there is no chance of a conflict), and
  155780. ** the statement is either an INSERT or an UPDATE that modifies the
  155781. ** rowid column. So if the conflict mode is REPLACE, then delete any
  155782. ** existing row with rowid=pNewRowid.
  155783. **
  155784. ** Or, if the conflict mode is not REPLACE, insert the new record into
  155785. ** the %_content table. If we hit the duplicate rowid constraint (or any
  155786. ** other error) while doing so, return immediately.
  155787. **
  155788. ** This branch may also run if pNewRowid contains a value that cannot
  155789. ** be losslessly converted to an integer. In this case, the eventual
  155790. ** call to fts3InsertData() (either just below or further on in this
  155791. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  155792. ** invoked, it will delete zero rows (since no row will have
  155793. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  155794. */
  155795. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  155796. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  155797. }else{
  155798. rc = fts3InsertData(p, apVal, pRowid);
  155799. bInsertDone = 1;
  155800. }
  155801. }
  155802. }
  155803. if( rc!=SQLITE_OK ){
  155804. goto update_out;
  155805. }
  155806. /* If this is a DELETE or UPDATE operation, remove the old record. */
  155807. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  155808. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  155809. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  155810. }
  155811. /* If this is an INSERT or UPDATE operation, insert the new record. */
  155812. if( nArg>1 && rc==SQLITE_OK ){
  155813. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  155814. if( bInsertDone==0 ){
  155815. rc = fts3InsertData(p, apVal, pRowid);
  155816. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  155817. rc = FTS_CORRUPT_VTAB;
  155818. }
  155819. }
  155820. if( rc==SQLITE_OK ){
  155821. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  155822. }
  155823. if( rc==SQLITE_OK ){
  155824. assert( p->iPrevDocid==*pRowid );
  155825. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  155826. }
  155827. if( p->bHasDocsize ){
  155828. fts3InsertDocsize(&rc, p, aSzIns);
  155829. }
  155830. nChng++;
  155831. }
  155832. if( p->bFts4 ){
  155833. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  155834. }
  155835. update_out:
  155836. sqlite3_free(aSzDel);
  155837. sqlite3Fts3SegmentsClose(p);
  155838. return rc;
  155839. }
  155840. /*
  155841. ** Flush any data in the pending-terms hash table to disk. If successful,
  155842. ** merge all segments in the database (including the new segment, if
  155843. ** there was any data to flush) into a single segment.
  155844. */
  155845. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  155846. int rc;
  155847. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  155848. if( rc==SQLITE_OK ){
  155849. rc = fts3DoOptimize(p, 1);
  155850. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  155851. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  155852. if( rc2!=SQLITE_OK ) rc = rc2;
  155853. }else{
  155854. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  155855. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  155856. }
  155857. }
  155858. sqlite3Fts3SegmentsClose(p);
  155859. return rc;
  155860. }
  155861. #endif
  155862. /************** End of fts3_write.c ******************************************/
  155863. /************** Begin file fts3_snippet.c ************************************/
  155864. /*
  155865. ** 2009 Oct 23
  155866. **
  155867. ** The author disclaims copyright to this source code. In place of
  155868. ** a legal notice, here is a blessing:
  155869. **
  155870. ** May you do good and not evil.
  155871. ** May you find forgiveness for yourself and forgive others.
  155872. ** May you share freely, never taking more than you give.
  155873. **
  155874. ******************************************************************************
  155875. */
  155876. /* #include "fts3Int.h" */
  155877. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  155878. /* #include <string.h> */
  155879. /* #include <assert.h> */
  155880. /*
  155881. ** Characters that may appear in the second argument to matchinfo().
  155882. */
  155883. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  155884. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  155885. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  155886. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  155887. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  155888. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  155889. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  155890. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  155891. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  155892. /*
  155893. ** The default value for the second argument to matchinfo().
  155894. */
  155895. #define FTS3_MATCHINFO_DEFAULT "pcx"
  155896. /*
  155897. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  155898. ** Fts3Expr.aDoclist[]/nDoclist.
  155899. */
  155900. typedef struct LoadDoclistCtx LoadDoclistCtx;
  155901. struct LoadDoclistCtx {
  155902. Fts3Cursor *pCsr; /* FTS3 Cursor */
  155903. int nPhrase; /* Number of phrases seen so far */
  155904. int nToken; /* Number of tokens seen so far */
  155905. };
  155906. /*
  155907. ** The following types are used as part of the implementation of the
  155908. ** fts3BestSnippet() routine.
  155909. */
  155910. typedef struct SnippetIter SnippetIter;
  155911. typedef struct SnippetPhrase SnippetPhrase;
  155912. typedef struct SnippetFragment SnippetFragment;
  155913. struct SnippetIter {
  155914. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  155915. int iCol; /* Extract snippet from this column */
  155916. int nSnippet; /* Requested snippet length (in tokens) */
  155917. int nPhrase; /* Number of phrases in query */
  155918. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  155919. int iCurrent; /* First token of current snippet */
  155920. };
  155921. struct SnippetPhrase {
  155922. int nToken; /* Number of tokens in phrase */
  155923. char *pList; /* Pointer to start of phrase position list */
  155924. int iHead; /* Next value in position list */
  155925. char *pHead; /* Position list data following iHead */
  155926. int iTail; /* Next value in trailing position list */
  155927. char *pTail; /* Position list data following iTail */
  155928. };
  155929. struct SnippetFragment {
  155930. int iCol; /* Column snippet is extracted from */
  155931. int iPos; /* Index of first token in snippet */
  155932. u64 covered; /* Mask of query phrases covered */
  155933. u64 hlmask; /* Mask of snippet terms to highlight */
  155934. };
  155935. /*
  155936. ** This type is used as an fts3ExprIterate() context object while
  155937. ** accumulating the data returned by the matchinfo() function.
  155938. */
  155939. typedef struct MatchInfo MatchInfo;
  155940. struct MatchInfo {
  155941. Fts3Cursor *pCursor; /* FTS3 Cursor */
  155942. int nCol; /* Number of columns in table */
  155943. int nPhrase; /* Number of matchable phrases in query */
  155944. sqlite3_int64 nDoc; /* Number of docs in database */
  155945. char flag;
  155946. u32 *aMatchinfo; /* Pre-allocated buffer */
  155947. };
  155948. /*
  155949. ** An instance of this structure is used to manage a pair of buffers, each
  155950. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  155951. ** for details.
  155952. */
  155953. struct MatchinfoBuffer {
  155954. u8 aRef[3];
  155955. int nElem;
  155956. int bGlobal; /* Set if global data is loaded */
  155957. char *zMatchinfo;
  155958. u32 aMatchinfo[1];
  155959. };
  155960. /*
  155961. ** The snippet() and offsets() functions both return text values. An instance
  155962. ** of the following structure is used to accumulate those values while the
  155963. ** functions are running. See fts3StringAppend() for details.
  155964. */
  155965. typedef struct StrBuffer StrBuffer;
  155966. struct StrBuffer {
  155967. char *z; /* Pointer to buffer containing string */
  155968. int n; /* Length of z in bytes (excl. nul-term) */
  155969. int nAlloc; /* Allocated size of buffer z in bytes */
  155970. };
  155971. /*************************************************************************
  155972. ** Start of MatchinfoBuffer code.
  155973. */
  155974. /*
  155975. ** Allocate a two-slot MatchinfoBuffer object.
  155976. */
  155977. static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
  155978. MatchinfoBuffer *pRet;
  155979. int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
  155980. int nStr = (int)strlen(zMatchinfo);
  155981. pRet = sqlite3_malloc(nByte + nStr+1);
  155982. if( pRet ){
  155983. memset(pRet, 0, nByte);
  155984. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  155985. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
  155986. pRet->nElem = nElem;
  155987. pRet->zMatchinfo = ((char*)pRet) + nByte;
  155988. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  155989. pRet->aRef[0] = 1;
  155990. }
  155991. return pRet;
  155992. }
  155993. static void fts3MIBufferFree(void *p){
  155994. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  155995. assert( (u32*)p==&pBuf->aMatchinfo[1]
  155996. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  155997. );
  155998. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  155999. pBuf->aRef[1] = 0;
  156000. }else{
  156001. pBuf->aRef[2] = 0;
  156002. }
  156003. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  156004. sqlite3_free(pBuf);
  156005. }
  156006. }
  156007. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  156008. void (*xRet)(void*) = 0;
  156009. u32 *aOut = 0;
  156010. if( p->aRef[1]==0 ){
  156011. p->aRef[1] = 1;
  156012. aOut = &p->aMatchinfo[1];
  156013. xRet = fts3MIBufferFree;
  156014. }
  156015. else if( p->aRef[2]==0 ){
  156016. p->aRef[2] = 1;
  156017. aOut = &p->aMatchinfo[p->nElem+2];
  156018. xRet = fts3MIBufferFree;
  156019. }else{
  156020. aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
  156021. if( aOut ){
  156022. xRet = sqlite3_free;
  156023. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  156024. }
  156025. }
  156026. *paOut = aOut;
  156027. return xRet;
  156028. }
  156029. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  156030. p->bGlobal = 1;
  156031. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  156032. }
  156033. /*
  156034. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  156035. */
  156036. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  156037. if( p ){
  156038. assert( p->aRef[0]==1 );
  156039. p->aRef[0] = 0;
  156040. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  156041. sqlite3_free(p);
  156042. }
  156043. }
  156044. }
  156045. /*
  156046. ** End of MatchinfoBuffer code.
  156047. *************************************************************************/
  156048. /*
  156049. ** This function is used to help iterate through a position-list. A position
  156050. ** list is a list of unique integers, sorted from smallest to largest. Each
  156051. ** element of the list is represented by an FTS3 varint that takes the value
  156052. ** of the difference between the current element and the previous one plus
  156053. ** two. For example, to store the position-list:
  156054. **
  156055. ** 4 9 113
  156056. **
  156057. ** the three varints:
  156058. **
  156059. ** 6 7 106
  156060. **
  156061. ** are encoded.
  156062. **
  156063. ** When this function is called, *pp points to the start of an element of
  156064. ** the list. *piPos contains the value of the previous entry in the list.
  156065. ** After it returns, *piPos contains the value of the next element of the
  156066. ** list and *pp is advanced to the following varint.
  156067. */
  156068. static void fts3GetDeltaPosition(char **pp, int *piPos){
  156069. int iVal;
  156070. *pp += fts3GetVarint32(*pp, &iVal);
  156071. *piPos += (iVal-2);
  156072. }
  156073. /*
  156074. ** Helper function for fts3ExprIterate() (see below).
  156075. */
  156076. static int fts3ExprIterate2(
  156077. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  156078. int *piPhrase, /* Pointer to phrase counter */
  156079. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  156080. void *pCtx /* Second argument to pass to callback */
  156081. ){
  156082. int rc; /* Return code */
  156083. int eType = pExpr->eType; /* Type of expression node pExpr */
  156084. if( eType!=FTSQUERY_PHRASE ){
  156085. assert( pExpr->pLeft && pExpr->pRight );
  156086. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  156087. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  156088. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  156089. }
  156090. }else{
  156091. rc = x(pExpr, *piPhrase, pCtx);
  156092. (*piPhrase)++;
  156093. }
  156094. return rc;
  156095. }
  156096. /*
  156097. ** Iterate through all phrase nodes in an FTS3 query, except those that
  156098. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  156099. ** For each phrase node found, the supplied callback function is invoked.
  156100. **
  156101. ** If the callback function returns anything other than SQLITE_OK,
  156102. ** the iteration is abandoned and the error code returned immediately.
  156103. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  156104. ** all eligible phrase nodes.
  156105. */
  156106. static int fts3ExprIterate(
  156107. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  156108. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  156109. void *pCtx /* Second argument to pass to callback */
  156110. ){
  156111. int iPhrase = 0; /* Variable used as the phrase counter */
  156112. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  156113. }
  156114. /*
  156115. ** This is an fts3ExprIterate() callback used while loading the doclists
  156116. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  156117. ** fts3ExprLoadDoclists().
  156118. */
  156119. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  156120. int rc = SQLITE_OK;
  156121. Fts3Phrase *pPhrase = pExpr->pPhrase;
  156122. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  156123. UNUSED_PARAMETER(iPhrase);
  156124. p->nPhrase++;
  156125. p->nToken += pPhrase->nToken;
  156126. return rc;
  156127. }
  156128. /*
  156129. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  156130. ** pCsr.
  156131. **
  156132. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  156133. ** phrases in the expression (all phrases except those directly or
  156134. ** indirectly descended from the right-hand-side of a NOT operator). If
  156135. ** pnToken is not NULL, then it is set to the number of tokens in all
  156136. ** matchable phrases of the expression.
  156137. */
  156138. static int fts3ExprLoadDoclists(
  156139. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  156140. int *pnPhrase, /* OUT: Number of phrases in query */
  156141. int *pnToken /* OUT: Number of tokens in query */
  156142. ){
  156143. int rc; /* Return Code */
  156144. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  156145. sCtx.pCsr = pCsr;
  156146. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  156147. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  156148. if( pnToken ) *pnToken = sCtx.nToken;
  156149. return rc;
  156150. }
  156151. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  156152. (*(int *)ctx)++;
  156153. pExpr->iPhrase = iPhrase;
  156154. return SQLITE_OK;
  156155. }
  156156. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  156157. int nPhrase = 0;
  156158. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  156159. return nPhrase;
  156160. }
  156161. /*
  156162. ** Advance the position list iterator specified by the first two
  156163. ** arguments so that it points to the first element with a value greater
  156164. ** than or equal to parameter iNext.
  156165. */
  156166. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  156167. char *pIter = *ppIter;
  156168. if( pIter ){
  156169. int iIter = *piIter;
  156170. while( iIter<iNext ){
  156171. if( 0==(*pIter & 0xFE) ){
  156172. iIter = -1;
  156173. pIter = 0;
  156174. break;
  156175. }
  156176. fts3GetDeltaPosition(&pIter, &iIter);
  156177. }
  156178. *piIter = iIter;
  156179. *ppIter = pIter;
  156180. }
  156181. }
  156182. /*
  156183. ** Advance the snippet iterator to the next candidate snippet.
  156184. */
  156185. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  156186. int i; /* Loop counter */
  156187. if( pIter->iCurrent<0 ){
  156188. /* The SnippetIter object has just been initialized. The first snippet
  156189. ** candidate always starts at offset 0 (even if this candidate has a
  156190. ** score of 0.0).
  156191. */
  156192. pIter->iCurrent = 0;
  156193. /* Advance the 'head' iterator of each phrase to the first offset that
  156194. ** is greater than or equal to (iNext+nSnippet).
  156195. */
  156196. for(i=0; i<pIter->nPhrase; i++){
  156197. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  156198. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  156199. }
  156200. }else{
  156201. int iStart;
  156202. int iEnd = 0x7FFFFFFF;
  156203. for(i=0; i<pIter->nPhrase; i++){
  156204. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  156205. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  156206. iEnd = pPhrase->iHead;
  156207. }
  156208. }
  156209. if( iEnd==0x7FFFFFFF ){
  156210. return 1;
  156211. }
  156212. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  156213. for(i=0; i<pIter->nPhrase; i++){
  156214. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  156215. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  156216. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  156217. }
  156218. }
  156219. return 0;
  156220. }
  156221. /*
  156222. ** Retrieve information about the current candidate snippet of snippet
  156223. ** iterator pIter.
  156224. */
  156225. static void fts3SnippetDetails(
  156226. SnippetIter *pIter, /* Snippet iterator */
  156227. u64 mCovered, /* Bitmask of phrases already covered */
  156228. int *piToken, /* OUT: First token of proposed snippet */
  156229. int *piScore, /* OUT: "Score" for this snippet */
  156230. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  156231. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  156232. ){
  156233. int iStart = pIter->iCurrent; /* First token of snippet */
  156234. int iScore = 0; /* Score of this snippet */
  156235. int i; /* Loop counter */
  156236. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  156237. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  156238. for(i=0; i<pIter->nPhrase; i++){
  156239. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  156240. if( pPhrase->pTail ){
  156241. char *pCsr = pPhrase->pTail;
  156242. int iCsr = pPhrase->iTail;
  156243. while( iCsr<(iStart+pIter->nSnippet) ){
  156244. int j;
  156245. u64 mPhrase = (u64)1 << i;
  156246. u64 mPos = (u64)1 << (iCsr - iStart);
  156247. assert( iCsr>=iStart );
  156248. if( (mCover|mCovered)&mPhrase ){
  156249. iScore++;
  156250. }else{
  156251. iScore += 1000;
  156252. }
  156253. mCover |= mPhrase;
  156254. for(j=0; j<pPhrase->nToken; j++){
  156255. mHighlight |= (mPos>>j);
  156256. }
  156257. if( 0==(*pCsr & 0x0FE) ) break;
  156258. fts3GetDeltaPosition(&pCsr, &iCsr);
  156259. }
  156260. }
  156261. }
  156262. /* Set the output variables before returning. */
  156263. *piToken = iStart;
  156264. *piScore = iScore;
  156265. *pmCover = mCover;
  156266. *pmHighlight = mHighlight;
  156267. }
  156268. /*
  156269. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  156270. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  156271. */
  156272. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  156273. SnippetIter *p = (SnippetIter *)ctx;
  156274. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  156275. char *pCsr;
  156276. int rc;
  156277. pPhrase->nToken = pExpr->pPhrase->nToken;
  156278. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  156279. assert( rc==SQLITE_OK || pCsr==0 );
  156280. if( pCsr ){
  156281. int iFirst = 0;
  156282. pPhrase->pList = pCsr;
  156283. fts3GetDeltaPosition(&pCsr, &iFirst);
  156284. assert( iFirst>=0 );
  156285. pPhrase->pHead = pCsr;
  156286. pPhrase->pTail = pCsr;
  156287. pPhrase->iHead = iFirst;
  156288. pPhrase->iTail = iFirst;
  156289. }else{
  156290. assert( rc!=SQLITE_OK || (
  156291. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  156292. ));
  156293. }
  156294. return rc;
  156295. }
  156296. /*
  156297. ** Select the fragment of text consisting of nFragment contiguous tokens
  156298. ** from column iCol that represent the "best" snippet. The best snippet
  156299. ** is the snippet with the highest score, where scores are calculated
  156300. ** by adding:
  156301. **
  156302. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  156303. **
  156304. ** (b) +1000 points for the first occurrence of each matchable phrase in
  156305. ** the snippet for which the corresponding mCovered bit is not set.
  156306. **
  156307. ** The selected snippet parameters are stored in structure *pFragment before
  156308. ** returning. The score of the selected snippet is stored in *piScore
  156309. ** before returning.
  156310. */
  156311. static int fts3BestSnippet(
  156312. int nSnippet, /* Desired snippet length */
  156313. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  156314. int iCol, /* Index of column to create snippet from */
  156315. u64 mCovered, /* Mask of phrases already covered */
  156316. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  156317. SnippetFragment *pFragment, /* OUT: Best snippet found */
  156318. int *piScore /* OUT: Score of snippet pFragment */
  156319. ){
  156320. int rc; /* Return Code */
  156321. int nList; /* Number of phrases in expression */
  156322. SnippetIter sIter; /* Iterates through snippet candidates */
  156323. int nByte; /* Number of bytes of space to allocate */
  156324. int iBestScore = -1; /* Best snippet score found so far */
  156325. int i; /* Loop counter */
  156326. memset(&sIter, 0, sizeof(sIter));
  156327. /* Iterate through the phrases in the expression to count them. The same
  156328. ** callback makes sure the doclists are loaded for each phrase.
  156329. */
  156330. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  156331. if( rc!=SQLITE_OK ){
  156332. return rc;
  156333. }
  156334. /* Now that it is known how many phrases there are, allocate and zero
  156335. ** the required space using malloc().
  156336. */
  156337. nByte = sizeof(SnippetPhrase) * nList;
  156338. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  156339. if( !sIter.aPhrase ){
  156340. return SQLITE_NOMEM;
  156341. }
  156342. memset(sIter.aPhrase, 0, nByte);
  156343. /* Initialize the contents of the SnippetIter object. Then iterate through
  156344. ** the set of phrases in the expression to populate the aPhrase[] array.
  156345. */
  156346. sIter.pCsr = pCsr;
  156347. sIter.iCol = iCol;
  156348. sIter.nSnippet = nSnippet;
  156349. sIter.nPhrase = nList;
  156350. sIter.iCurrent = -1;
  156351. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  156352. if( rc==SQLITE_OK ){
  156353. /* Set the *pmSeen output variable. */
  156354. for(i=0; i<nList; i++){
  156355. if( sIter.aPhrase[i].pHead ){
  156356. *pmSeen |= (u64)1 << i;
  156357. }
  156358. }
  156359. /* Loop through all candidate snippets. Store the best snippet in
  156360. ** *pFragment. Store its associated 'score' in iBestScore.
  156361. */
  156362. pFragment->iCol = iCol;
  156363. while( !fts3SnippetNextCandidate(&sIter) ){
  156364. int iPos;
  156365. int iScore;
  156366. u64 mCover;
  156367. u64 mHighlite;
  156368. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  156369. assert( iScore>=0 );
  156370. if( iScore>iBestScore ){
  156371. pFragment->iPos = iPos;
  156372. pFragment->hlmask = mHighlite;
  156373. pFragment->covered = mCover;
  156374. iBestScore = iScore;
  156375. }
  156376. }
  156377. *piScore = iBestScore;
  156378. }
  156379. sqlite3_free(sIter.aPhrase);
  156380. return rc;
  156381. }
  156382. /*
  156383. ** Append a string to the string-buffer passed as the first argument.
  156384. **
  156385. ** If nAppend is negative, then the length of the string zAppend is
  156386. ** determined using strlen().
  156387. */
  156388. static int fts3StringAppend(
  156389. StrBuffer *pStr, /* Buffer to append to */
  156390. const char *zAppend, /* Pointer to data to append to buffer */
  156391. int nAppend /* Size of zAppend in bytes (or -1) */
  156392. ){
  156393. if( nAppend<0 ){
  156394. nAppend = (int)strlen(zAppend);
  156395. }
  156396. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  156397. ** to grow the buffer until so that it is big enough to accomadate the
  156398. ** appended data.
  156399. */
  156400. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  156401. int nAlloc = pStr->nAlloc+nAppend+100;
  156402. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  156403. if( !zNew ){
  156404. return SQLITE_NOMEM;
  156405. }
  156406. pStr->z = zNew;
  156407. pStr->nAlloc = nAlloc;
  156408. }
  156409. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  156410. /* Append the data to the string buffer. */
  156411. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  156412. pStr->n += nAppend;
  156413. pStr->z[pStr->n] = '\0';
  156414. return SQLITE_OK;
  156415. }
  156416. /*
  156417. ** The fts3BestSnippet() function often selects snippets that end with a
  156418. ** query term. That is, the final term of the snippet is always a term
  156419. ** that requires highlighting. For example, if 'X' is a highlighted term
  156420. ** and '.' is a non-highlighted term, BestSnippet() may select:
  156421. **
  156422. ** ........X.....X
  156423. **
  156424. ** This function "shifts" the beginning of the snippet forward in the
  156425. ** document so that there are approximately the same number of
  156426. ** non-highlighted terms to the right of the final highlighted term as there
  156427. ** are to the left of the first highlighted term. For example, to this:
  156428. **
  156429. ** ....X.....X....
  156430. **
  156431. ** This is done as part of extracting the snippet text, not when selecting
  156432. ** the snippet. Snippet selection is done based on doclists only, so there
  156433. ** is no way for fts3BestSnippet() to know whether or not the document
  156434. ** actually contains terms that follow the final highlighted term.
  156435. */
  156436. static int fts3SnippetShift(
  156437. Fts3Table *pTab, /* FTS3 table snippet comes from */
  156438. int iLangid, /* Language id to use in tokenizing */
  156439. int nSnippet, /* Number of tokens desired for snippet */
  156440. const char *zDoc, /* Document text to extract snippet from */
  156441. int nDoc, /* Size of buffer zDoc in bytes */
  156442. int *piPos, /* IN/OUT: First token of snippet */
  156443. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  156444. ){
  156445. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  156446. if( hlmask ){
  156447. int nLeft; /* Tokens to the left of first highlight */
  156448. int nRight; /* Tokens to the right of last highlight */
  156449. int nDesired; /* Ideal number of tokens to shift forward */
  156450. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  156451. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  156452. nDesired = (nLeft-nRight)/2;
  156453. /* Ideally, the start of the snippet should be pushed forward in the
  156454. ** document nDesired tokens. This block checks if there are actually
  156455. ** nDesired tokens to the right of the snippet. If so, *piPos and
  156456. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  156457. ** right. Otherwise, the snippet is shifted by the number of tokens
  156458. ** available.
  156459. */
  156460. if( nDesired>0 ){
  156461. int nShift; /* Number of tokens to shift snippet by */
  156462. int iCurrent = 0; /* Token counter */
  156463. int rc; /* Return Code */
  156464. sqlite3_tokenizer_module *pMod;
  156465. sqlite3_tokenizer_cursor *pC;
  156466. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  156467. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  156468. ** or more tokens in zDoc/nDoc.
  156469. */
  156470. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  156471. if( rc!=SQLITE_OK ){
  156472. return rc;
  156473. }
  156474. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  156475. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  156476. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  156477. }
  156478. pMod->xClose(pC);
  156479. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  156480. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  156481. assert( nShift<=nDesired );
  156482. if( nShift>0 ){
  156483. *piPos += nShift;
  156484. *pHlmask = hlmask >> nShift;
  156485. }
  156486. }
  156487. }
  156488. return SQLITE_OK;
  156489. }
  156490. /*
  156491. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  156492. ** append it to string buffer pOut.
  156493. */
  156494. static int fts3SnippetText(
  156495. Fts3Cursor *pCsr, /* FTS3 Cursor */
  156496. SnippetFragment *pFragment, /* Snippet to extract */
  156497. int iFragment, /* Fragment number */
  156498. int isLast, /* True for final fragment in snippet */
  156499. int nSnippet, /* Number of tokens in extracted snippet */
  156500. const char *zOpen, /* String inserted before highlighted term */
  156501. const char *zClose, /* String inserted after highlighted term */
  156502. const char *zEllipsis, /* String inserted between snippets */
  156503. StrBuffer *pOut /* Write output here */
  156504. ){
  156505. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  156506. int rc; /* Return code */
  156507. const char *zDoc; /* Document text to extract snippet from */
  156508. int nDoc; /* Size of zDoc in bytes */
  156509. int iCurrent = 0; /* Current token number of document */
  156510. int iEnd = 0; /* Byte offset of end of current token */
  156511. int isShiftDone = 0; /* True after snippet is shifted */
  156512. int iPos = pFragment->iPos; /* First token of snippet */
  156513. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  156514. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  156515. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  156516. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  156517. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  156518. if( zDoc==0 ){
  156519. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  156520. return SQLITE_NOMEM;
  156521. }
  156522. return SQLITE_OK;
  156523. }
  156524. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  156525. /* Open a token cursor on the document. */
  156526. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  156527. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  156528. if( rc!=SQLITE_OK ){
  156529. return rc;
  156530. }
  156531. while( rc==SQLITE_OK ){
  156532. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  156533. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  156534. int iBegin = 0; /* Offset in zDoc of start of token */
  156535. int iFin = 0; /* Offset in zDoc of end of token */
  156536. int isHighlight = 0; /* True for highlighted terms */
  156537. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  156538. ** in the FTS code the variable that the third argument to xNext points to
  156539. ** is initialized to zero before the first (*but not necessarily
  156540. ** subsequent*) call to xNext(). This is done for a particular application
  156541. ** that needs to know whether or not the tokenizer is being used for
  156542. ** snippet generation or for some other purpose.
  156543. **
  156544. ** Extreme care is required when writing code to depend on this
  156545. ** initialization. It is not a documented part of the tokenizer interface.
  156546. ** If a tokenizer is used directly by any code outside of FTS, this
  156547. ** convention might not be respected. */
  156548. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  156549. if( rc!=SQLITE_OK ){
  156550. if( rc==SQLITE_DONE ){
  156551. /* Special case - the last token of the snippet is also the last token
  156552. ** of the column. Append any punctuation that occurred between the end
  156553. ** of the previous token and the end of the document to the output.
  156554. ** Then break out of the loop. */
  156555. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  156556. }
  156557. break;
  156558. }
  156559. if( iCurrent<iPos ){ continue; }
  156560. if( !isShiftDone ){
  156561. int n = nDoc - iBegin;
  156562. rc = fts3SnippetShift(
  156563. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  156564. );
  156565. isShiftDone = 1;
  156566. /* Now that the shift has been done, check if the initial "..." are
  156567. ** required. They are required if (a) this is not the first fragment,
  156568. ** or (b) this fragment does not begin at position 0 of its column.
  156569. */
  156570. if( rc==SQLITE_OK ){
  156571. if( iPos>0 || iFragment>0 ){
  156572. rc = fts3StringAppend(pOut, zEllipsis, -1);
  156573. }else if( iBegin ){
  156574. rc = fts3StringAppend(pOut, zDoc, iBegin);
  156575. }
  156576. }
  156577. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  156578. }
  156579. if( iCurrent>=(iPos+nSnippet) ){
  156580. if( isLast ){
  156581. rc = fts3StringAppend(pOut, zEllipsis, -1);
  156582. }
  156583. break;
  156584. }
  156585. /* Set isHighlight to true if this term should be highlighted. */
  156586. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  156587. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  156588. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  156589. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  156590. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  156591. iEnd = iFin;
  156592. }
  156593. pMod->xClose(pC);
  156594. return rc;
  156595. }
  156596. /*
  156597. ** This function is used to count the entries in a column-list (a
  156598. ** delta-encoded list of term offsets within a single column of a single
  156599. ** row). When this function is called, *ppCollist should point to the
  156600. ** beginning of the first varint in the column-list (the varint that
  156601. ** contains the position of the first matching term in the column data).
  156602. ** Before returning, *ppCollist is set to point to the first byte after
  156603. ** the last varint in the column-list (either the 0x00 signifying the end
  156604. ** of the position-list, or the 0x01 that precedes the column number of
  156605. ** the next column in the position-list).
  156606. **
  156607. ** The number of elements in the column-list is returned.
  156608. */
  156609. static int fts3ColumnlistCount(char **ppCollist){
  156610. char *pEnd = *ppCollist;
  156611. char c = 0;
  156612. int nEntry = 0;
  156613. /* A column-list is terminated by either a 0x01 or 0x00. */
  156614. while( 0xFE & (*pEnd | c) ){
  156615. c = *pEnd++ & 0x80;
  156616. if( !c ) nEntry++;
  156617. }
  156618. *ppCollist = pEnd;
  156619. return nEntry;
  156620. }
  156621. /*
  156622. ** This function gathers 'y' or 'b' data for a single phrase.
  156623. */
  156624. static void fts3ExprLHits(
  156625. Fts3Expr *pExpr, /* Phrase expression node */
  156626. MatchInfo *p /* Matchinfo context */
  156627. ){
  156628. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  156629. int iStart;
  156630. Fts3Phrase *pPhrase = pExpr->pPhrase;
  156631. char *pIter = pPhrase->doclist.pList;
  156632. int iCol = 0;
  156633. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  156634. if( p->flag==FTS3_MATCHINFO_LHITS ){
  156635. iStart = pExpr->iPhrase * p->nCol;
  156636. }else{
  156637. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  156638. }
  156639. while( 1 ){
  156640. int nHit = fts3ColumnlistCount(&pIter);
  156641. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  156642. if( p->flag==FTS3_MATCHINFO_LHITS ){
  156643. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  156644. }else if( nHit ){
  156645. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  156646. }
  156647. }
  156648. assert( *pIter==0x00 || *pIter==0x01 );
  156649. if( *pIter!=0x01 ) break;
  156650. pIter++;
  156651. pIter += fts3GetVarint32(pIter, &iCol);
  156652. }
  156653. }
  156654. /*
  156655. ** Gather the results for matchinfo directives 'y' and 'b'.
  156656. */
  156657. static void fts3ExprLHitGather(
  156658. Fts3Expr *pExpr,
  156659. MatchInfo *p
  156660. ){
  156661. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  156662. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  156663. if( pExpr->pLeft ){
  156664. fts3ExprLHitGather(pExpr->pLeft, p);
  156665. fts3ExprLHitGather(pExpr->pRight, p);
  156666. }else{
  156667. fts3ExprLHits(pExpr, p);
  156668. }
  156669. }
  156670. }
  156671. /*
  156672. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  156673. ** for a single query.
  156674. **
  156675. ** fts3ExprIterate() callback to load the 'global' elements of a
  156676. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  156677. ** of the matchinfo array that are constant for all rows returned by the
  156678. ** current query.
  156679. **
  156680. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  156681. ** function populates Matchinfo.aMatchinfo[] as follows:
  156682. **
  156683. ** for(iCol=0; iCol<nCol; iCol++){
  156684. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  156685. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  156686. ** }
  156687. **
  156688. ** where X is the number of matches for phrase iPhrase is column iCol of all
  156689. ** rows of the table. Y is the number of rows for which column iCol contains
  156690. ** at least one instance of phrase iPhrase.
  156691. **
  156692. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  156693. ** Y values are set to nDoc, where nDoc is the number of documents in the
  156694. ** file system. This is done because the full-text index doclist is required
  156695. ** to calculate these values properly, and the full-text index doclist is
  156696. ** not available for deferred tokens.
  156697. */
  156698. static int fts3ExprGlobalHitsCb(
  156699. Fts3Expr *pExpr, /* Phrase expression node */
  156700. int iPhrase, /* Phrase number (numbered from zero) */
  156701. void *pCtx /* Pointer to MatchInfo structure */
  156702. ){
  156703. MatchInfo *p = (MatchInfo *)pCtx;
  156704. return sqlite3Fts3EvalPhraseStats(
  156705. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  156706. );
  156707. }
  156708. /*
  156709. ** fts3ExprIterate() callback used to collect the "local" part of the
  156710. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  156711. ** array that are different for each row returned by the query.
  156712. */
  156713. static int fts3ExprLocalHitsCb(
  156714. Fts3Expr *pExpr, /* Phrase expression node */
  156715. int iPhrase, /* Phrase number */
  156716. void *pCtx /* Pointer to MatchInfo structure */
  156717. ){
  156718. int rc = SQLITE_OK;
  156719. MatchInfo *p = (MatchInfo *)pCtx;
  156720. int iStart = iPhrase * p->nCol * 3;
  156721. int i;
  156722. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  156723. char *pCsr;
  156724. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  156725. if( pCsr ){
  156726. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  156727. }else{
  156728. p->aMatchinfo[iStart+i*3] = 0;
  156729. }
  156730. }
  156731. return rc;
  156732. }
  156733. static int fts3MatchinfoCheck(
  156734. Fts3Table *pTab,
  156735. char cArg,
  156736. char **pzErr
  156737. ){
  156738. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  156739. || (cArg==FTS3_MATCHINFO_NCOL)
  156740. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  156741. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  156742. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  156743. || (cArg==FTS3_MATCHINFO_LCS)
  156744. || (cArg==FTS3_MATCHINFO_HITS)
  156745. || (cArg==FTS3_MATCHINFO_LHITS)
  156746. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  156747. ){
  156748. return SQLITE_OK;
  156749. }
  156750. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  156751. return SQLITE_ERROR;
  156752. }
  156753. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  156754. int nVal; /* Number of integers output by cArg */
  156755. switch( cArg ){
  156756. case FTS3_MATCHINFO_NDOC:
  156757. case FTS3_MATCHINFO_NPHRASE:
  156758. case FTS3_MATCHINFO_NCOL:
  156759. nVal = 1;
  156760. break;
  156761. case FTS3_MATCHINFO_AVGLENGTH:
  156762. case FTS3_MATCHINFO_LENGTH:
  156763. case FTS3_MATCHINFO_LCS:
  156764. nVal = pInfo->nCol;
  156765. break;
  156766. case FTS3_MATCHINFO_LHITS:
  156767. nVal = pInfo->nCol * pInfo->nPhrase;
  156768. break;
  156769. case FTS3_MATCHINFO_LHITS_BM:
  156770. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  156771. break;
  156772. default:
  156773. assert( cArg==FTS3_MATCHINFO_HITS );
  156774. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  156775. break;
  156776. }
  156777. return nVal;
  156778. }
  156779. static int fts3MatchinfoSelectDoctotal(
  156780. Fts3Table *pTab,
  156781. sqlite3_stmt **ppStmt,
  156782. sqlite3_int64 *pnDoc,
  156783. const char **paLen
  156784. ){
  156785. sqlite3_stmt *pStmt;
  156786. const char *a;
  156787. sqlite3_int64 nDoc;
  156788. if( !*ppStmt ){
  156789. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  156790. if( rc!=SQLITE_OK ) return rc;
  156791. }
  156792. pStmt = *ppStmt;
  156793. assert( sqlite3_data_count(pStmt)==1 );
  156794. a = sqlite3_column_blob(pStmt, 0);
  156795. a += sqlite3Fts3GetVarint(a, &nDoc);
  156796. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  156797. *pnDoc = (u32)nDoc;
  156798. if( paLen ) *paLen = a;
  156799. return SQLITE_OK;
  156800. }
  156801. /*
  156802. ** An instance of the following structure is used to store state while
  156803. ** iterating through a multi-column position-list corresponding to the
  156804. ** hits for a single phrase on a single row in order to calculate the
  156805. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  156806. */
  156807. typedef struct LcsIterator LcsIterator;
  156808. struct LcsIterator {
  156809. Fts3Expr *pExpr; /* Pointer to phrase expression */
  156810. int iPosOffset; /* Tokens count up to end of this phrase */
  156811. char *pRead; /* Cursor used to iterate through aDoclist */
  156812. int iPos; /* Current position */
  156813. };
  156814. /*
  156815. ** If LcsIterator.iCol is set to the following value, the iterator has
  156816. ** finished iterating through all offsets for all columns.
  156817. */
  156818. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  156819. static int fts3MatchinfoLcsCb(
  156820. Fts3Expr *pExpr, /* Phrase expression node */
  156821. int iPhrase, /* Phrase number (numbered from zero) */
  156822. void *pCtx /* Pointer to MatchInfo structure */
  156823. ){
  156824. LcsIterator *aIter = (LcsIterator *)pCtx;
  156825. aIter[iPhrase].pExpr = pExpr;
  156826. return SQLITE_OK;
  156827. }
  156828. /*
  156829. ** Advance the iterator passed as an argument to the next position. Return
  156830. ** 1 if the iterator is at EOF or if it now points to the start of the
  156831. ** position list for the next column.
  156832. */
  156833. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  156834. char *pRead = pIter->pRead;
  156835. sqlite3_int64 iRead;
  156836. int rc = 0;
  156837. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  156838. if( iRead==0 || iRead==1 ){
  156839. pRead = 0;
  156840. rc = 1;
  156841. }else{
  156842. pIter->iPos += (int)(iRead-2);
  156843. }
  156844. pIter->pRead = pRead;
  156845. return rc;
  156846. }
  156847. /*
  156848. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  156849. **
  156850. ** If the call is successful, the longest-common-substring lengths for each
  156851. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  156852. ** array before returning. SQLITE_OK is returned in this case.
  156853. **
  156854. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  156855. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  156856. ** undefined.
  156857. */
  156858. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  156859. LcsIterator *aIter;
  156860. int i;
  156861. int iCol;
  156862. int nToken = 0;
  156863. /* Allocate and populate the array of LcsIterator objects. The array
  156864. ** contains one element for each matchable phrase in the query.
  156865. **/
  156866. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  156867. if( !aIter ) return SQLITE_NOMEM;
  156868. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  156869. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  156870. for(i=0; i<pInfo->nPhrase; i++){
  156871. LcsIterator *pIter = &aIter[i];
  156872. nToken -= pIter->pExpr->pPhrase->nToken;
  156873. pIter->iPosOffset = nToken;
  156874. }
  156875. for(iCol=0; iCol<pInfo->nCol; iCol++){
  156876. int nLcs = 0; /* LCS value for this column */
  156877. int nLive = 0; /* Number of iterators in aIter not at EOF */
  156878. for(i=0; i<pInfo->nPhrase; i++){
  156879. int rc;
  156880. LcsIterator *pIt = &aIter[i];
  156881. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  156882. if( rc!=SQLITE_OK ) return rc;
  156883. if( pIt->pRead ){
  156884. pIt->iPos = pIt->iPosOffset;
  156885. fts3LcsIteratorAdvance(&aIter[i]);
  156886. nLive++;
  156887. }
  156888. }
  156889. while( nLive>0 ){
  156890. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  156891. int nThisLcs = 0; /* LCS for the current iterator positions */
  156892. for(i=0; i<pInfo->nPhrase; i++){
  156893. LcsIterator *pIter = &aIter[i];
  156894. if( pIter->pRead==0 ){
  156895. /* This iterator is already at EOF for this column. */
  156896. nThisLcs = 0;
  156897. }else{
  156898. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  156899. pAdv = pIter;
  156900. }
  156901. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  156902. nThisLcs++;
  156903. }else{
  156904. nThisLcs = 1;
  156905. }
  156906. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  156907. }
  156908. }
  156909. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  156910. }
  156911. pInfo->aMatchinfo[iCol] = nLcs;
  156912. }
  156913. sqlite3_free(aIter);
  156914. return SQLITE_OK;
  156915. }
  156916. /*
  156917. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  156918. ** be returned by the matchinfo() function. Argument zArg contains the
  156919. ** format string passed as the second argument to matchinfo (or the
  156920. ** default value "pcx" if no second argument was specified). The format
  156921. ** string has already been validated and the pInfo->aMatchinfo[] array
  156922. ** is guaranteed to be large enough for the output.
  156923. **
  156924. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  156925. ** If it is false, then assume that those fields that do not change between
  156926. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  156927. ** have already been populated.
  156928. **
  156929. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  156930. ** occurs. If a value other than SQLITE_OK is returned, the state the
  156931. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  156932. */
  156933. static int fts3MatchinfoValues(
  156934. Fts3Cursor *pCsr, /* FTS3 cursor object */
  156935. int bGlobal, /* True to grab the global stats */
  156936. MatchInfo *pInfo, /* Matchinfo context object */
  156937. const char *zArg /* Matchinfo format string */
  156938. ){
  156939. int rc = SQLITE_OK;
  156940. int i;
  156941. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  156942. sqlite3_stmt *pSelect = 0;
  156943. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  156944. pInfo->flag = zArg[i];
  156945. switch( zArg[i] ){
  156946. case FTS3_MATCHINFO_NPHRASE:
  156947. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  156948. break;
  156949. case FTS3_MATCHINFO_NCOL:
  156950. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  156951. break;
  156952. case FTS3_MATCHINFO_NDOC:
  156953. if( bGlobal ){
  156954. sqlite3_int64 nDoc = 0;
  156955. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  156956. pInfo->aMatchinfo[0] = (u32)nDoc;
  156957. }
  156958. break;
  156959. case FTS3_MATCHINFO_AVGLENGTH:
  156960. if( bGlobal ){
  156961. sqlite3_int64 nDoc; /* Number of rows in table */
  156962. const char *a; /* Aggregate column length array */
  156963. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  156964. if( rc==SQLITE_OK ){
  156965. int iCol;
  156966. for(iCol=0; iCol<pInfo->nCol; iCol++){
  156967. u32 iVal;
  156968. sqlite3_int64 nToken;
  156969. a += sqlite3Fts3GetVarint(a, &nToken);
  156970. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  156971. pInfo->aMatchinfo[iCol] = iVal;
  156972. }
  156973. }
  156974. }
  156975. break;
  156976. case FTS3_MATCHINFO_LENGTH: {
  156977. sqlite3_stmt *pSelectDocsize = 0;
  156978. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  156979. if( rc==SQLITE_OK ){
  156980. int iCol;
  156981. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  156982. for(iCol=0; iCol<pInfo->nCol; iCol++){
  156983. sqlite3_int64 nToken;
  156984. a += sqlite3Fts3GetVarint(a, &nToken);
  156985. pInfo->aMatchinfo[iCol] = (u32)nToken;
  156986. }
  156987. }
  156988. sqlite3_reset(pSelectDocsize);
  156989. break;
  156990. }
  156991. case FTS3_MATCHINFO_LCS:
  156992. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  156993. if( rc==SQLITE_OK ){
  156994. rc = fts3MatchinfoLcs(pCsr, pInfo);
  156995. }
  156996. break;
  156997. case FTS3_MATCHINFO_LHITS_BM:
  156998. case FTS3_MATCHINFO_LHITS: {
  156999. int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  157000. memset(pInfo->aMatchinfo, 0, nZero);
  157001. fts3ExprLHitGather(pCsr->pExpr, pInfo);
  157002. break;
  157003. }
  157004. default: {
  157005. Fts3Expr *pExpr;
  157006. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  157007. pExpr = pCsr->pExpr;
  157008. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  157009. if( rc!=SQLITE_OK ) break;
  157010. if( bGlobal ){
  157011. if( pCsr->pDeferred ){
  157012. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  157013. if( rc!=SQLITE_OK ) break;
  157014. }
  157015. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  157016. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  157017. if( rc!=SQLITE_OK ) break;
  157018. }
  157019. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  157020. break;
  157021. }
  157022. }
  157023. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  157024. }
  157025. sqlite3_reset(pSelect);
  157026. return rc;
  157027. }
  157028. /*
  157029. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  157030. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  157031. */
  157032. static void fts3GetMatchinfo(
  157033. sqlite3_context *pCtx, /* Return results here */
  157034. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  157035. const char *zArg /* Second argument to matchinfo() function */
  157036. ){
  157037. MatchInfo sInfo;
  157038. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  157039. int rc = SQLITE_OK;
  157040. int bGlobal = 0; /* Collect 'global' stats as well as local */
  157041. u32 *aOut = 0;
  157042. void (*xDestroyOut)(void*) = 0;
  157043. memset(&sInfo, 0, sizeof(MatchInfo));
  157044. sInfo.pCursor = pCsr;
  157045. sInfo.nCol = pTab->nColumn;
  157046. /* If there is cached matchinfo() data, but the format string for the
  157047. ** cache does not match the format string for this request, discard
  157048. ** the cached data. */
  157049. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  157050. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  157051. pCsr->pMIBuffer = 0;
  157052. }
  157053. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  157054. ** matchinfo function has been called for this query. In this case
  157055. ** allocate the array used to accumulate the matchinfo data and
  157056. ** initialize those elements that are constant for every row.
  157057. */
  157058. if( pCsr->pMIBuffer==0 ){
  157059. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  157060. int i; /* Used to iterate through zArg */
  157061. /* Determine the number of phrases in the query */
  157062. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  157063. sInfo.nPhrase = pCsr->nPhrase;
  157064. /* Determine the number of integers in the buffer returned by this call. */
  157065. for(i=0; zArg[i]; i++){
  157066. char *zErr = 0;
  157067. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  157068. sqlite3_result_error(pCtx, zErr, -1);
  157069. sqlite3_free(zErr);
  157070. return;
  157071. }
  157072. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  157073. }
  157074. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  157075. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  157076. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  157077. pCsr->isMatchinfoNeeded = 1;
  157078. bGlobal = 1;
  157079. }
  157080. if( rc==SQLITE_OK ){
  157081. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  157082. if( xDestroyOut==0 ){
  157083. rc = SQLITE_NOMEM;
  157084. }
  157085. }
  157086. if( rc==SQLITE_OK ){
  157087. sInfo.aMatchinfo = aOut;
  157088. sInfo.nPhrase = pCsr->nPhrase;
  157089. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  157090. if( bGlobal ){
  157091. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  157092. }
  157093. }
  157094. if( rc!=SQLITE_OK ){
  157095. sqlite3_result_error_code(pCtx, rc);
  157096. if( xDestroyOut ) xDestroyOut(aOut);
  157097. }else{
  157098. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  157099. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  157100. }
  157101. }
  157102. /*
  157103. ** Implementation of snippet() function.
  157104. */
  157105. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  157106. sqlite3_context *pCtx, /* SQLite function call context */
  157107. Fts3Cursor *pCsr, /* Cursor object */
  157108. const char *zStart, /* Snippet start text - "<b>" */
  157109. const char *zEnd, /* Snippet end text - "</b>" */
  157110. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  157111. int iCol, /* Extract snippet from this column */
  157112. int nToken /* Approximate number of tokens in snippet */
  157113. ){
  157114. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  157115. int rc = SQLITE_OK;
  157116. int i;
  157117. StrBuffer res = {0, 0, 0};
  157118. /* The returned text includes up to four fragments of text extracted from
  157119. ** the data in the current row. The first iteration of the for(...) loop
  157120. ** below attempts to locate a single fragment of text nToken tokens in
  157121. ** size that contains at least one instance of all phrases in the query
  157122. ** expression that appear in the current row. If such a fragment of text
  157123. ** cannot be found, the second iteration of the loop attempts to locate
  157124. ** a pair of fragments, and so on.
  157125. */
  157126. int nSnippet = 0; /* Number of fragments in this snippet */
  157127. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  157128. int nFToken = -1; /* Number of tokens in each fragment */
  157129. if( !pCsr->pExpr ){
  157130. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  157131. return;
  157132. }
  157133. for(nSnippet=1; 1; nSnippet++){
  157134. int iSnip; /* Loop counter 0..nSnippet-1 */
  157135. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  157136. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  157137. if( nToken>=0 ){
  157138. nFToken = (nToken+nSnippet-1) / nSnippet;
  157139. }else{
  157140. nFToken = -1 * nToken;
  157141. }
  157142. for(iSnip=0; iSnip<nSnippet; iSnip++){
  157143. int iBestScore = -1; /* Best score of columns checked so far */
  157144. int iRead; /* Used to iterate through columns */
  157145. SnippetFragment *pFragment = &aSnippet[iSnip];
  157146. memset(pFragment, 0, sizeof(*pFragment));
  157147. /* Loop through all columns of the table being considered for snippets.
  157148. ** If the iCol argument to this function was negative, this means all
  157149. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  157150. */
  157151. for(iRead=0; iRead<pTab->nColumn; iRead++){
  157152. SnippetFragment sF = {0, 0, 0, 0};
  157153. int iS = 0;
  157154. if( iCol>=0 && iRead!=iCol ) continue;
  157155. /* Find the best snippet of nFToken tokens in column iRead. */
  157156. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  157157. if( rc!=SQLITE_OK ){
  157158. goto snippet_out;
  157159. }
  157160. if( iS>iBestScore ){
  157161. *pFragment = sF;
  157162. iBestScore = iS;
  157163. }
  157164. }
  157165. mCovered |= pFragment->covered;
  157166. }
  157167. /* If all query phrases seen by fts3BestSnippet() are present in at least
  157168. ** one of the nSnippet snippet fragments, break out of the loop.
  157169. */
  157170. assert( (mCovered&mSeen)==mCovered );
  157171. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  157172. }
  157173. assert( nFToken>0 );
  157174. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  157175. rc = fts3SnippetText(pCsr, &aSnippet[i],
  157176. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  157177. );
  157178. }
  157179. snippet_out:
  157180. sqlite3Fts3SegmentsClose(pTab);
  157181. if( rc!=SQLITE_OK ){
  157182. sqlite3_result_error_code(pCtx, rc);
  157183. sqlite3_free(res.z);
  157184. }else{
  157185. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  157186. }
  157187. }
  157188. typedef struct TermOffset TermOffset;
  157189. typedef struct TermOffsetCtx TermOffsetCtx;
  157190. struct TermOffset {
  157191. char *pList; /* Position-list */
  157192. int iPos; /* Position just read from pList */
  157193. int iOff; /* Offset of this term from read positions */
  157194. };
  157195. struct TermOffsetCtx {
  157196. Fts3Cursor *pCsr;
  157197. int iCol; /* Column of table to populate aTerm for */
  157198. int iTerm;
  157199. sqlite3_int64 iDocid;
  157200. TermOffset *aTerm;
  157201. };
  157202. /*
  157203. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  157204. */
  157205. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  157206. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  157207. int nTerm; /* Number of tokens in phrase */
  157208. int iTerm; /* For looping through nTerm phrase terms */
  157209. char *pList; /* Pointer to position list for phrase */
  157210. int iPos = 0; /* First position in position-list */
  157211. int rc;
  157212. UNUSED_PARAMETER(iPhrase);
  157213. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  157214. nTerm = pExpr->pPhrase->nToken;
  157215. if( pList ){
  157216. fts3GetDeltaPosition(&pList, &iPos);
  157217. assert( iPos>=0 );
  157218. }
  157219. for(iTerm=0; iTerm<nTerm; iTerm++){
  157220. TermOffset *pT = &p->aTerm[p->iTerm++];
  157221. pT->iOff = nTerm-iTerm-1;
  157222. pT->pList = pList;
  157223. pT->iPos = iPos;
  157224. }
  157225. return rc;
  157226. }
  157227. /*
  157228. ** Implementation of offsets() function.
  157229. */
  157230. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  157231. sqlite3_context *pCtx, /* SQLite function call context */
  157232. Fts3Cursor *pCsr /* Cursor object */
  157233. ){
  157234. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  157235. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  157236. int rc; /* Return Code */
  157237. int nToken; /* Number of tokens in query */
  157238. int iCol; /* Column currently being processed */
  157239. StrBuffer res = {0, 0, 0}; /* Result string */
  157240. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  157241. if( !pCsr->pExpr ){
  157242. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  157243. return;
  157244. }
  157245. memset(&sCtx, 0, sizeof(sCtx));
  157246. assert( pCsr->isRequireSeek==0 );
  157247. /* Count the number of terms in the query */
  157248. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  157249. if( rc!=SQLITE_OK ) goto offsets_out;
  157250. /* Allocate the array of TermOffset iterators. */
  157251. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  157252. if( 0==sCtx.aTerm ){
  157253. rc = SQLITE_NOMEM;
  157254. goto offsets_out;
  157255. }
  157256. sCtx.iDocid = pCsr->iPrevId;
  157257. sCtx.pCsr = pCsr;
  157258. /* Loop through the table columns, appending offset information to
  157259. ** string-buffer res for each column.
  157260. */
  157261. for(iCol=0; iCol<pTab->nColumn; iCol++){
  157262. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  157263. const char *ZDUMMY; /* Dummy argument used with xNext() */
  157264. int NDUMMY = 0; /* Dummy argument used with xNext() */
  157265. int iStart = 0;
  157266. int iEnd = 0;
  157267. int iCurrent = 0;
  157268. const char *zDoc;
  157269. int nDoc;
  157270. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  157271. ** no way that this operation can fail, so the return code from
  157272. ** fts3ExprIterate() can be discarded.
  157273. */
  157274. sCtx.iCol = iCol;
  157275. sCtx.iTerm = 0;
  157276. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  157277. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  157278. ** in column iCol, jump immediately to the next iteration of the loop.
  157279. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  157280. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  157281. ** to the caller.
  157282. */
  157283. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  157284. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  157285. if( zDoc==0 ){
  157286. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  157287. continue;
  157288. }
  157289. rc = SQLITE_NOMEM;
  157290. goto offsets_out;
  157291. }
  157292. /* Initialize a tokenizer iterator to iterate through column iCol. */
  157293. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  157294. zDoc, nDoc, &pC
  157295. );
  157296. if( rc!=SQLITE_OK ) goto offsets_out;
  157297. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  157298. while( rc==SQLITE_OK ){
  157299. int i; /* Used to loop through terms */
  157300. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  157301. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  157302. for(i=0; i<nToken; i++){
  157303. TermOffset *pT = &sCtx.aTerm[i];
  157304. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  157305. iMinPos = pT->iPos-pT->iOff;
  157306. pTerm = pT;
  157307. }
  157308. }
  157309. if( !pTerm ){
  157310. /* All offsets for this column have been gathered. */
  157311. rc = SQLITE_DONE;
  157312. }else{
  157313. assert( iCurrent<=iMinPos );
  157314. if( 0==(0xFE&*pTerm->pList) ){
  157315. pTerm->pList = 0;
  157316. }else{
  157317. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  157318. }
  157319. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  157320. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  157321. }
  157322. if( rc==SQLITE_OK ){
  157323. char aBuffer[64];
  157324. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  157325. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  157326. );
  157327. rc = fts3StringAppend(&res, aBuffer, -1);
  157328. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  157329. rc = FTS_CORRUPT_VTAB;
  157330. }
  157331. }
  157332. }
  157333. if( rc==SQLITE_DONE ){
  157334. rc = SQLITE_OK;
  157335. }
  157336. pMod->xClose(pC);
  157337. if( rc!=SQLITE_OK ) goto offsets_out;
  157338. }
  157339. offsets_out:
  157340. sqlite3_free(sCtx.aTerm);
  157341. assert( rc!=SQLITE_DONE );
  157342. sqlite3Fts3SegmentsClose(pTab);
  157343. if( rc!=SQLITE_OK ){
  157344. sqlite3_result_error_code(pCtx, rc);
  157345. sqlite3_free(res.z);
  157346. }else{
  157347. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  157348. }
  157349. return;
  157350. }
  157351. /*
  157352. ** Implementation of matchinfo() function.
  157353. */
  157354. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  157355. sqlite3_context *pContext, /* Function call context */
  157356. Fts3Cursor *pCsr, /* FTS3 table cursor */
  157357. const char *zArg /* Second arg to matchinfo() function */
  157358. ){
  157359. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  157360. const char *zFormat;
  157361. if( zArg ){
  157362. zFormat = zArg;
  157363. }else{
  157364. zFormat = FTS3_MATCHINFO_DEFAULT;
  157365. }
  157366. if( !pCsr->pExpr ){
  157367. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  157368. return;
  157369. }else{
  157370. /* Retrieve matchinfo() data. */
  157371. fts3GetMatchinfo(pContext, pCsr, zFormat);
  157372. sqlite3Fts3SegmentsClose(pTab);
  157373. }
  157374. }
  157375. #endif
  157376. /************** End of fts3_snippet.c ****************************************/
  157377. /************** Begin file fts3_unicode.c ************************************/
  157378. /*
  157379. ** 2012 May 24
  157380. **
  157381. ** The author disclaims copyright to this source code. In place of
  157382. ** a legal notice, here is a blessing:
  157383. **
  157384. ** May you do good and not evil.
  157385. ** May you find forgiveness for yourself and forgive others.
  157386. ** May you share freely, never taking more than you give.
  157387. **
  157388. ******************************************************************************
  157389. **
  157390. ** Implementation of the "unicode" full-text-search tokenizer.
  157391. */
  157392. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  157393. /* #include "fts3Int.h" */
  157394. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  157395. /* #include <assert.h> */
  157396. /* #include <stdlib.h> */
  157397. /* #include <stdio.h> */
  157398. /* #include <string.h> */
  157399. /* #include "fts3_tokenizer.h" */
  157400. /*
  157401. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  157402. ** from the sqlite3 source file utf.c. If this file is compiled as part
  157403. ** of the amalgamation, they are not required.
  157404. */
  157405. #ifndef SQLITE_AMALGAMATION
  157406. static const unsigned char sqlite3Utf8Trans1[] = {
  157407. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  157408. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  157409. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  157410. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  157411. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  157412. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  157413. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  157414. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  157415. };
  157416. #define READ_UTF8(zIn, zTerm, c) \
  157417. c = *(zIn++); \
  157418. if( c>=0xc0 ){ \
  157419. c = sqlite3Utf8Trans1[c-0xc0]; \
  157420. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  157421. c = (c<<6) + (0x3f & *(zIn++)); \
  157422. } \
  157423. if( c<0x80 \
  157424. || (c&0xFFFFF800)==0xD800 \
  157425. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  157426. }
  157427. #define WRITE_UTF8(zOut, c) { \
  157428. if( c<0x00080 ){ \
  157429. *zOut++ = (u8)(c&0xFF); \
  157430. } \
  157431. else if( c<0x00800 ){ \
  157432. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  157433. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  157434. } \
  157435. else if( c<0x10000 ){ \
  157436. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  157437. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  157438. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  157439. }else{ \
  157440. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  157441. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  157442. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  157443. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  157444. } \
  157445. }
  157446. #endif /* ifndef SQLITE_AMALGAMATION */
  157447. typedef struct unicode_tokenizer unicode_tokenizer;
  157448. typedef struct unicode_cursor unicode_cursor;
  157449. struct unicode_tokenizer {
  157450. sqlite3_tokenizer base;
  157451. int bRemoveDiacritic;
  157452. int nException;
  157453. int *aiException;
  157454. };
  157455. struct unicode_cursor {
  157456. sqlite3_tokenizer_cursor base;
  157457. const unsigned char *aInput; /* Input text being tokenized */
  157458. int nInput; /* Size of aInput[] in bytes */
  157459. int iOff; /* Current offset within aInput[] */
  157460. int iToken; /* Index of next token to be returned */
  157461. char *zToken; /* storage for current token */
  157462. int nAlloc; /* space allocated at zToken */
  157463. };
  157464. /*
  157465. ** Destroy a tokenizer allocated by unicodeCreate().
  157466. */
  157467. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  157468. if( pTokenizer ){
  157469. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  157470. sqlite3_free(p->aiException);
  157471. sqlite3_free(p);
  157472. }
  157473. return SQLITE_OK;
  157474. }
  157475. /*
  157476. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  157477. ** statement has specified that the tokenizer for this table shall consider
  157478. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  157479. ** token characters (if bAlnum==1).
  157480. **
  157481. ** For each codepoint in the zIn/nIn string, this function checks if the
  157482. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  157483. ** If so, no action is taken. Otherwise, the codepoint is added to the
  157484. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  157485. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  157486. ** codepoints in the aiException[] array.
  157487. **
  157488. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  157489. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  157490. ** It is not possible to change the behavior of the tokenizer with respect
  157491. ** to these codepoints.
  157492. */
  157493. static int unicodeAddExceptions(
  157494. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  157495. int bAlnum, /* Replace Isalnum() return value with this */
  157496. const char *zIn, /* Array of characters to make exceptions */
  157497. int nIn /* Length of z in bytes */
  157498. ){
  157499. const unsigned char *z = (const unsigned char *)zIn;
  157500. const unsigned char *zTerm = &z[nIn];
  157501. unsigned int iCode;
  157502. int nEntry = 0;
  157503. assert( bAlnum==0 || bAlnum==1 );
  157504. while( z<zTerm ){
  157505. READ_UTF8(z, zTerm, iCode);
  157506. assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
  157507. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  157508. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  157509. ){
  157510. nEntry++;
  157511. }
  157512. }
  157513. if( nEntry ){
  157514. int *aNew; /* New aiException[] array */
  157515. int nNew; /* Number of valid entries in array aNew[] */
  157516. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  157517. if( aNew==0 ) return SQLITE_NOMEM;
  157518. nNew = p->nException;
  157519. z = (const unsigned char *)zIn;
  157520. while( z<zTerm ){
  157521. READ_UTF8(z, zTerm, iCode);
  157522. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  157523. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  157524. ){
  157525. int i, j;
  157526. for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
  157527. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  157528. aNew[i] = (int)iCode;
  157529. nNew++;
  157530. }
  157531. }
  157532. p->aiException = aNew;
  157533. p->nException = nNew;
  157534. }
  157535. return SQLITE_OK;
  157536. }
  157537. /*
  157538. ** Return true if the p->aiException[] array contains the value iCode.
  157539. */
  157540. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  157541. if( p->nException>0 ){
  157542. int *a = p->aiException;
  157543. int iLo = 0;
  157544. int iHi = p->nException-1;
  157545. while( iHi>=iLo ){
  157546. int iTest = (iHi + iLo) / 2;
  157547. if( iCode==a[iTest] ){
  157548. return 1;
  157549. }else if( iCode>a[iTest] ){
  157550. iLo = iTest+1;
  157551. }else{
  157552. iHi = iTest-1;
  157553. }
  157554. }
  157555. }
  157556. return 0;
  157557. }
  157558. /*
  157559. ** Return true if, for the purposes of tokenization, codepoint iCode is
  157560. ** considered a token character (not a separator).
  157561. */
  157562. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  157563. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  157564. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  157565. }
  157566. /*
  157567. ** Create a new tokenizer instance.
  157568. */
  157569. static int unicodeCreate(
  157570. int nArg, /* Size of array argv[] */
  157571. const char * const *azArg, /* Tokenizer creation arguments */
  157572. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  157573. ){
  157574. unicode_tokenizer *pNew; /* New tokenizer object */
  157575. int i;
  157576. int rc = SQLITE_OK;
  157577. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  157578. if( pNew==NULL ) return SQLITE_NOMEM;
  157579. memset(pNew, 0, sizeof(unicode_tokenizer));
  157580. pNew->bRemoveDiacritic = 1;
  157581. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  157582. const char *z = azArg[i];
  157583. int n = (int)strlen(z);
  157584. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  157585. pNew->bRemoveDiacritic = 1;
  157586. }
  157587. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  157588. pNew->bRemoveDiacritic = 0;
  157589. }
  157590. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  157591. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  157592. }
  157593. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  157594. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  157595. }
  157596. else{
  157597. /* Unrecognized argument */
  157598. rc = SQLITE_ERROR;
  157599. }
  157600. }
  157601. if( rc!=SQLITE_OK ){
  157602. unicodeDestroy((sqlite3_tokenizer *)pNew);
  157603. pNew = 0;
  157604. }
  157605. *pp = (sqlite3_tokenizer *)pNew;
  157606. return rc;
  157607. }
  157608. /*
  157609. ** Prepare to begin tokenizing a particular string. The input
  157610. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  157611. ** used to incrementally tokenize this string is returned in
  157612. ** *ppCursor.
  157613. */
  157614. static int unicodeOpen(
  157615. sqlite3_tokenizer *p, /* The tokenizer */
  157616. const char *aInput, /* Input string */
  157617. int nInput, /* Size of string aInput in bytes */
  157618. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  157619. ){
  157620. unicode_cursor *pCsr;
  157621. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  157622. if( pCsr==0 ){
  157623. return SQLITE_NOMEM;
  157624. }
  157625. memset(pCsr, 0, sizeof(unicode_cursor));
  157626. pCsr->aInput = (const unsigned char *)aInput;
  157627. if( aInput==0 ){
  157628. pCsr->nInput = 0;
  157629. }else if( nInput<0 ){
  157630. pCsr->nInput = (int)strlen(aInput);
  157631. }else{
  157632. pCsr->nInput = nInput;
  157633. }
  157634. *pp = &pCsr->base;
  157635. UNUSED_PARAMETER(p);
  157636. return SQLITE_OK;
  157637. }
  157638. /*
  157639. ** Close a tokenization cursor previously opened by a call to
  157640. ** simpleOpen() above.
  157641. */
  157642. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  157643. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  157644. sqlite3_free(pCsr->zToken);
  157645. sqlite3_free(pCsr);
  157646. return SQLITE_OK;
  157647. }
  157648. /*
  157649. ** Extract the next token from a tokenization cursor. The cursor must
  157650. ** have been opened by a prior call to simpleOpen().
  157651. */
  157652. static int unicodeNext(
  157653. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  157654. const char **paToken, /* OUT: Token text */
  157655. int *pnToken, /* OUT: Number of bytes at *paToken */
  157656. int *piStart, /* OUT: Starting offset of token */
  157657. int *piEnd, /* OUT: Ending offset of token */
  157658. int *piPos /* OUT: Position integer of token */
  157659. ){
  157660. unicode_cursor *pCsr = (unicode_cursor *)pC;
  157661. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  157662. unsigned int iCode = 0;
  157663. char *zOut;
  157664. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  157665. const unsigned char *zStart = z;
  157666. const unsigned char *zEnd;
  157667. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  157668. /* Scan past any delimiter characters before the start of the next token.
  157669. ** Return SQLITE_DONE early if this takes us all the way to the end of
  157670. ** the input. */
  157671. while( z<zTerm ){
  157672. READ_UTF8(z, zTerm, iCode);
  157673. if( unicodeIsAlnum(p, (int)iCode) ) break;
  157674. zStart = z;
  157675. }
  157676. if( zStart>=zTerm ) return SQLITE_DONE;
  157677. zOut = pCsr->zToken;
  157678. do {
  157679. int iOut;
  157680. /* Grow the output buffer if required. */
  157681. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  157682. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  157683. if( !zNew ) return SQLITE_NOMEM;
  157684. zOut = &zNew[zOut - pCsr->zToken];
  157685. pCsr->zToken = zNew;
  157686. pCsr->nAlloc += 64;
  157687. }
  157688. /* Write the folded case of the last character read to the output */
  157689. zEnd = z;
  157690. iOut = sqlite3FtsUnicodeFold((int)iCode, p->bRemoveDiacritic);
  157691. if( iOut ){
  157692. WRITE_UTF8(zOut, iOut);
  157693. }
  157694. /* If the cursor is not at EOF, read the next character */
  157695. if( z>=zTerm ) break;
  157696. READ_UTF8(z, zTerm, iCode);
  157697. }while( unicodeIsAlnum(p, (int)iCode)
  157698. || sqlite3FtsUnicodeIsdiacritic((int)iCode)
  157699. );
  157700. /* Set the output variables and return. */
  157701. pCsr->iOff = (int)(z - pCsr->aInput);
  157702. *paToken = pCsr->zToken;
  157703. *pnToken = (int)(zOut - pCsr->zToken);
  157704. *piStart = (int)(zStart - pCsr->aInput);
  157705. *piEnd = (int)(zEnd - pCsr->aInput);
  157706. *piPos = pCsr->iToken++;
  157707. return SQLITE_OK;
  157708. }
  157709. /*
  157710. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  157711. ** structure for the unicode tokenizer.
  157712. */
  157713. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  157714. static const sqlite3_tokenizer_module module = {
  157715. 0,
  157716. unicodeCreate,
  157717. unicodeDestroy,
  157718. unicodeOpen,
  157719. unicodeClose,
  157720. unicodeNext,
  157721. 0,
  157722. };
  157723. *ppModule = &module;
  157724. }
  157725. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  157726. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  157727. /************** End of fts3_unicode.c ****************************************/
  157728. /************** Begin file fts3_unicode2.c ***********************************/
  157729. /*
  157730. ** 2012 May 25
  157731. **
  157732. ** The author disclaims copyright to this source code. In place of
  157733. ** a legal notice, here is a blessing:
  157734. **
  157735. ** May you do good and not evil.
  157736. ** May you find forgiveness for yourself and forgive others.
  157737. ** May you share freely, never taking more than you give.
  157738. **
  157739. ******************************************************************************
  157740. */
  157741. /*
  157742. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  157743. */
  157744. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  157745. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  157746. /* #include <assert.h> */
  157747. /*
  157748. ** Return true if the argument corresponds to a unicode codepoint
  157749. ** classified as either a letter or a number. Otherwise false.
  157750. **
  157751. ** The results are undefined if the value passed to this function
  157752. ** is less than zero.
  157753. */
  157754. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  157755. /* Each unsigned integer in the following array corresponds to a contiguous
  157756. ** range of unicode codepoints that are not either letters or numbers (i.e.
  157757. ** codepoints for which this function should return 0).
  157758. **
  157759. ** The most significant 22 bits in each 32-bit value contain the first
  157760. ** codepoint in the range. The least significant 10 bits are used to store
  157761. ** the size of the range (always at least 1). In other words, the value
  157762. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  157763. ** C. It is not possible to represent a range larger than 1023 codepoints
  157764. ** using this format.
  157765. */
  157766. static const unsigned int aEntry[] = {
  157767. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  157768. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  157769. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  157770. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  157771. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  157772. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  157773. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  157774. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  157775. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  157776. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  157777. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  157778. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  157779. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  157780. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  157781. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  157782. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  157783. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  157784. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  157785. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  157786. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  157787. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  157788. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  157789. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  157790. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  157791. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  157792. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  157793. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  157794. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  157795. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  157796. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  157797. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  157798. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  157799. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  157800. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  157801. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  157802. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  157803. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  157804. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  157805. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  157806. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  157807. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  157808. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  157809. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  157810. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  157811. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  157812. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  157813. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  157814. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  157815. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  157816. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  157817. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  157818. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  157819. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  157820. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  157821. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  157822. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  157823. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  157824. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  157825. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  157826. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  157827. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  157828. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  157829. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  157830. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  157831. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  157832. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  157833. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  157834. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  157835. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  157836. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  157837. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  157838. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  157839. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  157840. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  157841. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  157842. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  157843. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  157844. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  157845. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  157846. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  157847. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  157848. 0x380400F0,
  157849. };
  157850. static const unsigned int aAscii[4] = {
  157851. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  157852. };
  157853. if( (unsigned int)c<128 ){
  157854. return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
  157855. }else if( (unsigned int)c<(1<<22) ){
  157856. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  157857. int iRes = 0;
  157858. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  157859. int iLo = 0;
  157860. while( iHi>=iLo ){
  157861. int iTest = (iHi + iLo) / 2;
  157862. if( key >= aEntry[iTest] ){
  157863. iRes = iTest;
  157864. iLo = iTest+1;
  157865. }else{
  157866. iHi = iTest-1;
  157867. }
  157868. }
  157869. assert( aEntry[0]<key );
  157870. assert( key>=aEntry[iRes] );
  157871. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  157872. }
  157873. return 1;
  157874. }
  157875. /*
  157876. ** If the argument is a codepoint corresponding to a lowercase letter
  157877. ** in the ASCII range with a diacritic added, return the codepoint
  157878. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  157879. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  157880. ** E"). The resuls of passing a codepoint that corresponds to an
  157881. ** uppercase letter are undefined.
  157882. */
  157883. static int remove_diacritic(int c){
  157884. unsigned short aDia[] = {
  157885. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  157886. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  157887. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  157888. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  157889. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  157890. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  157891. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  157892. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  157893. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  157894. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  157895. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  157896. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  157897. 62924, 63050, 63082, 63274, 63390,
  157898. };
  157899. char aChar[] = {
  157900. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  157901. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  157902. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  157903. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  157904. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  157905. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  157906. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  157907. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  157908. 'e', 'i', 'o', 'u', 'y',
  157909. };
  157910. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  157911. int iRes = 0;
  157912. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  157913. int iLo = 0;
  157914. while( iHi>=iLo ){
  157915. int iTest = (iHi + iLo) / 2;
  157916. if( key >= aDia[iTest] ){
  157917. iRes = iTest;
  157918. iLo = iTest+1;
  157919. }else{
  157920. iHi = iTest-1;
  157921. }
  157922. }
  157923. assert( key>=aDia[iRes] );
  157924. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  157925. }
  157926. /*
  157927. ** Return true if the argument interpreted as a unicode codepoint
  157928. ** is a diacritical modifier character.
  157929. */
  157930. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  157931. unsigned int mask0 = 0x08029FDF;
  157932. unsigned int mask1 = 0x000361F8;
  157933. if( c<768 || c>817 ) return 0;
  157934. return (c < 768+32) ?
  157935. (mask0 & (1 << (c-768))) :
  157936. (mask1 & (1 << (c-768-32)));
  157937. }
  157938. /*
  157939. ** Interpret the argument as a unicode codepoint. If the codepoint
  157940. ** is an upper case character that has a lower case equivalent,
  157941. ** return the codepoint corresponding to the lower case version.
  157942. ** Otherwise, return a copy of the argument.
  157943. **
  157944. ** The results are undefined if the value passed to this function
  157945. ** is less than zero.
  157946. */
  157947. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  157948. /* Each entry in the following array defines a rule for folding a range
  157949. ** of codepoints to lower case. The rule applies to a range of nRange
  157950. ** codepoints starting at codepoint iCode.
  157951. **
  157952. ** If the least significant bit in flags is clear, then the rule applies
  157953. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  157954. ** need to be folded). Or, if it is set, then the rule only applies to
  157955. ** every second codepoint in the range, starting with codepoint C.
  157956. **
  157957. ** The 7 most significant bits in flags are an index into the aiOff[]
  157958. ** array. If a specific codepoint C does require folding, then its lower
  157959. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  157960. **
  157961. ** The contents of this array are generated by parsing the CaseFolding.txt
  157962. ** file distributed as part of the "Unicode Character Database". See
  157963. ** http://www.unicode.org for details.
  157964. */
  157965. static const struct TableEntry {
  157966. unsigned short iCode;
  157967. unsigned char flags;
  157968. unsigned char nRange;
  157969. } aEntry[] = {
  157970. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  157971. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  157972. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  157973. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  157974. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  157975. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  157976. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  157977. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  157978. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  157979. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  157980. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  157981. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  157982. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  157983. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  157984. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  157985. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  157986. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  157987. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  157988. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  157989. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  157990. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  157991. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  157992. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  157993. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  157994. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  157995. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  157996. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  157997. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  157998. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  157999. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  158000. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  158001. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  158002. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  158003. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  158004. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  158005. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  158006. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  158007. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  158008. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  158009. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  158010. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  158011. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  158012. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  158013. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  158014. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  158015. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  158016. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  158017. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  158018. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  158019. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  158020. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  158021. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  158022. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  158023. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  158024. {65313, 14, 26},
  158025. };
  158026. static const unsigned short aiOff[] = {
  158027. 1, 2, 8, 15, 16, 26, 28, 32,
  158028. 37, 38, 40, 48, 63, 64, 69, 71,
  158029. 79, 80, 116, 202, 203, 205, 206, 207,
  158030. 209, 210, 211, 213, 214, 217, 218, 219,
  158031. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  158032. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  158033. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  158034. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  158035. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  158036. 65514, 65521, 65527, 65528, 65529,
  158037. };
  158038. int ret = c;
  158039. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  158040. if( c<128 ){
  158041. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  158042. }else if( c<65536 ){
  158043. const struct TableEntry *p;
  158044. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  158045. int iLo = 0;
  158046. int iRes = -1;
  158047. assert( c>aEntry[0].iCode );
  158048. while( iHi>=iLo ){
  158049. int iTest = (iHi + iLo) / 2;
  158050. int cmp = (c - aEntry[iTest].iCode);
  158051. if( cmp>=0 ){
  158052. iRes = iTest;
  158053. iLo = iTest+1;
  158054. }else{
  158055. iHi = iTest-1;
  158056. }
  158057. }
  158058. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  158059. p = &aEntry[iRes];
  158060. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  158061. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  158062. assert( ret>0 );
  158063. }
  158064. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  158065. }
  158066. else if( c>=66560 && c<66600 ){
  158067. ret = c + 40;
  158068. }
  158069. return ret;
  158070. }
  158071. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  158072. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  158073. /************** End of fts3_unicode2.c ***************************************/
  158074. /************** Begin file rtree.c *******************************************/
  158075. /*
  158076. ** 2001 September 15
  158077. **
  158078. ** The author disclaims copyright to this source code. In place of
  158079. ** a legal notice, here is a blessing:
  158080. **
  158081. ** May you do good and not evil.
  158082. ** May you find forgiveness for yourself and forgive others.
  158083. ** May you share freely, never taking more than you give.
  158084. **
  158085. *************************************************************************
  158086. ** This file contains code for implementations of the r-tree and r*-tree
  158087. ** algorithms packaged as an SQLite virtual table module.
  158088. */
  158089. /*
  158090. ** Database Format of R-Tree Tables
  158091. ** --------------------------------
  158092. **
  158093. ** The data structure for a single virtual r-tree table is stored in three
  158094. ** native SQLite tables declared as follows. In each case, the '%' character
  158095. ** in the table name is replaced with the user-supplied name of the r-tree
  158096. ** table.
  158097. **
  158098. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  158099. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  158100. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  158101. **
  158102. ** The data for each node of the r-tree structure is stored in the %_node
  158103. ** table. For each node that is not the root node of the r-tree, there is
  158104. ** an entry in the %_parent table associating the node with its parent.
  158105. ** And for each row of data in the table, there is an entry in the %_rowid
  158106. ** table that maps from the entries rowid to the id of the node that it
  158107. ** is stored on.
  158108. **
  158109. ** The root node of an r-tree always exists, even if the r-tree table is
  158110. ** empty. The nodeno of the root node is always 1. All other nodes in the
  158111. ** table must be the same size as the root node. The content of each node
  158112. ** is formatted as follows:
  158113. **
  158114. ** 1. If the node is the root node (node 1), then the first 2 bytes
  158115. ** of the node contain the tree depth as a big-endian integer.
  158116. ** For non-root nodes, the first 2 bytes are left unused.
  158117. **
  158118. ** 2. The next 2 bytes contain the number of entries currently
  158119. ** stored in the node.
  158120. **
  158121. ** 3. The remainder of the node contains the node entries. Each entry
  158122. ** consists of a single 8-byte integer followed by an even number
  158123. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  158124. ** of a record. For internal nodes it is the node number of a
  158125. ** child page.
  158126. */
  158127. #if !defined(SQLITE_CORE) \
  158128. || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
  158129. #ifndef SQLITE_CORE
  158130. /* #include "sqlite3ext.h" */
  158131. SQLITE_EXTENSION_INIT1
  158132. #else
  158133. /* #include "sqlite3.h" */
  158134. #endif
  158135. /* #include <string.h> */
  158136. /* #include <assert.h> */
  158137. /* #include <stdio.h> */
  158138. #ifndef SQLITE_AMALGAMATION
  158139. #include "sqlite3rtree.h"
  158140. typedef sqlite3_int64 i64;
  158141. typedef sqlite3_uint64 u64;
  158142. typedef unsigned char u8;
  158143. typedef unsigned short u16;
  158144. typedef unsigned int u32;
  158145. #endif
  158146. /* The following macro is used to suppress compiler warnings.
  158147. */
  158148. #ifndef UNUSED_PARAMETER
  158149. # define UNUSED_PARAMETER(x) (void)(x)
  158150. #endif
  158151. typedef struct Rtree Rtree;
  158152. typedef struct RtreeCursor RtreeCursor;
  158153. typedef struct RtreeNode RtreeNode;
  158154. typedef struct RtreeCell RtreeCell;
  158155. typedef struct RtreeConstraint RtreeConstraint;
  158156. typedef struct RtreeMatchArg RtreeMatchArg;
  158157. typedef struct RtreeGeomCallback RtreeGeomCallback;
  158158. typedef union RtreeCoord RtreeCoord;
  158159. typedef struct RtreeSearchPoint RtreeSearchPoint;
  158160. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  158161. #define RTREE_MAX_DIMENSIONS 5
  158162. /* Size of hash table Rtree.aHash. This hash table is not expected to
  158163. ** ever contain very many entries, so a fixed number of buckets is
  158164. ** used.
  158165. */
  158166. #define HASHSIZE 97
  158167. /* The xBestIndex method of this virtual table requires an estimate of
  158168. ** the number of rows in the virtual table to calculate the costs of
  158169. ** various strategies. If possible, this estimate is loaded from the
  158170. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  158171. ** Otherwise, if no sqlite_stat1 entry is available, use
  158172. ** RTREE_DEFAULT_ROWEST.
  158173. */
  158174. #define RTREE_DEFAULT_ROWEST 1048576
  158175. #define RTREE_MIN_ROWEST 100
  158176. /*
  158177. ** An rtree virtual-table object.
  158178. */
  158179. struct Rtree {
  158180. sqlite3_vtab base; /* Base class. Must be first */
  158181. sqlite3 *db; /* Host database connection */
  158182. int iNodeSize; /* Size in bytes of each node in the node table */
  158183. u8 nDim; /* Number of dimensions */
  158184. u8 nDim2; /* Twice the number of dimensions */
  158185. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  158186. u8 nBytesPerCell; /* Bytes consumed per cell */
  158187. u8 inWrTrans; /* True if inside write transaction */
  158188. int iDepth; /* Current depth of the r-tree structure */
  158189. char *zDb; /* Name of database containing r-tree table */
  158190. char *zName; /* Name of r-tree table */
  158191. u32 nBusy; /* Current number of users of this structure */
  158192. i64 nRowEst; /* Estimated number of rows in this table */
  158193. u32 nCursor; /* Number of open cursors */
  158194. /* List of nodes removed during a CondenseTree operation. List is
  158195. ** linked together via the pointer normally used for hash chains -
  158196. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  158197. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  158198. */
  158199. RtreeNode *pDeleted;
  158200. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  158201. /* Blob I/O on xxx_node */
  158202. sqlite3_blob *pNodeBlob;
  158203. /* Statements to read/write/delete a record from xxx_node */
  158204. sqlite3_stmt *pWriteNode;
  158205. sqlite3_stmt *pDeleteNode;
  158206. /* Statements to read/write/delete a record from xxx_rowid */
  158207. sqlite3_stmt *pReadRowid;
  158208. sqlite3_stmt *pWriteRowid;
  158209. sqlite3_stmt *pDeleteRowid;
  158210. /* Statements to read/write/delete a record from xxx_parent */
  158211. sqlite3_stmt *pReadParent;
  158212. sqlite3_stmt *pWriteParent;
  158213. sqlite3_stmt *pDeleteParent;
  158214. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  158215. };
  158216. /* Possible values for Rtree.eCoordType: */
  158217. #define RTREE_COORD_REAL32 0
  158218. #define RTREE_COORD_INT32 1
  158219. /*
  158220. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  158221. ** only deal with integer coordinates. No floating point operations
  158222. ** will be done.
  158223. */
  158224. #ifdef SQLITE_RTREE_INT_ONLY
  158225. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  158226. typedef int RtreeValue; /* Low accuracy coordinate */
  158227. # define RTREE_ZERO 0
  158228. #else
  158229. typedef double RtreeDValue; /* High accuracy coordinate */
  158230. typedef float RtreeValue; /* Low accuracy coordinate */
  158231. # define RTREE_ZERO 0.0
  158232. #endif
  158233. /*
  158234. ** When doing a search of an r-tree, instances of the following structure
  158235. ** record intermediate results from the tree walk.
  158236. **
  158237. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  158238. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  158239. ** the id is of the parent node and the cell that RtreeSearchPoint
  158240. ** represents is the iCell-th entry in the parent node.
  158241. */
  158242. struct RtreeSearchPoint {
  158243. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  158244. sqlite3_int64 id; /* Node ID */
  158245. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  158246. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  158247. u8 iCell; /* Cell index within the node */
  158248. };
  158249. /*
  158250. ** The minimum number of cells allowed for a node is a third of the
  158251. ** maximum. In Gutman's notation:
  158252. **
  158253. ** m = M/3
  158254. **
  158255. ** If an R*-tree "Reinsert" operation is required, the same number of
  158256. ** cells are removed from the overfull node and reinserted into the tree.
  158257. */
  158258. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  158259. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  158260. #define RTREE_MAXCELLS 51
  158261. /*
  158262. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  158263. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  158264. ** Therefore all non-root nodes must contain at least 3 entries. Since
  158265. ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
  158266. ** 40 or less.
  158267. */
  158268. #define RTREE_MAX_DEPTH 40
  158269. /*
  158270. ** Number of entries in the cursor RtreeNode cache. The first entry is
  158271. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  158272. ** entries cache the RtreeNode for the first elements of the priority queue.
  158273. */
  158274. #define RTREE_CACHE_SZ 5
  158275. /*
  158276. ** An rtree cursor object.
  158277. */
  158278. struct RtreeCursor {
  158279. sqlite3_vtab_cursor base; /* Base class. Must be first */
  158280. u8 atEOF; /* True if at end of search */
  158281. u8 bPoint; /* True if sPoint is valid */
  158282. int iStrategy; /* Copy of idxNum search parameter */
  158283. int nConstraint; /* Number of entries in aConstraint */
  158284. RtreeConstraint *aConstraint; /* Search constraints. */
  158285. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  158286. int nPoint; /* Number of slots used in aPoint[] */
  158287. int mxLevel; /* iLevel value for root of the tree */
  158288. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  158289. RtreeSearchPoint sPoint; /* Cached next search point */
  158290. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  158291. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  158292. };
  158293. /* Return the Rtree of a RtreeCursor */
  158294. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  158295. /*
  158296. ** A coordinate can be either a floating point number or a integer. All
  158297. ** coordinates within a single R-Tree are always of the same time.
  158298. */
  158299. union RtreeCoord {
  158300. RtreeValue f; /* Floating point value */
  158301. int i; /* Integer value */
  158302. u32 u; /* Unsigned for byte-order conversions */
  158303. };
  158304. /*
  158305. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  158306. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  158307. ** variable pRtree points to the Rtree structure associated with the
  158308. ** RtreeCoord.
  158309. */
  158310. #ifdef SQLITE_RTREE_INT_ONLY
  158311. # define DCOORD(coord) ((RtreeDValue)coord.i)
  158312. #else
  158313. # define DCOORD(coord) ( \
  158314. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  158315. ((double)coord.f) : \
  158316. ((double)coord.i) \
  158317. )
  158318. #endif
  158319. /*
  158320. ** A search constraint.
  158321. */
  158322. struct RtreeConstraint {
  158323. int iCoord; /* Index of constrained coordinate */
  158324. int op; /* Constraining operation */
  158325. union {
  158326. RtreeDValue rValue; /* Constraint value. */
  158327. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  158328. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  158329. } u;
  158330. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  158331. };
  158332. /* Possible values for RtreeConstraint.op */
  158333. #define RTREE_EQ 0x41 /* A */
  158334. #define RTREE_LE 0x42 /* B */
  158335. #define RTREE_LT 0x43 /* C */
  158336. #define RTREE_GE 0x44 /* D */
  158337. #define RTREE_GT 0x45 /* E */
  158338. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  158339. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  158340. /*
  158341. ** An rtree structure node.
  158342. */
  158343. struct RtreeNode {
  158344. RtreeNode *pParent; /* Parent node */
  158345. i64 iNode; /* The node number */
  158346. int nRef; /* Number of references to this node */
  158347. int isDirty; /* True if the node needs to be written to disk */
  158348. u8 *zData; /* Content of the node, as should be on disk */
  158349. RtreeNode *pNext; /* Next node in this hash collision chain */
  158350. };
  158351. /* Return the number of cells in a node */
  158352. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  158353. /*
  158354. ** A single cell from a node, deserialized
  158355. */
  158356. struct RtreeCell {
  158357. i64 iRowid; /* Node or entry ID */
  158358. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  158359. };
  158360. /*
  158361. ** This object becomes the sqlite3_user_data() for the SQL functions
  158362. ** that are created by sqlite3_rtree_geometry_callback() and
  158363. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  158364. ** operators in order to constrain a search.
  158365. **
  158366. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  158367. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  158368. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  158369. ** sqlite3_rtree_query_callback().
  158370. **
  158371. ** This object is deleted automatically by the destructor mechanism in
  158372. ** sqlite3_create_function_v2().
  158373. */
  158374. struct RtreeGeomCallback {
  158375. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  158376. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  158377. void (*xDestructor)(void*);
  158378. void *pContext;
  158379. };
  158380. /*
  158381. ** An instance of this structure (in the form of a BLOB) is returned by
  158382. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  158383. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  158384. ** operand to the MATCH operator of an R-Tree.
  158385. */
  158386. struct RtreeMatchArg {
  158387. u32 iSize; /* Size of this object */
  158388. RtreeGeomCallback cb; /* Info about the callback functions */
  158389. int nParam; /* Number of parameters to the SQL function */
  158390. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  158391. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  158392. };
  158393. #ifndef MAX
  158394. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  158395. #endif
  158396. #ifndef MIN
  158397. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  158398. #endif
  158399. /* What version of GCC is being used. 0 means GCC is not being used .
  158400. ** Note that the GCC_VERSION macro will also be set correctly when using
  158401. ** clang, since clang works hard to be gcc compatible. So the gcc
  158402. ** optimizations will also work when compiling with clang.
  158403. */
  158404. #ifndef GCC_VERSION
  158405. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  158406. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  158407. #else
  158408. # define GCC_VERSION 0
  158409. #endif
  158410. #endif
  158411. /* The testcase() macro should already be defined in the amalgamation. If
  158412. ** it is not, make it a no-op.
  158413. */
  158414. #ifndef SQLITE_AMALGAMATION
  158415. # define testcase(X)
  158416. #endif
  158417. /*
  158418. ** Macros to determine whether the machine is big or little endian,
  158419. ** and whether or not that determination is run-time or compile-time.
  158420. **
  158421. ** For best performance, an attempt is made to guess at the byte-order
  158422. ** using C-preprocessor macros. If that is unsuccessful, or if
  158423. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  158424. ** at run-time.
  158425. */
  158426. #ifndef SQLITE_BYTEORDER
  158427. #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  158428. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  158429. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  158430. defined(__arm__)
  158431. # define SQLITE_BYTEORDER 1234
  158432. #elif defined(sparc) || defined(__ppc__)
  158433. # define SQLITE_BYTEORDER 4321
  158434. #else
  158435. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  158436. #endif
  158437. #endif
  158438. /* What version of MSVC is being used. 0 means MSVC is not being used */
  158439. #ifndef MSVC_VERSION
  158440. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  158441. # define MSVC_VERSION _MSC_VER
  158442. #else
  158443. # define MSVC_VERSION 0
  158444. #endif
  158445. #endif
  158446. /*
  158447. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  158448. ** 64 bit integer. The deserialized value is returned.
  158449. */
  158450. static int readInt16(u8 *p){
  158451. return (p[0]<<8) + p[1];
  158452. }
  158453. static void readCoord(u8 *p, RtreeCoord *pCoord){
  158454. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  158455. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  158456. pCoord->u = _byteswap_ulong(*(u32*)p);
  158457. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  158458. pCoord->u = __builtin_bswap32(*(u32*)p);
  158459. #elif SQLITE_BYTEORDER==4321
  158460. pCoord->u = *(u32*)p;
  158461. #else
  158462. pCoord->u = (
  158463. (((u32)p[0]) << 24) +
  158464. (((u32)p[1]) << 16) +
  158465. (((u32)p[2]) << 8) +
  158466. (((u32)p[3]) << 0)
  158467. );
  158468. #endif
  158469. }
  158470. static i64 readInt64(u8 *p){
  158471. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  158472. u64 x;
  158473. memcpy(&x, p, 8);
  158474. return (i64)_byteswap_uint64(x);
  158475. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  158476. u64 x;
  158477. memcpy(&x, p, 8);
  158478. return (i64)__builtin_bswap64(x);
  158479. #elif SQLITE_BYTEORDER==4321
  158480. i64 x;
  158481. memcpy(&x, p, 8);
  158482. return x;
  158483. #else
  158484. return (i64)(
  158485. (((u64)p[0]) << 56) +
  158486. (((u64)p[1]) << 48) +
  158487. (((u64)p[2]) << 40) +
  158488. (((u64)p[3]) << 32) +
  158489. (((u64)p[4]) << 24) +
  158490. (((u64)p[5]) << 16) +
  158491. (((u64)p[6]) << 8) +
  158492. (((u64)p[7]) << 0)
  158493. );
  158494. #endif
  158495. }
  158496. /*
  158497. ** Functions to serialize a 16 bit integer, 32 bit real number and
  158498. ** 64 bit integer. The value returned is the number of bytes written
  158499. ** to the argument buffer (always 2, 4 and 8 respectively).
  158500. */
  158501. static void writeInt16(u8 *p, int i){
  158502. p[0] = (i>> 8)&0xFF;
  158503. p[1] = (i>> 0)&0xFF;
  158504. }
  158505. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  158506. u32 i;
  158507. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  158508. assert( sizeof(RtreeCoord)==4 );
  158509. assert( sizeof(u32)==4 );
  158510. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  158511. i = __builtin_bswap32(pCoord->u);
  158512. memcpy(p, &i, 4);
  158513. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  158514. i = _byteswap_ulong(pCoord->u);
  158515. memcpy(p, &i, 4);
  158516. #elif SQLITE_BYTEORDER==4321
  158517. i = pCoord->u;
  158518. memcpy(p, &i, 4);
  158519. #else
  158520. i = pCoord->u;
  158521. p[0] = (i>>24)&0xFF;
  158522. p[1] = (i>>16)&0xFF;
  158523. p[2] = (i>> 8)&0xFF;
  158524. p[3] = (i>> 0)&0xFF;
  158525. #endif
  158526. return 4;
  158527. }
  158528. static int writeInt64(u8 *p, i64 i){
  158529. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  158530. i = (i64)__builtin_bswap64((u64)i);
  158531. memcpy(p, &i, 8);
  158532. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  158533. i = (i64)_byteswap_uint64((u64)i);
  158534. memcpy(p, &i, 8);
  158535. #elif SQLITE_BYTEORDER==4321
  158536. memcpy(p, &i, 8);
  158537. #else
  158538. p[0] = (i>>56)&0xFF;
  158539. p[1] = (i>>48)&0xFF;
  158540. p[2] = (i>>40)&0xFF;
  158541. p[3] = (i>>32)&0xFF;
  158542. p[4] = (i>>24)&0xFF;
  158543. p[5] = (i>>16)&0xFF;
  158544. p[6] = (i>> 8)&0xFF;
  158545. p[7] = (i>> 0)&0xFF;
  158546. #endif
  158547. return 8;
  158548. }
  158549. /*
  158550. ** Increment the reference count of node p.
  158551. */
  158552. static void nodeReference(RtreeNode *p){
  158553. if( p ){
  158554. p->nRef++;
  158555. }
  158556. }
  158557. /*
  158558. ** Clear the content of node p (set all bytes to 0x00).
  158559. */
  158560. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  158561. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  158562. p->isDirty = 1;
  158563. }
  158564. /*
  158565. ** Given a node number iNode, return the corresponding key to use
  158566. ** in the Rtree.aHash table.
  158567. */
  158568. static int nodeHash(i64 iNode){
  158569. return iNode % HASHSIZE;
  158570. }
  158571. /*
  158572. ** Search the node hash table for node iNode. If found, return a pointer
  158573. ** to it. Otherwise, return 0.
  158574. */
  158575. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  158576. RtreeNode *p;
  158577. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  158578. return p;
  158579. }
  158580. /*
  158581. ** Add node pNode to the node hash table.
  158582. */
  158583. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  158584. int iHash;
  158585. assert( pNode->pNext==0 );
  158586. iHash = nodeHash(pNode->iNode);
  158587. pNode->pNext = pRtree->aHash[iHash];
  158588. pRtree->aHash[iHash] = pNode;
  158589. }
  158590. /*
  158591. ** Remove node pNode from the node hash table.
  158592. */
  158593. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  158594. RtreeNode **pp;
  158595. if( pNode->iNode!=0 ){
  158596. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  158597. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  158598. *pp = pNode->pNext;
  158599. pNode->pNext = 0;
  158600. }
  158601. }
  158602. /*
  158603. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  158604. ** indicating that node has not yet been assigned a node number. It is
  158605. ** assigned a node number when nodeWrite() is called to write the
  158606. ** node contents out to the database.
  158607. */
  158608. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  158609. RtreeNode *pNode;
  158610. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  158611. if( pNode ){
  158612. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  158613. pNode->zData = (u8 *)&pNode[1];
  158614. pNode->nRef = 1;
  158615. pNode->pParent = pParent;
  158616. pNode->isDirty = 1;
  158617. nodeReference(pParent);
  158618. }
  158619. return pNode;
  158620. }
  158621. /*
  158622. ** Clear the Rtree.pNodeBlob object
  158623. */
  158624. static void nodeBlobReset(Rtree *pRtree){
  158625. if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
  158626. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  158627. pRtree->pNodeBlob = 0;
  158628. sqlite3_blob_close(pBlob);
  158629. }
  158630. }
  158631. /*
  158632. ** Obtain a reference to an r-tree node.
  158633. */
  158634. static int nodeAcquire(
  158635. Rtree *pRtree, /* R-tree structure */
  158636. i64 iNode, /* Node number to load */
  158637. RtreeNode *pParent, /* Either the parent node or NULL */
  158638. RtreeNode **ppNode /* OUT: Acquired node */
  158639. ){
  158640. int rc = SQLITE_OK;
  158641. RtreeNode *pNode = 0;
  158642. /* Check if the requested node is already in the hash table. If so,
  158643. ** increase its reference count and return it.
  158644. */
  158645. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  158646. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  158647. if( pParent && !pNode->pParent ){
  158648. nodeReference(pParent);
  158649. pNode->pParent = pParent;
  158650. }
  158651. pNode->nRef++;
  158652. *ppNode = pNode;
  158653. return SQLITE_OK;
  158654. }
  158655. if( pRtree->pNodeBlob ){
  158656. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  158657. pRtree->pNodeBlob = 0;
  158658. rc = sqlite3_blob_reopen(pBlob, iNode);
  158659. pRtree->pNodeBlob = pBlob;
  158660. if( rc ){
  158661. nodeBlobReset(pRtree);
  158662. if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
  158663. }
  158664. }
  158665. if( pRtree->pNodeBlob==0 ){
  158666. char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
  158667. if( zTab==0 ) return SQLITE_NOMEM;
  158668. rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
  158669. &pRtree->pNodeBlob);
  158670. sqlite3_free(zTab);
  158671. }
  158672. if( rc ){
  158673. nodeBlobReset(pRtree);
  158674. *ppNode = 0;
  158675. /* If unable to open an sqlite3_blob on the desired row, that can only
  158676. ** be because the shadow tables hold erroneous data. */
  158677. if( rc==SQLITE_ERROR ) rc = SQLITE_CORRUPT_VTAB;
  158678. }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
  158679. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  158680. if( !pNode ){
  158681. rc = SQLITE_NOMEM;
  158682. }else{
  158683. pNode->pParent = pParent;
  158684. pNode->zData = (u8 *)&pNode[1];
  158685. pNode->nRef = 1;
  158686. pNode->iNode = iNode;
  158687. pNode->isDirty = 0;
  158688. pNode->pNext = 0;
  158689. rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
  158690. pRtree->iNodeSize, 0);
  158691. nodeReference(pParent);
  158692. }
  158693. }
  158694. /* If the root node was just loaded, set pRtree->iDepth to the height
  158695. ** of the r-tree structure. A height of zero means all data is stored on
  158696. ** the root node. A height of one means the children of the root node
  158697. ** are the leaves, and so on. If the depth as specified on the root node
  158698. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  158699. */
  158700. if( pNode && iNode==1 ){
  158701. pRtree->iDepth = readInt16(pNode->zData);
  158702. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  158703. rc = SQLITE_CORRUPT_VTAB;
  158704. }
  158705. }
  158706. /* If no error has occurred so far, check if the "number of entries"
  158707. ** field on the node is too large. If so, set the return code to
  158708. ** SQLITE_CORRUPT_VTAB.
  158709. */
  158710. if( pNode && rc==SQLITE_OK ){
  158711. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  158712. rc = SQLITE_CORRUPT_VTAB;
  158713. }
  158714. }
  158715. if( rc==SQLITE_OK ){
  158716. if( pNode!=0 ){
  158717. nodeHashInsert(pRtree, pNode);
  158718. }else{
  158719. rc = SQLITE_CORRUPT_VTAB;
  158720. }
  158721. *ppNode = pNode;
  158722. }else{
  158723. sqlite3_free(pNode);
  158724. *ppNode = 0;
  158725. }
  158726. return rc;
  158727. }
  158728. /*
  158729. ** Overwrite cell iCell of node pNode with the contents of pCell.
  158730. */
  158731. static void nodeOverwriteCell(
  158732. Rtree *pRtree, /* The overall R-Tree */
  158733. RtreeNode *pNode, /* The node into which the cell is to be written */
  158734. RtreeCell *pCell, /* The cell to write */
  158735. int iCell /* Index into pNode into which pCell is written */
  158736. ){
  158737. int ii;
  158738. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  158739. p += writeInt64(p, pCell->iRowid);
  158740. for(ii=0; ii<pRtree->nDim2; ii++){
  158741. p += writeCoord(p, &pCell->aCoord[ii]);
  158742. }
  158743. pNode->isDirty = 1;
  158744. }
  158745. /*
  158746. ** Remove the cell with index iCell from node pNode.
  158747. */
  158748. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  158749. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  158750. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  158751. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  158752. memmove(pDst, pSrc, nByte);
  158753. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  158754. pNode->isDirty = 1;
  158755. }
  158756. /*
  158757. ** Insert the contents of cell pCell into node pNode. If the insert
  158758. ** is successful, return SQLITE_OK.
  158759. **
  158760. ** If there is not enough free space in pNode, return SQLITE_FULL.
  158761. */
  158762. static int nodeInsertCell(
  158763. Rtree *pRtree, /* The overall R-Tree */
  158764. RtreeNode *pNode, /* Write new cell into this node */
  158765. RtreeCell *pCell /* The cell to be inserted */
  158766. ){
  158767. int nCell; /* Current number of cells in pNode */
  158768. int nMaxCell; /* Maximum number of cells for pNode */
  158769. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  158770. nCell = NCELL(pNode);
  158771. assert( nCell<=nMaxCell );
  158772. if( nCell<nMaxCell ){
  158773. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  158774. writeInt16(&pNode->zData[2], nCell+1);
  158775. pNode->isDirty = 1;
  158776. }
  158777. return (nCell==nMaxCell);
  158778. }
  158779. /*
  158780. ** If the node is dirty, write it out to the database.
  158781. */
  158782. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  158783. int rc = SQLITE_OK;
  158784. if( pNode->isDirty ){
  158785. sqlite3_stmt *p = pRtree->pWriteNode;
  158786. if( pNode->iNode ){
  158787. sqlite3_bind_int64(p, 1, pNode->iNode);
  158788. }else{
  158789. sqlite3_bind_null(p, 1);
  158790. }
  158791. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  158792. sqlite3_step(p);
  158793. pNode->isDirty = 0;
  158794. rc = sqlite3_reset(p);
  158795. sqlite3_bind_null(p, 2);
  158796. if( pNode->iNode==0 && rc==SQLITE_OK ){
  158797. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  158798. nodeHashInsert(pRtree, pNode);
  158799. }
  158800. }
  158801. return rc;
  158802. }
  158803. /*
  158804. ** Release a reference to a node. If the node is dirty and the reference
  158805. ** count drops to zero, the node data is written to the database.
  158806. */
  158807. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  158808. int rc = SQLITE_OK;
  158809. if( pNode ){
  158810. assert( pNode->nRef>0 );
  158811. pNode->nRef--;
  158812. if( pNode->nRef==0 ){
  158813. if( pNode->iNode==1 ){
  158814. pRtree->iDepth = -1;
  158815. }
  158816. if( pNode->pParent ){
  158817. rc = nodeRelease(pRtree, pNode->pParent);
  158818. }
  158819. if( rc==SQLITE_OK ){
  158820. rc = nodeWrite(pRtree, pNode);
  158821. }
  158822. nodeHashDelete(pRtree, pNode);
  158823. sqlite3_free(pNode);
  158824. }
  158825. }
  158826. return rc;
  158827. }
  158828. /*
  158829. ** Return the 64-bit integer value associated with cell iCell of
  158830. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  158831. ** an internal node, then the 64-bit integer is a child page number.
  158832. */
  158833. static i64 nodeGetRowid(
  158834. Rtree *pRtree, /* The overall R-Tree */
  158835. RtreeNode *pNode, /* The node from which to extract the ID */
  158836. int iCell /* The cell index from which to extract the ID */
  158837. ){
  158838. assert( iCell<NCELL(pNode) );
  158839. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  158840. }
  158841. /*
  158842. ** Return coordinate iCoord from cell iCell in node pNode.
  158843. */
  158844. static void nodeGetCoord(
  158845. Rtree *pRtree, /* The overall R-Tree */
  158846. RtreeNode *pNode, /* The node from which to extract a coordinate */
  158847. int iCell, /* The index of the cell within the node */
  158848. int iCoord, /* Which coordinate to extract */
  158849. RtreeCoord *pCoord /* OUT: Space to write result to */
  158850. ){
  158851. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  158852. }
  158853. /*
  158854. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  158855. ** to by pCell with the results.
  158856. */
  158857. static void nodeGetCell(
  158858. Rtree *pRtree, /* The overall R-Tree */
  158859. RtreeNode *pNode, /* The node containing the cell to be read */
  158860. int iCell, /* Index of the cell within the node */
  158861. RtreeCell *pCell /* OUT: Write the cell contents here */
  158862. ){
  158863. u8 *pData;
  158864. RtreeCoord *pCoord;
  158865. int ii = 0;
  158866. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  158867. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  158868. pCoord = pCell->aCoord;
  158869. do{
  158870. readCoord(pData, &pCoord[ii]);
  158871. readCoord(pData+4, &pCoord[ii+1]);
  158872. pData += 8;
  158873. ii += 2;
  158874. }while( ii<pRtree->nDim2 );
  158875. }
  158876. /* Forward declaration for the function that does the work of
  158877. ** the virtual table module xCreate() and xConnect() methods.
  158878. */
  158879. static int rtreeInit(
  158880. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  158881. );
  158882. /*
  158883. ** Rtree virtual table module xCreate method.
  158884. */
  158885. static int rtreeCreate(
  158886. sqlite3 *db,
  158887. void *pAux,
  158888. int argc, const char *const*argv,
  158889. sqlite3_vtab **ppVtab,
  158890. char **pzErr
  158891. ){
  158892. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  158893. }
  158894. /*
  158895. ** Rtree virtual table module xConnect method.
  158896. */
  158897. static int rtreeConnect(
  158898. sqlite3 *db,
  158899. void *pAux,
  158900. int argc, const char *const*argv,
  158901. sqlite3_vtab **ppVtab,
  158902. char **pzErr
  158903. ){
  158904. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  158905. }
  158906. /*
  158907. ** Increment the r-tree reference count.
  158908. */
  158909. static void rtreeReference(Rtree *pRtree){
  158910. pRtree->nBusy++;
  158911. }
  158912. /*
  158913. ** Decrement the r-tree reference count. When the reference count reaches
  158914. ** zero the structure is deleted.
  158915. */
  158916. static void rtreeRelease(Rtree *pRtree){
  158917. pRtree->nBusy--;
  158918. if( pRtree->nBusy==0 ){
  158919. pRtree->inWrTrans = 0;
  158920. pRtree->nCursor = 0;
  158921. nodeBlobReset(pRtree);
  158922. sqlite3_finalize(pRtree->pWriteNode);
  158923. sqlite3_finalize(pRtree->pDeleteNode);
  158924. sqlite3_finalize(pRtree->pReadRowid);
  158925. sqlite3_finalize(pRtree->pWriteRowid);
  158926. sqlite3_finalize(pRtree->pDeleteRowid);
  158927. sqlite3_finalize(pRtree->pReadParent);
  158928. sqlite3_finalize(pRtree->pWriteParent);
  158929. sqlite3_finalize(pRtree->pDeleteParent);
  158930. sqlite3_free(pRtree);
  158931. }
  158932. }
  158933. /*
  158934. ** Rtree virtual table module xDisconnect method.
  158935. */
  158936. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  158937. rtreeRelease((Rtree *)pVtab);
  158938. return SQLITE_OK;
  158939. }
  158940. /*
  158941. ** Rtree virtual table module xDestroy method.
  158942. */
  158943. static int rtreeDestroy(sqlite3_vtab *pVtab){
  158944. Rtree *pRtree = (Rtree *)pVtab;
  158945. int rc;
  158946. char *zCreate = sqlite3_mprintf(
  158947. "DROP TABLE '%q'.'%q_node';"
  158948. "DROP TABLE '%q'.'%q_rowid';"
  158949. "DROP TABLE '%q'.'%q_parent';",
  158950. pRtree->zDb, pRtree->zName,
  158951. pRtree->zDb, pRtree->zName,
  158952. pRtree->zDb, pRtree->zName
  158953. );
  158954. if( !zCreate ){
  158955. rc = SQLITE_NOMEM;
  158956. }else{
  158957. nodeBlobReset(pRtree);
  158958. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  158959. sqlite3_free(zCreate);
  158960. }
  158961. if( rc==SQLITE_OK ){
  158962. rtreeRelease(pRtree);
  158963. }
  158964. return rc;
  158965. }
  158966. /*
  158967. ** Rtree virtual table module xOpen method.
  158968. */
  158969. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  158970. int rc = SQLITE_NOMEM;
  158971. Rtree *pRtree = (Rtree *)pVTab;
  158972. RtreeCursor *pCsr;
  158973. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  158974. if( pCsr ){
  158975. memset(pCsr, 0, sizeof(RtreeCursor));
  158976. pCsr->base.pVtab = pVTab;
  158977. rc = SQLITE_OK;
  158978. pRtree->nCursor++;
  158979. }
  158980. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  158981. return rc;
  158982. }
  158983. /*
  158984. ** Free the RtreeCursor.aConstraint[] array and its contents.
  158985. */
  158986. static void freeCursorConstraints(RtreeCursor *pCsr){
  158987. if( pCsr->aConstraint ){
  158988. int i; /* Used to iterate through constraint array */
  158989. for(i=0; i<pCsr->nConstraint; i++){
  158990. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  158991. if( pInfo ){
  158992. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  158993. sqlite3_free(pInfo);
  158994. }
  158995. }
  158996. sqlite3_free(pCsr->aConstraint);
  158997. pCsr->aConstraint = 0;
  158998. }
  158999. }
  159000. /*
  159001. ** Rtree virtual table module xClose method.
  159002. */
  159003. static int rtreeClose(sqlite3_vtab_cursor *cur){
  159004. Rtree *pRtree = (Rtree *)(cur->pVtab);
  159005. int ii;
  159006. RtreeCursor *pCsr = (RtreeCursor *)cur;
  159007. assert( pRtree->nCursor>0 );
  159008. freeCursorConstraints(pCsr);
  159009. sqlite3_free(pCsr->aPoint);
  159010. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  159011. sqlite3_free(pCsr);
  159012. pRtree->nCursor--;
  159013. nodeBlobReset(pRtree);
  159014. return SQLITE_OK;
  159015. }
  159016. /*
  159017. ** Rtree virtual table module xEof method.
  159018. **
  159019. ** Return non-zero if the cursor does not currently point to a valid
  159020. ** record (i.e if the scan has finished), or zero otherwise.
  159021. */
  159022. static int rtreeEof(sqlite3_vtab_cursor *cur){
  159023. RtreeCursor *pCsr = (RtreeCursor *)cur;
  159024. return pCsr->atEOF;
  159025. }
  159026. /*
  159027. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  159028. ** The on-disk format is big-endian and needs to be converted for little-
  159029. ** endian platforms. The on-disk record stores integer coordinates if
  159030. ** eInt is true and it stores 32-bit floating point records if eInt is
  159031. ** false. a[] is the four bytes of the on-disk record to be decoded.
  159032. ** Store the results in "r".
  159033. **
  159034. ** There are five versions of this macro. The last one is generic. The
  159035. ** other four are various architectures-specific optimizations.
  159036. */
  159037. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  159038. #define RTREE_DECODE_COORD(eInt, a, r) { \
  159039. RtreeCoord c; /* Coordinate decoded */ \
  159040. c.u = _byteswap_ulong(*(u32*)a); \
  159041. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  159042. }
  159043. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  159044. #define RTREE_DECODE_COORD(eInt, a, r) { \
  159045. RtreeCoord c; /* Coordinate decoded */ \
  159046. c.u = __builtin_bswap32(*(u32*)a); \
  159047. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  159048. }
  159049. #elif SQLITE_BYTEORDER==1234
  159050. #define RTREE_DECODE_COORD(eInt, a, r) { \
  159051. RtreeCoord c; /* Coordinate decoded */ \
  159052. memcpy(&c.u,a,4); \
  159053. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  159054. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  159055. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  159056. }
  159057. #elif SQLITE_BYTEORDER==4321
  159058. #define RTREE_DECODE_COORD(eInt, a, r) { \
  159059. RtreeCoord c; /* Coordinate decoded */ \
  159060. memcpy(&c.u,a,4); \
  159061. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  159062. }
  159063. #else
  159064. #define RTREE_DECODE_COORD(eInt, a, r) { \
  159065. RtreeCoord c; /* Coordinate decoded */ \
  159066. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  159067. +((u32)a[2]<<8) + a[3]; \
  159068. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  159069. }
  159070. #endif
  159071. /*
  159072. ** Check the RTree node or entry given by pCellData and p against the MATCH
  159073. ** constraint pConstraint.
  159074. */
  159075. static int rtreeCallbackConstraint(
  159076. RtreeConstraint *pConstraint, /* The constraint to test */
  159077. int eInt, /* True if RTree holding integer coordinates */
  159078. u8 *pCellData, /* Raw cell content */
  159079. RtreeSearchPoint *pSearch, /* Container of this cell */
  159080. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  159081. int *peWithin /* OUT: visibility of the cell */
  159082. ){
  159083. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  159084. int nCoord = pInfo->nCoord; /* No. of coordinates */
  159085. int rc; /* Callback return code */
  159086. RtreeCoord c; /* Translator union */
  159087. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  159088. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  159089. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  159090. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  159091. pInfo->iRowid = readInt64(pCellData);
  159092. }
  159093. pCellData += 8;
  159094. #ifndef SQLITE_RTREE_INT_ONLY
  159095. if( eInt==0 ){
  159096. switch( nCoord ){
  159097. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
  159098. readCoord(pCellData+32, &c); aCoord[8] = c.f;
  159099. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
  159100. readCoord(pCellData+24, &c); aCoord[6] = c.f;
  159101. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
  159102. readCoord(pCellData+16, &c); aCoord[4] = c.f;
  159103. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
  159104. readCoord(pCellData+8, &c); aCoord[2] = c.f;
  159105. default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
  159106. readCoord(pCellData, &c); aCoord[0] = c.f;
  159107. }
  159108. }else
  159109. #endif
  159110. {
  159111. switch( nCoord ){
  159112. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
  159113. readCoord(pCellData+32, &c); aCoord[8] = c.i;
  159114. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
  159115. readCoord(pCellData+24, &c); aCoord[6] = c.i;
  159116. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
  159117. readCoord(pCellData+16, &c); aCoord[4] = c.i;
  159118. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
  159119. readCoord(pCellData+8, &c); aCoord[2] = c.i;
  159120. default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
  159121. readCoord(pCellData, &c); aCoord[0] = c.i;
  159122. }
  159123. }
  159124. if( pConstraint->op==RTREE_MATCH ){
  159125. int eWithin = 0;
  159126. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  159127. nCoord, aCoord, &eWithin);
  159128. if( eWithin==0 ) *peWithin = NOT_WITHIN;
  159129. *prScore = RTREE_ZERO;
  159130. }else{
  159131. pInfo->aCoord = aCoord;
  159132. pInfo->iLevel = pSearch->iLevel - 1;
  159133. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  159134. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  159135. rc = pConstraint->u.xQueryFunc(pInfo);
  159136. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  159137. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  159138. *prScore = pInfo->rScore;
  159139. }
  159140. }
  159141. return rc;
  159142. }
  159143. /*
  159144. ** Check the internal RTree node given by pCellData against constraint p.
  159145. ** If this constraint cannot be satisfied by any child within the node,
  159146. ** set *peWithin to NOT_WITHIN.
  159147. */
  159148. static void rtreeNonleafConstraint(
  159149. RtreeConstraint *p, /* The constraint to test */
  159150. int eInt, /* True if RTree holds integer coordinates */
  159151. u8 *pCellData, /* Raw cell content as appears on disk */
  159152. int *peWithin /* Adjust downward, as appropriate */
  159153. ){
  159154. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  159155. /* p->iCoord might point to either a lower or upper bound coordinate
  159156. ** in a coordinate pair. But make pCellData point to the lower bound.
  159157. */
  159158. pCellData += 8 + 4*(p->iCoord&0xfe);
  159159. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  159160. || p->op==RTREE_GT || p->op==RTREE_EQ );
  159161. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  159162. switch( p->op ){
  159163. case RTREE_LE:
  159164. case RTREE_LT:
  159165. case RTREE_EQ:
  159166. RTREE_DECODE_COORD(eInt, pCellData, val);
  159167. /* val now holds the lower bound of the coordinate pair */
  159168. if( p->u.rValue>=val ) return;
  159169. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  159170. /* Fall through for the RTREE_EQ case */
  159171. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  159172. pCellData += 4;
  159173. RTREE_DECODE_COORD(eInt, pCellData, val);
  159174. /* val now holds the upper bound of the coordinate pair */
  159175. if( p->u.rValue<=val ) return;
  159176. }
  159177. *peWithin = NOT_WITHIN;
  159178. }
  159179. /*
  159180. ** Check the leaf RTree cell given by pCellData against constraint p.
  159181. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  159182. ** If the constraint is satisfied, leave *peWithin unchanged.
  159183. **
  159184. ** The constraint is of the form: xN op $val
  159185. **
  159186. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  159187. ** pCellData. $val is given by p->u.rValue.
  159188. */
  159189. static void rtreeLeafConstraint(
  159190. RtreeConstraint *p, /* The constraint to test */
  159191. int eInt, /* True if RTree holds integer coordinates */
  159192. u8 *pCellData, /* Raw cell content as appears on disk */
  159193. int *peWithin /* Adjust downward, as appropriate */
  159194. ){
  159195. RtreeDValue xN; /* Coordinate value converted to a double */
  159196. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  159197. || p->op==RTREE_GT || p->op==RTREE_EQ );
  159198. pCellData += 8 + p->iCoord*4;
  159199. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  159200. RTREE_DECODE_COORD(eInt, pCellData, xN);
  159201. switch( p->op ){
  159202. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  159203. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  159204. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  159205. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  159206. default: if( xN == p->u.rValue ) return; break;
  159207. }
  159208. *peWithin = NOT_WITHIN;
  159209. }
  159210. /*
  159211. ** One of the cells in node pNode is guaranteed to have a 64-bit
  159212. ** integer value equal to iRowid. Return the index of this cell.
  159213. */
  159214. static int nodeRowidIndex(
  159215. Rtree *pRtree,
  159216. RtreeNode *pNode,
  159217. i64 iRowid,
  159218. int *piIndex
  159219. ){
  159220. int ii;
  159221. int nCell = NCELL(pNode);
  159222. assert( nCell<200 );
  159223. for(ii=0; ii<nCell; ii++){
  159224. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  159225. *piIndex = ii;
  159226. return SQLITE_OK;
  159227. }
  159228. }
  159229. return SQLITE_CORRUPT_VTAB;
  159230. }
  159231. /*
  159232. ** Return the index of the cell containing a pointer to node pNode
  159233. ** in its parent. If pNode is the root node, return -1.
  159234. */
  159235. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  159236. RtreeNode *pParent = pNode->pParent;
  159237. if( pParent ){
  159238. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  159239. }
  159240. *piIndex = -1;
  159241. return SQLITE_OK;
  159242. }
  159243. /*
  159244. ** Compare two search points. Return negative, zero, or positive if the first
  159245. ** is less than, equal to, or greater than the second.
  159246. **
  159247. ** The rScore is the primary key. Smaller rScore values come first.
  159248. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  159249. ** iLevel values coming first. In this way, if rScore is the same for all
  159250. ** SearchPoints, then iLevel becomes the deciding factor and the result
  159251. ** is a depth-first search, which is the desired default behavior.
  159252. */
  159253. static int rtreeSearchPointCompare(
  159254. const RtreeSearchPoint *pA,
  159255. const RtreeSearchPoint *pB
  159256. ){
  159257. if( pA->rScore<pB->rScore ) return -1;
  159258. if( pA->rScore>pB->rScore ) return +1;
  159259. if( pA->iLevel<pB->iLevel ) return -1;
  159260. if( pA->iLevel>pB->iLevel ) return +1;
  159261. return 0;
  159262. }
  159263. /*
  159264. ** Interchange two search points in a cursor.
  159265. */
  159266. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  159267. RtreeSearchPoint t = p->aPoint[i];
  159268. assert( i<j );
  159269. p->aPoint[i] = p->aPoint[j];
  159270. p->aPoint[j] = t;
  159271. i++; j++;
  159272. if( i<RTREE_CACHE_SZ ){
  159273. if( j>=RTREE_CACHE_SZ ){
  159274. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  159275. p->aNode[i] = 0;
  159276. }else{
  159277. RtreeNode *pTemp = p->aNode[i];
  159278. p->aNode[i] = p->aNode[j];
  159279. p->aNode[j] = pTemp;
  159280. }
  159281. }
  159282. }
  159283. /*
  159284. ** Return the search point with the lowest current score.
  159285. */
  159286. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  159287. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  159288. }
  159289. /*
  159290. ** Get the RtreeNode for the search point with the lowest score.
  159291. */
  159292. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  159293. sqlite3_int64 id;
  159294. int ii = 1 - pCur->bPoint;
  159295. assert( ii==0 || ii==1 );
  159296. assert( pCur->bPoint || pCur->nPoint );
  159297. if( pCur->aNode[ii]==0 ){
  159298. assert( pRC!=0 );
  159299. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  159300. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  159301. }
  159302. return pCur->aNode[ii];
  159303. }
  159304. /*
  159305. ** Push a new element onto the priority queue
  159306. */
  159307. static RtreeSearchPoint *rtreeEnqueue(
  159308. RtreeCursor *pCur, /* The cursor */
  159309. RtreeDValue rScore, /* Score for the new search point */
  159310. u8 iLevel /* Level for the new search point */
  159311. ){
  159312. int i, j;
  159313. RtreeSearchPoint *pNew;
  159314. if( pCur->nPoint>=pCur->nPointAlloc ){
  159315. int nNew = pCur->nPointAlloc*2 + 8;
  159316. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  159317. if( pNew==0 ) return 0;
  159318. pCur->aPoint = pNew;
  159319. pCur->nPointAlloc = nNew;
  159320. }
  159321. i = pCur->nPoint++;
  159322. pNew = pCur->aPoint + i;
  159323. pNew->rScore = rScore;
  159324. pNew->iLevel = iLevel;
  159325. assert( iLevel<=RTREE_MAX_DEPTH );
  159326. while( i>0 ){
  159327. RtreeSearchPoint *pParent;
  159328. j = (i-1)/2;
  159329. pParent = pCur->aPoint + j;
  159330. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  159331. rtreeSearchPointSwap(pCur, j, i);
  159332. i = j;
  159333. pNew = pParent;
  159334. }
  159335. return pNew;
  159336. }
  159337. /*
  159338. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  159339. ** NULL if malloc fails.
  159340. */
  159341. static RtreeSearchPoint *rtreeSearchPointNew(
  159342. RtreeCursor *pCur, /* The cursor */
  159343. RtreeDValue rScore, /* Score for the new search point */
  159344. u8 iLevel /* Level for the new search point */
  159345. ){
  159346. RtreeSearchPoint *pNew, *pFirst;
  159347. pFirst = rtreeSearchPointFirst(pCur);
  159348. pCur->anQueue[iLevel]++;
  159349. if( pFirst==0
  159350. || pFirst->rScore>rScore
  159351. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  159352. ){
  159353. if( pCur->bPoint ){
  159354. int ii;
  159355. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  159356. if( pNew==0 ) return 0;
  159357. ii = (int)(pNew - pCur->aPoint) + 1;
  159358. if( ii<RTREE_CACHE_SZ ){
  159359. assert( pCur->aNode[ii]==0 );
  159360. pCur->aNode[ii] = pCur->aNode[0];
  159361. }else{
  159362. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  159363. }
  159364. pCur->aNode[0] = 0;
  159365. *pNew = pCur->sPoint;
  159366. }
  159367. pCur->sPoint.rScore = rScore;
  159368. pCur->sPoint.iLevel = iLevel;
  159369. pCur->bPoint = 1;
  159370. return &pCur->sPoint;
  159371. }else{
  159372. return rtreeEnqueue(pCur, rScore, iLevel);
  159373. }
  159374. }
  159375. #if 0
  159376. /* Tracing routines for the RtreeSearchPoint queue */
  159377. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  159378. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  159379. printf(" %d.%05lld.%02d %g %d",
  159380. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  159381. );
  159382. idx++;
  159383. if( idx<RTREE_CACHE_SZ ){
  159384. printf(" %p\n", pCur->aNode[idx]);
  159385. }else{
  159386. printf("\n");
  159387. }
  159388. }
  159389. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  159390. int ii;
  159391. printf("=== %9s ", zPrefix);
  159392. if( pCur->bPoint ){
  159393. tracePoint(&pCur->sPoint, -1, pCur);
  159394. }
  159395. for(ii=0; ii<pCur->nPoint; ii++){
  159396. if( ii>0 || pCur->bPoint ) printf(" ");
  159397. tracePoint(&pCur->aPoint[ii], ii, pCur);
  159398. }
  159399. }
  159400. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  159401. #else
  159402. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  159403. #endif
  159404. /* Remove the search point with the lowest current score.
  159405. */
  159406. static void rtreeSearchPointPop(RtreeCursor *p){
  159407. int i, j, k, n;
  159408. i = 1 - p->bPoint;
  159409. assert( i==0 || i==1 );
  159410. if( p->aNode[i] ){
  159411. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  159412. p->aNode[i] = 0;
  159413. }
  159414. if( p->bPoint ){
  159415. p->anQueue[p->sPoint.iLevel]--;
  159416. p->bPoint = 0;
  159417. }else if( p->nPoint ){
  159418. p->anQueue[p->aPoint[0].iLevel]--;
  159419. n = --p->nPoint;
  159420. p->aPoint[0] = p->aPoint[n];
  159421. if( n<RTREE_CACHE_SZ-1 ){
  159422. p->aNode[1] = p->aNode[n+1];
  159423. p->aNode[n+1] = 0;
  159424. }
  159425. i = 0;
  159426. while( (j = i*2+1)<n ){
  159427. k = j+1;
  159428. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  159429. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  159430. rtreeSearchPointSwap(p, i, k);
  159431. i = k;
  159432. }else{
  159433. break;
  159434. }
  159435. }else{
  159436. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  159437. rtreeSearchPointSwap(p, i, j);
  159438. i = j;
  159439. }else{
  159440. break;
  159441. }
  159442. }
  159443. }
  159444. }
  159445. }
  159446. /*
  159447. ** Continue the search on cursor pCur until the front of the queue
  159448. ** contains an entry suitable for returning as a result-set row,
  159449. ** or until the RtreeSearchPoint queue is empty, indicating that the
  159450. ** query has completed.
  159451. */
  159452. static int rtreeStepToLeaf(RtreeCursor *pCur){
  159453. RtreeSearchPoint *p;
  159454. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  159455. RtreeNode *pNode;
  159456. int eWithin;
  159457. int rc = SQLITE_OK;
  159458. int nCell;
  159459. int nConstraint = pCur->nConstraint;
  159460. int ii;
  159461. int eInt;
  159462. RtreeSearchPoint x;
  159463. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  159464. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  159465. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  159466. if( rc ) return rc;
  159467. nCell = NCELL(pNode);
  159468. assert( nCell<200 );
  159469. while( p->iCell<nCell ){
  159470. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  159471. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  159472. eWithin = FULLY_WITHIN;
  159473. for(ii=0; ii<nConstraint; ii++){
  159474. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  159475. if( pConstraint->op>=RTREE_MATCH ){
  159476. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  159477. &rScore, &eWithin);
  159478. if( rc ) return rc;
  159479. }else if( p->iLevel==1 ){
  159480. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  159481. }else{
  159482. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  159483. }
  159484. if( eWithin==NOT_WITHIN ) break;
  159485. }
  159486. p->iCell++;
  159487. if( eWithin==NOT_WITHIN ) continue;
  159488. x.iLevel = p->iLevel - 1;
  159489. if( x.iLevel ){
  159490. x.id = readInt64(pCellData);
  159491. x.iCell = 0;
  159492. }else{
  159493. x.id = p->id;
  159494. x.iCell = p->iCell - 1;
  159495. }
  159496. if( p->iCell>=nCell ){
  159497. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  159498. rtreeSearchPointPop(pCur);
  159499. }
  159500. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  159501. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  159502. if( p==0 ) return SQLITE_NOMEM;
  159503. p->eWithin = (u8)eWithin;
  159504. p->id = x.id;
  159505. p->iCell = x.iCell;
  159506. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  159507. break;
  159508. }
  159509. if( p->iCell>=nCell ){
  159510. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  159511. rtreeSearchPointPop(pCur);
  159512. }
  159513. }
  159514. pCur->atEOF = p==0;
  159515. return SQLITE_OK;
  159516. }
  159517. /*
  159518. ** Rtree virtual table module xNext method.
  159519. */
  159520. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  159521. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  159522. int rc = SQLITE_OK;
  159523. /* Move to the next entry that matches the configured constraints. */
  159524. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  159525. rtreeSearchPointPop(pCsr);
  159526. rc = rtreeStepToLeaf(pCsr);
  159527. return rc;
  159528. }
  159529. /*
  159530. ** Rtree virtual table module xRowid method.
  159531. */
  159532. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  159533. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  159534. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  159535. int rc = SQLITE_OK;
  159536. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  159537. if( rc==SQLITE_OK && p ){
  159538. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  159539. }
  159540. return rc;
  159541. }
  159542. /*
  159543. ** Rtree virtual table module xColumn method.
  159544. */
  159545. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  159546. Rtree *pRtree = (Rtree *)cur->pVtab;
  159547. RtreeCursor *pCsr = (RtreeCursor *)cur;
  159548. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  159549. RtreeCoord c;
  159550. int rc = SQLITE_OK;
  159551. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  159552. if( rc ) return rc;
  159553. if( p==0 ) return SQLITE_OK;
  159554. if( i==0 ){
  159555. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  159556. }else{
  159557. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  159558. #ifndef SQLITE_RTREE_INT_ONLY
  159559. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  159560. sqlite3_result_double(ctx, c.f);
  159561. }else
  159562. #endif
  159563. {
  159564. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  159565. sqlite3_result_int(ctx, c.i);
  159566. }
  159567. }
  159568. return SQLITE_OK;
  159569. }
  159570. /*
  159571. ** Use nodeAcquire() to obtain the leaf node containing the record with
  159572. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  159573. ** return SQLITE_OK. If there is no such record in the table, set
  159574. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  159575. ** to zero and return an SQLite error code.
  159576. */
  159577. static int findLeafNode(
  159578. Rtree *pRtree, /* RTree to search */
  159579. i64 iRowid, /* The rowid searching for */
  159580. RtreeNode **ppLeaf, /* Write the node here */
  159581. sqlite3_int64 *piNode /* Write the node-id here */
  159582. ){
  159583. int rc;
  159584. *ppLeaf = 0;
  159585. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  159586. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  159587. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  159588. if( piNode ) *piNode = iNode;
  159589. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  159590. sqlite3_reset(pRtree->pReadRowid);
  159591. }else{
  159592. rc = sqlite3_reset(pRtree->pReadRowid);
  159593. }
  159594. return rc;
  159595. }
  159596. /*
  159597. ** This function is called to configure the RtreeConstraint object passed
  159598. ** as the second argument for a MATCH constraint. The value passed as the
  159599. ** first argument to this function is the right-hand operand to the MATCH
  159600. ** operator.
  159601. */
  159602. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  159603. RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
  159604. sqlite3_rtree_query_info *pInfo; /* Callback information */
  159605. pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
  159606. if( pSrc==0 ) return SQLITE_ERROR;
  159607. pInfo = (sqlite3_rtree_query_info*)
  159608. sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
  159609. if( !pInfo ) return SQLITE_NOMEM;
  159610. memset(pInfo, 0, sizeof(*pInfo));
  159611. pBlob = (RtreeMatchArg*)&pInfo[1];
  159612. memcpy(pBlob, pSrc, pSrc->iSize);
  159613. pInfo->pContext = pBlob->cb.pContext;
  159614. pInfo->nParam = pBlob->nParam;
  159615. pInfo->aParam = pBlob->aParam;
  159616. pInfo->apSqlParam = pBlob->apSqlParam;
  159617. if( pBlob->cb.xGeom ){
  159618. pCons->u.xGeom = pBlob->cb.xGeom;
  159619. }else{
  159620. pCons->op = RTREE_QUERY;
  159621. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  159622. }
  159623. pCons->pInfo = pInfo;
  159624. return SQLITE_OK;
  159625. }
  159626. /*
  159627. ** Rtree virtual table module xFilter method.
  159628. */
  159629. static int rtreeFilter(
  159630. sqlite3_vtab_cursor *pVtabCursor,
  159631. int idxNum, const char *idxStr,
  159632. int argc, sqlite3_value **argv
  159633. ){
  159634. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  159635. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  159636. RtreeNode *pRoot = 0;
  159637. int ii;
  159638. int rc = SQLITE_OK;
  159639. int iCell = 0;
  159640. rtreeReference(pRtree);
  159641. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  159642. freeCursorConstraints(pCsr);
  159643. sqlite3_free(pCsr->aPoint);
  159644. memset(pCsr, 0, sizeof(RtreeCursor));
  159645. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  159646. pCsr->iStrategy = idxNum;
  159647. if( idxNum==1 ){
  159648. /* Special case - lookup by rowid. */
  159649. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  159650. RtreeSearchPoint *p; /* Search point for the leaf */
  159651. i64 iRowid = sqlite3_value_int64(argv[0]);
  159652. i64 iNode = 0;
  159653. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  159654. if( rc==SQLITE_OK && pLeaf!=0 ){
  159655. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  159656. assert( p!=0 ); /* Always returns pCsr->sPoint */
  159657. pCsr->aNode[0] = pLeaf;
  159658. p->id = iNode;
  159659. p->eWithin = PARTLY_WITHIN;
  159660. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  159661. p->iCell = (u8)iCell;
  159662. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  159663. }else{
  159664. pCsr->atEOF = 1;
  159665. }
  159666. }else{
  159667. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  159668. ** with the configured constraints.
  159669. */
  159670. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  159671. if( rc==SQLITE_OK && argc>0 ){
  159672. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  159673. pCsr->nConstraint = argc;
  159674. if( !pCsr->aConstraint ){
  159675. rc = SQLITE_NOMEM;
  159676. }else{
  159677. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  159678. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  159679. assert( (idxStr==0 && argc==0)
  159680. || (idxStr && (int)strlen(idxStr)==argc*2) );
  159681. for(ii=0; ii<argc; ii++){
  159682. RtreeConstraint *p = &pCsr->aConstraint[ii];
  159683. p->op = idxStr[ii*2];
  159684. p->iCoord = idxStr[ii*2+1]-'0';
  159685. if( p->op>=RTREE_MATCH ){
  159686. /* A MATCH operator. The right-hand-side must be a blob that
  159687. ** can be cast into an RtreeMatchArg object. One created using
  159688. ** an sqlite3_rtree_geometry_callback() SQL user function.
  159689. */
  159690. rc = deserializeGeometry(argv[ii], p);
  159691. if( rc!=SQLITE_OK ){
  159692. break;
  159693. }
  159694. p->pInfo->nCoord = pRtree->nDim2;
  159695. p->pInfo->anQueue = pCsr->anQueue;
  159696. p->pInfo->mxLevel = pRtree->iDepth + 1;
  159697. }else{
  159698. #ifdef SQLITE_RTREE_INT_ONLY
  159699. p->u.rValue = sqlite3_value_int64(argv[ii]);
  159700. #else
  159701. p->u.rValue = sqlite3_value_double(argv[ii]);
  159702. #endif
  159703. }
  159704. }
  159705. }
  159706. }
  159707. if( rc==SQLITE_OK ){
  159708. RtreeSearchPoint *pNew;
  159709. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  159710. if( pNew==0 ) return SQLITE_NOMEM;
  159711. pNew->id = 1;
  159712. pNew->iCell = 0;
  159713. pNew->eWithin = PARTLY_WITHIN;
  159714. assert( pCsr->bPoint==1 );
  159715. pCsr->aNode[0] = pRoot;
  159716. pRoot = 0;
  159717. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  159718. rc = rtreeStepToLeaf(pCsr);
  159719. }
  159720. }
  159721. nodeRelease(pRtree, pRoot);
  159722. rtreeRelease(pRtree);
  159723. return rc;
  159724. }
  159725. /*
  159726. ** Rtree virtual table module xBestIndex method. There are three
  159727. ** table scan strategies to choose from (in order from most to
  159728. ** least desirable):
  159729. **
  159730. ** idxNum idxStr Strategy
  159731. ** ------------------------------------------------
  159732. ** 1 Unused Direct lookup by rowid.
  159733. ** 2 See below R-tree query or full-table scan.
  159734. ** ------------------------------------------------
  159735. **
  159736. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  159737. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  159738. ** constraint used. The first two bytes of idxStr correspond to
  159739. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  159740. ** (argvIndex==1) etc.
  159741. **
  159742. ** The first of each pair of bytes in idxStr identifies the constraint
  159743. ** operator as follows:
  159744. **
  159745. ** Operator Byte Value
  159746. ** ----------------------
  159747. ** = 0x41 ('A')
  159748. ** <= 0x42 ('B')
  159749. ** < 0x43 ('C')
  159750. ** >= 0x44 ('D')
  159751. ** > 0x45 ('E')
  159752. ** MATCH 0x46 ('F')
  159753. ** ----------------------
  159754. **
  159755. ** The second of each pair of bytes identifies the coordinate column
  159756. ** to which the constraint applies. The leftmost coordinate column
  159757. ** is 'a', the second from the left 'b' etc.
  159758. */
  159759. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  159760. Rtree *pRtree = (Rtree*)tab;
  159761. int rc = SQLITE_OK;
  159762. int ii;
  159763. int bMatch = 0; /* True if there exists a MATCH constraint */
  159764. i64 nRow; /* Estimated rows returned by this scan */
  159765. int iIdx = 0;
  159766. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  159767. memset(zIdxStr, 0, sizeof(zIdxStr));
  159768. /* Check if there exists a MATCH constraint - even an unusable one. If there
  159769. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  159770. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  159771. ** possible. */
  159772. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  159773. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  159774. bMatch = 1;
  159775. }
  159776. }
  159777. assert( pIdxInfo->idxStr==0 );
  159778. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  159779. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  159780. if( bMatch==0 && p->usable
  159781. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  159782. ){
  159783. /* We have an equality constraint on the rowid. Use strategy 1. */
  159784. int jj;
  159785. for(jj=0; jj<ii; jj++){
  159786. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  159787. pIdxInfo->aConstraintUsage[jj].omit = 0;
  159788. }
  159789. pIdxInfo->idxNum = 1;
  159790. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  159791. pIdxInfo->aConstraintUsage[jj].omit = 1;
  159792. /* This strategy involves a two rowid lookups on an B-Tree structures
  159793. ** and then a linear search of an R-Tree node. This should be
  159794. ** considered almost as quick as a direct rowid lookup (for which
  159795. ** sqlite uses an internal cost of 0.0). It is expected to return
  159796. ** a single row.
  159797. */
  159798. pIdxInfo->estimatedCost = 30.0;
  159799. pIdxInfo->estimatedRows = 1;
  159800. return SQLITE_OK;
  159801. }
  159802. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  159803. u8 op;
  159804. switch( p->op ){
  159805. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  159806. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  159807. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  159808. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  159809. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  159810. default:
  159811. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  159812. op = RTREE_MATCH;
  159813. break;
  159814. }
  159815. zIdxStr[iIdx++] = op;
  159816. zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
  159817. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  159818. pIdxInfo->aConstraintUsage[ii].omit = 1;
  159819. }
  159820. }
  159821. pIdxInfo->idxNum = 2;
  159822. pIdxInfo->needToFreeIdxStr = 1;
  159823. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  159824. return SQLITE_NOMEM;
  159825. }
  159826. nRow = pRtree->nRowEst >> (iIdx/2);
  159827. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  159828. pIdxInfo->estimatedRows = nRow;
  159829. return rc;
  159830. }
  159831. /*
  159832. ** Return the N-dimensional volumn of the cell stored in *p.
  159833. */
  159834. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  159835. RtreeDValue area = (RtreeDValue)1;
  159836. assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
  159837. #ifndef SQLITE_RTREE_INT_ONLY
  159838. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  159839. switch( pRtree->nDim ){
  159840. case 5: area = p->aCoord[9].f - p->aCoord[8].f;
  159841. case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
  159842. case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
  159843. case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
  159844. default: area *= p->aCoord[1].f - p->aCoord[0].f;
  159845. }
  159846. }else
  159847. #endif
  159848. {
  159849. switch( pRtree->nDim ){
  159850. case 5: area = p->aCoord[9].i - p->aCoord[8].i;
  159851. case 4: area *= p->aCoord[7].i - p->aCoord[6].i;
  159852. case 3: area *= p->aCoord[5].i - p->aCoord[4].i;
  159853. case 2: area *= p->aCoord[3].i - p->aCoord[2].i;
  159854. default: area *= p->aCoord[1].i - p->aCoord[0].i;
  159855. }
  159856. }
  159857. return area;
  159858. }
  159859. /*
  159860. ** Return the margin length of cell p. The margin length is the sum
  159861. ** of the objects size in each dimension.
  159862. */
  159863. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  159864. RtreeDValue margin = 0;
  159865. int ii = pRtree->nDim2 - 2;
  159866. do{
  159867. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  159868. ii -= 2;
  159869. }while( ii>=0 );
  159870. return margin;
  159871. }
  159872. /*
  159873. ** Store the union of cells p1 and p2 in p1.
  159874. */
  159875. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  159876. int ii = 0;
  159877. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  159878. do{
  159879. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  159880. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  159881. ii += 2;
  159882. }while( ii<pRtree->nDim2 );
  159883. }else{
  159884. do{
  159885. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  159886. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  159887. ii += 2;
  159888. }while( ii<pRtree->nDim2 );
  159889. }
  159890. }
  159891. /*
  159892. ** Return true if the area covered by p2 is a subset of the area covered
  159893. ** by p1. False otherwise.
  159894. */
  159895. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  159896. int ii;
  159897. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  159898. for(ii=0; ii<pRtree->nDim2; ii+=2){
  159899. RtreeCoord *a1 = &p1->aCoord[ii];
  159900. RtreeCoord *a2 = &p2->aCoord[ii];
  159901. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  159902. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  159903. ){
  159904. return 0;
  159905. }
  159906. }
  159907. return 1;
  159908. }
  159909. /*
  159910. ** Return the amount cell p would grow by if it were unioned with pCell.
  159911. */
  159912. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  159913. RtreeDValue area;
  159914. RtreeCell cell;
  159915. memcpy(&cell, p, sizeof(RtreeCell));
  159916. area = cellArea(pRtree, &cell);
  159917. cellUnion(pRtree, &cell, pCell);
  159918. return (cellArea(pRtree, &cell)-area);
  159919. }
  159920. static RtreeDValue cellOverlap(
  159921. Rtree *pRtree,
  159922. RtreeCell *p,
  159923. RtreeCell *aCell,
  159924. int nCell
  159925. ){
  159926. int ii;
  159927. RtreeDValue overlap = RTREE_ZERO;
  159928. for(ii=0; ii<nCell; ii++){
  159929. int jj;
  159930. RtreeDValue o = (RtreeDValue)1;
  159931. for(jj=0; jj<pRtree->nDim2; jj+=2){
  159932. RtreeDValue x1, x2;
  159933. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  159934. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  159935. if( x2<x1 ){
  159936. o = (RtreeDValue)0;
  159937. break;
  159938. }else{
  159939. o = o * (x2-x1);
  159940. }
  159941. }
  159942. overlap += o;
  159943. }
  159944. return overlap;
  159945. }
  159946. /*
  159947. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  159948. ** ChooseSubTree in r*tree terminology.
  159949. */
  159950. static int ChooseLeaf(
  159951. Rtree *pRtree, /* Rtree table */
  159952. RtreeCell *pCell, /* Cell to insert into rtree */
  159953. int iHeight, /* Height of sub-tree rooted at pCell */
  159954. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  159955. ){
  159956. int rc;
  159957. int ii;
  159958. RtreeNode *pNode = 0;
  159959. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  159960. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  159961. int iCell;
  159962. sqlite3_int64 iBest = 0;
  159963. RtreeDValue fMinGrowth = RTREE_ZERO;
  159964. RtreeDValue fMinArea = RTREE_ZERO;
  159965. int nCell = NCELL(pNode);
  159966. RtreeCell cell;
  159967. RtreeNode *pChild;
  159968. RtreeCell *aCell = 0;
  159969. /* Select the child node which will be enlarged the least if pCell
  159970. ** is inserted into it. Resolve ties by choosing the entry with
  159971. ** the smallest area.
  159972. */
  159973. for(iCell=0; iCell<nCell; iCell++){
  159974. int bBest = 0;
  159975. RtreeDValue growth;
  159976. RtreeDValue area;
  159977. nodeGetCell(pRtree, pNode, iCell, &cell);
  159978. growth = cellGrowth(pRtree, &cell, pCell);
  159979. area = cellArea(pRtree, &cell);
  159980. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  159981. bBest = 1;
  159982. }
  159983. if( bBest ){
  159984. fMinGrowth = growth;
  159985. fMinArea = area;
  159986. iBest = cell.iRowid;
  159987. }
  159988. }
  159989. sqlite3_free(aCell);
  159990. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  159991. nodeRelease(pRtree, pNode);
  159992. pNode = pChild;
  159993. }
  159994. *ppLeaf = pNode;
  159995. return rc;
  159996. }
  159997. /*
  159998. ** A cell with the same content as pCell has just been inserted into
  159999. ** the node pNode. This function updates the bounding box cells in
  160000. ** all ancestor elements.
  160001. */
  160002. static int AdjustTree(
  160003. Rtree *pRtree, /* Rtree table */
  160004. RtreeNode *pNode, /* Adjust ancestry of this node. */
  160005. RtreeCell *pCell /* This cell was just inserted */
  160006. ){
  160007. RtreeNode *p = pNode;
  160008. while( p->pParent ){
  160009. RtreeNode *pParent = p->pParent;
  160010. RtreeCell cell;
  160011. int iCell;
  160012. if( nodeParentIndex(pRtree, p, &iCell) ){
  160013. return SQLITE_CORRUPT_VTAB;
  160014. }
  160015. nodeGetCell(pRtree, pParent, iCell, &cell);
  160016. if( !cellContains(pRtree, &cell, pCell) ){
  160017. cellUnion(pRtree, &cell, pCell);
  160018. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  160019. }
  160020. p = pParent;
  160021. }
  160022. return SQLITE_OK;
  160023. }
  160024. /*
  160025. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  160026. */
  160027. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  160028. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  160029. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  160030. sqlite3_step(pRtree->pWriteRowid);
  160031. return sqlite3_reset(pRtree->pWriteRowid);
  160032. }
  160033. /*
  160034. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  160035. */
  160036. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  160037. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  160038. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  160039. sqlite3_step(pRtree->pWriteParent);
  160040. return sqlite3_reset(pRtree->pWriteParent);
  160041. }
  160042. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  160043. /*
  160044. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  160045. ** nIdx. The aIdx array contains the set of integers from 0 to
  160046. ** (nIdx-1) in no particular order. This function sorts the values
  160047. ** in aIdx according to the indexed values in aDistance. For
  160048. ** example, assuming the inputs:
  160049. **
  160050. ** aIdx = { 0, 1, 2, 3 }
  160051. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  160052. **
  160053. ** this function sets the aIdx array to contain:
  160054. **
  160055. ** aIdx = { 0, 1, 2, 3 }
  160056. **
  160057. ** The aSpare array is used as temporary working space by the
  160058. ** sorting algorithm.
  160059. */
  160060. static void SortByDistance(
  160061. int *aIdx,
  160062. int nIdx,
  160063. RtreeDValue *aDistance,
  160064. int *aSpare
  160065. ){
  160066. if( nIdx>1 ){
  160067. int iLeft = 0;
  160068. int iRight = 0;
  160069. int nLeft = nIdx/2;
  160070. int nRight = nIdx-nLeft;
  160071. int *aLeft = aIdx;
  160072. int *aRight = &aIdx[nLeft];
  160073. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  160074. SortByDistance(aRight, nRight, aDistance, aSpare);
  160075. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  160076. aLeft = aSpare;
  160077. while( iLeft<nLeft || iRight<nRight ){
  160078. if( iLeft==nLeft ){
  160079. aIdx[iLeft+iRight] = aRight[iRight];
  160080. iRight++;
  160081. }else if( iRight==nRight ){
  160082. aIdx[iLeft+iRight] = aLeft[iLeft];
  160083. iLeft++;
  160084. }else{
  160085. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  160086. RtreeDValue fRight = aDistance[aRight[iRight]];
  160087. if( fLeft<fRight ){
  160088. aIdx[iLeft+iRight] = aLeft[iLeft];
  160089. iLeft++;
  160090. }else{
  160091. aIdx[iLeft+iRight] = aRight[iRight];
  160092. iRight++;
  160093. }
  160094. }
  160095. }
  160096. #if 0
  160097. /* Check that the sort worked */
  160098. {
  160099. int jj;
  160100. for(jj=1; jj<nIdx; jj++){
  160101. RtreeDValue left = aDistance[aIdx[jj-1]];
  160102. RtreeDValue right = aDistance[aIdx[jj]];
  160103. assert( left<=right );
  160104. }
  160105. }
  160106. #endif
  160107. }
  160108. }
  160109. /*
  160110. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  160111. ** nIdx. The aIdx array contains the set of integers from 0 to
  160112. ** (nIdx-1) in no particular order. This function sorts the values
  160113. ** in aIdx according to dimension iDim of the cells in aCell. The
  160114. ** minimum value of dimension iDim is considered first, the
  160115. ** maximum used to break ties.
  160116. **
  160117. ** The aSpare array is used as temporary working space by the
  160118. ** sorting algorithm.
  160119. */
  160120. static void SortByDimension(
  160121. Rtree *pRtree,
  160122. int *aIdx,
  160123. int nIdx,
  160124. int iDim,
  160125. RtreeCell *aCell,
  160126. int *aSpare
  160127. ){
  160128. if( nIdx>1 ){
  160129. int iLeft = 0;
  160130. int iRight = 0;
  160131. int nLeft = nIdx/2;
  160132. int nRight = nIdx-nLeft;
  160133. int *aLeft = aIdx;
  160134. int *aRight = &aIdx[nLeft];
  160135. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  160136. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  160137. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  160138. aLeft = aSpare;
  160139. while( iLeft<nLeft || iRight<nRight ){
  160140. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  160141. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  160142. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  160143. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  160144. if( (iLeft!=nLeft) && ((iRight==nRight)
  160145. || (xleft1<xright1)
  160146. || (xleft1==xright1 && xleft2<xright2)
  160147. )){
  160148. aIdx[iLeft+iRight] = aLeft[iLeft];
  160149. iLeft++;
  160150. }else{
  160151. aIdx[iLeft+iRight] = aRight[iRight];
  160152. iRight++;
  160153. }
  160154. }
  160155. #if 0
  160156. /* Check that the sort worked */
  160157. {
  160158. int jj;
  160159. for(jj=1; jj<nIdx; jj++){
  160160. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  160161. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  160162. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  160163. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  160164. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  160165. }
  160166. }
  160167. #endif
  160168. }
  160169. }
  160170. /*
  160171. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  160172. */
  160173. static int splitNodeStartree(
  160174. Rtree *pRtree,
  160175. RtreeCell *aCell,
  160176. int nCell,
  160177. RtreeNode *pLeft,
  160178. RtreeNode *pRight,
  160179. RtreeCell *pBboxLeft,
  160180. RtreeCell *pBboxRight
  160181. ){
  160182. int **aaSorted;
  160183. int *aSpare;
  160184. int ii;
  160185. int iBestDim = 0;
  160186. int iBestSplit = 0;
  160187. RtreeDValue fBestMargin = RTREE_ZERO;
  160188. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  160189. aaSorted = (int **)sqlite3_malloc(nByte);
  160190. if( !aaSorted ){
  160191. return SQLITE_NOMEM;
  160192. }
  160193. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  160194. memset(aaSorted, 0, nByte);
  160195. for(ii=0; ii<pRtree->nDim; ii++){
  160196. int jj;
  160197. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  160198. for(jj=0; jj<nCell; jj++){
  160199. aaSorted[ii][jj] = jj;
  160200. }
  160201. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  160202. }
  160203. for(ii=0; ii<pRtree->nDim; ii++){
  160204. RtreeDValue margin = RTREE_ZERO;
  160205. RtreeDValue fBestOverlap = RTREE_ZERO;
  160206. RtreeDValue fBestArea = RTREE_ZERO;
  160207. int iBestLeft = 0;
  160208. int nLeft;
  160209. for(
  160210. nLeft=RTREE_MINCELLS(pRtree);
  160211. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  160212. nLeft++
  160213. ){
  160214. RtreeCell left;
  160215. RtreeCell right;
  160216. int kk;
  160217. RtreeDValue overlap;
  160218. RtreeDValue area;
  160219. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  160220. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  160221. for(kk=1; kk<(nCell-1); kk++){
  160222. if( kk<nLeft ){
  160223. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  160224. }else{
  160225. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  160226. }
  160227. }
  160228. margin += cellMargin(pRtree, &left);
  160229. margin += cellMargin(pRtree, &right);
  160230. overlap = cellOverlap(pRtree, &left, &right, 1);
  160231. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  160232. if( (nLeft==RTREE_MINCELLS(pRtree))
  160233. || (overlap<fBestOverlap)
  160234. || (overlap==fBestOverlap && area<fBestArea)
  160235. ){
  160236. iBestLeft = nLeft;
  160237. fBestOverlap = overlap;
  160238. fBestArea = area;
  160239. }
  160240. }
  160241. if( ii==0 || margin<fBestMargin ){
  160242. iBestDim = ii;
  160243. fBestMargin = margin;
  160244. iBestSplit = iBestLeft;
  160245. }
  160246. }
  160247. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  160248. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  160249. for(ii=0; ii<nCell; ii++){
  160250. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  160251. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  160252. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  160253. nodeInsertCell(pRtree, pTarget, pCell);
  160254. cellUnion(pRtree, pBbox, pCell);
  160255. }
  160256. sqlite3_free(aaSorted);
  160257. return SQLITE_OK;
  160258. }
  160259. static int updateMapping(
  160260. Rtree *pRtree,
  160261. i64 iRowid,
  160262. RtreeNode *pNode,
  160263. int iHeight
  160264. ){
  160265. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  160266. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  160267. if( iHeight>0 ){
  160268. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  160269. if( pChild ){
  160270. nodeRelease(pRtree, pChild->pParent);
  160271. nodeReference(pNode);
  160272. pChild->pParent = pNode;
  160273. }
  160274. }
  160275. return xSetMapping(pRtree, iRowid, pNode->iNode);
  160276. }
  160277. static int SplitNode(
  160278. Rtree *pRtree,
  160279. RtreeNode *pNode,
  160280. RtreeCell *pCell,
  160281. int iHeight
  160282. ){
  160283. int i;
  160284. int newCellIsRight = 0;
  160285. int rc = SQLITE_OK;
  160286. int nCell = NCELL(pNode);
  160287. RtreeCell *aCell;
  160288. int *aiUsed;
  160289. RtreeNode *pLeft = 0;
  160290. RtreeNode *pRight = 0;
  160291. RtreeCell leftbbox;
  160292. RtreeCell rightbbox;
  160293. /* Allocate an array and populate it with a copy of pCell and
  160294. ** all cells from node pLeft. Then zero the original node.
  160295. */
  160296. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  160297. if( !aCell ){
  160298. rc = SQLITE_NOMEM;
  160299. goto splitnode_out;
  160300. }
  160301. aiUsed = (int *)&aCell[nCell+1];
  160302. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  160303. for(i=0; i<nCell; i++){
  160304. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  160305. }
  160306. nodeZero(pRtree, pNode);
  160307. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  160308. nCell++;
  160309. if( pNode->iNode==1 ){
  160310. pRight = nodeNew(pRtree, pNode);
  160311. pLeft = nodeNew(pRtree, pNode);
  160312. pRtree->iDepth++;
  160313. pNode->isDirty = 1;
  160314. writeInt16(pNode->zData, pRtree->iDepth);
  160315. }else{
  160316. pLeft = pNode;
  160317. pRight = nodeNew(pRtree, pLeft->pParent);
  160318. nodeReference(pLeft);
  160319. }
  160320. if( !pLeft || !pRight ){
  160321. rc = SQLITE_NOMEM;
  160322. goto splitnode_out;
  160323. }
  160324. memset(pLeft->zData, 0, pRtree->iNodeSize);
  160325. memset(pRight->zData, 0, pRtree->iNodeSize);
  160326. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  160327. &leftbbox, &rightbbox);
  160328. if( rc!=SQLITE_OK ){
  160329. goto splitnode_out;
  160330. }
  160331. /* Ensure both child nodes have node numbers assigned to them by calling
  160332. ** nodeWrite(). Node pRight always needs a node number, as it was created
  160333. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  160334. ** In this case avoid the all to nodeWrite().
  160335. */
  160336. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  160337. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  160338. ){
  160339. goto splitnode_out;
  160340. }
  160341. rightbbox.iRowid = pRight->iNode;
  160342. leftbbox.iRowid = pLeft->iNode;
  160343. if( pNode->iNode==1 ){
  160344. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  160345. if( rc!=SQLITE_OK ){
  160346. goto splitnode_out;
  160347. }
  160348. }else{
  160349. RtreeNode *pParent = pLeft->pParent;
  160350. int iCell;
  160351. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  160352. if( rc==SQLITE_OK ){
  160353. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  160354. rc = AdjustTree(pRtree, pParent, &leftbbox);
  160355. }
  160356. if( rc!=SQLITE_OK ){
  160357. goto splitnode_out;
  160358. }
  160359. }
  160360. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  160361. goto splitnode_out;
  160362. }
  160363. for(i=0; i<NCELL(pRight); i++){
  160364. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  160365. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  160366. if( iRowid==pCell->iRowid ){
  160367. newCellIsRight = 1;
  160368. }
  160369. if( rc!=SQLITE_OK ){
  160370. goto splitnode_out;
  160371. }
  160372. }
  160373. if( pNode->iNode==1 ){
  160374. for(i=0; i<NCELL(pLeft); i++){
  160375. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  160376. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  160377. if( rc!=SQLITE_OK ){
  160378. goto splitnode_out;
  160379. }
  160380. }
  160381. }else if( newCellIsRight==0 ){
  160382. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  160383. }
  160384. if( rc==SQLITE_OK ){
  160385. rc = nodeRelease(pRtree, pRight);
  160386. pRight = 0;
  160387. }
  160388. if( rc==SQLITE_OK ){
  160389. rc = nodeRelease(pRtree, pLeft);
  160390. pLeft = 0;
  160391. }
  160392. splitnode_out:
  160393. nodeRelease(pRtree, pRight);
  160394. nodeRelease(pRtree, pLeft);
  160395. sqlite3_free(aCell);
  160396. return rc;
  160397. }
  160398. /*
  160399. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  160400. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  160401. ** the pLeaf->pParent chain all the way up to the root node.
  160402. **
  160403. ** This operation is required when a row is deleted (or updated - an update
  160404. ** is implemented as a delete followed by an insert). SQLite provides the
  160405. ** rowid of the row to delete, which can be used to find the leaf on which
  160406. ** the entry resides (argument pLeaf). Once the leaf is located, this
  160407. ** function is called to determine its ancestry.
  160408. */
  160409. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  160410. int rc = SQLITE_OK;
  160411. RtreeNode *pChild = pLeaf;
  160412. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  160413. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  160414. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  160415. rc = sqlite3_step(pRtree->pReadParent);
  160416. if( rc==SQLITE_ROW ){
  160417. RtreeNode *pTest; /* Used to test for reference loops */
  160418. i64 iNode; /* Node number of parent node */
  160419. /* Before setting pChild->pParent, test that we are not creating a
  160420. ** loop of references (as we would if, say, pChild==pParent). We don't
  160421. ** want to do this as it leads to a memory leak when trying to delete
  160422. ** the referenced counted node structures.
  160423. */
  160424. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  160425. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  160426. if( !pTest ){
  160427. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  160428. }
  160429. }
  160430. rc = sqlite3_reset(pRtree->pReadParent);
  160431. if( rc==SQLITE_OK ) rc = rc2;
  160432. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  160433. pChild = pChild->pParent;
  160434. }
  160435. return rc;
  160436. }
  160437. static int deleteCell(Rtree *, RtreeNode *, int, int);
  160438. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  160439. int rc;
  160440. int rc2;
  160441. RtreeNode *pParent = 0;
  160442. int iCell;
  160443. assert( pNode->nRef==1 );
  160444. /* Remove the entry in the parent cell. */
  160445. rc = nodeParentIndex(pRtree, pNode, &iCell);
  160446. if( rc==SQLITE_OK ){
  160447. pParent = pNode->pParent;
  160448. pNode->pParent = 0;
  160449. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  160450. }
  160451. rc2 = nodeRelease(pRtree, pParent);
  160452. if( rc==SQLITE_OK ){
  160453. rc = rc2;
  160454. }
  160455. if( rc!=SQLITE_OK ){
  160456. return rc;
  160457. }
  160458. /* Remove the xxx_node entry. */
  160459. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  160460. sqlite3_step(pRtree->pDeleteNode);
  160461. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  160462. return rc;
  160463. }
  160464. /* Remove the xxx_parent entry. */
  160465. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  160466. sqlite3_step(pRtree->pDeleteParent);
  160467. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  160468. return rc;
  160469. }
  160470. /* Remove the node from the in-memory hash table and link it into
  160471. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  160472. */
  160473. nodeHashDelete(pRtree, pNode);
  160474. pNode->iNode = iHeight;
  160475. pNode->pNext = pRtree->pDeleted;
  160476. pNode->nRef++;
  160477. pRtree->pDeleted = pNode;
  160478. return SQLITE_OK;
  160479. }
  160480. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  160481. RtreeNode *pParent = pNode->pParent;
  160482. int rc = SQLITE_OK;
  160483. if( pParent ){
  160484. int ii;
  160485. int nCell = NCELL(pNode);
  160486. RtreeCell box; /* Bounding box for pNode */
  160487. nodeGetCell(pRtree, pNode, 0, &box);
  160488. for(ii=1; ii<nCell; ii++){
  160489. RtreeCell cell;
  160490. nodeGetCell(pRtree, pNode, ii, &cell);
  160491. cellUnion(pRtree, &box, &cell);
  160492. }
  160493. box.iRowid = pNode->iNode;
  160494. rc = nodeParentIndex(pRtree, pNode, &ii);
  160495. if( rc==SQLITE_OK ){
  160496. nodeOverwriteCell(pRtree, pParent, &box, ii);
  160497. rc = fixBoundingBox(pRtree, pParent);
  160498. }
  160499. }
  160500. return rc;
  160501. }
  160502. /*
  160503. ** Delete the cell at index iCell of node pNode. After removing the
  160504. ** cell, adjust the r-tree data structure if required.
  160505. */
  160506. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  160507. RtreeNode *pParent;
  160508. int rc;
  160509. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  160510. return rc;
  160511. }
  160512. /* Remove the cell from the node. This call just moves bytes around
  160513. ** the in-memory node image, so it cannot fail.
  160514. */
  160515. nodeDeleteCell(pRtree, pNode, iCell);
  160516. /* If the node is not the tree root and now has less than the minimum
  160517. ** number of cells, remove it from the tree. Otherwise, update the
  160518. ** cell in the parent node so that it tightly contains the updated
  160519. ** node.
  160520. */
  160521. pParent = pNode->pParent;
  160522. assert( pParent || pNode->iNode==1 );
  160523. if( pParent ){
  160524. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  160525. rc = removeNode(pRtree, pNode, iHeight);
  160526. }else{
  160527. rc = fixBoundingBox(pRtree, pNode);
  160528. }
  160529. }
  160530. return rc;
  160531. }
  160532. static int Reinsert(
  160533. Rtree *pRtree,
  160534. RtreeNode *pNode,
  160535. RtreeCell *pCell,
  160536. int iHeight
  160537. ){
  160538. int *aOrder;
  160539. int *aSpare;
  160540. RtreeCell *aCell;
  160541. RtreeDValue *aDistance;
  160542. int nCell;
  160543. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  160544. int iDim;
  160545. int ii;
  160546. int rc = SQLITE_OK;
  160547. int n;
  160548. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  160549. nCell = NCELL(pNode)+1;
  160550. n = (nCell+1)&(~1);
  160551. /* Allocate the buffers used by this operation. The allocation is
  160552. ** relinquished before this function returns.
  160553. */
  160554. aCell = (RtreeCell *)sqlite3_malloc(n * (
  160555. sizeof(RtreeCell) + /* aCell array */
  160556. sizeof(int) + /* aOrder array */
  160557. sizeof(int) + /* aSpare array */
  160558. sizeof(RtreeDValue) /* aDistance array */
  160559. ));
  160560. if( !aCell ){
  160561. return SQLITE_NOMEM;
  160562. }
  160563. aOrder = (int *)&aCell[n];
  160564. aSpare = (int *)&aOrder[n];
  160565. aDistance = (RtreeDValue *)&aSpare[n];
  160566. for(ii=0; ii<nCell; ii++){
  160567. if( ii==(nCell-1) ){
  160568. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  160569. }else{
  160570. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  160571. }
  160572. aOrder[ii] = ii;
  160573. for(iDim=0; iDim<pRtree->nDim; iDim++){
  160574. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  160575. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  160576. }
  160577. }
  160578. for(iDim=0; iDim<pRtree->nDim; iDim++){
  160579. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  160580. }
  160581. for(ii=0; ii<nCell; ii++){
  160582. aDistance[ii] = RTREE_ZERO;
  160583. for(iDim=0; iDim<pRtree->nDim; iDim++){
  160584. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  160585. DCOORD(aCell[ii].aCoord[iDim*2]));
  160586. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  160587. }
  160588. }
  160589. SortByDistance(aOrder, nCell, aDistance, aSpare);
  160590. nodeZero(pRtree, pNode);
  160591. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  160592. RtreeCell *p = &aCell[aOrder[ii]];
  160593. nodeInsertCell(pRtree, pNode, p);
  160594. if( p->iRowid==pCell->iRowid ){
  160595. if( iHeight==0 ){
  160596. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  160597. }else{
  160598. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  160599. }
  160600. }
  160601. }
  160602. if( rc==SQLITE_OK ){
  160603. rc = fixBoundingBox(pRtree, pNode);
  160604. }
  160605. for(; rc==SQLITE_OK && ii<nCell; ii++){
  160606. /* Find a node to store this cell in. pNode->iNode currently contains
  160607. ** the height of the sub-tree headed by the cell.
  160608. */
  160609. RtreeNode *pInsert;
  160610. RtreeCell *p = &aCell[aOrder[ii]];
  160611. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  160612. if( rc==SQLITE_OK ){
  160613. int rc2;
  160614. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  160615. rc2 = nodeRelease(pRtree, pInsert);
  160616. if( rc==SQLITE_OK ){
  160617. rc = rc2;
  160618. }
  160619. }
  160620. }
  160621. sqlite3_free(aCell);
  160622. return rc;
  160623. }
  160624. /*
  160625. ** Insert cell pCell into node pNode. Node pNode is the head of a
  160626. ** subtree iHeight high (leaf nodes have iHeight==0).
  160627. */
  160628. static int rtreeInsertCell(
  160629. Rtree *pRtree,
  160630. RtreeNode *pNode,
  160631. RtreeCell *pCell,
  160632. int iHeight
  160633. ){
  160634. int rc = SQLITE_OK;
  160635. if( iHeight>0 ){
  160636. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  160637. if( pChild ){
  160638. nodeRelease(pRtree, pChild->pParent);
  160639. nodeReference(pNode);
  160640. pChild->pParent = pNode;
  160641. }
  160642. }
  160643. if( nodeInsertCell(pRtree, pNode, pCell) ){
  160644. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  160645. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  160646. }else{
  160647. pRtree->iReinsertHeight = iHeight;
  160648. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  160649. }
  160650. }else{
  160651. rc = AdjustTree(pRtree, pNode, pCell);
  160652. if( rc==SQLITE_OK ){
  160653. if( iHeight==0 ){
  160654. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  160655. }else{
  160656. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  160657. }
  160658. }
  160659. }
  160660. return rc;
  160661. }
  160662. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  160663. int ii;
  160664. int rc = SQLITE_OK;
  160665. int nCell = NCELL(pNode);
  160666. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  160667. RtreeNode *pInsert;
  160668. RtreeCell cell;
  160669. nodeGetCell(pRtree, pNode, ii, &cell);
  160670. /* Find a node to store this cell in. pNode->iNode currently contains
  160671. ** the height of the sub-tree headed by the cell.
  160672. */
  160673. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  160674. if( rc==SQLITE_OK ){
  160675. int rc2;
  160676. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  160677. rc2 = nodeRelease(pRtree, pInsert);
  160678. if( rc==SQLITE_OK ){
  160679. rc = rc2;
  160680. }
  160681. }
  160682. }
  160683. return rc;
  160684. }
  160685. /*
  160686. ** Select a currently unused rowid for a new r-tree record.
  160687. */
  160688. static int newRowid(Rtree *pRtree, i64 *piRowid){
  160689. int rc;
  160690. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  160691. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  160692. sqlite3_step(pRtree->pWriteRowid);
  160693. rc = sqlite3_reset(pRtree->pWriteRowid);
  160694. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  160695. return rc;
  160696. }
  160697. /*
  160698. ** Remove the entry with rowid=iDelete from the r-tree structure.
  160699. */
  160700. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  160701. int rc; /* Return code */
  160702. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  160703. int iCell; /* Index of iDelete cell in pLeaf */
  160704. RtreeNode *pRoot = 0; /* Root node of rtree structure */
  160705. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  160706. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  160707. /* Obtain a reference to the leaf node that contains the entry
  160708. ** about to be deleted.
  160709. */
  160710. if( rc==SQLITE_OK ){
  160711. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  160712. }
  160713. /* Delete the cell in question from the leaf node. */
  160714. if( rc==SQLITE_OK ){
  160715. int rc2;
  160716. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  160717. if( rc==SQLITE_OK ){
  160718. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  160719. }
  160720. rc2 = nodeRelease(pRtree, pLeaf);
  160721. if( rc==SQLITE_OK ){
  160722. rc = rc2;
  160723. }
  160724. }
  160725. /* Delete the corresponding entry in the <rtree>_rowid table. */
  160726. if( rc==SQLITE_OK ){
  160727. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  160728. sqlite3_step(pRtree->pDeleteRowid);
  160729. rc = sqlite3_reset(pRtree->pDeleteRowid);
  160730. }
  160731. /* Check if the root node now has exactly one child. If so, remove
  160732. ** it, schedule the contents of the child for reinsertion and
  160733. ** reduce the tree height by one.
  160734. **
  160735. ** This is equivalent to copying the contents of the child into
  160736. ** the root node (the operation that Gutman's paper says to perform
  160737. ** in this scenario).
  160738. */
  160739. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  160740. int rc2;
  160741. RtreeNode *pChild = 0;
  160742. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  160743. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  160744. if( rc==SQLITE_OK ){
  160745. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  160746. }
  160747. rc2 = nodeRelease(pRtree, pChild);
  160748. if( rc==SQLITE_OK ) rc = rc2;
  160749. if( rc==SQLITE_OK ){
  160750. pRtree->iDepth--;
  160751. writeInt16(pRoot->zData, pRtree->iDepth);
  160752. pRoot->isDirty = 1;
  160753. }
  160754. }
  160755. /* Re-insert the contents of any underfull nodes removed from the tree. */
  160756. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  160757. if( rc==SQLITE_OK ){
  160758. rc = reinsertNodeContent(pRtree, pLeaf);
  160759. }
  160760. pRtree->pDeleted = pLeaf->pNext;
  160761. sqlite3_free(pLeaf);
  160762. }
  160763. /* Release the reference to the root node. */
  160764. if( rc==SQLITE_OK ){
  160765. rc = nodeRelease(pRtree, pRoot);
  160766. }else{
  160767. nodeRelease(pRtree, pRoot);
  160768. }
  160769. return rc;
  160770. }
  160771. /*
  160772. ** Rounding constants for float->double conversion.
  160773. */
  160774. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  160775. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  160776. #if !defined(SQLITE_RTREE_INT_ONLY)
  160777. /*
  160778. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  160779. ** while taking care to round toward negative or positive, respectively.
  160780. */
  160781. static RtreeValue rtreeValueDown(sqlite3_value *v){
  160782. double d = sqlite3_value_double(v);
  160783. float f = (float)d;
  160784. if( f>d ){
  160785. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  160786. }
  160787. return f;
  160788. }
  160789. static RtreeValue rtreeValueUp(sqlite3_value *v){
  160790. double d = sqlite3_value_double(v);
  160791. float f = (float)d;
  160792. if( f<d ){
  160793. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  160794. }
  160795. return f;
  160796. }
  160797. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  160798. /*
  160799. ** A constraint has failed while inserting a row into an rtree table.
  160800. ** Assuming no OOM error occurs, this function sets the error message
  160801. ** (at pRtree->base.zErrMsg) to an appropriate value and returns
  160802. ** SQLITE_CONSTRAINT.
  160803. **
  160804. ** Parameter iCol is the index of the leftmost column involved in the
  160805. ** constraint failure. If it is 0, then the constraint that failed is
  160806. ** the unique constraint on the id column. Otherwise, it is the rtree
  160807. ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
  160808. **
  160809. ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
  160810. */
  160811. static int rtreeConstraintError(Rtree *pRtree, int iCol){
  160812. sqlite3_stmt *pStmt = 0;
  160813. char *zSql;
  160814. int rc;
  160815. assert( iCol==0 || iCol%2 );
  160816. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
  160817. if( zSql ){
  160818. rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
  160819. }else{
  160820. rc = SQLITE_NOMEM;
  160821. }
  160822. sqlite3_free(zSql);
  160823. if( rc==SQLITE_OK ){
  160824. if( iCol==0 ){
  160825. const char *zCol = sqlite3_column_name(pStmt, 0);
  160826. pRtree->base.zErrMsg = sqlite3_mprintf(
  160827. "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
  160828. );
  160829. }else{
  160830. const char *zCol1 = sqlite3_column_name(pStmt, iCol);
  160831. const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
  160832. pRtree->base.zErrMsg = sqlite3_mprintf(
  160833. "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
  160834. );
  160835. }
  160836. }
  160837. sqlite3_finalize(pStmt);
  160838. return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
  160839. }
  160840. /*
  160841. ** The xUpdate method for rtree module virtual tables.
  160842. */
  160843. static int rtreeUpdate(
  160844. sqlite3_vtab *pVtab,
  160845. int nData,
  160846. sqlite3_value **azData,
  160847. sqlite_int64 *pRowid
  160848. ){
  160849. Rtree *pRtree = (Rtree *)pVtab;
  160850. int rc = SQLITE_OK;
  160851. RtreeCell cell; /* New cell to insert if nData>1 */
  160852. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  160853. rtreeReference(pRtree);
  160854. assert(nData>=1);
  160855. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  160856. /* Constraint handling. A write operation on an r-tree table may return
  160857. ** SQLITE_CONSTRAINT for two reasons:
  160858. **
  160859. ** 1. A duplicate rowid value, or
  160860. ** 2. The supplied data violates the "x2>=x1" constraint.
  160861. **
  160862. ** In the first case, if the conflict-handling mode is REPLACE, then
  160863. ** the conflicting row can be removed before proceeding. In the second
  160864. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  160865. ** conflict-handling mode specified by the user.
  160866. */
  160867. if( nData>1 ){
  160868. int ii;
  160869. /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
  160870. **
  160871. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  160872. ** with "column" that are interpreted as table constraints.
  160873. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  160874. ** This problem was discovered after years of use, so we silently ignore
  160875. ** these kinds of misdeclared tables to avoid breaking any legacy.
  160876. */
  160877. assert( nData<=(pRtree->nDim2 + 3) );
  160878. #ifndef SQLITE_RTREE_INT_ONLY
  160879. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  160880. for(ii=0; ii<nData-4; ii+=2){
  160881. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  160882. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  160883. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  160884. rc = rtreeConstraintError(pRtree, ii+1);
  160885. goto constraint;
  160886. }
  160887. }
  160888. }else
  160889. #endif
  160890. {
  160891. for(ii=0; ii<nData-4; ii+=2){
  160892. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  160893. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  160894. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  160895. rc = rtreeConstraintError(pRtree, ii+1);
  160896. goto constraint;
  160897. }
  160898. }
  160899. }
  160900. /* If a rowid value was supplied, check if it is already present in
  160901. ** the table. If so, the constraint has failed. */
  160902. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  160903. cell.iRowid = sqlite3_value_int64(azData[2]);
  160904. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  160905. || sqlite3_value_int64(azData[0])!=cell.iRowid
  160906. ){
  160907. int steprc;
  160908. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  160909. steprc = sqlite3_step(pRtree->pReadRowid);
  160910. rc = sqlite3_reset(pRtree->pReadRowid);
  160911. if( SQLITE_ROW==steprc ){
  160912. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  160913. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  160914. }else{
  160915. rc = rtreeConstraintError(pRtree, 0);
  160916. goto constraint;
  160917. }
  160918. }
  160919. }
  160920. bHaveRowid = 1;
  160921. }
  160922. }
  160923. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  160924. ** record to delete from the r-tree table. The following block does
  160925. ** just that.
  160926. */
  160927. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  160928. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  160929. }
  160930. /* If the azData[] array contains more than one element, elements
  160931. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  160932. ** the r-tree structure.
  160933. */
  160934. if( rc==SQLITE_OK && nData>1 ){
  160935. /* Insert the new record into the r-tree */
  160936. RtreeNode *pLeaf = 0;
  160937. /* Figure out the rowid of the new row. */
  160938. if( bHaveRowid==0 ){
  160939. rc = newRowid(pRtree, &cell.iRowid);
  160940. }
  160941. *pRowid = cell.iRowid;
  160942. if( rc==SQLITE_OK ){
  160943. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  160944. }
  160945. if( rc==SQLITE_OK ){
  160946. int rc2;
  160947. pRtree->iReinsertHeight = -1;
  160948. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  160949. rc2 = nodeRelease(pRtree, pLeaf);
  160950. if( rc==SQLITE_OK ){
  160951. rc = rc2;
  160952. }
  160953. }
  160954. }
  160955. constraint:
  160956. rtreeRelease(pRtree);
  160957. return rc;
  160958. }
  160959. /*
  160960. ** Called when a transaction starts.
  160961. */
  160962. static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
  160963. Rtree *pRtree = (Rtree *)pVtab;
  160964. assert( pRtree->inWrTrans==0 );
  160965. pRtree->inWrTrans++;
  160966. return SQLITE_OK;
  160967. }
  160968. /*
  160969. ** Called when a transaction completes (either by COMMIT or ROLLBACK).
  160970. ** The sqlite3_blob object should be released at this point.
  160971. */
  160972. static int rtreeEndTransaction(sqlite3_vtab *pVtab){
  160973. Rtree *pRtree = (Rtree *)pVtab;
  160974. pRtree->inWrTrans = 0;
  160975. nodeBlobReset(pRtree);
  160976. return SQLITE_OK;
  160977. }
  160978. /*
  160979. ** The xRename method for rtree module virtual tables.
  160980. */
  160981. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  160982. Rtree *pRtree = (Rtree *)pVtab;
  160983. int rc = SQLITE_NOMEM;
  160984. char *zSql = sqlite3_mprintf(
  160985. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  160986. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  160987. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  160988. , pRtree->zDb, pRtree->zName, zNewName
  160989. , pRtree->zDb, pRtree->zName, zNewName
  160990. , pRtree->zDb, pRtree->zName, zNewName
  160991. );
  160992. if( zSql ){
  160993. nodeBlobReset(pRtree);
  160994. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  160995. sqlite3_free(zSql);
  160996. }
  160997. return rc;
  160998. }
  160999. /*
  161000. ** The xSavepoint method.
  161001. **
  161002. ** This module does not need to do anything to support savepoints. However,
  161003. ** it uses this hook to close any open blob handle. This is done because a
  161004. ** DROP TABLE command - which fortunately always opens a savepoint - cannot
  161005. ** succeed if there are any open blob handles. i.e. if the blob handle were
  161006. ** not closed here, the following would fail:
  161007. **
  161008. ** BEGIN;
  161009. ** INSERT INTO rtree...
  161010. ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
  161011. ** COMMIT;
  161012. */
  161013. static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
  161014. Rtree *pRtree = (Rtree *)pVtab;
  161015. int iwt = pRtree->inWrTrans;
  161016. UNUSED_PARAMETER(iSavepoint);
  161017. pRtree->inWrTrans = 0;
  161018. nodeBlobReset(pRtree);
  161019. pRtree->inWrTrans = iwt;
  161020. return SQLITE_OK;
  161021. }
  161022. /*
  161023. ** This function populates the pRtree->nRowEst variable with an estimate
  161024. ** of the number of rows in the virtual table. If possible, this is based
  161025. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  161026. */
  161027. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  161028. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  161029. char *zSql;
  161030. sqlite3_stmt *p;
  161031. int rc;
  161032. i64 nRow = 0;
  161033. rc = sqlite3_table_column_metadata(
  161034. db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
  161035. );
  161036. if( rc!=SQLITE_OK ){
  161037. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  161038. return rc==SQLITE_ERROR ? SQLITE_OK : rc;
  161039. }
  161040. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  161041. if( zSql==0 ){
  161042. rc = SQLITE_NOMEM;
  161043. }else{
  161044. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  161045. if( rc==SQLITE_OK ){
  161046. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  161047. rc = sqlite3_finalize(p);
  161048. }else if( rc!=SQLITE_NOMEM ){
  161049. rc = SQLITE_OK;
  161050. }
  161051. if( rc==SQLITE_OK ){
  161052. if( nRow==0 ){
  161053. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  161054. }else{
  161055. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  161056. }
  161057. }
  161058. sqlite3_free(zSql);
  161059. }
  161060. return rc;
  161061. }
  161062. static sqlite3_module rtreeModule = {
  161063. 2, /* iVersion */
  161064. rtreeCreate, /* xCreate - create a table */
  161065. rtreeConnect, /* xConnect - connect to an existing table */
  161066. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  161067. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  161068. rtreeDestroy, /* xDestroy - Drop a table */
  161069. rtreeOpen, /* xOpen - open a cursor */
  161070. rtreeClose, /* xClose - close a cursor */
  161071. rtreeFilter, /* xFilter - configure scan constraints */
  161072. rtreeNext, /* xNext - advance a cursor */
  161073. rtreeEof, /* xEof */
  161074. rtreeColumn, /* xColumn - read data */
  161075. rtreeRowid, /* xRowid - read data */
  161076. rtreeUpdate, /* xUpdate - write data */
  161077. rtreeBeginTransaction, /* xBegin - begin transaction */
  161078. rtreeEndTransaction, /* xSync - sync transaction */
  161079. rtreeEndTransaction, /* xCommit - commit transaction */
  161080. rtreeEndTransaction, /* xRollback - rollback transaction */
  161081. 0, /* xFindFunction - function overloading */
  161082. rtreeRename, /* xRename - rename the table */
  161083. rtreeSavepoint, /* xSavepoint */
  161084. 0, /* xRelease */
  161085. 0, /* xRollbackTo */
  161086. };
  161087. static int rtreeSqlInit(
  161088. Rtree *pRtree,
  161089. sqlite3 *db,
  161090. const char *zDb,
  161091. const char *zPrefix,
  161092. int isCreate
  161093. ){
  161094. int rc = SQLITE_OK;
  161095. #define N_STATEMENT 8
  161096. static const char *azSql[N_STATEMENT] = {
  161097. /* Write the xxx_node table */
  161098. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  161099. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  161100. /* Read and write the xxx_rowid table */
  161101. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  161102. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  161103. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  161104. /* Read and write the xxx_parent table */
  161105. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  161106. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  161107. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  161108. };
  161109. sqlite3_stmt **appStmt[N_STATEMENT];
  161110. int i;
  161111. pRtree->db = db;
  161112. if( isCreate ){
  161113. char *zCreate = sqlite3_mprintf(
  161114. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  161115. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  161116. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  161117. " parentnode INTEGER);"
  161118. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  161119. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  161120. );
  161121. if( !zCreate ){
  161122. return SQLITE_NOMEM;
  161123. }
  161124. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  161125. sqlite3_free(zCreate);
  161126. if( rc!=SQLITE_OK ){
  161127. return rc;
  161128. }
  161129. }
  161130. appStmt[0] = &pRtree->pWriteNode;
  161131. appStmt[1] = &pRtree->pDeleteNode;
  161132. appStmt[2] = &pRtree->pReadRowid;
  161133. appStmt[3] = &pRtree->pWriteRowid;
  161134. appStmt[4] = &pRtree->pDeleteRowid;
  161135. appStmt[5] = &pRtree->pReadParent;
  161136. appStmt[6] = &pRtree->pWriteParent;
  161137. appStmt[7] = &pRtree->pDeleteParent;
  161138. rc = rtreeQueryStat1(db, pRtree);
  161139. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  161140. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  161141. if( zSql ){
  161142. rc = sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_PERSISTENT,
  161143. appStmt[i], 0);
  161144. }else{
  161145. rc = SQLITE_NOMEM;
  161146. }
  161147. sqlite3_free(zSql);
  161148. }
  161149. return rc;
  161150. }
  161151. /*
  161152. ** The second argument to this function contains the text of an SQL statement
  161153. ** that returns a single integer value. The statement is compiled and executed
  161154. ** using database connection db. If successful, the integer value returned
  161155. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  161156. ** code is returned and the value of *piVal after returning is not defined.
  161157. */
  161158. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  161159. int rc = SQLITE_NOMEM;
  161160. if( zSql ){
  161161. sqlite3_stmt *pStmt = 0;
  161162. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  161163. if( rc==SQLITE_OK ){
  161164. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161165. *piVal = sqlite3_column_int(pStmt, 0);
  161166. }
  161167. rc = sqlite3_finalize(pStmt);
  161168. }
  161169. }
  161170. return rc;
  161171. }
  161172. /*
  161173. ** This function is called from within the xConnect() or xCreate() method to
  161174. ** determine the node-size used by the rtree table being created or connected
  161175. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  161176. ** Otherwise, an SQLite error code is returned.
  161177. **
  161178. ** If this function is being called as part of an xConnect(), then the rtree
  161179. ** table already exists. In this case the node-size is determined by inspecting
  161180. ** the root node of the tree.
  161181. **
  161182. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  161183. ** This ensures that each node is stored on a single database page. If the
  161184. ** database page-size is so large that more than RTREE_MAXCELLS entries
  161185. ** would fit in a single node, use a smaller node-size.
  161186. */
  161187. static int getNodeSize(
  161188. sqlite3 *db, /* Database handle */
  161189. Rtree *pRtree, /* Rtree handle */
  161190. int isCreate, /* True for xCreate, false for xConnect */
  161191. char **pzErr /* OUT: Error message, if any */
  161192. ){
  161193. int rc;
  161194. char *zSql;
  161195. if( isCreate ){
  161196. int iPageSize = 0;
  161197. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  161198. rc = getIntFromStmt(db, zSql, &iPageSize);
  161199. if( rc==SQLITE_OK ){
  161200. pRtree->iNodeSize = iPageSize-64;
  161201. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  161202. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  161203. }
  161204. }else{
  161205. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  161206. }
  161207. }else{
  161208. zSql = sqlite3_mprintf(
  161209. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  161210. pRtree->zDb, pRtree->zName
  161211. );
  161212. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  161213. if( rc!=SQLITE_OK ){
  161214. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  161215. }else if( pRtree->iNodeSize<(512-64) ){
  161216. rc = SQLITE_CORRUPT_VTAB;
  161217. *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
  161218. pRtree->zName);
  161219. }
  161220. }
  161221. sqlite3_free(zSql);
  161222. return rc;
  161223. }
  161224. /*
  161225. ** This function is the implementation of both the xConnect and xCreate
  161226. ** methods of the r-tree virtual table.
  161227. **
  161228. ** argv[0] -> module name
  161229. ** argv[1] -> database name
  161230. ** argv[2] -> table name
  161231. ** argv[...] -> column names...
  161232. */
  161233. static int rtreeInit(
  161234. sqlite3 *db, /* Database connection */
  161235. void *pAux, /* One of the RTREE_COORD_* constants */
  161236. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  161237. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  161238. char **pzErr, /* OUT: Error message, if any */
  161239. int isCreate /* True for xCreate, false for xConnect */
  161240. ){
  161241. int rc = SQLITE_OK;
  161242. Rtree *pRtree;
  161243. int nDb; /* Length of string argv[1] */
  161244. int nName; /* Length of string argv[2] */
  161245. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  161246. const char *aErrMsg[] = {
  161247. 0, /* 0 */
  161248. "Wrong number of columns for an rtree table", /* 1 */
  161249. "Too few columns for an rtree table", /* 2 */
  161250. "Too many columns for an rtree table" /* 3 */
  161251. };
  161252. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  161253. if( aErrMsg[iErr] ){
  161254. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  161255. return SQLITE_ERROR;
  161256. }
  161257. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  161258. /* Allocate the sqlite3_vtab structure */
  161259. nDb = (int)strlen(argv[1]);
  161260. nName = (int)strlen(argv[2]);
  161261. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  161262. if( !pRtree ){
  161263. return SQLITE_NOMEM;
  161264. }
  161265. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  161266. pRtree->nBusy = 1;
  161267. pRtree->base.pModule = &rtreeModule;
  161268. pRtree->zDb = (char *)&pRtree[1];
  161269. pRtree->zName = &pRtree->zDb[nDb+1];
  161270. pRtree->nDim = (u8)((argc-4)/2);
  161271. pRtree->nDim2 = pRtree->nDim*2;
  161272. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  161273. pRtree->eCoordType = (u8)eCoordType;
  161274. memcpy(pRtree->zDb, argv[1], nDb);
  161275. memcpy(pRtree->zName, argv[2], nName);
  161276. /* Figure out the node size to use. */
  161277. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  161278. /* Create/Connect to the underlying relational database schema. If
  161279. ** that is successful, call sqlite3_declare_vtab() to configure
  161280. ** the r-tree table schema.
  161281. */
  161282. if( rc==SQLITE_OK ){
  161283. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  161284. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  161285. }else{
  161286. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  161287. char *zTmp;
  161288. int ii;
  161289. for(ii=4; zSql && ii<argc; ii++){
  161290. zTmp = zSql;
  161291. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  161292. sqlite3_free(zTmp);
  161293. }
  161294. if( zSql ){
  161295. zTmp = zSql;
  161296. zSql = sqlite3_mprintf("%s);", zTmp);
  161297. sqlite3_free(zTmp);
  161298. }
  161299. if( !zSql ){
  161300. rc = SQLITE_NOMEM;
  161301. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  161302. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  161303. }
  161304. sqlite3_free(zSql);
  161305. }
  161306. }
  161307. if( rc==SQLITE_OK ){
  161308. *ppVtab = (sqlite3_vtab *)pRtree;
  161309. }else{
  161310. assert( *ppVtab==0 );
  161311. assert( pRtree->nBusy==1 );
  161312. rtreeRelease(pRtree);
  161313. }
  161314. return rc;
  161315. }
  161316. /*
  161317. ** Implementation of a scalar function that decodes r-tree nodes to
  161318. ** human readable strings. This can be used for debugging and analysis.
  161319. **
  161320. ** The scalar function takes two arguments: (1) the number of dimensions
  161321. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  161322. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  161323. ** deserialize all nodes, a statement like:
  161324. **
  161325. ** SELECT rtreenode(2, data) FROM rt_node;
  161326. **
  161327. ** The human readable string takes the form of a Tcl list with one
  161328. ** entry for each cell in the r-tree node. Each entry is itself a
  161329. ** list, containing the 8-byte rowid/pageno followed by the
  161330. ** <num-dimension>*2 coordinates.
  161331. */
  161332. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  161333. char *zText = 0;
  161334. RtreeNode node;
  161335. Rtree tree;
  161336. int ii;
  161337. UNUSED_PARAMETER(nArg);
  161338. memset(&node, 0, sizeof(RtreeNode));
  161339. memset(&tree, 0, sizeof(Rtree));
  161340. tree.nDim = (u8)sqlite3_value_int(apArg[0]);
  161341. tree.nDim2 = tree.nDim*2;
  161342. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  161343. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  161344. for(ii=0; ii<NCELL(&node); ii++){
  161345. char zCell[512];
  161346. int nCell = 0;
  161347. RtreeCell cell;
  161348. int jj;
  161349. nodeGetCell(&tree, &node, ii, &cell);
  161350. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  161351. nCell = (int)strlen(zCell);
  161352. for(jj=0; jj<tree.nDim2; jj++){
  161353. #ifndef SQLITE_RTREE_INT_ONLY
  161354. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  161355. (double)cell.aCoord[jj].f);
  161356. #else
  161357. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  161358. cell.aCoord[jj].i);
  161359. #endif
  161360. nCell = (int)strlen(zCell);
  161361. }
  161362. if( zText ){
  161363. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  161364. sqlite3_free(zText);
  161365. zText = zTextNew;
  161366. }else{
  161367. zText = sqlite3_mprintf("{%s}", zCell);
  161368. }
  161369. }
  161370. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  161371. }
  161372. /* This routine implements an SQL function that returns the "depth" parameter
  161373. ** from the front of a blob that is an r-tree node. For example:
  161374. **
  161375. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  161376. **
  161377. ** The depth value is 0 for all nodes other than the root node, and the root
  161378. ** node always has nodeno=1, so the example above is the primary use for this
  161379. ** routine. This routine is intended for testing and analysis only.
  161380. */
  161381. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  161382. UNUSED_PARAMETER(nArg);
  161383. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  161384. || sqlite3_value_bytes(apArg[0])<2
  161385. ){
  161386. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  161387. }else{
  161388. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  161389. sqlite3_result_int(ctx, readInt16(zBlob));
  161390. }
  161391. }
  161392. /*
  161393. ** Context object passed between the various routines that make up the
  161394. ** implementation of integrity-check function rtreecheck().
  161395. */
  161396. typedef struct RtreeCheck RtreeCheck;
  161397. struct RtreeCheck {
  161398. sqlite3 *db; /* Database handle */
  161399. const char *zDb; /* Database containing rtree table */
  161400. const char *zTab; /* Name of rtree table */
  161401. int bInt; /* True for rtree_i32 table */
  161402. int nDim; /* Number of dimensions for this rtree tbl */
  161403. sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */
  161404. sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
  161405. int nLeaf; /* Number of leaf cells in table */
  161406. int nNonLeaf; /* Number of non-leaf cells in table */
  161407. int rc; /* Return code */
  161408. char *zReport; /* Message to report */
  161409. int nErr; /* Number of lines in zReport */
  161410. };
  161411. #define RTREE_CHECK_MAX_ERROR 100
  161412. /*
  161413. ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
  161414. ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
  161415. */
  161416. static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
  161417. int rc = sqlite3_reset(pStmt);
  161418. if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
  161419. }
  161420. /*
  161421. ** The second and subsequent arguments to this function are a format string
  161422. ** and printf style arguments. This function formats the string and attempts
  161423. ** to compile it as an SQL statement.
  161424. **
  161425. ** If successful, a pointer to the new SQL statement is returned. Otherwise,
  161426. ** NULL is returned and an error code left in RtreeCheck.rc.
  161427. */
  161428. static sqlite3_stmt *rtreeCheckPrepare(
  161429. RtreeCheck *pCheck, /* RtreeCheck object */
  161430. const char *zFmt, ... /* Format string and trailing args */
  161431. ){
  161432. va_list ap;
  161433. char *z;
  161434. sqlite3_stmt *pRet = 0;
  161435. va_start(ap, zFmt);
  161436. z = sqlite3_vmprintf(zFmt, ap);
  161437. if( pCheck->rc==SQLITE_OK ){
  161438. if( z==0 ){
  161439. pCheck->rc = SQLITE_NOMEM;
  161440. }else{
  161441. pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
  161442. }
  161443. }
  161444. sqlite3_free(z);
  161445. va_end(ap);
  161446. return pRet;
  161447. }
  161448. /*
  161449. ** The second and subsequent arguments to this function are a printf()
  161450. ** style format string and arguments. This function formats the string and
  161451. ** appends it to the report being accumuated in pCheck.
  161452. */
  161453. static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
  161454. va_list ap;
  161455. va_start(ap, zFmt);
  161456. if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
  161457. char *z = sqlite3_vmprintf(zFmt, ap);
  161458. if( z==0 ){
  161459. pCheck->rc = SQLITE_NOMEM;
  161460. }else{
  161461. pCheck->zReport = sqlite3_mprintf("%z%s%z",
  161462. pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
  161463. );
  161464. if( pCheck->zReport==0 ){
  161465. pCheck->rc = SQLITE_NOMEM;
  161466. }
  161467. }
  161468. pCheck->nErr++;
  161469. }
  161470. va_end(ap);
  161471. }
  161472. /*
  161473. ** This function is a no-op if there is already an error code stored
  161474. ** in the RtreeCheck object indicated by the first argument. NULL is
  161475. ** returned in this case.
  161476. **
  161477. ** Otherwise, the contents of rtree table node iNode are loaded from
  161478. ** the database and copied into a buffer obtained from sqlite3_malloc().
  161479. ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
  161480. ** is set to the size of the buffer in bytes.
  161481. **
  161482. ** Or, if an error does occur, NULL is returned and an error code left
  161483. ** in the RtreeCheck object. The final value of *pnNode is undefined in
  161484. ** this case.
  161485. */
  161486. static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
  161487. u8 *pRet = 0; /* Return value */
  161488. assert( pCheck->rc==SQLITE_OK );
  161489. if( pCheck->pGetNode==0 ){
  161490. pCheck->pGetNode = rtreeCheckPrepare(pCheck,
  161491. "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
  161492. pCheck->zDb, pCheck->zTab
  161493. );
  161494. }
  161495. if( pCheck->rc==SQLITE_OK ){
  161496. sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
  161497. if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
  161498. int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
  161499. const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
  161500. pRet = sqlite3_malloc(nNode);
  161501. if( pRet==0 ){
  161502. pCheck->rc = SQLITE_NOMEM;
  161503. }else{
  161504. memcpy(pRet, pNode, nNode);
  161505. *pnNode = nNode;
  161506. }
  161507. }
  161508. rtreeCheckReset(pCheck, pCheck->pGetNode);
  161509. if( pCheck->rc==SQLITE_OK && pRet==0 ){
  161510. rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
  161511. }
  161512. }
  161513. return pRet;
  161514. }
  161515. /*
  161516. ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
  161517. ** (if bLeaf==1) table contains a specified entry. The schemas of the
  161518. ** two tables are:
  161519. **
  161520. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  161521. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  161522. **
  161523. ** In both cases, this function checks that there exists an entry with
  161524. ** IPK value iKey and the second column set to iVal.
  161525. **
  161526. */
  161527. static void rtreeCheckMapping(
  161528. RtreeCheck *pCheck, /* RtreeCheck object */
  161529. int bLeaf, /* True for a leaf cell, false for interior */
  161530. i64 iKey, /* Key for mapping */
  161531. i64 iVal /* Expected value for mapping */
  161532. ){
  161533. int rc;
  161534. sqlite3_stmt *pStmt;
  161535. const char *azSql[2] = {
  161536. "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?",
  161537. "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?"
  161538. };
  161539. assert( bLeaf==0 || bLeaf==1 );
  161540. if( pCheck->aCheckMapping[bLeaf]==0 ){
  161541. pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
  161542. azSql[bLeaf], pCheck->zDb, pCheck->zTab
  161543. );
  161544. }
  161545. if( pCheck->rc!=SQLITE_OK ) return;
  161546. pStmt = pCheck->aCheckMapping[bLeaf];
  161547. sqlite3_bind_int64(pStmt, 1, iKey);
  161548. rc = sqlite3_step(pStmt);
  161549. if( rc==SQLITE_DONE ){
  161550. rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
  161551. iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
  161552. );
  161553. }else if( rc==SQLITE_ROW ){
  161554. i64 ii = sqlite3_column_int64(pStmt, 0);
  161555. if( ii!=iVal ){
  161556. rtreeCheckAppendMsg(pCheck,
  161557. "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
  161558. iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
  161559. );
  161560. }
  161561. }
  161562. rtreeCheckReset(pCheck, pStmt);
  161563. }
  161564. /*
  161565. ** Argument pCell points to an array of coordinates stored on an rtree page.
  161566. ** This function checks that the coordinates are internally consistent (no
  161567. ** x1>x2 conditions) and adds an error message to the RtreeCheck object
  161568. ** if they are not.
  161569. **
  161570. ** Additionally, if pParent is not NULL, then it is assumed to point to
  161571. ** the array of coordinates on the parent page that bound the page
  161572. ** containing pCell. In this case it is also verified that the two
  161573. ** sets of coordinates are mutually consistent and an error message added
  161574. ** to the RtreeCheck object if they are not.
  161575. */
  161576. static void rtreeCheckCellCoord(
  161577. RtreeCheck *pCheck,
  161578. i64 iNode, /* Node id to use in error messages */
  161579. int iCell, /* Cell number to use in error messages */
  161580. u8 *pCell, /* Pointer to cell coordinates */
  161581. u8 *pParent /* Pointer to parent coordinates */
  161582. ){
  161583. RtreeCoord c1, c2;
  161584. RtreeCoord p1, p2;
  161585. int i;
  161586. for(i=0; i<pCheck->nDim; i++){
  161587. readCoord(&pCell[4*2*i], &c1);
  161588. readCoord(&pCell[4*(2*i + 1)], &c2);
  161589. /* printf("%e, %e\n", c1.u.f, c2.u.f); */
  161590. if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
  161591. rtreeCheckAppendMsg(pCheck,
  161592. "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
  161593. );
  161594. }
  161595. if( pParent ){
  161596. readCoord(&pParent[4*2*i], &p1);
  161597. readCoord(&pParent[4*(2*i + 1)], &p2);
  161598. if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
  161599. || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
  161600. ){
  161601. rtreeCheckAppendMsg(pCheck,
  161602. "Dimension %d of cell %d on node %lld is corrupt relative to parent"
  161603. , i, iCell, iNode
  161604. );
  161605. }
  161606. }
  161607. }
  161608. }
  161609. /*
  161610. ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
  161611. ** the r-tree structure. Argument aParent points to the array of coordinates
  161612. ** that bound node iNode on the parent node.
  161613. **
  161614. ** If any problems are discovered, an error message is appended to the
  161615. ** report accumulated in the RtreeCheck object.
  161616. */
  161617. static void rtreeCheckNode(
  161618. RtreeCheck *pCheck,
  161619. int iDepth, /* Depth of iNode (0==leaf) */
  161620. u8 *aParent, /* Buffer containing parent coords */
  161621. i64 iNode /* Node to check */
  161622. ){
  161623. u8 *aNode = 0;
  161624. int nNode = 0;
  161625. assert( iNode==1 || aParent!=0 );
  161626. assert( pCheck->nDim>0 );
  161627. aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
  161628. if( aNode ){
  161629. if( nNode<4 ){
  161630. rtreeCheckAppendMsg(pCheck,
  161631. "Node %lld is too small (%d bytes)", iNode, nNode
  161632. );
  161633. }else{
  161634. int nCell; /* Number of cells on page */
  161635. int i; /* Used to iterate through cells */
  161636. if( aParent==0 ){
  161637. iDepth = readInt16(aNode);
  161638. if( iDepth>RTREE_MAX_DEPTH ){
  161639. rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
  161640. sqlite3_free(aNode);
  161641. return;
  161642. }
  161643. }
  161644. nCell = readInt16(&aNode[2]);
  161645. if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
  161646. rtreeCheckAppendMsg(pCheck,
  161647. "Node %lld is too small for cell count of %d (%d bytes)",
  161648. iNode, nCell, nNode
  161649. );
  161650. }else{
  161651. for(i=0; i<nCell; i++){
  161652. u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
  161653. i64 iVal = readInt64(pCell);
  161654. rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
  161655. if( iDepth>0 ){
  161656. rtreeCheckMapping(pCheck, 0, iVal, iNode);
  161657. rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
  161658. pCheck->nNonLeaf++;
  161659. }else{
  161660. rtreeCheckMapping(pCheck, 1, iVal, iNode);
  161661. pCheck->nLeaf++;
  161662. }
  161663. }
  161664. }
  161665. }
  161666. sqlite3_free(aNode);
  161667. }
  161668. }
  161669. /*
  161670. ** The second argument to this function must be either "_rowid" or
  161671. ** "_parent". This function checks that the number of entries in the
  161672. ** %_rowid or %_parent table is exactly nExpect. If not, it adds
  161673. ** an error message to the report in the RtreeCheck object indicated
  161674. ** by the first argument.
  161675. */
  161676. static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
  161677. if( pCheck->rc==SQLITE_OK ){
  161678. sqlite3_stmt *pCount;
  161679. pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
  161680. pCheck->zDb, pCheck->zTab, zTbl
  161681. );
  161682. if( pCount ){
  161683. if( sqlite3_step(pCount)==SQLITE_ROW ){
  161684. i64 nActual = sqlite3_column_int64(pCount, 0);
  161685. if( nActual!=nExpect ){
  161686. rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
  161687. " - expected %lld, actual %lld" , zTbl, nExpect, nActual
  161688. );
  161689. }
  161690. }
  161691. pCheck->rc = sqlite3_finalize(pCount);
  161692. }
  161693. }
  161694. }
  161695. /*
  161696. ** This function does the bulk of the work for the rtree integrity-check.
  161697. ** It is called by rtreecheck(), which is the SQL function implementation.
  161698. */
  161699. static int rtreeCheckTable(
  161700. sqlite3 *db, /* Database handle to access db through */
  161701. const char *zDb, /* Name of db ("main", "temp" etc.) */
  161702. const char *zTab, /* Name of rtree table to check */
  161703. char **pzReport /* OUT: sqlite3_malloc'd report text */
  161704. ){
  161705. RtreeCheck check; /* Common context for various routines */
  161706. sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */
  161707. int bEnd = 0; /* True if transaction should be closed */
  161708. /* Initialize the context object */
  161709. memset(&check, 0, sizeof(check));
  161710. check.db = db;
  161711. check.zDb = zDb;
  161712. check.zTab = zTab;
  161713. /* If there is not already an open transaction, open one now. This is
  161714. ** to ensure that the queries run as part of this integrity-check operate
  161715. ** on a consistent snapshot. */
  161716. if( sqlite3_get_autocommit(db) ){
  161717. check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
  161718. bEnd = 1;
  161719. }
  161720. /* Find number of dimensions in the rtree table. */
  161721. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
  161722. if( pStmt ){
  161723. int rc;
  161724. check.nDim = (sqlite3_column_count(pStmt) - 1) / 2;
  161725. if( check.nDim<1 ){
  161726. rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
  161727. }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
  161728. check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
  161729. }
  161730. rc = sqlite3_finalize(pStmt);
  161731. if( rc!=SQLITE_CORRUPT ) check.rc = rc;
  161732. }
  161733. /* Do the actual integrity-check */
  161734. if( check.nDim>=1 ){
  161735. if( check.rc==SQLITE_OK ){
  161736. rtreeCheckNode(&check, 0, 0, 1);
  161737. }
  161738. rtreeCheckCount(&check, "_rowid", check.nLeaf);
  161739. rtreeCheckCount(&check, "_parent", check.nNonLeaf);
  161740. }
  161741. /* Finalize SQL statements used by the integrity-check */
  161742. sqlite3_finalize(check.pGetNode);
  161743. sqlite3_finalize(check.aCheckMapping[0]);
  161744. sqlite3_finalize(check.aCheckMapping[1]);
  161745. /* If one was opened, close the transaction */
  161746. if( bEnd ){
  161747. int rc = sqlite3_exec(db, "END", 0, 0, 0);
  161748. if( check.rc==SQLITE_OK ) check.rc = rc;
  161749. }
  161750. *pzReport = check.zReport;
  161751. return check.rc;
  161752. }
  161753. /*
  161754. ** Usage:
  161755. **
  161756. ** rtreecheck(<rtree-table>);
  161757. ** rtreecheck(<database>, <rtree-table>);
  161758. **
  161759. ** Invoking this SQL function runs an integrity-check on the named rtree
  161760. ** table. The integrity-check verifies the following:
  161761. **
  161762. ** 1. For each cell in the r-tree structure (%_node table), that:
  161763. **
  161764. ** a) for each dimension, (coord1 <= coord2).
  161765. **
  161766. ** b) unless the cell is on the root node, that the cell is bounded
  161767. ** by the parent cell on the parent node.
  161768. **
  161769. ** c) for leaf nodes, that there is an entry in the %_rowid
  161770. ** table corresponding to the cell's rowid value that
  161771. ** points to the correct node.
  161772. **
  161773. ** d) for cells on non-leaf nodes, that there is an entry in the
  161774. ** %_parent table mapping from the cell's child node to the
  161775. ** node that it resides on.
  161776. **
  161777. ** 2. That there are the same number of entries in the %_rowid table
  161778. ** as there are leaf cells in the r-tree structure, and that there
  161779. ** is a leaf cell that corresponds to each entry in the %_rowid table.
  161780. **
  161781. ** 3. That there are the same number of entries in the %_parent table
  161782. ** as there are non-leaf cells in the r-tree structure, and that
  161783. ** there is a non-leaf cell that corresponds to each entry in the
  161784. ** %_parent table.
  161785. */
  161786. static void rtreecheck(
  161787. sqlite3_context *ctx,
  161788. int nArg,
  161789. sqlite3_value **apArg
  161790. ){
  161791. if( nArg!=1 && nArg!=2 ){
  161792. sqlite3_result_error(ctx,
  161793. "wrong number of arguments to function rtreecheck()", -1
  161794. );
  161795. }else{
  161796. int rc;
  161797. char *zReport = 0;
  161798. const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
  161799. const char *zTab;
  161800. if( nArg==1 ){
  161801. zTab = zDb;
  161802. zDb = "main";
  161803. }else{
  161804. zTab = (const char*)sqlite3_value_text(apArg[1]);
  161805. }
  161806. rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
  161807. if( rc==SQLITE_OK ){
  161808. sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
  161809. }else{
  161810. sqlite3_result_error_code(ctx, rc);
  161811. }
  161812. sqlite3_free(zReport);
  161813. }
  161814. }
  161815. /*
  161816. ** Register the r-tree module with database handle db. This creates the
  161817. ** virtual table module "rtree" and the debugging/analysis scalar
  161818. ** function "rtreenode".
  161819. */
  161820. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  161821. const int utf8 = SQLITE_UTF8;
  161822. int rc;
  161823. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  161824. if( rc==SQLITE_OK ){
  161825. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  161826. }
  161827. if( rc==SQLITE_OK ){
  161828. rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
  161829. }
  161830. if( rc==SQLITE_OK ){
  161831. #ifdef SQLITE_RTREE_INT_ONLY
  161832. void *c = (void *)RTREE_COORD_INT32;
  161833. #else
  161834. void *c = (void *)RTREE_COORD_REAL32;
  161835. #endif
  161836. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  161837. }
  161838. if( rc==SQLITE_OK ){
  161839. void *c = (void *)RTREE_COORD_INT32;
  161840. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  161841. }
  161842. return rc;
  161843. }
  161844. /*
  161845. ** This routine deletes the RtreeGeomCallback object that was attached
  161846. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  161847. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  161848. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  161849. ** the corresponding SQL function is deleted.
  161850. */
  161851. static void rtreeFreeCallback(void *p){
  161852. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  161853. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  161854. sqlite3_free(p);
  161855. }
  161856. /*
  161857. ** This routine frees the BLOB that is returned by geomCallback().
  161858. */
  161859. static void rtreeMatchArgFree(void *pArg){
  161860. int i;
  161861. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  161862. for(i=0; i<p->nParam; i++){
  161863. sqlite3_value_free(p->apSqlParam[i]);
  161864. }
  161865. sqlite3_free(p);
  161866. }
  161867. /*
  161868. ** Each call to sqlite3_rtree_geometry_callback() or
  161869. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  161870. ** scalar function that is implemented by this routine.
  161871. **
  161872. ** All this function does is construct an RtreeMatchArg object that
  161873. ** contains the geometry-checking callback routines and a list of
  161874. ** parameters to this function, then return that RtreeMatchArg object
  161875. ** as a BLOB.
  161876. **
  161877. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  161878. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  161879. ** out which elements of the R-Tree should be returned by the query.
  161880. */
  161881. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  161882. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  161883. RtreeMatchArg *pBlob;
  161884. int nBlob;
  161885. int memErr = 0;
  161886. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  161887. + nArg*sizeof(sqlite3_value*);
  161888. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  161889. if( !pBlob ){
  161890. sqlite3_result_error_nomem(ctx);
  161891. }else{
  161892. int i;
  161893. pBlob->iSize = nBlob;
  161894. pBlob->cb = pGeomCtx[0];
  161895. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  161896. pBlob->nParam = nArg;
  161897. for(i=0; i<nArg; i++){
  161898. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  161899. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  161900. #ifdef SQLITE_RTREE_INT_ONLY
  161901. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  161902. #else
  161903. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  161904. #endif
  161905. }
  161906. if( memErr ){
  161907. sqlite3_result_error_nomem(ctx);
  161908. rtreeMatchArgFree(pBlob);
  161909. }else{
  161910. sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
  161911. }
  161912. }
  161913. }
  161914. /*
  161915. ** Register a new geometry function for use with the r-tree MATCH operator.
  161916. */
  161917. SQLITE_API int sqlite3_rtree_geometry_callback(
  161918. sqlite3 *db, /* Register SQL function on this connection */
  161919. const char *zGeom, /* Name of the new SQL function */
  161920. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  161921. void *pContext /* Extra data associated with the callback */
  161922. ){
  161923. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  161924. /* Allocate and populate the context object. */
  161925. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  161926. if( !pGeomCtx ) return SQLITE_NOMEM;
  161927. pGeomCtx->xGeom = xGeom;
  161928. pGeomCtx->xQueryFunc = 0;
  161929. pGeomCtx->xDestructor = 0;
  161930. pGeomCtx->pContext = pContext;
  161931. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  161932. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  161933. );
  161934. }
  161935. /*
  161936. ** Register a new 2nd-generation geometry function for use with the
  161937. ** r-tree MATCH operator.
  161938. */
  161939. SQLITE_API int sqlite3_rtree_query_callback(
  161940. sqlite3 *db, /* Register SQL function on this connection */
  161941. const char *zQueryFunc, /* Name of new SQL function */
  161942. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  161943. void *pContext, /* Extra data passed into the callback */
  161944. void (*xDestructor)(void*) /* Destructor for the extra data */
  161945. ){
  161946. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  161947. /* Allocate and populate the context object. */
  161948. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  161949. if( !pGeomCtx ) return SQLITE_NOMEM;
  161950. pGeomCtx->xGeom = 0;
  161951. pGeomCtx->xQueryFunc = xQueryFunc;
  161952. pGeomCtx->xDestructor = xDestructor;
  161953. pGeomCtx->pContext = pContext;
  161954. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  161955. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  161956. );
  161957. }
  161958. #if !SQLITE_CORE
  161959. #ifdef _WIN32
  161960. __declspec(dllexport)
  161961. #endif
  161962. SQLITE_API int sqlite3_rtree_init(
  161963. sqlite3 *db,
  161964. char **pzErrMsg,
  161965. const sqlite3_api_routines *pApi
  161966. ){
  161967. SQLITE_EXTENSION_INIT2(pApi)
  161968. return sqlite3RtreeInit(db);
  161969. }
  161970. #endif
  161971. #endif
  161972. /************** End of rtree.c ***********************************************/
  161973. /************** Begin file icu.c *********************************************/
  161974. /*
  161975. ** 2007 May 6
  161976. **
  161977. ** The author disclaims copyright to this source code. In place of
  161978. ** a legal notice, here is a blessing:
  161979. **
  161980. ** May you do good and not evil.
  161981. ** May you find forgiveness for yourself and forgive others.
  161982. ** May you share freely, never taking more than you give.
  161983. **
  161984. *************************************************************************
  161985. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  161986. **
  161987. ** This file implements an integration between the ICU library
  161988. ** ("International Components for Unicode", an open-source library
  161989. ** for handling unicode data) and SQLite. The integration uses
  161990. ** ICU to provide the following to SQLite:
  161991. **
  161992. ** * An implementation of the SQL regexp() function (and hence REGEXP
  161993. ** operator) using the ICU uregex_XX() APIs.
  161994. **
  161995. ** * Implementations of the SQL scalar upper() and lower() functions
  161996. ** for case mapping.
  161997. **
  161998. ** * Integration of ICU and SQLite collation sequences.
  161999. **
  162000. ** * An implementation of the LIKE operator that uses ICU to
  162001. ** provide case-independent matching.
  162002. */
  162003. #if !defined(SQLITE_CORE) \
  162004. || defined(SQLITE_ENABLE_ICU) \
  162005. || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  162006. /* Include ICU headers */
  162007. #include <unicode/utypes.h>
  162008. #include <unicode/uregex.h>
  162009. #include <unicode/ustring.h>
  162010. #include <unicode/ucol.h>
  162011. /* #include <assert.h> */
  162012. #ifndef SQLITE_CORE
  162013. /* #include "sqlite3ext.h" */
  162014. SQLITE_EXTENSION_INIT1
  162015. #else
  162016. /* #include "sqlite3.h" */
  162017. #endif
  162018. /*
  162019. ** This function is called when an ICU function called from within
  162020. ** the implementation of an SQL scalar function returns an error.
  162021. **
  162022. ** The scalar function context passed as the first argument is
  162023. ** loaded with an error message based on the following two args.
  162024. */
  162025. static void icuFunctionError(
  162026. sqlite3_context *pCtx, /* SQLite scalar function context */
  162027. const char *zName, /* Name of ICU function that failed */
  162028. UErrorCode e /* Error code returned by ICU function */
  162029. ){
  162030. char zBuf[128];
  162031. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  162032. zBuf[127] = '\0';
  162033. sqlite3_result_error(pCtx, zBuf, -1);
  162034. }
  162035. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  162036. /*
  162037. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  162038. ** operator.
  162039. */
  162040. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  162041. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  162042. #endif
  162043. /*
  162044. ** Version of sqlite3_free() that is always a function, never a macro.
  162045. */
  162046. static void xFree(void *p){
  162047. sqlite3_free(p);
  162048. }
  162049. /*
  162050. ** This lookup table is used to help decode the first byte of
  162051. ** a multi-byte UTF8 character. It is copied here from SQLite source
  162052. ** code file utf8.c.
  162053. */
  162054. static const unsigned char icuUtf8Trans1[] = {
  162055. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  162056. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  162057. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  162058. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  162059. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  162060. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  162061. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  162062. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  162063. };
  162064. #define SQLITE_ICU_READ_UTF8(zIn, c) \
  162065. c = *(zIn++); \
  162066. if( c>=0xc0 ){ \
  162067. c = icuUtf8Trans1[c-0xc0]; \
  162068. while( (*zIn & 0xc0)==0x80 ){ \
  162069. c = (c<<6) + (0x3f & *(zIn++)); \
  162070. } \
  162071. }
  162072. #define SQLITE_ICU_SKIP_UTF8(zIn) \
  162073. assert( *zIn ); \
  162074. if( *(zIn++)>=0xc0 ){ \
  162075. while( (*zIn & 0xc0)==0x80 ){zIn++;} \
  162076. }
  162077. /*
  162078. ** Compare two UTF-8 strings for equality where the first string is
  162079. ** a "LIKE" expression. Return true (1) if they are the same and
  162080. ** false (0) if they are different.
  162081. */
  162082. static int icuLikeCompare(
  162083. const uint8_t *zPattern, /* LIKE pattern */
  162084. const uint8_t *zString, /* The UTF-8 string to compare against */
  162085. const UChar32 uEsc /* The escape character */
  162086. ){
  162087. static const uint32_t MATCH_ONE = (uint32_t)'_';
  162088. static const uint32_t MATCH_ALL = (uint32_t)'%';
  162089. int prevEscape = 0; /* True if the previous character was uEsc */
  162090. while( 1 ){
  162091. /* Read (and consume) the next character from the input pattern. */
  162092. uint32_t uPattern;
  162093. SQLITE_ICU_READ_UTF8(zPattern, uPattern);
  162094. if( uPattern==0 ) break;
  162095. /* There are now 4 possibilities:
  162096. **
  162097. ** 1. uPattern is an unescaped match-all character "%",
  162098. ** 2. uPattern is an unescaped match-one character "_",
  162099. ** 3. uPattern is an unescaped escape character, or
  162100. ** 4. uPattern is to be handled as an ordinary character
  162101. */
  162102. if( !prevEscape && uPattern==MATCH_ALL ){
  162103. /* Case 1. */
  162104. uint8_t c;
  162105. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  162106. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  162107. ** test string.
  162108. */
  162109. while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
  162110. if( c==MATCH_ONE ){
  162111. if( *zString==0 ) return 0;
  162112. SQLITE_ICU_SKIP_UTF8(zString);
  162113. }
  162114. zPattern++;
  162115. }
  162116. if( *zPattern==0 ) return 1;
  162117. while( *zString ){
  162118. if( icuLikeCompare(zPattern, zString, uEsc) ){
  162119. return 1;
  162120. }
  162121. SQLITE_ICU_SKIP_UTF8(zString);
  162122. }
  162123. return 0;
  162124. }else if( !prevEscape && uPattern==MATCH_ONE ){
  162125. /* Case 2. */
  162126. if( *zString==0 ) return 0;
  162127. SQLITE_ICU_SKIP_UTF8(zString);
  162128. }else if( !prevEscape && uPattern==(uint32_t)uEsc){
  162129. /* Case 3. */
  162130. prevEscape = 1;
  162131. }else{
  162132. /* Case 4. */
  162133. uint32_t uString;
  162134. SQLITE_ICU_READ_UTF8(zString, uString);
  162135. uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
  162136. uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
  162137. if( uString!=uPattern ){
  162138. return 0;
  162139. }
  162140. prevEscape = 0;
  162141. }
  162142. }
  162143. return *zString==0;
  162144. }
  162145. /*
  162146. ** Implementation of the like() SQL function. This function implements
  162147. ** the build-in LIKE operator. The first argument to the function is the
  162148. ** pattern and the second argument is the string. So, the SQL statements:
  162149. **
  162150. ** A LIKE B
  162151. **
  162152. ** is implemented as like(B, A). If there is an escape character E,
  162153. **
  162154. ** A LIKE B ESCAPE E
  162155. **
  162156. ** is mapped to like(B, A, E).
  162157. */
  162158. static void icuLikeFunc(
  162159. sqlite3_context *context,
  162160. int argc,
  162161. sqlite3_value **argv
  162162. ){
  162163. const unsigned char *zA = sqlite3_value_text(argv[0]);
  162164. const unsigned char *zB = sqlite3_value_text(argv[1]);
  162165. UChar32 uEsc = 0;
  162166. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  162167. ** of deep recursion and N*N behavior in patternCompare().
  162168. */
  162169. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  162170. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  162171. return;
  162172. }
  162173. if( argc==3 ){
  162174. /* The escape character string must consist of a single UTF-8 character.
  162175. ** Otherwise, return an error.
  162176. */
  162177. int nE= sqlite3_value_bytes(argv[2]);
  162178. const unsigned char *zE = sqlite3_value_text(argv[2]);
  162179. int i = 0;
  162180. if( zE==0 ) return;
  162181. U8_NEXT(zE, i, nE, uEsc);
  162182. if( i!=nE){
  162183. sqlite3_result_error(context,
  162184. "ESCAPE expression must be a single character", -1);
  162185. return;
  162186. }
  162187. }
  162188. if( zA && zB ){
  162189. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  162190. }
  162191. }
  162192. /*
  162193. ** Function to delete compiled regexp objects. Registered as
  162194. ** a destructor function with sqlite3_set_auxdata().
  162195. */
  162196. static void icuRegexpDelete(void *p){
  162197. URegularExpression *pExpr = (URegularExpression *)p;
  162198. uregex_close(pExpr);
  162199. }
  162200. /*
  162201. ** Implementation of SQLite REGEXP operator. This scalar function takes
  162202. ** two arguments. The first is a regular expression pattern to compile
  162203. ** the second is a string to match against that pattern. If either
  162204. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  162205. ** is 1 if the string matches the pattern, or 0 otherwise.
  162206. **
  162207. ** SQLite maps the regexp() function to the regexp() operator such
  162208. ** that the following two are equivalent:
  162209. **
  162210. ** zString REGEXP zPattern
  162211. ** regexp(zPattern, zString)
  162212. **
  162213. ** Uses the following ICU regexp APIs:
  162214. **
  162215. ** uregex_open()
  162216. ** uregex_matches()
  162217. ** uregex_close()
  162218. */
  162219. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  162220. UErrorCode status = U_ZERO_ERROR;
  162221. URegularExpression *pExpr;
  162222. UBool res;
  162223. const UChar *zString = sqlite3_value_text16(apArg[1]);
  162224. (void)nArg; /* Unused parameter */
  162225. /* If the left hand side of the regexp operator is NULL,
  162226. ** then the result is also NULL.
  162227. */
  162228. if( !zString ){
  162229. return;
  162230. }
  162231. pExpr = sqlite3_get_auxdata(p, 0);
  162232. if( !pExpr ){
  162233. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  162234. if( !zPattern ){
  162235. return;
  162236. }
  162237. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  162238. if( U_SUCCESS(status) ){
  162239. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  162240. }else{
  162241. assert(!pExpr);
  162242. icuFunctionError(p, "uregex_open", status);
  162243. return;
  162244. }
  162245. }
  162246. /* Configure the text that the regular expression operates on. */
  162247. uregex_setText(pExpr, zString, -1, &status);
  162248. if( !U_SUCCESS(status) ){
  162249. icuFunctionError(p, "uregex_setText", status);
  162250. return;
  162251. }
  162252. /* Attempt the match */
  162253. res = uregex_matches(pExpr, 0, &status);
  162254. if( !U_SUCCESS(status) ){
  162255. icuFunctionError(p, "uregex_matches", status);
  162256. return;
  162257. }
  162258. /* Set the text that the regular expression operates on to a NULL
  162259. ** pointer. This is not really necessary, but it is tidier than
  162260. ** leaving the regular expression object configured with an invalid
  162261. ** pointer after this function returns.
  162262. */
  162263. uregex_setText(pExpr, 0, 0, &status);
  162264. /* Return 1 or 0. */
  162265. sqlite3_result_int(p, res ? 1 : 0);
  162266. }
  162267. /*
  162268. ** Implementations of scalar functions for case mapping - upper() and
  162269. ** lower(). Function upper() converts its input to upper-case (ABC).
  162270. ** Function lower() converts to lower-case (abc).
  162271. **
  162272. ** ICU provides two types of case mapping, "general" case mapping and
  162273. ** "language specific". Refer to ICU documentation for the differences
  162274. ** between the two.
  162275. **
  162276. ** To utilise "general" case mapping, the upper() or lower() scalar
  162277. ** functions are invoked with one argument:
  162278. **
  162279. ** upper('ABC') -> 'abc'
  162280. ** lower('abc') -> 'ABC'
  162281. **
  162282. ** To access ICU "language specific" case mapping, upper() or lower()
  162283. ** should be invoked with two arguments. The second argument is the name
  162284. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  162285. ** as the second argument is the same as invoking the 1 argument version
  162286. ** of upper() or lower().
  162287. **
  162288. ** lower('I', 'en_us') -> 'i'
  162289. ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
  162290. **
  162291. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  162292. */
  162293. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  162294. const UChar *zInput; /* Pointer to input string */
  162295. UChar *zOutput = 0; /* Pointer to output buffer */
  162296. int nInput; /* Size of utf-16 input string in bytes */
  162297. int nOut; /* Size of output buffer in bytes */
  162298. int cnt;
  162299. int bToUpper; /* True for toupper(), false for tolower() */
  162300. UErrorCode status;
  162301. const char *zLocale = 0;
  162302. assert(nArg==1 || nArg==2);
  162303. bToUpper = (sqlite3_user_data(p)!=0);
  162304. if( nArg==2 ){
  162305. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  162306. }
  162307. zInput = sqlite3_value_text16(apArg[0]);
  162308. if( !zInput ){
  162309. return;
  162310. }
  162311. nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  162312. if( nOut==0 ){
  162313. sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
  162314. return;
  162315. }
  162316. for(cnt=0; cnt<2; cnt++){
  162317. UChar *zNew = sqlite3_realloc(zOutput, nOut);
  162318. if( zNew==0 ){
  162319. sqlite3_free(zOutput);
  162320. sqlite3_result_error_nomem(p);
  162321. return;
  162322. }
  162323. zOutput = zNew;
  162324. status = U_ZERO_ERROR;
  162325. if( bToUpper ){
  162326. nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  162327. }else{
  162328. nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  162329. }
  162330. if( U_SUCCESS(status) ){
  162331. sqlite3_result_text16(p, zOutput, nOut, xFree);
  162332. }else if( status==U_BUFFER_OVERFLOW_ERROR ){
  162333. assert( cnt==0 );
  162334. continue;
  162335. }else{
  162336. icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
  162337. }
  162338. return;
  162339. }
  162340. assert( 0 ); /* Unreachable */
  162341. }
  162342. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  162343. /*
  162344. ** Collation sequence destructor function. The pCtx argument points to
  162345. ** a UCollator structure previously allocated using ucol_open().
  162346. */
  162347. static void icuCollationDel(void *pCtx){
  162348. UCollator *p = (UCollator *)pCtx;
  162349. ucol_close(p);
  162350. }
  162351. /*
  162352. ** Collation sequence comparison function. The pCtx argument points to
  162353. ** a UCollator structure previously allocated using ucol_open().
  162354. */
  162355. static int icuCollationColl(
  162356. void *pCtx,
  162357. int nLeft,
  162358. const void *zLeft,
  162359. int nRight,
  162360. const void *zRight
  162361. ){
  162362. UCollationResult res;
  162363. UCollator *p = (UCollator *)pCtx;
  162364. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  162365. switch( res ){
  162366. case UCOL_LESS: return -1;
  162367. case UCOL_GREATER: return +1;
  162368. case UCOL_EQUAL: return 0;
  162369. }
  162370. assert(!"Unexpected return value from ucol_strcoll()");
  162371. return 0;
  162372. }
  162373. /*
  162374. ** Implementation of the scalar function icu_load_collation().
  162375. **
  162376. ** This scalar function is used to add ICU collation based collation
  162377. ** types to an SQLite database connection. It is intended to be called
  162378. ** as follows:
  162379. **
  162380. ** SELECT icu_load_collation(<locale>, <collation-name>);
  162381. **
  162382. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  162383. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  162384. ** collation sequence to create.
  162385. */
  162386. static void icuLoadCollation(
  162387. sqlite3_context *p,
  162388. int nArg,
  162389. sqlite3_value **apArg
  162390. ){
  162391. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  162392. UErrorCode status = U_ZERO_ERROR;
  162393. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  162394. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  162395. UCollator *pUCollator; /* ICU library collation object */
  162396. int rc; /* Return code from sqlite3_create_collation_x() */
  162397. assert(nArg==2);
  162398. (void)nArg; /* Unused parameter */
  162399. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  162400. zName = (const char *)sqlite3_value_text(apArg[1]);
  162401. if( !zLocale || !zName ){
  162402. return;
  162403. }
  162404. pUCollator = ucol_open(zLocale, &status);
  162405. if( !U_SUCCESS(status) ){
  162406. icuFunctionError(p, "ucol_open", status);
  162407. return;
  162408. }
  162409. assert(p);
  162410. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  162411. icuCollationColl, icuCollationDel
  162412. );
  162413. if( rc!=SQLITE_OK ){
  162414. ucol_close(pUCollator);
  162415. sqlite3_result_error(p, "Error registering collation function", -1);
  162416. }
  162417. }
  162418. /*
  162419. ** Register the ICU extension functions with database db.
  162420. */
  162421. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  162422. static const struct IcuScalar {
  162423. const char *zName; /* Function name */
  162424. unsigned char nArg; /* Number of arguments */
  162425. unsigned short enc; /* Optimal text encoding */
  162426. unsigned char iContext; /* sqlite3_user_data() context */
  162427. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  162428. } scalars[] = {
  162429. {"icu_load_collation", 2, SQLITE_UTF8, 1, icuLoadCollation},
  162430. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  162431. {"regexp", 2, SQLITE_ANY|SQLITE_DETERMINISTIC, 0, icuRegexpFunc},
  162432. {"lower", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  162433. {"lower", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  162434. {"upper", 1, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  162435. {"upper", 2, SQLITE_UTF16|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  162436. {"lower", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  162437. {"lower", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuCaseFunc16},
  162438. {"upper", 1, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  162439. {"upper", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 1, icuCaseFunc16},
  162440. {"like", 2, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  162441. {"like", 3, SQLITE_UTF8|SQLITE_DETERMINISTIC, 0, icuLikeFunc},
  162442. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  162443. };
  162444. int rc = SQLITE_OK;
  162445. int i;
  162446. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  162447. const struct IcuScalar *p = &scalars[i];
  162448. rc = sqlite3_create_function(
  162449. db, p->zName, p->nArg, p->enc,
  162450. p->iContext ? (void*)db : (void*)0,
  162451. p->xFunc, 0, 0
  162452. );
  162453. }
  162454. return rc;
  162455. }
  162456. #if !SQLITE_CORE
  162457. #ifdef _WIN32
  162458. __declspec(dllexport)
  162459. #endif
  162460. SQLITE_API int sqlite3_icu_init(
  162461. sqlite3 *db,
  162462. char **pzErrMsg,
  162463. const sqlite3_api_routines *pApi
  162464. ){
  162465. SQLITE_EXTENSION_INIT2(pApi)
  162466. return sqlite3IcuInit(db);
  162467. }
  162468. #endif
  162469. #endif
  162470. /************** End of icu.c *************************************************/
  162471. /************** Begin file fts3_icu.c ****************************************/
  162472. /*
  162473. ** 2007 June 22
  162474. **
  162475. ** The author disclaims copyright to this source code. In place of
  162476. ** a legal notice, here is a blessing:
  162477. **
  162478. ** May you do good and not evil.
  162479. ** May you find forgiveness for yourself and forgive others.
  162480. ** May you share freely, never taking more than you give.
  162481. **
  162482. *************************************************************************
  162483. ** This file implements a tokenizer for fts3 based on the ICU library.
  162484. */
  162485. /* #include "fts3Int.h" */
  162486. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  162487. #ifdef SQLITE_ENABLE_ICU
  162488. /* #include <assert.h> */
  162489. /* #include <string.h> */
  162490. /* #include "fts3_tokenizer.h" */
  162491. #include <unicode/ubrk.h>
  162492. /* #include <unicode/ucol.h> */
  162493. /* #include <unicode/ustring.h> */
  162494. #include <unicode/utf16.h>
  162495. typedef struct IcuTokenizer IcuTokenizer;
  162496. typedef struct IcuCursor IcuCursor;
  162497. struct IcuTokenizer {
  162498. sqlite3_tokenizer base;
  162499. char *zLocale;
  162500. };
  162501. struct IcuCursor {
  162502. sqlite3_tokenizer_cursor base;
  162503. UBreakIterator *pIter; /* ICU break-iterator object */
  162504. int nChar; /* Number of UChar elements in pInput */
  162505. UChar *aChar; /* Copy of input using utf-16 encoding */
  162506. int *aOffset; /* Offsets of each character in utf-8 input */
  162507. int nBuffer;
  162508. char *zBuffer;
  162509. int iToken;
  162510. };
  162511. /*
  162512. ** Create a new tokenizer instance.
  162513. */
  162514. static int icuCreate(
  162515. int argc, /* Number of entries in argv[] */
  162516. const char * const *argv, /* Tokenizer creation arguments */
  162517. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  162518. ){
  162519. IcuTokenizer *p;
  162520. int n = 0;
  162521. if( argc>0 ){
  162522. n = strlen(argv[0])+1;
  162523. }
  162524. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  162525. if( !p ){
  162526. return SQLITE_NOMEM;
  162527. }
  162528. memset(p, 0, sizeof(IcuTokenizer));
  162529. if( n ){
  162530. p->zLocale = (char *)&p[1];
  162531. memcpy(p->zLocale, argv[0], n);
  162532. }
  162533. *ppTokenizer = (sqlite3_tokenizer *)p;
  162534. return SQLITE_OK;
  162535. }
  162536. /*
  162537. ** Destroy a tokenizer
  162538. */
  162539. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  162540. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  162541. sqlite3_free(p);
  162542. return SQLITE_OK;
  162543. }
  162544. /*
  162545. ** Prepare to begin tokenizing a particular string. The input
  162546. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  162547. ** used to incrementally tokenize this string is returned in
  162548. ** *ppCursor.
  162549. */
  162550. static int icuOpen(
  162551. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  162552. const char *zInput, /* Input string */
  162553. int nInput, /* Length of zInput in bytes */
  162554. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  162555. ){
  162556. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  162557. IcuCursor *pCsr;
  162558. const int32_t opt = U_FOLD_CASE_DEFAULT;
  162559. UErrorCode status = U_ZERO_ERROR;
  162560. int nChar;
  162561. UChar32 c;
  162562. int iInput = 0;
  162563. int iOut = 0;
  162564. *ppCursor = 0;
  162565. if( zInput==0 ){
  162566. nInput = 0;
  162567. zInput = "";
  162568. }else if( nInput<0 ){
  162569. nInput = strlen(zInput);
  162570. }
  162571. nChar = nInput+1;
  162572. pCsr = (IcuCursor *)sqlite3_malloc(
  162573. sizeof(IcuCursor) + /* IcuCursor */
  162574. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  162575. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  162576. );
  162577. if( !pCsr ){
  162578. return SQLITE_NOMEM;
  162579. }
  162580. memset(pCsr, 0, sizeof(IcuCursor));
  162581. pCsr->aChar = (UChar *)&pCsr[1];
  162582. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  162583. pCsr->aOffset[iOut] = iInput;
  162584. U8_NEXT(zInput, iInput, nInput, c);
  162585. while( c>0 ){
  162586. int isError = 0;
  162587. c = u_foldCase(c, opt);
  162588. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  162589. if( isError ){
  162590. sqlite3_free(pCsr);
  162591. return SQLITE_ERROR;
  162592. }
  162593. pCsr->aOffset[iOut] = iInput;
  162594. if( iInput<nInput ){
  162595. U8_NEXT(zInput, iInput, nInput, c);
  162596. }else{
  162597. c = 0;
  162598. }
  162599. }
  162600. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  162601. if( !U_SUCCESS(status) ){
  162602. sqlite3_free(pCsr);
  162603. return SQLITE_ERROR;
  162604. }
  162605. pCsr->nChar = iOut;
  162606. ubrk_first(pCsr->pIter);
  162607. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  162608. return SQLITE_OK;
  162609. }
  162610. /*
  162611. ** Close a tokenization cursor previously opened by a call to icuOpen().
  162612. */
  162613. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  162614. IcuCursor *pCsr = (IcuCursor *)pCursor;
  162615. ubrk_close(pCsr->pIter);
  162616. sqlite3_free(pCsr->zBuffer);
  162617. sqlite3_free(pCsr);
  162618. return SQLITE_OK;
  162619. }
  162620. /*
  162621. ** Extract the next token from a tokenization cursor.
  162622. */
  162623. static int icuNext(
  162624. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  162625. const char **ppToken, /* OUT: *ppToken is the token text */
  162626. int *pnBytes, /* OUT: Number of bytes in token */
  162627. int *piStartOffset, /* OUT: Starting offset of token */
  162628. int *piEndOffset, /* OUT: Ending offset of token */
  162629. int *piPosition /* OUT: Position integer of token */
  162630. ){
  162631. IcuCursor *pCsr = (IcuCursor *)pCursor;
  162632. int iStart = 0;
  162633. int iEnd = 0;
  162634. int nByte = 0;
  162635. while( iStart==iEnd ){
  162636. UChar32 c;
  162637. iStart = ubrk_current(pCsr->pIter);
  162638. iEnd = ubrk_next(pCsr->pIter);
  162639. if( iEnd==UBRK_DONE ){
  162640. return SQLITE_DONE;
  162641. }
  162642. while( iStart<iEnd ){
  162643. int iWhite = iStart;
  162644. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  162645. if( u_isspace(c) ){
  162646. iStart = iWhite;
  162647. }else{
  162648. break;
  162649. }
  162650. }
  162651. assert(iStart<=iEnd);
  162652. }
  162653. do {
  162654. UErrorCode status = U_ZERO_ERROR;
  162655. if( nByte ){
  162656. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  162657. if( !zNew ){
  162658. return SQLITE_NOMEM;
  162659. }
  162660. pCsr->zBuffer = zNew;
  162661. pCsr->nBuffer = nByte;
  162662. }
  162663. u_strToUTF8(
  162664. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  162665. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  162666. &status /* Output success/failure */
  162667. );
  162668. } while( nByte>pCsr->nBuffer );
  162669. *ppToken = pCsr->zBuffer;
  162670. *pnBytes = nByte;
  162671. *piStartOffset = pCsr->aOffset[iStart];
  162672. *piEndOffset = pCsr->aOffset[iEnd];
  162673. *piPosition = pCsr->iToken++;
  162674. return SQLITE_OK;
  162675. }
  162676. /*
  162677. ** The set of routines that implement the simple tokenizer
  162678. */
  162679. static const sqlite3_tokenizer_module icuTokenizerModule = {
  162680. 0, /* iVersion */
  162681. icuCreate, /* xCreate */
  162682. icuDestroy, /* xCreate */
  162683. icuOpen, /* xOpen */
  162684. icuClose, /* xClose */
  162685. icuNext, /* xNext */
  162686. 0, /* xLanguageid */
  162687. };
  162688. /*
  162689. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  162690. */
  162691. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  162692. sqlite3_tokenizer_module const**ppModule
  162693. ){
  162694. *ppModule = &icuTokenizerModule;
  162695. }
  162696. #endif /* defined(SQLITE_ENABLE_ICU) */
  162697. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  162698. /************** End of fts3_icu.c ********************************************/
  162699. /************** Begin file sqlite3rbu.c **************************************/
  162700. /*
  162701. ** 2014 August 30
  162702. **
  162703. ** The author disclaims copyright to this source code. In place of
  162704. ** a legal notice, here is a blessing:
  162705. **
  162706. ** May you do good and not evil.
  162707. ** May you find forgiveness for yourself and forgive others.
  162708. ** May you share freely, never taking more than you give.
  162709. **
  162710. *************************************************************************
  162711. **
  162712. **
  162713. ** OVERVIEW
  162714. **
  162715. ** The RBU extension requires that the RBU update be packaged as an
  162716. ** SQLite database. The tables it expects to find are described in
  162717. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  162718. ** that the user wishes to write to, a corresponding data_xyz table is
  162719. ** created in the RBU database and populated with one row for each row to
  162720. ** update, insert or delete from the target table.
  162721. **
  162722. ** The update proceeds in three stages:
  162723. **
  162724. ** 1) The database is updated. The modified database pages are written
  162725. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  162726. ** that it is named "<database>-oal" instead of "<database>-wal".
  162727. ** Because regular SQLite clients do not look for file named
  162728. ** "<database>-oal", they go on using the original database in
  162729. ** rollback mode while the *-oal file is being generated.
  162730. **
  162731. ** During this stage RBU does not update the database by writing
  162732. ** directly to the target tables. Instead it creates "imposter"
  162733. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  162734. ** to update each b-tree individually. All updates required by each
  162735. ** b-tree are completed before moving on to the next, and all
  162736. ** updates are done in sorted key order.
  162737. **
  162738. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  162739. ** location using a call to rename(2). Before doing this the RBU
  162740. ** module takes an EXCLUSIVE lock on the database file, ensuring
  162741. ** that there are no other active readers.
  162742. **
  162743. ** Once the EXCLUSIVE lock is released, any other database readers
  162744. ** detect the new *-wal file and read the database in wal mode. At
  162745. ** this point they see the new version of the database - including
  162746. ** the updates made as part of the RBU update.
  162747. **
  162748. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  162749. ** as a regular database checkpoint, except that a single frame is
  162750. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  162751. ** handle is closed before the entire *-wal file is checkpointed,
  162752. ** the checkpoint progress is saved in the RBU database and the
  162753. ** checkpoint can be resumed by another RBU client at some point in
  162754. ** the future.
  162755. **
  162756. ** POTENTIAL PROBLEMS
  162757. **
  162758. ** The rename() call might not be portable. And RBU is not currently
  162759. ** syncing the directory after renaming the file.
  162760. **
  162761. ** When state is saved, any commit to the *-oal file and the commit to
  162762. ** the RBU update database are not atomic. So if the power fails at the
  162763. ** wrong moment they might get out of sync. As the main database will be
  162764. ** committed before the RBU update database this will likely either just
  162765. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  162766. ** constraint violations).
  162767. **
  162768. ** If some client does modify the target database mid RBU update, or some
  162769. ** other error occurs, the RBU extension will keep throwing errors. It's
  162770. ** not really clear how to get out of this state. The system could just
  162771. ** by delete the RBU update database and *-oal file and have the device
  162772. ** download the update again and start over.
  162773. **
  162774. ** At present, for an UPDATE, both the new.* and old.* records are
  162775. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  162776. ** fields are collected. This means we're probably writing a lot more
  162777. ** data to disk when saving the state of an ongoing update to the RBU
  162778. ** update database than is strictly necessary.
  162779. **
  162780. */
  162781. /* #include <assert.h> */
  162782. /* #include <string.h> */
  162783. /* #include <stdio.h> */
  162784. /* #include "sqlite3.h" */
  162785. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  162786. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  162787. /************** Begin file sqlite3rbu.h **************************************/
  162788. /*
  162789. ** 2014 August 30
  162790. **
  162791. ** The author disclaims copyright to this source code. In place of
  162792. ** a legal notice, here is a blessing:
  162793. **
  162794. ** May you do good and not evil.
  162795. ** May you find forgiveness for yourself and forgive others.
  162796. ** May you share freely, never taking more than you give.
  162797. **
  162798. *************************************************************************
  162799. **
  162800. ** This file contains the public interface for the RBU extension.
  162801. */
  162802. /*
  162803. ** SUMMARY
  162804. **
  162805. ** Writing a transaction containing a large number of operations on
  162806. ** b-tree indexes that are collectively larger than the available cache
  162807. ** memory can be very inefficient.
  162808. **
  162809. ** The problem is that in order to update a b-tree, the leaf page (at least)
  162810. ** containing the entry being inserted or deleted must be modified. If the
  162811. ** working set of leaves is larger than the available cache memory, then a
  162812. ** single leaf that is modified more than once as part of the transaction
  162813. ** may be loaded from or written to the persistent media multiple times.
  162814. ** Additionally, because the index updates are likely to be applied in
  162815. ** random order, access to pages within the database is also likely to be in
  162816. ** random order, which is itself quite inefficient.
  162817. **
  162818. ** One way to improve the situation is to sort the operations on each index
  162819. ** by index key before applying them to the b-tree. This leads to an IO
  162820. ** pattern that resembles a single linear scan through the index b-tree,
  162821. ** and all but guarantees each modified leaf page is loaded and stored
  162822. ** exactly once. SQLite uses this trick to improve the performance of
  162823. ** CREATE INDEX commands. This extension allows it to be used to improve
  162824. ** the performance of large transactions on existing databases.
  162825. **
  162826. ** Additionally, this extension allows the work involved in writing the
  162827. ** large transaction to be broken down into sub-transactions performed
  162828. ** sequentially by separate processes. This is useful if the system cannot
  162829. ** guarantee that a single update process will run for long enough to apply
  162830. ** the entire update, for example because the update is being applied on a
  162831. ** mobile device that is frequently rebooted. Even after the writer process
  162832. ** has committed one or more sub-transactions, other database clients continue
  162833. ** to read from the original database snapshot. In other words, partially
  162834. ** applied transactions are not visible to other clients.
  162835. **
  162836. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  162837. ** transmitted via a wireless network to a mobile device. A transaction
  162838. ** applied using this extension is hence refered to as an "RBU update".
  162839. **
  162840. **
  162841. ** LIMITATIONS
  162842. **
  162843. ** An "RBU update" transaction is subject to the following limitations:
  162844. **
  162845. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  162846. ** only.
  162847. **
  162848. ** * INSERT statements may not use any default values.
  162849. **
  162850. ** * UPDATE and DELETE statements must identify their target rows by
  162851. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  162852. ** KEY fields may not be updated or deleted. If the table being written
  162853. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  162854. **
  162855. ** * UPDATE statements may not modify PRIMARY KEY columns.
  162856. **
  162857. ** * No triggers will be fired.
  162858. **
  162859. ** * No foreign key violations are detected or reported.
  162860. **
  162861. ** * CHECK constraints are not enforced.
  162862. **
  162863. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  162864. **
  162865. **
  162866. ** PREPARATION
  162867. **
  162868. ** An "RBU update" is stored as a separate SQLite database. A database
  162869. ** containing an RBU update is an "RBU database". For each table in the
  162870. ** target database to be updated, the RBU database should contain a table
  162871. ** named "data_<target name>" containing the same set of columns as the
  162872. ** target table, and one more - "rbu_control". The data_% table should
  162873. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  162874. ** the same type as the corresponding column in the target database.
  162875. ** The "rbu_control" column should have no type at all. For example, if
  162876. ** the target database contains:
  162877. **
  162878. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  162879. **
  162880. ** Then the RBU database should contain:
  162881. **
  162882. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  162883. **
  162884. ** The order of the columns in the data_% table does not matter.
  162885. **
  162886. ** Instead of a regular table, the RBU database may also contain virtual
  162887. ** tables or view named using the data_<target> naming scheme.
  162888. **
  162889. ** Instead of the plain data_<target> naming scheme, RBU database tables
  162890. ** may also be named data<integer>_<target>, where <integer> is any sequence
  162891. ** of zero or more numeric characters (0-9). This can be significant because
  162892. ** tables within the RBU database are always processed in order sorted by
  162893. ** name. By judicious selection of the <integer> portion of the names
  162894. ** of the RBU tables the user can therefore control the order in which they
  162895. ** are processed. This can be useful, for example, to ensure that "external
  162896. ** content" FTS4 tables are updated before their underlying content tables.
  162897. **
  162898. ** If the target database table is a virtual table or a table that has no
  162899. ** PRIMARY KEY declaration, the data_% table must also contain a column
  162900. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  162901. ** key column - "rowid". Virtual tables for which the "rowid" column does
  162902. ** not function like a primary key value cannot be updated using RBU. For
  162903. ** example, if the target db contains either of the following:
  162904. **
  162905. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  162906. ** CREATE TABLE x1(a, b)
  162907. **
  162908. ** then the RBU database should contain:
  162909. **
  162910. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  162911. **
  162912. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  162913. ** target table must be present in the input table. For virtual tables,
  162914. ** hidden columns are optional - they are updated by RBU if present in
  162915. ** the input table, or not otherwise. For example, to write to an fts4
  162916. ** table with a hidden languageid column such as:
  162917. **
  162918. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  162919. **
  162920. ** Either of the following input table schemas may be used:
  162921. **
  162922. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  162923. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  162924. **
  162925. ** For each row to INSERT into the target database as part of the RBU
  162926. ** update, the corresponding data_% table should contain a single record
  162927. ** with the "rbu_control" column set to contain integer value 0. The
  162928. ** other columns should be set to the values that make up the new record
  162929. ** to insert.
  162930. **
  162931. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  162932. ** possible to insert a NULL value into the IPK column. Attempting to
  162933. ** do so results in an SQLITE_MISMATCH error.
  162934. **
  162935. ** For each row to DELETE from the target database as part of the RBU
  162936. ** update, the corresponding data_% table should contain a single record
  162937. ** with the "rbu_control" column set to contain integer value 1. The
  162938. ** real primary key values of the row to delete should be stored in the
  162939. ** corresponding columns of the data_% table. The values stored in the
  162940. ** other columns are not used.
  162941. **
  162942. ** For each row to UPDATE from the target database as part of the RBU
  162943. ** update, the corresponding data_% table should contain a single record
  162944. ** with the "rbu_control" column set to contain a value of type text.
  162945. ** The real primary key values identifying the row to update should be
  162946. ** stored in the corresponding columns of the data_% table row, as should
  162947. ** the new values of all columns being update. The text value in the
  162948. ** "rbu_control" column must contain the same number of characters as
  162949. ** there are columns in the target database table, and must consist entirely
  162950. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  162951. ** each column that is being updated, the corresponding character is set to
  162952. ** 'x'. For those that remain as they are, the corresponding character of the
  162953. ** rbu_control value should be set to '.'. For example, given the tables
  162954. ** above, the update statement:
  162955. **
  162956. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  162957. **
  162958. ** is represented by the data_t1 row created by:
  162959. **
  162960. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  162961. **
  162962. ** Instead of an 'x' character, characters of the rbu_control value specified
  162963. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  162964. ** target table with the value stored in the corresponding data_% column, the
  162965. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  162966. ** the target table column. rbu_delta() is invoked with two arguments - the
  162967. ** original value currently stored in the target table column and the
  162968. ** value specified in the data_xxx table.
  162969. **
  162970. ** For example, this row:
  162971. **
  162972. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  162973. **
  162974. ** is similar to an UPDATE statement such as:
  162975. **
  162976. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  162977. **
  162978. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  162979. ** ota_control string, the contents of the data_xxx table column is assumed
  162980. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  162981. ** format used by the fossil source-code management system. In this case
  162982. ** the existing value within the target database table must be of type BLOB.
  162983. ** It is replaced by the result of applying the specified fossil delta to
  162984. ** itself.
  162985. **
  162986. ** If the target database table is a virtual table or a table with no PRIMARY
  162987. ** KEY, the rbu_control value should not include a character corresponding
  162988. ** to the rbu_rowid value. For example, this:
  162989. **
  162990. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  162991. ** VALUES(NULL, 'usa', 12, '.x');
  162992. **
  162993. ** causes a result similar to:
  162994. **
  162995. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  162996. **
  162997. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  162998. ** However, RBU is more efficient if reading the rows in from each data_xxx
  162999. ** table in "rowid" order is roughly the same as reading them sorted by
  163000. ** the PRIMARY KEY of the corresponding target database table. In other
  163001. ** words, rows should be sorted using the destination table PRIMARY KEY
  163002. ** fields before they are inserted into the data_xxx tables.
  163003. **
  163004. ** USAGE
  163005. **
  163006. ** The API declared below allows an application to apply an RBU update
  163007. ** stored on disk to an existing target database. Essentially, the
  163008. ** application:
  163009. **
  163010. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  163011. **
  163012. ** 2) Registers any required virtual table modules with the database
  163013. ** handle returned by sqlite3rbu_db(). Also, if required, register
  163014. ** the rbu_delta() implementation.
  163015. **
  163016. ** 3) Calls the sqlite3rbu_step() function one or more times on
  163017. ** the new handle. Each call to sqlite3rbu_step() performs a single
  163018. ** b-tree operation, so thousands of calls may be required to apply
  163019. ** a complete update.
  163020. **
  163021. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  163022. ** sqlite3rbu_step() has been called enough times to completely
  163023. ** apply the update to the target database, then the RBU database
  163024. ** is marked as fully applied. Otherwise, the state of the RBU
  163025. ** update application is saved in the RBU database for later
  163026. ** resumption.
  163027. **
  163028. ** See comments below for more detail on APIs.
  163029. **
  163030. ** If an update is only partially applied to the target database by the
  163031. ** time sqlite3rbu_close() is called, various state information is saved
  163032. ** within the RBU database. This allows subsequent processes to automatically
  163033. ** resume the RBU update from where it left off.
  163034. **
  163035. ** To remove all RBU extension state information, returning an RBU database
  163036. ** to its original contents, it is sufficient to drop all tables that begin
  163037. ** with the prefix "rbu_"
  163038. **
  163039. ** DATABASE LOCKING
  163040. **
  163041. ** An RBU update may not be applied to a database in WAL mode. Attempting
  163042. ** to do so is an error (SQLITE_ERROR).
  163043. **
  163044. ** While an RBU handle is open, a SHARED lock may be held on the target
  163045. ** database file. This means it is possible for other clients to read the
  163046. ** database, but not to write it.
  163047. **
  163048. ** If an RBU update is started and then suspended before it is completed,
  163049. ** then an external client writes to the database, then attempting to resume
  163050. ** the suspended RBU update is also an error (SQLITE_BUSY).
  163051. */
  163052. #ifndef _SQLITE3RBU_H
  163053. #define _SQLITE3RBU_H
  163054. /* #include "sqlite3.h" ** Required for error code definitions ** */
  163055. #if 0
  163056. extern "C" {
  163057. #endif
  163058. typedef struct sqlite3rbu sqlite3rbu;
  163059. /*
  163060. ** Open an RBU handle.
  163061. **
  163062. ** Argument zTarget is the path to the target database. Argument zRbu is
  163063. ** the path to the RBU database. Each call to this function must be matched
  163064. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  163065. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  163066. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  163067. ** database URI, not a regular file name.
  163068. **
  163069. ** If the zState argument is passed a NULL value, the RBU extension stores
  163070. ** the current state of the update (how many rows have been updated, which
  163071. ** indexes are yet to be updated etc.) within the RBU database itself. This
  163072. ** can be convenient, as it means that the RBU application does not need to
  163073. ** organize removing a separate state file after the update is concluded.
  163074. ** Or, if zState is non-NULL, it must be a path to a database file in which
  163075. ** the RBU extension can store the state of the update.
  163076. **
  163077. ** When resuming an RBU update, the zState argument must be passed the same
  163078. ** value as when the RBU update was started.
  163079. **
  163080. ** Once the RBU update is finished, the RBU extension does not
  163081. ** automatically remove any zState database file, even if it created it.
  163082. **
  163083. ** By default, RBU uses the default VFS to access the files on disk. To
  163084. ** use a VFS other than the default, an SQLite "file:" URI containing a
  163085. ** "vfs=..." option may be passed as the zTarget option.
  163086. **
  163087. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  163088. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  163089. ** not work out of the box with zipvfs. Refer to the comment describing
  163090. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  163091. */
  163092. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  163093. const char *zTarget,
  163094. const char *zRbu,
  163095. const char *zState
  163096. );
  163097. /*
  163098. ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
  163099. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
  163100. ** that it can be suspended and resumed like an RBU update.
  163101. **
  163102. ** The second argument to this function identifies a database in which
  163103. ** to store the state of the RBU vacuum operation if it is suspended. The
  163104. ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
  163105. ** operation, the state database should either not exist or be empty
  163106. ** (contain no tables). If an RBU vacuum is suspended by calling
  163107. ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
  163108. ** returned SQLITE_DONE, the vacuum state is stored in the state database.
  163109. ** The vacuum can be resumed by calling this function to open a new RBU
  163110. ** handle specifying the same target and state databases.
  163111. **
  163112. ** If the second argument passed to this function is NULL, then the
  163113. ** name of the state database is "<database>-vacuum", where <database>
  163114. ** is the name of the target database file. In this case, on UNIX, if the
  163115. ** state database is not already present in the file-system, it is created
  163116. ** with the same permissions as the target db is made.
  163117. **
  163118. ** This function does not delete the state database after an RBU vacuum
  163119. ** is completed, even if it created it. However, if the call to
  163120. ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
  163121. ** of the state tables within the state database are zeroed. This way,
  163122. ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
  163123. ** new RBU vacuum operation.
  163124. **
  163125. ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
  163126. ** describing the sqlite3rbu_create_vfs() API function below for
  163127. ** a description of the complications associated with using RBU with
  163128. ** zipvfs databases.
  163129. */
  163130. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  163131. const char *zTarget,
  163132. const char *zState
  163133. );
  163134. /*
  163135. ** Configure a limit for the amount of temp space that may be used by
  163136. ** the RBU handle passed as the first argument. The new limit is specified
  163137. ** in bytes by the second parameter. If it is positive, the limit is updated.
  163138. ** If the second parameter to this function is passed zero, then the limit
  163139. ** is removed entirely. If the second parameter is negative, the limit is
  163140. ** not modified (this is useful for querying the current limit).
  163141. **
  163142. ** In all cases the returned value is the current limit in bytes (zero
  163143. ** indicates unlimited).
  163144. **
  163145. ** If the temp space limit is exceeded during operation, an SQLITE_FULL
  163146. ** error is returned.
  163147. */
  163148. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
  163149. /*
  163150. ** Return the current amount of temp file space, in bytes, currently used by
  163151. ** the RBU handle passed as the only argument.
  163152. */
  163153. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
  163154. /*
  163155. ** Internally, each RBU connection uses a separate SQLite database
  163156. ** connection to access the target and rbu update databases. This
  163157. ** API allows the application direct access to these database handles.
  163158. **
  163159. ** The first argument passed to this function must be a valid, open, RBU
  163160. ** handle. The second argument should be passed zero to access the target
  163161. ** database handle, or non-zero to access the rbu update database handle.
  163162. ** Accessing the underlying database handles may be useful in the
  163163. ** following scenarios:
  163164. **
  163165. ** * If any target tables are virtual tables, it may be necessary to
  163166. ** call sqlite3_create_module() on the target database handle to
  163167. ** register the required virtual table implementations.
  163168. **
  163169. ** * If the data_xxx tables in the RBU source database are virtual
  163170. ** tables, the application may need to call sqlite3_create_module() on
  163171. ** the rbu update db handle to any required virtual table
  163172. ** implementations.
  163173. **
  163174. ** * If the application uses the "rbu_delta()" feature described above,
  163175. ** it must use sqlite3_create_function() or similar to register the
  163176. ** rbu_delta() implementation with the target database handle.
  163177. **
  163178. ** If an error has occurred, either while opening or stepping the RBU object,
  163179. ** this function may return NULL. The error code and message may be collected
  163180. ** when sqlite3rbu_close() is called.
  163181. **
  163182. ** Database handles returned by this function remain valid until the next
  163183. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  163184. */
  163185. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
  163186. /*
  163187. ** Do some work towards applying the RBU update to the target db.
  163188. **
  163189. ** Return SQLITE_DONE if the update has been completely applied, or
  163190. ** SQLITE_OK if no error occurs but there remains work to do to apply
  163191. ** the RBU update. If an error does occur, some other error code is
  163192. ** returned.
  163193. **
  163194. ** Once a call to sqlite3rbu_step() has returned a value other than
  163195. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  163196. ** that immediately return the same value.
  163197. */
  163198. SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
  163199. /*
  163200. ** Force RBU to save its state to disk.
  163201. **
  163202. ** If a power failure or application crash occurs during an update, following
  163203. ** system recovery RBU may resume the update from the point at which the state
  163204. ** was last saved. In other words, from the most recent successful call to
  163205. ** sqlite3rbu_close() or this function.
  163206. **
  163207. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  163208. */
  163209. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
  163210. /*
  163211. ** Close an RBU handle.
  163212. **
  163213. ** If the RBU update has been completely applied, mark the RBU database
  163214. ** as fully applied. Otherwise, assuming no error has occurred, save the
  163215. ** current state of the RBU update appliation to the RBU database.
  163216. **
  163217. ** If an error has already occurred as part of an sqlite3rbu_step()
  163218. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  163219. ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
  163220. ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
  163221. ** English language error message. It is the responsibility of the caller to
  163222. ** eventually free any such buffer using sqlite3_free().
  163223. **
  163224. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  163225. ** update has been partially applied, or SQLITE_DONE if it has been
  163226. ** completely applied.
  163227. */
  163228. SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  163229. /*
  163230. ** Return the total number of key-value operations (inserts, deletes or
  163231. ** updates) that have been performed on the target database since the
  163232. ** current RBU update was started.
  163233. */
  163234. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
  163235. /*
  163236. ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
  163237. ** progress indications for the two stages of an RBU update. This API may
  163238. ** be useful for driving GUI progress indicators and similar.
  163239. **
  163240. ** An RBU update is divided into two stages:
  163241. **
  163242. ** * Stage 1, in which changes are accumulated in an oal/wal file, and
  163243. ** * Stage 2, in which the contents of the wal file are copied into the
  163244. ** main database.
  163245. **
  163246. ** The update is visible to non-RBU clients during stage 2. During stage 1
  163247. ** non-RBU reader clients may see the original database.
  163248. **
  163249. ** If this API is called during stage 2 of the update, output variable
  163250. ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
  163251. ** to a value between 0 and 10000 to indicate the permyriadage progress of
  163252. ** stage 2. A value of 5000 indicates that stage 2 is half finished,
  163253. ** 9000 indicates that it is 90% finished, and so on.
  163254. **
  163255. ** If this API is called during stage 1 of the update, output variable
  163256. ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
  163257. ** value to which (*pnOne) is set depends on whether or not the RBU
  163258. ** database contains an "rbu_count" table. The rbu_count table, if it
  163259. ** exists, must contain the same columns as the following:
  163260. **
  163261. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  163262. **
  163263. ** There must be one row in the table for each source (data_xxx) table within
  163264. ** the RBU database. The 'tbl' column should contain the name of the source
  163265. ** table. The 'cnt' column should contain the number of rows within the
  163266. ** source table.
  163267. **
  163268. ** If the rbu_count table is present and populated correctly and this
  163269. ** API is called during stage 1, the *pnOne output variable is set to the
  163270. ** permyriadage progress of the same stage. If the rbu_count table does
  163271. ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
  163272. ** table exists but is not correctly populated, the value of the *pnOne
  163273. ** output variable during stage 1 is undefined.
  163274. */
  163275. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
  163276. /*
  163277. ** Obtain an indication as to the current stage of an RBU update or vacuum.
  163278. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
  163279. ** defined in this file. Return values should be interpreted as follows:
  163280. **
  163281. ** SQLITE_RBU_STATE_OAL:
  163282. ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
  163283. ** may either add further data to the *-oal file, or compute data that will
  163284. ** be added by a subsequent call.
  163285. **
  163286. ** SQLITE_RBU_STATE_MOVE:
  163287. ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
  163288. ** will move the *-oal file to the equivalent *-wal path. If the current
  163289. ** operation is an RBU update, then the updated version of the database
  163290. ** file will become visible to ordinary SQLite clients following the next
  163291. ** call to sqlite3rbu_step().
  163292. **
  163293. ** SQLITE_RBU_STATE_CHECKPOINT:
  163294. ** RBU is currently performing an incremental checkpoint. The next call to
  163295. ** sqlite3rbu_step() will copy a page of data from the *-wal file into
  163296. ** the target database file.
  163297. **
  163298. ** SQLITE_RBU_STATE_DONE:
  163299. ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
  163300. ** will immediately return SQLITE_DONE.
  163301. **
  163302. ** SQLITE_RBU_STATE_ERROR:
  163303. ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
  163304. ** immediately return the SQLite error code associated with the error.
  163305. */
  163306. #define SQLITE_RBU_STATE_OAL 1
  163307. #define SQLITE_RBU_STATE_MOVE 2
  163308. #define SQLITE_RBU_STATE_CHECKPOINT 3
  163309. #define SQLITE_RBU_STATE_DONE 4
  163310. #define SQLITE_RBU_STATE_ERROR 5
  163311. SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
  163312. /*
  163313. ** Create an RBU VFS named zName that accesses the underlying file-system
  163314. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  163315. ** then the new RBU VFS uses the default system VFS to access the file-system.
  163316. ** The new object is registered as a non-default VFS with SQLite before
  163317. ** returning.
  163318. **
  163319. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  163320. ** object is created and deleted automatically by RBU.
  163321. **
  163322. ** The exception is for applications that also use zipvfs. In this case,
  163323. ** the custom VFS must be explicitly created by the user before the RBU
  163324. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  163325. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  163326. ** (for example multiplexor) to access the file-system. For example,
  163327. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  163328. ** multiplexor (error checking omitted):
  163329. **
  163330. ** // Create a VFS named "multiplex" (not the default).
  163331. ** sqlite3_multiplex_initialize(0, 0);
  163332. **
  163333. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  163334. ** // second argument were replaced with NULL, the "rbu" VFS would
  163335. ** // access the file-system via the system default VFS, bypassing the
  163336. ** // multiplexor.
  163337. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  163338. **
  163339. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  163340. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  163341. **
  163342. ** // Make zipvfs the default VFS.
  163343. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  163344. **
  163345. ** Because the default VFS created above includes a RBU functionality, it
  163346. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  163347. ** that does not include the RBU layer results in an error.
  163348. **
  163349. ** The overhead of adding the "rbu" VFS to the system is negligible for
  163350. ** non-RBU users. There is no harm in an application accessing the
  163351. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  163352. ** occasionally.
  163353. */
  163354. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  163355. /*
  163356. ** Deregister and destroy an RBU vfs created by an earlier call to
  163357. ** sqlite3rbu_create_vfs().
  163358. **
  163359. ** VFS objects are not reference counted. If a VFS object is destroyed
  163360. ** before all database handles that use it have been closed, the results
  163361. ** are undefined.
  163362. */
  163363. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
  163364. #if 0
  163365. } /* end of the 'extern "C"' block */
  163366. #endif
  163367. #endif /* _SQLITE3RBU_H */
  163368. /************** End of sqlite3rbu.h ******************************************/
  163369. /************** Continuing where we left off in sqlite3rbu.c *****************/
  163370. #if defined(_WIN32_WCE)
  163371. /* #include "windows.h" */
  163372. #endif
  163373. /* Maximum number of prepared UPDATE statements held by this module */
  163374. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  163375. /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
  163376. ** to enable checksum verification.
  163377. */
  163378. #ifndef RBU_ENABLE_DELTA_CKSUM
  163379. # define RBU_ENABLE_DELTA_CKSUM 0
  163380. #endif
  163381. /*
  163382. ** Swap two objects of type TYPE.
  163383. */
  163384. #if !defined(SQLITE_AMALGAMATION)
  163385. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  163386. #endif
  163387. /*
  163388. ** The rbu_state table is used to save the state of a partially applied
  163389. ** update so that it can be resumed later. The table consists of integer
  163390. ** keys mapped to values as follows:
  163391. **
  163392. ** RBU_STATE_STAGE:
  163393. ** May be set to integer values 1, 2, 4 or 5. As follows:
  163394. ** 1: the *-rbu file is currently under construction.
  163395. ** 2: the *-rbu file has been constructed, but not yet moved
  163396. ** to the *-wal path.
  163397. ** 4: the checkpoint is underway.
  163398. ** 5: the rbu update has been checkpointed.
  163399. **
  163400. ** RBU_STATE_TBL:
  163401. ** Only valid if STAGE==1. The target database name of the table
  163402. ** currently being written.
  163403. **
  163404. ** RBU_STATE_IDX:
  163405. ** Only valid if STAGE==1. The target database name of the index
  163406. ** currently being written, or NULL if the main table is currently being
  163407. ** updated.
  163408. **
  163409. ** RBU_STATE_ROW:
  163410. ** Only valid if STAGE==1. Number of rows already processed for the current
  163411. ** table/index.
  163412. **
  163413. ** RBU_STATE_PROGRESS:
  163414. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  163415. ** rbu update.
  163416. **
  163417. ** RBU_STATE_CKPT:
  163418. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  163419. ** header created by recovering the *-wal file. This is used to detect
  163420. ** cases when another client appends frames to the *-wal file in the
  163421. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  163422. ** be continued if this happens).
  163423. **
  163424. ** RBU_STATE_COOKIE:
  163425. ** Valid if STAGE==1. The current change-counter cookie value in the
  163426. ** target db file.
  163427. **
  163428. ** RBU_STATE_OALSZ:
  163429. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  163430. */
  163431. #define RBU_STATE_STAGE 1
  163432. #define RBU_STATE_TBL 2
  163433. #define RBU_STATE_IDX 3
  163434. #define RBU_STATE_ROW 4
  163435. #define RBU_STATE_PROGRESS 5
  163436. #define RBU_STATE_CKPT 6
  163437. #define RBU_STATE_COOKIE 7
  163438. #define RBU_STATE_OALSZ 8
  163439. #define RBU_STATE_PHASEONESTEP 9
  163440. #define RBU_STAGE_OAL 1
  163441. #define RBU_STAGE_MOVE 2
  163442. #define RBU_STAGE_CAPTURE 3
  163443. #define RBU_STAGE_CKPT 4
  163444. #define RBU_STAGE_DONE 5
  163445. #define RBU_CREATE_STATE \
  163446. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  163447. typedef struct RbuFrame RbuFrame;
  163448. typedef struct RbuObjIter RbuObjIter;
  163449. typedef struct RbuState RbuState;
  163450. typedef struct rbu_vfs rbu_vfs;
  163451. typedef struct rbu_file rbu_file;
  163452. typedef struct RbuUpdateStmt RbuUpdateStmt;
  163453. #if !defined(SQLITE_AMALGAMATION)
  163454. typedef unsigned int u32;
  163455. typedef unsigned short u16;
  163456. typedef unsigned char u8;
  163457. typedef sqlite3_int64 i64;
  163458. #endif
  163459. /*
  163460. ** These values must match the values defined in wal.c for the equivalent
  163461. ** locks. These are not magic numbers as they are part of the SQLite file
  163462. ** format.
  163463. */
  163464. #define WAL_LOCK_WRITE 0
  163465. #define WAL_LOCK_CKPT 1
  163466. #define WAL_LOCK_READ0 3
  163467. #define SQLITE_FCNTL_RBUCNT 5149216
  163468. /*
  163469. ** A structure to store values read from the rbu_state table in memory.
  163470. */
  163471. struct RbuState {
  163472. int eStage;
  163473. char *zTbl;
  163474. char *zIdx;
  163475. i64 iWalCksum;
  163476. int nRow;
  163477. i64 nProgress;
  163478. u32 iCookie;
  163479. i64 iOalSz;
  163480. i64 nPhaseOneStep;
  163481. };
  163482. struct RbuUpdateStmt {
  163483. char *zMask; /* Copy of update mask used with pUpdate */
  163484. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  163485. RbuUpdateStmt *pNext;
  163486. };
  163487. /*
  163488. ** An iterator of this type is used to iterate through all objects in
  163489. ** the target database that require updating. For each such table, the
  163490. ** iterator visits, in order:
  163491. **
  163492. ** * the table itself,
  163493. ** * each index of the table (zero or more points to visit), and
  163494. ** * a special "cleanup table" state.
  163495. **
  163496. ** abIndexed:
  163497. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  163498. ** it points to an array of flags nTblCol elements in size. The flag is
  163499. ** set for each column that is either a part of the PK or a part of an
  163500. ** index. Or clear otherwise.
  163501. **
  163502. */
  163503. struct RbuObjIter {
  163504. sqlite3_stmt *pTblIter; /* Iterate through tables */
  163505. sqlite3_stmt *pIdxIter; /* Index iterator */
  163506. int nTblCol; /* Size of azTblCol[] array */
  163507. char **azTblCol; /* Array of unquoted target column names */
  163508. char **azTblType; /* Array of target column types */
  163509. int *aiSrcOrder; /* src table col -> target table col */
  163510. u8 *abTblPk; /* Array of flags, set on target PK columns */
  163511. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  163512. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  163513. int eType; /* Table type - an RBU_PK_XXX value */
  163514. /* Output variables. zTbl==0 implies EOF. */
  163515. int bCleanup; /* True in "cleanup" state */
  163516. const char *zTbl; /* Name of target db table */
  163517. const char *zDataTbl; /* Name of rbu db table (or null) */
  163518. const char *zIdx; /* Name of target db index (or null) */
  163519. int iTnum; /* Root page of current object */
  163520. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  163521. int bUnique; /* Current index is unique */
  163522. int nIndex; /* Number of aux. indexes on table zTbl */
  163523. /* Statements created by rbuObjIterPrepareAll() */
  163524. int nCol; /* Number of columns in current object */
  163525. sqlite3_stmt *pSelect; /* Source data */
  163526. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  163527. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  163528. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  163529. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  163530. RbuUpdateStmt *pRbuUpdate;
  163531. };
  163532. /*
  163533. ** Values for RbuObjIter.eType
  163534. **
  163535. ** 0: Table does not exist (error)
  163536. ** 1: Table has an implicit rowid.
  163537. ** 2: Table has an explicit IPK column.
  163538. ** 3: Table has an external PK index.
  163539. ** 4: Table is WITHOUT ROWID.
  163540. ** 5: Table is a virtual table.
  163541. */
  163542. #define RBU_PK_NOTABLE 0
  163543. #define RBU_PK_NONE 1
  163544. #define RBU_PK_IPK 2
  163545. #define RBU_PK_EXTERNAL 3
  163546. #define RBU_PK_WITHOUT_ROWID 4
  163547. #define RBU_PK_VTAB 5
  163548. /*
  163549. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  163550. ** one of the following operations.
  163551. */
  163552. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  163553. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  163554. #define RBU_REPLACE 3 /* Delete and then insert a row */
  163555. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  163556. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  163557. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  163558. /*
  163559. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  163560. ** file should be copied to page iDbPage of the database file.
  163561. */
  163562. struct RbuFrame {
  163563. u32 iDbPage;
  163564. u32 iWalFrame;
  163565. };
  163566. /*
  163567. ** RBU handle.
  163568. **
  163569. ** nPhaseOneStep:
  163570. ** If the RBU database contains an rbu_count table, this value is set to
  163571. ** a running estimate of the number of b-tree operations required to
  163572. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  163573. ** API to calculate the permyriadage progress of populating the *-oal file
  163574. ** using the formula:
  163575. **
  163576. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  163577. **
  163578. ** nPhaseOneStep is initialized to the sum of:
  163579. **
  163580. ** nRow * (nIndex + 1)
  163581. **
  163582. ** for all source tables in the RBU database, where nRow is the number
  163583. ** of rows in the source table and nIndex the number of indexes on the
  163584. ** corresponding target database table.
  163585. **
  163586. ** This estimate is accurate if the RBU update consists entirely of
  163587. ** INSERT operations. However, it is inaccurate if:
  163588. **
  163589. ** * the RBU update contains any UPDATE operations. If the PK specified
  163590. ** for an UPDATE operation does not exist in the target table, then
  163591. ** no b-tree operations are required on index b-trees. Or if the
  163592. ** specified PK does exist, then (nIndex*2) such operations are
  163593. ** required (one delete and one insert on each index b-tree).
  163594. **
  163595. ** * the RBU update contains any DELETE operations for which the specified
  163596. ** PK does not exist. In this case no operations are required on index
  163597. ** b-trees.
  163598. **
  163599. ** * the RBU update contains REPLACE operations. These are similar to
  163600. ** UPDATE operations.
  163601. **
  163602. ** nPhaseOneStep is updated to account for the conditions above during the
  163603. ** first pass of each source table. The updated nPhaseOneStep value is
  163604. ** stored in the rbu_state table if the RBU update is suspended.
  163605. */
  163606. struct sqlite3rbu {
  163607. int eStage; /* Value of RBU_STATE_STAGE field */
  163608. sqlite3 *dbMain; /* target database handle */
  163609. sqlite3 *dbRbu; /* rbu database handle */
  163610. char *zTarget; /* Path to target db */
  163611. char *zRbu; /* Path to rbu db */
  163612. char *zState; /* Path to state db (or NULL if zRbu) */
  163613. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  163614. int rc; /* Value returned by last rbu_step() call */
  163615. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  163616. int nStep; /* Rows processed for current object */
  163617. int nProgress; /* Rows processed for all objects */
  163618. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  163619. const char *zVfsName; /* Name of automatically created rbu vfs */
  163620. rbu_file *pTargetFd; /* File handle open on target db */
  163621. int nPagePerSector; /* Pages per sector for pTargetFd */
  163622. i64 iOalSz;
  163623. i64 nPhaseOneStep;
  163624. /* The following state variables are used as part of the incremental
  163625. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  163626. ** function rbuSetupCheckpoint() for details. */
  163627. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  163628. u32 mLock;
  163629. int nFrame; /* Entries in aFrame[] array */
  163630. int nFrameAlloc; /* Allocated size of aFrame[] array */
  163631. RbuFrame *aFrame;
  163632. int pgsz;
  163633. u8 *aBuf;
  163634. i64 iWalCksum;
  163635. i64 szTemp; /* Current size of all temp files in use */
  163636. i64 szTempLimit; /* Total size limit for temp files */
  163637. /* Used in RBU vacuum mode only */
  163638. int nRbu; /* Number of RBU VFS in the stack */
  163639. rbu_file *pRbuFd; /* Fd for main db of dbRbu */
  163640. };
  163641. /*
  163642. ** An rbu VFS is implemented using an instance of this structure.
  163643. **
  163644. ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
  163645. ** It is NULL for RBU VFS objects created explicitly using
  163646. ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
  163647. ** space used by the RBU handle.
  163648. */
  163649. struct rbu_vfs {
  163650. sqlite3_vfs base; /* rbu VFS shim methods */
  163651. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  163652. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  163653. sqlite3rbu *pRbu; /* Owner RBU object */
  163654. rbu_file *pMain; /* Linked list of main db files */
  163655. };
  163656. /*
  163657. ** Each file opened by an rbu VFS is represented by an instance of
  163658. ** the following structure.
  163659. **
  163660. ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
  163661. ** "sz" is set to the current size of the database file.
  163662. */
  163663. struct rbu_file {
  163664. sqlite3_file base; /* sqlite3_file methods */
  163665. sqlite3_file *pReal; /* Underlying file handle */
  163666. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  163667. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  163668. i64 sz; /* Size of file in bytes (temp only) */
  163669. int openFlags; /* Flags this file was opened with */
  163670. u32 iCookie; /* Cookie value for main db files */
  163671. u8 iWriteVer; /* "write-version" value for main db files */
  163672. u8 bNolock; /* True to fail EXCLUSIVE locks */
  163673. int nShm; /* Number of entries in apShm[] array */
  163674. char **apShm; /* Array of mmap'd *-shm regions */
  163675. char *zDel; /* Delete this when closing file */
  163676. const char *zWal; /* Wal filename for this main db file */
  163677. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  163678. rbu_file *pMainNext; /* Next MAIN_DB file */
  163679. };
  163680. /*
  163681. ** True for an RBU vacuum handle, or false otherwise.
  163682. */
  163683. #define rbuIsVacuum(p) ((p)->zTarget==0)
  163684. /*************************************************************************
  163685. ** The following three functions, found below:
  163686. **
  163687. ** rbuDeltaGetInt()
  163688. ** rbuDeltaChecksum()
  163689. ** rbuDeltaApply()
  163690. **
  163691. ** are lifted from the fossil source code (http://fossil-scm.org). They
  163692. ** are used to implement the scalar SQL function rbu_fossil_delta().
  163693. */
  163694. /*
  163695. ** Read bytes from *pz and convert them into a positive integer. When
  163696. ** finished, leave *pz pointing to the first character past the end of
  163697. ** the integer. The *pLen parameter holds the length of the string
  163698. ** in *pz and is decremented once for each character in the integer.
  163699. */
  163700. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  163701. static const signed char zValue[] = {
  163702. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  163703. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  163704. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  163705. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  163706. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  163707. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  163708. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  163709. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  163710. };
  163711. unsigned int v = 0;
  163712. int c;
  163713. unsigned char *z = (unsigned char*)*pz;
  163714. unsigned char *zStart = z;
  163715. while( (c = zValue[0x7f&*(z++)])>=0 ){
  163716. v = (v<<6) + c;
  163717. }
  163718. z--;
  163719. *pLen -= z - zStart;
  163720. *pz = (char*)z;
  163721. return v;
  163722. }
  163723. #if RBU_ENABLE_DELTA_CKSUM
  163724. /*
  163725. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  163726. */
  163727. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  163728. const unsigned char *z = (const unsigned char *)zIn;
  163729. unsigned sum0 = 0;
  163730. unsigned sum1 = 0;
  163731. unsigned sum2 = 0;
  163732. unsigned sum3 = 0;
  163733. while(N >= 16){
  163734. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  163735. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  163736. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  163737. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  163738. z += 16;
  163739. N -= 16;
  163740. }
  163741. while(N >= 4){
  163742. sum0 += z[0];
  163743. sum1 += z[1];
  163744. sum2 += z[2];
  163745. sum3 += z[3];
  163746. z += 4;
  163747. N -= 4;
  163748. }
  163749. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  163750. switch(N){
  163751. case 3: sum3 += (z[2] << 8);
  163752. case 2: sum3 += (z[1] << 16);
  163753. case 1: sum3 += (z[0] << 24);
  163754. default: ;
  163755. }
  163756. return sum3;
  163757. }
  163758. #endif
  163759. /*
  163760. ** Apply a delta.
  163761. **
  163762. ** The output buffer should be big enough to hold the whole output
  163763. ** file and a NUL terminator at the end. The delta_output_size()
  163764. ** routine will determine this size for you.
  163765. **
  163766. ** The delta string should be null-terminated. But the delta string
  163767. ** may contain embedded NUL characters (if the input and output are
  163768. ** binary files) so we also have to pass in the length of the delta in
  163769. ** the lenDelta parameter.
  163770. **
  163771. ** This function returns the size of the output file in bytes (excluding
  163772. ** the final NUL terminator character). Except, if the delta string is
  163773. ** malformed or intended for use with a source file other than zSrc,
  163774. ** then this routine returns -1.
  163775. **
  163776. ** Refer to the delta_create() documentation above for a description
  163777. ** of the delta file format.
  163778. */
  163779. static int rbuDeltaApply(
  163780. const char *zSrc, /* The source or pattern file */
  163781. int lenSrc, /* Length of the source file */
  163782. const char *zDelta, /* Delta to apply to the pattern */
  163783. int lenDelta, /* Length of the delta */
  163784. char *zOut /* Write the output into this preallocated buffer */
  163785. ){
  163786. unsigned int limit;
  163787. unsigned int total = 0;
  163788. #if RBU_ENABLE_DELTA_CKSUM
  163789. char *zOrigOut = zOut;
  163790. #endif
  163791. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  163792. if( *zDelta!='\n' ){
  163793. /* ERROR: size integer not terminated by "\n" */
  163794. return -1;
  163795. }
  163796. zDelta++; lenDelta--;
  163797. while( *zDelta && lenDelta>0 ){
  163798. unsigned int cnt, ofst;
  163799. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  163800. switch( zDelta[0] ){
  163801. case '@': {
  163802. zDelta++; lenDelta--;
  163803. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  163804. if( lenDelta>0 && zDelta[0]!=',' ){
  163805. /* ERROR: copy command not terminated by ',' */
  163806. return -1;
  163807. }
  163808. zDelta++; lenDelta--;
  163809. total += cnt;
  163810. if( total>limit ){
  163811. /* ERROR: copy exceeds output file size */
  163812. return -1;
  163813. }
  163814. if( (int)(ofst+cnt) > lenSrc ){
  163815. /* ERROR: copy extends past end of input */
  163816. return -1;
  163817. }
  163818. memcpy(zOut, &zSrc[ofst], cnt);
  163819. zOut += cnt;
  163820. break;
  163821. }
  163822. case ':': {
  163823. zDelta++; lenDelta--;
  163824. total += cnt;
  163825. if( total>limit ){
  163826. /* ERROR: insert command gives an output larger than predicted */
  163827. return -1;
  163828. }
  163829. if( (int)cnt>lenDelta ){
  163830. /* ERROR: insert count exceeds size of delta */
  163831. return -1;
  163832. }
  163833. memcpy(zOut, zDelta, cnt);
  163834. zOut += cnt;
  163835. zDelta += cnt;
  163836. lenDelta -= cnt;
  163837. break;
  163838. }
  163839. case ';': {
  163840. zDelta++; lenDelta--;
  163841. zOut[0] = 0;
  163842. #if RBU_ENABLE_DELTA_CKSUM
  163843. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  163844. /* ERROR: bad checksum */
  163845. return -1;
  163846. }
  163847. #endif
  163848. if( total!=limit ){
  163849. /* ERROR: generated size does not match predicted size */
  163850. return -1;
  163851. }
  163852. return total;
  163853. }
  163854. default: {
  163855. /* ERROR: unknown delta operator */
  163856. return -1;
  163857. }
  163858. }
  163859. }
  163860. /* ERROR: unterminated delta */
  163861. return -1;
  163862. }
  163863. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  163864. int size;
  163865. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  163866. if( *zDelta!='\n' ){
  163867. /* ERROR: size integer not terminated by "\n" */
  163868. return -1;
  163869. }
  163870. return size;
  163871. }
  163872. /*
  163873. ** End of code taken from fossil.
  163874. *************************************************************************/
  163875. /*
  163876. ** Implementation of SQL scalar function rbu_fossil_delta().
  163877. **
  163878. ** This function applies a fossil delta patch to a blob. Exactly two
  163879. ** arguments must be passed to this function. The first is the blob to
  163880. ** patch and the second the patch to apply. If no error occurs, this
  163881. ** function returns the patched blob.
  163882. */
  163883. static void rbuFossilDeltaFunc(
  163884. sqlite3_context *context,
  163885. int argc,
  163886. sqlite3_value **argv
  163887. ){
  163888. const char *aDelta;
  163889. int nDelta;
  163890. const char *aOrig;
  163891. int nOrig;
  163892. int nOut;
  163893. int nOut2;
  163894. char *aOut;
  163895. assert( argc==2 );
  163896. nOrig = sqlite3_value_bytes(argv[0]);
  163897. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  163898. nDelta = sqlite3_value_bytes(argv[1]);
  163899. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  163900. /* Figure out the size of the output */
  163901. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  163902. if( nOut<0 ){
  163903. sqlite3_result_error(context, "corrupt fossil delta", -1);
  163904. return;
  163905. }
  163906. aOut = sqlite3_malloc(nOut+1);
  163907. if( aOut==0 ){
  163908. sqlite3_result_error_nomem(context);
  163909. }else{
  163910. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  163911. if( nOut2!=nOut ){
  163912. sqlite3_result_error(context, "corrupt fossil delta", -1);
  163913. }else{
  163914. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  163915. }
  163916. }
  163917. }
  163918. /*
  163919. ** Prepare the SQL statement in buffer zSql against database handle db.
  163920. ** If successful, set *ppStmt to point to the new statement and return
  163921. ** SQLITE_OK.
  163922. **
  163923. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  163924. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  163925. ** point to a buffer containing an error message. It is the responsibility
  163926. ** of the caller to (eventually) free this buffer using sqlite3_free().
  163927. */
  163928. static int prepareAndCollectError(
  163929. sqlite3 *db,
  163930. sqlite3_stmt **ppStmt,
  163931. char **pzErrmsg,
  163932. const char *zSql
  163933. ){
  163934. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  163935. if( rc!=SQLITE_OK ){
  163936. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  163937. *ppStmt = 0;
  163938. }
  163939. return rc;
  163940. }
  163941. /*
  163942. ** Reset the SQL statement passed as the first argument. Return a copy
  163943. ** of the value returned by sqlite3_reset().
  163944. **
  163945. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  163946. ** containing an error message. It is the responsibility of the caller
  163947. ** to eventually free this buffer using sqlite3_free().
  163948. */
  163949. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  163950. int rc = sqlite3_reset(pStmt);
  163951. if( rc!=SQLITE_OK ){
  163952. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  163953. }
  163954. return rc;
  163955. }
  163956. /*
  163957. ** Unless it is NULL, argument zSql points to a buffer allocated using
  163958. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  163959. ** statement against database db and frees the buffer. If statement
  163960. ** compilation is successful, *ppStmt is set to point to the new statement
  163961. ** handle and SQLITE_OK is returned.
  163962. **
  163963. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  163964. ** returned. In this case, *pzErrmsg may also be set to point to an error
  163965. ** message. It is the responsibility of the caller to free this error message
  163966. ** buffer using sqlite3_free().
  163967. **
  163968. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  163969. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  163970. */
  163971. static int prepareFreeAndCollectError(
  163972. sqlite3 *db,
  163973. sqlite3_stmt **ppStmt,
  163974. char **pzErrmsg,
  163975. char *zSql
  163976. ){
  163977. int rc;
  163978. assert( *pzErrmsg==0 );
  163979. if( zSql==0 ){
  163980. rc = SQLITE_NOMEM;
  163981. *ppStmt = 0;
  163982. }else{
  163983. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  163984. sqlite3_free(zSql);
  163985. }
  163986. return rc;
  163987. }
  163988. /*
  163989. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  163990. ** by an earlier call to rbuObjIterCacheTableInfo().
  163991. */
  163992. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  163993. int i;
  163994. for(i=0; i<pIter->nTblCol; i++){
  163995. sqlite3_free(pIter->azTblCol[i]);
  163996. sqlite3_free(pIter->azTblType[i]);
  163997. }
  163998. sqlite3_free(pIter->azTblCol);
  163999. pIter->azTblCol = 0;
  164000. pIter->azTblType = 0;
  164001. pIter->aiSrcOrder = 0;
  164002. pIter->abTblPk = 0;
  164003. pIter->abNotNull = 0;
  164004. pIter->nTblCol = 0;
  164005. pIter->eType = 0; /* Invalid value */
  164006. }
  164007. /*
  164008. ** Finalize all statements and free all allocations that are specific to
  164009. ** the current object (table/index pair).
  164010. */
  164011. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  164012. RbuUpdateStmt *pUp;
  164013. sqlite3_finalize(pIter->pSelect);
  164014. sqlite3_finalize(pIter->pInsert);
  164015. sqlite3_finalize(pIter->pDelete);
  164016. sqlite3_finalize(pIter->pTmpInsert);
  164017. pUp = pIter->pRbuUpdate;
  164018. while( pUp ){
  164019. RbuUpdateStmt *pTmp = pUp->pNext;
  164020. sqlite3_finalize(pUp->pUpdate);
  164021. sqlite3_free(pUp);
  164022. pUp = pTmp;
  164023. }
  164024. pIter->pSelect = 0;
  164025. pIter->pInsert = 0;
  164026. pIter->pDelete = 0;
  164027. pIter->pRbuUpdate = 0;
  164028. pIter->pTmpInsert = 0;
  164029. pIter->nCol = 0;
  164030. }
  164031. /*
  164032. ** Clean up any resources allocated as part of the iterator object passed
  164033. ** as the only argument.
  164034. */
  164035. static void rbuObjIterFinalize(RbuObjIter *pIter){
  164036. rbuObjIterClearStatements(pIter);
  164037. sqlite3_finalize(pIter->pTblIter);
  164038. sqlite3_finalize(pIter->pIdxIter);
  164039. rbuObjIterFreeCols(pIter);
  164040. memset(pIter, 0, sizeof(RbuObjIter));
  164041. }
  164042. /*
  164043. ** Advance the iterator to the next position.
  164044. **
  164045. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  164046. ** pointing to the next entry. Otherwise, an error code and message is
  164047. ** left in the RBU handle passed as the first argument. A copy of the
  164048. ** error code is returned.
  164049. */
  164050. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  164051. int rc = p->rc;
  164052. if( rc==SQLITE_OK ){
  164053. /* Free any SQLite statements used while processing the previous object */
  164054. rbuObjIterClearStatements(pIter);
  164055. if( pIter->zIdx==0 ){
  164056. rc = sqlite3_exec(p->dbMain,
  164057. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  164058. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  164059. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  164060. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  164061. , 0, 0, &p->zErrmsg
  164062. );
  164063. }
  164064. if( rc==SQLITE_OK ){
  164065. if( pIter->bCleanup ){
  164066. rbuObjIterFreeCols(pIter);
  164067. pIter->bCleanup = 0;
  164068. rc = sqlite3_step(pIter->pTblIter);
  164069. if( rc!=SQLITE_ROW ){
  164070. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  164071. pIter->zTbl = 0;
  164072. }else{
  164073. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  164074. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  164075. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  164076. }
  164077. }else{
  164078. if( pIter->zIdx==0 ){
  164079. sqlite3_stmt *pIdx = pIter->pIdxIter;
  164080. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  164081. }
  164082. if( rc==SQLITE_OK ){
  164083. rc = sqlite3_step(pIter->pIdxIter);
  164084. if( rc!=SQLITE_ROW ){
  164085. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  164086. pIter->bCleanup = 1;
  164087. pIter->zIdx = 0;
  164088. }else{
  164089. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  164090. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  164091. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  164092. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  164093. }
  164094. }
  164095. }
  164096. }
  164097. }
  164098. if( rc!=SQLITE_OK ){
  164099. rbuObjIterFinalize(pIter);
  164100. p->rc = rc;
  164101. }
  164102. return rc;
  164103. }
  164104. /*
  164105. ** The implementation of the rbu_target_name() SQL function. This function
  164106. ** accepts one or two arguments. The first argument is the name of a table -
  164107. ** the name of a table in the RBU database. The second, if it is present, is 1
  164108. ** for a view or 0 for a table.
  164109. **
  164110. ** For a non-vacuum RBU handle, if the table name matches the pattern:
  164111. **
  164112. ** data[0-9]_<name>
  164113. **
  164114. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  164115. ** Otherwise, if the only argument does not match the above pattern, an SQL
  164116. ** NULL is returned.
  164117. **
  164118. ** "data_t1" -> "t1"
  164119. ** "data0123_t2" -> "t2"
  164120. ** "dataAB_t3" -> NULL
  164121. **
  164122. ** For an rbu vacuum handle, a copy of the first argument is returned if
  164123. ** the second argument is either missing or 0 (not a view).
  164124. */
  164125. static void rbuTargetNameFunc(
  164126. sqlite3_context *pCtx,
  164127. int argc,
  164128. sqlite3_value **argv
  164129. ){
  164130. sqlite3rbu *p = sqlite3_user_data(pCtx);
  164131. const char *zIn;
  164132. assert( argc==1 || argc==2 );
  164133. zIn = (const char*)sqlite3_value_text(argv[0]);
  164134. if( zIn ){
  164135. if( rbuIsVacuum(p) ){
  164136. if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
  164137. sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
  164138. }
  164139. }else{
  164140. if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  164141. int i;
  164142. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  164143. if( zIn[i]=='_' && zIn[i+1] ){
  164144. sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
  164145. }
  164146. }
  164147. }
  164148. }
  164149. }
  164150. /*
  164151. ** Initialize the iterator structure passed as the second argument.
  164152. **
  164153. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  164154. ** pointing to the first entry. Otherwise, an error code and message is
  164155. ** left in the RBU handle passed as the first argument. A copy of the
  164156. ** error code is returned.
  164157. */
  164158. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  164159. int rc;
  164160. memset(pIter, 0, sizeof(RbuObjIter));
  164161. rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  164162. sqlite3_mprintf(
  164163. "SELECT rbu_target_name(name, type='view') AS target, name "
  164164. "FROM sqlite_master "
  164165. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  164166. " %s "
  164167. "ORDER BY name"
  164168. , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
  164169. if( rc==SQLITE_OK ){
  164170. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  164171. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  164172. " FROM main.sqlite_master "
  164173. " WHERE type='index' AND tbl_name = ?"
  164174. );
  164175. }
  164176. pIter->bCleanup = 1;
  164177. p->rc = rc;
  164178. return rbuObjIterNext(p, pIter);
  164179. }
  164180. /*
  164181. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  164182. ** an error code is stored in the RBU handle passed as the first argument.
  164183. **
  164184. ** If an error has already occurred (p->rc is already set to something other
  164185. ** than SQLITE_OK), then this function returns NULL without modifying the
  164186. ** stored error code. In this case it still calls sqlite3_free() on any
  164187. ** printf() parameters associated with %z conversions.
  164188. */
  164189. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  164190. char *zSql = 0;
  164191. va_list ap;
  164192. va_start(ap, zFmt);
  164193. zSql = sqlite3_vmprintf(zFmt, ap);
  164194. if( p->rc==SQLITE_OK ){
  164195. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  164196. }else{
  164197. sqlite3_free(zSql);
  164198. zSql = 0;
  164199. }
  164200. va_end(ap);
  164201. return zSql;
  164202. }
  164203. /*
  164204. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  164205. ** arguments are the usual subsitution values. This function performs
  164206. ** the printf() style substitutions and executes the result as an SQL
  164207. ** statement on the RBU handles database.
  164208. **
  164209. ** If an error occurs, an error code and error message is stored in the
  164210. ** RBU handle. If an error has already occurred when this function is
  164211. ** called, it is a no-op.
  164212. */
  164213. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  164214. va_list ap;
  164215. char *zSql;
  164216. va_start(ap, zFmt);
  164217. zSql = sqlite3_vmprintf(zFmt, ap);
  164218. if( p->rc==SQLITE_OK ){
  164219. if( zSql==0 ){
  164220. p->rc = SQLITE_NOMEM;
  164221. }else{
  164222. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  164223. }
  164224. }
  164225. sqlite3_free(zSql);
  164226. va_end(ap);
  164227. return p->rc;
  164228. }
  164229. /*
  164230. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  164231. ** bytes.
  164232. **
  164233. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  164234. ** error code in the rbu handle passed as the first argument. Or, if an
  164235. ** error has already occurred when this function is called, return NULL
  164236. ** immediately without attempting the allocation or modifying the stored
  164237. ** error code.
  164238. */
  164239. static void *rbuMalloc(sqlite3rbu *p, int nByte){
  164240. void *pRet = 0;
  164241. if( p->rc==SQLITE_OK ){
  164242. assert( nByte>0 );
  164243. pRet = sqlite3_malloc64(nByte);
  164244. if( pRet==0 ){
  164245. p->rc = SQLITE_NOMEM;
  164246. }else{
  164247. memset(pRet, 0, nByte);
  164248. }
  164249. }
  164250. return pRet;
  164251. }
  164252. /*
  164253. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  164254. ** there is room for at least nCol elements. If an OOM occurs, store an
  164255. ** error code in the RBU handle passed as the first argument.
  164256. */
  164257. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  164258. int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  164259. char **azNew;
  164260. azNew = (char**)rbuMalloc(p, nByte);
  164261. if( azNew ){
  164262. pIter->azTblCol = azNew;
  164263. pIter->azTblType = &azNew[nCol];
  164264. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  164265. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  164266. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  164267. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  164268. }
  164269. }
  164270. /*
  164271. ** The first argument must be a nul-terminated string. This function
  164272. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  164273. ** It is the responsibility of the caller to eventually free this memory
  164274. ** using sqlite3_free().
  164275. **
  164276. ** If an OOM condition is encountered when attempting to allocate memory,
  164277. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  164278. ** if the allocation succeeds, (*pRc) is left unchanged.
  164279. */
  164280. static char *rbuStrndup(const char *zStr, int *pRc){
  164281. char *zRet = 0;
  164282. assert( *pRc==SQLITE_OK );
  164283. if( zStr ){
  164284. size_t nCopy = strlen(zStr) + 1;
  164285. zRet = (char*)sqlite3_malloc64(nCopy);
  164286. if( zRet ){
  164287. memcpy(zRet, zStr, nCopy);
  164288. }else{
  164289. *pRc = SQLITE_NOMEM;
  164290. }
  164291. }
  164292. return zRet;
  164293. }
  164294. /*
  164295. ** Finalize the statement passed as the second argument.
  164296. **
  164297. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  164298. ** rbu handle error code is not already set, set the error code and error
  164299. ** message accordingly.
  164300. */
  164301. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  164302. sqlite3 *db = sqlite3_db_handle(pStmt);
  164303. int rc = sqlite3_finalize(pStmt);
  164304. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  164305. p->rc = rc;
  164306. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  164307. }
  164308. }
  164309. /* Determine the type of a table.
  164310. **
  164311. ** peType is of type (int*), a pointer to an output parameter of type
  164312. ** (int). This call sets the output parameter as follows, depending
  164313. ** on the type of the table specified by parameters dbName and zTbl.
  164314. **
  164315. ** RBU_PK_NOTABLE: No such table.
  164316. ** RBU_PK_NONE: Table has an implicit rowid.
  164317. ** RBU_PK_IPK: Table has an explicit IPK column.
  164318. ** RBU_PK_EXTERNAL: Table has an external PK index.
  164319. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  164320. ** RBU_PK_VTAB: Table is a virtual table.
  164321. **
  164322. ** Argument *piPk is also of type (int*), and also points to an output
  164323. ** parameter. Unless the table has an external primary key index
  164324. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  164325. ** if the table does have an external primary key index, then *piPk
  164326. ** is set to the root page number of the primary key index before
  164327. ** returning.
  164328. **
  164329. ** ALGORITHM:
  164330. **
  164331. ** if( no entry exists in sqlite_master ){
  164332. ** return RBU_PK_NOTABLE
  164333. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  164334. ** return RBU_PK_VTAB
  164335. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  164336. ** if( the index that is the pk exists in sqlite_master ){
  164337. ** *piPK = rootpage of that index.
  164338. ** return RBU_PK_EXTERNAL
  164339. ** }else{
  164340. ** return RBU_PK_WITHOUT_ROWID
  164341. ** }
  164342. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  164343. ** return RBU_PK_IPK
  164344. ** }else{
  164345. ** return RBU_PK_NONE
  164346. ** }
  164347. */
  164348. static void rbuTableType(
  164349. sqlite3rbu *p,
  164350. const char *zTab,
  164351. int *peType,
  164352. int *piTnum,
  164353. int *piPk
  164354. ){
  164355. /*
  164356. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  164357. ** 1) PRAGMA index_list = ?
  164358. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  164359. ** 3) PRAGMA table_info = ?
  164360. */
  164361. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  164362. *peType = RBU_PK_NOTABLE;
  164363. *piPk = 0;
  164364. assert( p->rc==SQLITE_OK );
  164365. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  164366. sqlite3_mprintf(
  164367. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  164368. " FROM sqlite_master"
  164369. " WHERE name=%Q", zTab
  164370. ));
  164371. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  164372. /* Either an error, or no such table. */
  164373. goto rbuTableType_end;
  164374. }
  164375. if( sqlite3_column_int(aStmt[0], 0) ){
  164376. *peType = RBU_PK_VTAB; /* virtual table */
  164377. goto rbuTableType_end;
  164378. }
  164379. *piTnum = sqlite3_column_int(aStmt[0], 1);
  164380. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  164381. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  164382. );
  164383. if( p->rc ) goto rbuTableType_end;
  164384. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  164385. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  164386. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  164387. if( zOrig && zIdx && zOrig[0]=='p' ){
  164388. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  164389. sqlite3_mprintf(
  164390. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  164391. ));
  164392. if( p->rc==SQLITE_OK ){
  164393. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  164394. *piPk = sqlite3_column_int(aStmt[2], 0);
  164395. *peType = RBU_PK_EXTERNAL;
  164396. }else{
  164397. *peType = RBU_PK_WITHOUT_ROWID;
  164398. }
  164399. }
  164400. goto rbuTableType_end;
  164401. }
  164402. }
  164403. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  164404. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  164405. );
  164406. if( p->rc==SQLITE_OK ){
  164407. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  164408. if( sqlite3_column_int(aStmt[3],5)>0 ){
  164409. *peType = RBU_PK_IPK; /* explicit IPK column */
  164410. goto rbuTableType_end;
  164411. }
  164412. }
  164413. *peType = RBU_PK_NONE;
  164414. }
  164415. rbuTableType_end: {
  164416. unsigned int i;
  164417. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  164418. rbuFinalize(p, aStmt[i]);
  164419. }
  164420. }
  164421. }
  164422. /*
  164423. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  164424. ** the pIter->abIndexed[] array.
  164425. */
  164426. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  164427. sqlite3_stmt *pList = 0;
  164428. int bIndex = 0;
  164429. if( p->rc==SQLITE_OK ){
  164430. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  164431. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  164432. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  164433. );
  164434. }
  164435. pIter->nIndex = 0;
  164436. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  164437. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  164438. sqlite3_stmt *pXInfo = 0;
  164439. if( zIdx==0 ) break;
  164440. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  164441. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  164442. );
  164443. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  164444. int iCid = sqlite3_column_int(pXInfo, 1);
  164445. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  164446. }
  164447. rbuFinalize(p, pXInfo);
  164448. bIndex = 1;
  164449. pIter->nIndex++;
  164450. }
  164451. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  164452. /* "PRAGMA index_list" includes the main PK b-tree */
  164453. pIter->nIndex--;
  164454. }
  164455. rbuFinalize(p, pList);
  164456. if( bIndex==0 ) pIter->abIndexed = 0;
  164457. }
  164458. /*
  164459. ** If they are not already populated, populate the pIter->azTblCol[],
  164460. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  164461. ** the table (not index) that the iterator currently points to.
  164462. **
  164463. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  164464. ** an error does occur, an error code and error message are also left in
  164465. ** the RBU handle.
  164466. */
  164467. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  164468. if( pIter->azTblCol==0 ){
  164469. sqlite3_stmt *pStmt = 0;
  164470. int nCol = 0;
  164471. int i; /* for() loop iterator variable */
  164472. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  164473. int iOrder = 0;
  164474. int iTnum = 0;
  164475. /* Figure out the type of table this step will deal with. */
  164476. assert( pIter->eType==0 );
  164477. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  164478. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  164479. p->rc = SQLITE_ERROR;
  164480. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  164481. }
  164482. if( p->rc ) return p->rc;
  164483. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  164484. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  164485. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  164486. || pIter->eType==RBU_PK_VTAB
  164487. );
  164488. /* Populate the azTblCol[] and nTblCol variables based on the columns
  164489. ** of the input table. Ignore any input table columns that begin with
  164490. ** "rbu_". */
  164491. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  164492. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  164493. );
  164494. if( p->rc==SQLITE_OK ){
  164495. nCol = sqlite3_column_count(pStmt);
  164496. rbuAllocateIterArrays(p, pIter, nCol);
  164497. }
  164498. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  164499. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  164500. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  164501. char *zCopy = rbuStrndup(zName, &p->rc);
  164502. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  164503. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  164504. }
  164505. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  164506. bRbuRowid = 1;
  164507. }
  164508. }
  164509. sqlite3_finalize(pStmt);
  164510. pStmt = 0;
  164511. if( p->rc==SQLITE_OK
  164512. && rbuIsVacuum(p)==0
  164513. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  164514. ){
  164515. p->rc = SQLITE_ERROR;
  164516. p->zErrmsg = sqlite3_mprintf(
  164517. "table %q %s rbu_rowid column", pIter->zDataTbl,
  164518. (bRbuRowid ? "may not have" : "requires")
  164519. );
  164520. }
  164521. /* Check that all non-HIDDEN columns in the destination table are also
  164522. ** present in the input table. Populate the abTblPk[], azTblType[] and
  164523. ** aiTblOrder[] arrays at the same time. */
  164524. if( p->rc==SQLITE_OK ){
  164525. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  164526. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  164527. );
  164528. }
  164529. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  164530. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  164531. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  164532. for(i=iOrder; i<pIter->nTblCol; i++){
  164533. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  164534. }
  164535. if( i==pIter->nTblCol ){
  164536. p->rc = SQLITE_ERROR;
  164537. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  164538. pIter->zDataTbl, zName
  164539. );
  164540. }else{
  164541. int iPk = sqlite3_column_int(pStmt, 5);
  164542. int bNotNull = sqlite3_column_int(pStmt, 3);
  164543. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  164544. if( i!=iOrder ){
  164545. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  164546. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  164547. }
  164548. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  164549. pIter->abTblPk[iOrder] = (iPk!=0);
  164550. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  164551. iOrder++;
  164552. }
  164553. }
  164554. rbuFinalize(p, pStmt);
  164555. rbuObjIterCacheIndexedCols(p, pIter);
  164556. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  164557. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  164558. }
  164559. return p->rc;
  164560. }
  164561. /*
  164562. ** This function constructs and returns a pointer to a nul-terminated
  164563. ** string containing some SQL clause or list based on one or more of the
  164564. ** column names currently stored in the pIter->azTblCol[] array.
  164565. */
  164566. static char *rbuObjIterGetCollist(
  164567. sqlite3rbu *p, /* RBU object */
  164568. RbuObjIter *pIter /* Object iterator for column names */
  164569. ){
  164570. char *zList = 0;
  164571. const char *zSep = "";
  164572. int i;
  164573. for(i=0; i<pIter->nTblCol; i++){
  164574. const char *z = pIter->azTblCol[i];
  164575. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  164576. zSep = ", ";
  164577. }
  164578. return zList;
  164579. }
  164580. /*
  164581. ** This function is used to create a SELECT list (the list of SQL
  164582. ** expressions that follows a SELECT keyword) for a SELECT statement
  164583. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  164584. ** index object currently indicated by the iterator object passed as the
  164585. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  164586. ** to obtain the required information.
  164587. **
  164588. ** If the index is of the following form:
  164589. **
  164590. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  164591. **
  164592. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  164593. ** "ipk", the returned string is:
  164594. **
  164595. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  164596. **
  164597. ** As well as the returned string, three other malloc'd strings are
  164598. ** returned via output parameters. As follows:
  164599. **
  164600. ** pzImposterCols: ...
  164601. ** pzImposterPk: ...
  164602. ** pzWhere: ...
  164603. */
  164604. static char *rbuObjIterGetIndexCols(
  164605. sqlite3rbu *p, /* RBU object */
  164606. RbuObjIter *pIter, /* Object iterator for column names */
  164607. char **pzImposterCols, /* OUT: Columns for imposter table */
  164608. char **pzImposterPk, /* OUT: Imposter PK clause */
  164609. char **pzWhere, /* OUT: WHERE clause */
  164610. int *pnBind /* OUT: Trbul number of columns */
  164611. ){
  164612. int rc = p->rc; /* Error code */
  164613. int rc2; /* sqlite3_finalize() return code */
  164614. char *zRet = 0; /* String to return */
  164615. char *zImpCols = 0; /* String to return via *pzImposterCols */
  164616. char *zImpPK = 0; /* String to return via *pzImposterPK */
  164617. char *zWhere = 0; /* String to return via *pzWhere */
  164618. int nBind = 0; /* Value to return via *pnBind */
  164619. const char *zCom = ""; /* Set to ", " later on */
  164620. const char *zAnd = ""; /* Set to " AND " later on */
  164621. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  164622. if( rc==SQLITE_OK ){
  164623. assert( p->zErrmsg==0 );
  164624. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  164625. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  164626. );
  164627. }
  164628. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  164629. int iCid = sqlite3_column_int(pXInfo, 1);
  164630. int bDesc = sqlite3_column_int(pXInfo, 3);
  164631. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  164632. const char *zCol;
  164633. const char *zType;
  164634. if( iCid<0 ){
  164635. /* An integer primary key. If the table has an explicit IPK, use
  164636. ** its name. Otherwise, use "rbu_rowid". */
  164637. if( pIter->eType==RBU_PK_IPK ){
  164638. int i;
  164639. for(i=0; pIter->abTblPk[i]==0; i++);
  164640. assert( i<pIter->nTblCol );
  164641. zCol = pIter->azTblCol[i];
  164642. }else if( rbuIsVacuum(p) ){
  164643. zCol = "_rowid_";
  164644. }else{
  164645. zCol = "rbu_rowid";
  164646. }
  164647. zType = "INTEGER";
  164648. }else{
  164649. zCol = pIter->azTblCol[iCid];
  164650. zType = pIter->azTblType[iCid];
  164651. }
  164652. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  164653. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  164654. const char *zOrder = (bDesc ? " DESC" : "");
  164655. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  164656. zImpPK, zCom, nBind, zCol, zOrder
  164657. );
  164658. }
  164659. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  164660. zImpCols, zCom, nBind, zCol, zType, zCollate
  164661. );
  164662. zWhere = sqlite3_mprintf(
  164663. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  164664. );
  164665. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  164666. zCom = ", ";
  164667. zAnd = " AND ";
  164668. nBind++;
  164669. }
  164670. rc2 = sqlite3_finalize(pXInfo);
  164671. if( rc==SQLITE_OK ) rc = rc2;
  164672. if( rc!=SQLITE_OK ){
  164673. sqlite3_free(zRet);
  164674. sqlite3_free(zImpCols);
  164675. sqlite3_free(zImpPK);
  164676. sqlite3_free(zWhere);
  164677. zRet = 0;
  164678. zImpCols = 0;
  164679. zImpPK = 0;
  164680. zWhere = 0;
  164681. p->rc = rc;
  164682. }
  164683. *pzImposterCols = zImpCols;
  164684. *pzImposterPk = zImpPK;
  164685. *pzWhere = zWhere;
  164686. *pnBind = nBind;
  164687. return zRet;
  164688. }
  164689. /*
  164690. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  164691. ** paramter is passed "old", return a string of the form:
  164692. **
  164693. ** "old.a, old.b, old.b"
  164694. **
  164695. ** With the column names escaped.
  164696. **
  164697. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  164698. ** the text ", old._rowid_" to the returned value.
  164699. */
  164700. static char *rbuObjIterGetOldlist(
  164701. sqlite3rbu *p,
  164702. RbuObjIter *pIter,
  164703. const char *zObj
  164704. ){
  164705. char *zList = 0;
  164706. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  164707. const char *zS = "";
  164708. int i;
  164709. for(i=0; i<pIter->nTblCol; i++){
  164710. if( pIter->abIndexed[i] ){
  164711. const char *zCol = pIter->azTblCol[i];
  164712. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  164713. }else{
  164714. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  164715. }
  164716. zS = ", ";
  164717. if( zList==0 ){
  164718. p->rc = SQLITE_NOMEM;
  164719. break;
  164720. }
  164721. }
  164722. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  164723. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  164724. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  164725. }
  164726. }
  164727. return zList;
  164728. }
  164729. /*
  164730. ** Return an expression that can be used in a WHERE clause to match the
  164731. ** primary key of the current table. For example, if the table is:
  164732. **
  164733. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  164734. **
  164735. ** Return the string:
  164736. **
  164737. ** "b = ?1 AND c = ?2"
  164738. */
  164739. static char *rbuObjIterGetWhere(
  164740. sqlite3rbu *p,
  164741. RbuObjIter *pIter
  164742. ){
  164743. char *zList = 0;
  164744. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  164745. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  164746. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  164747. const char *zSep = "";
  164748. int i;
  164749. for(i=0; i<pIter->nTblCol; i++){
  164750. if( pIter->abTblPk[i] ){
  164751. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  164752. zSep = " AND ";
  164753. }
  164754. }
  164755. zList = rbuMPrintf(p,
  164756. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  164757. );
  164758. }else{
  164759. const char *zSep = "";
  164760. int i;
  164761. for(i=0; i<pIter->nTblCol; i++){
  164762. if( pIter->abTblPk[i] ){
  164763. const char *zCol = pIter->azTblCol[i];
  164764. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  164765. zSep = " AND ";
  164766. }
  164767. }
  164768. }
  164769. return zList;
  164770. }
  164771. /*
  164772. ** The SELECT statement iterating through the keys for the current object
  164773. ** (p->objiter.pSelect) currently points to a valid row. However, there
  164774. ** is something wrong with the rbu_control value in the rbu_control value
  164775. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  164776. ** of the RBU handle to something reflecting this.
  164777. */
  164778. static void rbuBadControlError(sqlite3rbu *p){
  164779. p->rc = SQLITE_ERROR;
  164780. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  164781. }
  164782. /*
  164783. ** Return a nul-terminated string containing the comma separated list of
  164784. ** assignments that should be included following the "SET" keyword of
  164785. ** an UPDATE statement used to update the table object that the iterator
  164786. ** passed as the second argument currently points to if the rbu_control
  164787. ** column of the data_xxx table entry is set to zMask.
  164788. **
  164789. ** The memory for the returned string is obtained from sqlite3_malloc().
  164790. ** It is the responsibility of the caller to eventually free it using
  164791. ** sqlite3_free().
  164792. **
  164793. ** If an OOM error is encountered when allocating space for the new
  164794. ** string, an error code is left in the rbu handle passed as the first
  164795. ** argument and NULL is returned. Or, if an error has already occurred
  164796. ** when this function is called, NULL is returned immediately, without
  164797. ** attempting the allocation or modifying the stored error code.
  164798. */
  164799. static char *rbuObjIterGetSetlist(
  164800. sqlite3rbu *p,
  164801. RbuObjIter *pIter,
  164802. const char *zMask
  164803. ){
  164804. char *zList = 0;
  164805. if( p->rc==SQLITE_OK ){
  164806. int i;
  164807. if( (int)strlen(zMask)!=pIter->nTblCol ){
  164808. rbuBadControlError(p);
  164809. }else{
  164810. const char *zSep = "";
  164811. for(i=0; i<pIter->nTblCol; i++){
  164812. char c = zMask[pIter->aiSrcOrder[i]];
  164813. if( c=='x' ){
  164814. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  164815. zList, zSep, pIter->azTblCol[i], i+1
  164816. );
  164817. zSep = ", ";
  164818. }
  164819. else if( c=='d' ){
  164820. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  164821. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  164822. );
  164823. zSep = ", ";
  164824. }
  164825. else if( c=='f' ){
  164826. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  164827. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  164828. );
  164829. zSep = ", ";
  164830. }
  164831. }
  164832. }
  164833. }
  164834. return zList;
  164835. }
  164836. /*
  164837. ** Return a nul-terminated string consisting of nByte comma separated
  164838. ** "?" expressions. For example, if nByte is 3, return a pointer to
  164839. ** a buffer containing the string "?,?,?".
  164840. **
  164841. ** The memory for the returned string is obtained from sqlite3_malloc().
  164842. ** It is the responsibility of the caller to eventually free it using
  164843. ** sqlite3_free().
  164844. **
  164845. ** If an OOM error is encountered when allocating space for the new
  164846. ** string, an error code is left in the rbu handle passed as the first
  164847. ** argument and NULL is returned. Or, if an error has already occurred
  164848. ** when this function is called, NULL is returned immediately, without
  164849. ** attempting the allocation or modifying the stored error code.
  164850. */
  164851. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  164852. char *zRet = 0;
  164853. int nByte = nBind*2 + 1;
  164854. zRet = (char*)rbuMalloc(p, nByte);
  164855. if( zRet ){
  164856. int i;
  164857. for(i=0; i<nBind; i++){
  164858. zRet[i*2] = '?';
  164859. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  164860. }
  164861. }
  164862. return zRet;
  164863. }
  164864. /*
  164865. ** The iterator currently points to a table (not index) of type
  164866. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  164867. ** declaration for the corresponding imposter table. For example,
  164868. ** if the iterator points to a table created as:
  164869. **
  164870. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  164871. **
  164872. ** this function returns:
  164873. **
  164874. ** PRIMARY KEY("b", "a" DESC)
  164875. */
  164876. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  164877. char *z = 0;
  164878. assert( pIter->zIdx==0 );
  164879. if( p->rc==SQLITE_OK ){
  164880. const char *zSep = "PRIMARY KEY(";
  164881. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  164882. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  164883. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  164884. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  164885. );
  164886. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  164887. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  164888. if( zOrig && strcmp(zOrig, "pk")==0 ){
  164889. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  164890. if( zIdx ){
  164891. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  164892. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  164893. );
  164894. }
  164895. break;
  164896. }
  164897. }
  164898. rbuFinalize(p, pXList);
  164899. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  164900. if( sqlite3_column_int(pXInfo, 5) ){
  164901. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  164902. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  164903. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  164904. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  164905. zSep = ", ";
  164906. }
  164907. }
  164908. z = rbuMPrintf(p, "%z)", z);
  164909. rbuFinalize(p, pXInfo);
  164910. }
  164911. return z;
  164912. }
  164913. /*
  164914. ** This function creates the second imposter table used when writing to
  164915. ** a table b-tree where the table has an external primary key. If the
  164916. ** iterator passed as the second argument does not currently point to
  164917. ** a table (not index) with an external primary key, this function is a
  164918. ** no-op.
  164919. **
  164920. ** Assuming the iterator does point to a table with an external PK, this
  164921. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  164922. ** used to access that PK index. For example, if the target table is
  164923. ** declared as follows:
  164924. **
  164925. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  164926. **
  164927. ** then the imposter table schema is:
  164928. **
  164929. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  164930. **
  164931. */
  164932. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  164933. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  164934. int tnum = pIter->iPkTnum; /* Root page of PK index */
  164935. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  164936. const char *zIdx = 0; /* Name of PK index */
  164937. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  164938. const char *zComma = "";
  164939. char *zCols = 0; /* Used to build up list of table cols */
  164940. char *zPk = 0; /* Used to build up table PK declaration */
  164941. /* Figure out the name of the primary key index for the current table.
  164942. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  164943. ** zIdx to point to a nul-terminated string containing this name. */
  164944. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  164945. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  164946. );
  164947. if( p->rc==SQLITE_OK ){
  164948. sqlite3_bind_int(pQuery, 1, tnum);
  164949. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  164950. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  164951. }
  164952. }
  164953. if( zIdx ){
  164954. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  164955. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  164956. );
  164957. }
  164958. rbuFinalize(p, pQuery);
  164959. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  164960. int bKey = sqlite3_column_int(pXInfo, 5);
  164961. if( bKey ){
  164962. int iCid = sqlite3_column_int(pXInfo, 1);
  164963. int bDesc = sqlite3_column_int(pXInfo, 3);
  164964. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  164965. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
  164966. iCid, pIter->azTblType[iCid], zCollate
  164967. );
  164968. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  164969. zComma = ", ";
  164970. }
  164971. }
  164972. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  164973. rbuFinalize(p, pXInfo);
  164974. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  164975. rbuMPrintfExec(p, p->dbMain,
  164976. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  164977. zCols, zPk
  164978. );
  164979. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  164980. }
  164981. }
  164982. /*
  164983. ** If an error has already occurred when this function is called, it
  164984. ** immediately returns zero (without doing any work). Or, if an error
  164985. ** occurs during the execution of this function, it sets the error code
  164986. ** in the sqlite3rbu object indicated by the first argument and returns
  164987. ** zero.
  164988. **
  164989. ** The iterator passed as the second argument is guaranteed to point to
  164990. ** a table (not an index) when this function is called. This function
  164991. ** attempts to create any imposter table required to write to the main
  164992. ** table b-tree of the table before returning. Non-zero is returned if
  164993. ** an imposter table are created, or zero otherwise.
  164994. **
  164995. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  164996. ** virtual tables are written to directly. The imposter table has the
  164997. ** same schema as the actual target table (less any UNIQUE constraints).
  164998. ** More precisely, the "same schema" means the same columns, types,
  164999. ** collation sequences. For tables that do not have an external PRIMARY
  165000. ** KEY, it also means the same PRIMARY KEY declaration.
  165001. */
  165002. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  165003. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  165004. int tnum = pIter->iTnum;
  165005. const char *zComma = "";
  165006. char *zSql = 0;
  165007. int iCol;
  165008. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  165009. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  165010. const char *zPk = "";
  165011. const char *zCol = pIter->azTblCol[iCol];
  165012. const char *zColl = 0;
  165013. p->rc = sqlite3_table_column_metadata(
  165014. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  165015. );
  165016. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  165017. /* If the target table column is an "INTEGER PRIMARY KEY", add
  165018. ** "PRIMARY KEY" to the imposter table column declaration. */
  165019. zPk = "PRIMARY KEY ";
  165020. }
  165021. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
  165022. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  165023. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  165024. );
  165025. zComma = ", ";
  165026. }
  165027. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  165028. char *zPk = rbuWithoutRowidPK(p, pIter);
  165029. if( zPk ){
  165030. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  165031. }
  165032. }
  165033. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  165034. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  165035. pIter->zTbl, zSql,
  165036. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  165037. );
  165038. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  165039. }
  165040. }
  165041. /*
  165042. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  165043. ** Specifically a statement of the form:
  165044. **
  165045. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  165046. **
  165047. ** The number of bound variables is equal to the number of columns in
  165048. ** the target table, plus one (for the rbu_control column), plus one more
  165049. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  165050. ** virtual table.
  165051. */
  165052. static void rbuObjIterPrepareTmpInsert(
  165053. sqlite3rbu *p,
  165054. RbuObjIter *pIter,
  165055. const char *zCollist,
  165056. const char *zRbuRowid
  165057. ){
  165058. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  165059. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  165060. if( zBind ){
  165061. assert( pIter->pTmpInsert==0 );
  165062. p->rc = prepareFreeAndCollectError(
  165063. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  165064. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  165065. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  165066. ));
  165067. }
  165068. }
  165069. static void rbuTmpInsertFunc(
  165070. sqlite3_context *pCtx,
  165071. int nVal,
  165072. sqlite3_value **apVal
  165073. ){
  165074. sqlite3rbu *p = sqlite3_user_data(pCtx);
  165075. int rc = SQLITE_OK;
  165076. int i;
  165077. assert( sqlite3_value_int(apVal[0])!=0
  165078. || p->objiter.eType==RBU_PK_EXTERNAL
  165079. || p->objiter.eType==RBU_PK_NONE
  165080. );
  165081. if( sqlite3_value_int(apVal[0])!=0 ){
  165082. p->nPhaseOneStep += p->objiter.nIndex;
  165083. }
  165084. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  165085. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  165086. }
  165087. if( rc==SQLITE_OK ){
  165088. sqlite3_step(p->objiter.pTmpInsert);
  165089. rc = sqlite3_reset(p->objiter.pTmpInsert);
  165090. }
  165091. if( rc!=SQLITE_OK ){
  165092. sqlite3_result_error_code(pCtx, rc);
  165093. }
  165094. }
  165095. /*
  165096. ** Ensure that the SQLite statement handles required to update the
  165097. ** target database object currently indicated by the iterator passed
  165098. ** as the second argument are available.
  165099. */
  165100. static int rbuObjIterPrepareAll(
  165101. sqlite3rbu *p,
  165102. RbuObjIter *pIter,
  165103. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  165104. ){
  165105. assert( pIter->bCleanup==0 );
  165106. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  165107. const int tnum = pIter->iTnum;
  165108. char *zCollist = 0; /* List of indexed columns */
  165109. char **pz = &p->zErrmsg;
  165110. const char *zIdx = pIter->zIdx;
  165111. char *zLimit = 0;
  165112. if( nOffset ){
  165113. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  165114. if( !zLimit ) p->rc = SQLITE_NOMEM;
  165115. }
  165116. if( zIdx ){
  165117. const char *zTbl = pIter->zTbl;
  165118. char *zImposterCols = 0; /* Columns for imposter table */
  165119. char *zImposterPK = 0; /* Primary key declaration for imposter */
  165120. char *zWhere = 0; /* WHERE clause on PK columns */
  165121. char *zBind = 0;
  165122. int nBind = 0;
  165123. assert( pIter->eType!=RBU_PK_VTAB );
  165124. zCollist = rbuObjIterGetIndexCols(
  165125. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  165126. );
  165127. zBind = rbuObjIterGetBindlist(p, nBind);
  165128. /* Create the imposter table used to write to this index. */
  165129. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  165130. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  165131. rbuMPrintfExec(p, p->dbMain,
  165132. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  165133. zTbl, zImposterCols, zImposterPK
  165134. );
  165135. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  165136. /* Create the statement to insert index entries */
  165137. pIter->nCol = nBind;
  165138. if( p->rc==SQLITE_OK ){
  165139. p->rc = prepareFreeAndCollectError(
  165140. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  165141. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  165142. );
  165143. }
  165144. /* And to delete index entries */
  165145. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  165146. p->rc = prepareFreeAndCollectError(
  165147. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  165148. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  165149. );
  165150. }
  165151. /* Create the SELECT statement to read keys in sorted order */
  165152. if( p->rc==SQLITE_OK ){
  165153. char *zSql;
  165154. if( rbuIsVacuum(p) ){
  165155. zSql = sqlite3_mprintf(
  165156. "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
  165157. zCollist,
  165158. pIter->zDataTbl,
  165159. zCollist, zLimit
  165160. );
  165161. }else
  165162. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  165163. zSql = sqlite3_mprintf(
  165164. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
  165165. zCollist, p->zStateDb, pIter->zDataTbl,
  165166. zCollist, zLimit
  165167. );
  165168. }else{
  165169. zSql = sqlite3_mprintf(
  165170. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
  165171. "UNION ALL "
  165172. "SELECT %s, rbu_control FROM '%q' "
  165173. "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
  165174. "ORDER BY %s%s",
  165175. zCollist, p->zStateDb, pIter->zDataTbl,
  165176. zCollist, pIter->zDataTbl,
  165177. zCollist, zLimit
  165178. );
  165179. }
  165180. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  165181. }
  165182. sqlite3_free(zImposterCols);
  165183. sqlite3_free(zImposterPK);
  165184. sqlite3_free(zWhere);
  165185. sqlite3_free(zBind);
  165186. }else{
  165187. int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
  165188. ||(pIter->eType==RBU_PK_NONE)
  165189. ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
  165190. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  165191. const char *zWrite; /* Imposter table name */
  165192. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  165193. char *zWhere = rbuObjIterGetWhere(p, pIter);
  165194. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  165195. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  165196. zCollist = rbuObjIterGetCollist(p, pIter);
  165197. pIter->nCol = pIter->nTblCol;
  165198. /* Create the imposter table or tables (if required). */
  165199. rbuCreateImposterTable(p, pIter);
  165200. rbuCreateImposterTable2(p, pIter);
  165201. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  165202. /* Create the INSERT statement to write to the target PK b-tree */
  165203. if( p->rc==SQLITE_OK ){
  165204. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  165205. sqlite3_mprintf(
  165206. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  165207. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  165208. )
  165209. );
  165210. }
  165211. /* Create the DELETE statement to write to the target PK b-tree.
  165212. ** Because it only performs INSERT operations, this is not required for
  165213. ** an rbu vacuum handle. */
  165214. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  165215. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  165216. sqlite3_mprintf(
  165217. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  165218. )
  165219. );
  165220. }
  165221. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  165222. const char *zRbuRowid = "";
  165223. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  165224. zRbuRowid = ", rbu_rowid";
  165225. }
  165226. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  165227. rbuMPrintfExec(p, p->dbRbu,
  165228. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  165229. "SELECT *%s FROM '%q' WHERE 0;"
  165230. , p->zStateDb, pIter->zDataTbl
  165231. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  165232. , pIter->zDataTbl
  165233. );
  165234. rbuMPrintfExec(p, p->dbMain,
  165235. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  165236. "BEGIN "
  165237. " SELECT rbu_tmp_insert(3, %s);"
  165238. "END;"
  165239. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  165240. "BEGIN "
  165241. " SELECT rbu_tmp_insert(3, %s);"
  165242. "END;"
  165243. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  165244. "BEGIN "
  165245. " SELECT rbu_tmp_insert(4, %s);"
  165246. "END;",
  165247. zWrite, zTbl, zOldlist,
  165248. zWrite, zTbl, zOldlist,
  165249. zWrite, zTbl, zNewlist
  165250. );
  165251. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  165252. rbuMPrintfExec(p, p->dbMain,
  165253. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  165254. "BEGIN "
  165255. " SELECT rbu_tmp_insert(0, %s);"
  165256. "END;",
  165257. zWrite, zTbl, zNewlist
  165258. );
  165259. }
  165260. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  165261. }
  165262. /* Create the SELECT statement to read keys from data_xxx */
  165263. if( p->rc==SQLITE_OK ){
  165264. const char *zRbuRowid = "";
  165265. if( bRbuRowid ){
  165266. zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
  165267. }
  165268. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  165269. sqlite3_mprintf(
  165270. "SELECT %s,%s rbu_control%s FROM '%q'%s",
  165271. zCollist,
  165272. (rbuIsVacuum(p) ? "0 AS " : ""),
  165273. zRbuRowid,
  165274. pIter->zDataTbl, zLimit
  165275. )
  165276. );
  165277. }
  165278. sqlite3_free(zWhere);
  165279. sqlite3_free(zOldlist);
  165280. sqlite3_free(zNewlist);
  165281. sqlite3_free(zBindings);
  165282. }
  165283. sqlite3_free(zCollist);
  165284. sqlite3_free(zLimit);
  165285. }
  165286. return p->rc;
  165287. }
  165288. /*
  165289. ** Set output variable *ppStmt to point to an UPDATE statement that may
  165290. ** be used to update the imposter table for the main table b-tree of the
  165291. ** table object that pIter currently points to, assuming that the
  165292. ** rbu_control column of the data_xyz table contains zMask.
  165293. **
  165294. ** If the zMask string does not specify any columns to update, then this
  165295. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  165296. */
  165297. static int rbuGetUpdateStmt(
  165298. sqlite3rbu *p, /* RBU handle */
  165299. RbuObjIter *pIter, /* Object iterator */
  165300. const char *zMask, /* rbu_control value ('x.x.') */
  165301. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  165302. ){
  165303. RbuUpdateStmt **pp;
  165304. RbuUpdateStmt *pUp = 0;
  165305. int nUp = 0;
  165306. /* In case an error occurs */
  165307. *ppStmt = 0;
  165308. /* Search for an existing statement. If one is found, shift it to the front
  165309. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  165310. ** to the number of statements currently in the cache and pUp to the
  165311. ** last object in the list. */
  165312. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  165313. pUp = *pp;
  165314. if( strcmp(pUp->zMask, zMask)==0 ){
  165315. *pp = pUp->pNext;
  165316. pUp->pNext = pIter->pRbuUpdate;
  165317. pIter->pRbuUpdate = pUp;
  165318. *ppStmt = pUp->pUpdate;
  165319. return SQLITE_OK;
  165320. }
  165321. nUp++;
  165322. }
  165323. assert( pUp==0 || pUp->pNext==0 );
  165324. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  165325. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  165326. *pp = 0;
  165327. sqlite3_finalize(pUp->pUpdate);
  165328. pUp->pUpdate = 0;
  165329. }else{
  165330. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  165331. }
  165332. if( pUp ){
  165333. char *zWhere = rbuObjIterGetWhere(p, pIter);
  165334. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  165335. char *zUpdate = 0;
  165336. pUp->zMask = (char*)&pUp[1];
  165337. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  165338. pUp->pNext = pIter->pRbuUpdate;
  165339. pIter->pRbuUpdate = pUp;
  165340. if( zSet ){
  165341. const char *zPrefix = "";
  165342. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  165343. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  165344. zPrefix, pIter->zTbl, zSet, zWhere
  165345. );
  165346. p->rc = prepareFreeAndCollectError(
  165347. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  165348. );
  165349. *ppStmt = pUp->pUpdate;
  165350. }
  165351. sqlite3_free(zWhere);
  165352. sqlite3_free(zSet);
  165353. }
  165354. return p->rc;
  165355. }
  165356. static sqlite3 *rbuOpenDbhandle(
  165357. sqlite3rbu *p,
  165358. const char *zName,
  165359. int bUseVfs
  165360. ){
  165361. sqlite3 *db = 0;
  165362. if( p->rc==SQLITE_OK ){
  165363. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  165364. p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
  165365. if( p->rc ){
  165366. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  165367. sqlite3_close(db);
  165368. db = 0;
  165369. }
  165370. }
  165371. return db;
  165372. }
  165373. /*
  165374. ** Free an RbuState object allocated by rbuLoadState().
  165375. */
  165376. static void rbuFreeState(RbuState *p){
  165377. if( p ){
  165378. sqlite3_free(p->zTbl);
  165379. sqlite3_free(p->zIdx);
  165380. sqlite3_free(p);
  165381. }
  165382. }
  165383. /*
  165384. ** Allocate an RbuState object and load the contents of the rbu_state
  165385. ** table into it. Return a pointer to the new object. It is the
  165386. ** responsibility of the caller to eventually free the object using
  165387. ** sqlite3_free().
  165388. **
  165389. ** If an error occurs, leave an error code and message in the rbu handle
  165390. ** and return NULL.
  165391. */
  165392. static RbuState *rbuLoadState(sqlite3rbu *p){
  165393. RbuState *pRet = 0;
  165394. sqlite3_stmt *pStmt = 0;
  165395. int rc;
  165396. int rc2;
  165397. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  165398. if( pRet==0 ) return 0;
  165399. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  165400. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  165401. );
  165402. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  165403. switch( sqlite3_column_int(pStmt, 0) ){
  165404. case RBU_STATE_STAGE:
  165405. pRet->eStage = sqlite3_column_int(pStmt, 1);
  165406. if( pRet->eStage!=RBU_STAGE_OAL
  165407. && pRet->eStage!=RBU_STAGE_MOVE
  165408. && pRet->eStage!=RBU_STAGE_CKPT
  165409. ){
  165410. p->rc = SQLITE_CORRUPT;
  165411. }
  165412. break;
  165413. case RBU_STATE_TBL:
  165414. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  165415. break;
  165416. case RBU_STATE_IDX:
  165417. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  165418. break;
  165419. case RBU_STATE_ROW:
  165420. pRet->nRow = sqlite3_column_int(pStmt, 1);
  165421. break;
  165422. case RBU_STATE_PROGRESS:
  165423. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  165424. break;
  165425. case RBU_STATE_CKPT:
  165426. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  165427. break;
  165428. case RBU_STATE_COOKIE:
  165429. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  165430. break;
  165431. case RBU_STATE_OALSZ:
  165432. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  165433. break;
  165434. case RBU_STATE_PHASEONESTEP:
  165435. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  165436. break;
  165437. default:
  165438. rc = SQLITE_CORRUPT;
  165439. break;
  165440. }
  165441. }
  165442. rc2 = sqlite3_finalize(pStmt);
  165443. if( rc==SQLITE_OK ) rc = rc2;
  165444. p->rc = rc;
  165445. return pRet;
  165446. }
  165447. /*
  165448. ** Open the database handle and attach the RBU database as "rbu". If an
  165449. ** error occurs, leave an error code and message in the RBU handle.
  165450. */
  165451. static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
  165452. assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
  165453. assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  165454. /* Open the RBU database */
  165455. p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  165456. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  165457. sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  165458. if( p->zState==0 ){
  165459. const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
  165460. p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
  165461. }
  165462. }
  165463. /* If using separate RBU and state databases, attach the state database to
  165464. ** the RBU db handle now. */
  165465. if( p->zState ){
  165466. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  165467. memcpy(p->zStateDb, "stat", 4);
  165468. }else{
  165469. memcpy(p->zStateDb, "main", 4);
  165470. }
  165471. #if 0
  165472. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  165473. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
  165474. }
  165475. #endif
  165476. /* If it has not already been created, create the rbu_state table */
  165477. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  165478. #if 0
  165479. if( rbuIsVacuum(p) ){
  165480. if( p->rc==SQLITE_OK ){
  165481. int rc2;
  165482. int bOk = 0;
  165483. sqlite3_stmt *pCnt = 0;
  165484. p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
  165485. "SELECT count(*) FROM stat.sqlite_master"
  165486. );
  165487. if( p->rc==SQLITE_OK
  165488. && sqlite3_step(pCnt)==SQLITE_ROW
  165489. && 1==sqlite3_column_int(pCnt, 0)
  165490. ){
  165491. bOk = 1;
  165492. }
  165493. rc2 = sqlite3_finalize(pCnt);
  165494. if( p->rc==SQLITE_OK ) p->rc = rc2;
  165495. if( p->rc==SQLITE_OK && bOk==0 ){
  165496. p->rc = SQLITE_ERROR;
  165497. p->zErrmsg = sqlite3_mprintf("invalid state database");
  165498. }
  165499. if( p->rc==SQLITE_OK ){
  165500. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  165501. }
  165502. }
  165503. }
  165504. #endif
  165505. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  165506. int bOpen = 0;
  165507. int rc;
  165508. p->nRbu = 0;
  165509. p->pRbuFd = 0;
  165510. rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  165511. if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
  165512. if( p->eStage>=RBU_STAGE_MOVE ){
  165513. bOpen = 1;
  165514. }else{
  165515. RbuState *pState = rbuLoadState(p);
  165516. if( pState ){
  165517. bOpen = (pState->eStage>=RBU_STAGE_MOVE);
  165518. rbuFreeState(pState);
  165519. }
  165520. }
  165521. if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
  165522. }
  165523. p->eStage = 0;
  165524. if( p->rc==SQLITE_OK && p->dbMain==0 ){
  165525. if( !rbuIsVacuum(p) ){
  165526. p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  165527. }else if( p->pRbuFd->pWalFd ){
  165528. if( pbRetry ){
  165529. p->pRbuFd->bNolock = 0;
  165530. sqlite3_close(p->dbRbu);
  165531. sqlite3_close(p->dbMain);
  165532. p->dbMain = 0;
  165533. p->dbRbu = 0;
  165534. *pbRetry = 1;
  165535. return;
  165536. }
  165537. p->rc = SQLITE_ERROR;
  165538. p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
  165539. }else{
  165540. char *zTarget;
  165541. char *zExtra = 0;
  165542. if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
  165543. zExtra = &p->zRbu[5];
  165544. while( *zExtra ){
  165545. if( *zExtra++=='?' ) break;
  165546. }
  165547. if( *zExtra=='\0' ) zExtra = 0;
  165548. }
  165549. zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
  165550. sqlite3_db_filename(p->dbRbu, "main"),
  165551. (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
  165552. );
  165553. if( zTarget==0 ){
  165554. p->rc = SQLITE_NOMEM;
  165555. return;
  165556. }
  165557. p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
  165558. sqlite3_free(zTarget);
  165559. }
  165560. }
  165561. if( p->rc==SQLITE_OK ){
  165562. p->rc = sqlite3_create_function(p->dbMain,
  165563. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  165564. );
  165565. }
  165566. if( p->rc==SQLITE_OK ){
  165567. p->rc = sqlite3_create_function(p->dbMain,
  165568. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  165569. );
  165570. }
  165571. if( p->rc==SQLITE_OK ){
  165572. p->rc = sqlite3_create_function(p->dbRbu,
  165573. "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  165574. );
  165575. }
  165576. if( p->rc==SQLITE_OK ){
  165577. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  165578. }
  165579. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  165580. /* Mark the database file just opened as an RBU target database. If
  165581. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  165582. ** This is an error. */
  165583. if( p->rc==SQLITE_OK ){
  165584. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  165585. }
  165586. if( p->rc==SQLITE_NOTFOUND ){
  165587. p->rc = SQLITE_ERROR;
  165588. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  165589. }
  165590. }
  165591. /*
  165592. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  165593. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  165594. **
  165595. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  165596. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  165597. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  165598. ** three characters, then shorten the suffix on z[] to be the last three
  165599. ** characters of the original suffix.
  165600. **
  165601. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  165602. ** do the suffix shortening regardless of URI parameter.
  165603. **
  165604. ** Examples:
  165605. **
  165606. ** test.db-journal => test.nal
  165607. ** test.db-wal => test.wal
  165608. ** test.db-shm => test.shm
  165609. ** test.db-mj7f3319fa => test.9fa
  165610. */
  165611. static void rbuFileSuffix3(const char *zBase, char *z){
  165612. #ifdef SQLITE_ENABLE_8_3_NAMES
  165613. #if SQLITE_ENABLE_8_3_NAMES<2
  165614. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  165615. #endif
  165616. {
  165617. int i, sz;
  165618. sz = (int)strlen(z)&0xffffff;
  165619. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  165620. if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
  165621. }
  165622. #endif
  165623. }
  165624. /*
  165625. ** Return the current wal-index header checksum for the target database
  165626. ** as a 64-bit integer.
  165627. **
  165628. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  165629. ** blob starting at byte offset 40.
  165630. */
  165631. static i64 rbuShmChecksum(sqlite3rbu *p){
  165632. i64 iRet = 0;
  165633. if( p->rc==SQLITE_OK ){
  165634. sqlite3_file *pDb = p->pTargetFd->pReal;
  165635. u32 volatile *ptr;
  165636. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  165637. if( p->rc==SQLITE_OK ){
  165638. iRet = ((i64)ptr[10] << 32) + ptr[11];
  165639. }
  165640. }
  165641. return iRet;
  165642. }
  165643. /*
  165644. ** This function is called as part of initializing or reinitializing an
  165645. ** incremental checkpoint.
  165646. **
  165647. ** It populates the sqlite3rbu.aFrame[] array with the set of
  165648. ** (wal frame -> db page) copy operations required to checkpoint the
  165649. ** current wal file, and obtains the set of shm locks required to safely
  165650. ** perform the copy operations directly on the file-system.
  165651. **
  165652. ** If argument pState is not NULL, then the incremental checkpoint is
  165653. ** being resumed. In this case, if the checksum of the wal-index-header
  165654. ** following recovery is not the same as the checksum saved in the RbuState
  165655. ** object, then the rbu handle is set to DONE state. This occurs if some
  165656. ** other client appends a transaction to the wal file in the middle of
  165657. ** an incremental checkpoint.
  165658. */
  165659. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  165660. /* If pState is NULL, then the wal file may not have been opened and
  165661. ** recovered. Running a read-statement here to ensure that doing so
  165662. ** does not interfere with the "capture" process below. */
  165663. if( pState==0 ){
  165664. p->eStage = 0;
  165665. if( p->rc==SQLITE_OK ){
  165666. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  165667. }
  165668. }
  165669. /* Assuming no error has occurred, run a "restart" checkpoint with the
  165670. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  165671. ** special behaviour in the rbu VFS:
  165672. **
  165673. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  165674. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  165675. ** proceed with running a passive checkpoint instead of failing).
  165676. **
  165677. ** * Attempts to read from the *-wal file or write to the database file
  165678. ** do not perform any IO. Instead, the frame/page combinations that
  165679. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  165680. ** array.
  165681. **
  165682. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  165683. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  165684. ** no-ops. These locks will not be released until the connection
  165685. ** is closed.
  165686. **
  165687. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  165688. ** error.
  165689. **
  165690. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  165691. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  165692. ** array populated with a set of (frame -> page) mappings. Because the
  165693. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  165694. ** data from the wal file into the database file according to the
  165695. ** contents of aFrame[].
  165696. */
  165697. if( p->rc==SQLITE_OK ){
  165698. int rc2;
  165699. p->eStage = RBU_STAGE_CAPTURE;
  165700. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  165701. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  165702. }
  165703. if( p->rc==SQLITE_OK && p->nFrame>0 ){
  165704. p->eStage = RBU_STAGE_CKPT;
  165705. p->nStep = (pState ? pState->nRow : 0);
  165706. p->aBuf = rbuMalloc(p, p->pgsz);
  165707. p->iWalCksum = rbuShmChecksum(p);
  165708. }
  165709. if( p->rc==SQLITE_OK ){
  165710. if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
  165711. p->rc = SQLITE_DONE;
  165712. p->eStage = RBU_STAGE_DONE;
  165713. }else{
  165714. int nSectorSize;
  165715. sqlite3_file *pDb = p->pTargetFd->pReal;
  165716. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  165717. assert( p->nPagePerSector==0 );
  165718. nSectorSize = pDb->pMethods->xSectorSize(pDb);
  165719. if( nSectorSize>p->pgsz ){
  165720. p->nPagePerSector = nSectorSize / p->pgsz;
  165721. }else{
  165722. p->nPagePerSector = 1;
  165723. }
  165724. /* Call xSync() on the wal file. This causes SQLite to sync the
  165725. ** directory in which the target database and the wal file reside, in
  165726. ** case it has not been synced since the rename() call in
  165727. ** rbuMoveOalFile(). */
  165728. p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
  165729. }
  165730. }
  165731. }
  165732. /*
  165733. ** Called when iAmt bytes are read from offset iOff of the wal file while
  165734. ** the rbu object is in capture mode. Record the frame number of the frame
  165735. ** being read in the aFrame[] array.
  165736. */
  165737. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  165738. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  165739. u32 iFrame;
  165740. if( pRbu->mLock!=mReq ){
  165741. pRbu->rc = SQLITE_BUSY;
  165742. return SQLITE_INTERNAL;
  165743. }
  165744. pRbu->pgsz = iAmt;
  165745. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  165746. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  165747. RbuFrame *aNew;
  165748. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  165749. if( aNew==0 ) return SQLITE_NOMEM;
  165750. pRbu->aFrame = aNew;
  165751. pRbu->nFrameAlloc = nNew;
  165752. }
  165753. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  165754. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  165755. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  165756. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  165757. pRbu->nFrame++;
  165758. return SQLITE_OK;
  165759. }
  165760. /*
  165761. ** Called when a page of data is written to offset iOff of the database
  165762. ** file while the rbu handle is in capture mode. Record the page number
  165763. ** of the page being written in the aFrame[] array.
  165764. */
  165765. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  165766. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  165767. return SQLITE_OK;
  165768. }
  165769. /*
  165770. ** This is called as part of an incremental checkpoint operation. Copy
  165771. ** a single frame of data from the wal file into the database file, as
  165772. ** indicated by the RbuFrame object.
  165773. */
  165774. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  165775. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  165776. sqlite3_file *pDb = p->pTargetFd->pReal;
  165777. i64 iOff;
  165778. assert( p->rc==SQLITE_OK );
  165779. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  165780. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  165781. if( p->rc ) return;
  165782. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  165783. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  165784. }
  165785. /*
  165786. ** Take an EXCLUSIVE lock on the database file.
  165787. */
  165788. static void rbuLockDatabase(sqlite3rbu *p){
  165789. sqlite3_file *pReal = p->pTargetFd->pReal;
  165790. assert( p->rc==SQLITE_OK );
  165791. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  165792. if( p->rc==SQLITE_OK ){
  165793. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  165794. }
  165795. }
  165796. #if defined(_WIN32_WCE)
  165797. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  165798. int nChar;
  165799. LPWSTR zWideFilename;
  165800. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  165801. if( nChar==0 ){
  165802. return 0;
  165803. }
  165804. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  165805. if( zWideFilename==0 ){
  165806. return 0;
  165807. }
  165808. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  165809. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  165810. nChar);
  165811. if( nChar==0 ){
  165812. sqlite3_free(zWideFilename);
  165813. zWideFilename = 0;
  165814. }
  165815. return zWideFilename;
  165816. }
  165817. #endif
  165818. /*
  165819. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  165820. ** on the database file. This proc moves the *-oal file to the *-wal path,
  165821. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  165822. ** If an error occurs, leave an error code and error message in the rbu
  165823. ** handle.
  165824. */
  165825. static void rbuMoveOalFile(sqlite3rbu *p){
  165826. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  165827. const char *zMove = zBase;
  165828. char *zOal;
  165829. char *zWal;
  165830. if( rbuIsVacuum(p) ){
  165831. zMove = sqlite3_db_filename(p->dbRbu, "main");
  165832. }
  165833. zOal = sqlite3_mprintf("%s-oal", zMove);
  165834. zWal = sqlite3_mprintf("%s-wal", zMove);
  165835. assert( p->eStage==RBU_STAGE_MOVE );
  165836. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  165837. if( zWal==0 || zOal==0 ){
  165838. p->rc = SQLITE_NOMEM;
  165839. }else{
  165840. /* Move the *-oal file to *-wal. At this point connection p->db is
  165841. ** holding a SHARED lock on the target database file (because it is
  165842. ** in WAL mode). So no other connection may be writing the db.
  165843. **
  165844. ** In order to ensure that there are no database readers, an EXCLUSIVE
  165845. ** lock is obtained here before the *-oal is moved to *-wal.
  165846. */
  165847. rbuLockDatabase(p);
  165848. if( p->rc==SQLITE_OK ){
  165849. rbuFileSuffix3(zBase, zWal);
  165850. rbuFileSuffix3(zBase, zOal);
  165851. /* Re-open the databases. */
  165852. rbuObjIterFinalize(&p->objiter);
  165853. sqlite3_close(p->dbRbu);
  165854. sqlite3_close(p->dbMain);
  165855. p->dbMain = 0;
  165856. p->dbRbu = 0;
  165857. #if defined(_WIN32_WCE)
  165858. {
  165859. LPWSTR zWideOal;
  165860. LPWSTR zWideWal;
  165861. zWideOal = rbuWinUtf8ToUnicode(zOal);
  165862. if( zWideOal ){
  165863. zWideWal = rbuWinUtf8ToUnicode(zWal);
  165864. if( zWideWal ){
  165865. if( MoveFileW(zWideOal, zWideWal) ){
  165866. p->rc = SQLITE_OK;
  165867. }else{
  165868. p->rc = SQLITE_IOERR;
  165869. }
  165870. sqlite3_free(zWideWal);
  165871. }else{
  165872. p->rc = SQLITE_IOERR_NOMEM;
  165873. }
  165874. sqlite3_free(zWideOal);
  165875. }else{
  165876. p->rc = SQLITE_IOERR_NOMEM;
  165877. }
  165878. }
  165879. #else
  165880. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  165881. #endif
  165882. if( p->rc==SQLITE_OK ){
  165883. rbuOpenDatabase(p, 0);
  165884. rbuSetupCheckpoint(p, 0);
  165885. }
  165886. }
  165887. }
  165888. sqlite3_free(zWal);
  165889. sqlite3_free(zOal);
  165890. }
  165891. /*
  165892. ** The SELECT statement iterating through the keys for the current object
  165893. ** (p->objiter.pSelect) currently points to a valid row. This function
  165894. ** determines the type of operation requested by this row and returns
  165895. ** one of the following values to indicate the result:
  165896. **
  165897. ** * RBU_INSERT
  165898. ** * RBU_DELETE
  165899. ** * RBU_IDX_DELETE
  165900. ** * RBU_UPDATE
  165901. **
  165902. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  165903. ** point to the text value indicating the columns to update.
  165904. **
  165905. ** If the rbu_control field contains an invalid value, an error code and
  165906. ** message are left in the RBU handle and zero returned.
  165907. */
  165908. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  165909. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  165910. int res = 0; /* Return value */
  165911. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  165912. case SQLITE_INTEGER: {
  165913. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  165914. switch( iVal ){
  165915. case 0: res = RBU_INSERT; break;
  165916. case 1: res = RBU_DELETE; break;
  165917. case 2: res = RBU_REPLACE; break;
  165918. case 3: res = RBU_IDX_DELETE; break;
  165919. case 4: res = RBU_IDX_INSERT; break;
  165920. }
  165921. break;
  165922. }
  165923. case SQLITE_TEXT: {
  165924. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  165925. if( z==0 ){
  165926. p->rc = SQLITE_NOMEM;
  165927. }else{
  165928. *pzMask = (const char*)z;
  165929. }
  165930. res = RBU_UPDATE;
  165931. break;
  165932. }
  165933. default:
  165934. break;
  165935. }
  165936. if( res==0 ){
  165937. rbuBadControlError(p);
  165938. }
  165939. return res;
  165940. }
  165941. #ifdef SQLITE_DEBUG
  165942. /*
  165943. ** Assert that column iCol of statement pStmt is named zName.
  165944. */
  165945. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  165946. const char *zCol = sqlite3_column_name(pStmt, iCol);
  165947. assert( 0==sqlite3_stricmp(zName, zCol) );
  165948. }
  165949. #else
  165950. # define assertColumnName(x,y,z)
  165951. #endif
  165952. /*
  165953. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  165954. ** RBU_IDX_DELETE. This function performs the work of a single
  165955. ** sqlite3rbu_step() call for the type of operation specified by eType.
  165956. */
  165957. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  165958. RbuObjIter *pIter = &p->objiter;
  165959. sqlite3_value *pVal;
  165960. sqlite3_stmt *pWriter;
  165961. int i;
  165962. assert( p->rc==SQLITE_OK );
  165963. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  165964. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  165965. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  165966. );
  165967. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  165968. ** statement below does actually delete a row, nPhaseOneStep will be
  165969. ** incremented by the same amount when SQL function rbu_tmp_insert()
  165970. ** is invoked by the trigger. */
  165971. if( eType==RBU_DELETE ){
  165972. p->nPhaseOneStep -= p->objiter.nIndex;
  165973. }
  165974. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  165975. pWriter = pIter->pDelete;
  165976. }else{
  165977. pWriter = pIter->pInsert;
  165978. }
  165979. for(i=0; i<pIter->nCol; i++){
  165980. /* If this is an INSERT into a table b-tree and the table has an
  165981. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  165982. ** to write a NULL into the IPK column. That is not permitted. */
  165983. if( eType==RBU_INSERT
  165984. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  165985. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  165986. ){
  165987. p->rc = SQLITE_MISMATCH;
  165988. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  165989. return;
  165990. }
  165991. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  165992. continue;
  165993. }
  165994. pVal = sqlite3_column_value(pIter->pSelect, i);
  165995. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  165996. if( p->rc ) return;
  165997. }
  165998. if( pIter->zIdx==0 ){
  165999. if( pIter->eType==RBU_PK_VTAB
  166000. || pIter->eType==RBU_PK_NONE
  166001. || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
  166002. ){
  166003. /* For a virtual table, or a table with no primary key, the
  166004. ** SELECT statement is:
  166005. **
  166006. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  166007. **
  166008. ** Hence column_value(pIter->nCol+1).
  166009. */
  166010. assertColumnName(pIter->pSelect, pIter->nCol+1,
  166011. rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
  166012. );
  166013. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  166014. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  166015. }
  166016. }
  166017. if( p->rc==SQLITE_OK ){
  166018. sqlite3_step(pWriter);
  166019. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  166020. }
  166021. }
  166022. /*
  166023. ** This function does the work for an sqlite3rbu_step() call.
  166024. **
  166025. ** The object-iterator (p->objiter) currently points to a valid object,
  166026. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  166027. ** input row. Perform whatever processing is required and return.
  166028. **
  166029. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  166030. ** and message is left in the RBU handle and a copy of the error code
  166031. ** returned.
  166032. */
  166033. static int rbuStep(sqlite3rbu *p){
  166034. RbuObjIter *pIter = &p->objiter;
  166035. const char *zMask = 0;
  166036. int eType = rbuStepType(p, &zMask);
  166037. if( eType ){
  166038. assert( eType==RBU_INSERT || eType==RBU_DELETE
  166039. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  166040. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  166041. );
  166042. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  166043. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  166044. rbuBadControlError(p);
  166045. }
  166046. else if( eType==RBU_REPLACE ){
  166047. if( pIter->zIdx==0 ){
  166048. p->nPhaseOneStep += p->objiter.nIndex;
  166049. rbuStepOneOp(p, RBU_DELETE);
  166050. }
  166051. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  166052. }
  166053. else if( eType!=RBU_UPDATE ){
  166054. rbuStepOneOp(p, eType);
  166055. }
  166056. else{
  166057. sqlite3_value *pVal;
  166058. sqlite3_stmt *pUpdate = 0;
  166059. assert( eType==RBU_UPDATE );
  166060. p->nPhaseOneStep -= p->objiter.nIndex;
  166061. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  166062. if( pUpdate ){
  166063. int i;
  166064. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  166065. char c = zMask[pIter->aiSrcOrder[i]];
  166066. pVal = sqlite3_column_value(pIter->pSelect, i);
  166067. if( pIter->abTblPk[i] || c!='.' ){
  166068. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  166069. }
  166070. }
  166071. if( p->rc==SQLITE_OK
  166072. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  166073. ){
  166074. /* Bind the rbu_rowid value to column _rowid_ */
  166075. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  166076. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  166077. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  166078. }
  166079. if( p->rc==SQLITE_OK ){
  166080. sqlite3_step(pUpdate);
  166081. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  166082. }
  166083. }
  166084. }
  166085. }
  166086. return p->rc;
  166087. }
  166088. /*
  166089. ** Increment the schema cookie of the main database opened by p->dbMain.
  166090. **
  166091. ** Or, if this is an RBU vacuum, set the schema cookie of the main db
  166092. ** opened by p->dbMain to one more than the schema cookie of the main
  166093. ** db opened by p->dbRbu.
  166094. */
  166095. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  166096. if( p->rc==SQLITE_OK ){
  166097. sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  166098. int iCookie = 1000000;
  166099. sqlite3_stmt *pStmt;
  166100. p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
  166101. "PRAGMA schema_version"
  166102. );
  166103. if( p->rc==SQLITE_OK ){
  166104. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  166105. ** is already a transaction open, so the prepared statement cannot
  166106. ** throw an SQLITE_SCHEMA exception. The only database page the
  166107. ** statement reads is page 1, which is guaranteed to be in the cache.
  166108. ** And no memory allocations are required. */
  166109. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  166110. iCookie = sqlite3_column_int(pStmt, 0);
  166111. }
  166112. rbuFinalize(p, pStmt);
  166113. }
  166114. if( p->rc==SQLITE_OK ){
  166115. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  166116. }
  166117. }
  166118. }
  166119. /*
  166120. ** Update the contents of the rbu_state table within the rbu database. The
  166121. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  166122. ** are determined by inspecting the rbu handle passed as the first argument.
  166123. */
  166124. static void rbuSaveState(sqlite3rbu *p, int eStage){
  166125. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  166126. sqlite3_stmt *pInsert = 0;
  166127. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  166128. int rc;
  166129. assert( p->zErrmsg==0 );
  166130. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  166131. sqlite3_mprintf(
  166132. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  166133. "(%d, %d), "
  166134. "(%d, %Q), "
  166135. "(%d, %Q), "
  166136. "(%d, %d), "
  166137. "(%d, %d), "
  166138. "(%d, %lld), "
  166139. "(%d, %lld), "
  166140. "(%d, %lld), "
  166141. "(%d, %lld) ",
  166142. p->zStateDb,
  166143. RBU_STATE_STAGE, eStage,
  166144. RBU_STATE_TBL, p->objiter.zTbl,
  166145. RBU_STATE_IDX, p->objiter.zIdx,
  166146. RBU_STATE_ROW, p->nStep,
  166147. RBU_STATE_PROGRESS, p->nProgress,
  166148. RBU_STATE_CKPT, p->iWalCksum,
  166149. RBU_STATE_COOKIE, (i64)pFd->iCookie,
  166150. RBU_STATE_OALSZ, p->iOalSz,
  166151. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
  166152. )
  166153. );
  166154. assert( pInsert==0 || rc==SQLITE_OK );
  166155. if( rc==SQLITE_OK ){
  166156. sqlite3_step(pInsert);
  166157. rc = sqlite3_finalize(pInsert);
  166158. }
  166159. if( rc!=SQLITE_OK ) p->rc = rc;
  166160. }
  166161. }
  166162. /*
  166163. ** The second argument passed to this function is the name of a PRAGMA
  166164. ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
  166165. ** This function executes the following on sqlite3rbu.dbRbu:
  166166. **
  166167. ** "PRAGMA main.$zPragma"
  166168. **
  166169. ** where $zPragma is the string passed as the second argument, then
  166170. ** on sqlite3rbu.dbMain:
  166171. **
  166172. ** "PRAGMA main.$zPragma = $val"
  166173. **
  166174. ** where $val is the value returned by the first PRAGMA invocation.
  166175. **
  166176. ** In short, it copies the value of the specified PRAGMA setting from
  166177. ** dbRbu to dbMain.
  166178. */
  166179. static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
  166180. if( p->rc==SQLITE_OK ){
  166181. sqlite3_stmt *pPragma = 0;
  166182. p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
  166183. sqlite3_mprintf("PRAGMA main.%s", zPragma)
  166184. );
  166185. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
  166186. p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
  166187. zPragma, sqlite3_column_int(pPragma, 0)
  166188. );
  166189. }
  166190. rbuFinalize(p, pPragma);
  166191. }
  166192. }
  166193. /*
  166194. ** The RBU handle passed as the only argument has just been opened and
  166195. ** the state database is empty. If this RBU handle was opened for an
  166196. ** RBU vacuum operation, create the schema in the target db.
  166197. */
  166198. static void rbuCreateTargetSchema(sqlite3rbu *p){
  166199. sqlite3_stmt *pSql = 0;
  166200. sqlite3_stmt *pInsert = 0;
  166201. assert( rbuIsVacuum(p) );
  166202. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
  166203. if( p->rc==SQLITE_OK ){
  166204. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  166205. "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
  166206. " AND name!='sqlite_sequence' "
  166207. " ORDER BY type DESC"
  166208. );
  166209. }
  166210. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  166211. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  166212. p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
  166213. }
  166214. rbuFinalize(p, pSql);
  166215. if( p->rc!=SQLITE_OK ) return;
  166216. if( p->rc==SQLITE_OK ){
  166217. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  166218. "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
  166219. );
  166220. }
  166221. if( p->rc==SQLITE_OK ){
  166222. p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
  166223. "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
  166224. );
  166225. }
  166226. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  166227. int i;
  166228. for(i=0; i<5; i++){
  166229. sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
  166230. }
  166231. sqlite3_step(pInsert);
  166232. p->rc = sqlite3_reset(pInsert);
  166233. }
  166234. if( p->rc==SQLITE_OK ){
  166235. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
  166236. }
  166237. rbuFinalize(p, pSql);
  166238. rbuFinalize(p, pInsert);
  166239. }
  166240. /*
  166241. ** Step the RBU object.
  166242. */
  166243. SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
  166244. if( p ){
  166245. switch( p->eStage ){
  166246. case RBU_STAGE_OAL: {
  166247. RbuObjIter *pIter = &p->objiter;
  166248. /* If this is an RBU vacuum operation and the state table was empty
  166249. ** when this handle was opened, create the target database schema. */
  166250. if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
  166251. rbuCreateTargetSchema(p);
  166252. rbuCopyPragma(p, "user_version");
  166253. rbuCopyPragma(p, "application_id");
  166254. }
  166255. while( p->rc==SQLITE_OK && pIter->zTbl ){
  166256. if( pIter->bCleanup ){
  166257. /* Clean up the rbu_tmp_xxx table for the previous table. It
  166258. ** cannot be dropped as there are currently active SQL statements.
  166259. ** But the contents can be deleted. */
  166260. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  166261. rbuMPrintfExec(p, p->dbRbu,
  166262. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  166263. );
  166264. }
  166265. }else{
  166266. rbuObjIterPrepareAll(p, pIter, 0);
  166267. /* Advance to the next row to process. */
  166268. if( p->rc==SQLITE_OK ){
  166269. int rc = sqlite3_step(pIter->pSelect);
  166270. if( rc==SQLITE_ROW ){
  166271. p->nProgress++;
  166272. p->nStep++;
  166273. return rbuStep(p);
  166274. }
  166275. p->rc = sqlite3_reset(pIter->pSelect);
  166276. p->nStep = 0;
  166277. }
  166278. }
  166279. rbuObjIterNext(p, pIter);
  166280. }
  166281. if( p->rc==SQLITE_OK ){
  166282. assert( pIter->zTbl==0 );
  166283. rbuSaveState(p, RBU_STAGE_MOVE);
  166284. rbuIncrSchemaCookie(p);
  166285. if( p->rc==SQLITE_OK ){
  166286. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  166287. }
  166288. if( p->rc==SQLITE_OK ){
  166289. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  166290. }
  166291. p->eStage = RBU_STAGE_MOVE;
  166292. }
  166293. break;
  166294. }
  166295. case RBU_STAGE_MOVE: {
  166296. if( p->rc==SQLITE_OK ){
  166297. rbuMoveOalFile(p);
  166298. p->nProgress++;
  166299. }
  166300. break;
  166301. }
  166302. case RBU_STAGE_CKPT: {
  166303. if( p->rc==SQLITE_OK ){
  166304. if( p->nStep>=p->nFrame ){
  166305. sqlite3_file *pDb = p->pTargetFd->pReal;
  166306. /* Sync the db file */
  166307. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  166308. /* Update nBackfill */
  166309. if( p->rc==SQLITE_OK ){
  166310. void volatile *ptr;
  166311. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  166312. if( p->rc==SQLITE_OK ){
  166313. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  166314. }
  166315. }
  166316. if( p->rc==SQLITE_OK ){
  166317. p->eStage = RBU_STAGE_DONE;
  166318. p->rc = SQLITE_DONE;
  166319. }
  166320. }else{
  166321. /* At one point the following block copied a single frame from the
  166322. ** wal file to the database file. So that one call to sqlite3rbu_step()
  166323. ** checkpointed a single frame.
  166324. **
  166325. ** However, if the sector-size is larger than the page-size, and the
  166326. ** application calls sqlite3rbu_savestate() or close() immediately
  166327. ** after this step, then rbu_step() again, then a power failure occurs,
  166328. ** then the database page written here may be damaged. Work around
  166329. ** this by checkpointing frames until the next page in the aFrame[]
  166330. ** lies on a different disk sector to the current one. */
  166331. u32 iSector;
  166332. do{
  166333. RbuFrame *pFrame = &p->aFrame[p->nStep];
  166334. iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
  166335. rbuCheckpointFrame(p, pFrame);
  166336. p->nStep++;
  166337. }while( p->nStep<p->nFrame
  166338. && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
  166339. && p->rc==SQLITE_OK
  166340. );
  166341. }
  166342. p->nProgress++;
  166343. }
  166344. break;
  166345. }
  166346. default:
  166347. break;
  166348. }
  166349. return p->rc;
  166350. }else{
  166351. return SQLITE_NOMEM;
  166352. }
  166353. }
  166354. /*
  166355. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  166356. ** otherwise. Either or both argument may be NULL. Two NULL values are
  166357. ** considered equal, and NULL is considered distinct from all other values.
  166358. */
  166359. static int rbuStrCompare(const char *z1, const char *z2){
  166360. if( z1==0 && z2==0 ) return 0;
  166361. if( z1==0 || z2==0 ) return 1;
  166362. return (sqlite3_stricmp(z1, z2)!=0);
  166363. }
  166364. /*
  166365. ** This function is called as part of sqlite3rbu_open() when initializing
  166366. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  166367. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  166368. ** things so that the next call to sqlite3rbu_step() continues on from
  166369. ** where the previous rbu handle left off.
  166370. **
  166371. ** If an error occurs, an error code and error message are left in the
  166372. ** rbu handle passed as the first argument.
  166373. */
  166374. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  166375. assert( p->rc==SQLITE_OK );
  166376. if( pState->zTbl ){
  166377. RbuObjIter *pIter = &p->objiter;
  166378. int rc = SQLITE_OK;
  166379. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  166380. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  166381. || rbuStrCompare(pIter->zTbl, pState->zTbl)
  166382. )){
  166383. rc = rbuObjIterNext(p, pIter);
  166384. }
  166385. if( rc==SQLITE_OK && !pIter->zTbl ){
  166386. rc = SQLITE_ERROR;
  166387. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  166388. }
  166389. if( rc==SQLITE_OK ){
  166390. p->nStep = pState->nRow;
  166391. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  166392. }
  166393. p->rc = rc;
  166394. }
  166395. }
  166396. /*
  166397. ** If there is a "*-oal" file in the file-system corresponding to the
  166398. ** target database in the file-system, delete it. If an error occurs,
  166399. ** leave an error code and error message in the rbu handle.
  166400. */
  166401. static void rbuDeleteOalFile(sqlite3rbu *p){
  166402. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  166403. if( zOal ){
  166404. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  166405. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  166406. pVfs->xDelete(pVfs, zOal, 0);
  166407. sqlite3_free(zOal);
  166408. }
  166409. }
  166410. /*
  166411. ** Allocate a private rbu VFS for the rbu handle passed as the only
  166412. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  166413. ** specified a URI with a vfs=? option in place of a target database
  166414. ** file name.
  166415. */
  166416. static void rbuCreateVfs(sqlite3rbu *p){
  166417. int rnd;
  166418. char zRnd[64];
  166419. assert( p->rc==SQLITE_OK );
  166420. sqlite3_randomness(sizeof(int), (void*)&rnd);
  166421. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  166422. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  166423. if( p->rc==SQLITE_OK ){
  166424. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  166425. assert( pVfs );
  166426. p->zVfsName = pVfs->zName;
  166427. ((rbu_vfs*)pVfs)->pRbu = p;
  166428. }
  166429. }
  166430. /*
  166431. ** Destroy the private VFS created for the rbu handle passed as the only
  166432. ** argument by an earlier call to rbuCreateVfs().
  166433. */
  166434. static void rbuDeleteVfs(sqlite3rbu *p){
  166435. if( p->zVfsName ){
  166436. sqlite3rbu_destroy_vfs(p->zVfsName);
  166437. p->zVfsName = 0;
  166438. }
  166439. }
  166440. /*
  166441. ** This user-defined SQL function is invoked with a single argument - the
  166442. ** name of a table expected to appear in the target database. It returns
  166443. ** the number of auxilliary indexes on the table.
  166444. */
  166445. static void rbuIndexCntFunc(
  166446. sqlite3_context *pCtx,
  166447. int nVal,
  166448. sqlite3_value **apVal
  166449. ){
  166450. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  166451. sqlite3_stmt *pStmt = 0;
  166452. char *zErrmsg = 0;
  166453. int rc;
  166454. assert( nVal==1 );
  166455. rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
  166456. sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
  166457. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  166458. );
  166459. if( rc!=SQLITE_OK ){
  166460. sqlite3_result_error(pCtx, zErrmsg, -1);
  166461. }else{
  166462. int nIndex = 0;
  166463. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  166464. nIndex = sqlite3_column_int(pStmt, 0);
  166465. }
  166466. rc = sqlite3_finalize(pStmt);
  166467. if( rc==SQLITE_OK ){
  166468. sqlite3_result_int(pCtx, nIndex);
  166469. }else{
  166470. sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
  166471. }
  166472. }
  166473. sqlite3_free(zErrmsg);
  166474. }
  166475. /*
  166476. ** If the RBU database contains the rbu_count table, use it to initialize
  166477. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  166478. ** is assumed to contain the same columns as:
  166479. **
  166480. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  166481. **
  166482. ** There should be one row in the table for each data_xxx table in the
  166483. ** database. The 'tbl' column should contain the name of a data_xxx table,
  166484. ** and the cnt column the number of rows it contains.
  166485. **
  166486. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  166487. ** for all rows in the rbu_count table, where nIndex is the number of
  166488. ** indexes on the corresponding target database table.
  166489. */
  166490. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  166491. if( p->rc==SQLITE_OK ){
  166492. sqlite3_stmt *pStmt = 0;
  166493. int bExists = 0; /* True if rbu_count exists */
  166494. p->nPhaseOneStep = -1;
  166495. p->rc = sqlite3_create_function(p->dbRbu,
  166496. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  166497. );
  166498. /* Check for the rbu_count table. If it does not exist, or if an error
  166499. ** occurs, nPhaseOneStep will be left set to -1. */
  166500. if( p->rc==SQLITE_OK ){
  166501. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  166502. "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
  166503. );
  166504. }
  166505. if( p->rc==SQLITE_OK ){
  166506. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  166507. bExists = 1;
  166508. }
  166509. p->rc = sqlite3_finalize(pStmt);
  166510. }
  166511. if( p->rc==SQLITE_OK && bExists ){
  166512. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  166513. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  166514. "FROM rbu_count"
  166515. );
  166516. if( p->rc==SQLITE_OK ){
  166517. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  166518. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  166519. }
  166520. p->rc = sqlite3_finalize(pStmt);
  166521. }
  166522. }
  166523. }
  166524. }
  166525. static sqlite3rbu *openRbuHandle(
  166526. const char *zTarget,
  166527. const char *zRbu,
  166528. const char *zState
  166529. ){
  166530. sqlite3rbu *p;
  166531. size_t nTarget = zTarget ? strlen(zTarget) : 0;
  166532. size_t nRbu = strlen(zRbu);
  166533. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  166534. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  166535. if( p ){
  166536. RbuState *pState = 0;
  166537. /* Create the custom VFS. */
  166538. memset(p, 0, sizeof(sqlite3rbu));
  166539. rbuCreateVfs(p);
  166540. /* Open the target, RBU and state databases */
  166541. if( p->rc==SQLITE_OK ){
  166542. char *pCsr = (char*)&p[1];
  166543. int bRetry = 0;
  166544. if( zTarget ){
  166545. p->zTarget = pCsr;
  166546. memcpy(p->zTarget, zTarget, nTarget+1);
  166547. pCsr += nTarget+1;
  166548. }
  166549. p->zRbu = pCsr;
  166550. memcpy(p->zRbu, zRbu, nRbu+1);
  166551. pCsr += nRbu+1;
  166552. if( zState ){
  166553. p->zState = rbuMPrintf(p, "%s", zState);
  166554. }
  166555. /* If the first attempt to open the database file fails and the bRetry
  166556. ** flag it set, this means that the db was not opened because it seemed
  166557. ** to be a wal-mode db. But, this may have happened due to an earlier
  166558. ** RBU vacuum operation leaving an old wal file in the directory.
  166559. ** If this is the case, it will have been checkpointed and deleted
  166560. ** when the handle was closed and a second attempt to open the
  166561. ** database may succeed. */
  166562. rbuOpenDatabase(p, &bRetry);
  166563. if( bRetry ){
  166564. rbuOpenDatabase(p, 0);
  166565. }
  166566. }
  166567. if( p->rc==SQLITE_OK ){
  166568. pState = rbuLoadState(p);
  166569. assert( pState || p->rc!=SQLITE_OK );
  166570. if( p->rc==SQLITE_OK ){
  166571. if( pState->eStage==0 ){
  166572. rbuDeleteOalFile(p);
  166573. rbuInitPhaseOneSteps(p);
  166574. p->eStage = RBU_STAGE_OAL;
  166575. }else{
  166576. p->eStage = pState->eStage;
  166577. p->nPhaseOneStep = pState->nPhaseOneStep;
  166578. }
  166579. p->nProgress = pState->nProgress;
  166580. p->iOalSz = pState->iOalSz;
  166581. }
  166582. }
  166583. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  166584. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  166585. if( p->eStage==RBU_STAGE_OAL ){
  166586. p->rc = SQLITE_ERROR;
  166587. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  166588. }else if( p->eStage==RBU_STAGE_MOVE ){
  166589. p->eStage = RBU_STAGE_CKPT;
  166590. p->nStep = 0;
  166591. }
  166592. }
  166593. if( p->rc==SQLITE_OK
  166594. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  166595. && pState->eStage!=0
  166596. ){
  166597. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  166598. if( pFd->iCookie!=pState->iCookie ){
  166599. /* At this point (pTargetFd->iCookie) contains the value of the
  166600. ** change-counter cookie (the thing that gets incremented when a
  166601. ** transaction is committed in rollback mode) currently stored on
  166602. ** page 1 of the database file. */
  166603. p->rc = SQLITE_BUSY;
  166604. p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
  166605. (rbuIsVacuum(p) ? "vacuum" : "update")
  166606. );
  166607. }
  166608. }
  166609. if( p->rc==SQLITE_OK ){
  166610. if( p->eStage==RBU_STAGE_OAL ){
  166611. sqlite3 *db = p->dbMain;
  166612. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
  166613. /* Point the object iterator at the first object */
  166614. if( p->rc==SQLITE_OK ){
  166615. p->rc = rbuObjIterFirst(p, &p->objiter);
  166616. }
  166617. /* If the RBU database contains no data_xxx tables, declare the RBU
  166618. ** update finished. */
  166619. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  166620. p->rc = SQLITE_DONE;
  166621. p->eStage = RBU_STAGE_DONE;
  166622. }else{
  166623. if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
  166624. rbuCopyPragma(p, "page_size");
  166625. rbuCopyPragma(p, "auto_vacuum");
  166626. }
  166627. /* Open transactions both databases. The *-oal file is opened or
  166628. ** created at this point. */
  166629. if( p->rc==SQLITE_OK ){
  166630. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  166631. }
  166632. /* Check if the main database is a zipvfs db. If it is, set the upper
  166633. ** level pager to use "journal_mode=off". This prevents it from
  166634. ** generating a large journal using a temp file. */
  166635. if( p->rc==SQLITE_OK ){
  166636. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  166637. if( frc==SQLITE_OK ){
  166638. p->rc = sqlite3_exec(
  166639. db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  166640. }
  166641. }
  166642. if( p->rc==SQLITE_OK ){
  166643. rbuSetupOal(p, pState);
  166644. }
  166645. }
  166646. }else if( p->eStage==RBU_STAGE_MOVE ){
  166647. /* no-op */
  166648. }else if( p->eStage==RBU_STAGE_CKPT ){
  166649. rbuSetupCheckpoint(p, pState);
  166650. }else if( p->eStage==RBU_STAGE_DONE ){
  166651. p->rc = SQLITE_DONE;
  166652. }else{
  166653. p->rc = SQLITE_CORRUPT;
  166654. }
  166655. }
  166656. rbuFreeState(pState);
  166657. }
  166658. return p;
  166659. }
  166660. /*
  166661. ** Allocate and return an RBU handle with all fields zeroed except for the
  166662. ** error code, which is set to SQLITE_MISUSE.
  166663. */
  166664. static sqlite3rbu *rbuMisuseError(void){
  166665. sqlite3rbu *pRet;
  166666. pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
  166667. if( pRet ){
  166668. memset(pRet, 0, sizeof(sqlite3rbu));
  166669. pRet->rc = SQLITE_MISUSE;
  166670. }
  166671. return pRet;
  166672. }
  166673. /*
  166674. ** Open and return a new RBU handle.
  166675. */
  166676. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  166677. const char *zTarget,
  166678. const char *zRbu,
  166679. const char *zState
  166680. ){
  166681. if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  166682. /* TODO: Check that zTarget and zRbu are non-NULL */
  166683. return openRbuHandle(zTarget, zRbu, zState);
  166684. }
  166685. /*
  166686. ** Open a handle to begin or resume an RBU VACUUM operation.
  166687. */
  166688. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  166689. const char *zTarget,
  166690. const char *zState
  166691. ){
  166692. if( zTarget==0 ){ return rbuMisuseError(); }
  166693. /* TODO: Check that both arguments are non-NULL */
  166694. return openRbuHandle(0, zTarget, zState);
  166695. }
  166696. /*
  166697. ** Return the database handle used by pRbu.
  166698. */
  166699. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  166700. sqlite3 *db = 0;
  166701. if( pRbu ){
  166702. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  166703. }
  166704. return db;
  166705. }
  166706. /*
  166707. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  166708. ** then edit any error message string so as to remove all occurrences of
  166709. ** the pattern "rbu_imp_[0-9]*".
  166710. */
  166711. static void rbuEditErrmsg(sqlite3rbu *p){
  166712. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  166713. unsigned int i;
  166714. size_t nErrmsg = strlen(p->zErrmsg);
  166715. for(i=0; i<(nErrmsg-8); i++){
  166716. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  166717. int nDel = 8;
  166718. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  166719. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  166720. nErrmsg -= nDel;
  166721. }
  166722. }
  166723. }
  166724. }
  166725. /*
  166726. ** Close the RBU handle.
  166727. */
  166728. SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  166729. int rc;
  166730. if( p ){
  166731. /* Commit the transaction to the *-oal file. */
  166732. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  166733. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  166734. }
  166735. /* Sync the db file if currently doing an incremental checkpoint */
  166736. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  166737. sqlite3_file *pDb = p->pTargetFd->pReal;
  166738. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  166739. }
  166740. rbuSaveState(p, p->eStage);
  166741. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  166742. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  166743. }
  166744. /* Close any open statement handles. */
  166745. rbuObjIterFinalize(&p->objiter);
  166746. /* If this is an RBU vacuum handle and the vacuum has either finished
  166747. ** successfully or encountered an error, delete the contents of the
  166748. ** state table. This causes the next call to sqlite3rbu_vacuum()
  166749. ** specifying the current target and state databases to start a new
  166750. ** vacuum from scratch. */
  166751. if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
  166752. int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
  166753. if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
  166754. }
  166755. /* Close the open database handle and VFS object. */
  166756. sqlite3_close(p->dbRbu);
  166757. sqlite3_close(p->dbMain);
  166758. assert( p->szTemp==0 );
  166759. rbuDeleteVfs(p);
  166760. sqlite3_free(p->aBuf);
  166761. sqlite3_free(p->aFrame);
  166762. rbuEditErrmsg(p);
  166763. rc = p->rc;
  166764. if( pzErrmsg ){
  166765. *pzErrmsg = p->zErrmsg;
  166766. }else{
  166767. sqlite3_free(p->zErrmsg);
  166768. }
  166769. sqlite3_free(p->zState);
  166770. sqlite3_free(p);
  166771. }else{
  166772. rc = SQLITE_NOMEM;
  166773. *pzErrmsg = 0;
  166774. }
  166775. return rc;
  166776. }
  166777. /*
  166778. ** Return the total number of key-value operations (inserts, deletes or
  166779. ** updates) that have been performed on the target database since the
  166780. ** current RBU update was started.
  166781. */
  166782. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
  166783. return pRbu->nProgress;
  166784. }
  166785. /*
  166786. ** Return permyriadage progress indications for the two main stages of
  166787. ** an RBU update.
  166788. */
  166789. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  166790. const int MAX_PROGRESS = 10000;
  166791. switch( p->eStage ){
  166792. case RBU_STAGE_OAL:
  166793. if( p->nPhaseOneStep>0 ){
  166794. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  166795. }else{
  166796. *pnOne = -1;
  166797. }
  166798. *pnTwo = 0;
  166799. break;
  166800. case RBU_STAGE_MOVE:
  166801. *pnOne = MAX_PROGRESS;
  166802. *pnTwo = 0;
  166803. break;
  166804. case RBU_STAGE_CKPT:
  166805. *pnOne = MAX_PROGRESS;
  166806. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  166807. break;
  166808. case RBU_STAGE_DONE:
  166809. *pnOne = MAX_PROGRESS;
  166810. *pnTwo = MAX_PROGRESS;
  166811. break;
  166812. default:
  166813. assert( 0 );
  166814. }
  166815. }
  166816. /*
  166817. ** Return the current state of the RBU vacuum or update operation.
  166818. */
  166819. SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
  166820. int aRes[] = {
  166821. 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
  166822. 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
  166823. };
  166824. assert( RBU_STAGE_OAL==1 );
  166825. assert( RBU_STAGE_MOVE==2 );
  166826. assert( RBU_STAGE_CKPT==4 );
  166827. assert( RBU_STAGE_DONE==5 );
  166828. assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
  166829. assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
  166830. assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
  166831. assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
  166832. if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
  166833. return SQLITE_RBU_STATE_ERROR;
  166834. }else{
  166835. assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
  166836. assert( p->eStage==RBU_STAGE_OAL
  166837. || p->eStage==RBU_STAGE_MOVE
  166838. || p->eStage==RBU_STAGE_CKPT
  166839. || p->eStage==RBU_STAGE_DONE
  166840. );
  166841. return aRes[p->eStage];
  166842. }
  166843. }
  166844. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
  166845. int rc = p->rc;
  166846. if( rc==SQLITE_DONE ) return SQLITE_OK;
  166847. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  166848. if( p->eStage==RBU_STAGE_OAL ){
  166849. assert( rc!=SQLITE_DONE );
  166850. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  166851. }
  166852. /* Sync the db file */
  166853. if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  166854. sqlite3_file *pDb = p->pTargetFd->pReal;
  166855. rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  166856. }
  166857. p->rc = rc;
  166858. rbuSaveState(p, p->eStage);
  166859. rc = p->rc;
  166860. if( p->eStage==RBU_STAGE_OAL ){
  166861. assert( rc!=SQLITE_DONE );
  166862. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  166863. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
  166864. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  166865. }
  166866. p->rc = rc;
  166867. return rc;
  166868. }
  166869. /**************************************************************************
  166870. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  166871. ** of a standard VFS in the following ways:
  166872. **
  166873. ** 1. Whenever the first page of a main database file is read or
  166874. ** written, the value of the change-counter cookie is stored in
  166875. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  166876. ** database header field is stored in rbu_file.iWriteVer. This ensures
  166877. ** that the values are always trustworthy within an open transaction.
  166878. **
  166879. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  166880. ** member variable of the associated database file descriptor is set
  166881. ** to point to the new file. A mutex protected linked list of all main
  166882. ** db fds opened using a particular RBU VFS is maintained at
  166883. ** rbu_vfs.pMain to facilitate this.
  166884. **
  166885. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  166886. ** object can be marked as the target database of an RBU update. This
  166887. ** turns on the following extra special behaviour:
  166888. **
  166889. ** 3a. If xAccess() is called to check if there exists a *-wal file
  166890. ** associated with an RBU target database currently in RBU_STAGE_OAL
  166891. ** stage (preparing the *-oal file), the following special handling
  166892. ** applies:
  166893. **
  166894. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  166895. ** target database may not be in wal mode already.
  166896. **
  166897. ** * if the *-wal file does not exist, set the output parameter to
  166898. ** non-zero (to tell SQLite that it does exist) anyway.
  166899. **
  166900. ** Then, when xOpen() is called to open the *-wal file associated with
  166901. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  166902. ** file, the rbu vfs opens the corresponding *-oal file instead.
  166903. **
  166904. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  166905. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  166906. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  166907. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  166908. ** because assert() statements in some VFS implementations fail if
  166909. ** xShmLock() is called before xShmMap().
  166910. **
  166911. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  166912. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  166913. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  166914. ** from automatically checkpointing a *-wal (or *-oal) file from within
  166915. ** sqlite3_close().
  166916. **
  166917. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  166918. ** all xWrite() calls on the target database file perform no IO.
  166919. ** Instead the frame and page numbers that would be read and written
  166920. ** are recorded. Additionally, successful attempts to obtain exclusive
  166921. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  166922. ** database file are recorded. xShmLock() calls to unlock the same
  166923. ** locks are no-ops (so that once obtained, these locks are never
  166924. ** relinquished). Finally, calls to xSync() on the target database
  166925. ** file fail with SQLITE_INTERNAL errors.
  166926. */
  166927. static void rbuUnlockShm(rbu_file *p){
  166928. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  166929. if( p->pRbu ){
  166930. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  166931. int i;
  166932. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  166933. if( (1<<i) & p->pRbu->mLock ){
  166934. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  166935. }
  166936. }
  166937. p->pRbu->mLock = 0;
  166938. }
  166939. }
  166940. /*
  166941. */
  166942. static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
  166943. sqlite3rbu *pRbu = pFd->pRbu;
  166944. i64 nDiff = nNew - pFd->sz;
  166945. pRbu->szTemp += nDiff;
  166946. pFd->sz = nNew;
  166947. assert( pRbu->szTemp>=0 );
  166948. if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
  166949. return SQLITE_OK;
  166950. }
  166951. /*
  166952. ** Close an rbu file.
  166953. */
  166954. static int rbuVfsClose(sqlite3_file *pFile){
  166955. rbu_file *p = (rbu_file*)pFile;
  166956. int rc;
  166957. int i;
  166958. /* Free the contents of the apShm[] array. And the array itself. */
  166959. for(i=0; i<p->nShm; i++){
  166960. sqlite3_free(p->apShm[i]);
  166961. }
  166962. sqlite3_free(p->apShm);
  166963. p->apShm = 0;
  166964. sqlite3_free(p->zDel);
  166965. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  166966. rbu_file **pp;
  166967. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  166968. for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
  166969. *pp = p->pMainNext;
  166970. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  166971. rbuUnlockShm(p);
  166972. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  166973. }
  166974. else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  166975. rbuUpdateTempSize(p, 0);
  166976. }
  166977. /* Close the underlying file handle */
  166978. rc = p->pReal->pMethods->xClose(p->pReal);
  166979. return rc;
  166980. }
  166981. /*
  166982. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  166983. ** passed as the only argument.
  166984. */
  166985. static u32 rbuGetU32(u8 *aBuf){
  166986. return ((u32)aBuf[0] << 24)
  166987. + ((u32)aBuf[1] << 16)
  166988. + ((u32)aBuf[2] << 8)
  166989. + ((u32)aBuf[3]);
  166990. }
  166991. /*
  166992. ** Write an unsigned 32-bit value in big-endian format to the supplied
  166993. ** buffer.
  166994. */
  166995. static void rbuPutU32(u8 *aBuf, u32 iVal){
  166996. aBuf[0] = (iVal >> 24) & 0xFF;
  166997. aBuf[1] = (iVal >> 16) & 0xFF;
  166998. aBuf[2] = (iVal >> 8) & 0xFF;
  166999. aBuf[3] = (iVal >> 0) & 0xFF;
  167000. }
  167001. static void rbuPutU16(u8 *aBuf, u16 iVal){
  167002. aBuf[0] = (iVal >> 8) & 0xFF;
  167003. aBuf[1] = (iVal >> 0) & 0xFF;
  167004. }
  167005. /*
  167006. ** Read data from an rbuVfs-file.
  167007. */
  167008. static int rbuVfsRead(
  167009. sqlite3_file *pFile,
  167010. void *zBuf,
  167011. int iAmt,
  167012. sqlite_int64 iOfst
  167013. ){
  167014. rbu_file *p = (rbu_file*)pFile;
  167015. sqlite3rbu *pRbu = p->pRbu;
  167016. int rc;
  167017. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  167018. assert( p->openFlags & SQLITE_OPEN_WAL );
  167019. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  167020. }else{
  167021. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  167022. && (p->openFlags & SQLITE_OPEN_WAL)
  167023. && iOfst>=pRbu->iOalSz
  167024. ){
  167025. rc = SQLITE_OK;
  167026. memset(zBuf, 0, iAmt);
  167027. }else{
  167028. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  167029. #if 1
  167030. /* If this is being called to read the first page of the target
  167031. ** database as part of an rbu vacuum operation, synthesize the
  167032. ** contents of the first page if it does not yet exist. Otherwise,
  167033. ** SQLite will not check for a *-wal file. */
  167034. if( pRbu && rbuIsVacuum(pRbu)
  167035. && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
  167036. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  167037. && pRbu->rc==SQLITE_OK
  167038. ){
  167039. sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
  167040. rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
  167041. if( rc==SQLITE_OK ){
  167042. u8 *aBuf = (u8*)zBuf;
  167043. u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
  167044. rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
  167045. rbuPutU32(&aBuf[36], 0); /* number of free pages */
  167046. rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
  167047. rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
  167048. rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
  167049. if( iAmt>100 ){
  167050. memset(&aBuf[100], 0, iAmt-100);
  167051. rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
  167052. aBuf[100] = 0x0D;
  167053. }
  167054. }
  167055. }
  167056. #endif
  167057. }
  167058. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  167059. /* These look like magic numbers. But they are stable, as they are part
  167060. ** of the definition of the SQLite file format, which may not change. */
  167061. u8 *pBuf = (u8*)zBuf;
  167062. p->iCookie = rbuGetU32(&pBuf[24]);
  167063. p->iWriteVer = pBuf[19];
  167064. }
  167065. }
  167066. return rc;
  167067. }
  167068. /*
  167069. ** Write data to an rbuVfs-file.
  167070. */
  167071. static int rbuVfsWrite(
  167072. sqlite3_file *pFile,
  167073. const void *zBuf,
  167074. int iAmt,
  167075. sqlite_int64 iOfst
  167076. ){
  167077. rbu_file *p = (rbu_file*)pFile;
  167078. sqlite3rbu *pRbu = p->pRbu;
  167079. int rc;
  167080. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  167081. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  167082. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  167083. }else{
  167084. if( pRbu ){
  167085. if( pRbu->eStage==RBU_STAGE_OAL
  167086. && (p->openFlags & SQLITE_OPEN_WAL)
  167087. && iOfst>=pRbu->iOalSz
  167088. ){
  167089. pRbu->iOalSz = iAmt + iOfst;
  167090. }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
  167091. i64 szNew = iAmt+iOfst;
  167092. if( szNew>p->sz ){
  167093. rc = rbuUpdateTempSize(p, szNew);
  167094. if( rc!=SQLITE_OK ) return rc;
  167095. }
  167096. }
  167097. }
  167098. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  167099. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  167100. /* These look like magic numbers. But they are stable, as they are part
  167101. ** of the definition of the SQLite file format, which may not change. */
  167102. u8 *pBuf = (u8*)zBuf;
  167103. p->iCookie = rbuGetU32(&pBuf[24]);
  167104. p->iWriteVer = pBuf[19];
  167105. }
  167106. }
  167107. return rc;
  167108. }
  167109. /*
  167110. ** Truncate an rbuVfs-file.
  167111. */
  167112. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  167113. rbu_file *p = (rbu_file*)pFile;
  167114. if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  167115. int rc = rbuUpdateTempSize(p, size);
  167116. if( rc!=SQLITE_OK ) return rc;
  167117. }
  167118. return p->pReal->pMethods->xTruncate(p->pReal, size);
  167119. }
  167120. /*
  167121. ** Sync an rbuVfs-file.
  167122. */
  167123. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  167124. rbu_file *p = (rbu_file *)pFile;
  167125. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  167126. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  167127. return SQLITE_INTERNAL;
  167128. }
  167129. return SQLITE_OK;
  167130. }
  167131. return p->pReal->pMethods->xSync(p->pReal, flags);
  167132. }
  167133. /*
  167134. ** Return the current file-size of an rbuVfs-file.
  167135. */
  167136. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  167137. rbu_file *p = (rbu_file *)pFile;
  167138. int rc;
  167139. rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
  167140. /* If this is an RBU vacuum operation and this is the target database,
  167141. ** pretend that it has at least one page. Otherwise, SQLite will not
  167142. ** check for the existance of a *-wal file. rbuVfsRead() contains
  167143. ** similar logic. */
  167144. if( rc==SQLITE_OK && *pSize==0
  167145. && p->pRbu && rbuIsVacuum(p->pRbu)
  167146. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  167147. ){
  167148. *pSize = 1024;
  167149. }
  167150. return rc;
  167151. }
  167152. /*
  167153. ** Lock an rbuVfs-file.
  167154. */
  167155. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  167156. rbu_file *p = (rbu_file*)pFile;
  167157. sqlite3rbu *pRbu = p->pRbu;
  167158. int rc = SQLITE_OK;
  167159. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  167160. if( eLock==SQLITE_LOCK_EXCLUSIVE
  167161. && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
  167162. ){
  167163. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  167164. ** prevents it from checkpointing the database from sqlite3_close(). */
  167165. rc = SQLITE_BUSY;
  167166. }else{
  167167. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  167168. }
  167169. return rc;
  167170. }
  167171. /*
  167172. ** Unlock an rbuVfs-file.
  167173. */
  167174. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  167175. rbu_file *p = (rbu_file *)pFile;
  167176. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  167177. }
  167178. /*
  167179. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  167180. */
  167181. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  167182. rbu_file *p = (rbu_file *)pFile;
  167183. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  167184. }
  167185. /*
  167186. ** File control method. For custom operations on an rbuVfs-file.
  167187. */
  167188. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  167189. rbu_file *p = (rbu_file *)pFile;
  167190. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  167191. int rc;
  167192. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  167193. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  167194. );
  167195. if( op==SQLITE_FCNTL_RBU ){
  167196. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  167197. /* First try to find another RBU vfs lower down in the vfs stack. If
  167198. ** one is found, this vfs will operate in pass-through mode. The lower
  167199. ** level vfs will do the special RBU handling. */
  167200. rc = xControl(p->pReal, op, pArg);
  167201. if( rc==SQLITE_NOTFOUND ){
  167202. /* Now search for a zipvfs instance lower down in the VFS stack. If
  167203. ** one is found, this is an error. */
  167204. void *dummy = 0;
  167205. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  167206. if( rc==SQLITE_OK ){
  167207. rc = SQLITE_ERROR;
  167208. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  167209. }else if( rc==SQLITE_NOTFOUND ){
  167210. pRbu->pTargetFd = p;
  167211. p->pRbu = pRbu;
  167212. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  167213. rc = SQLITE_OK;
  167214. }
  167215. }
  167216. return rc;
  167217. }
  167218. else if( op==SQLITE_FCNTL_RBUCNT ){
  167219. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  167220. pRbu->nRbu++;
  167221. pRbu->pRbuFd = p;
  167222. p->bNolock = 1;
  167223. }
  167224. rc = xControl(p->pReal, op, pArg);
  167225. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  167226. rbu_vfs *pRbuVfs = p->pRbuVfs;
  167227. char *zIn = *(char**)pArg;
  167228. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  167229. *(char**)pArg = zOut;
  167230. if( zOut==0 ) rc = SQLITE_NOMEM;
  167231. }
  167232. return rc;
  167233. }
  167234. /*
  167235. ** Return the sector-size in bytes for an rbuVfs-file.
  167236. */
  167237. static int rbuVfsSectorSize(sqlite3_file *pFile){
  167238. rbu_file *p = (rbu_file *)pFile;
  167239. return p->pReal->pMethods->xSectorSize(p->pReal);
  167240. }
  167241. /*
  167242. ** Return the device characteristic flags supported by an rbuVfs-file.
  167243. */
  167244. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  167245. rbu_file *p = (rbu_file *)pFile;
  167246. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  167247. }
  167248. /*
  167249. ** Take or release a shared-memory lock.
  167250. */
  167251. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  167252. rbu_file *p = (rbu_file*)pFile;
  167253. sqlite3rbu *pRbu = p->pRbu;
  167254. int rc = SQLITE_OK;
  167255. #ifdef SQLITE_AMALGAMATION
  167256. assert( WAL_CKPT_LOCK==1 );
  167257. #endif
  167258. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  167259. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  167260. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  167261. ** taking this lock also prevents any checkpoints from occurring.
  167262. ** todo: really, it's not clear why this might occur, as
  167263. ** wal_autocheckpoint ought to be turned off. */
  167264. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  167265. }else{
  167266. int bCapture = 0;
  167267. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  167268. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  167269. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  167270. ){
  167271. bCapture = 1;
  167272. }
  167273. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  167274. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  167275. if( bCapture && rc==SQLITE_OK ){
  167276. pRbu->mLock |= (1 << ofst);
  167277. }
  167278. }
  167279. }
  167280. return rc;
  167281. }
  167282. /*
  167283. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  167284. */
  167285. static int rbuVfsShmMap(
  167286. sqlite3_file *pFile,
  167287. int iRegion,
  167288. int szRegion,
  167289. int isWrite,
  167290. void volatile **pp
  167291. ){
  167292. rbu_file *p = (rbu_file*)pFile;
  167293. int rc = SQLITE_OK;
  167294. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  167295. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  167296. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  167297. ** instead of a file on disk. */
  167298. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  167299. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  167300. if( iRegion<=p->nShm ){
  167301. int nByte = (iRegion+1) * sizeof(char*);
  167302. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  167303. if( apNew==0 ){
  167304. rc = SQLITE_NOMEM;
  167305. }else{
  167306. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  167307. p->apShm = apNew;
  167308. p->nShm = iRegion+1;
  167309. }
  167310. }
  167311. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  167312. char *pNew = (char*)sqlite3_malloc64(szRegion);
  167313. if( pNew==0 ){
  167314. rc = SQLITE_NOMEM;
  167315. }else{
  167316. memset(pNew, 0, szRegion);
  167317. p->apShm[iRegion] = pNew;
  167318. }
  167319. }
  167320. if( rc==SQLITE_OK ){
  167321. *pp = p->apShm[iRegion];
  167322. }else{
  167323. *pp = 0;
  167324. }
  167325. }else{
  167326. assert( p->apShm==0 );
  167327. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  167328. }
  167329. return rc;
  167330. }
  167331. /*
  167332. ** Memory barrier.
  167333. */
  167334. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  167335. rbu_file *p = (rbu_file *)pFile;
  167336. p->pReal->pMethods->xShmBarrier(p->pReal);
  167337. }
  167338. /*
  167339. ** The xShmUnmap method.
  167340. */
  167341. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  167342. rbu_file *p = (rbu_file*)pFile;
  167343. int rc = SQLITE_OK;
  167344. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  167345. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  167346. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  167347. /* no-op */
  167348. }else{
  167349. /* Release the checkpointer and writer locks */
  167350. rbuUnlockShm(p);
  167351. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  167352. }
  167353. return rc;
  167354. }
  167355. /*
  167356. ** Given that zWal points to a buffer containing a wal file name passed to
  167357. ** either the xOpen() or xAccess() VFS method, return a pointer to the
  167358. ** file-handle opened by the same database connection on the corresponding
  167359. ** database file.
  167360. */
  167361. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
  167362. rbu_file *pDb;
  167363. sqlite3_mutex_enter(pRbuVfs->mutex);
  167364. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  167365. sqlite3_mutex_leave(pRbuVfs->mutex);
  167366. return pDb;
  167367. }
  167368. /*
  167369. ** A main database named zName has just been opened. The following
  167370. ** function returns a pointer to a buffer owned by SQLite that contains
  167371. ** the name of the *-wal file this db connection will use. SQLite
  167372. ** happens to pass a pointer to this buffer when using xAccess()
  167373. ** or xOpen() to operate on the *-wal file.
  167374. */
  167375. static const char *rbuMainToWal(const char *zName, int flags){
  167376. int n = (int)strlen(zName);
  167377. const char *z = &zName[n];
  167378. if( flags & SQLITE_OPEN_URI ){
  167379. int odd = 0;
  167380. while( 1 ){
  167381. if( z[0]==0 ){
  167382. odd = 1 - odd;
  167383. if( odd && z[1]==0 ) break;
  167384. }
  167385. z++;
  167386. }
  167387. z += 2;
  167388. }else{
  167389. while( *z==0 ) z++;
  167390. }
  167391. z += (n + 8 + 1);
  167392. return z;
  167393. }
  167394. /*
  167395. ** Open an rbu file handle.
  167396. */
  167397. static int rbuVfsOpen(
  167398. sqlite3_vfs *pVfs,
  167399. const char *zName,
  167400. sqlite3_file *pFile,
  167401. int flags,
  167402. int *pOutFlags
  167403. ){
  167404. static sqlite3_io_methods rbuvfs_io_methods = {
  167405. 2, /* iVersion */
  167406. rbuVfsClose, /* xClose */
  167407. rbuVfsRead, /* xRead */
  167408. rbuVfsWrite, /* xWrite */
  167409. rbuVfsTruncate, /* xTruncate */
  167410. rbuVfsSync, /* xSync */
  167411. rbuVfsFileSize, /* xFileSize */
  167412. rbuVfsLock, /* xLock */
  167413. rbuVfsUnlock, /* xUnlock */
  167414. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  167415. rbuVfsFileControl, /* xFileControl */
  167416. rbuVfsSectorSize, /* xSectorSize */
  167417. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  167418. rbuVfsShmMap, /* xShmMap */
  167419. rbuVfsShmLock, /* xShmLock */
  167420. rbuVfsShmBarrier, /* xShmBarrier */
  167421. rbuVfsShmUnmap, /* xShmUnmap */
  167422. 0, 0 /* xFetch, xUnfetch */
  167423. };
  167424. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  167425. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  167426. rbu_file *pFd = (rbu_file *)pFile;
  167427. int rc = SQLITE_OK;
  167428. const char *zOpen = zName;
  167429. int oflags = flags;
  167430. memset(pFd, 0, sizeof(rbu_file));
  167431. pFd->pReal = (sqlite3_file*)&pFd[1];
  167432. pFd->pRbuVfs = pRbuVfs;
  167433. pFd->openFlags = flags;
  167434. if( zName ){
  167435. if( flags & SQLITE_OPEN_MAIN_DB ){
  167436. /* A main database has just been opened. The following block sets
  167437. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  167438. ** the name of the *-wal file this db connection will use. SQLite
  167439. ** happens to pass a pointer to this buffer when using xAccess()
  167440. ** or xOpen() to operate on the *-wal file. */
  167441. pFd->zWal = rbuMainToWal(zName, flags);
  167442. }
  167443. else if( flags & SQLITE_OPEN_WAL ){
  167444. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
  167445. if( pDb ){
  167446. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  167447. /* This call is to open a *-wal file. Intead, open the *-oal. This
  167448. ** code ensures that the string passed to xOpen() is terminated by a
  167449. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  167450. ** parameter from it. */
  167451. const char *zBase = zName;
  167452. size_t nCopy;
  167453. char *zCopy;
  167454. if( rbuIsVacuum(pDb->pRbu) ){
  167455. zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
  167456. zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
  167457. }
  167458. nCopy = strlen(zBase);
  167459. zCopy = sqlite3_malloc64(nCopy+2);
  167460. if( zCopy ){
  167461. memcpy(zCopy, zBase, nCopy);
  167462. zCopy[nCopy-3] = 'o';
  167463. zCopy[nCopy] = '\0';
  167464. zCopy[nCopy+1] = '\0';
  167465. zOpen = (const char*)(pFd->zDel = zCopy);
  167466. }else{
  167467. rc = SQLITE_NOMEM;
  167468. }
  167469. pFd->pRbu = pDb->pRbu;
  167470. }
  167471. pDb->pWalFd = pFd;
  167472. }
  167473. }
  167474. }else{
  167475. pFd->pRbu = pRbuVfs->pRbu;
  167476. }
  167477. if( oflags & SQLITE_OPEN_MAIN_DB
  167478. && sqlite3_uri_boolean(zName, "rbu_memory", 0)
  167479. ){
  167480. assert( oflags & SQLITE_OPEN_MAIN_DB );
  167481. oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  167482. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  167483. zOpen = 0;
  167484. }
  167485. if( rc==SQLITE_OK ){
  167486. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
  167487. }
  167488. if( pFd->pReal->pMethods ){
  167489. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  167490. ** pointer and, if the file is a main database file, link it into the
  167491. ** mutex protected linked list of all such files. */
  167492. pFile->pMethods = &rbuvfs_io_methods;
  167493. if( flags & SQLITE_OPEN_MAIN_DB ){
  167494. sqlite3_mutex_enter(pRbuVfs->mutex);
  167495. pFd->pMainNext = pRbuVfs->pMain;
  167496. pRbuVfs->pMain = pFd;
  167497. sqlite3_mutex_leave(pRbuVfs->mutex);
  167498. }
  167499. }else{
  167500. sqlite3_free(pFd->zDel);
  167501. }
  167502. return rc;
  167503. }
  167504. /*
  167505. ** Delete the file located at zPath.
  167506. */
  167507. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  167508. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  167509. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  167510. }
  167511. /*
  167512. ** Test for access permissions. Return true if the requested permission
  167513. ** is available, or false otherwise.
  167514. */
  167515. static int rbuVfsAccess(
  167516. sqlite3_vfs *pVfs,
  167517. const char *zPath,
  167518. int flags,
  167519. int *pResOut
  167520. ){
  167521. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  167522. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  167523. int rc;
  167524. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  167525. /* If this call is to check if a *-wal file associated with an RBU target
  167526. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  167527. ** the following special handling is activated:
  167528. **
  167529. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  167530. ** ensures that the RBU extension never tries to update a database
  167531. ** in wal mode, even if the first page of the database file has
  167532. ** been damaged.
  167533. **
  167534. ** b) if the *-wal file does not exist, claim that it does anyway,
  167535. ** causing SQLite to call xOpen() to open it. This call will also
  167536. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  167537. ** file opened instead.
  167538. */
  167539. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  167540. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
  167541. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  167542. if( *pResOut ){
  167543. rc = SQLITE_CANTOPEN;
  167544. }else{
  167545. sqlite3_int64 sz = 0;
  167546. rc = rbuVfsFileSize(&pDb->base, &sz);
  167547. *pResOut = (sz>0);
  167548. }
  167549. }
  167550. }
  167551. return rc;
  167552. }
  167553. /*
  167554. ** Populate buffer zOut with the full canonical pathname corresponding
  167555. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  167556. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  167557. */
  167558. static int rbuVfsFullPathname(
  167559. sqlite3_vfs *pVfs,
  167560. const char *zPath,
  167561. int nOut,
  167562. char *zOut
  167563. ){
  167564. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  167565. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  167566. }
  167567. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  167568. /*
  167569. ** Open the dynamic library located at zPath and return a handle.
  167570. */
  167571. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  167572. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  167573. return pRealVfs->xDlOpen(pRealVfs, zPath);
  167574. }
  167575. /*
  167576. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  167577. ** utf-8 string describing the most recent error encountered associated
  167578. ** with dynamic libraries.
  167579. */
  167580. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  167581. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  167582. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  167583. }
  167584. /*
  167585. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  167586. */
  167587. static void (*rbuVfsDlSym(
  167588. sqlite3_vfs *pVfs,
  167589. void *pArg,
  167590. const char *zSym
  167591. ))(void){
  167592. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  167593. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  167594. }
  167595. /*
  167596. ** Close the dynamic library handle pHandle.
  167597. */
  167598. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  167599. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  167600. pRealVfs->xDlClose(pRealVfs, pHandle);
  167601. }
  167602. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  167603. /*
  167604. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  167605. ** random data.
  167606. */
  167607. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  167608. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  167609. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  167610. }
  167611. /*
  167612. ** Sleep for nMicro microseconds. Return the number of microseconds
  167613. ** actually slept.
  167614. */
  167615. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  167616. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  167617. return pRealVfs->xSleep(pRealVfs, nMicro);
  167618. }
  167619. /*
  167620. ** Return the current time as a Julian Day number in *pTimeOut.
  167621. */
  167622. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  167623. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  167624. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  167625. }
  167626. /*
  167627. ** No-op.
  167628. */
  167629. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  167630. return 0;
  167631. }
  167632. /*
  167633. ** Deregister and destroy an RBU vfs created by an earlier call to
  167634. ** sqlite3rbu_create_vfs().
  167635. */
  167636. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
  167637. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  167638. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  167639. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  167640. sqlite3_vfs_unregister(pVfs);
  167641. sqlite3_free(pVfs);
  167642. }
  167643. }
  167644. /*
  167645. ** Create an RBU VFS named zName that accesses the underlying file-system
  167646. ** via existing VFS zParent. The new object is registered as a non-default
  167647. ** VFS with SQLite before returning.
  167648. */
  167649. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  167650. /* Template for VFS */
  167651. static sqlite3_vfs vfs_template = {
  167652. 1, /* iVersion */
  167653. 0, /* szOsFile */
  167654. 0, /* mxPathname */
  167655. 0, /* pNext */
  167656. 0, /* zName */
  167657. 0, /* pAppData */
  167658. rbuVfsOpen, /* xOpen */
  167659. rbuVfsDelete, /* xDelete */
  167660. rbuVfsAccess, /* xAccess */
  167661. rbuVfsFullPathname, /* xFullPathname */
  167662. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  167663. rbuVfsDlOpen, /* xDlOpen */
  167664. rbuVfsDlError, /* xDlError */
  167665. rbuVfsDlSym, /* xDlSym */
  167666. rbuVfsDlClose, /* xDlClose */
  167667. #else
  167668. 0, 0, 0, 0,
  167669. #endif
  167670. rbuVfsRandomness, /* xRandomness */
  167671. rbuVfsSleep, /* xSleep */
  167672. rbuVfsCurrentTime, /* xCurrentTime */
  167673. rbuVfsGetLastError, /* xGetLastError */
  167674. 0, /* xCurrentTimeInt64 (version 2) */
  167675. 0, 0, 0 /* Unimplemented version 3 methods */
  167676. };
  167677. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  167678. int rc = SQLITE_OK;
  167679. size_t nName;
  167680. size_t nByte;
  167681. nName = strlen(zName);
  167682. nByte = sizeof(rbu_vfs) + nName + 1;
  167683. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  167684. if( pNew==0 ){
  167685. rc = SQLITE_NOMEM;
  167686. }else{
  167687. sqlite3_vfs *pParent; /* Parent VFS */
  167688. memset(pNew, 0, nByte);
  167689. pParent = sqlite3_vfs_find(zParent);
  167690. if( pParent==0 ){
  167691. rc = SQLITE_NOTFOUND;
  167692. }else{
  167693. char *zSpace;
  167694. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  167695. pNew->base.mxPathname = pParent->mxPathname;
  167696. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  167697. pNew->pRealVfs = pParent;
  167698. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  167699. memcpy(zSpace, zName, nName);
  167700. /* Allocate the mutex and register the new VFS (not as the default) */
  167701. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  167702. if( pNew->mutex==0 ){
  167703. rc = SQLITE_NOMEM;
  167704. }else{
  167705. rc = sqlite3_vfs_register(&pNew->base, 0);
  167706. }
  167707. }
  167708. if( rc!=SQLITE_OK ){
  167709. sqlite3_mutex_free(pNew->mutex);
  167710. sqlite3_free(pNew);
  167711. }
  167712. }
  167713. return rc;
  167714. }
  167715. /*
  167716. ** Configure the aggregate temp file size limit for this RBU handle.
  167717. */
  167718. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
  167719. if( n>=0 ){
  167720. pRbu->szTempLimit = n;
  167721. }
  167722. return pRbu->szTempLimit;
  167723. }
  167724. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
  167725. return pRbu->szTemp;
  167726. }
  167727. /**************************************************************************/
  167728. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  167729. /************** End of sqlite3rbu.c ******************************************/
  167730. /************** Begin file dbstat.c ******************************************/
  167731. /*
  167732. ** 2010 July 12
  167733. **
  167734. ** The author disclaims copyright to this source code. In place of
  167735. ** a legal notice, here is a blessing:
  167736. **
  167737. ** May you do good and not evil.
  167738. ** May you find forgiveness for yourself and forgive others.
  167739. ** May you share freely, never taking more than you give.
  167740. **
  167741. ******************************************************************************
  167742. **
  167743. ** This file contains an implementation of the "dbstat" virtual table.
  167744. **
  167745. ** The dbstat virtual table is used to extract low-level formatting
  167746. ** information from an SQLite database in order to implement the
  167747. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  167748. ** for an example implementation.
  167749. **
  167750. ** Additional information is available on the "dbstat.html" page of the
  167751. ** official SQLite documentation.
  167752. */
  167753. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  167754. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  167755. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  167756. /*
  167757. ** Page paths:
  167758. **
  167759. ** The value of the 'path' column describes the path taken from the
  167760. ** root-node of the b-tree structure to each page. The value of the
  167761. ** root-node path is '/'.
  167762. **
  167763. ** The value of the path for the left-most child page of the root of
  167764. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  167765. ** so the pages to the left have smaller keys than the pages to the right.)
  167766. ** The next to left-most child of the root page is
  167767. ** '/001', and so on, each sibling page identified by a 3-digit hex
  167768. ** value. The children of the 451st left-most sibling have paths such
  167769. ** as '/1c2/000/, '/1c2/001/' etc.
  167770. **
  167771. ** Overflow pages are specified by appending a '+' character and a
  167772. ** six-digit hexadecimal value to the path to the cell they are linked
  167773. ** from. For example, the three overflow pages in a chain linked from
  167774. ** the left-most cell of the 450th child of the root page are identified
  167775. ** by the paths:
  167776. **
  167777. ** '/1c2/000+000000' // First page in overflow chain
  167778. ** '/1c2/000+000001' // Second page in overflow chain
  167779. ** '/1c2/000+000002' // Third page in overflow chain
  167780. **
  167781. ** If the paths are sorted using the BINARY collation sequence, then
  167782. ** the overflow pages associated with a cell will appear earlier in the
  167783. ** sort-order than its child page:
  167784. **
  167785. ** '/1c2/000/' // Left-most child of 451st child of root
  167786. */
  167787. #define VTAB_SCHEMA \
  167788. "CREATE TABLE xx( " \
  167789. " name TEXT, /* Name of table or index */" \
  167790. " path TEXT, /* Path to page from root */" \
  167791. " pageno INTEGER, /* Page number */" \
  167792. " pagetype TEXT, /* 'internal', 'leaf' or 'overflow' */" \
  167793. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  167794. " payload INTEGER, /* Bytes of payload on this page */" \
  167795. " unused INTEGER, /* Bytes of unused space on this page */" \
  167796. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  167797. " pgoffset INTEGER, /* Offset of page in file */" \
  167798. " pgsize INTEGER, /* Size of the page */" \
  167799. " schema TEXT HIDDEN /* Database schema being analyzed */" \
  167800. ");"
  167801. typedef struct StatTable StatTable;
  167802. typedef struct StatCursor StatCursor;
  167803. typedef struct StatPage StatPage;
  167804. typedef struct StatCell StatCell;
  167805. struct StatCell {
  167806. int nLocal; /* Bytes of local payload */
  167807. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  167808. int nOvfl; /* Entries in aOvfl[] */
  167809. u32 *aOvfl; /* Array of overflow page numbers */
  167810. int nLastOvfl; /* Bytes of payload on final overflow page */
  167811. int iOvfl; /* Iterates through aOvfl[] */
  167812. };
  167813. struct StatPage {
  167814. u32 iPgno;
  167815. DbPage *pPg;
  167816. int iCell;
  167817. char *zPath; /* Path to this page */
  167818. /* Variables populated by statDecodePage(): */
  167819. u8 flags; /* Copy of flags byte */
  167820. int nCell; /* Number of cells on page */
  167821. int nUnused; /* Number of unused bytes on page */
  167822. StatCell *aCell; /* Array of parsed cells */
  167823. u32 iRightChildPg; /* Right-child page number (or 0) */
  167824. int nMxPayload; /* Largest payload of any cell on this page */
  167825. };
  167826. struct StatCursor {
  167827. sqlite3_vtab_cursor base;
  167828. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  167829. int isEof; /* After pStmt has returned SQLITE_DONE */
  167830. int iDb; /* Schema used for this query */
  167831. StatPage aPage[32];
  167832. int iPage; /* Current entry in aPage[] */
  167833. /* Values to return. */
  167834. char *zName; /* Value of 'name' column */
  167835. char *zPath; /* Value of 'path' column */
  167836. u32 iPageno; /* Value of 'pageno' column */
  167837. char *zPagetype; /* Value of 'pagetype' column */
  167838. int nCell; /* Value of 'ncell' column */
  167839. int nPayload; /* Value of 'payload' column */
  167840. int nUnused; /* Value of 'unused' column */
  167841. int nMxPayload; /* Value of 'mx_payload' column */
  167842. i64 iOffset; /* Value of 'pgOffset' column */
  167843. int szPage; /* Value of 'pgSize' column */
  167844. };
  167845. struct StatTable {
  167846. sqlite3_vtab base;
  167847. sqlite3 *db;
  167848. int iDb; /* Index of database to analyze */
  167849. };
  167850. #ifndef get2byte
  167851. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  167852. #endif
  167853. /*
  167854. ** Connect to or create a statvfs virtual table.
  167855. */
  167856. static int statConnect(
  167857. sqlite3 *db,
  167858. void *pAux,
  167859. int argc, const char *const*argv,
  167860. sqlite3_vtab **ppVtab,
  167861. char **pzErr
  167862. ){
  167863. StatTable *pTab = 0;
  167864. int rc = SQLITE_OK;
  167865. int iDb;
  167866. if( argc>=4 ){
  167867. Token nm;
  167868. sqlite3TokenInit(&nm, (char*)argv[3]);
  167869. iDb = sqlite3FindDb(db, &nm);
  167870. if( iDb<0 ){
  167871. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  167872. return SQLITE_ERROR;
  167873. }
  167874. }else{
  167875. iDb = 0;
  167876. }
  167877. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  167878. if( rc==SQLITE_OK ){
  167879. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  167880. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  167881. }
  167882. assert( rc==SQLITE_OK || pTab==0 );
  167883. if( rc==SQLITE_OK ){
  167884. memset(pTab, 0, sizeof(StatTable));
  167885. pTab->db = db;
  167886. pTab->iDb = iDb;
  167887. }
  167888. *ppVtab = (sqlite3_vtab*)pTab;
  167889. return rc;
  167890. }
  167891. /*
  167892. ** Disconnect from or destroy a statvfs virtual table.
  167893. */
  167894. static int statDisconnect(sqlite3_vtab *pVtab){
  167895. sqlite3_free(pVtab);
  167896. return SQLITE_OK;
  167897. }
  167898. /*
  167899. ** There is no "best-index". This virtual table always does a linear
  167900. ** scan. However, a schema=? constraint should cause this table to
  167901. ** operate on a different database schema, so check for it.
  167902. **
  167903. ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
  167904. */
  167905. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  167906. int i;
  167907. pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
  167908. /* Look for a valid schema=? constraint. If found, change the idxNum to
  167909. ** 1 and request the value of that constraint be sent to xFilter. And
  167910. ** lower the cost estimate to encourage the constrained version to be
  167911. ** used.
  167912. */
  167913. for(i=0; i<pIdxInfo->nConstraint; i++){
  167914. if( pIdxInfo->aConstraint[i].usable==0 ) continue;
  167915. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  167916. if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
  167917. pIdxInfo->idxNum = 1;
  167918. pIdxInfo->estimatedCost = 1.0;
  167919. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  167920. pIdxInfo->aConstraintUsage[i].omit = 1;
  167921. break;
  167922. }
  167923. /* Records are always returned in ascending order of (name, path).
  167924. ** If this will satisfy the client, set the orderByConsumed flag so that
  167925. ** SQLite does not do an external sort.
  167926. */
  167927. if( ( pIdxInfo->nOrderBy==1
  167928. && pIdxInfo->aOrderBy[0].iColumn==0
  167929. && pIdxInfo->aOrderBy[0].desc==0
  167930. ) ||
  167931. ( pIdxInfo->nOrderBy==2
  167932. && pIdxInfo->aOrderBy[0].iColumn==0
  167933. && pIdxInfo->aOrderBy[0].desc==0
  167934. && pIdxInfo->aOrderBy[1].iColumn==1
  167935. && pIdxInfo->aOrderBy[1].desc==0
  167936. )
  167937. ){
  167938. pIdxInfo->orderByConsumed = 1;
  167939. }
  167940. return SQLITE_OK;
  167941. }
  167942. /*
  167943. ** Open a new statvfs cursor.
  167944. */
  167945. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  167946. StatTable *pTab = (StatTable *)pVTab;
  167947. StatCursor *pCsr;
  167948. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  167949. if( pCsr==0 ){
  167950. return SQLITE_NOMEM_BKPT;
  167951. }else{
  167952. memset(pCsr, 0, sizeof(StatCursor));
  167953. pCsr->base.pVtab = pVTab;
  167954. pCsr->iDb = pTab->iDb;
  167955. }
  167956. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  167957. return SQLITE_OK;
  167958. }
  167959. static void statClearPage(StatPage *p){
  167960. int i;
  167961. if( p->aCell ){
  167962. for(i=0; i<p->nCell; i++){
  167963. sqlite3_free(p->aCell[i].aOvfl);
  167964. }
  167965. sqlite3_free(p->aCell);
  167966. }
  167967. sqlite3PagerUnref(p->pPg);
  167968. sqlite3_free(p->zPath);
  167969. memset(p, 0, sizeof(StatPage));
  167970. }
  167971. static void statResetCsr(StatCursor *pCsr){
  167972. int i;
  167973. sqlite3_reset(pCsr->pStmt);
  167974. for(i=0; i<ArraySize(pCsr->aPage); i++){
  167975. statClearPage(&pCsr->aPage[i]);
  167976. }
  167977. pCsr->iPage = 0;
  167978. sqlite3_free(pCsr->zPath);
  167979. pCsr->zPath = 0;
  167980. pCsr->isEof = 0;
  167981. }
  167982. /*
  167983. ** Close a statvfs cursor.
  167984. */
  167985. static int statClose(sqlite3_vtab_cursor *pCursor){
  167986. StatCursor *pCsr = (StatCursor *)pCursor;
  167987. statResetCsr(pCsr);
  167988. sqlite3_finalize(pCsr->pStmt);
  167989. sqlite3_free(pCsr);
  167990. return SQLITE_OK;
  167991. }
  167992. static void getLocalPayload(
  167993. int nUsable, /* Usable bytes per page */
  167994. u8 flags, /* Page flags */
  167995. int nTotal, /* Total record (payload) size */
  167996. int *pnLocal /* OUT: Bytes stored locally */
  167997. ){
  167998. int nLocal;
  167999. int nMinLocal;
  168000. int nMaxLocal;
  168001. if( flags==0x0D ){ /* Table leaf node */
  168002. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  168003. nMaxLocal = nUsable - 35;
  168004. }else{ /* Index interior and leaf nodes */
  168005. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  168006. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  168007. }
  168008. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  168009. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  168010. *pnLocal = nLocal;
  168011. }
  168012. static int statDecodePage(Btree *pBt, StatPage *p){
  168013. int nUnused;
  168014. int iOff;
  168015. int nHdr;
  168016. int isLeaf;
  168017. int szPage;
  168018. u8 *aData = sqlite3PagerGetData(p->pPg);
  168019. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  168020. p->flags = aHdr[0];
  168021. p->nCell = get2byte(&aHdr[3]);
  168022. p->nMxPayload = 0;
  168023. isLeaf = (p->flags==0x0A || p->flags==0x0D);
  168024. nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
  168025. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  168026. nUnused += (int)aHdr[7];
  168027. iOff = get2byte(&aHdr[1]);
  168028. while( iOff ){
  168029. nUnused += get2byte(&aData[iOff+2]);
  168030. iOff = get2byte(&aData[iOff]);
  168031. }
  168032. p->nUnused = nUnused;
  168033. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  168034. szPage = sqlite3BtreeGetPageSize(pBt);
  168035. if( p->nCell ){
  168036. int i; /* Used to iterate through cells */
  168037. int nUsable; /* Usable bytes per page */
  168038. sqlite3BtreeEnter(pBt);
  168039. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  168040. sqlite3BtreeLeave(pBt);
  168041. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  168042. if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
  168043. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  168044. for(i=0; i<p->nCell; i++){
  168045. StatCell *pCell = &p->aCell[i];
  168046. iOff = get2byte(&aData[nHdr+i*2]);
  168047. if( !isLeaf ){
  168048. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  168049. iOff += 4;
  168050. }
  168051. if( p->flags==0x05 ){
  168052. /* A table interior node. nPayload==0. */
  168053. }else{
  168054. u32 nPayload; /* Bytes of payload total (local+overflow) */
  168055. int nLocal; /* Bytes of payload stored locally */
  168056. iOff += getVarint32(&aData[iOff], nPayload);
  168057. if( p->flags==0x0D ){
  168058. u64 dummy;
  168059. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  168060. }
  168061. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  168062. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  168063. pCell->nLocal = nLocal;
  168064. assert( nLocal>=0 );
  168065. assert( nPayload>=(u32)nLocal );
  168066. assert( nLocal<=(nUsable-35) );
  168067. if( nPayload>(u32)nLocal ){
  168068. int j;
  168069. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  168070. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  168071. pCell->nOvfl = nOvfl;
  168072. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  168073. if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
  168074. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  168075. for(j=1; j<nOvfl; j++){
  168076. int rc;
  168077. u32 iPrev = pCell->aOvfl[j-1];
  168078. DbPage *pPg = 0;
  168079. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  168080. if( rc!=SQLITE_OK ){
  168081. assert( pPg==0 );
  168082. return rc;
  168083. }
  168084. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  168085. sqlite3PagerUnref(pPg);
  168086. }
  168087. }
  168088. }
  168089. }
  168090. }
  168091. return SQLITE_OK;
  168092. }
  168093. /*
  168094. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  168095. ** the current value of pCsr->iPageno.
  168096. */
  168097. static void statSizeAndOffset(StatCursor *pCsr){
  168098. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  168099. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  168100. Pager *pPager = sqlite3BtreePager(pBt);
  168101. sqlite3_file *fd;
  168102. sqlite3_int64 x[2];
  168103. /* The default page size and offset */
  168104. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  168105. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  168106. /* If connected to a ZIPVFS backend, override the page size and
  168107. ** offset with actual values obtained from ZIPVFS.
  168108. */
  168109. fd = sqlite3PagerFile(pPager);
  168110. x[0] = pCsr->iPageno;
  168111. if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  168112. pCsr->iOffset = x[0];
  168113. pCsr->szPage = (int)x[1];
  168114. }
  168115. }
  168116. /*
  168117. ** Move a statvfs cursor to the next entry in the file.
  168118. */
  168119. static int statNext(sqlite3_vtab_cursor *pCursor){
  168120. int rc;
  168121. int nPayload;
  168122. char *z;
  168123. StatCursor *pCsr = (StatCursor *)pCursor;
  168124. StatTable *pTab = (StatTable *)pCursor->pVtab;
  168125. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  168126. Pager *pPager = sqlite3BtreePager(pBt);
  168127. sqlite3_free(pCsr->zPath);
  168128. pCsr->zPath = 0;
  168129. statNextRestart:
  168130. if( pCsr->aPage[0].pPg==0 ){
  168131. rc = sqlite3_step(pCsr->pStmt);
  168132. if( rc==SQLITE_ROW ){
  168133. int nPage;
  168134. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  168135. sqlite3PagerPagecount(pPager, &nPage);
  168136. if( nPage==0 ){
  168137. pCsr->isEof = 1;
  168138. return sqlite3_reset(pCsr->pStmt);
  168139. }
  168140. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  168141. pCsr->aPage[0].iPgno = iRoot;
  168142. pCsr->aPage[0].iCell = 0;
  168143. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  168144. pCsr->iPage = 0;
  168145. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  168146. }else{
  168147. pCsr->isEof = 1;
  168148. return sqlite3_reset(pCsr->pStmt);
  168149. }
  168150. }else{
  168151. /* Page p itself has already been visited. */
  168152. StatPage *p = &pCsr->aPage[pCsr->iPage];
  168153. while( p->iCell<p->nCell ){
  168154. StatCell *pCell = &p->aCell[p->iCell];
  168155. if( pCell->iOvfl<pCell->nOvfl ){
  168156. int nUsable;
  168157. sqlite3BtreeEnter(pBt);
  168158. nUsable = sqlite3BtreeGetPageSize(pBt) -
  168159. sqlite3BtreeGetReserveNoMutex(pBt);
  168160. sqlite3BtreeLeave(pBt);
  168161. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  168162. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  168163. pCsr->zPagetype = "overflow";
  168164. pCsr->nCell = 0;
  168165. pCsr->nMxPayload = 0;
  168166. pCsr->zPath = z = sqlite3_mprintf(
  168167. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  168168. );
  168169. if( pCell->iOvfl<pCell->nOvfl-1 ){
  168170. pCsr->nUnused = 0;
  168171. pCsr->nPayload = nUsable - 4;
  168172. }else{
  168173. pCsr->nPayload = pCell->nLastOvfl;
  168174. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  168175. }
  168176. pCell->iOvfl++;
  168177. statSizeAndOffset(pCsr);
  168178. return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  168179. }
  168180. if( p->iRightChildPg ) break;
  168181. p->iCell++;
  168182. }
  168183. if( !p->iRightChildPg || p->iCell>p->nCell ){
  168184. statClearPage(p);
  168185. if( pCsr->iPage==0 ) return statNext(pCursor);
  168186. pCsr->iPage--;
  168187. goto statNextRestart; /* Tail recursion */
  168188. }
  168189. pCsr->iPage++;
  168190. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  168191. if( p->iCell==p->nCell ){
  168192. p[1].iPgno = p->iRightChildPg;
  168193. }else{
  168194. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  168195. }
  168196. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  168197. p[1].iCell = 0;
  168198. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  168199. p->iCell++;
  168200. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  168201. }
  168202. /* Populate the StatCursor fields with the values to be returned
  168203. ** by the xColumn() and xRowid() methods.
  168204. */
  168205. if( rc==SQLITE_OK ){
  168206. int i;
  168207. StatPage *p = &pCsr->aPage[pCsr->iPage];
  168208. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  168209. pCsr->iPageno = p->iPgno;
  168210. rc = statDecodePage(pBt, p);
  168211. if( rc==SQLITE_OK ){
  168212. statSizeAndOffset(pCsr);
  168213. switch( p->flags ){
  168214. case 0x05: /* table internal */
  168215. case 0x02: /* index internal */
  168216. pCsr->zPagetype = "internal";
  168217. break;
  168218. case 0x0D: /* table leaf */
  168219. case 0x0A: /* index leaf */
  168220. pCsr->zPagetype = "leaf";
  168221. break;
  168222. default:
  168223. pCsr->zPagetype = "corrupted";
  168224. break;
  168225. }
  168226. pCsr->nCell = p->nCell;
  168227. pCsr->nUnused = p->nUnused;
  168228. pCsr->nMxPayload = p->nMxPayload;
  168229. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  168230. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  168231. nPayload = 0;
  168232. for(i=0; i<p->nCell; i++){
  168233. nPayload += p->aCell[i].nLocal;
  168234. }
  168235. pCsr->nPayload = nPayload;
  168236. }
  168237. }
  168238. return rc;
  168239. }
  168240. static int statEof(sqlite3_vtab_cursor *pCursor){
  168241. StatCursor *pCsr = (StatCursor *)pCursor;
  168242. return pCsr->isEof;
  168243. }
  168244. static int statFilter(
  168245. sqlite3_vtab_cursor *pCursor,
  168246. int idxNum, const char *idxStr,
  168247. int argc, sqlite3_value **argv
  168248. ){
  168249. StatCursor *pCsr = (StatCursor *)pCursor;
  168250. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  168251. char *zSql;
  168252. int rc = SQLITE_OK;
  168253. char *zMaster;
  168254. if( idxNum==1 ){
  168255. const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
  168256. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  168257. if( pCsr->iDb<0 ){
  168258. sqlite3_free(pCursor->pVtab->zErrMsg);
  168259. pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
  168260. return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
  168261. }
  168262. }else{
  168263. pCsr->iDb = pTab->iDb;
  168264. }
  168265. statResetCsr(pCsr);
  168266. sqlite3_finalize(pCsr->pStmt);
  168267. pCsr->pStmt = 0;
  168268. zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
  168269. zSql = sqlite3_mprintf(
  168270. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  168271. " UNION ALL "
  168272. "SELECT name, rootpage, type"
  168273. " FROM \"%w\".%s WHERE rootpage!=0"
  168274. " ORDER BY name", pTab->db->aDb[pCsr->iDb].zDbSName, zMaster);
  168275. if( zSql==0 ){
  168276. return SQLITE_NOMEM_BKPT;
  168277. }else{
  168278. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  168279. sqlite3_free(zSql);
  168280. }
  168281. if( rc==SQLITE_OK ){
  168282. rc = statNext(pCursor);
  168283. }
  168284. return rc;
  168285. }
  168286. static int statColumn(
  168287. sqlite3_vtab_cursor *pCursor,
  168288. sqlite3_context *ctx,
  168289. int i
  168290. ){
  168291. StatCursor *pCsr = (StatCursor *)pCursor;
  168292. switch( i ){
  168293. case 0: /* name */
  168294. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  168295. break;
  168296. case 1: /* path */
  168297. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  168298. break;
  168299. case 2: /* pageno */
  168300. sqlite3_result_int64(ctx, pCsr->iPageno);
  168301. break;
  168302. case 3: /* pagetype */
  168303. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  168304. break;
  168305. case 4: /* ncell */
  168306. sqlite3_result_int(ctx, pCsr->nCell);
  168307. break;
  168308. case 5: /* payload */
  168309. sqlite3_result_int(ctx, pCsr->nPayload);
  168310. break;
  168311. case 6: /* unused */
  168312. sqlite3_result_int(ctx, pCsr->nUnused);
  168313. break;
  168314. case 7: /* mx_payload */
  168315. sqlite3_result_int(ctx, pCsr->nMxPayload);
  168316. break;
  168317. case 8: /* pgoffset */
  168318. sqlite3_result_int64(ctx, pCsr->iOffset);
  168319. break;
  168320. case 9: /* pgsize */
  168321. sqlite3_result_int(ctx, pCsr->szPage);
  168322. break;
  168323. default: { /* schema */
  168324. sqlite3 *db = sqlite3_context_db_handle(ctx);
  168325. int iDb = pCsr->iDb;
  168326. sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
  168327. break;
  168328. }
  168329. }
  168330. return SQLITE_OK;
  168331. }
  168332. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  168333. StatCursor *pCsr = (StatCursor *)pCursor;
  168334. *pRowid = pCsr->iPageno;
  168335. return SQLITE_OK;
  168336. }
  168337. /*
  168338. ** Invoke this routine to register the "dbstat" virtual table module
  168339. */
  168340. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  168341. static sqlite3_module dbstat_module = {
  168342. 0, /* iVersion */
  168343. statConnect, /* xCreate */
  168344. statConnect, /* xConnect */
  168345. statBestIndex, /* xBestIndex */
  168346. statDisconnect, /* xDisconnect */
  168347. statDisconnect, /* xDestroy */
  168348. statOpen, /* xOpen - open a cursor */
  168349. statClose, /* xClose - close a cursor */
  168350. statFilter, /* xFilter - configure scan constraints */
  168351. statNext, /* xNext - advance a cursor */
  168352. statEof, /* xEof - check for end of scan */
  168353. statColumn, /* xColumn - read data */
  168354. statRowid, /* xRowid - read data */
  168355. 0, /* xUpdate */
  168356. 0, /* xBegin */
  168357. 0, /* xSync */
  168358. 0, /* xCommit */
  168359. 0, /* xRollback */
  168360. 0, /* xFindMethod */
  168361. 0, /* xRename */
  168362. 0, /* xSavepoint */
  168363. 0, /* xRelease */
  168364. 0, /* xRollbackTo */
  168365. };
  168366. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  168367. }
  168368. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  168369. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  168370. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  168371. /************** End of dbstat.c **********************************************/
  168372. /************** Begin file dbpage.c ******************************************/
  168373. /*
  168374. ** 2017-10-11
  168375. **
  168376. ** The author disclaims copyright to this source code. In place of
  168377. ** a legal notice, here is a blessing:
  168378. **
  168379. ** May you do good and not evil.
  168380. ** May you find forgiveness for yourself and forgive others.
  168381. ** May you share freely, never taking more than you give.
  168382. **
  168383. ******************************************************************************
  168384. **
  168385. ** This file contains an implementation of the "sqlite_dbpage" virtual table.
  168386. **
  168387. ** The sqlite_dbpage virtual table is used to read or write whole raw
  168388. ** pages of the database file. The pager interface is used so that
  168389. ** uncommitted changes and changes recorded in the WAL file are correctly
  168390. ** retrieved.
  168391. **
  168392. ** Usage example:
  168393. **
  168394. ** SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
  168395. **
  168396. ** This is an eponymous virtual table so it does not need to be created before
  168397. ** use. The optional argument to the sqlite_dbpage() table name is the
  168398. ** schema for the database file that is to be read. The default schema is
  168399. ** "main".
  168400. **
  168401. ** The data field of sqlite_dbpage table can be updated. The new
  168402. ** value must be a BLOB which is the correct page size, otherwise the
  168403. ** update fails. Rows may not be deleted or inserted.
  168404. */
  168405. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  168406. #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
  168407. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  168408. typedef struct DbpageTable DbpageTable;
  168409. typedef struct DbpageCursor DbpageCursor;
  168410. struct DbpageCursor {
  168411. sqlite3_vtab_cursor base; /* Base class. Must be first */
  168412. int pgno; /* Current page number */
  168413. int mxPgno; /* Last page to visit on this scan */
  168414. Pager *pPager; /* Pager being read/written */
  168415. DbPage *pPage1; /* Page 1 of the database */
  168416. int iDb; /* Index of database to analyze */
  168417. int szPage; /* Size of each page in bytes */
  168418. };
  168419. struct DbpageTable {
  168420. sqlite3_vtab base; /* Base class. Must be first */
  168421. sqlite3 *db; /* The database */
  168422. };
  168423. /* Columns */
  168424. #define DBPAGE_COLUMN_PGNO 0
  168425. #define DBPAGE_COLUMN_DATA 1
  168426. #define DBPAGE_COLUMN_SCHEMA 2
  168427. /*
  168428. ** Connect to or create a dbpagevfs virtual table.
  168429. */
  168430. static int dbpageConnect(
  168431. sqlite3 *db,
  168432. void *pAux,
  168433. int argc, const char *const*argv,
  168434. sqlite3_vtab **ppVtab,
  168435. char **pzErr
  168436. ){
  168437. DbpageTable *pTab = 0;
  168438. int rc = SQLITE_OK;
  168439. rc = sqlite3_declare_vtab(db,
  168440. "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
  168441. if( rc==SQLITE_OK ){
  168442. pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
  168443. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  168444. }
  168445. assert( rc==SQLITE_OK || pTab==0 );
  168446. if( rc==SQLITE_OK ){
  168447. memset(pTab, 0, sizeof(DbpageTable));
  168448. pTab->db = db;
  168449. }
  168450. *ppVtab = (sqlite3_vtab*)pTab;
  168451. return rc;
  168452. }
  168453. /*
  168454. ** Disconnect from or destroy a dbpagevfs virtual table.
  168455. */
  168456. static int dbpageDisconnect(sqlite3_vtab *pVtab){
  168457. sqlite3_free(pVtab);
  168458. return SQLITE_OK;
  168459. }
  168460. /*
  168461. ** idxNum:
  168462. **
  168463. ** 0 schema=main, full table scan
  168464. ** 1 schema=main, pgno=?1
  168465. ** 2 schema=?1, full table scan
  168466. ** 3 schema=?1, pgno=?2
  168467. */
  168468. static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  168469. int i;
  168470. int iPlan = 0;
  168471. /* If there is a schema= constraint, it must be honored. Report a
  168472. ** ridiculously large estimated cost if the schema= constraint is
  168473. ** unavailable
  168474. */
  168475. for(i=0; i<pIdxInfo->nConstraint; i++){
  168476. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  168477. if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;
  168478. if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  168479. if( !p->usable ){
  168480. /* No solution. Use the default SQLITE_BIG_DBL cost */
  168481. pIdxInfo->estimatedRows = 0x7fffffff;
  168482. return SQLITE_OK;
  168483. }
  168484. iPlan = 2;
  168485. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  168486. pIdxInfo->aConstraintUsage[i].omit = 1;
  168487. break;
  168488. }
  168489. /* If we reach this point, it means that either there is no schema=
  168490. ** constraint (in which case we use the "main" schema) or else the
  168491. ** schema constraint was accepted. Lower the estimated cost accordingly
  168492. */
  168493. pIdxInfo->estimatedCost = 1.0e6;
  168494. /* Check for constraints against pgno */
  168495. for(i=0; i<pIdxInfo->nConstraint; i++){
  168496. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  168497. if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  168498. pIdxInfo->estimatedRows = 1;
  168499. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  168500. pIdxInfo->estimatedCost = 1.0;
  168501. pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;
  168502. pIdxInfo->aConstraintUsage[i].omit = 1;
  168503. iPlan |= 1;
  168504. break;
  168505. }
  168506. }
  168507. pIdxInfo->idxNum = iPlan;
  168508. if( pIdxInfo->nOrderBy>=1
  168509. && pIdxInfo->aOrderBy[0].iColumn<=0
  168510. && pIdxInfo->aOrderBy[0].desc==0
  168511. ){
  168512. pIdxInfo->orderByConsumed = 1;
  168513. }
  168514. return SQLITE_OK;
  168515. }
  168516. /*
  168517. ** Open a new dbpagevfs cursor.
  168518. */
  168519. static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  168520. DbpageCursor *pCsr;
  168521. pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
  168522. if( pCsr==0 ){
  168523. return SQLITE_NOMEM_BKPT;
  168524. }else{
  168525. memset(pCsr, 0, sizeof(DbpageCursor));
  168526. pCsr->base.pVtab = pVTab;
  168527. pCsr->pgno = -1;
  168528. }
  168529. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  168530. return SQLITE_OK;
  168531. }
  168532. /*
  168533. ** Close a dbpagevfs cursor.
  168534. */
  168535. static int dbpageClose(sqlite3_vtab_cursor *pCursor){
  168536. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  168537. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  168538. sqlite3_free(pCsr);
  168539. return SQLITE_OK;
  168540. }
  168541. /*
  168542. ** Move a dbpagevfs cursor to the next entry in the file.
  168543. */
  168544. static int dbpageNext(sqlite3_vtab_cursor *pCursor){
  168545. int rc = SQLITE_OK;
  168546. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  168547. pCsr->pgno++;
  168548. return rc;
  168549. }
  168550. static int dbpageEof(sqlite3_vtab_cursor *pCursor){
  168551. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  168552. return pCsr->pgno > pCsr->mxPgno;
  168553. }
  168554. /*
  168555. ** idxNum:
  168556. **
  168557. ** 0 schema=main, full table scan
  168558. ** 1 schema=main, pgno=?1
  168559. ** 2 schema=?1, full table scan
  168560. ** 3 schema=?1, pgno=?2
  168561. **
  168562. ** idxStr is not used
  168563. */
  168564. static int dbpageFilter(
  168565. sqlite3_vtab_cursor *pCursor,
  168566. int idxNum, const char *idxStr,
  168567. int argc, sqlite3_value **argv
  168568. ){
  168569. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  168570. DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
  168571. int rc;
  168572. sqlite3 *db = pTab->db;
  168573. Btree *pBt;
  168574. /* Default setting is no rows of result */
  168575. pCsr->pgno = 1;
  168576. pCsr->mxPgno = 0;
  168577. if( idxNum & 2 ){
  168578. const char *zSchema;
  168579. assert( argc>=1 );
  168580. zSchema = (const char*)sqlite3_value_text(argv[0]);
  168581. pCsr->iDb = sqlite3FindDbName(db, zSchema);
  168582. if( pCsr->iDb<0 ) return SQLITE_OK;
  168583. }else{
  168584. pCsr->iDb = 0;
  168585. }
  168586. pBt = db->aDb[pCsr->iDb].pBt;
  168587. if( pBt==0 ) return SQLITE_OK;
  168588. pCsr->pPager = sqlite3BtreePager(pBt);
  168589. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  168590. pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
  168591. if( idxNum & 1 ){
  168592. assert( argc>(idxNum>>1) );
  168593. pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);
  168594. if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){
  168595. pCsr->pgno = 1;
  168596. pCsr->mxPgno = 0;
  168597. }else{
  168598. pCsr->mxPgno = pCsr->pgno;
  168599. }
  168600. }else{
  168601. assert( pCsr->pgno==1 );
  168602. }
  168603. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  168604. rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);
  168605. return rc;
  168606. }
  168607. static int dbpageColumn(
  168608. sqlite3_vtab_cursor *pCursor,
  168609. sqlite3_context *ctx,
  168610. int i
  168611. ){
  168612. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  168613. int rc = SQLITE_OK;
  168614. switch( i ){
  168615. case 0: { /* pgno */
  168616. sqlite3_result_int(ctx, pCsr->pgno);
  168617. break;
  168618. }
  168619. case 1: { /* data */
  168620. DbPage *pDbPage = 0;
  168621. rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
  168622. if( rc==SQLITE_OK ){
  168623. sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,
  168624. SQLITE_TRANSIENT);
  168625. }
  168626. sqlite3PagerUnref(pDbPage);
  168627. break;
  168628. }
  168629. default: { /* schema */
  168630. sqlite3 *db = sqlite3_context_db_handle(ctx);
  168631. sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);
  168632. break;
  168633. }
  168634. }
  168635. return SQLITE_OK;
  168636. }
  168637. static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  168638. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  168639. *pRowid = pCsr->pgno;
  168640. return SQLITE_OK;
  168641. }
  168642. static int dbpageUpdate(
  168643. sqlite3_vtab *pVtab,
  168644. int argc,
  168645. sqlite3_value **argv,
  168646. sqlite_int64 *pRowid
  168647. ){
  168648. DbpageTable *pTab = (DbpageTable *)pVtab;
  168649. Pgno pgno;
  168650. DbPage *pDbPage = 0;
  168651. int rc = SQLITE_OK;
  168652. char *zErr = 0;
  168653. const char *zSchema;
  168654. int iDb;
  168655. Btree *pBt;
  168656. Pager *pPager;
  168657. int szPage;
  168658. if( argc==1 ){
  168659. zErr = "cannot delete";
  168660. goto update_fail;
  168661. }
  168662. pgno = sqlite3_value_int(argv[0]);
  168663. if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){
  168664. zErr = "cannot insert";
  168665. goto update_fail;
  168666. }
  168667. zSchema = (const char*)sqlite3_value_text(argv[4]);
  168668. iDb = zSchema ? sqlite3FindDbName(pTab->db, zSchema) : -1;
  168669. if( iDb<0 ){
  168670. zErr = "no such schema";
  168671. goto update_fail;
  168672. }
  168673. pBt = pTab->db->aDb[iDb].pBt;
  168674. if( pgno<1 || pBt==0 || pgno>(int)sqlite3BtreeLastPage(pBt) ){
  168675. zErr = "bad page number";
  168676. goto update_fail;
  168677. }
  168678. szPage = sqlite3BtreeGetPageSize(pBt);
  168679. if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
  168680. || sqlite3_value_bytes(argv[3])!=szPage
  168681. ){
  168682. zErr = "bad page value";
  168683. goto update_fail;
  168684. }
  168685. pPager = sqlite3BtreePager(pBt);
  168686. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
  168687. if( rc==SQLITE_OK ){
  168688. rc = sqlite3PagerWrite(pDbPage);
  168689. if( rc==SQLITE_OK ){
  168690. memcpy(sqlite3PagerGetData(pDbPage),
  168691. sqlite3_value_blob(argv[3]),
  168692. szPage);
  168693. }
  168694. }
  168695. sqlite3PagerUnref(pDbPage);
  168696. return rc;
  168697. update_fail:
  168698. sqlite3_free(pVtab->zErrMsg);
  168699. pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
  168700. return SQLITE_ERROR;
  168701. }
  168702. /* Since we do not know in advance which database files will be
  168703. ** written by the sqlite_dbpage virtual table, start a write transaction
  168704. ** on them all.
  168705. */
  168706. static int dbpageBegin(sqlite3_vtab *pVtab){
  168707. DbpageTable *pTab = (DbpageTable *)pVtab;
  168708. sqlite3 *db = pTab->db;
  168709. int i;
  168710. for(i=0; i<db->nDb; i++){
  168711. Btree *pBt = db->aDb[i].pBt;
  168712. if( pBt ) sqlite3BtreeBeginTrans(pBt, 1);
  168713. }
  168714. return SQLITE_OK;
  168715. }
  168716. /*
  168717. ** Invoke this routine to register the "dbpage" virtual table module
  168718. */
  168719. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
  168720. static sqlite3_module dbpage_module = {
  168721. 0, /* iVersion */
  168722. dbpageConnect, /* xCreate */
  168723. dbpageConnect, /* xConnect */
  168724. dbpageBestIndex, /* xBestIndex */
  168725. dbpageDisconnect, /* xDisconnect */
  168726. dbpageDisconnect, /* xDestroy */
  168727. dbpageOpen, /* xOpen - open a cursor */
  168728. dbpageClose, /* xClose - close a cursor */
  168729. dbpageFilter, /* xFilter - configure scan constraints */
  168730. dbpageNext, /* xNext - advance a cursor */
  168731. dbpageEof, /* xEof - check for end of scan */
  168732. dbpageColumn, /* xColumn - read data */
  168733. dbpageRowid, /* xRowid - read data */
  168734. dbpageUpdate, /* xUpdate */
  168735. dbpageBegin, /* xBegin */
  168736. 0, /* xSync */
  168737. 0, /* xCommit */
  168738. 0, /* xRollback */
  168739. 0, /* xFindMethod */
  168740. 0, /* xRename */
  168741. 0, /* xSavepoint */
  168742. 0, /* xRelease */
  168743. 0, /* xRollbackTo */
  168744. };
  168745. return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
  168746. }
  168747. #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
  168748. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
  168749. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  168750. /************** End of dbpage.c **********************************************/
  168751. /************** Begin file sqlite3session.c **********************************/
  168752. #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  168753. /* #include "sqlite3session.h" */
  168754. /* #include <assert.h> */
  168755. /* #include <string.h> */
  168756. #ifndef SQLITE_AMALGAMATION
  168757. /* # include "sqliteInt.h" */
  168758. /* # include "vdbeInt.h" */
  168759. #endif
  168760. typedef struct SessionTable SessionTable;
  168761. typedef struct SessionChange SessionChange;
  168762. typedef struct SessionBuffer SessionBuffer;
  168763. typedef struct SessionInput SessionInput;
  168764. /*
  168765. ** Minimum chunk size used by streaming versions of functions.
  168766. */
  168767. #ifndef SESSIONS_STRM_CHUNK_SIZE
  168768. # ifdef SQLITE_TEST
  168769. # define SESSIONS_STRM_CHUNK_SIZE 64
  168770. # else
  168771. # define SESSIONS_STRM_CHUNK_SIZE 1024
  168772. # endif
  168773. #endif
  168774. typedef struct SessionHook SessionHook;
  168775. struct SessionHook {
  168776. void *pCtx;
  168777. int (*xOld)(void*,int,sqlite3_value**);
  168778. int (*xNew)(void*,int,sqlite3_value**);
  168779. int (*xCount)(void*);
  168780. int (*xDepth)(void*);
  168781. };
  168782. /*
  168783. ** Session handle structure.
  168784. */
  168785. struct sqlite3_session {
  168786. sqlite3 *db; /* Database handle session is attached to */
  168787. char *zDb; /* Name of database session is attached to */
  168788. int bEnable; /* True if currently recording */
  168789. int bIndirect; /* True if all changes are indirect */
  168790. int bAutoAttach; /* True to auto-attach tables */
  168791. int rc; /* Non-zero if an error has occurred */
  168792. void *pFilterCtx; /* First argument to pass to xTableFilter */
  168793. int (*xTableFilter)(void *pCtx, const char *zTab);
  168794. sqlite3_value *pZeroBlob; /* Value containing X'' */
  168795. sqlite3_session *pNext; /* Next session object on same db. */
  168796. SessionTable *pTable; /* List of attached tables */
  168797. SessionHook hook; /* APIs to grab new and old data with */
  168798. };
  168799. /*
  168800. ** Instances of this structure are used to build strings or binary records.
  168801. */
  168802. struct SessionBuffer {
  168803. u8 *aBuf; /* Pointer to changeset buffer */
  168804. int nBuf; /* Size of buffer aBuf */
  168805. int nAlloc; /* Size of allocation containing aBuf */
  168806. };
  168807. /*
  168808. ** An object of this type is used internally as an abstraction for
  168809. ** input data. Input data may be supplied either as a single large buffer
  168810. ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
  168811. ** sqlite3changeset_start_strm()).
  168812. */
  168813. struct SessionInput {
  168814. int bNoDiscard; /* If true, do not discard in InputBuffer() */
  168815. int iCurrent; /* Offset in aData[] of current change */
  168816. int iNext; /* Offset in aData[] of next change */
  168817. u8 *aData; /* Pointer to buffer containing changeset */
  168818. int nData; /* Number of bytes in aData */
  168819. SessionBuffer buf; /* Current read buffer */
  168820. int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
  168821. void *pIn; /* First argument to xInput */
  168822. int bEof; /* Set to true after xInput finished */
  168823. };
  168824. /*
  168825. ** Structure for changeset iterators.
  168826. */
  168827. struct sqlite3_changeset_iter {
  168828. SessionInput in; /* Input buffer or stream */
  168829. SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
  168830. int bPatchset; /* True if this is a patchset */
  168831. int rc; /* Iterator error code */
  168832. sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
  168833. char *zTab; /* Current table */
  168834. int nCol; /* Number of columns in zTab */
  168835. int op; /* Current operation */
  168836. int bIndirect; /* True if current change was indirect */
  168837. u8 *abPK; /* Primary key array */
  168838. sqlite3_value **apValue; /* old.* and new.* values */
  168839. };
  168840. /*
  168841. ** Each session object maintains a set of the following structures, one
  168842. ** for each table the session object is monitoring. The structures are
  168843. ** stored in a linked list starting at sqlite3_session.pTable.
  168844. **
  168845. ** The keys of the SessionTable.aChange[] hash table are all rows that have
  168846. ** been modified in any way since the session object was attached to the
  168847. ** table.
  168848. **
  168849. ** The data associated with each hash-table entry is a structure containing
  168850. ** a subset of the initial values that the modified row contained at the
  168851. ** start of the session. Or no initial values if the row was inserted.
  168852. */
  168853. struct SessionTable {
  168854. SessionTable *pNext;
  168855. char *zName; /* Local name of table */
  168856. int nCol; /* Number of columns in table zName */
  168857. int bStat1; /* True if this is sqlite_stat1 */
  168858. const char **azCol; /* Column names */
  168859. u8 *abPK; /* Array of primary key flags */
  168860. int nEntry; /* Total number of entries in hash table */
  168861. int nChange; /* Size of apChange[] array */
  168862. SessionChange **apChange; /* Hash table buckets */
  168863. };
  168864. /*
  168865. ** RECORD FORMAT:
  168866. **
  168867. ** The following record format is similar to (but not compatible with) that
  168868. ** used in SQLite database files. This format is used as part of the
  168869. ** change-set binary format, and so must be architecture independent.
  168870. **
  168871. ** Unlike the SQLite database record format, each field is self-contained -
  168872. ** there is no separation of header and data. Each field begins with a
  168873. ** single byte describing its type, as follows:
  168874. **
  168875. ** 0x00: Undefined value.
  168876. ** 0x01: Integer value.
  168877. ** 0x02: Real value.
  168878. ** 0x03: Text value.
  168879. ** 0x04: Blob value.
  168880. ** 0x05: SQL NULL value.
  168881. **
  168882. ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
  168883. ** and so on in sqlite3.h. For undefined and NULL values, the field consists
  168884. ** only of the single type byte. For other types of values, the type byte
  168885. ** is followed by:
  168886. **
  168887. ** Text values:
  168888. ** A varint containing the number of bytes in the value (encoded using
  168889. ** UTF-8). Followed by a buffer containing the UTF-8 representation
  168890. ** of the text value. There is no nul terminator.
  168891. **
  168892. ** Blob values:
  168893. ** A varint containing the number of bytes in the value, followed by
  168894. ** a buffer containing the value itself.
  168895. **
  168896. ** Integer values:
  168897. ** An 8-byte big-endian integer value.
  168898. **
  168899. ** Real values:
  168900. ** An 8-byte big-endian IEEE 754-2008 real value.
  168901. **
  168902. ** Varint values are encoded in the same way as varints in the SQLite
  168903. ** record format.
  168904. **
  168905. ** CHANGESET FORMAT:
  168906. **
  168907. ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
  168908. ** one or more tables. Operations on a single table are grouped together,
  168909. ** but may occur in any order (i.e. deletes, updates and inserts are all
  168910. ** mixed together).
  168911. **
  168912. ** Each group of changes begins with a table header:
  168913. **
  168914. ** 1 byte: Constant 0x54 (capital 'T')
  168915. ** Varint: Number of columns in the table.
  168916. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  168917. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  168918. **
  168919. ** Followed by one or more changes to the table.
  168920. **
  168921. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  168922. ** 1 byte: The "indirect-change" flag.
  168923. ** old.* record: (delete and update only)
  168924. ** new.* record: (insert and update only)
  168925. **
  168926. ** The "old.*" and "new.*" records, if present, are N field records in the
  168927. ** format described above under "RECORD FORMAT", where N is the number of
  168928. ** columns in the table. The i'th field of each record is associated with
  168929. ** the i'th column of the table, counting from left to right in the order
  168930. ** in which columns were declared in the CREATE TABLE statement.
  168931. **
  168932. ** The new.* record that is part of each INSERT change contains the values
  168933. ** that make up the new row. Similarly, the old.* record that is part of each
  168934. ** DELETE change contains the values that made up the row that was deleted
  168935. ** from the database. In the changeset format, the records that are part
  168936. ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
  168937. ** fields.
  168938. **
  168939. ** Within the old.* record associated with an UPDATE change, all fields
  168940. ** associated with table columns that are not PRIMARY KEY columns and are
  168941. ** not modified by the UPDATE change are set to "undefined". Other fields
  168942. ** are set to the values that made up the row before the UPDATE that the
  168943. ** change records took place. Within the new.* record, fields associated
  168944. ** with table columns modified by the UPDATE change contain the new
  168945. ** values. Fields associated with table columns that are not modified
  168946. ** are set to "undefined".
  168947. **
  168948. ** PATCHSET FORMAT:
  168949. **
  168950. ** A patchset is also a collection of changes. It is similar to a changeset,
  168951. ** but leaves undefined those fields that are not useful if no conflict
  168952. ** resolution is required when applying the changeset.
  168953. **
  168954. ** Each group of changes begins with a table header:
  168955. **
  168956. ** 1 byte: Constant 0x50 (capital 'P')
  168957. ** Varint: Number of columns in the table.
  168958. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  168959. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  168960. **
  168961. ** Followed by one or more changes to the table.
  168962. **
  168963. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  168964. ** 1 byte: The "indirect-change" flag.
  168965. ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
  168966. ** full record for INSERT).
  168967. **
  168968. ** As in the changeset format, each field of the single record that is part
  168969. ** of a patchset change is associated with the correspondingly positioned
  168970. ** table column, counting from left to right within the CREATE TABLE
  168971. ** statement.
  168972. **
  168973. ** For a DELETE change, all fields within the record except those associated
  168974. ** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
  168975. ** values identifying the row to delete.
  168976. **
  168977. ** For an UPDATE change, all fields except those associated with PRIMARY KEY
  168978. ** columns and columns that are modified by the UPDATE are set to "undefined".
  168979. ** PRIMARY KEY fields contain the values identifying the table row to update,
  168980. ** and fields associated with modified columns contain the new column values.
  168981. **
  168982. ** The records associated with INSERT changes are in the same format as for
  168983. ** changesets. It is not possible for a record associated with an INSERT
  168984. ** change to contain a field set to "undefined".
  168985. */
  168986. /*
  168987. ** For each row modified during a session, there exists a single instance of
  168988. ** this structure stored in a SessionTable.aChange[] hash table.
  168989. */
  168990. struct SessionChange {
  168991. int op; /* One of UPDATE, DELETE, INSERT */
  168992. int bIndirect; /* True if this change is "indirect" */
  168993. int nRecord; /* Number of bytes in buffer aRecord[] */
  168994. u8 *aRecord; /* Buffer containing old.* record */
  168995. SessionChange *pNext; /* For hash-table collisions */
  168996. };
  168997. /*
  168998. ** Write a varint with value iVal into the buffer at aBuf. Return the
  168999. ** number of bytes written.
  169000. */
  169001. static int sessionVarintPut(u8 *aBuf, int iVal){
  169002. return putVarint32(aBuf, iVal);
  169003. }
  169004. /*
  169005. ** Return the number of bytes required to store value iVal as a varint.
  169006. */
  169007. static int sessionVarintLen(int iVal){
  169008. return sqlite3VarintLen(iVal);
  169009. }
  169010. /*
  169011. ** Read a varint value from aBuf[] into *piVal. Return the number of
  169012. ** bytes read.
  169013. */
  169014. static int sessionVarintGet(u8 *aBuf, int *piVal){
  169015. return getVarint32(aBuf, *piVal);
  169016. }
  169017. /* Load an unaligned and unsigned 32-bit integer */
  169018. #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  169019. /*
  169020. ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
  169021. ** the value read.
  169022. */
  169023. static sqlite3_int64 sessionGetI64(u8 *aRec){
  169024. u64 x = SESSION_UINT32(aRec);
  169025. u32 y = SESSION_UINT32(aRec+4);
  169026. x = (x<<32) + y;
  169027. return (sqlite3_int64)x;
  169028. }
  169029. /*
  169030. ** Write a 64-bit big-endian integer value to the buffer aBuf[].
  169031. */
  169032. static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
  169033. aBuf[0] = (i>>56) & 0xFF;
  169034. aBuf[1] = (i>>48) & 0xFF;
  169035. aBuf[2] = (i>>40) & 0xFF;
  169036. aBuf[3] = (i>>32) & 0xFF;
  169037. aBuf[4] = (i>>24) & 0xFF;
  169038. aBuf[5] = (i>>16) & 0xFF;
  169039. aBuf[6] = (i>> 8) & 0xFF;
  169040. aBuf[7] = (i>> 0) & 0xFF;
  169041. }
  169042. /*
  169043. ** This function is used to serialize the contents of value pValue (see
  169044. ** comment titled "RECORD FORMAT" above).
  169045. **
  169046. ** If it is non-NULL, the serialized form of the value is written to
  169047. ** buffer aBuf. *pnWrite is set to the number of bytes written before
  169048. ** returning. Or, if aBuf is NULL, the only thing this function does is
  169049. ** set *pnWrite.
  169050. **
  169051. ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
  169052. ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
  169053. ** SQLITE_NOMEM is returned.
  169054. */
  169055. static int sessionSerializeValue(
  169056. u8 *aBuf, /* If non-NULL, write serialized value here */
  169057. sqlite3_value *pValue, /* Value to serialize */
  169058. int *pnWrite /* IN/OUT: Increment by bytes written */
  169059. ){
  169060. int nByte; /* Size of serialized value in bytes */
  169061. if( pValue ){
  169062. int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
  169063. eType = sqlite3_value_type(pValue);
  169064. if( aBuf ) aBuf[0] = eType;
  169065. switch( eType ){
  169066. case SQLITE_NULL:
  169067. nByte = 1;
  169068. break;
  169069. case SQLITE_INTEGER:
  169070. case SQLITE_FLOAT:
  169071. if( aBuf ){
  169072. /* TODO: SQLite does something special to deal with mixed-endian
  169073. ** floating point values (e.g. ARM7). This code probably should
  169074. ** too. */
  169075. u64 i;
  169076. if( eType==SQLITE_INTEGER ){
  169077. i = (u64)sqlite3_value_int64(pValue);
  169078. }else{
  169079. double r;
  169080. assert( sizeof(double)==8 && sizeof(u64)==8 );
  169081. r = sqlite3_value_double(pValue);
  169082. memcpy(&i, &r, 8);
  169083. }
  169084. sessionPutI64(&aBuf[1], i);
  169085. }
  169086. nByte = 9;
  169087. break;
  169088. default: {
  169089. u8 *z;
  169090. int n;
  169091. int nVarint;
  169092. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  169093. if( eType==SQLITE_TEXT ){
  169094. z = (u8 *)sqlite3_value_text(pValue);
  169095. }else{
  169096. z = (u8 *)sqlite3_value_blob(pValue);
  169097. }
  169098. n = sqlite3_value_bytes(pValue);
  169099. if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  169100. nVarint = sessionVarintLen(n);
  169101. if( aBuf ){
  169102. sessionVarintPut(&aBuf[1], n);
  169103. if( n ) memcpy(&aBuf[nVarint + 1], z, n);
  169104. }
  169105. nByte = 1 + nVarint + n;
  169106. break;
  169107. }
  169108. }
  169109. }else{
  169110. nByte = 1;
  169111. if( aBuf ) aBuf[0] = '\0';
  169112. }
  169113. if( pnWrite ) *pnWrite += nByte;
  169114. return SQLITE_OK;
  169115. }
  169116. /*
  169117. ** This macro is used to calculate hash key values for data structures. In
  169118. ** order to use this macro, the entire data structure must be represented
  169119. ** as a series of unsigned integers. In order to calculate a hash-key value
  169120. ** for a data structure represented as three such integers, the macro may
  169121. ** then be used as follows:
  169122. **
  169123. ** int hash_key_value;
  169124. ** hash_key_value = HASH_APPEND(0, <value 1>);
  169125. ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
  169126. ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
  169127. **
  169128. ** In practice, the data structures this macro is used for are the primary
  169129. ** key values of modified rows.
  169130. */
  169131. #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
  169132. /*
  169133. ** Append the hash of the 64-bit integer passed as the second argument to the
  169134. ** hash-key value passed as the first. Return the new hash-key value.
  169135. */
  169136. static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
  169137. h = HASH_APPEND(h, i & 0xFFFFFFFF);
  169138. return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
  169139. }
  169140. /*
  169141. ** Append the hash of the blob passed via the second and third arguments to
  169142. ** the hash-key value passed as the first. Return the new hash-key value.
  169143. */
  169144. static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
  169145. int i;
  169146. for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
  169147. return h;
  169148. }
  169149. /*
  169150. ** Append the hash of the data type passed as the second argument to the
  169151. ** hash-key value passed as the first. Return the new hash-key value.
  169152. */
  169153. static unsigned int sessionHashAppendType(unsigned int h, int eType){
  169154. return HASH_APPEND(h, eType);
  169155. }
  169156. /*
  169157. ** This function may only be called from within a pre-update callback.
  169158. ** It calculates a hash based on the primary key values of the old.* or
  169159. ** new.* row currently available and, assuming no error occurs, writes it to
  169160. ** *piHash before returning. If the primary key contains one or more NULL
  169161. ** values, *pbNullPK is set to true before returning.
  169162. **
  169163. ** If an error occurs, an SQLite error code is returned and the final values
  169164. ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
  169165. ** and the output variables are set as described above.
  169166. */
  169167. static int sessionPreupdateHash(
  169168. sqlite3_session *pSession, /* Session object that owns pTab */
  169169. SessionTable *pTab, /* Session table handle */
  169170. int bNew, /* True to hash the new.* PK */
  169171. int *piHash, /* OUT: Hash value */
  169172. int *pbNullPK /* OUT: True if there are NULL values in PK */
  169173. ){
  169174. unsigned int h = 0; /* Hash value to return */
  169175. int i; /* Used to iterate through columns */
  169176. assert( *pbNullPK==0 );
  169177. assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
  169178. for(i=0; i<pTab->nCol; i++){
  169179. if( pTab->abPK[i] ){
  169180. int rc;
  169181. int eType;
  169182. sqlite3_value *pVal;
  169183. if( bNew ){
  169184. rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
  169185. }else{
  169186. rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
  169187. }
  169188. if( rc!=SQLITE_OK ) return rc;
  169189. eType = sqlite3_value_type(pVal);
  169190. h = sessionHashAppendType(h, eType);
  169191. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  169192. i64 iVal;
  169193. if( eType==SQLITE_INTEGER ){
  169194. iVal = sqlite3_value_int64(pVal);
  169195. }else{
  169196. double rVal = sqlite3_value_double(pVal);
  169197. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  169198. memcpy(&iVal, &rVal, 8);
  169199. }
  169200. h = sessionHashAppendI64(h, iVal);
  169201. }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  169202. const u8 *z;
  169203. int n;
  169204. if( eType==SQLITE_TEXT ){
  169205. z = (const u8 *)sqlite3_value_text(pVal);
  169206. }else{
  169207. z = (const u8 *)sqlite3_value_blob(pVal);
  169208. }
  169209. n = sqlite3_value_bytes(pVal);
  169210. if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  169211. h = sessionHashAppendBlob(h, n, z);
  169212. }else{
  169213. assert( eType==SQLITE_NULL );
  169214. assert( pTab->bStat1==0 || i!=1 );
  169215. *pbNullPK = 1;
  169216. }
  169217. }
  169218. }
  169219. *piHash = (h % pTab->nChange);
  169220. return SQLITE_OK;
  169221. }
  169222. /*
  169223. ** The buffer that the argument points to contains a serialized SQL value.
  169224. ** Return the number of bytes of space occupied by the value (including
  169225. ** the type byte).
  169226. */
  169227. static int sessionSerialLen(u8 *a){
  169228. int e = *a;
  169229. int n;
  169230. if( e==0 || e==0xFF ) return 1;
  169231. if( e==SQLITE_NULL ) return 1;
  169232. if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
  169233. return sessionVarintGet(&a[1], &n) + 1 + n;
  169234. }
  169235. /*
  169236. ** Based on the primary key values stored in change aRecord, calculate a
  169237. ** hash key. Assume the has table has nBucket buckets. The hash keys
  169238. ** calculated by this function are compatible with those calculated by
  169239. ** sessionPreupdateHash().
  169240. **
  169241. ** The bPkOnly argument is non-zero if the record at aRecord[] is from
  169242. ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
  169243. */
  169244. static unsigned int sessionChangeHash(
  169245. SessionTable *pTab, /* Table handle */
  169246. int bPkOnly, /* Record consists of PK fields only */
  169247. u8 *aRecord, /* Change record */
  169248. int nBucket /* Assume this many buckets in hash table */
  169249. ){
  169250. unsigned int h = 0; /* Value to return */
  169251. int i; /* Used to iterate through columns */
  169252. u8 *a = aRecord; /* Used to iterate through change record */
  169253. for(i=0; i<pTab->nCol; i++){
  169254. int eType = *a;
  169255. int isPK = pTab->abPK[i];
  169256. if( bPkOnly && isPK==0 ) continue;
  169257. /* It is not possible for eType to be SQLITE_NULL here. The session
  169258. ** module does not record changes for rows with NULL values stored in
  169259. ** primary key columns. */
  169260. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  169261. || eType==SQLITE_TEXT || eType==SQLITE_BLOB
  169262. || eType==SQLITE_NULL || eType==0
  169263. );
  169264. assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
  169265. if( isPK ){
  169266. a++;
  169267. h = sessionHashAppendType(h, eType);
  169268. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  169269. h = sessionHashAppendI64(h, sessionGetI64(a));
  169270. a += 8;
  169271. }else{
  169272. int n;
  169273. a += sessionVarintGet(a, &n);
  169274. h = sessionHashAppendBlob(h, n, a);
  169275. a += n;
  169276. }
  169277. }else{
  169278. a += sessionSerialLen(a);
  169279. }
  169280. }
  169281. return (h % nBucket);
  169282. }
  169283. /*
  169284. ** Arguments aLeft and aRight are pointers to change records for table pTab.
  169285. ** This function returns true if the two records apply to the same row (i.e.
  169286. ** have the same values stored in the primary key columns), or false
  169287. ** otherwise.
  169288. */
  169289. static int sessionChangeEqual(
  169290. SessionTable *pTab, /* Table used for PK definition */
  169291. int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
  169292. u8 *aLeft, /* Change record */
  169293. int bRightPkOnly, /* True if aRight[] contains PK fields only */
  169294. u8 *aRight /* Change record */
  169295. ){
  169296. u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
  169297. u8 *a2 = aRight; /* Cursor to iterate through aRight */
  169298. int iCol; /* Used to iterate through table columns */
  169299. for(iCol=0; iCol<pTab->nCol; iCol++){
  169300. if( pTab->abPK[iCol] ){
  169301. int n1 = sessionSerialLen(a1);
  169302. int n2 = sessionSerialLen(a2);
  169303. if( n1!=n2 || memcmp(a1, a2, n1) ){
  169304. return 0;
  169305. }
  169306. a1 += n1;
  169307. a2 += n2;
  169308. }else{
  169309. if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
  169310. if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
  169311. }
  169312. }
  169313. return 1;
  169314. }
  169315. /*
  169316. ** Arguments aLeft and aRight both point to buffers containing change
  169317. ** records with nCol columns. This function "merges" the two records into
  169318. ** a single records which is written to the buffer at *paOut. *paOut is
  169319. ** then set to point to one byte after the last byte written before
  169320. ** returning.
  169321. **
  169322. ** The merging of records is done as follows: For each column, if the
  169323. ** aRight record contains a value for the column, copy the value from
  169324. ** their. Otherwise, if aLeft contains a value, copy it. If neither
  169325. ** record contains a value for a given column, then neither does the
  169326. ** output record.
  169327. */
  169328. static void sessionMergeRecord(
  169329. u8 **paOut,
  169330. int nCol,
  169331. u8 *aLeft,
  169332. u8 *aRight
  169333. ){
  169334. u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
  169335. u8 *a2 = aRight; /* Cursor used to iterate through aRight */
  169336. u8 *aOut = *paOut; /* Output cursor */
  169337. int iCol; /* Used to iterate from 0 to nCol */
  169338. for(iCol=0; iCol<nCol; iCol++){
  169339. int n1 = sessionSerialLen(a1);
  169340. int n2 = sessionSerialLen(a2);
  169341. if( *a2 ){
  169342. memcpy(aOut, a2, n2);
  169343. aOut += n2;
  169344. }else{
  169345. memcpy(aOut, a1, n1);
  169346. aOut += n1;
  169347. }
  169348. a1 += n1;
  169349. a2 += n2;
  169350. }
  169351. *paOut = aOut;
  169352. }
  169353. /*
  169354. ** This is a helper function used by sessionMergeUpdate().
  169355. **
  169356. ** When this function is called, both *paOne and *paTwo point to a value
  169357. ** within a change record. Before it returns, both have been advanced so
  169358. ** as to point to the next value in the record.
  169359. **
  169360. ** If, when this function is called, *paTwo points to a valid value (i.e.
  169361. ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
  169362. ** pointer is returned and *pnVal is set to the number of bytes in the
  169363. ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
  169364. ** set to the number of bytes in the value at *paOne. If *paOne points
  169365. ** to the "no value" placeholder, *pnVal is set to 1. In other words:
  169366. **
  169367. ** if( *paTwo is valid ) return *paTwo;
  169368. ** return *paOne;
  169369. **
  169370. */
  169371. static u8 *sessionMergeValue(
  169372. u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
  169373. u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
  169374. int *pnVal /* OUT: Bytes in returned value */
  169375. ){
  169376. u8 *a1 = *paOne;
  169377. u8 *a2 = *paTwo;
  169378. u8 *pRet = 0;
  169379. int n1;
  169380. assert( a1 );
  169381. if( a2 ){
  169382. int n2 = sessionSerialLen(a2);
  169383. if( *a2 ){
  169384. *pnVal = n2;
  169385. pRet = a2;
  169386. }
  169387. *paTwo = &a2[n2];
  169388. }
  169389. n1 = sessionSerialLen(a1);
  169390. if( pRet==0 ){
  169391. *pnVal = n1;
  169392. pRet = a1;
  169393. }
  169394. *paOne = &a1[n1];
  169395. return pRet;
  169396. }
  169397. /*
  169398. ** This function is used by changeset_concat() to merge two UPDATE changes
  169399. ** on the same row.
  169400. */
  169401. static int sessionMergeUpdate(
  169402. u8 **paOut, /* IN/OUT: Pointer to output buffer */
  169403. SessionTable *pTab, /* Table change pertains to */
  169404. int bPatchset, /* True if records are patchset records */
  169405. u8 *aOldRecord1, /* old.* record for first change */
  169406. u8 *aOldRecord2, /* old.* record for second change */
  169407. u8 *aNewRecord1, /* new.* record for first change */
  169408. u8 *aNewRecord2 /* new.* record for second change */
  169409. ){
  169410. u8 *aOld1 = aOldRecord1;
  169411. u8 *aOld2 = aOldRecord2;
  169412. u8 *aNew1 = aNewRecord1;
  169413. u8 *aNew2 = aNewRecord2;
  169414. u8 *aOut = *paOut;
  169415. int i;
  169416. if( bPatchset==0 ){
  169417. int bRequired = 0;
  169418. assert( aOldRecord1 && aNewRecord1 );
  169419. /* Write the old.* vector first. */
  169420. for(i=0; i<pTab->nCol; i++){
  169421. int nOld;
  169422. u8 *aOld;
  169423. int nNew;
  169424. u8 *aNew;
  169425. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  169426. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  169427. if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
  169428. if( pTab->abPK[i]==0 ) bRequired = 1;
  169429. memcpy(aOut, aOld, nOld);
  169430. aOut += nOld;
  169431. }else{
  169432. *(aOut++) = '\0';
  169433. }
  169434. }
  169435. if( !bRequired ) return 0;
  169436. }
  169437. /* Write the new.* vector */
  169438. aOld1 = aOldRecord1;
  169439. aOld2 = aOldRecord2;
  169440. aNew1 = aNewRecord1;
  169441. aNew2 = aNewRecord2;
  169442. for(i=0; i<pTab->nCol; i++){
  169443. int nOld;
  169444. u8 *aOld;
  169445. int nNew;
  169446. u8 *aNew;
  169447. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  169448. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  169449. if( bPatchset==0
  169450. && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
  169451. ){
  169452. *(aOut++) = '\0';
  169453. }else{
  169454. memcpy(aOut, aNew, nNew);
  169455. aOut += nNew;
  169456. }
  169457. }
  169458. *paOut = aOut;
  169459. return 1;
  169460. }
  169461. /*
  169462. ** This function is only called from within a pre-update-hook callback.
  169463. ** It determines if the current pre-update-hook change affects the same row
  169464. ** as the change stored in argument pChange. If so, it returns true. Otherwise
  169465. ** if the pre-update-hook does not affect the same row as pChange, it returns
  169466. ** false.
  169467. */
  169468. static int sessionPreupdateEqual(
  169469. sqlite3_session *pSession, /* Session object that owns SessionTable */
  169470. SessionTable *pTab, /* Table associated with change */
  169471. SessionChange *pChange, /* Change to compare to */
  169472. int op /* Current pre-update operation */
  169473. ){
  169474. int iCol; /* Used to iterate through columns */
  169475. u8 *a = pChange->aRecord; /* Cursor used to scan change record */
  169476. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  169477. for(iCol=0; iCol<pTab->nCol; iCol++){
  169478. if( !pTab->abPK[iCol] ){
  169479. a += sessionSerialLen(a);
  169480. }else{
  169481. sqlite3_value *pVal; /* Value returned by preupdate_new/old */
  169482. int rc; /* Error code from preupdate_new/old */
  169483. int eType = *a++; /* Type of value from change record */
  169484. /* The following calls to preupdate_new() and preupdate_old() can not
  169485. ** fail. This is because they cache their return values, and by the
  169486. ** time control flows to here they have already been called once from
  169487. ** within sessionPreupdateHash(). The first two asserts below verify
  169488. ** this (that the method has already been called). */
  169489. if( op==SQLITE_INSERT ){
  169490. /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
  169491. rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
  169492. }else{
  169493. /* assert( db->pPreUpdate->pUnpacked ); */
  169494. rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
  169495. }
  169496. assert( rc==SQLITE_OK );
  169497. if( sqlite3_value_type(pVal)!=eType ) return 0;
  169498. /* A SessionChange object never has a NULL value in a PK column */
  169499. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  169500. || eType==SQLITE_BLOB || eType==SQLITE_TEXT
  169501. );
  169502. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  169503. i64 iVal = sessionGetI64(a);
  169504. a += 8;
  169505. if( eType==SQLITE_INTEGER ){
  169506. if( sqlite3_value_int64(pVal)!=iVal ) return 0;
  169507. }else{
  169508. double rVal;
  169509. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  169510. memcpy(&rVal, &iVal, 8);
  169511. if( sqlite3_value_double(pVal)!=rVal ) return 0;
  169512. }
  169513. }else{
  169514. int n;
  169515. const u8 *z;
  169516. a += sessionVarintGet(a, &n);
  169517. if( sqlite3_value_bytes(pVal)!=n ) return 0;
  169518. if( eType==SQLITE_TEXT ){
  169519. z = sqlite3_value_text(pVal);
  169520. }else{
  169521. z = sqlite3_value_blob(pVal);
  169522. }
  169523. if( n>0 && memcmp(a, z, n) ) return 0;
  169524. a += n;
  169525. }
  169526. }
  169527. }
  169528. return 1;
  169529. }
  169530. /*
  169531. ** If required, grow the hash table used to store changes on table pTab
  169532. ** (part of the session pSession). If a fatal OOM error occurs, set the
  169533. ** session object to failed and return SQLITE_ERROR. Otherwise, return
  169534. ** SQLITE_OK.
  169535. **
  169536. ** It is possible that a non-fatal OOM error occurs in this function. In
  169537. ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
  169538. ** Growing the hash table in this case is a performance optimization only,
  169539. ** it is not required for correct operation.
  169540. */
  169541. static int sessionGrowHash(int bPatchset, SessionTable *pTab){
  169542. if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
  169543. int i;
  169544. SessionChange **apNew;
  169545. int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
  169546. apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
  169547. if( apNew==0 ){
  169548. if( pTab->nChange==0 ){
  169549. return SQLITE_ERROR;
  169550. }
  169551. return SQLITE_OK;
  169552. }
  169553. memset(apNew, 0, sizeof(SessionChange *) * nNew);
  169554. for(i=0; i<pTab->nChange; i++){
  169555. SessionChange *p;
  169556. SessionChange *pNext;
  169557. for(p=pTab->apChange[i]; p; p=pNext){
  169558. int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
  169559. int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
  169560. pNext = p->pNext;
  169561. p->pNext = apNew[iHash];
  169562. apNew[iHash] = p;
  169563. }
  169564. }
  169565. sqlite3_free(pTab->apChange);
  169566. pTab->nChange = nNew;
  169567. pTab->apChange = apNew;
  169568. }
  169569. return SQLITE_OK;
  169570. }
  169571. /*
  169572. ** This function queries the database for the names of the columns of table
  169573. ** zThis, in schema zDb.
  169574. **
  169575. ** Otherwise, if they are not NULL, variable *pnCol is set to the number
  169576. ** of columns in the database table and variable *pzTab is set to point to a
  169577. ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
  169578. ** point to an array of pointers to column names. And *pabPK (again, if not
  169579. ** NULL) is set to point to an array of booleans - true if the corresponding
  169580. ** column is part of the primary key.
  169581. **
  169582. ** For example, if the table is declared as:
  169583. **
  169584. ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
  169585. **
  169586. ** Then the four output variables are populated as follows:
  169587. **
  169588. ** *pnCol = 4
  169589. ** *pzTab = "tbl1"
  169590. ** *pazCol = {"w", "x", "y", "z"}
  169591. ** *pabPK = {1, 0, 0, 1}
  169592. **
  169593. ** All returned buffers are part of the same single allocation, which must
  169594. ** be freed using sqlite3_free() by the caller
  169595. */
  169596. static int sessionTableInfo(
  169597. sqlite3 *db, /* Database connection */
  169598. const char *zDb, /* Name of attached database (e.g. "main") */
  169599. const char *zThis, /* Table name */
  169600. int *pnCol, /* OUT: number of columns */
  169601. const char **pzTab, /* OUT: Copy of zThis */
  169602. const char ***pazCol, /* OUT: Array of column names for table */
  169603. u8 **pabPK /* OUT: Array of booleans - true for PK col */
  169604. ){
  169605. char *zPragma;
  169606. sqlite3_stmt *pStmt;
  169607. int rc;
  169608. int nByte;
  169609. int nDbCol = 0;
  169610. int nThis;
  169611. int i;
  169612. u8 *pAlloc = 0;
  169613. char **azCol = 0;
  169614. u8 *abPK = 0;
  169615. assert( pazCol && pabPK );
  169616. nThis = sqlite3Strlen30(zThis);
  169617. if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
  169618. rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
  169619. if( rc==SQLITE_OK ){
  169620. /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
  169621. zPragma = sqlite3_mprintf(
  169622. "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL "
  169623. "SELECT 1, 'idx', '', 0, '', 2 UNION ALL "
  169624. "SELECT 2, 'stat', '', 0, '', 0"
  169625. );
  169626. }else if( rc==SQLITE_ERROR ){
  169627. zPragma = sqlite3_mprintf("");
  169628. }else{
  169629. return rc;
  169630. }
  169631. }else{
  169632. zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
  169633. }
  169634. if( !zPragma ) return SQLITE_NOMEM;
  169635. rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
  169636. sqlite3_free(zPragma);
  169637. if( rc!=SQLITE_OK ) return rc;
  169638. nByte = nThis + 1;
  169639. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  169640. nByte += sqlite3_column_bytes(pStmt, 1);
  169641. nDbCol++;
  169642. }
  169643. rc = sqlite3_reset(pStmt);
  169644. if( rc==SQLITE_OK ){
  169645. nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
  169646. pAlloc = sqlite3_malloc(nByte);
  169647. if( pAlloc==0 ){
  169648. rc = SQLITE_NOMEM;
  169649. }
  169650. }
  169651. if( rc==SQLITE_OK ){
  169652. azCol = (char **)pAlloc;
  169653. pAlloc = (u8 *)&azCol[nDbCol];
  169654. abPK = (u8 *)pAlloc;
  169655. pAlloc = &abPK[nDbCol];
  169656. if( pzTab ){
  169657. memcpy(pAlloc, zThis, nThis+1);
  169658. *pzTab = (char *)pAlloc;
  169659. pAlloc += nThis+1;
  169660. }
  169661. i = 0;
  169662. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  169663. int nName = sqlite3_column_bytes(pStmt, 1);
  169664. const unsigned char *zName = sqlite3_column_text(pStmt, 1);
  169665. if( zName==0 ) break;
  169666. memcpy(pAlloc, zName, nName+1);
  169667. azCol[i] = (char *)pAlloc;
  169668. pAlloc += nName+1;
  169669. abPK[i] = sqlite3_column_int(pStmt, 5);
  169670. i++;
  169671. }
  169672. rc = sqlite3_reset(pStmt);
  169673. }
  169674. /* If successful, populate the output variables. Otherwise, zero them and
  169675. ** free any allocation made. An error code will be returned in this case.
  169676. */
  169677. if( rc==SQLITE_OK ){
  169678. *pazCol = (const char **)azCol;
  169679. *pabPK = abPK;
  169680. *pnCol = nDbCol;
  169681. }else{
  169682. *pazCol = 0;
  169683. *pabPK = 0;
  169684. *pnCol = 0;
  169685. if( pzTab ) *pzTab = 0;
  169686. sqlite3_free(azCol);
  169687. }
  169688. sqlite3_finalize(pStmt);
  169689. return rc;
  169690. }
  169691. /*
  169692. ** This function is only called from within a pre-update handler for a
  169693. ** write to table pTab, part of session pSession. If this is the first
  169694. ** write to this table, initalize the SessionTable.nCol, azCol[] and
  169695. ** abPK[] arrays accordingly.
  169696. **
  169697. ** If an error occurs, an error code is stored in sqlite3_session.rc and
  169698. ** non-zero returned. Or, if no error occurs but the table has no primary
  169699. ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
  169700. ** indicate that updates on this table should be ignored. SessionTable.abPK
  169701. ** is set to NULL in this case.
  169702. */
  169703. static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  169704. if( pTab->nCol==0 ){
  169705. u8 *abPK;
  169706. assert( pTab->azCol==0 || pTab->abPK==0 );
  169707. pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
  169708. pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
  169709. );
  169710. if( pSession->rc==SQLITE_OK ){
  169711. int i;
  169712. for(i=0; i<pTab->nCol; i++){
  169713. if( abPK[i] ){
  169714. pTab->abPK = abPK;
  169715. break;
  169716. }
  169717. }
  169718. if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
  169719. pTab->bStat1 = 1;
  169720. }
  169721. }
  169722. }
  169723. return (pSession->rc || pTab->abPK==0);
  169724. }
  169725. /*
  169726. ** Versions of the four methods in object SessionHook for use with the
  169727. ** sqlite_stat1 table. The purpose of this is to substitute a zero-length
  169728. ** blob each time a NULL value is read from the "idx" column of the
  169729. ** sqlite_stat1 table.
  169730. */
  169731. typedef struct SessionStat1Ctx SessionStat1Ctx;
  169732. struct SessionStat1Ctx {
  169733. SessionHook hook;
  169734. sqlite3_session *pSession;
  169735. };
  169736. static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
  169737. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  169738. sqlite3_value *pVal = 0;
  169739. int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
  169740. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  169741. pVal = p->pSession->pZeroBlob;
  169742. }
  169743. *ppVal = pVal;
  169744. return rc;
  169745. }
  169746. static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
  169747. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  169748. sqlite3_value *pVal = 0;
  169749. int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
  169750. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  169751. pVal = p->pSession->pZeroBlob;
  169752. }
  169753. *ppVal = pVal;
  169754. return rc;
  169755. }
  169756. static int sessionStat1Count(void *pCtx){
  169757. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  169758. return p->hook.xCount(p->hook.pCtx);
  169759. }
  169760. static int sessionStat1Depth(void *pCtx){
  169761. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  169762. return p->hook.xDepth(p->hook.pCtx);
  169763. }
  169764. /*
  169765. ** This function is only called from with a pre-update-hook reporting a
  169766. ** change on table pTab (attached to session pSession). The type of change
  169767. ** (UPDATE, INSERT, DELETE) is specified by the first argument.
  169768. **
  169769. ** Unless one is already present or an error occurs, an entry is added
  169770. ** to the changed-rows hash table associated with table pTab.
  169771. */
  169772. static void sessionPreupdateOneChange(
  169773. int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
  169774. sqlite3_session *pSession, /* Session object pTab is attached to */
  169775. SessionTable *pTab /* Table that change applies to */
  169776. ){
  169777. int iHash;
  169778. int bNull = 0;
  169779. int rc = SQLITE_OK;
  169780. SessionStat1Ctx stat1 = {0};
  169781. if( pSession->rc ) return;
  169782. /* Load table details if required */
  169783. if( sessionInitTable(pSession, pTab) ) return;
  169784. /* Check the number of columns in this xPreUpdate call matches the
  169785. ** number of columns in the table. */
  169786. if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
  169787. pSession->rc = SQLITE_SCHEMA;
  169788. return;
  169789. }
  169790. /* Grow the hash table if required */
  169791. if( sessionGrowHash(0, pTab) ){
  169792. pSession->rc = SQLITE_NOMEM;
  169793. return;
  169794. }
  169795. if( pTab->bStat1 ){
  169796. stat1.hook = pSession->hook;
  169797. stat1.pSession = pSession;
  169798. pSession->hook.pCtx = (void*)&stat1;
  169799. pSession->hook.xNew = sessionStat1New;
  169800. pSession->hook.xOld = sessionStat1Old;
  169801. pSession->hook.xCount = sessionStat1Count;
  169802. pSession->hook.xDepth = sessionStat1Depth;
  169803. if( pSession->pZeroBlob==0 ){
  169804. sqlite3_value *p = sqlite3ValueNew(0);
  169805. if( p==0 ){
  169806. rc = SQLITE_NOMEM;
  169807. goto error_out;
  169808. }
  169809. sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
  169810. pSession->pZeroBlob = p;
  169811. }
  169812. }
  169813. /* Calculate the hash-key for this change. If the primary key of the row
  169814. ** includes a NULL value, exit early. Such changes are ignored by the
  169815. ** session module. */
  169816. rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
  169817. if( rc!=SQLITE_OK ) goto error_out;
  169818. if( bNull==0 ){
  169819. /* Search the hash table for an existing record for this row. */
  169820. SessionChange *pC;
  169821. for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
  169822. if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
  169823. }
  169824. if( pC==0 ){
  169825. /* Create a new change object containing all the old values (if
  169826. ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
  169827. ** values (if this is an INSERT). */
  169828. SessionChange *pChange; /* New change object */
  169829. int nByte; /* Number of bytes to allocate */
  169830. int i; /* Used to iterate through columns */
  169831. assert( rc==SQLITE_OK );
  169832. pTab->nEntry++;
  169833. /* Figure out how large an allocation is required */
  169834. nByte = sizeof(SessionChange);
  169835. for(i=0; i<pTab->nCol; i++){
  169836. sqlite3_value *p = 0;
  169837. if( op!=SQLITE_INSERT ){
  169838. TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  169839. assert( trc==SQLITE_OK );
  169840. }else if( pTab->abPK[i] ){
  169841. TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  169842. assert( trc==SQLITE_OK );
  169843. }
  169844. /* This may fail if SQLite value p contains a utf-16 string that must
  169845. ** be converted to utf-8 and an OOM error occurs while doing so. */
  169846. rc = sessionSerializeValue(0, p, &nByte);
  169847. if( rc!=SQLITE_OK ) goto error_out;
  169848. }
  169849. /* Allocate the change object */
  169850. pChange = (SessionChange *)sqlite3_malloc(nByte);
  169851. if( !pChange ){
  169852. rc = SQLITE_NOMEM;
  169853. goto error_out;
  169854. }else{
  169855. memset(pChange, 0, sizeof(SessionChange));
  169856. pChange->aRecord = (u8 *)&pChange[1];
  169857. }
  169858. /* Populate the change object. None of the preupdate_old(),
  169859. ** preupdate_new() or SerializeValue() calls below may fail as all
  169860. ** required values and encodings have already been cached in memory.
  169861. ** It is not possible for an OOM to occur in this block. */
  169862. nByte = 0;
  169863. for(i=0; i<pTab->nCol; i++){
  169864. sqlite3_value *p = 0;
  169865. if( op!=SQLITE_INSERT ){
  169866. pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  169867. }else if( pTab->abPK[i] ){
  169868. pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  169869. }
  169870. sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
  169871. }
  169872. /* Add the change to the hash-table */
  169873. if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
  169874. pChange->bIndirect = 1;
  169875. }
  169876. pChange->nRecord = nByte;
  169877. pChange->op = op;
  169878. pChange->pNext = pTab->apChange[iHash];
  169879. pTab->apChange[iHash] = pChange;
  169880. }else if( pC->bIndirect ){
  169881. /* If the existing change is considered "indirect", but this current
  169882. ** change is "direct", mark the change object as direct. */
  169883. if( pSession->hook.xDepth(pSession->hook.pCtx)==0
  169884. && pSession->bIndirect==0
  169885. ){
  169886. pC->bIndirect = 0;
  169887. }
  169888. }
  169889. }
  169890. /* If an error has occurred, mark the session object as failed. */
  169891. error_out:
  169892. if( pTab->bStat1 ){
  169893. pSession->hook = stat1.hook;
  169894. }
  169895. if( rc!=SQLITE_OK ){
  169896. pSession->rc = rc;
  169897. }
  169898. }
  169899. static int sessionFindTable(
  169900. sqlite3_session *pSession,
  169901. const char *zName,
  169902. SessionTable **ppTab
  169903. ){
  169904. int rc = SQLITE_OK;
  169905. int nName = sqlite3Strlen30(zName);
  169906. SessionTable *pRet;
  169907. /* Search for an existing table */
  169908. for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
  169909. if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
  169910. }
  169911. if( pRet==0 && pSession->bAutoAttach ){
  169912. /* If there is a table-filter configured, invoke it. If it returns 0,
  169913. ** do not automatically add the new table. */
  169914. if( pSession->xTableFilter==0
  169915. || pSession->xTableFilter(pSession->pFilterCtx, zName)
  169916. ){
  169917. rc = sqlite3session_attach(pSession, zName);
  169918. if( rc==SQLITE_OK ){
  169919. for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
  169920. assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
  169921. }
  169922. }
  169923. }
  169924. assert( rc==SQLITE_OK || pRet==0 );
  169925. *ppTab = pRet;
  169926. return rc;
  169927. }
  169928. /*
  169929. ** The 'pre-update' hook registered by this module with SQLite databases.
  169930. */
  169931. static void xPreUpdate(
  169932. void *pCtx, /* Copy of third arg to preupdate_hook() */
  169933. sqlite3 *db, /* Database handle */
  169934. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  169935. char const *zDb, /* Database name */
  169936. char const *zName, /* Table name */
  169937. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  169938. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  169939. ){
  169940. sqlite3_session *pSession;
  169941. int nDb = sqlite3Strlen30(zDb);
  169942. assert( sqlite3_mutex_held(db->mutex) );
  169943. for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
  169944. SessionTable *pTab;
  169945. /* If this session is attached to a different database ("main", "temp"
  169946. ** etc.), or if it is not currently enabled, there is nothing to do. Skip
  169947. ** to the next session object attached to this database. */
  169948. if( pSession->bEnable==0 ) continue;
  169949. if( pSession->rc ) continue;
  169950. if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
  169951. pSession->rc = sessionFindTable(pSession, zName, &pTab);
  169952. if( pTab ){
  169953. assert( pSession->rc==SQLITE_OK );
  169954. sessionPreupdateOneChange(op, pSession, pTab);
  169955. if( op==SQLITE_UPDATE ){
  169956. sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
  169957. }
  169958. }
  169959. }
  169960. }
  169961. /*
  169962. ** The pre-update hook implementations.
  169963. */
  169964. static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  169965. return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
  169966. }
  169967. static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  169968. return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
  169969. }
  169970. static int sessionPreupdateCount(void *pCtx){
  169971. return sqlite3_preupdate_count((sqlite3*)pCtx);
  169972. }
  169973. static int sessionPreupdateDepth(void *pCtx){
  169974. return sqlite3_preupdate_depth((sqlite3*)pCtx);
  169975. }
  169976. /*
  169977. ** Install the pre-update hooks on the session object passed as the only
  169978. ** argument.
  169979. */
  169980. static void sessionPreupdateHooks(
  169981. sqlite3_session *pSession
  169982. ){
  169983. pSession->hook.pCtx = (void*)pSession->db;
  169984. pSession->hook.xOld = sessionPreupdateOld;
  169985. pSession->hook.xNew = sessionPreupdateNew;
  169986. pSession->hook.xCount = sessionPreupdateCount;
  169987. pSession->hook.xDepth = sessionPreupdateDepth;
  169988. }
  169989. typedef struct SessionDiffCtx SessionDiffCtx;
  169990. struct SessionDiffCtx {
  169991. sqlite3_stmt *pStmt;
  169992. int nOldOff;
  169993. };
  169994. /*
  169995. ** The diff hook implementations.
  169996. */
  169997. static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  169998. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  169999. *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
  170000. return SQLITE_OK;
  170001. }
  170002. static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  170003. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  170004. *ppVal = sqlite3_column_value(p->pStmt, iVal);
  170005. return SQLITE_OK;
  170006. }
  170007. static int sessionDiffCount(void *pCtx){
  170008. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  170009. return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
  170010. }
  170011. static int sessionDiffDepth(void *pCtx){
  170012. return 0;
  170013. }
  170014. /*
  170015. ** Install the diff hooks on the session object passed as the only
  170016. ** argument.
  170017. */
  170018. static void sessionDiffHooks(
  170019. sqlite3_session *pSession,
  170020. SessionDiffCtx *pDiffCtx
  170021. ){
  170022. pSession->hook.pCtx = (void*)pDiffCtx;
  170023. pSession->hook.xOld = sessionDiffOld;
  170024. pSession->hook.xNew = sessionDiffNew;
  170025. pSession->hook.xCount = sessionDiffCount;
  170026. pSession->hook.xDepth = sessionDiffDepth;
  170027. }
  170028. static char *sessionExprComparePK(
  170029. int nCol,
  170030. const char *zDb1, const char *zDb2,
  170031. const char *zTab,
  170032. const char **azCol, u8 *abPK
  170033. ){
  170034. int i;
  170035. const char *zSep = "";
  170036. char *zRet = 0;
  170037. for(i=0; i<nCol; i++){
  170038. if( abPK[i] ){
  170039. zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
  170040. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  170041. );
  170042. zSep = " AND ";
  170043. if( zRet==0 ) break;
  170044. }
  170045. }
  170046. return zRet;
  170047. }
  170048. static char *sessionExprCompareOther(
  170049. int nCol,
  170050. const char *zDb1, const char *zDb2,
  170051. const char *zTab,
  170052. const char **azCol, u8 *abPK
  170053. ){
  170054. int i;
  170055. const char *zSep = "";
  170056. char *zRet = 0;
  170057. int bHave = 0;
  170058. for(i=0; i<nCol; i++){
  170059. if( abPK[i]==0 ){
  170060. bHave = 1;
  170061. zRet = sqlite3_mprintf(
  170062. "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
  170063. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  170064. );
  170065. zSep = " OR ";
  170066. if( zRet==0 ) break;
  170067. }
  170068. }
  170069. if( bHave==0 ){
  170070. assert( zRet==0 );
  170071. zRet = sqlite3_mprintf("0");
  170072. }
  170073. return zRet;
  170074. }
  170075. static char *sessionSelectFindNew(
  170076. int nCol,
  170077. const char *zDb1, /* Pick rows in this db only */
  170078. const char *zDb2, /* But not in this one */
  170079. const char *zTbl, /* Table name */
  170080. const char *zExpr
  170081. ){
  170082. char *zRet = sqlite3_mprintf(
  170083. "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
  170084. " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
  170085. ")",
  170086. zDb1, zTbl, zDb2, zTbl, zExpr
  170087. );
  170088. return zRet;
  170089. }
  170090. static int sessionDiffFindNew(
  170091. int op,
  170092. sqlite3_session *pSession,
  170093. SessionTable *pTab,
  170094. const char *zDb1,
  170095. const char *zDb2,
  170096. char *zExpr
  170097. ){
  170098. int rc = SQLITE_OK;
  170099. char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
  170100. if( zStmt==0 ){
  170101. rc = SQLITE_NOMEM;
  170102. }else{
  170103. sqlite3_stmt *pStmt;
  170104. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  170105. if( rc==SQLITE_OK ){
  170106. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  170107. pDiffCtx->pStmt = pStmt;
  170108. pDiffCtx->nOldOff = 0;
  170109. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  170110. sessionPreupdateOneChange(op, pSession, pTab);
  170111. }
  170112. rc = sqlite3_finalize(pStmt);
  170113. }
  170114. sqlite3_free(zStmt);
  170115. }
  170116. return rc;
  170117. }
  170118. static int sessionDiffFindModified(
  170119. sqlite3_session *pSession,
  170120. SessionTable *pTab,
  170121. const char *zFrom,
  170122. const char *zExpr
  170123. ){
  170124. int rc = SQLITE_OK;
  170125. char *zExpr2 = sessionExprCompareOther(pTab->nCol,
  170126. pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  170127. );
  170128. if( zExpr2==0 ){
  170129. rc = SQLITE_NOMEM;
  170130. }else{
  170131. char *zStmt = sqlite3_mprintf(
  170132. "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
  170133. pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
  170134. );
  170135. if( zStmt==0 ){
  170136. rc = SQLITE_NOMEM;
  170137. }else{
  170138. sqlite3_stmt *pStmt;
  170139. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  170140. if( rc==SQLITE_OK ){
  170141. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  170142. pDiffCtx->pStmt = pStmt;
  170143. pDiffCtx->nOldOff = pTab->nCol;
  170144. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  170145. sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
  170146. }
  170147. rc = sqlite3_finalize(pStmt);
  170148. }
  170149. sqlite3_free(zStmt);
  170150. }
  170151. }
  170152. return rc;
  170153. }
  170154. SQLITE_API int sqlite3session_diff(
  170155. sqlite3_session *pSession,
  170156. const char *zFrom,
  170157. const char *zTbl,
  170158. char **pzErrMsg
  170159. ){
  170160. const char *zDb = pSession->zDb;
  170161. int rc = pSession->rc;
  170162. SessionDiffCtx d;
  170163. memset(&d, 0, sizeof(d));
  170164. sessionDiffHooks(pSession, &d);
  170165. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  170166. if( pzErrMsg ) *pzErrMsg = 0;
  170167. if( rc==SQLITE_OK ){
  170168. char *zExpr = 0;
  170169. sqlite3 *db = pSession->db;
  170170. SessionTable *pTo; /* Table zTbl */
  170171. /* Locate and if necessary initialize the target table object */
  170172. rc = sessionFindTable(pSession, zTbl, &pTo);
  170173. if( pTo==0 ) goto diff_out;
  170174. if( sessionInitTable(pSession, pTo) ){
  170175. rc = pSession->rc;
  170176. goto diff_out;
  170177. }
  170178. /* Check the table schemas match */
  170179. if( rc==SQLITE_OK ){
  170180. int bHasPk = 0;
  170181. int bMismatch = 0;
  170182. int nCol; /* Columns in zFrom.zTbl */
  170183. u8 *abPK;
  170184. const char **azCol = 0;
  170185. rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
  170186. if( rc==SQLITE_OK ){
  170187. if( pTo->nCol!=nCol ){
  170188. bMismatch = 1;
  170189. }else{
  170190. int i;
  170191. for(i=0; i<nCol; i++){
  170192. if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
  170193. if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
  170194. if( abPK[i] ) bHasPk = 1;
  170195. }
  170196. }
  170197. }
  170198. sqlite3_free((char*)azCol);
  170199. if( bMismatch ){
  170200. *pzErrMsg = sqlite3_mprintf("table schemas do not match");
  170201. rc = SQLITE_SCHEMA;
  170202. }
  170203. if( bHasPk==0 ){
  170204. /* Ignore tables with no primary keys */
  170205. goto diff_out;
  170206. }
  170207. }
  170208. if( rc==SQLITE_OK ){
  170209. zExpr = sessionExprComparePK(pTo->nCol,
  170210. zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
  170211. );
  170212. }
  170213. /* Find new rows */
  170214. if( rc==SQLITE_OK ){
  170215. rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
  170216. }
  170217. /* Find old rows */
  170218. if( rc==SQLITE_OK ){
  170219. rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
  170220. }
  170221. /* Find modified rows */
  170222. if( rc==SQLITE_OK ){
  170223. rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
  170224. }
  170225. sqlite3_free(zExpr);
  170226. }
  170227. diff_out:
  170228. sessionPreupdateHooks(pSession);
  170229. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  170230. return rc;
  170231. }
  170232. /*
  170233. ** Create a session object. This session object will record changes to
  170234. ** database zDb attached to connection db.
  170235. */
  170236. SQLITE_API int sqlite3session_create(
  170237. sqlite3 *db, /* Database handle */
  170238. const char *zDb, /* Name of db (e.g. "main") */
  170239. sqlite3_session **ppSession /* OUT: New session object */
  170240. ){
  170241. sqlite3_session *pNew; /* Newly allocated session object */
  170242. sqlite3_session *pOld; /* Session object already attached to db */
  170243. int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
  170244. /* Zero the output value in case an error occurs. */
  170245. *ppSession = 0;
  170246. /* Allocate and populate the new session object. */
  170247. pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
  170248. if( !pNew ) return SQLITE_NOMEM;
  170249. memset(pNew, 0, sizeof(sqlite3_session));
  170250. pNew->db = db;
  170251. pNew->zDb = (char *)&pNew[1];
  170252. pNew->bEnable = 1;
  170253. memcpy(pNew->zDb, zDb, nDb+1);
  170254. sessionPreupdateHooks(pNew);
  170255. /* Add the new session object to the linked list of session objects
  170256. ** attached to database handle $db. Do this under the cover of the db
  170257. ** handle mutex. */
  170258. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  170259. pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
  170260. pNew->pNext = pOld;
  170261. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  170262. *ppSession = pNew;
  170263. return SQLITE_OK;
  170264. }
  170265. /*
  170266. ** Free the list of table objects passed as the first argument. The contents
  170267. ** of the changed-rows hash tables are also deleted.
  170268. */
  170269. static void sessionDeleteTable(SessionTable *pList){
  170270. SessionTable *pNext;
  170271. SessionTable *pTab;
  170272. for(pTab=pList; pTab; pTab=pNext){
  170273. int i;
  170274. pNext = pTab->pNext;
  170275. for(i=0; i<pTab->nChange; i++){
  170276. SessionChange *p;
  170277. SessionChange *pNextChange;
  170278. for(p=pTab->apChange[i]; p; p=pNextChange){
  170279. pNextChange = p->pNext;
  170280. sqlite3_free(p);
  170281. }
  170282. }
  170283. sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
  170284. sqlite3_free(pTab->apChange);
  170285. sqlite3_free(pTab);
  170286. }
  170287. }
  170288. /*
  170289. ** Delete a session object previously allocated using sqlite3session_create().
  170290. */
  170291. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
  170292. sqlite3 *db = pSession->db;
  170293. sqlite3_session *pHead;
  170294. sqlite3_session **pp;
  170295. /* Unlink the session from the linked list of sessions attached to the
  170296. ** database handle. Hold the db mutex while doing so. */
  170297. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  170298. pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
  170299. for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
  170300. if( (*pp)==pSession ){
  170301. *pp = (*pp)->pNext;
  170302. if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
  170303. break;
  170304. }
  170305. }
  170306. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  170307. sqlite3ValueFree(pSession->pZeroBlob);
  170308. /* Delete all attached table objects. And the contents of their
  170309. ** associated hash-tables. */
  170310. sessionDeleteTable(pSession->pTable);
  170311. /* Free the session object itself. */
  170312. sqlite3_free(pSession);
  170313. }
  170314. /*
  170315. ** Set a table filter on a Session Object.
  170316. */
  170317. SQLITE_API void sqlite3session_table_filter(
  170318. sqlite3_session *pSession,
  170319. int(*xFilter)(void*, const char*),
  170320. void *pCtx /* First argument passed to xFilter */
  170321. ){
  170322. pSession->bAutoAttach = 1;
  170323. pSession->pFilterCtx = pCtx;
  170324. pSession->xTableFilter = xFilter;
  170325. }
  170326. /*
  170327. ** Attach a table to a session. All subsequent changes made to the table
  170328. ** while the session object is enabled will be recorded.
  170329. **
  170330. ** Only tables that have a PRIMARY KEY defined may be attached. It does
  170331. ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
  170332. ** or not.
  170333. */
  170334. SQLITE_API int sqlite3session_attach(
  170335. sqlite3_session *pSession, /* Session object */
  170336. const char *zName /* Table name */
  170337. ){
  170338. int rc = SQLITE_OK;
  170339. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  170340. if( !zName ){
  170341. pSession->bAutoAttach = 1;
  170342. }else{
  170343. SessionTable *pTab; /* New table object (if required) */
  170344. int nName; /* Number of bytes in string zName */
  170345. /* First search for an existing entry. If one is found, this call is
  170346. ** a no-op. Return early. */
  170347. nName = sqlite3Strlen30(zName);
  170348. for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
  170349. if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
  170350. }
  170351. if( !pTab ){
  170352. /* Allocate new SessionTable object. */
  170353. pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
  170354. if( !pTab ){
  170355. rc = SQLITE_NOMEM;
  170356. }else{
  170357. /* Populate the new SessionTable object and link it into the list.
  170358. ** The new object must be linked onto the end of the list, not
  170359. ** simply added to the start of it in order to ensure that tables
  170360. ** appear in the correct order when a changeset or patchset is
  170361. ** eventually generated. */
  170362. SessionTable **ppTab;
  170363. memset(pTab, 0, sizeof(SessionTable));
  170364. pTab->zName = (char *)&pTab[1];
  170365. memcpy(pTab->zName, zName, nName+1);
  170366. for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
  170367. *ppTab = pTab;
  170368. }
  170369. }
  170370. }
  170371. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  170372. return rc;
  170373. }
  170374. /*
  170375. ** Ensure that there is room in the buffer to append nByte bytes of data.
  170376. ** If not, use sqlite3_realloc() to grow the buffer so that there is.
  170377. **
  170378. ** If successful, return zero. Otherwise, if an OOM condition is encountered,
  170379. ** set *pRc to SQLITE_NOMEM and return non-zero.
  170380. */
  170381. static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
  170382. if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
  170383. u8 *aNew;
  170384. int nNew = p->nAlloc ? p->nAlloc : 128;
  170385. do {
  170386. nNew = nNew*2;
  170387. }while( nNew<(p->nBuf+nByte) );
  170388. aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
  170389. if( 0==aNew ){
  170390. *pRc = SQLITE_NOMEM;
  170391. }else{
  170392. p->aBuf = aNew;
  170393. p->nAlloc = nNew;
  170394. }
  170395. }
  170396. return (*pRc!=SQLITE_OK);
  170397. }
  170398. /*
  170399. ** Append the value passed as the second argument to the buffer passed
  170400. ** as the first.
  170401. **
  170402. ** This function is a no-op if *pRc is non-zero when it is called.
  170403. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
  170404. ** before returning.
  170405. */
  170406. static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
  170407. int rc = *pRc;
  170408. if( rc==SQLITE_OK ){
  170409. int nByte = 0;
  170410. rc = sessionSerializeValue(0, pVal, &nByte);
  170411. sessionBufferGrow(p, nByte, &rc);
  170412. if( rc==SQLITE_OK ){
  170413. rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
  170414. p->nBuf += nByte;
  170415. }else{
  170416. *pRc = rc;
  170417. }
  170418. }
  170419. }
  170420. /*
  170421. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  170422. ** called. Otherwise, append a single byte to the buffer.
  170423. **
  170424. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  170425. ** returning.
  170426. */
  170427. static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
  170428. if( 0==sessionBufferGrow(p, 1, pRc) ){
  170429. p->aBuf[p->nBuf++] = v;
  170430. }
  170431. }
  170432. /*
  170433. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  170434. ** called. Otherwise, append a single varint to the buffer.
  170435. **
  170436. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  170437. ** returning.
  170438. */
  170439. static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
  170440. if( 0==sessionBufferGrow(p, 9, pRc) ){
  170441. p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
  170442. }
  170443. }
  170444. /*
  170445. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  170446. ** called. Otherwise, append a blob of data to the buffer.
  170447. **
  170448. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  170449. ** returning.
  170450. */
  170451. static void sessionAppendBlob(
  170452. SessionBuffer *p,
  170453. const u8 *aBlob,
  170454. int nBlob,
  170455. int *pRc
  170456. ){
  170457. if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
  170458. memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
  170459. p->nBuf += nBlob;
  170460. }
  170461. }
  170462. /*
  170463. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  170464. ** called. Otherwise, append a string to the buffer. All bytes in the string
  170465. ** up to (but not including) the nul-terminator are written to the buffer.
  170466. **
  170467. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  170468. ** returning.
  170469. */
  170470. static void sessionAppendStr(
  170471. SessionBuffer *p,
  170472. const char *zStr,
  170473. int *pRc
  170474. ){
  170475. int nStr = sqlite3Strlen30(zStr);
  170476. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  170477. memcpy(&p->aBuf[p->nBuf], zStr, nStr);
  170478. p->nBuf += nStr;
  170479. }
  170480. }
  170481. /*
  170482. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  170483. ** called. Otherwise, append the string representation of integer iVal
  170484. ** to the buffer. No nul-terminator is written.
  170485. **
  170486. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  170487. ** returning.
  170488. */
  170489. static void sessionAppendInteger(
  170490. SessionBuffer *p, /* Buffer to append to */
  170491. int iVal, /* Value to write the string rep. of */
  170492. int *pRc /* IN/OUT: Error code */
  170493. ){
  170494. char aBuf[24];
  170495. sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  170496. sessionAppendStr(p, aBuf, pRc);
  170497. }
  170498. /*
  170499. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  170500. ** called. Otherwise, append the string zStr enclosed in quotes (") and
  170501. ** with any embedded quote characters escaped to the buffer. No
  170502. ** nul-terminator byte is written.
  170503. **
  170504. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  170505. ** returning.
  170506. */
  170507. static void sessionAppendIdent(
  170508. SessionBuffer *p, /* Buffer to a append to */
  170509. const char *zStr, /* String to quote, escape and append */
  170510. int *pRc /* IN/OUT: Error code */
  170511. ){
  170512. int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
  170513. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  170514. char *zOut = (char *)&p->aBuf[p->nBuf];
  170515. const char *zIn = zStr;
  170516. *zOut++ = '"';
  170517. while( *zIn ){
  170518. if( *zIn=='"' ) *zOut++ = '"';
  170519. *zOut++ = *(zIn++);
  170520. }
  170521. *zOut++ = '"';
  170522. p->nBuf = (int)((u8 *)zOut - p->aBuf);
  170523. }
  170524. }
  170525. /*
  170526. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  170527. ** called. Otherwse, it appends the serialized version of the value stored
  170528. ** in column iCol of the row that SQL statement pStmt currently points
  170529. ** to to the buffer.
  170530. */
  170531. static void sessionAppendCol(
  170532. SessionBuffer *p, /* Buffer to append to */
  170533. sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
  170534. int iCol, /* Column to read value from */
  170535. int *pRc /* IN/OUT: Error code */
  170536. ){
  170537. if( *pRc==SQLITE_OK ){
  170538. int eType = sqlite3_column_type(pStmt, iCol);
  170539. sessionAppendByte(p, (u8)eType, pRc);
  170540. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  170541. sqlite3_int64 i;
  170542. u8 aBuf[8];
  170543. if( eType==SQLITE_INTEGER ){
  170544. i = sqlite3_column_int64(pStmt, iCol);
  170545. }else{
  170546. double r = sqlite3_column_double(pStmt, iCol);
  170547. memcpy(&i, &r, 8);
  170548. }
  170549. sessionPutI64(aBuf, i);
  170550. sessionAppendBlob(p, aBuf, 8, pRc);
  170551. }
  170552. if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
  170553. u8 *z;
  170554. int nByte;
  170555. if( eType==SQLITE_BLOB ){
  170556. z = (u8 *)sqlite3_column_blob(pStmt, iCol);
  170557. }else{
  170558. z = (u8 *)sqlite3_column_text(pStmt, iCol);
  170559. }
  170560. nByte = sqlite3_column_bytes(pStmt, iCol);
  170561. if( z || (eType==SQLITE_BLOB && nByte==0) ){
  170562. sessionAppendVarint(p, nByte, pRc);
  170563. sessionAppendBlob(p, z, nByte, pRc);
  170564. }else{
  170565. *pRc = SQLITE_NOMEM;
  170566. }
  170567. }
  170568. }
  170569. }
  170570. /*
  170571. **
  170572. ** This function appends an update change to the buffer (see the comments
  170573. ** under "CHANGESET FORMAT" at the top of the file). An update change
  170574. ** consists of:
  170575. **
  170576. ** 1 byte: SQLITE_UPDATE (0x17)
  170577. ** n bytes: old.* record (see RECORD FORMAT)
  170578. ** m bytes: new.* record (see RECORD FORMAT)
  170579. **
  170580. ** The SessionChange object passed as the third argument contains the
  170581. ** values that were stored in the row when the session began (the old.*
  170582. ** values). The statement handle passed as the second argument points
  170583. ** at the current version of the row (the new.* values).
  170584. **
  170585. ** If all of the old.* values are equal to their corresponding new.* value
  170586. ** (i.e. nothing has changed), then no data at all is appended to the buffer.
  170587. **
  170588. ** Otherwise, the old.* record contains all primary key values and the
  170589. ** original values of any fields that have been modified. The new.* record
  170590. ** contains the new values of only those fields that have been modified.
  170591. */
  170592. static int sessionAppendUpdate(
  170593. SessionBuffer *pBuf, /* Buffer to append to */
  170594. int bPatchset, /* True for "patchset", 0 for "changeset" */
  170595. sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
  170596. SessionChange *p, /* Object containing old values */
  170597. u8 *abPK /* Boolean array - true for PK columns */
  170598. ){
  170599. int rc = SQLITE_OK;
  170600. SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
  170601. int bNoop = 1; /* Set to zero if any values are modified */
  170602. int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
  170603. int i; /* Used to iterate through columns */
  170604. u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
  170605. sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
  170606. sessionAppendByte(pBuf, p->bIndirect, &rc);
  170607. for(i=0; i<sqlite3_column_count(pStmt); i++){
  170608. int bChanged = 0;
  170609. int nAdvance;
  170610. int eType = *pCsr;
  170611. switch( eType ){
  170612. case SQLITE_NULL:
  170613. nAdvance = 1;
  170614. if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  170615. bChanged = 1;
  170616. }
  170617. break;
  170618. case SQLITE_FLOAT:
  170619. case SQLITE_INTEGER: {
  170620. nAdvance = 9;
  170621. if( eType==sqlite3_column_type(pStmt, i) ){
  170622. sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
  170623. if( eType==SQLITE_INTEGER ){
  170624. if( iVal==sqlite3_column_int64(pStmt, i) ) break;
  170625. }else{
  170626. double dVal;
  170627. memcpy(&dVal, &iVal, 8);
  170628. if( dVal==sqlite3_column_double(pStmt, i) ) break;
  170629. }
  170630. }
  170631. bChanged = 1;
  170632. break;
  170633. }
  170634. default: {
  170635. int n;
  170636. int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
  170637. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  170638. nAdvance = nHdr + n;
  170639. if( eType==sqlite3_column_type(pStmt, i)
  170640. && n==sqlite3_column_bytes(pStmt, i)
  170641. && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
  170642. ){
  170643. break;
  170644. }
  170645. bChanged = 1;
  170646. }
  170647. }
  170648. /* If at least one field has been modified, this is not a no-op. */
  170649. if( bChanged ) bNoop = 0;
  170650. /* Add a field to the old.* record. This is omitted if this modules is
  170651. ** currently generating a patchset. */
  170652. if( bPatchset==0 ){
  170653. if( bChanged || abPK[i] ){
  170654. sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
  170655. }else{
  170656. sessionAppendByte(pBuf, 0, &rc);
  170657. }
  170658. }
  170659. /* Add a field to the new.* record. Or the only record if currently
  170660. ** generating a patchset. */
  170661. if( bChanged || (bPatchset && abPK[i]) ){
  170662. sessionAppendCol(&buf2, pStmt, i, &rc);
  170663. }else{
  170664. sessionAppendByte(&buf2, 0, &rc);
  170665. }
  170666. pCsr += nAdvance;
  170667. }
  170668. if( bNoop ){
  170669. pBuf->nBuf = nRewind;
  170670. }else{
  170671. sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
  170672. }
  170673. sqlite3_free(buf2.aBuf);
  170674. return rc;
  170675. }
  170676. /*
  170677. ** Append a DELETE change to the buffer passed as the first argument. Use
  170678. ** the changeset format if argument bPatchset is zero, or the patchset
  170679. ** format otherwise.
  170680. */
  170681. static int sessionAppendDelete(
  170682. SessionBuffer *pBuf, /* Buffer to append to */
  170683. int bPatchset, /* True for "patchset", 0 for "changeset" */
  170684. SessionChange *p, /* Object containing old values */
  170685. int nCol, /* Number of columns in table */
  170686. u8 *abPK /* Boolean array - true for PK columns */
  170687. ){
  170688. int rc = SQLITE_OK;
  170689. sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
  170690. sessionAppendByte(pBuf, p->bIndirect, &rc);
  170691. if( bPatchset==0 ){
  170692. sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
  170693. }else{
  170694. int i;
  170695. u8 *a = p->aRecord;
  170696. for(i=0; i<nCol; i++){
  170697. u8 *pStart = a;
  170698. int eType = *a++;
  170699. switch( eType ){
  170700. case 0:
  170701. case SQLITE_NULL:
  170702. assert( abPK[i]==0 );
  170703. break;
  170704. case SQLITE_FLOAT:
  170705. case SQLITE_INTEGER:
  170706. a += 8;
  170707. break;
  170708. default: {
  170709. int n;
  170710. a += sessionVarintGet(a, &n);
  170711. a += n;
  170712. break;
  170713. }
  170714. }
  170715. if( abPK[i] ){
  170716. sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
  170717. }
  170718. }
  170719. assert( (a - p->aRecord)==p->nRecord );
  170720. }
  170721. return rc;
  170722. }
  170723. /*
  170724. ** Formulate and prepare a SELECT statement to retrieve a row from table
  170725. ** zTab in database zDb based on its primary key. i.e.
  170726. **
  170727. ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
  170728. */
  170729. static int sessionSelectStmt(
  170730. sqlite3 *db, /* Database handle */
  170731. const char *zDb, /* Database name */
  170732. const char *zTab, /* Table name */
  170733. int nCol, /* Number of columns in table */
  170734. const char **azCol, /* Names of table columns */
  170735. u8 *abPK, /* PRIMARY KEY array */
  170736. sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
  170737. ){
  170738. int rc = SQLITE_OK;
  170739. char *zSql = 0;
  170740. int nSql = -1;
  170741. if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
  170742. zSql = sqlite3_mprintf(
  170743. "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
  170744. "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
  170745. );
  170746. if( zSql==0 ) rc = SQLITE_NOMEM;
  170747. }else{
  170748. int i;
  170749. const char *zSep = "";
  170750. SessionBuffer buf = {0, 0, 0};
  170751. sessionAppendStr(&buf, "SELECT * FROM ", &rc);
  170752. sessionAppendIdent(&buf, zDb, &rc);
  170753. sessionAppendStr(&buf, ".", &rc);
  170754. sessionAppendIdent(&buf, zTab, &rc);
  170755. sessionAppendStr(&buf, " WHERE ", &rc);
  170756. for(i=0; i<nCol; i++){
  170757. if( abPK[i] ){
  170758. sessionAppendStr(&buf, zSep, &rc);
  170759. sessionAppendIdent(&buf, azCol[i], &rc);
  170760. sessionAppendStr(&buf, " IS ?", &rc);
  170761. sessionAppendInteger(&buf, i+1, &rc);
  170762. zSep = " AND ";
  170763. }
  170764. }
  170765. zSql = (char*)buf.aBuf;
  170766. nSql = buf.nBuf;
  170767. }
  170768. if( rc==SQLITE_OK ){
  170769. rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
  170770. }
  170771. sqlite3_free(zSql);
  170772. return rc;
  170773. }
  170774. /*
  170775. ** Bind the PRIMARY KEY values from the change passed in argument pChange
  170776. ** to the SELECT statement passed as the first argument. The SELECT statement
  170777. ** is as prepared by function sessionSelectStmt().
  170778. **
  170779. ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
  170780. ** error code (e.g. SQLITE_NOMEM) otherwise.
  170781. */
  170782. static int sessionSelectBind(
  170783. sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
  170784. int nCol, /* Number of columns in table */
  170785. u8 *abPK, /* PRIMARY KEY array */
  170786. SessionChange *pChange /* Change structure */
  170787. ){
  170788. int i;
  170789. int rc = SQLITE_OK;
  170790. u8 *a = pChange->aRecord;
  170791. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  170792. int eType = *a++;
  170793. switch( eType ){
  170794. case 0:
  170795. case SQLITE_NULL:
  170796. assert( abPK[i]==0 );
  170797. break;
  170798. case SQLITE_INTEGER: {
  170799. if( abPK[i] ){
  170800. i64 iVal = sessionGetI64(a);
  170801. rc = sqlite3_bind_int64(pSelect, i+1, iVal);
  170802. }
  170803. a += 8;
  170804. break;
  170805. }
  170806. case SQLITE_FLOAT: {
  170807. if( abPK[i] ){
  170808. double rVal;
  170809. i64 iVal = sessionGetI64(a);
  170810. memcpy(&rVal, &iVal, 8);
  170811. rc = sqlite3_bind_double(pSelect, i+1, rVal);
  170812. }
  170813. a += 8;
  170814. break;
  170815. }
  170816. case SQLITE_TEXT: {
  170817. int n;
  170818. a += sessionVarintGet(a, &n);
  170819. if( abPK[i] ){
  170820. rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
  170821. }
  170822. a += n;
  170823. break;
  170824. }
  170825. default: {
  170826. int n;
  170827. assert( eType==SQLITE_BLOB );
  170828. a += sessionVarintGet(a, &n);
  170829. if( abPK[i] ){
  170830. rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
  170831. }
  170832. a += n;
  170833. break;
  170834. }
  170835. }
  170836. }
  170837. return rc;
  170838. }
  170839. /*
  170840. ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
  170841. ** is called. Otherwise, append a serialized table header (part of the binary
  170842. ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
  170843. ** SQLite error code before returning.
  170844. */
  170845. static void sessionAppendTableHdr(
  170846. SessionBuffer *pBuf, /* Append header to this buffer */
  170847. int bPatchset, /* Use the patchset format if true */
  170848. SessionTable *pTab, /* Table object to append header for */
  170849. int *pRc /* IN/OUT: Error code */
  170850. ){
  170851. /* Write a table header */
  170852. sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
  170853. sessionAppendVarint(pBuf, pTab->nCol, pRc);
  170854. sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
  170855. sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
  170856. }
  170857. /*
  170858. ** Generate either a changeset (if argument bPatchset is zero) or a patchset
  170859. ** (if it is non-zero) based on the current contents of the session object
  170860. ** passed as the first argument.
  170861. **
  170862. ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
  170863. ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
  170864. ** occurs, an SQLite error code is returned and both output variables set
  170865. ** to 0.
  170866. */
  170867. static int sessionGenerateChangeset(
  170868. sqlite3_session *pSession, /* Session object */
  170869. int bPatchset, /* True for patchset, false for changeset */
  170870. int (*xOutput)(void *pOut, const void *pData, int nData),
  170871. void *pOut, /* First argument for xOutput */
  170872. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  170873. void **ppChangeset /* OUT: Buffer containing changeset */
  170874. ){
  170875. sqlite3 *db = pSession->db; /* Source database handle */
  170876. SessionTable *pTab; /* Used to iterate through attached tables */
  170877. SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
  170878. int rc; /* Return code */
  170879. assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
  170880. /* Zero the output variables in case an error occurs. If this session
  170881. ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
  170882. ** this call will be a no-op. */
  170883. if( xOutput==0 ){
  170884. *pnChangeset = 0;
  170885. *ppChangeset = 0;
  170886. }
  170887. if( pSession->rc ) return pSession->rc;
  170888. rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
  170889. if( rc!=SQLITE_OK ) return rc;
  170890. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  170891. for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  170892. if( pTab->nEntry ){
  170893. const char *zName = pTab->zName;
  170894. int nCol; /* Number of columns in table */
  170895. u8 *abPK; /* Primary key array */
  170896. const char **azCol = 0; /* Table columns */
  170897. int i; /* Used to iterate through hash buckets */
  170898. sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
  170899. int nRewind = buf.nBuf; /* Initial size of write buffer */
  170900. int nNoop; /* Size of buffer after writing tbl header */
  170901. /* Check the table schema is still Ok. */
  170902. rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
  170903. if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
  170904. rc = SQLITE_SCHEMA;
  170905. }
  170906. /* Write a table header */
  170907. sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
  170908. /* Build and compile a statement to execute: */
  170909. if( rc==SQLITE_OK ){
  170910. rc = sessionSelectStmt(
  170911. db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
  170912. }
  170913. nNoop = buf.nBuf;
  170914. for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
  170915. SessionChange *p; /* Used to iterate through changes */
  170916. for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
  170917. rc = sessionSelectBind(pSel, nCol, abPK, p);
  170918. if( rc!=SQLITE_OK ) continue;
  170919. if( sqlite3_step(pSel)==SQLITE_ROW ){
  170920. if( p->op==SQLITE_INSERT ){
  170921. int iCol;
  170922. sessionAppendByte(&buf, SQLITE_INSERT, &rc);
  170923. sessionAppendByte(&buf, p->bIndirect, &rc);
  170924. for(iCol=0; iCol<nCol; iCol++){
  170925. sessionAppendCol(&buf, pSel, iCol, &rc);
  170926. }
  170927. }else{
  170928. rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
  170929. }
  170930. }else if( p->op!=SQLITE_INSERT ){
  170931. rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
  170932. }
  170933. if( rc==SQLITE_OK ){
  170934. rc = sqlite3_reset(pSel);
  170935. }
  170936. /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
  170937. ** its contents to the xOutput() callback. */
  170938. if( xOutput
  170939. && rc==SQLITE_OK
  170940. && buf.nBuf>nNoop
  170941. && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
  170942. ){
  170943. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  170944. nNoop = -1;
  170945. buf.nBuf = 0;
  170946. }
  170947. }
  170948. }
  170949. sqlite3_finalize(pSel);
  170950. if( buf.nBuf==nNoop ){
  170951. buf.nBuf = nRewind;
  170952. }
  170953. sqlite3_free((char*)azCol); /* cast works around VC++ bug */
  170954. }
  170955. }
  170956. if( rc==SQLITE_OK ){
  170957. if( xOutput==0 ){
  170958. *pnChangeset = buf.nBuf;
  170959. *ppChangeset = buf.aBuf;
  170960. buf.aBuf = 0;
  170961. }else if( buf.nBuf>0 ){
  170962. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  170963. }
  170964. }
  170965. sqlite3_free(buf.aBuf);
  170966. sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
  170967. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  170968. return rc;
  170969. }
  170970. /*
  170971. ** Obtain a changeset object containing all changes recorded by the
  170972. ** session object passed as the first argument.
  170973. **
  170974. ** It is the responsibility of the caller to eventually free the buffer
  170975. ** using sqlite3_free().
  170976. */
  170977. SQLITE_API int sqlite3session_changeset(
  170978. sqlite3_session *pSession, /* Session object */
  170979. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  170980. void **ppChangeset /* OUT: Buffer containing changeset */
  170981. ){
  170982. return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
  170983. }
  170984. /*
  170985. ** Streaming version of sqlite3session_changeset().
  170986. */
  170987. SQLITE_API int sqlite3session_changeset_strm(
  170988. sqlite3_session *pSession,
  170989. int (*xOutput)(void *pOut, const void *pData, int nData),
  170990. void *pOut
  170991. ){
  170992. return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
  170993. }
  170994. /*
  170995. ** Streaming version of sqlite3session_patchset().
  170996. */
  170997. SQLITE_API int sqlite3session_patchset_strm(
  170998. sqlite3_session *pSession,
  170999. int (*xOutput)(void *pOut, const void *pData, int nData),
  171000. void *pOut
  171001. ){
  171002. return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
  171003. }
  171004. /*
  171005. ** Obtain a patchset object containing all changes recorded by the
  171006. ** session object passed as the first argument.
  171007. **
  171008. ** It is the responsibility of the caller to eventually free the buffer
  171009. ** using sqlite3_free().
  171010. */
  171011. SQLITE_API int sqlite3session_patchset(
  171012. sqlite3_session *pSession, /* Session object */
  171013. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  171014. void **ppPatchset /* OUT: Buffer containing changeset */
  171015. ){
  171016. return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
  171017. }
  171018. /*
  171019. ** Enable or disable the session object passed as the first argument.
  171020. */
  171021. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
  171022. int ret;
  171023. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  171024. if( bEnable>=0 ){
  171025. pSession->bEnable = bEnable;
  171026. }
  171027. ret = pSession->bEnable;
  171028. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  171029. return ret;
  171030. }
  171031. /*
  171032. ** Enable or disable the session object passed as the first argument.
  171033. */
  171034. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
  171035. int ret;
  171036. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  171037. if( bIndirect>=0 ){
  171038. pSession->bIndirect = bIndirect;
  171039. }
  171040. ret = pSession->bIndirect;
  171041. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  171042. return ret;
  171043. }
  171044. /*
  171045. ** Return true if there have been no changes to monitored tables recorded
  171046. ** by the session object passed as the only argument.
  171047. */
  171048. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
  171049. int ret = 0;
  171050. SessionTable *pTab;
  171051. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  171052. for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
  171053. ret = (pTab->nEntry>0);
  171054. }
  171055. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  171056. return (ret==0);
  171057. }
  171058. /*
  171059. ** Do the work for either sqlite3changeset_start() or start_strm().
  171060. */
  171061. static int sessionChangesetStart(
  171062. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  171063. int (*xInput)(void *pIn, void *pData, int *pnData),
  171064. void *pIn,
  171065. int nChangeset, /* Size of buffer pChangeset in bytes */
  171066. void *pChangeset /* Pointer to buffer containing changeset */
  171067. ){
  171068. sqlite3_changeset_iter *pRet; /* Iterator to return */
  171069. int nByte; /* Number of bytes to allocate for iterator */
  171070. assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
  171071. /* Zero the output variable in case an error occurs. */
  171072. *pp = 0;
  171073. /* Allocate and initialize the iterator structure. */
  171074. nByte = sizeof(sqlite3_changeset_iter);
  171075. pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
  171076. if( !pRet ) return SQLITE_NOMEM;
  171077. memset(pRet, 0, sizeof(sqlite3_changeset_iter));
  171078. pRet->in.aData = (u8 *)pChangeset;
  171079. pRet->in.nData = nChangeset;
  171080. pRet->in.xInput = xInput;
  171081. pRet->in.pIn = pIn;
  171082. pRet->in.bEof = (xInput ? 0 : 1);
  171083. /* Populate the output variable and return success. */
  171084. *pp = pRet;
  171085. return SQLITE_OK;
  171086. }
  171087. /*
  171088. ** Create an iterator used to iterate through the contents of a changeset.
  171089. */
  171090. SQLITE_API int sqlite3changeset_start(
  171091. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  171092. int nChangeset, /* Size of buffer pChangeset in bytes */
  171093. void *pChangeset /* Pointer to buffer containing changeset */
  171094. ){
  171095. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
  171096. }
  171097. /*
  171098. ** Streaming version of sqlite3changeset_start().
  171099. */
  171100. SQLITE_API int sqlite3changeset_start_strm(
  171101. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  171102. int (*xInput)(void *pIn, void *pData, int *pnData),
  171103. void *pIn
  171104. ){
  171105. return sessionChangesetStart(pp, xInput, pIn, 0, 0);
  171106. }
  171107. /*
  171108. ** If the SessionInput object passed as the only argument is a streaming
  171109. ** object and the buffer is full, discard some data to free up space.
  171110. */
  171111. static void sessionDiscardData(SessionInput *pIn){
  171112. if( pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
  171113. int nMove = pIn->buf.nBuf - pIn->iNext;
  171114. assert( nMove>=0 );
  171115. if( nMove>0 ){
  171116. memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
  171117. }
  171118. pIn->buf.nBuf -= pIn->iNext;
  171119. pIn->iNext = 0;
  171120. pIn->nData = pIn->buf.nBuf;
  171121. }
  171122. }
  171123. /*
  171124. ** Ensure that there are at least nByte bytes available in the buffer. Or,
  171125. ** if there are not nByte bytes remaining in the input, that all available
  171126. ** data is in the buffer.
  171127. **
  171128. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  171129. */
  171130. static int sessionInputBuffer(SessionInput *pIn, int nByte){
  171131. int rc = SQLITE_OK;
  171132. if( pIn->xInput ){
  171133. while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
  171134. int nNew = SESSIONS_STRM_CHUNK_SIZE;
  171135. if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
  171136. if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
  171137. rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
  171138. if( nNew==0 ){
  171139. pIn->bEof = 1;
  171140. }else{
  171141. pIn->buf.nBuf += nNew;
  171142. }
  171143. }
  171144. pIn->aData = pIn->buf.aBuf;
  171145. pIn->nData = pIn->buf.nBuf;
  171146. }
  171147. }
  171148. return rc;
  171149. }
  171150. /*
  171151. ** When this function is called, *ppRec points to the start of a record
  171152. ** that contains nCol values. This function advances the pointer *ppRec
  171153. ** until it points to the byte immediately following that record.
  171154. */
  171155. static void sessionSkipRecord(
  171156. u8 **ppRec, /* IN/OUT: Record pointer */
  171157. int nCol /* Number of values in record */
  171158. ){
  171159. u8 *aRec = *ppRec;
  171160. int i;
  171161. for(i=0; i<nCol; i++){
  171162. int eType = *aRec++;
  171163. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  171164. int nByte;
  171165. aRec += sessionVarintGet((u8*)aRec, &nByte);
  171166. aRec += nByte;
  171167. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  171168. aRec += 8;
  171169. }
  171170. }
  171171. *ppRec = aRec;
  171172. }
  171173. /*
  171174. ** This function sets the value of the sqlite3_value object passed as the
  171175. ** first argument to a copy of the string or blob held in the aData[]
  171176. ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
  171177. ** error occurs.
  171178. */
  171179. static int sessionValueSetStr(
  171180. sqlite3_value *pVal, /* Set the value of this object */
  171181. u8 *aData, /* Buffer containing string or blob data */
  171182. int nData, /* Size of buffer aData[] in bytes */
  171183. u8 enc /* String encoding (0 for blobs) */
  171184. ){
  171185. /* In theory this code could just pass SQLITE_TRANSIENT as the final
  171186. ** argument to sqlite3ValueSetStr() and have the copy created
  171187. ** automatically. But doing so makes it difficult to detect any OOM
  171188. ** error. Hence the code to create the copy externally. */
  171189. u8 *aCopy = sqlite3_malloc(nData+1);
  171190. if( aCopy==0 ) return SQLITE_NOMEM;
  171191. memcpy(aCopy, aData, nData);
  171192. sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
  171193. return SQLITE_OK;
  171194. }
  171195. /*
  171196. ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
  171197. ** for details.
  171198. **
  171199. ** When this function is called, *paChange points to the start of the record
  171200. ** to deserialize. Assuming no error occurs, *paChange is set to point to
  171201. ** one byte after the end of the same record before this function returns.
  171202. ** If the argument abPK is NULL, then the record contains nCol values. Or,
  171203. ** if abPK is other than NULL, then the record contains only the PK fields
  171204. ** (in other words, it is a patchset DELETE record).
  171205. **
  171206. ** If successful, each element of the apOut[] array (allocated by the caller)
  171207. ** is set to point to an sqlite3_value object containing the value read
  171208. ** from the corresponding position in the record. If that value is not
  171209. ** included in the record (i.e. because the record is part of an UPDATE change
  171210. ** and the field was not modified), the corresponding element of apOut[] is
  171211. ** set to NULL.
  171212. **
  171213. ** It is the responsibility of the caller to free all sqlite_value structures
  171214. ** using sqlite3_free().
  171215. **
  171216. ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  171217. ** The apOut[] array may have been partially populated in this case.
  171218. */
  171219. static int sessionReadRecord(
  171220. SessionInput *pIn, /* Input data */
  171221. int nCol, /* Number of values in record */
  171222. u8 *abPK, /* Array of primary key flags, or NULL */
  171223. sqlite3_value **apOut /* Write values to this array */
  171224. ){
  171225. int i; /* Used to iterate through columns */
  171226. int rc = SQLITE_OK;
  171227. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  171228. int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
  171229. if( abPK && abPK[i]==0 ) continue;
  171230. rc = sessionInputBuffer(pIn, 9);
  171231. if( rc==SQLITE_OK ){
  171232. if( pIn->iNext>=pIn->nData ){
  171233. rc = SQLITE_CORRUPT_BKPT;
  171234. }else{
  171235. eType = pIn->aData[pIn->iNext++];
  171236. assert( apOut[i]==0 );
  171237. if( eType ){
  171238. apOut[i] = sqlite3ValueNew(0);
  171239. if( !apOut[i] ) rc = SQLITE_NOMEM;
  171240. }
  171241. }
  171242. }
  171243. if( rc==SQLITE_OK ){
  171244. u8 *aVal = &pIn->aData[pIn->iNext];
  171245. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  171246. int nByte;
  171247. pIn->iNext += sessionVarintGet(aVal, &nByte);
  171248. rc = sessionInputBuffer(pIn, nByte);
  171249. if( rc==SQLITE_OK ){
  171250. if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
  171251. rc = SQLITE_CORRUPT_BKPT;
  171252. }else{
  171253. u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
  171254. rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
  171255. pIn->iNext += nByte;
  171256. }
  171257. }
  171258. }
  171259. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  171260. sqlite3_int64 v = sessionGetI64(aVal);
  171261. if( eType==SQLITE_INTEGER ){
  171262. sqlite3VdbeMemSetInt64(apOut[i], v);
  171263. }else{
  171264. double d;
  171265. memcpy(&d, &v, 8);
  171266. sqlite3VdbeMemSetDouble(apOut[i], d);
  171267. }
  171268. pIn->iNext += 8;
  171269. }
  171270. }
  171271. }
  171272. return rc;
  171273. }
  171274. /*
  171275. ** The input pointer currently points to the second byte of a table-header.
  171276. ** Specifically, to the following:
  171277. **
  171278. ** + number of columns in table (varint)
  171279. ** + array of PK flags (1 byte per column),
  171280. ** + table name (nul terminated).
  171281. **
  171282. ** This function ensures that all of the above is present in the input
  171283. ** buffer (i.e. that it can be accessed without any calls to xInput()).
  171284. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  171285. ** The input pointer is not moved.
  171286. */
  171287. static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
  171288. int rc = SQLITE_OK;
  171289. int nCol = 0;
  171290. int nRead = 0;
  171291. rc = sessionInputBuffer(pIn, 9);
  171292. if( rc==SQLITE_OK ){
  171293. nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
  171294. /* The hard upper limit for the number of columns in an SQLite
  171295. ** database table is, according to sqliteLimit.h, 32676. So
  171296. ** consider any table-header that purports to have more than 65536
  171297. ** columns to be corrupt. This is convenient because otherwise,
  171298. ** if the (nCol>65536) condition below were omitted, a sufficiently
  171299. ** large value for nCol may cause nRead to wrap around and become
  171300. ** negative. Leading to a crash. */
  171301. if( nCol<0 || nCol>65536 ){
  171302. rc = SQLITE_CORRUPT_BKPT;
  171303. }else{
  171304. rc = sessionInputBuffer(pIn, nRead+nCol+100);
  171305. nRead += nCol;
  171306. }
  171307. }
  171308. while( rc==SQLITE_OK ){
  171309. while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
  171310. nRead++;
  171311. }
  171312. if( (pIn->iNext + nRead)<pIn->nData ) break;
  171313. rc = sessionInputBuffer(pIn, nRead + 100);
  171314. }
  171315. *pnByte = nRead+1;
  171316. return rc;
  171317. }
  171318. /*
  171319. ** The input pointer currently points to the first byte of the first field
  171320. ** of a record consisting of nCol columns. This function ensures the entire
  171321. ** record is buffered. It does not move the input pointer.
  171322. **
  171323. ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
  171324. ** the record in bytes. Otherwise, an SQLite error code is returned. The
  171325. ** final value of *pnByte is undefined in this case.
  171326. */
  171327. static int sessionChangesetBufferRecord(
  171328. SessionInput *pIn, /* Input data */
  171329. int nCol, /* Number of columns in record */
  171330. int *pnByte /* OUT: Size of record in bytes */
  171331. ){
  171332. int rc = SQLITE_OK;
  171333. int nByte = 0;
  171334. int i;
  171335. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  171336. int eType;
  171337. rc = sessionInputBuffer(pIn, nByte + 10);
  171338. if( rc==SQLITE_OK ){
  171339. eType = pIn->aData[pIn->iNext + nByte++];
  171340. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  171341. int n;
  171342. nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
  171343. nByte += n;
  171344. rc = sessionInputBuffer(pIn, nByte);
  171345. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  171346. nByte += 8;
  171347. }
  171348. }
  171349. }
  171350. *pnByte = nByte;
  171351. return rc;
  171352. }
  171353. /*
  171354. ** The input pointer currently points to the second byte of a table-header.
  171355. ** Specifically, to the following:
  171356. **
  171357. ** + number of columns in table (varint)
  171358. ** + array of PK flags (1 byte per column),
  171359. ** + table name (nul terminated).
  171360. **
  171361. ** This function decodes the table-header and populates the p->nCol,
  171362. ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
  171363. ** also allocated or resized according to the new value of p->nCol. The
  171364. ** input pointer is left pointing to the byte following the table header.
  171365. **
  171366. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
  171367. ** is returned and the final values of the various fields enumerated above
  171368. ** are undefined.
  171369. */
  171370. static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
  171371. int rc;
  171372. int nCopy;
  171373. assert( p->rc==SQLITE_OK );
  171374. rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
  171375. if( rc==SQLITE_OK ){
  171376. int nByte;
  171377. int nVarint;
  171378. nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
  171379. if( p->nCol>0 ){
  171380. nCopy -= nVarint;
  171381. p->in.iNext += nVarint;
  171382. nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
  171383. p->tblhdr.nBuf = 0;
  171384. sessionBufferGrow(&p->tblhdr, nByte, &rc);
  171385. }else{
  171386. rc = SQLITE_CORRUPT_BKPT;
  171387. }
  171388. }
  171389. if( rc==SQLITE_OK ){
  171390. int iPK = sizeof(sqlite3_value*)*p->nCol*2;
  171391. memset(p->tblhdr.aBuf, 0, iPK);
  171392. memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
  171393. p->in.iNext += nCopy;
  171394. }
  171395. p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
  171396. p->abPK = (u8*)&p->apValue[p->nCol*2];
  171397. p->zTab = (char*)&p->abPK[p->nCol];
  171398. return (p->rc = rc);
  171399. }
  171400. /*
  171401. ** Advance the changeset iterator to the next change.
  171402. **
  171403. ** If both paRec and pnRec are NULL, then this function works like the public
  171404. ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
  171405. ** sqlite3changeset_new() and old() APIs may be used to query for values.
  171406. **
  171407. ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
  171408. ** record is written to *paRec before returning and the number of bytes in
  171409. ** the record to *pnRec.
  171410. **
  171411. ** Either way, this function returns SQLITE_ROW if the iterator is
  171412. ** successfully advanced to the next change in the changeset, an SQLite
  171413. ** error code if an error occurs, or SQLITE_DONE if there are no further
  171414. ** changes in the changeset.
  171415. */
  171416. static int sessionChangesetNext(
  171417. sqlite3_changeset_iter *p, /* Changeset iterator */
  171418. u8 **paRec, /* If non-NULL, store record pointer here */
  171419. int *pnRec, /* If non-NULL, store size of record here */
  171420. int *pbNew /* If non-NULL, true if new table */
  171421. ){
  171422. int i;
  171423. u8 op;
  171424. assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
  171425. /* If the iterator is in the error-state, return immediately. */
  171426. if( p->rc!=SQLITE_OK ) return p->rc;
  171427. /* Free the current contents of p->apValue[], if any. */
  171428. if( p->apValue ){
  171429. for(i=0; i<p->nCol*2; i++){
  171430. sqlite3ValueFree(p->apValue[i]);
  171431. }
  171432. memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
  171433. }
  171434. /* Make sure the buffer contains at least 10 bytes of input data, or all
  171435. ** remaining data if there are less than 10 bytes available. This is
  171436. ** sufficient either for the 'T' or 'P' byte and the varint that follows
  171437. ** it, or for the two single byte values otherwise. */
  171438. p->rc = sessionInputBuffer(&p->in, 2);
  171439. if( p->rc!=SQLITE_OK ) return p->rc;
  171440. /* If the iterator is already at the end of the changeset, return DONE. */
  171441. if( p->in.iNext>=p->in.nData ){
  171442. return SQLITE_DONE;
  171443. }
  171444. sessionDiscardData(&p->in);
  171445. p->in.iCurrent = p->in.iNext;
  171446. op = p->in.aData[p->in.iNext++];
  171447. while( op=='T' || op=='P' ){
  171448. if( pbNew ) *pbNew = 1;
  171449. p->bPatchset = (op=='P');
  171450. if( sessionChangesetReadTblhdr(p) ) return p->rc;
  171451. if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
  171452. p->in.iCurrent = p->in.iNext;
  171453. if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
  171454. op = p->in.aData[p->in.iNext++];
  171455. }
  171456. if( p->zTab==0 ){
  171457. /* The first record in the changeset is not a table header. Must be a
  171458. ** corrupt changeset. */
  171459. assert( p->in.iNext==1 );
  171460. return (p->rc = SQLITE_CORRUPT_BKPT);
  171461. }
  171462. p->op = op;
  171463. p->bIndirect = p->in.aData[p->in.iNext++];
  171464. if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
  171465. return (p->rc = SQLITE_CORRUPT_BKPT);
  171466. }
  171467. if( paRec ){
  171468. int nVal; /* Number of values to buffer */
  171469. if( p->bPatchset==0 && op==SQLITE_UPDATE ){
  171470. nVal = p->nCol * 2;
  171471. }else if( p->bPatchset && op==SQLITE_DELETE ){
  171472. nVal = 0;
  171473. for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
  171474. }else{
  171475. nVal = p->nCol;
  171476. }
  171477. p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
  171478. if( p->rc!=SQLITE_OK ) return p->rc;
  171479. *paRec = &p->in.aData[p->in.iNext];
  171480. p->in.iNext += *pnRec;
  171481. }else{
  171482. /* If this is an UPDATE or DELETE, read the old.* record. */
  171483. if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
  171484. u8 *abPK = p->bPatchset ? p->abPK : 0;
  171485. p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
  171486. if( p->rc!=SQLITE_OK ) return p->rc;
  171487. }
  171488. /* If this is an INSERT or UPDATE, read the new.* record. */
  171489. if( p->op!=SQLITE_DELETE ){
  171490. p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
  171491. if( p->rc!=SQLITE_OK ) return p->rc;
  171492. }
  171493. if( p->bPatchset && p->op==SQLITE_UPDATE ){
  171494. /* If this is an UPDATE that is part of a patchset, then all PK and
  171495. ** modified fields are present in the new.* record. The old.* record
  171496. ** is currently completely empty. This block shifts the PK fields from
  171497. ** new.* to old.*, to accommodate the code that reads these arrays. */
  171498. for(i=0; i<p->nCol; i++){
  171499. assert( p->apValue[i]==0 );
  171500. if( p->abPK[i] ){
  171501. p->apValue[i] = p->apValue[i+p->nCol];
  171502. if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
  171503. p->apValue[i+p->nCol] = 0;
  171504. }
  171505. }
  171506. }
  171507. }
  171508. return SQLITE_ROW;
  171509. }
  171510. /*
  171511. ** Advance an iterator created by sqlite3changeset_start() to the next
  171512. ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
  171513. ** or SQLITE_CORRUPT.
  171514. **
  171515. ** This function may not be called on iterators passed to a conflict handler
  171516. ** callback by changeset_apply().
  171517. */
  171518. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
  171519. return sessionChangesetNext(p, 0, 0, 0);
  171520. }
  171521. /*
  171522. ** The following function extracts information on the current change
  171523. ** from a changeset iterator. It may only be called after changeset_next()
  171524. ** has returned SQLITE_ROW.
  171525. */
  171526. SQLITE_API int sqlite3changeset_op(
  171527. sqlite3_changeset_iter *pIter, /* Iterator handle */
  171528. const char **pzTab, /* OUT: Pointer to table name */
  171529. int *pnCol, /* OUT: Number of columns in table */
  171530. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  171531. int *pbIndirect /* OUT: True if change is indirect */
  171532. ){
  171533. *pOp = pIter->op;
  171534. *pnCol = pIter->nCol;
  171535. *pzTab = pIter->zTab;
  171536. if( pbIndirect ) *pbIndirect = pIter->bIndirect;
  171537. return SQLITE_OK;
  171538. }
  171539. /*
  171540. ** Return information regarding the PRIMARY KEY and number of columns in
  171541. ** the database table affected by the change that pIter currently points
  171542. ** to. This function may only be called after changeset_next() returns
  171543. ** SQLITE_ROW.
  171544. */
  171545. SQLITE_API int sqlite3changeset_pk(
  171546. sqlite3_changeset_iter *pIter, /* Iterator object */
  171547. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  171548. int *pnCol /* OUT: Number of entries in output array */
  171549. ){
  171550. *pabPK = pIter->abPK;
  171551. if( pnCol ) *pnCol = pIter->nCol;
  171552. return SQLITE_OK;
  171553. }
  171554. /*
  171555. ** This function may only be called while the iterator is pointing to an
  171556. ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
  171557. ** Otherwise, SQLITE_MISUSE is returned.
  171558. **
  171559. ** It sets *ppValue to point to an sqlite3_value structure containing the
  171560. ** iVal'th value in the old.* record. Or, if that particular value is not
  171561. ** included in the record (because the change is an UPDATE and the field
  171562. ** was not modified and is not a PK column), set *ppValue to NULL.
  171563. **
  171564. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  171565. ** not modified. Otherwise, SQLITE_OK.
  171566. */
  171567. SQLITE_API int sqlite3changeset_old(
  171568. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  171569. int iVal, /* Index of old.* value to retrieve */
  171570. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  171571. ){
  171572. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
  171573. return SQLITE_MISUSE;
  171574. }
  171575. if( iVal<0 || iVal>=pIter->nCol ){
  171576. return SQLITE_RANGE;
  171577. }
  171578. *ppValue = pIter->apValue[iVal];
  171579. return SQLITE_OK;
  171580. }
  171581. /*
  171582. ** This function may only be called while the iterator is pointing to an
  171583. ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
  171584. ** Otherwise, SQLITE_MISUSE is returned.
  171585. **
  171586. ** It sets *ppValue to point to an sqlite3_value structure containing the
  171587. ** iVal'th value in the new.* record. Or, if that particular value is not
  171588. ** included in the record (because the change is an UPDATE and the field
  171589. ** was not modified), set *ppValue to NULL.
  171590. **
  171591. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  171592. ** not modified. Otherwise, SQLITE_OK.
  171593. */
  171594. SQLITE_API int sqlite3changeset_new(
  171595. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  171596. int iVal, /* Index of new.* value to retrieve */
  171597. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  171598. ){
  171599. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
  171600. return SQLITE_MISUSE;
  171601. }
  171602. if( iVal<0 || iVal>=pIter->nCol ){
  171603. return SQLITE_RANGE;
  171604. }
  171605. *ppValue = pIter->apValue[pIter->nCol+iVal];
  171606. return SQLITE_OK;
  171607. }
  171608. /*
  171609. ** The following two macros are used internally. They are similar to the
  171610. ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
  171611. ** they omit all error checking and return a pointer to the requested value.
  171612. */
  171613. #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
  171614. #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
  171615. /*
  171616. ** This function may only be called with a changeset iterator that has been
  171617. ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
  171618. ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
  171619. **
  171620. ** If successful, *ppValue is set to point to an sqlite3_value structure
  171621. ** containing the iVal'th value of the conflicting record.
  171622. **
  171623. ** If value iVal is out-of-range or some other error occurs, an SQLite error
  171624. ** code is returned. Otherwise, SQLITE_OK.
  171625. */
  171626. SQLITE_API int sqlite3changeset_conflict(
  171627. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  171628. int iVal, /* Index of conflict record value to fetch */
  171629. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  171630. ){
  171631. if( !pIter->pConflict ){
  171632. return SQLITE_MISUSE;
  171633. }
  171634. if( iVal<0 || iVal>=pIter->nCol ){
  171635. return SQLITE_RANGE;
  171636. }
  171637. *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
  171638. return SQLITE_OK;
  171639. }
  171640. /*
  171641. ** This function may only be called with an iterator passed to an
  171642. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  171643. ** it sets the output variable to the total number of known foreign key
  171644. ** violations in the destination database and returns SQLITE_OK.
  171645. **
  171646. ** In all other cases this function returns SQLITE_MISUSE.
  171647. */
  171648. SQLITE_API int sqlite3changeset_fk_conflicts(
  171649. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  171650. int *pnOut /* OUT: Number of FK violations */
  171651. ){
  171652. if( pIter->pConflict || pIter->apValue ){
  171653. return SQLITE_MISUSE;
  171654. }
  171655. *pnOut = pIter->nCol;
  171656. return SQLITE_OK;
  171657. }
  171658. /*
  171659. ** Finalize an iterator allocated with sqlite3changeset_start().
  171660. **
  171661. ** This function may not be called on iterators passed to a conflict handler
  171662. ** callback by changeset_apply().
  171663. */
  171664. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
  171665. int rc = SQLITE_OK;
  171666. if( p ){
  171667. int i; /* Used to iterate through p->apValue[] */
  171668. rc = p->rc;
  171669. if( p->apValue ){
  171670. for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
  171671. }
  171672. sqlite3_free(p->tblhdr.aBuf);
  171673. sqlite3_free(p->in.buf.aBuf);
  171674. sqlite3_free(p);
  171675. }
  171676. return rc;
  171677. }
  171678. static int sessionChangesetInvert(
  171679. SessionInput *pInput, /* Input changeset */
  171680. int (*xOutput)(void *pOut, const void *pData, int nData),
  171681. void *pOut,
  171682. int *pnInverted, /* OUT: Number of bytes in output changeset */
  171683. void **ppInverted /* OUT: Inverse of pChangeset */
  171684. ){
  171685. int rc = SQLITE_OK; /* Return value */
  171686. SessionBuffer sOut; /* Output buffer */
  171687. int nCol = 0; /* Number of cols in current table */
  171688. u8 *abPK = 0; /* PK array for current table */
  171689. sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
  171690. SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
  171691. /* Initialize the output buffer */
  171692. memset(&sOut, 0, sizeof(SessionBuffer));
  171693. /* Zero the output variables in case an error occurs. */
  171694. if( ppInverted ){
  171695. *ppInverted = 0;
  171696. *pnInverted = 0;
  171697. }
  171698. while( 1 ){
  171699. u8 eType;
  171700. /* Test for EOF. */
  171701. if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
  171702. if( pInput->iNext>=pInput->nData ) break;
  171703. eType = pInput->aData[pInput->iNext];
  171704. switch( eType ){
  171705. case 'T': {
  171706. /* A 'table' record consists of:
  171707. **
  171708. ** * A constant 'T' character,
  171709. ** * Number of columns in said table (a varint),
  171710. ** * An array of nCol bytes (sPK),
  171711. ** * A nul-terminated table name.
  171712. */
  171713. int nByte;
  171714. int nVar;
  171715. pInput->iNext++;
  171716. if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
  171717. goto finished_invert;
  171718. }
  171719. nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
  171720. sPK.nBuf = 0;
  171721. sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
  171722. sessionAppendByte(&sOut, eType, &rc);
  171723. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  171724. if( rc ) goto finished_invert;
  171725. pInput->iNext += nByte;
  171726. sqlite3_free(apVal);
  171727. apVal = 0;
  171728. abPK = sPK.aBuf;
  171729. break;
  171730. }
  171731. case SQLITE_INSERT:
  171732. case SQLITE_DELETE: {
  171733. int nByte;
  171734. int bIndirect = pInput->aData[pInput->iNext+1];
  171735. int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
  171736. pInput->iNext += 2;
  171737. assert( rc==SQLITE_OK );
  171738. rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
  171739. sessionAppendByte(&sOut, eType2, &rc);
  171740. sessionAppendByte(&sOut, bIndirect, &rc);
  171741. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  171742. pInput->iNext += nByte;
  171743. if( rc ) goto finished_invert;
  171744. break;
  171745. }
  171746. case SQLITE_UPDATE: {
  171747. int iCol;
  171748. if( 0==apVal ){
  171749. apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
  171750. if( 0==apVal ){
  171751. rc = SQLITE_NOMEM;
  171752. goto finished_invert;
  171753. }
  171754. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  171755. }
  171756. /* Write the header for the new UPDATE change. Same as the original. */
  171757. sessionAppendByte(&sOut, eType, &rc);
  171758. sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
  171759. /* Read the old.* and new.* records for the update change. */
  171760. pInput->iNext += 2;
  171761. rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
  171762. if( rc==SQLITE_OK ){
  171763. rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
  171764. }
  171765. /* Write the new old.* record. Consists of the PK columns from the
  171766. ** original old.* record, and the other values from the original
  171767. ** new.* record. */
  171768. for(iCol=0; iCol<nCol; iCol++){
  171769. sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
  171770. sessionAppendValue(&sOut, pVal, &rc);
  171771. }
  171772. /* Write the new new.* record. Consists of a copy of all values
  171773. ** from the original old.* record, except for the PK columns, which
  171774. ** are set to "undefined". */
  171775. for(iCol=0; iCol<nCol; iCol++){
  171776. sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
  171777. sessionAppendValue(&sOut, pVal, &rc);
  171778. }
  171779. for(iCol=0; iCol<nCol*2; iCol++){
  171780. sqlite3ValueFree(apVal[iCol]);
  171781. }
  171782. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  171783. if( rc!=SQLITE_OK ){
  171784. goto finished_invert;
  171785. }
  171786. break;
  171787. }
  171788. default:
  171789. rc = SQLITE_CORRUPT_BKPT;
  171790. goto finished_invert;
  171791. }
  171792. assert( rc==SQLITE_OK );
  171793. if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
  171794. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  171795. sOut.nBuf = 0;
  171796. if( rc!=SQLITE_OK ) goto finished_invert;
  171797. }
  171798. }
  171799. assert( rc==SQLITE_OK );
  171800. if( pnInverted ){
  171801. *pnInverted = sOut.nBuf;
  171802. *ppInverted = sOut.aBuf;
  171803. sOut.aBuf = 0;
  171804. }else if( sOut.nBuf>0 ){
  171805. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  171806. }
  171807. finished_invert:
  171808. sqlite3_free(sOut.aBuf);
  171809. sqlite3_free(apVal);
  171810. sqlite3_free(sPK.aBuf);
  171811. return rc;
  171812. }
  171813. /*
  171814. ** Invert a changeset object.
  171815. */
  171816. SQLITE_API int sqlite3changeset_invert(
  171817. int nChangeset, /* Number of bytes in input */
  171818. const void *pChangeset, /* Input changeset */
  171819. int *pnInverted, /* OUT: Number of bytes in output changeset */
  171820. void **ppInverted /* OUT: Inverse of pChangeset */
  171821. ){
  171822. SessionInput sInput;
  171823. /* Set up the input stream */
  171824. memset(&sInput, 0, sizeof(SessionInput));
  171825. sInput.nData = nChangeset;
  171826. sInput.aData = (u8*)pChangeset;
  171827. return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
  171828. }
  171829. /*
  171830. ** Streaming version of sqlite3changeset_invert().
  171831. */
  171832. SQLITE_API int sqlite3changeset_invert_strm(
  171833. int (*xInput)(void *pIn, void *pData, int *pnData),
  171834. void *pIn,
  171835. int (*xOutput)(void *pOut, const void *pData, int nData),
  171836. void *pOut
  171837. ){
  171838. SessionInput sInput;
  171839. int rc;
  171840. /* Set up the input stream */
  171841. memset(&sInput, 0, sizeof(SessionInput));
  171842. sInput.xInput = xInput;
  171843. sInput.pIn = pIn;
  171844. rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
  171845. sqlite3_free(sInput.buf.aBuf);
  171846. return rc;
  171847. }
  171848. typedef struct SessionApplyCtx SessionApplyCtx;
  171849. struct SessionApplyCtx {
  171850. sqlite3 *db;
  171851. sqlite3_stmt *pDelete; /* DELETE statement */
  171852. sqlite3_stmt *pUpdate; /* UPDATE statement */
  171853. sqlite3_stmt *pInsert; /* INSERT statement */
  171854. sqlite3_stmt *pSelect; /* SELECT statement */
  171855. int nCol; /* Size of azCol[] and abPK[] arrays */
  171856. const char **azCol; /* Array of column names */
  171857. u8 *abPK; /* Boolean array - true if column is in PK */
  171858. int bStat1; /* True if table is sqlite_stat1 */
  171859. int bDeferConstraints; /* True to defer constraints */
  171860. SessionBuffer constraints; /* Deferred constraints are stored here */
  171861. SessionBuffer rebase; /* Rebase information (if any) here */
  171862. int bRebaseStarted; /* If table header is already in rebase */
  171863. };
  171864. /*
  171865. ** Formulate a statement to DELETE a row from database db. Assuming a table
  171866. ** structure like this:
  171867. **
  171868. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  171869. **
  171870. ** The DELETE statement looks like this:
  171871. **
  171872. ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
  171873. **
  171874. ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
  171875. ** matching b and d values, or 1 otherwise. The second case comes up if the
  171876. ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
  171877. **
  171878. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
  171879. ** pointing to the prepared version of the SQL statement.
  171880. */
  171881. static int sessionDeleteRow(
  171882. sqlite3 *db, /* Database handle */
  171883. const char *zTab, /* Table name */
  171884. SessionApplyCtx *p /* Session changeset-apply context */
  171885. ){
  171886. int i;
  171887. const char *zSep = "";
  171888. int rc = SQLITE_OK;
  171889. SessionBuffer buf = {0, 0, 0};
  171890. int nPk = 0;
  171891. sessionAppendStr(&buf, "DELETE FROM ", &rc);
  171892. sessionAppendIdent(&buf, zTab, &rc);
  171893. sessionAppendStr(&buf, " WHERE ", &rc);
  171894. for(i=0; i<p->nCol; i++){
  171895. if( p->abPK[i] ){
  171896. nPk++;
  171897. sessionAppendStr(&buf, zSep, &rc);
  171898. sessionAppendIdent(&buf, p->azCol[i], &rc);
  171899. sessionAppendStr(&buf, " = ?", &rc);
  171900. sessionAppendInteger(&buf, i+1, &rc);
  171901. zSep = " AND ";
  171902. }
  171903. }
  171904. if( nPk<p->nCol ){
  171905. sessionAppendStr(&buf, " AND (?", &rc);
  171906. sessionAppendInteger(&buf, p->nCol+1, &rc);
  171907. sessionAppendStr(&buf, " OR ", &rc);
  171908. zSep = "";
  171909. for(i=0; i<p->nCol; i++){
  171910. if( !p->abPK[i] ){
  171911. sessionAppendStr(&buf, zSep, &rc);
  171912. sessionAppendIdent(&buf, p->azCol[i], &rc);
  171913. sessionAppendStr(&buf, " IS ?", &rc);
  171914. sessionAppendInteger(&buf, i+1, &rc);
  171915. zSep = "AND ";
  171916. }
  171917. }
  171918. sessionAppendStr(&buf, ")", &rc);
  171919. }
  171920. if( rc==SQLITE_OK ){
  171921. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
  171922. }
  171923. sqlite3_free(buf.aBuf);
  171924. return rc;
  171925. }
  171926. /*
  171927. ** Formulate and prepare a statement to UPDATE a row from database db.
  171928. ** Assuming a table structure like this:
  171929. **
  171930. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  171931. **
  171932. ** The UPDATE statement looks like this:
  171933. **
  171934. ** UPDATE x SET
  171935. ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
  171936. ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
  171937. ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
  171938. ** d = CASE WHEN ?11 THEN ?12 ELSE d END
  171939. ** WHERE a = ?1 AND c = ?7 AND (?13 OR
  171940. ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
  171941. ** )
  171942. **
  171943. ** For each column in the table, there are three variables to bind:
  171944. **
  171945. ** ?(i*3+1) The old.* value of the column, if any.
  171946. ** ?(i*3+2) A boolean flag indicating that the value is being modified.
  171947. ** ?(i*3+3) The new.* value of the column, if any.
  171948. **
  171949. ** Also, a boolean flag that, if set to true, causes the statement to update
  171950. ** a row even if the non-PK values do not match. This is required if the
  171951. ** conflict-handler is invoked with CHANGESET_DATA and returns
  171952. ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
  171953. **
  171954. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
  171955. ** pointing to the prepared version of the SQL statement.
  171956. */
  171957. static int sessionUpdateRow(
  171958. sqlite3 *db, /* Database handle */
  171959. const char *zTab, /* Table name */
  171960. SessionApplyCtx *p /* Session changeset-apply context */
  171961. ){
  171962. int rc = SQLITE_OK;
  171963. int i;
  171964. const char *zSep = "";
  171965. SessionBuffer buf = {0, 0, 0};
  171966. /* Append "UPDATE tbl SET " */
  171967. sessionAppendStr(&buf, "UPDATE ", &rc);
  171968. sessionAppendIdent(&buf, zTab, &rc);
  171969. sessionAppendStr(&buf, " SET ", &rc);
  171970. /* Append the assignments */
  171971. for(i=0; i<p->nCol; i++){
  171972. sessionAppendStr(&buf, zSep, &rc);
  171973. sessionAppendIdent(&buf, p->azCol[i], &rc);
  171974. sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
  171975. sessionAppendInteger(&buf, i*3+2, &rc);
  171976. sessionAppendStr(&buf, " THEN ?", &rc);
  171977. sessionAppendInteger(&buf, i*3+3, &rc);
  171978. sessionAppendStr(&buf, " ELSE ", &rc);
  171979. sessionAppendIdent(&buf, p->azCol[i], &rc);
  171980. sessionAppendStr(&buf, " END", &rc);
  171981. zSep = ", ";
  171982. }
  171983. /* Append the PK part of the WHERE clause */
  171984. sessionAppendStr(&buf, " WHERE ", &rc);
  171985. for(i=0; i<p->nCol; i++){
  171986. if( p->abPK[i] ){
  171987. sessionAppendIdent(&buf, p->azCol[i], &rc);
  171988. sessionAppendStr(&buf, " = ?", &rc);
  171989. sessionAppendInteger(&buf, i*3+1, &rc);
  171990. sessionAppendStr(&buf, " AND ", &rc);
  171991. }
  171992. }
  171993. /* Append the non-PK part of the WHERE clause */
  171994. sessionAppendStr(&buf, " (?", &rc);
  171995. sessionAppendInteger(&buf, p->nCol*3+1, &rc);
  171996. sessionAppendStr(&buf, " OR 1", &rc);
  171997. for(i=0; i<p->nCol; i++){
  171998. if( !p->abPK[i] ){
  171999. sessionAppendStr(&buf, " AND (?", &rc);
  172000. sessionAppendInteger(&buf, i*3+2, &rc);
  172001. sessionAppendStr(&buf, "=0 OR ", &rc);
  172002. sessionAppendIdent(&buf, p->azCol[i], &rc);
  172003. sessionAppendStr(&buf, " IS ?", &rc);
  172004. sessionAppendInteger(&buf, i*3+1, &rc);
  172005. sessionAppendStr(&buf, ")", &rc);
  172006. }
  172007. }
  172008. sessionAppendStr(&buf, ")", &rc);
  172009. if( rc==SQLITE_OK ){
  172010. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
  172011. }
  172012. sqlite3_free(buf.aBuf);
  172013. return rc;
  172014. }
  172015. /*
  172016. ** Formulate and prepare an SQL statement to query table zTab by primary
  172017. ** key. Assuming the following table structure:
  172018. **
  172019. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  172020. **
  172021. ** The SELECT statement looks like this:
  172022. **
  172023. ** SELECT * FROM x WHERE a = ?1 AND c = ?3
  172024. **
  172025. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
  172026. ** pointing to the prepared version of the SQL statement.
  172027. */
  172028. static int sessionSelectRow(
  172029. sqlite3 *db, /* Database handle */
  172030. const char *zTab, /* Table name */
  172031. SessionApplyCtx *p /* Session changeset-apply context */
  172032. ){
  172033. return sessionSelectStmt(
  172034. db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
  172035. }
  172036. /*
  172037. ** Formulate and prepare an INSERT statement to add a record to table zTab.
  172038. ** For example:
  172039. **
  172040. ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
  172041. **
  172042. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
  172043. ** pointing to the prepared version of the SQL statement.
  172044. */
  172045. static int sessionInsertRow(
  172046. sqlite3 *db, /* Database handle */
  172047. const char *zTab, /* Table name */
  172048. SessionApplyCtx *p /* Session changeset-apply context */
  172049. ){
  172050. int rc = SQLITE_OK;
  172051. int i;
  172052. SessionBuffer buf = {0, 0, 0};
  172053. sessionAppendStr(&buf, "INSERT INTO main.", &rc);
  172054. sessionAppendIdent(&buf, zTab, &rc);
  172055. sessionAppendStr(&buf, "(", &rc);
  172056. for(i=0; i<p->nCol; i++){
  172057. if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
  172058. sessionAppendIdent(&buf, p->azCol[i], &rc);
  172059. }
  172060. sessionAppendStr(&buf, ") VALUES(?", &rc);
  172061. for(i=1; i<p->nCol; i++){
  172062. sessionAppendStr(&buf, ", ?", &rc);
  172063. }
  172064. sessionAppendStr(&buf, ")", &rc);
  172065. if( rc==SQLITE_OK ){
  172066. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
  172067. }
  172068. sqlite3_free(buf.aBuf);
  172069. return rc;
  172070. }
  172071. static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
  172072. return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
  172073. }
  172074. /*
  172075. ** Prepare statements for applying changes to the sqlite_stat1 table.
  172076. ** These are similar to those created by sessionSelectRow(),
  172077. ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
  172078. ** other tables.
  172079. */
  172080. static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
  172081. int rc = sessionSelectRow(db, "sqlite_stat1", p);
  172082. if( rc==SQLITE_OK ){
  172083. rc = sessionPrepare(db, &p->pInsert,
  172084. "INSERT INTO main.sqlite_stat1 VALUES(?1, "
  172085. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
  172086. "?3)"
  172087. );
  172088. }
  172089. if( rc==SQLITE_OK ){
  172090. rc = sessionPrepare(db, &p->pUpdate,
  172091. "UPDATE main.sqlite_stat1 SET "
  172092. "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
  172093. "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
  172094. "stat = CASE WHEN ?8 THEN ?9 ELSE stat END "
  172095. "WHERE tbl=?1 AND idx IS "
  172096. "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
  172097. "AND (?10 OR ?8=0 OR stat IS ?7)"
  172098. );
  172099. }
  172100. if( rc==SQLITE_OK ){
  172101. rc = sessionPrepare(db, &p->pDelete,
  172102. "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
  172103. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
  172104. "AND (?4 OR stat IS ?3)"
  172105. );
  172106. }
  172107. return rc;
  172108. }
  172109. /*
  172110. ** A wrapper around sqlite3_bind_value() that detects an extra problem.
  172111. ** See comments in the body of this function for details.
  172112. */
  172113. static int sessionBindValue(
  172114. sqlite3_stmt *pStmt, /* Statement to bind value to */
  172115. int i, /* Parameter number to bind to */
  172116. sqlite3_value *pVal /* Value to bind */
  172117. ){
  172118. int eType = sqlite3_value_type(pVal);
  172119. /* COVERAGE: The (pVal->z==0) branch is never true using current versions
  172120. ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
  172121. ** the (pVal->z) variable remains as it was or the type of the value is
  172122. ** set to SQLITE_NULL. */
  172123. if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
  172124. /* This condition occurs when an earlier OOM in a call to
  172125. ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
  172126. ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
  172127. return SQLITE_NOMEM;
  172128. }
  172129. return sqlite3_bind_value(pStmt, i, pVal);
  172130. }
  172131. /*
  172132. ** Iterator pIter must point to an SQLITE_INSERT entry. This function
  172133. ** transfers new.* values from the current iterator entry to statement
  172134. ** pStmt. The table being inserted into has nCol columns.
  172135. **
  172136. ** New.* value $i from the iterator is bound to variable ($i+1) of
  172137. ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
  172138. ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
  172139. ** to an array nCol elements in size. In this case only those values for
  172140. ** which abPK[$i] is true are read from the iterator and bound to the
  172141. ** statement.
  172142. **
  172143. ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
  172144. */
  172145. static int sessionBindRow(
  172146. sqlite3_changeset_iter *pIter, /* Iterator to read values from */
  172147. int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
  172148. int nCol, /* Number of columns */
  172149. u8 *abPK, /* If not NULL, bind only if true */
  172150. sqlite3_stmt *pStmt /* Bind values to this statement */
  172151. ){
  172152. int i;
  172153. int rc = SQLITE_OK;
  172154. /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
  172155. ** argument iterator points to a suitable entry. Make sure that xValue
  172156. ** is one of these to guarantee that it is safe to ignore the return
  172157. ** in the code below. */
  172158. assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
  172159. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  172160. if( !abPK || abPK[i] ){
  172161. sqlite3_value *pVal;
  172162. (void)xValue(pIter, i, &pVal);
  172163. if( pVal==0 ){
  172164. /* The value in the changeset was "undefined". This indicates a
  172165. ** corrupt changeset blob. */
  172166. rc = SQLITE_CORRUPT_BKPT;
  172167. }else{
  172168. rc = sessionBindValue(pStmt, i+1, pVal);
  172169. }
  172170. }
  172171. }
  172172. return rc;
  172173. }
  172174. /*
  172175. ** SQL statement pSelect is as generated by the sessionSelectRow() function.
  172176. ** This function binds the primary key values from the change that changeset
  172177. ** iterator pIter points to to the SELECT and attempts to seek to the table
  172178. ** entry. If a row is found, the SELECT statement left pointing at the row
  172179. ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
  172180. ** has occured, the statement is reset and SQLITE_OK is returned. If an
  172181. ** error occurs, the statement is reset and an SQLite error code is returned.
  172182. **
  172183. ** If this function returns SQLITE_ROW, the caller must eventually reset()
  172184. ** statement pSelect. If any other value is returned, the statement does
  172185. ** not require a reset().
  172186. **
  172187. ** If the iterator currently points to an INSERT record, bind values from the
  172188. ** new.* record to the SELECT statement. Or, if it points to a DELETE or
  172189. ** UPDATE, bind values from the old.* record.
  172190. */
  172191. static int sessionSeekToRow(
  172192. sqlite3 *db, /* Database handle */
  172193. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  172194. u8 *abPK, /* Primary key flags array */
  172195. sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
  172196. ){
  172197. int rc; /* Return code */
  172198. int nCol; /* Number of columns in table */
  172199. int op; /* Changset operation (SQLITE_UPDATE etc.) */
  172200. const char *zDummy; /* Unused */
  172201. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  172202. rc = sessionBindRow(pIter,
  172203. op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
  172204. nCol, abPK, pSelect
  172205. );
  172206. if( rc==SQLITE_OK ){
  172207. rc = sqlite3_step(pSelect);
  172208. if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  172209. }
  172210. return rc;
  172211. }
  172212. /*
  172213. ** This function is called from within sqlite3changset_apply_v2() when
  172214. ** a conflict is encountered and resolved using conflict resolution
  172215. ** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
  172216. ** It adds a conflict resolution record to the buffer in
  172217. ** SessionApplyCtx.rebase, which will eventually be returned to the caller
  172218. ** of apply_v2() as the "rebase" buffer.
  172219. **
  172220. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  172221. */
  172222. static int sessionRebaseAdd(
  172223. SessionApplyCtx *p, /* Apply context */
  172224. int eType, /* Conflict resolution (OMIT or REPLACE) */
  172225. sqlite3_changeset_iter *pIter /* Iterator pointing at current change */
  172226. ){
  172227. int rc = SQLITE_OK;
  172228. int i;
  172229. int eOp = pIter->op;
  172230. if( p->bRebaseStarted==0 ){
  172231. /* Append a table-header to the rebase buffer */
  172232. const char *zTab = pIter->zTab;
  172233. sessionAppendByte(&p->rebase, 'T', &rc);
  172234. sessionAppendVarint(&p->rebase, p->nCol, &rc);
  172235. sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
  172236. sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
  172237. p->bRebaseStarted = 1;
  172238. }
  172239. assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
  172240. assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
  172241. sessionAppendByte(&p->rebase,
  172242. (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
  172243. );
  172244. sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
  172245. for(i=0; i<p->nCol; i++){
  172246. sqlite3_value *pVal = 0;
  172247. if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
  172248. sqlite3changeset_old(pIter, i, &pVal);
  172249. }else{
  172250. sqlite3changeset_new(pIter, i, &pVal);
  172251. }
  172252. sessionAppendValue(&p->rebase, pVal, &rc);
  172253. }
  172254. return rc;
  172255. }
  172256. /*
  172257. ** Invoke the conflict handler for the change that the changeset iterator
  172258. ** currently points to.
  172259. **
  172260. ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
  172261. ** If argument pbReplace is NULL, then the type of conflict handler invoked
  172262. ** depends solely on eType, as follows:
  172263. **
  172264. ** eType value Value passed to xConflict
  172265. ** -------------------------------------------------
  172266. ** CHANGESET_DATA CHANGESET_NOTFOUND
  172267. ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
  172268. **
  172269. ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
  172270. ** record with the same primary key as the record about to be deleted, updated
  172271. ** or inserted. If such a record can be found, it is available to the conflict
  172272. ** handler as the "conflicting" record. In this case the type of conflict
  172273. ** handler invoked is as follows:
  172274. **
  172275. ** eType value PK Record found? Value passed to xConflict
  172276. ** ----------------------------------------------------------------
  172277. ** CHANGESET_DATA Yes CHANGESET_DATA
  172278. ** CHANGESET_DATA No CHANGESET_NOTFOUND
  172279. ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
  172280. ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
  172281. **
  172282. ** If pbReplace is not NULL, and a record with a matching PK is found, and
  172283. ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
  172284. ** is set to non-zero before returning SQLITE_OK.
  172285. **
  172286. ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
  172287. ** returned. Or, if the conflict handler returns an invalid value,
  172288. ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
  172289. ** this function returns SQLITE_OK.
  172290. */
  172291. static int sessionConflictHandler(
  172292. int eType, /* Either CHANGESET_DATA or CONFLICT */
  172293. SessionApplyCtx *p, /* changeset_apply() context */
  172294. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  172295. int(*xConflict)(void *, int, sqlite3_changeset_iter*),
  172296. void *pCtx, /* First argument for conflict handler */
  172297. int *pbReplace /* OUT: Set to true if PK row is found */
  172298. ){
  172299. int res = 0; /* Value returned by conflict handler */
  172300. int rc;
  172301. int nCol;
  172302. int op;
  172303. const char *zDummy;
  172304. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  172305. assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  172306. assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  172307. assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
  172308. /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  172309. if( pbReplace ){
  172310. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  172311. }else{
  172312. rc = SQLITE_OK;
  172313. }
  172314. if( rc==SQLITE_ROW ){
  172315. /* There exists another row with the new.* primary key. */
  172316. pIter->pConflict = p->pSelect;
  172317. res = xConflict(pCtx, eType, pIter);
  172318. pIter->pConflict = 0;
  172319. rc = sqlite3_reset(p->pSelect);
  172320. }else if( rc==SQLITE_OK ){
  172321. if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
  172322. /* Instead of invoking the conflict handler, append the change blob
  172323. ** to the SessionApplyCtx.constraints buffer. */
  172324. u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
  172325. int nBlob = pIter->in.iNext - pIter->in.iCurrent;
  172326. sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
  172327. return SQLITE_OK;
  172328. }else{
  172329. /* No other row with the new.* primary key. */
  172330. res = xConflict(pCtx, eType+1, pIter);
  172331. if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
  172332. }
  172333. }
  172334. if( rc==SQLITE_OK ){
  172335. switch( res ){
  172336. case SQLITE_CHANGESET_REPLACE:
  172337. assert( pbReplace );
  172338. *pbReplace = 1;
  172339. break;
  172340. case SQLITE_CHANGESET_OMIT:
  172341. break;
  172342. case SQLITE_CHANGESET_ABORT:
  172343. rc = SQLITE_ABORT;
  172344. break;
  172345. default:
  172346. rc = SQLITE_MISUSE;
  172347. break;
  172348. }
  172349. if( rc==SQLITE_OK ){
  172350. rc = sessionRebaseAdd(p, res, pIter);
  172351. }
  172352. }
  172353. return rc;
  172354. }
  172355. /*
  172356. ** Attempt to apply the change that the iterator passed as the first argument
  172357. ** currently points to to the database. If a conflict is encountered, invoke
  172358. ** the conflict handler callback.
  172359. **
  172360. ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
  172361. ** one is encountered, update or delete the row with the matching primary key
  172362. ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
  172363. ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
  172364. ** to true before returning. In this case the caller will invoke this function
  172365. ** again, this time with pbRetry set to NULL.
  172366. **
  172367. ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
  172368. ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
  172369. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
  172370. ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
  172371. ** before retrying. In this case the caller attempts to remove the conflicting
  172372. ** row before invoking this function again, this time with pbReplace set
  172373. ** to NULL.
  172374. **
  172375. ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
  172376. ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
  172377. ** returned.
  172378. */
  172379. static int sessionApplyOneOp(
  172380. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  172381. SessionApplyCtx *p, /* changeset_apply() context */
  172382. int(*xConflict)(void *, int, sqlite3_changeset_iter *),
  172383. void *pCtx, /* First argument for the conflict handler */
  172384. int *pbReplace, /* OUT: True to remove PK row and retry */
  172385. int *pbRetry /* OUT: True to retry. */
  172386. ){
  172387. const char *zDummy;
  172388. int op;
  172389. int nCol;
  172390. int rc = SQLITE_OK;
  172391. assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
  172392. assert( p->azCol && p->abPK );
  172393. assert( !pbReplace || *pbReplace==0 );
  172394. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  172395. if( op==SQLITE_DELETE ){
  172396. /* Bind values to the DELETE statement. If conflict handling is required,
  172397. ** bind values for all columns and set bound variable (nCol+1) to true.
  172398. ** Or, if conflict handling is not required, bind just the PK column
  172399. ** values and, if it exists, set (nCol+1) to false. Conflict handling
  172400. ** is not required if:
  172401. **
  172402. ** * this is a patchset, or
  172403. ** * (pbRetry==0), or
  172404. ** * all columns of the table are PK columns (in this case there is
  172405. ** no (nCol+1) variable to bind to).
  172406. */
  172407. u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
  172408. rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
  172409. if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
  172410. rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
  172411. }
  172412. if( rc!=SQLITE_OK ) return rc;
  172413. sqlite3_step(p->pDelete);
  172414. rc = sqlite3_reset(p->pDelete);
  172415. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  172416. rc = sessionConflictHandler(
  172417. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  172418. );
  172419. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  172420. rc = sessionConflictHandler(
  172421. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  172422. );
  172423. }
  172424. }else if( op==SQLITE_UPDATE ){
  172425. int i;
  172426. /* Bind values to the UPDATE statement. */
  172427. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  172428. sqlite3_value *pOld = sessionChangesetOld(pIter, i);
  172429. sqlite3_value *pNew = sessionChangesetNew(pIter, i);
  172430. sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
  172431. if( pOld ){
  172432. rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
  172433. }
  172434. if( rc==SQLITE_OK && pNew ){
  172435. rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
  172436. }
  172437. }
  172438. if( rc==SQLITE_OK ){
  172439. sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
  172440. }
  172441. if( rc!=SQLITE_OK ) return rc;
  172442. /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
  172443. ** the result will be SQLITE_OK with 0 rows modified. */
  172444. sqlite3_step(p->pUpdate);
  172445. rc = sqlite3_reset(p->pUpdate);
  172446. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  172447. /* A NOTFOUND or DATA error. Search the table to see if it contains
  172448. ** a row with a matching primary key. If so, this is a DATA conflict.
  172449. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
  172450. rc = sessionConflictHandler(
  172451. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  172452. );
  172453. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  172454. /* This is always a CONSTRAINT conflict. */
  172455. rc = sessionConflictHandler(
  172456. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  172457. );
  172458. }
  172459. }else{
  172460. assert( op==SQLITE_INSERT );
  172461. if( p->bStat1 ){
  172462. /* Check if there is a conflicting row. For sqlite_stat1, this needs
  172463. ** to be done using a SELECT, as there is no PRIMARY KEY in the
  172464. ** database schema to throw an exception if a duplicate is inserted. */
  172465. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  172466. if( rc==SQLITE_ROW ){
  172467. rc = SQLITE_CONSTRAINT;
  172468. sqlite3_reset(p->pSelect);
  172469. }
  172470. }
  172471. if( rc==SQLITE_OK ){
  172472. rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
  172473. if( rc!=SQLITE_OK ) return rc;
  172474. sqlite3_step(p->pInsert);
  172475. rc = sqlite3_reset(p->pInsert);
  172476. }
  172477. if( (rc&0xff)==SQLITE_CONSTRAINT ){
  172478. rc = sessionConflictHandler(
  172479. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
  172480. );
  172481. }
  172482. }
  172483. return rc;
  172484. }
  172485. /*
  172486. ** Attempt to apply the change that the iterator passed as the first argument
  172487. ** currently points to to the database. If a conflict is encountered, invoke
  172488. ** the conflict handler callback.
  172489. **
  172490. ** The difference between this function and sessionApplyOne() is that this
  172491. ** function handles the case where the conflict-handler is invoked and
  172492. ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
  172493. ** retried in some manner.
  172494. */
  172495. static int sessionApplyOneWithRetry(
  172496. sqlite3 *db, /* Apply change to "main" db of this handle */
  172497. sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
  172498. SessionApplyCtx *pApply, /* Apply context */
  172499. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  172500. void *pCtx /* First argument passed to xConflict */
  172501. ){
  172502. int bReplace = 0;
  172503. int bRetry = 0;
  172504. int rc;
  172505. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
  172506. if( rc==SQLITE_OK ){
  172507. /* If the bRetry flag is set, the change has not been applied due to an
  172508. ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
  172509. ** a row with the correct PK is present in the db, but one or more other
  172510. ** fields do not contain the expected values) and the conflict handler
  172511. ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
  172512. ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
  172513. ** the SQLITE_CHANGESET_DATA problem. */
  172514. if( bRetry ){
  172515. assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
  172516. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  172517. }
  172518. /* If the bReplace flag is set, the change is an INSERT that has not
  172519. ** been performed because the database already contains a row with the
  172520. ** specified primary key and the conflict handler returned
  172521. ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
  172522. ** before reattempting the INSERT. */
  172523. else if( bReplace ){
  172524. assert( pIter->op==SQLITE_INSERT );
  172525. rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
  172526. if( rc==SQLITE_OK ){
  172527. rc = sessionBindRow(pIter,
  172528. sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
  172529. sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
  172530. }
  172531. if( rc==SQLITE_OK ){
  172532. sqlite3_step(pApply->pDelete);
  172533. rc = sqlite3_reset(pApply->pDelete);
  172534. }
  172535. if( rc==SQLITE_OK ){
  172536. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  172537. }
  172538. if( rc==SQLITE_OK ){
  172539. rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
  172540. }
  172541. }
  172542. }
  172543. return rc;
  172544. }
  172545. /*
  172546. ** Retry the changes accumulated in the pApply->constraints buffer.
  172547. */
  172548. static int sessionRetryConstraints(
  172549. sqlite3 *db,
  172550. int bPatchset,
  172551. const char *zTab,
  172552. SessionApplyCtx *pApply,
  172553. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  172554. void *pCtx /* First argument passed to xConflict */
  172555. ){
  172556. int rc = SQLITE_OK;
  172557. while( pApply->constraints.nBuf ){
  172558. sqlite3_changeset_iter *pIter2 = 0;
  172559. SessionBuffer cons = pApply->constraints;
  172560. memset(&pApply->constraints, 0, sizeof(SessionBuffer));
  172561. rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
  172562. if( rc==SQLITE_OK ){
  172563. int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
  172564. int rc2;
  172565. pIter2->bPatchset = bPatchset;
  172566. pIter2->zTab = (char*)zTab;
  172567. pIter2->nCol = pApply->nCol;
  172568. pIter2->abPK = pApply->abPK;
  172569. sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
  172570. pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
  172571. if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
  172572. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
  172573. rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
  172574. }
  172575. rc2 = sqlite3changeset_finalize(pIter2);
  172576. if( rc==SQLITE_OK ) rc = rc2;
  172577. }
  172578. assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
  172579. sqlite3_free(cons.aBuf);
  172580. if( rc!=SQLITE_OK ) break;
  172581. if( pApply->constraints.nBuf>=cons.nBuf ){
  172582. /* No progress was made on the last round. */
  172583. pApply->bDeferConstraints = 0;
  172584. }
  172585. }
  172586. return rc;
  172587. }
  172588. /*
  172589. ** Argument pIter is a changeset iterator that has been initialized, but
  172590. ** not yet passed to sqlite3changeset_next(). This function applies the
  172591. ** changeset to the main database attached to handle "db". The supplied
  172592. ** conflict handler callback is invoked to resolve any conflicts encountered
  172593. ** while applying the change.
  172594. */
  172595. static int sessionChangesetApply(
  172596. sqlite3 *db, /* Apply change to "main" db of this handle */
  172597. sqlite3_changeset_iter *pIter, /* Changeset to apply */
  172598. int(*xFilter)(
  172599. void *pCtx, /* Copy of sixth arg to _apply() */
  172600. const char *zTab /* Table name */
  172601. ),
  172602. int(*xConflict)(
  172603. void *pCtx, /* Copy of fifth arg to _apply() */
  172604. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  172605. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  172606. ),
  172607. void *pCtx, /* First argument passed to xConflict */
  172608. void **ppRebase, int *pnRebase, /* OUT: Rebase information */
  172609. int flags /* SESSION_APPLY_XXX flags */
  172610. ){
  172611. int schemaMismatch = 0;
  172612. int rc = SQLITE_OK; /* Return code */
  172613. const char *zTab = 0; /* Name of current table */
  172614. int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
  172615. SessionApplyCtx sApply; /* changeset_apply() context object */
  172616. int bPatchset;
  172617. assert( xConflict!=0 );
  172618. pIter->in.bNoDiscard = 1;
  172619. memset(&sApply, 0, sizeof(sApply));
  172620. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  172621. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  172622. rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  172623. }
  172624. if( rc==SQLITE_OK ){
  172625. rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  172626. }
  172627. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
  172628. int nCol;
  172629. int op;
  172630. const char *zNew;
  172631. sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
  172632. if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
  172633. u8 *abPK;
  172634. rc = sessionRetryConstraints(
  172635. db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
  172636. );
  172637. if( rc!=SQLITE_OK ) break;
  172638. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  172639. sqlite3_finalize(sApply.pDelete);
  172640. sqlite3_finalize(sApply.pUpdate);
  172641. sqlite3_finalize(sApply.pInsert);
  172642. sqlite3_finalize(sApply.pSelect);
  172643. sApply.db = db;
  172644. sApply.pDelete = 0;
  172645. sApply.pUpdate = 0;
  172646. sApply.pInsert = 0;
  172647. sApply.pSelect = 0;
  172648. sApply.nCol = 0;
  172649. sApply.azCol = 0;
  172650. sApply.abPK = 0;
  172651. sApply.bStat1 = 0;
  172652. sApply.bDeferConstraints = 1;
  172653. sApply.bRebaseStarted = 0;
  172654. memset(&sApply.constraints, 0, sizeof(SessionBuffer));
  172655. /* If an xFilter() callback was specified, invoke it now. If the
  172656. ** xFilter callback returns zero, skip this table. If it returns
  172657. ** non-zero, proceed. */
  172658. schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
  172659. if( schemaMismatch ){
  172660. zTab = sqlite3_mprintf("%s", zNew);
  172661. if( zTab==0 ){
  172662. rc = SQLITE_NOMEM;
  172663. break;
  172664. }
  172665. nTab = (int)strlen(zTab);
  172666. sApply.azCol = (const char **)zTab;
  172667. }else{
  172668. int nMinCol = 0;
  172669. int i;
  172670. sqlite3changeset_pk(pIter, &abPK, 0);
  172671. rc = sessionTableInfo(
  172672. db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
  172673. );
  172674. if( rc!=SQLITE_OK ) break;
  172675. for(i=0; i<sApply.nCol; i++){
  172676. if( sApply.abPK[i] ) nMinCol = i+1;
  172677. }
  172678. if( sApply.nCol==0 ){
  172679. schemaMismatch = 1;
  172680. sqlite3_log(SQLITE_SCHEMA,
  172681. "sqlite3changeset_apply(): no such table: %s", zTab
  172682. );
  172683. }
  172684. else if( sApply.nCol<nCol ){
  172685. schemaMismatch = 1;
  172686. sqlite3_log(SQLITE_SCHEMA,
  172687. "sqlite3changeset_apply(): table %s has %d columns, "
  172688. "expected %d or more",
  172689. zTab, sApply.nCol, nCol
  172690. );
  172691. }
  172692. else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
  172693. schemaMismatch = 1;
  172694. sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
  172695. "primary key mismatch for table %s", zTab
  172696. );
  172697. }
  172698. else{
  172699. sApply.nCol = nCol;
  172700. if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
  172701. if( (rc = sessionStat1Sql(db, &sApply) ) ){
  172702. break;
  172703. }
  172704. sApply.bStat1 = 1;
  172705. }else{
  172706. if((rc = sessionSelectRow(db, zTab, &sApply))
  172707. || (rc = sessionUpdateRow(db, zTab, &sApply))
  172708. || (rc = sessionDeleteRow(db, zTab, &sApply))
  172709. || (rc = sessionInsertRow(db, zTab, &sApply))
  172710. ){
  172711. break;
  172712. }
  172713. sApply.bStat1 = 0;
  172714. }
  172715. }
  172716. nTab = sqlite3Strlen30(zTab);
  172717. }
  172718. }
  172719. /* If there is a schema mismatch on the current table, proceed to the
  172720. ** next change. A log message has already been issued. */
  172721. if( schemaMismatch ) continue;
  172722. rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
  172723. }
  172724. bPatchset = pIter->bPatchset;
  172725. if( rc==SQLITE_OK ){
  172726. rc = sqlite3changeset_finalize(pIter);
  172727. }else{
  172728. sqlite3changeset_finalize(pIter);
  172729. }
  172730. if( rc==SQLITE_OK ){
  172731. rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
  172732. }
  172733. if( rc==SQLITE_OK ){
  172734. int nFk, notUsed;
  172735. sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
  172736. if( nFk!=0 ){
  172737. int res = SQLITE_CHANGESET_ABORT;
  172738. sqlite3_changeset_iter sIter;
  172739. memset(&sIter, 0, sizeof(sIter));
  172740. sIter.nCol = nFk;
  172741. res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
  172742. if( res!=SQLITE_CHANGESET_OMIT ){
  172743. rc = SQLITE_CONSTRAINT;
  172744. }
  172745. }
  172746. }
  172747. sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
  172748. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  172749. if( rc==SQLITE_OK ){
  172750. rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  172751. }else{
  172752. sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
  172753. sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  172754. }
  172755. }
  172756. if( rc==SQLITE_OK && bPatchset==0 && ppRebase && pnRebase ){
  172757. *ppRebase = (void*)sApply.rebase.aBuf;
  172758. *pnRebase = sApply.rebase.nBuf;
  172759. sApply.rebase.aBuf = 0;
  172760. }
  172761. sqlite3_finalize(sApply.pInsert);
  172762. sqlite3_finalize(sApply.pDelete);
  172763. sqlite3_finalize(sApply.pUpdate);
  172764. sqlite3_finalize(sApply.pSelect);
  172765. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  172766. sqlite3_free((char*)sApply.constraints.aBuf);
  172767. sqlite3_free((char*)sApply.rebase.aBuf);
  172768. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  172769. return rc;
  172770. }
  172771. /*
  172772. ** Apply the changeset passed via pChangeset/nChangeset to the main
  172773. ** database attached to handle "db".
  172774. */
  172775. SQLITE_API int sqlite3changeset_apply_v2(
  172776. sqlite3 *db, /* Apply change to "main" db of this handle */
  172777. int nChangeset, /* Size of changeset in bytes */
  172778. void *pChangeset, /* Changeset blob */
  172779. int(*xFilter)(
  172780. void *pCtx, /* Copy of sixth arg to _apply() */
  172781. const char *zTab /* Table name */
  172782. ),
  172783. int(*xConflict)(
  172784. void *pCtx, /* Copy of sixth arg to _apply() */
  172785. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  172786. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  172787. ),
  172788. void *pCtx, /* First argument passed to xConflict */
  172789. void **ppRebase, int *pnRebase,
  172790. int flags
  172791. ){
  172792. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  172793. int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
  172794. if( rc==SQLITE_OK ){
  172795. rc = sessionChangesetApply(
  172796. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  172797. );
  172798. }
  172799. return rc;
  172800. }
  172801. /*
  172802. ** Apply the changeset passed via pChangeset/nChangeset to the main database
  172803. ** attached to handle "db". Invoke the supplied conflict handler callback
  172804. ** to resolve any conflicts encountered while applying the change.
  172805. */
  172806. SQLITE_API int sqlite3changeset_apply(
  172807. sqlite3 *db, /* Apply change to "main" db of this handle */
  172808. int nChangeset, /* Size of changeset in bytes */
  172809. void *pChangeset, /* Changeset blob */
  172810. int(*xFilter)(
  172811. void *pCtx, /* Copy of sixth arg to _apply() */
  172812. const char *zTab /* Table name */
  172813. ),
  172814. int(*xConflict)(
  172815. void *pCtx, /* Copy of fifth arg to _apply() */
  172816. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  172817. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  172818. ),
  172819. void *pCtx /* First argument passed to xConflict */
  172820. ){
  172821. return sqlite3changeset_apply_v2(
  172822. db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
  172823. );
  172824. }
  172825. /*
  172826. ** Apply the changeset passed via xInput/pIn to the main database
  172827. ** attached to handle "db". Invoke the supplied conflict handler callback
  172828. ** to resolve any conflicts encountered while applying the change.
  172829. */
  172830. SQLITE_API int sqlite3changeset_apply_v2_strm(
  172831. sqlite3 *db, /* Apply change to "main" db of this handle */
  172832. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  172833. void *pIn, /* First arg for xInput */
  172834. int(*xFilter)(
  172835. void *pCtx, /* Copy of sixth arg to _apply() */
  172836. const char *zTab /* Table name */
  172837. ),
  172838. int(*xConflict)(
  172839. void *pCtx, /* Copy of sixth arg to _apply() */
  172840. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  172841. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  172842. ),
  172843. void *pCtx, /* First argument passed to xConflict */
  172844. void **ppRebase, int *pnRebase,
  172845. int flags
  172846. ){
  172847. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  172848. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  172849. if( rc==SQLITE_OK ){
  172850. rc = sessionChangesetApply(
  172851. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  172852. );
  172853. }
  172854. return rc;
  172855. }
  172856. SQLITE_API int sqlite3changeset_apply_strm(
  172857. sqlite3 *db, /* Apply change to "main" db of this handle */
  172858. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  172859. void *pIn, /* First arg for xInput */
  172860. int(*xFilter)(
  172861. void *pCtx, /* Copy of sixth arg to _apply() */
  172862. const char *zTab /* Table name */
  172863. ),
  172864. int(*xConflict)(
  172865. void *pCtx, /* Copy of sixth arg to _apply() */
  172866. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  172867. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  172868. ),
  172869. void *pCtx /* First argument passed to xConflict */
  172870. ){
  172871. return sqlite3changeset_apply_v2_strm(
  172872. db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
  172873. );
  172874. }
  172875. /*
  172876. ** sqlite3_changegroup handle.
  172877. */
  172878. struct sqlite3_changegroup {
  172879. int rc; /* Error code */
  172880. int bPatch; /* True to accumulate patchsets */
  172881. SessionTable *pList; /* List of tables in current patch */
  172882. };
  172883. /*
  172884. ** This function is called to merge two changes to the same row together as
  172885. ** part of an sqlite3changeset_concat() operation. A new change object is
  172886. ** allocated and a pointer to it stored in *ppNew.
  172887. */
  172888. static int sessionChangeMerge(
  172889. SessionTable *pTab, /* Table structure */
  172890. int bRebase, /* True for a rebase hash-table */
  172891. int bPatchset, /* True for patchsets */
  172892. SessionChange *pExist, /* Existing change */
  172893. int op2, /* Second change operation */
  172894. int bIndirect, /* True if second change is indirect */
  172895. u8 *aRec, /* Second change record */
  172896. int nRec, /* Number of bytes in aRec */
  172897. SessionChange **ppNew /* OUT: Merged change */
  172898. ){
  172899. SessionChange *pNew = 0;
  172900. int rc = SQLITE_OK;
  172901. if( !pExist ){
  172902. pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
  172903. if( !pNew ){
  172904. return SQLITE_NOMEM;
  172905. }
  172906. memset(pNew, 0, sizeof(SessionChange));
  172907. pNew->op = op2;
  172908. pNew->bIndirect = bIndirect;
  172909. pNew->aRecord = (u8*)&pNew[1];
  172910. if( bIndirect==0 || bRebase==0 ){
  172911. pNew->nRecord = nRec;
  172912. memcpy(pNew->aRecord, aRec, nRec);
  172913. }else{
  172914. int i;
  172915. u8 *pIn = aRec;
  172916. u8 *pOut = pNew->aRecord;
  172917. for(i=0; i<pTab->nCol; i++){
  172918. int nIn = sessionSerialLen(pIn);
  172919. if( *pIn==0 ){
  172920. *pOut++ = 0;
  172921. }else if( pTab->abPK[i]==0 ){
  172922. *pOut++ = 0xFF;
  172923. }else{
  172924. memcpy(pOut, pIn, nIn);
  172925. pOut += nIn;
  172926. }
  172927. pIn += nIn;
  172928. }
  172929. pNew->nRecord = pOut - pNew->aRecord;
  172930. }
  172931. }else if( bRebase ){
  172932. if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
  172933. *ppNew = pExist;
  172934. }else{
  172935. int nByte = nRec + pExist->nRecord + sizeof(SessionChange);
  172936. pNew = (SessionChange*)sqlite3_malloc(nByte);
  172937. if( pNew==0 ){
  172938. rc = SQLITE_NOMEM;
  172939. }else{
  172940. int i;
  172941. u8 *a1 = pExist->aRecord;
  172942. u8 *a2 = aRec;
  172943. u8 *pOut;
  172944. memset(pNew, 0, nByte);
  172945. pNew->bIndirect = bIndirect || pExist->bIndirect;
  172946. pNew->op = op2;
  172947. pOut = pNew->aRecord = (u8*)&pNew[1];
  172948. for(i=0; i<pTab->nCol; i++){
  172949. int n1 = sessionSerialLen(a1);
  172950. int n2 = sessionSerialLen(a2);
  172951. if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
  172952. *pOut++ = 0xFF;
  172953. }else if( *a2==0 ){
  172954. memcpy(pOut, a1, n1);
  172955. pOut += n1;
  172956. }else{
  172957. memcpy(pOut, a2, n2);
  172958. pOut += n2;
  172959. }
  172960. a1 += n1;
  172961. a2 += n2;
  172962. }
  172963. pNew->nRecord = pOut - pNew->aRecord;
  172964. }
  172965. sqlite3_free(pExist);
  172966. }
  172967. }else{
  172968. int op1 = pExist->op;
  172969. /*
  172970. ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
  172971. ** op1=INSERT, op2=UPDATE -> INSERT.
  172972. ** op1=INSERT, op2=DELETE -> (none)
  172973. **
  172974. ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
  172975. ** op1=UPDATE, op2=UPDATE -> UPDATE.
  172976. ** op1=UPDATE, op2=DELETE -> DELETE.
  172977. **
  172978. ** op1=DELETE, op2=INSERT -> UPDATE.
  172979. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
  172980. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
  172981. */
  172982. if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
  172983. || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
  172984. || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
  172985. || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
  172986. ){
  172987. pNew = pExist;
  172988. }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
  172989. sqlite3_free(pExist);
  172990. assert( pNew==0 );
  172991. }else{
  172992. u8 *aExist = pExist->aRecord;
  172993. int nByte;
  172994. u8 *aCsr;
  172995. /* Allocate a new SessionChange object. Ensure that the aRecord[]
  172996. ** buffer of the new object is large enough to hold any record that
  172997. ** may be generated by combining the input records. */
  172998. nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
  172999. pNew = (SessionChange *)sqlite3_malloc(nByte);
  173000. if( !pNew ){
  173001. sqlite3_free(pExist);
  173002. return SQLITE_NOMEM;
  173003. }
  173004. memset(pNew, 0, sizeof(SessionChange));
  173005. pNew->bIndirect = (bIndirect && pExist->bIndirect);
  173006. aCsr = pNew->aRecord = (u8 *)&pNew[1];
  173007. if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
  173008. u8 *a1 = aRec;
  173009. assert( op2==SQLITE_UPDATE );
  173010. pNew->op = SQLITE_INSERT;
  173011. if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
  173012. sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
  173013. }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
  173014. assert( op2==SQLITE_INSERT );
  173015. pNew->op = SQLITE_UPDATE;
  173016. if( bPatchset ){
  173017. memcpy(aCsr, aRec, nRec);
  173018. aCsr += nRec;
  173019. }else{
  173020. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
  173021. sqlite3_free(pNew);
  173022. pNew = 0;
  173023. }
  173024. }
  173025. }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
  173026. u8 *a1 = aExist;
  173027. u8 *a2 = aRec;
  173028. assert( op1==SQLITE_UPDATE );
  173029. if( bPatchset==0 ){
  173030. sessionSkipRecord(&a1, pTab->nCol);
  173031. sessionSkipRecord(&a2, pTab->nCol);
  173032. }
  173033. pNew->op = SQLITE_UPDATE;
  173034. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
  173035. sqlite3_free(pNew);
  173036. pNew = 0;
  173037. }
  173038. }else{ /* UPDATE + DELETE */
  173039. assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
  173040. pNew->op = SQLITE_DELETE;
  173041. if( bPatchset ){
  173042. memcpy(aCsr, aRec, nRec);
  173043. aCsr += nRec;
  173044. }else{
  173045. sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
  173046. }
  173047. }
  173048. if( pNew ){
  173049. pNew->nRecord = (int)(aCsr - pNew->aRecord);
  173050. }
  173051. sqlite3_free(pExist);
  173052. }
  173053. }
  173054. *ppNew = pNew;
  173055. return rc;
  173056. }
  173057. /*
  173058. ** Add all changes in the changeset traversed by the iterator passed as
  173059. ** the first argument to the changegroup hash tables.
  173060. */
  173061. static int sessionChangesetToHash(
  173062. sqlite3_changeset_iter *pIter, /* Iterator to read from */
  173063. sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */
  173064. int bRebase /* True if hash table is for rebasing */
  173065. ){
  173066. u8 *aRec;
  173067. int nRec;
  173068. int rc = SQLITE_OK;
  173069. SessionTable *pTab = 0;
  173070. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
  173071. const char *zNew;
  173072. int nCol;
  173073. int op;
  173074. int iHash;
  173075. int bIndirect;
  173076. SessionChange *pChange;
  173077. SessionChange *pExist = 0;
  173078. SessionChange **pp;
  173079. if( pGrp->pList==0 ){
  173080. pGrp->bPatch = pIter->bPatchset;
  173081. }else if( pIter->bPatchset!=pGrp->bPatch ){
  173082. rc = SQLITE_ERROR;
  173083. break;
  173084. }
  173085. sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
  173086. if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
  173087. /* Search the list for a matching table */
  173088. int nNew = (int)strlen(zNew);
  173089. u8 *abPK;
  173090. sqlite3changeset_pk(pIter, &abPK, 0);
  173091. for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
  173092. if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
  173093. }
  173094. if( !pTab ){
  173095. SessionTable **ppTab;
  173096. pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
  173097. if( !pTab ){
  173098. rc = SQLITE_NOMEM;
  173099. break;
  173100. }
  173101. memset(pTab, 0, sizeof(SessionTable));
  173102. pTab->nCol = nCol;
  173103. pTab->abPK = (u8*)&pTab[1];
  173104. memcpy(pTab->abPK, abPK, nCol);
  173105. pTab->zName = (char*)&pTab->abPK[nCol];
  173106. memcpy(pTab->zName, zNew, nNew+1);
  173107. /* The new object must be linked on to the end of the list, not
  173108. ** simply added to the start of it. This is to ensure that the
  173109. ** tables within the output of sqlite3changegroup_output() are in
  173110. ** the right order. */
  173111. for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
  173112. *ppTab = pTab;
  173113. }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
  173114. rc = SQLITE_SCHEMA;
  173115. break;
  173116. }
  173117. }
  173118. if( sessionGrowHash(pIter->bPatchset, pTab) ){
  173119. rc = SQLITE_NOMEM;
  173120. break;
  173121. }
  173122. iHash = sessionChangeHash(
  173123. pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
  173124. );
  173125. /* Search for existing entry. If found, remove it from the hash table.
  173126. ** Code below may link it back in.
  173127. */
  173128. for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
  173129. int bPkOnly1 = 0;
  173130. int bPkOnly2 = 0;
  173131. if( pIter->bPatchset ){
  173132. bPkOnly1 = (*pp)->op==SQLITE_DELETE;
  173133. bPkOnly2 = op==SQLITE_DELETE;
  173134. }
  173135. if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
  173136. pExist = *pp;
  173137. *pp = (*pp)->pNext;
  173138. pTab->nEntry--;
  173139. break;
  173140. }
  173141. }
  173142. rc = sessionChangeMerge(pTab, bRebase,
  173143. pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
  173144. );
  173145. if( rc ) break;
  173146. if( pChange ){
  173147. pChange->pNext = pTab->apChange[iHash];
  173148. pTab->apChange[iHash] = pChange;
  173149. pTab->nEntry++;
  173150. }
  173151. }
  173152. if( rc==SQLITE_OK ) rc = pIter->rc;
  173153. return rc;
  173154. }
  173155. /*
  173156. ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
  173157. ** added to the changegroup object passed as the first argument.
  173158. **
  173159. ** If xOutput is not NULL, then the changeset/patchset is returned to the
  173160. ** user via one or more calls to xOutput, as with the other streaming
  173161. ** interfaces.
  173162. **
  173163. ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
  173164. ** buffer containing the output changeset before this function returns. In
  173165. ** this case (*pnOut) is set to the size of the output buffer in bytes. It
  173166. ** is the responsibility of the caller to free the output buffer using
  173167. ** sqlite3_free() when it is no longer required.
  173168. **
  173169. ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
  173170. ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
  173171. ** are both set to 0 before returning.
  173172. */
  173173. static int sessionChangegroupOutput(
  173174. sqlite3_changegroup *pGrp,
  173175. int (*xOutput)(void *pOut, const void *pData, int nData),
  173176. void *pOut,
  173177. int *pnOut,
  173178. void **ppOut
  173179. ){
  173180. int rc = SQLITE_OK;
  173181. SessionBuffer buf = {0, 0, 0};
  173182. SessionTable *pTab;
  173183. assert( xOutput==0 || (ppOut==0 && pnOut==0) );
  173184. /* Create the serialized output changeset based on the contents of the
  173185. ** hash tables attached to the SessionTable objects in list p->pList.
  173186. */
  173187. for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  173188. int i;
  173189. if( pTab->nEntry==0 ) continue;
  173190. sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
  173191. for(i=0; i<pTab->nChange; i++){
  173192. SessionChange *p;
  173193. for(p=pTab->apChange[i]; p; p=p->pNext){
  173194. sessionAppendByte(&buf, p->op, &rc);
  173195. sessionAppendByte(&buf, p->bIndirect, &rc);
  173196. sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
  173197. }
  173198. }
  173199. if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
  173200. rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  173201. buf.nBuf = 0;
  173202. }
  173203. }
  173204. if( rc==SQLITE_OK ){
  173205. if( xOutput ){
  173206. if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  173207. }else{
  173208. *ppOut = buf.aBuf;
  173209. *pnOut = buf.nBuf;
  173210. buf.aBuf = 0;
  173211. }
  173212. }
  173213. sqlite3_free(buf.aBuf);
  173214. return rc;
  173215. }
  173216. /*
  173217. ** Allocate a new, empty, sqlite3_changegroup.
  173218. */
  173219. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
  173220. int rc = SQLITE_OK; /* Return code */
  173221. sqlite3_changegroup *p; /* New object */
  173222. p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
  173223. if( p==0 ){
  173224. rc = SQLITE_NOMEM;
  173225. }else{
  173226. memset(p, 0, sizeof(sqlite3_changegroup));
  173227. }
  173228. *pp = p;
  173229. return rc;
  173230. }
  173231. /*
  173232. ** Add the changeset currently stored in buffer pData, size nData bytes,
  173233. ** to changeset-group p.
  173234. */
  173235. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
  173236. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  173237. int rc; /* Return code */
  173238. rc = sqlite3changeset_start(&pIter, nData, pData);
  173239. if( rc==SQLITE_OK ){
  173240. rc = sessionChangesetToHash(pIter, pGrp, 0);
  173241. }
  173242. sqlite3changeset_finalize(pIter);
  173243. return rc;
  173244. }
  173245. /*
  173246. ** Obtain a buffer containing a changeset representing the concatenation
  173247. ** of all changesets added to the group so far.
  173248. */
  173249. SQLITE_API int sqlite3changegroup_output(
  173250. sqlite3_changegroup *pGrp,
  173251. int *pnData,
  173252. void **ppData
  173253. ){
  173254. return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
  173255. }
  173256. /*
  173257. ** Streaming versions of changegroup_add().
  173258. */
  173259. SQLITE_API int sqlite3changegroup_add_strm(
  173260. sqlite3_changegroup *pGrp,
  173261. int (*xInput)(void *pIn, void *pData, int *pnData),
  173262. void *pIn
  173263. ){
  173264. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  173265. int rc; /* Return code */
  173266. rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  173267. if( rc==SQLITE_OK ){
  173268. rc = sessionChangesetToHash(pIter, pGrp, 0);
  173269. }
  173270. sqlite3changeset_finalize(pIter);
  173271. return rc;
  173272. }
  173273. /*
  173274. ** Streaming versions of changegroup_output().
  173275. */
  173276. SQLITE_API int sqlite3changegroup_output_strm(
  173277. sqlite3_changegroup *pGrp,
  173278. int (*xOutput)(void *pOut, const void *pData, int nData),
  173279. void *pOut
  173280. ){
  173281. return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
  173282. }
  173283. /*
  173284. ** Delete a changegroup object.
  173285. */
  173286. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
  173287. if( pGrp ){
  173288. sessionDeleteTable(pGrp->pList);
  173289. sqlite3_free(pGrp);
  173290. }
  173291. }
  173292. /*
  173293. ** Combine two changesets together.
  173294. */
  173295. SQLITE_API int sqlite3changeset_concat(
  173296. int nLeft, /* Number of bytes in lhs input */
  173297. void *pLeft, /* Lhs input changeset */
  173298. int nRight /* Number of bytes in rhs input */,
  173299. void *pRight, /* Rhs input changeset */
  173300. int *pnOut, /* OUT: Number of bytes in output changeset */
  173301. void **ppOut /* OUT: changeset (left <concat> right) */
  173302. ){
  173303. sqlite3_changegroup *pGrp;
  173304. int rc;
  173305. rc = sqlite3changegroup_new(&pGrp);
  173306. if( rc==SQLITE_OK ){
  173307. rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
  173308. }
  173309. if( rc==SQLITE_OK ){
  173310. rc = sqlite3changegroup_add(pGrp, nRight, pRight);
  173311. }
  173312. if( rc==SQLITE_OK ){
  173313. rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  173314. }
  173315. sqlite3changegroup_delete(pGrp);
  173316. return rc;
  173317. }
  173318. /*
  173319. ** Streaming version of sqlite3changeset_concat().
  173320. */
  173321. SQLITE_API int sqlite3changeset_concat_strm(
  173322. int (*xInputA)(void *pIn, void *pData, int *pnData),
  173323. void *pInA,
  173324. int (*xInputB)(void *pIn, void *pData, int *pnData),
  173325. void *pInB,
  173326. int (*xOutput)(void *pOut, const void *pData, int nData),
  173327. void *pOut
  173328. ){
  173329. sqlite3_changegroup *pGrp;
  173330. int rc;
  173331. rc = sqlite3changegroup_new(&pGrp);
  173332. if( rc==SQLITE_OK ){
  173333. rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
  173334. }
  173335. if( rc==SQLITE_OK ){
  173336. rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
  173337. }
  173338. if( rc==SQLITE_OK ){
  173339. rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
  173340. }
  173341. sqlite3changegroup_delete(pGrp);
  173342. return rc;
  173343. }
  173344. /*
  173345. ** Changeset rebaser handle.
  173346. */
  173347. struct sqlite3_rebaser {
  173348. sqlite3_changegroup grp; /* Hash table */
  173349. };
  173350. /*
  173351. ** Buffers a1 and a2 must both contain a sessions module record nCol
  173352. ** fields in size. This function appends an nCol sessions module
  173353. ** record to buffer pBuf that is a copy of a1, except that for
  173354. ** each field that is undefined in a1[], swap in the field from a2[].
  173355. */
  173356. static void sessionAppendRecordMerge(
  173357. SessionBuffer *pBuf, /* Buffer to append to */
  173358. int nCol, /* Number of columns in each record */
  173359. u8 *a1, int n1, /* Record 1 */
  173360. u8 *a2, int n2, /* Record 2 */
  173361. int *pRc /* IN/OUT: error code */
  173362. ){
  173363. sessionBufferGrow(pBuf, n1+n2, pRc);
  173364. if( *pRc==SQLITE_OK ){
  173365. int i;
  173366. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  173367. for(i=0; i<nCol; i++){
  173368. int nn1 = sessionSerialLen(a1);
  173369. int nn2 = sessionSerialLen(a2);
  173370. if( *a1==0 || *a1==0xFF ){
  173371. memcpy(pOut, a2, nn2);
  173372. pOut += nn2;
  173373. }else{
  173374. memcpy(pOut, a1, nn1);
  173375. pOut += nn1;
  173376. }
  173377. a1 += nn1;
  173378. a2 += nn2;
  173379. }
  173380. pBuf->nBuf = pOut-pBuf->aBuf;
  173381. assert( pBuf->nBuf<=pBuf->nAlloc );
  173382. }
  173383. }
  173384. /*
  173385. ** This function is called when rebasing a local UPDATE change against one
  173386. ** or more remote UPDATE changes. The aRec/nRec buffer contains the current
  173387. ** old.* and new.* records for the change. The rebase buffer (a single
  173388. ** record) is in aChange/nChange. The rebased change is appended to buffer
  173389. ** pBuf.
  173390. **
  173391. ** Rebasing the UPDATE involves:
  173392. **
  173393. ** * Removing any changes to fields for which the corresponding field
  173394. ** in the rebase buffer is set to "replaced" (type 0xFF). If this
  173395. ** means the UPDATE change updates no fields, nothing is appended
  173396. ** to the output buffer.
  173397. **
  173398. ** * For each field modified by the local change for which the
  173399. ** corresponding field in the rebase buffer is not "undefined" (0x00)
  173400. ** or "replaced" (0xFF), the old.* value is replaced by the value
  173401. ** in the rebase buffer.
  173402. */
  173403. static void sessionAppendPartialUpdate(
  173404. SessionBuffer *pBuf, /* Append record here */
  173405. sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
  173406. u8 *aRec, int nRec, /* Local change */
  173407. u8 *aChange, int nChange, /* Record to rebase against */
  173408. int *pRc /* IN/OUT: Return Code */
  173409. ){
  173410. sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
  173411. if( *pRc==SQLITE_OK ){
  173412. int bData = 0;
  173413. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  173414. int i;
  173415. u8 *a1 = aRec;
  173416. u8 *a2 = aChange;
  173417. *pOut++ = SQLITE_UPDATE;
  173418. *pOut++ = pIter->bIndirect;
  173419. for(i=0; i<pIter->nCol; i++){
  173420. int n1 = sessionSerialLen(a1);
  173421. int n2 = sessionSerialLen(a2);
  173422. if( pIter->abPK[i] || a2[0]==0 ){
  173423. if( !pIter->abPK[i] ) bData = 1;
  173424. memcpy(pOut, a1, n1);
  173425. pOut += n1;
  173426. }else if( a2[0]!=0xFF ){
  173427. bData = 1;
  173428. memcpy(pOut, a2, n2);
  173429. pOut += n2;
  173430. }else{
  173431. *pOut++ = '\0';
  173432. }
  173433. a1 += n1;
  173434. a2 += n2;
  173435. }
  173436. if( bData ){
  173437. a2 = aChange;
  173438. for(i=0; i<pIter->nCol; i++){
  173439. int n1 = sessionSerialLen(a1);
  173440. int n2 = sessionSerialLen(a2);
  173441. if( pIter->abPK[i] || a2[0]!=0xFF ){
  173442. memcpy(pOut, a1, n1);
  173443. pOut += n1;
  173444. }else{
  173445. *pOut++ = '\0';
  173446. }
  173447. a1 += n1;
  173448. a2 += n2;
  173449. }
  173450. pBuf->nBuf = (pOut - pBuf->aBuf);
  173451. }
  173452. }
  173453. }
  173454. /*
  173455. ** pIter is configured to iterate through a changeset. This function rebases
  173456. ** that changeset according to the current configuration of the rebaser
  173457. ** object passed as the first argument. If no error occurs and argument xOutput
  173458. ** is not NULL, then the changeset is returned to the caller by invoking
  173459. ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
  173460. ** then (*ppOut) is set to point to a buffer containing the rebased changeset
  173461. ** before this function returns. In this case (*pnOut) is set to the size of
  173462. ** the buffer in bytes. It is the responsibility of the caller to eventually
  173463. ** free the (*ppOut) buffer using sqlite3_free().
  173464. **
  173465. ** If an error occurs, an SQLite error code is returned. If ppOut and
  173466. ** pnOut are not NULL, then the two output parameters are set to 0 before
  173467. ** returning.
  173468. */
  173469. static int sessionRebase(
  173470. sqlite3_rebaser *p, /* Rebaser hash table */
  173471. sqlite3_changeset_iter *pIter, /* Input data */
  173472. int (*xOutput)(void *pOut, const void *pData, int nData),
  173473. void *pOut, /* Context for xOutput callback */
  173474. int *pnOut, /* OUT: Number of bytes in output changeset */
  173475. void **ppOut /* OUT: Inverse of pChangeset */
  173476. ){
  173477. int rc = SQLITE_OK;
  173478. u8 *aRec = 0;
  173479. int nRec = 0;
  173480. int bNew = 0;
  173481. SessionTable *pTab = 0;
  173482. SessionBuffer sOut = {0,0,0};
  173483. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
  173484. SessionChange *pChange = 0;
  173485. int bDone = 0;
  173486. if( bNew ){
  173487. const char *zTab = pIter->zTab;
  173488. for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
  173489. if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
  173490. }
  173491. bNew = 0;
  173492. /* A patchset may not be rebased */
  173493. if( pIter->bPatchset ){
  173494. rc = SQLITE_ERROR;
  173495. }
  173496. /* Append a table header to the output for this new table */
  173497. sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
  173498. sessionAppendVarint(&sOut, pIter->nCol, &rc);
  173499. sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
  173500. sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
  173501. }
  173502. if( pTab && rc==SQLITE_OK ){
  173503. int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
  173504. for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
  173505. if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
  173506. break;
  173507. }
  173508. }
  173509. }
  173510. if( pChange ){
  173511. assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
  173512. switch( pIter->op ){
  173513. case SQLITE_INSERT:
  173514. if( pChange->op==SQLITE_INSERT ){
  173515. bDone = 1;
  173516. if( pChange->bIndirect==0 ){
  173517. sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
  173518. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  173519. sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
  173520. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  173521. }
  173522. }
  173523. break;
  173524. case SQLITE_UPDATE:
  173525. bDone = 1;
  173526. if( pChange->op==SQLITE_DELETE ){
  173527. if( pChange->bIndirect==0 ){
  173528. u8 *pCsr = aRec;
  173529. sessionSkipRecord(&pCsr, pIter->nCol);
  173530. sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
  173531. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  173532. sessionAppendRecordMerge(&sOut, pIter->nCol,
  173533. pCsr, nRec-(pCsr-aRec),
  173534. pChange->aRecord, pChange->nRecord, &rc
  173535. );
  173536. }
  173537. }else{
  173538. sessionAppendPartialUpdate(&sOut, pIter,
  173539. aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
  173540. );
  173541. }
  173542. break;
  173543. default:
  173544. assert( pIter->op==SQLITE_DELETE );
  173545. bDone = 1;
  173546. if( pChange->op==SQLITE_INSERT ){
  173547. sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
  173548. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  173549. sessionAppendRecordMerge(&sOut, pIter->nCol,
  173550. pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
  173551. );
  173552. }
  173553. break;
  173554. }
  173555. }
  173556. if( bDone==0 ){
  173557. sessionAppendByte(&sOut, pIter->op, &rc);
  173558. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  173559. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  173560. }
  173561. if( rc==SQLITE_OK && xOutput && sOut.nBuf>SESSIONS_STRM_CHUNK_SIZE ){
  173562. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  173563. sOut.nBuf = 0;
  173564. }
  173565. if( rc ) break;
  173566. }
  173567. if( rc!=SQLITE_OK ){
  173568. sqlite3_free(sOut.aBuf);
  173569. memset(&sOut, 0, sizeof(sOut));
  173570. }
  173571. if( rc==SQLITE_OK ){
  173572. if( xOutput ){
  173573. if( sOut.nBuf>0 ){
  173574. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  173575. }
  173576. }else{
  173577. *ppOut = (void*)sOut.aBuf;
  173578. *pnOut = sOut.nBuf;
  173579. sOut.aBuf = 0;
  173580. }
  173581. }
  173582. sqlite3_free(sOut.aBuf);
  173583. return rc;
  173584. }
  173585. /*
  173586. ** Create a new rebaser object.
  173587. */
  173588. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
  173589. int rc = SQLITE_OK;
  173590. sqlite3_rebaser *pNew;
  173591. pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
  173592. if( pNew==0 ){
  173593. rc = SQLITE_NOMEM;
  173594. }else{
  173595. memset(pNew, 0, sizeof(sqlite3_rebaser));
  173596. }
  173597. *ppNew = pNew;
  173598. return rc;
  173599. }
  173600. /*
  173601. ** Call this one or more times to configure a rebaser.
  173602. */
  173603. SQLITE_API int sqlite3rebaser_configure(
  173604. sqlite3_rebaser *p,
  173605. int nRebase, const void *pRebase
  173606. ){
  173607. sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
  173608. int rc; /* Return code */
  173609. rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
  173610. if( rc==SQLITE_OK ){
  173611. rc = sessionChangesetToHash(pIter, &p->grp, 1);
  173612. }
  173613. sqlite3changeset_finalize(pIter);
  173614. return rc;
  173615. }
  173616. /*
  173617. ** Rebase a changeset according to current rebaser configuration
  173618. */
  173619. SQLITE_API int sqlite3rebaser_rebase(
  173620. sqlite3_rebaser *p,
  173621. int nIn, const void *pIn,
  173622. int *pnOut, void **ppOut
  173623. ){
  173624. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  173625. int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
  173626. if( rc==SQLITE_OK ){
  173627. rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
  173628. sqlite3changeset_finalize(pIter);
  173629. }
  173630. return rc;
  173631. }
  173632. /*
  173633. ** Rebase a changeset according to current rebaser configuration
  173634. */
  173635. SQLITE_API int sqlite3rebaser_rebase_strm(
  173636. sqlite3_rebaser *p,
  173637. int (*xInput)(void *pIn, void *pData, int *pnData),
  173638. void *pIn,
  173639. int (*xOutput)(void *pOut, const void *pData, int nData),
  173640. void *pOut
  173641. ){
  173642. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  173643. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  173644. if( rc==SQLITE_OK ){
  173645. rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
  173646. sqlite3changeset_finalize(pIter);
  173647. }
  173648. return rc;
  173649. }
  173650. /*
  173651. ** Destroy a rebaser object
  173652. */
  173653. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
  173654. if( p ){
  173655. sessionDeleteTable(p->grp.pList);
  173656. sqlite3_free(p);
  173657. }
  173658. }
  173659. #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
  173660. /************** End of sqlite3session.c **************************************/
  173661. /************** Begin file json1.c *******************************************/
  173662. /*
  173663. ** 2015-08-12
  173664. **
  173665. ** The author disclaims copyright to this source code. In place of
  173666. ** a legal notice, here is a blessing:
  173667. **
  173668. ** May you do good and not evil.
  173669. ** May you find forgiveness for yourself and forgive others.
  173670. ** May you share freely, never taking more than you give.
  173671. **
  173672. ******************************************************************************
  173673. **
  173674. ** This SQLite extension implements JSON functions. The interface is
  173675. ** modeled after MySQL JSON functions:
  173676. **
  173677. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  173678. **
  173679. ** For the time being, all JSON is stored as pure text. (We might add
  173680. ** a JSONB type in the future which stores a binary encoding of JSON in
  173681. ** a BLOB, but there is no support for JSONB in the current implementation.
  173682. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  173683. ** how JSONB might improve on that.)
  173684. */
  173685. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  173686. #if !defined(SQLITEINT_H)
  173687. /* #include "sqlite3ext.h" */
  173688. #endif
  173689. SQLITE_EXTENSION_INIT1
  173690. /* #include <assert.h> */
  173691. /* #include <string.h> */
  173692. /* #include <stdlib.h> */
  173693. /* #include <stdarg.h> */
  173694. /* Mark a function parameter as unused, to suppress nuisance compiler
  173695. ** warnings. */
  173696. #ifndef UNUSED_PARAM
  173697. # define UNUSED_PARAM(X) (void)(X)
  173698. #endif
  173699. #ifndef LARGEST_INT64
  173700. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  173701. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  173702. #endif
  173703. /*
  173704. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  173705. ** to pass signed char values.
  173706. */
  173707. #ifdef sqlite3Isdigit
  173708. /* Use the SQLite core versions if this routine is part of the
  173709. ** SQLite amalgamation */
  173710. # define safe_isdigit(x) sqlite3Isdigit(x)
  173711. # define safe_isalnum(x) sqlite3Isalnum(x)
  173712. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  173713. #else
  173714. /* Use the standard library for separate compilation */
  173715. #include <ctype.h> /* amalgamator: keep */
  173716. # define safe_isdigit(x) isdigit((unsigned char)(x))
  173717. # define safe_isalnum(x) isalnum((unsigned char)(x))
  173718. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  173719. #endif
  173720. /*
  173721. ** Growing our own isspace() routine this way is twice as fast as
  173722. ** the library isspace() function, resulting in a 7% overall performance
  173723. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  173724. */
  173725. static const char jsonIsSpace[] = {
  173726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  173727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173728. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173742. };
  173743. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  173744. #ifndef SQLITE_AMALGAMATION
  173745. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  173746. ** but the definitions need to be repeated for separate compilation. */
  173747. typedef sqlite3_uint64 u64;
  173748. typedef unsigned int u32;
  173749. typedef unsigned short int u16;
  173750. typedef unsigned char u8;
  173751. #endif
  173752. /* Objects */
  173753. typedef struct JsonString JsonString;
  173754. typedef struct JsonNode JsonNode;
  173755. typedef struct JsonParse JsonParse;
  173756. /* An instance of this object represents a JSON string
  173757. ** under construction. Really, this is a generic string accumulator
  173758. ** that can be and is used to create strings other than JSON.
  173759. */
  173760. struct JsonString {
  173761. sqlite3_context *pCtx; /* Function context - put error messages here */
  173762. char *zBuf; /* Append JSON content here */
  173763. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  173764. u64 nUsed; /* Bytes of zBuf[] currently used */
  173765. u8 bStatic; /* True if zBuf is static space */
  173766. u8 bErr; /* True if an error has been encountered */
  173767. char zSpace[100]; /* Initial static space */
  173768. };
  173769. /* JSON type values
  173770. */
  173771. #define JSON_NULL 0
  173772. #define JSON_TRUE 1
  173773. #define JSON_FALSE 2
  173774. #define JSON_INT 3
  173775. #define JSON_REAL 4
  173776. #define JSON_STRING 5
  173777. #define JSON_ARRAY 6
  173778. #define JSON_OBJECT 7
  173779. /* The "subtype" set for JSON values */
  173780. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  173781. /*
  173782. ** Names of the various JSON types:
  173783. */
  173784. static const char * const jsonType[] = {
  173785. "null", "true", "false", "integer", "real", "text", "array", "object"
  173786. };
  173787. /* Bit values for the JsonNode.jnFlag field
  173788. */
  173789. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  173790. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  173791. #define JNODE_REMOVE 0x04 /* Do not output */
  173792. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
  173793. #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
  173794. #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
  173795. #define JNODE_LABEL 0x40 /* Is a label of an object */
  173796. /* A single node of parsed JSON
  173797. */
  173798. struct JsonNode {
  173799. u8 eType; /* One of the JSON_ type values */
  173800. u8 jnFlags; /* JNODE flags */
  173801. u32 n; /* Bytes of content, or number of sub-nodes */
  173802. union {
  173803. const char *zJContent; /* Content for INT, REAL, and STRING */
  173804. u32 iAppend; /* More terms for ARRAY and OBJECT */
  173805. u32 iKey; /* Key for ARRAY objects in json_tree() */
  173806. u32 iReplace; /* Replacement content for JNODE_REPLACE */
  173807. JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
  173808. } u;
  173809. };
  173810. /* A completely parsed JSON string
  173811. */
  173812. struct JsonParse {
  173813. u32 nNode; /* Number of slots of aNode[] used */
  173814. u32 nAlloc; /* Number of slots of aNode[] allocated */
  173815. JsonNode *aNode; /* Array of nodes containing the parse */
  173816. const char *zJson; /* Original JSON string */
  173817. u32 *aUp; /* Index of parent of each node */
  173818. u8 oom; /* Set to true if out of memory */
  173819. u8 nErr; /* Number of errors seen */
  173820. u16 iDepth; /* Nesting depth */
  173821. int nJson; /* Length of the zJson string in bytes */
  173822. };
  173823. /*
  173824. ** Maximum nesting depth of JSON for this implementation.
  173825. **
  173826. ** This limit is needed to avoid a stack overflow in the recursive
  173827. ** descent parser. A depth of 2000 is far deeper than any sane JSON
  173828. ** should go.
  173829. */
  173830. #define JSON_MAX_DEPTH 2000
  173831. /**************************************************************************
  173832. ** Utility routines for dealing with JsonString objects
  173833. **************************************************************************/
  173834. /* Set the JsonString object to an empty string
  173835. */
  173836. static void jsonZero(JsonString *p){
  173837. p->zBuf = p->zSpace;
  173838. p->nAlloc = sizeof(p->zSpace);
  173839. p->nUsed = 0;
  173840. p->bStatic = 1;
  173841. }
  173842. /* Initialize the JsonString object
  173843. */
  173844. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  173845. p->pCtx = pCtx;
  173846. p->bErr = 0;
  173847. jsonZero(p);
  173848. }
  173849. /* Free all allocated memory and reset the JsonString object back to its
  173850. ** initial state.
  173851. */
  173852. static void jsonReset(JsonString *p){
  173853. if( !p->bStatic ) sqlite3_free(p->zBuf);
  173854. jsonZero(p);
  173855. }
  173856. /* Report an out-of-memory (OOM) condition
  173857. */
  173858. static void jsonOom(JsonString *p){
  173859. p->bErr = 1;
  173860. sqlite3_result_error_nomem(p->pCtx);
  173861. jsonReset(p);
  173862. }
  173863. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  173864. ** Return zero on success. Return non-zero on an OOM error
  173865. */
  173866. static int jsonGrow(JsonString *p, u32 N){
  173867. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  173868. char *zNew;
  173869. if( p->bStatic ){
  173870. if( p->bErr ) return 1;
  173871. zNew = sqlite3_malloc64(nTotal);
  173872. if( zNew==0 ){
  173873. jsonOom(p);
  173874. return SQLITE_NOMEM;
  173875. }
  173876. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  173877. p->zBuf = zNew;
  173878. p->bStatic = 0;
  173879. }else{
  173880. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  173881. if( zNew==0 ){
  173882. jsonOom(p);
  173883. return SQLITE_NOMEM;
  173884. }
  173885. p->zBuf = zNew;
  173886. }
  173887. p->nAlloc = nTotal;
  173888. return SQLITE_OK;
  173889. }
  173890. /* Append N bytes from zIn onto the end of the JsonString string.
  173891. */
  173892. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  173893. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  173894. memcpy(p->zBuf+p->nUsed, zIn, N);
  173895. p->nUsed += N;
  173896. }
  173897. /* Append formatted text (not to exceed N bytes) to the JsonString.
  173898. */
  173899. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  173900. va_list ap;
  173901. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  173902. va_start(ap, zFormat);
  173903. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  173904. va_end(ap);
  173905. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  173906. }
  173907. /* Append a single character
  173908. */
  173909. static void jsonAppendChar(JsonString *p, char c){
  173910. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  173911. p->zBuf[p->nUsed++] = c;
  173912. }
  173913. /* Append a comma separator to the output buffer, if the previous
  173914. ** character is not '[' or '{'.
  173915. */
  173916. static void jsonAppendSeparator(JsonString *p){
  173917. char c;
  173918. if( p->nUsed==0 ) return;
  173919. c = p->zBuf[p->nUsed-1];
  173920. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  173921. }
  173922. /* Append the N-byte string in zIn to the end of the JsonString string
  173923. ** under construction. Enclose the string in "..." and escape
  173924. ** any double-quotes or backslash characters contained within the
  173925. ** string.
  173926. */
  173927. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  173928. u32 i;
  173929. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  173930. p->zBuf[p->nUsed++] = '"';
  173931. for(i=0; i<N; i++){
  173932. unsigned char c = ((unsigned const char*)zIn)[i];
  173933. if( c=='"' || c=='\\' ){
  173934. json_simple_escape:
  173935. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  173936. p->zBuf[p->nUsed++] = '\\';
  173937. }else if( c<=0x1f ){
  173938. static const char aSpecial[] = {
  173939. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
  173940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  173941. };
  173942. assert( sizeof(aSpecial)==32 );
  173943. assert( aSpecial['\b']=='b' );
  173944. assert( aSpecial['\f']=='f' );
  173945. assert( aSpecial['\n']=='n' );
  173946. assert( aSpecial['\r']=='r' );
  173947. assert( aSpecial['\t']=='t' );
  173948. if( aSpecial[c] ){
  173949. c = aSpecial[c];
  173950. goto json_simple_escape;
  173951. }
  173952. if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
  173953. p->zBuf[p->nUsed++] = '\\';
  173954. p->zBuf[p->nUsed++] = 'u';
  173955. p->zBuf[p->nUsed++] = '0';
  173956. p->zBuf[p->nUsed++] = '0';
  173957. p->zBuf[p->nUsed++] = '0' + (c>>4);
  173958. c = "0123456789abcdef"[c&0xf];
  173959. }
  173960. p->zBuf[p->nUsed++] = c;
  173961. }
  173962. p->zBuf[p->nUsed++] = '"';
  173963. assert( p->nUsed<p->nAlloc );
  173964. }
  173965. /*
  173966. ** Append a function parameter value to the JSON string under
  173967. ** construction.
  173968. */
  173969. static void jsonAppendValue(
  173970. JsonString *p, /* Append to this JSON string */
  173971. sqlite3_value *pValue /* Value to append */
  173972. ){
  173973. switch( sqlite3_value_type(pValue) ){
  173974. case SQLITE_NULL: {
  173975. jsonAppendRaw(p, "null", 4);
  173976. break;
  173977. }
  173978. case SQLITE_INTEGER:
  173979. case SQLITE_FLOAT: {
  173980. const char *z = (const char*)sqlite3_value_text(pValue);
  173981. u32 n = (u32)sqlite3_value_bytes(pValue);
  173982. jsonAppendRaw(p, z, n);
  173983. break;
  173984. }
  173985. case SQLITE_TEXT: {
  173986. const char *z = (const char*)sqlite3_value_text(pValue);
  173987. u32 n = (u32)sqlite3_value_bytes(pValue);
  173988. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  173989. jsonAppendRaw(p, z, n);
  173990. }else{
  173991. jsonAppendString(p, z, n);
  173992. }
  173993. break;
  173994. }
  173995. default: {
  173996. if( p->bErr==0 ){
  173997. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  173998. p->bErr = 2;
  173999. jsonReset(p);
  174000. }
  174001. break;
  174002. }
  174003. }
  174004. }
  174005. /* Make the JSON in p the result of the SQL function.
  174006. */
  174007. static void jsonResult(JsonString *p){
  174008. if( p->bErr==0 ){
  174009. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  174010. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  174011. SQLITE_UTF8);
  174012. jsonZero(p);
  174013. }
  174014. assert( p->bStatic );
  174015. }
  174016. /**************************************************************************
  174017. ** Utility routines for dealing with JsonNode and JsonParse objects
  174018. **************************************************************************/
  174019. /*
  174020. ** Return the number of consecutive JsonNode slots need to represent
  174021. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  174022. ** OBJECT types, the number might be larger.
  174023. **
  174024. ** Appended elements are not counted. The value returned is the number
  174025. ** by which the JsonNode counter should increment in order to go to the
  174026. ** next peer value.
  174027. */
  174028. static u32 jsonNodeSize(JsonNode *pNode){
  174029. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  174030. }
  174031. /*
  174032. ** Reclaim all memory allocated by a JsonParse object. But do not
  174033. ** delete the JsonParse object itself.
  174034. */
  174035. static void jsonParseReset(JsonParse *pParse){
  174036. sqlite3_free(pParse->aNode);
  174037. pParse->aNode = 0;
  174038. pParse->nNode = 0;
  174039. pParse->nAlloc = 0;
  174040. sqlite3_free(pParse->aUp);
  174041. pParse->aUp = 0;
  174042. }
  174043. /*
  174044. ** Free a JsonParse object that was obtained from sqlite3_malloc().
  174045. */
  174046. static void jsonParseFree(JsonParse *pParse){
  174047. jsonParseReset(pParse);
  174048. sqlite3_free(pParse);
  174049. }
  174050. /*
  174051. ** Convert the JsonNode pNode into a pure JSON string and
  174052. ** append to pOut. Subsubstructure is also included. Return
  174053. ** the number of JsonNode objects that are encoded.
  174054. */
  174055. static void jsonRenderNode(
  174056. JsonNode *pNode, /* The node to render */
  174057. JsonString *pOut, /* Write JSON here */
  174058. sqlite3_value **aReplace /* Replacement values */
  174059. ){
  174060. if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
  174061. if( pNode->jnFlags & JNODE_REPLACE ){
  174062. jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
  174063. return;
  174064. }
  174065. pNode = pNode->u.pPatch;
  174066. }
  174067. switch( pNode->eType ){
  174068. default: {
  174069. assert( pNode->eType==JSON_NULL );
  174070. jsonAppendRaw(pOut, "null", 4);
  174071. break;
  174072. }
  174073. case JSON_TRUE: {
  174074. jsonAppendRaw(pOut, "true", 4);
  174075. break;
  174076. }
  174077. case JSON_FALSE: {
  174078. jsonAppendRaw(pOut, "false", 5);
  174079. break;
  174080. }
  174081. case JSON_STRING: {
  174082. if( pNode->jnFlags & JNODE_RAW ){
  174083. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  174084. break;
  174085. }
  174086. /* Fall through into the next case */
  174087. }
  174088. case JSON_REAL:
  174089. case JSON_INT: {
  174090. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  174091. break;
  174092. }
  174093. case JSON_ARRAY: {
  174094. u32 j = 1;
  174095. jsonAppendChar(pOut, '[');
  174096. for(;;){
  174097. while( j<=pNode->n ){
  174098. if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
  174099. jsonAppendSeparator(pOut);
  174100. jsonRenderNode(&pNode[j], pOut, aReplace);
  174101. }
  174102. j += jsonNodeSize(&pNode[j]);
  174103. }
  174104. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  174105. pNode = &pNode[pNode->u.iAppend];
  174106. j = 1;
  174107. }
  174108. jsonAppendChar(pOut, ']');
  174109. break;
  174110. }
  174111. case JSON_OBJECT: {
  174112. u32 j = 1;
  174113. jsonAppendChar(pOut, '{');
  174114. for(;;){
  174115. while( j<=pNode->n ){
  174116. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  174117. jsonAppendSeparator(pOut);
  174118. jsonRenderNode(&pNode[j], pOut, aReplace);
  174119. jsonAppendChar(pOut, ':');
  174120. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  174121. }
  174122. j += 1 + jsonNodeSize(&pNode[j+1]);
  174123. }
  174124. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  174125. pNode = &pNode[pNode->u.iAppend];
  174126. j = 1;
  174127. }
  174128. jsonAppendChar(pOut, '}');
  174129. break;
  174130. }
  174131. }
  174132. }
  174133. /*
  174134. ** Return a JsonNode and all its descendents as a JSON string.
  174135. */
  174136. static void jsonReturnJson(
  174137. JsonNode *pNode, /* Node to return */
  174138. sqlite3_context *pCtx, /* Return value for this function */
  174139. sqlite3_value **aReplace /* Array of replacement values */
  174140. ){
  174141. JsonString s;
  174142. jsonInit(&s, pCtx);
  174143. jsonRenderNode(pNode, &s, aReplace);
  174144. jsonResult(&s);
  174145. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  174146. }
  174147. /*
  174148. ** Make the JsonNode the return value of the function.
  174149. */
  174150. static void jsonReturn(
  174151. JsonNode *pNode, /* Node to return */
  174152. sqlite3_context *pCtx, /* Return value for this function */
  174153. sqlite3_value **aReplace /* Array of replacement values */
  174154. ){
  174155. switch( pNode->eType ){
  174156. default: {
  174157. assert( pNode->eType==JSON_NULL );
  174158. sqlite3_result_null(pCtx);
  174159. break;
  174160. }
  174161. case JSON_TRUE: {
  174162. sqlite3_result_int(pCtx, 1);
  174163. break;
  174164. }
  174165. case JSON_FALSE: {
  174166. sqlite3_result_int(pCtx, 0);
  174167. break;
  174168. }
  174169. case JSON_INT: {
  174170. sqlite3_int64 i = 0;
  174171. const char *z = pNode->u.zJContent;
  174172. if( z[0]=='-' ){ z++; }
  174173. while( z[0]>='0' && z[0]<='9' ){
  174174. unsigned v = *(z++) - '0';
  174175. if( i>=LARGEST_INT64/10 ){
  174176. if( i>LARGEST_INT64/10 ) goto int_as_real;
  174177. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  174178. if( v==9 ) goto int_as_real;
  174179. if( v==8 ){
  174180. if( pNode->u.zJContent[0]=='-' ){
  174181. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  174182. goto int_done;
  174183. }else{
  174184. goto int_as_real;
  174185. }
  174186. }
  174187. }
  174188. i = i*10 + v;
  174189. }
  174190. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  174191. sqlite3_result_int64(pCtx, i);
  174192. int_done:
  174193. break;
  174194. int_as_real: /* fall through to real */;
  174195. }
  174196. case JSON_REAL: {
  174197. double r;
  174198. #ifdef SQLITE_AMALGAMATION
  174199. const char *z = pNode->u.zJContent;
  174200. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  174201. #else
  174202. r = strtod(pNode->u.zJContent, 0);
  174203. #endif
  174204. sqlite3_result_double(pCtx, r);
  174205. break;
  174206. }
  174207. case JSON_STRING: {
  174208. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  174209. ** json_insert() and json_replace() and those routines do not
  174210. ** call jsonReturn() */
  174211. if( pNode->jnFlags & JNODE_RAW ){
  174212. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  174213. SQLITE_TRANSIENT);
  174214. }else
  174215. #endif
  174216. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  174217. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  174218. /* JSON formatted without any backslash-escapes */
  174219. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  174220. SQLITE_TRANSIENT);
  174221. }else{
  174222. /* Translate JSON formatted string into raw text */
  174223. u32 i;
  174224. u32 n = pNode->n;
  174225. const char *z = pNode->u.zJContent;
  174226. char *zOut;
  174227. u32 j;
  174228. zOut = sqlite3_malloc( n+1 );
  174229. if( zOut==0 ){
  174230. sqlite3_result_error_nomem(pCtx);
  174231. break;
  174232. }
  174233. for(i=1, j=0; i<n-1; i++){
  174234. char c = z[i];
  174235. if( c!='\\' ){
  174236. zOut[j++] = c;
  174237. }else{
  174238. c = z[++i];
  174239. if( c=='u' ){
  174240. u32 v = 0, k;
  174241. for(k=0; k<4; i++, k++){
  174242. assert( i<n-2 );
  174243. c = z[i+1];
  174244. assert( safe_isxdigit(c) );
  174245. if( c<='9' ) v = v*16 + c - '0';
  174246. else if( c<='F' ) v = v*16 + c - 'A' + 10;
  174247. else v = v*16 + c - 'a' + 10;
  174248. }
  174249. if( v==0 ) break;
  174250. if( v<=0x7f ){
  174251. zOut[j++] = (char)v;
  174252. }else if( v<=0x7ff ){
  174253. zOut[j++] = (char)(0xc0 | (v>>6));
  174254. zOut[j++] = 0x80 | (v&0x3f);
  174255. }else{
  174256. zOut[j++] = (char)(0xe0 | (v>>12));
  174257. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  174258. zOut[j++] = 0x80 | (v&0x3f);
  174259. }
  174260. }else{
  174261. if( c=='b' ){
  174262. c = '\b';
  174263. }else if( c=='f' ){
  174264. c = '\f';
  174265. }else if( c=='n' ){
  174266. c = '\n';
  174267. }else if( c=='r' ){
  174268. c = '\r';
  174269. }else if( c=='t' ){
  174270. c = '\t';
  174271. }
  174272. zOut[j++] = c;
  174273. }
  174274. }
  174275. }
  174276. zOut[j] = 0;
  174277. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  174278. }
  174279. break;
  174280. }
  174281. case JSON_ARRAY:
  174282. case JSON_OBJECT: {
  174283. jsonReturnJson(pNode, pCtx, aReplace);
  174284. break;
  174285. }
  174286. }
  174287. }
  174288. /* Forward reference */
  174289. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  174290. /*
  174291. ** A macro to hint to the compiler that a function should not be
  174292. ** inlined.
  174293. */
  174294. #if defined(__GNUC__)
  174295. # define JSON_NOINLINE __attribute__((noinline))
  174296. #elif defined(_MSC_VER) && _MSC_VER>=1310
  174297. # define JSON_NOINLINE __declspec(noinline)
  174298. #else
  174299. # define JSON_NOINLINE
  174300. #endif
  174301. static JSON_NOINLINE int jsonParseAddNodeExpand(
  174302. JsonParse *pParse, /* Append the node to this object */
  174303. u32 eType, /* Node type */
  174304. u32 n, /* Content size or sub-node count */
  174305. const char *zContent /* Content */
  174306. ){
  174307. u32 nNew;
  174308. JsonNode *pNew;
  174309. assert( pParse->nNode>=pParse->nAlloc );
  174310. if( pParse->oom ) return -1;
  174311. nNew = pParse->nAlloc*2 + 10;
  174312. pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
  174313. if( pNew==0 ){
  174314. pParse->oom = 1;
  174315. return -1;
  174316. }
  174317. pParse->nAlloc = nNew;
  174318. pParse->aNode = pNew;
  174319. assert( pParse->nNode<pParse->nAlloc );
  174320. return jsonParseAddNode(pParse, eType, n, zContent);
  174321. }
  174322. /*
  174323. ** Create a new JsonNode instance based on the arguments and append that
  174324. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  174325. ** new node, or -1 if a memory allocation fails.
  174326. */
  174327. static int jsonParseAddNode(
  174328. JsonParse *pParse, /* Append the node to this object */
  174329. u32 eType, /* Node type */
  174330. u32 n, /* Content size or sub-node count */
  174331. const char *zContent /* Content */
  174332. ){
  174333. JsonNode *p;
  174334. if( pParse->nNode>=pParse->nAlloc ){
  174335. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  174336. }
  174337. p = &pParse->aNode[pParse->nNode];
  174338. p->eType = (u8)eType;
  174339. p->jnFlags = 0;
  174340. p->n = n;
  174341. p->u.zJContent = zContent;
  174342. return pParse->nNode++;
  174343. }
  174344. /*
  174345. ** Return true if z[] begins with 4 (or more) hexadecimal digits
  174346. */
  174347. static int jsonIs4Hex(const char *z){
  174348. int i;
  174349. for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
  174350. return 1;
  174351. }
  174352. /*
  174353. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  174354. ** index of the first character past the end of the value parsed.
  174355. **
  174356. ** Return negative for a syntax error. Special cases: return -2 if the
  174357. ** first non-whitespace character is '}' and return -3 if the first
  174358. ** non-whitespace character is ']'.
  174359. */
  174360. static int jsonParseValue(JsonParse *pParse, u32 i){
  174361. char c;
  174362. u32 j;
  174363. int iThis;
  174364. int x;
  174365. JsonNode *pNode;
  174366. const char *z = pParse->zJson;
  174367. while( safe_isspace(z[i]) ){ i++; }
  174368. if( (c = z[i])=='{' ){
  174369. /* Parse object */
  174370. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  174371. if( iThis<0 ) return -1;
  174372. for(j=i+1;;j++){
  174373. while( safe_isspace(z[j]) ){ j++; }
  174374. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  174375. x = jsonParseValue(pParse, j);
  174376. if( x<0 ){
  174377. pParse->iDepth--;
  174378. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  174379. return -1;
  174380. }
  174381. if( pParse->oom ) return -1;
  174382. pNode = &pParse->aNode[pParse->nNode-1];
  174383. if( pNode->eType!=JSON_STRING ) return -1;
  174384. pNode->jnFlags |= JNODE_LABEL;
  174385. j = x;
  174386. while( safe_isspace(z[j]) ){ j++; }
  174387. if( z[j]!=':' ) return -1;
  174388. j++;
  174389. x = jsonParseValue(pParse, j);
  174390. pParse->iDepth--;
  174391. if( x<0 ) return -1;
  174392. j = x;
  174393. while( safe_isspace(z[j]) ){ j++; }
  174394. c = z[j];
  174395. if( c==',' ) continue;
  174396. if( c!='}' ) return -1;
  174397. break;
  174398. }
  174399. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  174400. return j+1;
  174401. }else if( c=='[' ){
  174402. /* Parse array */
  174403. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  174404. if( iThis<0 ) return -1;
  174405. for(j=i+1;;j++){
  174406. while( safe_isspace(z[j]) ){ j++; }
  174407. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  174408. x = jsonParseValue(pParse, j);
  174409. pParse->iDepth--;
  174410. if( x<0 ){
  174411. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  174412. return -1;
  174413. }
  174414. j = x;
  174415. while( safe_isspace(z[j]) ){ j++; }
  174416. c = z[j];
  174417. if( c==',' ) continue;
  174418. if( c!=']' ) return -1;
  174419. break;
  174420. }
  174421. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  174422. return j+1;
  174423. }else if( c=='"' ){
  174424. /* Parse string */
  174425. u8 jnFlags = 0;
  174426. j = i+1;
  174427. for(;;){
  174428. c = z[j];
  174429. if( (c & ~0x1f)==0 ){
  174430. /* Control characters are not allowed in strings */
  174431. return -1;
  174432. }
  174433. if( c=='\\' ){
  174434. c = z[++j];
  174435. if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
  174436. || c=='n' || c=='r' || c=='t'
  174437. || (c=='u' && jsonIs4Hex(z+j+1)) ){
  174438. jnFlags = JNODE_ESCAPE;
  174439. }else{
  174440. return -1;
  174441. }
  174442. }else if( c=='"' ){
  174443. break;
  174444. }
  174445. j++;
  174446. }
  174447. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
  174448. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  174449. return j+1;
  174450. }else if( c=='n'
  174451. && strncmp(z+i,"null",4)==0
  174452. && !safe_isalnum(z[i+4]) ){
  174453. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  174454. return i+4;
  174455. }else if( c=='t'
  174456. && strncmp(z+i,"true",4)==0
  174457. && !safe_isalnum(z[i+4]) ){
  174458. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  174459. return i+4;
  174460. }else if( c=='f'
  174461. && strncmp(z+i,"false",5)==0
  174462. && !safe_isalnum(z[i+5]) ){
  174463. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  174464. return i+5;
  174465. }else if( c=='-' || (c>='0' && c<='9') ){
  174466. /* Parse number */
  174467. u8 seenDP = 0;
  174468. u8 seenE = 0;
  174469. assert( '-' < '0' );
  174470. if( c<='0' ){
  174471. j = c=='-' ? i+1 : i;
  174472. if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
  174473. }
  174474. j = i+1;
  174475. for(;; j++){
  174476. c = z[j];
  174477. if( c>='0' && c<='9' ) continue;
  174478. if( c=='.' ){
  174479. if( z[j-1]=='-' ) return -1;
  174480. if( seenDP ) return -1;
  174481. seenDP = 1;
  174482. continue;
  174483. }
  174484. if( c=='e' || c=='E' ){
  174485. if( z[j-1]<'0' ) return -1;
  174486. if( seenE ) return -1;
  174487. seenDP = seenE = 1;
  174488. c = z[j+1];
  174489. if( c=='+' || c=='-' ){
  174490. j++;
  174491. c = z[j+1];
  174492. }
  174493. if( c<'0' || c>'9' ) return -1;
  174494. continue;
  174495. }
  174496. break;
  174497. }
  174498. if( z[j-1]<'0' ) return -1;
  174499. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  174500. j - i, &z[i]);
  174501. return j;
  174502. }else if( c=='}' ){
  174503. return -2; /* End of {...} */
  174504. }else if( c==']' ){
  174505. return -3; /* End of [...] */
  174506. }else if( c==0 ){
  174507. return 0; /* End of file */
  174508. }else{
  174509. return -1; /* Syntax error */
  174510. }
  174511. }
  174512. /*
  174513. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  174514. ** are any errors. If an error occurs, free all memory associated with
  174515. ** pParse.
  174516. **
  174517. ** pParse is uninitialized when this routine is called.
  174518. */
  174519. static int jsonParse(
  174520. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  174521. sqlite3_context *pCtx, /* Report errors here */
  174522. const char *zJson /* Input JSON text to be parsed */
  174523. ){
  174524. int i;
  174525. memset(pParse, 0, sizeof(*pParse));
  174526. if( zJson==0 ) return 1;
  174527. pParse->zJson = zJson;
  174528. i = jsonParseValue(pParse, 0);
  174529. if( pParse->oom ) i = -1;
  174530. if( i>0 ){
  174531. assert( pParse->iDepth==0 );
  174532. while( safe_isspace(zJson[i]) ) i++;
  174533. if( zJson[i] ) i = -1;
  174534. }
  174535. if( i<=0 ){
  174536. if( pCtx!=0 ){
  174537. if( pParse->oom ){
  174538. sqlite3_result_error_nomem(pCtx);
  174539. }else{
  174540. sqlite3_result_error(pCtx, "malformed JSON", -1);
  174541. }
  174542. }
  174543. jsonParseReset(pParse);
  174544. return 1;
  174545. }
  174546. return 0;
  174547. }
  174548. /* Mark node i of pParse as being a child of iParent. Call recursively
  174549. ** to fill in all the descendants of node i.
  174550. */
  174551. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  174552. JsonNode *pNode = &pParse->aNode[i];
  174553. u32 j;
  174554. pParse->aUp[i] = iParent;
  174555. switch( pNode->eType ){
  174556. case JSON_ARRAY: {
  174557. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  174558. jsonParseFillInParentage(pParse, i+j, i);
  174559. }
  174560. break;
  174561. }
  174562. case JSON_OBJECT: {
  174563. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  174564. pParse->aUp[i+j] = i;
  174565. jsonParseFillInParentage(pParse, i+j+1, i);
  174566. }
  174567. break;
  174568. }
  174569. default: {
  174570. break;
  174571. }
  174572. }
  174573. }
  174574. /*
  174575. ** Compute the parentage of all nodes in a completed parse.
  174576. */
  174577. static int jsonParseFindParents(JsonParse *pParse){
  174578. u32 *aUp;
  174579. assert( pParse->aUp==0 );
  174580. aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
  174581. if( aUp==0 ){
  174582. pParse->oom = 1;
  174583. return SQLITE_NOMEM;
  174584. }
  174585. jsonParseFillInParentage(pParse, 0, 0);
  174586. return SQLITE_OK;
  174587. }
  174588. /*
  174589. ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
  174590. */
  174591. #define JSON_CACHE_ID (-429938)
  174592. /*
  174593. ** Obtain a complete parse of the JSON found in the first argument
  174594. ** of the argv array. Use the sqlite3_get_auxdata() cache for this
  174595. ** parse if it is available. If the cache is not available or if it
  174596. ** is no longer valid, parse the JSON again and return the new parse,
  174597. ** and also register the new parse so that it will be available for
  174598. ** future sqlite3_get_auxdata() calls.
  174599. */
  174600. static JsonParse *jsonParseCached(
  174601. sqlite3_context *pCtx,
  174602. sqlite3_value **argv
  174603. ){
  174604. const char *zJson = (const char*)sqlite3_value_text(argv[0]);
  174605. int nJson = sqlite3_value_bytes(argv[0]);
  174606. JsonParse *p;
  174607. if( zJson==0 ) return 0;
  174608. p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  174609. if( p && p->nJson==nJson && memcmp(p->zJson,zJson,nJson)==0 ){
  174610. p->nErr = 0;
  174611. return p; /* The cached entry matches, so return it */
  174612. }
  174613. p = sqlite3_malloc( sizeof(*p) + nJson + 1 );
  174614. if( p==0 ){
  174615. sqlite3_result_error_nomem(pCtx);
  174616. return 0;
  174617. }
  174618. memset(p, 0, sizeof(*p));
  174619. p->zJson = (char*)&p[1];
  174620. memcpy((char*)p->zJson, zJson, nJson+1);
  174621. if( jsonParse(p, pCtx, p->zJson) ){
  174622. sqlite3_free(p);
  174623. return 0;
  174624. }
  174625. p->nJson = nJson;
  174626. sqlite3_set_auxdata(pCtx, JSON_CACHE_ID, p, (void(*)(void*))jsonParseFree);
  174627. return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID);
  174628. }
  174629. /*
  174630. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  174631. ** a match.
  174632. */
  174633. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  174634. if( pNode->jnFlags & JNODE_RAW ){
  174635. if( pNode->n!=nKey ) return 0;
  174636. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  174637. }else{
  174638. if( pNode->n!=nKey+2 ) return 0;
  174639. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  174640. }
  174641. }
  174642. /* forward declaration */
  174643. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  174644. /*
  174645. ** Search along zPath to find the node specified. Return a pointer
  174646. ** to that node, or NULL if zPath is malformed or if there is no such
  174647. ** node.
  174648. **
  174649. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  174650. ** possible to do so and if no existing node corresponds to zPath. If
  174651. ** new nodes are appended *pApnd is set to 1.
  174652. */
  174653. static JsonNode *jsonLookupStep(
  174654. JsonParse *pParse, /* The JSON to search */
  174655. u32 iRoot, /* Begin the search at this node */
  174656. const char *zPath, /* The path to search */
  174657. int *pApnd, /* Append nodes to complete path if not NULL */
  174658. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  174659. ){
  174660. u32 i, j, nKey;
  174661. const char *zKey;
  174662. JsonNode *pRoot = &pParse->aNode[iRoot];
  174663. if( zPath[0]==0 ) return pRoot;
  174664. if( zPath[0]=='.' ){
  174665. if( pRoot->eType!=JSON_OBJECT ) return 0;
  174666. zPath++;
  174667. if( zPath[0]=='"' ){
  174668. zKey = zPath + 1;
  174669. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  174670. nKey = i-1;
  174671. if( zPath[i] ){
  174672. i++;
  174673. }else{
  174674. *pzErr = zPath;
  174675. return 0;
  174676. }
  174677. }else{
  174678. zKey = zPath;
  174679. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  174680. nKey = i;
  174681. }
  174682. if( nKey==0 ){
  174683. *pzErr = zPath;
  174684. return 0;
  174685. }
  174686. j = 1;
  174687. for(;;){
  174688. while( j<=pRoot->n ){
  174689. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  174690. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  174691. }
  174692. j++;
  174693. j += jsonNodeSize(&pRoot[j]);
  174694. }
  174695. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  174696. iRoot += pRoot->u.iAppend;
  174697. pRoot = &pParse->aNode[iRoot];
  174698. j = 1;
  174699. }
  174700. if( pApnd ){
  174701. u32 iStart, iLabel;
  174702. JsonNode *pNode;
  174703. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  174704. iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
  174705. zPath += i;
  174706. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  174707. if( pParse->oom ) return 0;
  174708. if( pNode ){
  174709. pRoot = &pParse->aNode[iRoot];
  174710. pRoot->u.iAppend = iStart - iRoot;
  174711. pRoot->jnFlags |= JNODE_APPEND;
  174712. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  174713. }
  174714. return pNode;
  174715. }
  174716. }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
  174717. if( pRoot->eType!=JSON_ARRAY ) return 0;
  174718. i = 0;
  174719. j = 1;
  174720. while( safe_isdigit(zPath[j]) ){
  174721. i = i*10 + zPath[j] - '0';
  174722. j++;
  174723. }
  174724. if( zPath[j]!=']' ){
  174725. *pzErr = zPath;
  174726. return 0;
  174727. }
  174728. zPath += j + 1;
  174729. j = 1;
  174730. for(;;){
  174731. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  174732. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  174733. j += jsonNodeSize(&pRoot[j]);
  174734. }
  174735. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  174736. iRoot += pRoot->u.iAppend;
  174737. pRoot = &pParse->aNode[iRoot];
  174738. j = 1;
  174739. }
  174740. if( j<=pRoot->n ){
  174741. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  174742. }
  174743. if( i==0 && pApnd ){
  174744. u32 iStart;
  174745. JsonNode *pNode;
  174746. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  174747. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  174748. if( pParse->oom ) return 0;
  174749. if( pNode ){
  174750. pRoot = &pParse->aNode[iRoot];
  174751. pRoot->u.iAppend = iStart - iRoot;
  174752. pRoot->jnFlags |= JNODE_APPEND;
  174753. }
  174754. return pNode;
  174755. }
  174756. }else{
  174757. *pzErr = zPath;
  174758. }
  174759. return 0;
  174760. }
  174761. /*
  174762. ** Append content to pParse that will complete zPath. Return a pointer
  174763. ** to the inserted node, or return NULL if the append fails.
  174764. */
  174765. static JsonNode *jsonLookupAppend(
  174766. JsonParse *pParse, /* Append content to the JSON parse */
  174767. const char *zPath, /* Description of content to append */
  174768. int *pApnd, /* Set this flag to 1 */
  174769. const char **pzErr /* Make this point to any syntax error */
  174770. ){
  174771. *pApnd = 1;
  174772. if( zPath[0]==0 ){
  174773. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  174774. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  174775. }
  174776. if( zPath[0]=='.' ){
  174777. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  174778. }else if( strncmp(zPath,"[0]",3)==0 ){
  174779. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  174780. }else{
  174781. return 0;
  174782. }
  174783. if( pParse->oom ) return 0;
  174784. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  174785. }
  174786. /*
  174787. ** Return the text of a syntax error message on a JSON path. Space is
  174788. ** obtained from sqlite3_malloc().
  174789. */
  174790. static char *jsonPathSyntaxError(const char *zErr){
  174791. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  174792. }
  174793. /*
  174794. ** Do a node lookup using zPath. Return a pointer to the node on success.
  174795. ** Return NULL if not found or if there is an error.
  174796. **
  174797. ** On an error, write an error message into pCtx and increment the
  174798. ** pParse->nErr counter.
  174799. **
  174800. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  174801. ** nodes are appended.
  174802. */
  174803. static JsonNode *jsonLookup(
  174804. JsonParse *pParse, /* The JSON to search */
  174805. const char *zPath, /* The path to search */
  174806. int *pApnd, /* Append nodes to complete path if not NULL */
  174807. sqlite3_context *pCtx /* Report errors here, if not NULL */
  174808. ){
  174809. const char *zErr = 0;
  174810. JsonNode *pNode = 0;
  174811. char *zMsg;
  174812. if( zPath==0 ) return 0;
  174813. if( zPath[0]!='$' ){
  174814. zErr = zPath;
  174815. goto lookup_err;
  174816. }
  174817. zPath++;
  174818. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  174819. if( zErr==0 ) return pNode;
  174820. lookup_err:
  174821. pParse->nErr++;
  174822. assert( zErr!=0 && pCtx!=0 );
  174823. zMsg = jsonPathSyntaxError(zErr);
  174824. if( zMsg ){
  174825. sqlite3_result_error(pCtx, zMsg, -1);
  174826. sqlite3_free(zMsg);
  174827. }else{
  174828. sqlite3_result_error_nomem(pCtx);
  174829. }
  174830. return 0;
  174831. }
  174832. /*
  174833. ** Report the wrong number of arguments for json_insert(), json_replace()
  174834. ** or json_set().
  174835. */
  174836. static void jsonWrongNumArgs(
  174837. sqlite3_context *pCtx,
  174838. const char *zFuncName
  174839. ){
  174840. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  174841. zFuncName);
  174842. sqlite3_result_error(pCtx, zMsg, -1);
  174843. sqlite3_free(zMsg);
  174844. }
  174845. /*
  174846. ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
  174847. */
  174848. static void jsonRemoveAllNulls(JsonNode *pNode){
  174849. int i, n;
  174850. assert( pNode->eType==JSON_OBJECT );
  174851. n = pNode->n;
  174852. for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
  174853. switch( pNode[i].eType ){
  174854. case JSON_NULL:
  174855. pNode[i].jnFlags |= JNODE_REMOVE;
  174856. break;
  174857. case JSON_OBJECT:
  174858. jsonRemoveAllNulls(&pNode[i]);
  174859. break;
  174860. }
  174861. }
  174862. }
  174863. /****************************************************************************
  174864. ** SQL functions used for testing and debugging
  174865. ****************************************************************************/
  174866. #ifdef SQLITE_DEBUG
  174867. /*
  174868. ** The json_parse(JSON) function returns a string which describes
  174869. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  174870. ** well-formed.
  174871. */
  174872. static void jsonParseFunc(
  174873. sqlite3_context *ctx,
  174874. int argc,
  174875. sqlite3_value **argv
  174876. ){
  174877. JsonString s; /* Output string - not real JSON */
  174878. JsonParse x; /* The parse */
  174879. u32 i;
  174880. assert( argc==1 );
  174881. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  174882. jsonParseFindParents(&x);
  174883. jsonInit(&s, ctx);
  174884. for(i=0; i<x.nNode; i++){
  174885. const char *zType;
  174886. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  174887. assert( x.aNode[i].eType==JSON_STRING );
  174888. zType = "label";
  174889. }else{
  174890. zType = jsonType[x.aNode[i].eType];
  174891. }
  174892. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  174893. i, zType, x.aNode[i].n, x.aUp[i]);
  174894. if( x.aNode[i].u.zJContent!=0 ){
  174895. jsonAppendRaw(&s, " ", 1);
  174896. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  174897. }
  174898. jsonAppendRaw(&s, "\n", 1);
  174899. }
  174900. jsonParseReset(&x);
  174901. jsonResult(&s);
  174902. }
  174903. /*
  174904. ** The json_test1(JSON) function return true (1) if the input is JSON
  174905. ** text generated by another json function. It returns (0) if the input
  174906. ** is not known to be JSON.
  174907. */
  174908. static void jsonTest1Func(
  174909. sqlite3_context *ctx,
  174910. int argc,
  174911. sqlite3_value **argv
  174912. ){
  174913. UNUSED_PARAM(argc);
  174914. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  174915. }
  174916. #endif /* SQLITE_DEBUG */
  174917. /****************************************************************************
  174918. ** Scalar SQL function implementations
  174919. ****************************************************************************/
  174920. /*
  174921. ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
  174922. ** corresponding to the SQL value input. Mostly this means putting
  174923. ** double-quotes around strings and returning the unquoted string "null"
  174924. ** when given a NULL input.
  174925. */
  174926. static void jsonQuoteFunc(
  174927. sqlite3_context *ctx,
  174928. int argc,
  174929. sqlite3_value **argv
  174930. ){
  174931. JsonString jx;
  174932. UNUSED_PARAM(argc);
  174933. jsonInit(&jx, ctx);
  174934. jsonAppendValue(&jx, argv[0]);
  174935. jsonResult(&jx);
  174936. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  174937. }
  174938. /*
  174939. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  174940. ** array that contains all values given in arguments. Or if any argument
  174941. ** is a BLOB, throw an error.
  174942. */
  174943. static void jsonArrayFunc(
  174944. sqlite3_context *ctx,
  174945. int argc,
  174946. sqlite3_value **argv
  174947. ){
  174948. int i;
  174949. JsonString jx;
  174950. jsonInit(&jx, ctx);
  174951. jsonAppendChar(&jx, '[');
  174952. for(i=0; i<argc; i++){
  174953. jsonAppendSeparator(&jx);
  174954. jsonAppendValue(&jx, argv[i]);
  174955. }
  174956. jsonAppendChar(&jx, ']');
  174957. jsonResult(&jx);
  174958. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  174959. }
  174960. /*
  174961. ** json_array_length(JSON)
  174962. ** json_array_length(JSON, PATH)
  174963. **
  174964. ** Return the number of elements in the top-level JSON array.
  174965. ** Return 0 if the input is not a well-formed JSON array.
  174966. */
  174967. static void jsonArrayLengthFunc(
  174968. sqlite3_context *ctx,
  174969. int argc,
  174970. sqlite3_value **argv
  174971. ){
  174972. JsonParse *p; /* The parse */
  174973. sqlite3_int64 n = 0;
  174974. u32 i;
  174975. JsonNode *pNode;
  174976. p = jsonParseCached(ctx, argv);
  174977. if( p==0 ) return;
  174978. assert( p->nNode );
  174979. if( argc==2 ){
  174980. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  174981. pNode = jsonLookup(p, zPath, 0, ctx);
  174982. }else{
  174983. pNode = p->aNode;
  174984. }
  174985. if( pNode==0 ){
  174986. return;
  174987. }
  174988. if( pNode->eType==JSON_ARRAY ){
  174989. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  174990. for(i=1; i<=pNode->n; n++){
  174991. i += jsonNodeSize(&pNode[i]);
  174992. }
  174993. }
  174994. sqlite3_result_int64(ctx, n);
  174995. }
  174996. /*
  174997. ** json_extract(JSON, PATH, ...)
  174998. **
  174999. ** Return the element described by PATH. Return NULL if there is no
  175000. ** PATH element. If there are multiple PATHs, then return a JSON array
  175001. ** with the result from each path. Throw an error if the JSON or any PATH
  175002. ** is malformed.
  175003. */
  175004. static void jsonExtractFunc(
  175005. sqlite3_context *ctx,
  175006. int argc,
  175007. sqlite3_value **argv
  175008. ){
  175009. JsonParse *p; /* The parse */
  175010. JsonNode *pNode;
  175011. const char *zPath;
  175012. JsonString jx;
  175013. int i;
  175014. if( argc<2 ) return;
  175015. p = jsonParseCached(ctx, argv);
  175016. if( p==0 ) return;
  175017. jsonInit(&jx, ctx);
  175018. jsonAppendChar(&jx, '[');
  175019. for(i=1; i<argc; i++){
  175020. zPath = (const char*)sqlite3_value_text(argv[i]);
  175021. pNode = jsonLookup(p, zPath, 0, ctx);
  175022. if( p->nErr ) break;
  175023. if( argc>2 ){
  175024. jsonAppendSeparator(&jx);
  175025. if( pNode ){
  175026. jsonRenderNode(pNode, &jx, 0);
  175027. }else{
  175028. jsonAppendRaw(&jx, "null", 4);
  175029. }
  175030. }else if( pNode ){
  175031. jsonReturn(pNode, ctx, 0);
  175032. }
  175033. }
  175034. if( argc>2 && i==argc ){
  175035. jsonAppendChar(&jx, ']');
  175036. jsonResult(&jx);
  175037. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  175038. }
  175039. jsonReset(&jx);
  175040. }
  175041. /* This is the RFC 7396 MergePatch algorithm.
  175042. */
  175043. static JsonNode *jsonMergePatch(
  175044. JsonParse *pParse, /* The JSON parser that contains the TARGET */
  175045. u32 iTarget, /* Node of the TARGET in pParse */
  175046. JsonNode *pPatch /* The PATCH */
  175047. ){
  175048. u32 i, j;
  175049. u32 iRoot;
  175050. JsonNode *pTarget;
  175051. if( pPatch->eType!=JSON_OBJECT ){
  175052. return pPatch;
  175053. }
  175054. assert( iTarget>=0 && iTarget<pParse->nNode );
  175055. pTarget = &pParse->aNode[iTarget];
  175056. assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
  175057. if( pTarget->eType!=JSON_OBJECT ){
  175058. jsonRemoveAllNulls(pPatch);
  175059. return pPatch;
  175060. }
  175061. iRoot = iTarget;
  175062. for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
  175063. u32 nKey;
  175064. const char *zKey;
  175065. assert( pPatch[i].eType==JSON_STRING );
  175066. assert( pPatch[i].jnFlags & JNODE_LABEL );
  175067. nKey = pPatch[i].n;
  175068. zKey = pPatch[i].u.zJContent;
  175069. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  175070. for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
  175071. assert( pTarget[j].eType==JSON_STRING );
  175072. assert( pTarget[j].jnFlags & JNODE_LABEL );
  175073. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  175074. if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
  175075. if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
  175076. if( pPatch[i+1].eType==JSON_NULL ){
  175077. pTarget[j+1].jnFlags |= JNODE_REMOVE;
  175078. }else{
  175079. JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
  175080. if( pNew==0 ) return 0;
  175081. pTarget = &pParse->aNode[iTarget];
  175082. if( pNew!=&pTarget[j+1] ){
  175083. pTarget[j+1].u.pPatch = pNew;
  175084. pTarget[j+1].jnFlags |= JNODE_PATCH;
  175085. }
  175086. }
  175087. break;
  175088. }
  175089. }
  175090. if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
  175091. int iStart, iPatch;
  175092. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  175093. jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  175094. iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  175095. if( pParse->oom ) return 0;
  175096. jsonRemoveAllNulls(pPatch);
  175097. pTarget = &pParse->aNode[iTarget];
  175098. pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
  175099. pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
  175100. iRoot = iStart;
  175101. pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
  175102. pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
  175103. }
  175104. }
  175105. return pTarget;
  175106. }
  175107. /*
  175108. ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
  175109. ** object that is the result of running the RFC 7396 MergePatch() algorithm
  175110. ** on the two arguments.
  175111. */
  175112. static void jsonPatchFunc(
  175113. sqlite3_context *ctx,
  175114. int argc,
  175115. sqlite3_value **argv
  175116. ){
  175117. JsonParse x; /* The JSON that is being patched */
  175118. JsonParse y; /* The patch */
  175119. JsonNode *pResult; /* The result of the merge */
  175120. UNUSED_PARAM(argc);
  175121. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  175122. if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
  175123. jsonParseReset(&x);
  175124. return;
  175125. }
  175126. pResult = jsonMergePatch(&x, 0, y.aNode);
  175127. assert( pResult!=0 || x.oom );
  175128. if( pResult ){
  175129. jsonReturnJson(pResult, ctx, 0);
  175130. }else{
  175131. sqlite3_result_error_nomem(ctx);
  175132. }
  175133. jsonParseReset(&x);
  175134. jsonParseReset(&y);
  175135. }
  175136. /*
  175137. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  175138. ** object that contains all name/value given in arguments. Or if any name
  175139. ** is not a string or if any value is a BLOB, throw an error.
  175140. */
  175141. static void jsonObjectFunc(
  175142. sqlite3_context *ctx,
  175143. int argc,
  175144. sqlite3_value **argv
  175145. ){
  175146. int i;
  175147. JsonString jx;
  175148. const char *z;
  175149. u32 n;
  175150. if( argc&1 ){
  175151. sqlite3_result_error(ctx, "json_object() requires an even number "
  175152. "of arguments", -1);
  175153. return;
  175154. }
  175155. jsonInit(&jx, ctx);
  175156. jsonAppendChar(&jx, '{');
  175157. for(i=0; i<argc; i+=2){
  175158. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  175159. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  175160. jsonReset(&jx);
  175161. return;
  175162. }
  175163. jsonAppendSeparator(&jx);
  175164. z = (const char*)sqlite3_value_text(argv[i]);
  175165. n = (u32)sqlite3_value_bytes(argv[i]);
  175166. jsonAppendString(&jx, z, n);
  175167. jsonAppendChar(&jx, ':');
  175168. jsonAppendValue(&jx, argv[i+1]);
  175169. }
  175170. jsonAppendChar(&jx, '}');
  175171. jsonResult(&jx);
  175172. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  175173. }
  175174. /*
  175175. ** json_remove(JSON, PATH, ...)
  175176. **
  175177. ** Remove the named elements from JSON and return the result. malformed
  175178. ** JSON or PATH arguments result in an error.
  175179. */
  175180. static void jsonRemoveFunc(
  175181. sqlite3_context *ctx,
  175182. int argc,
  175183. sqlite3_value **argv
  175184. ){
  175185. JsonParse x; /* The parse */
  175186. JsonNode *pNode;
  175187. const char *zPath;
  175188. u32 i;
  175189. if( argc<1 ) return;
  175190. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  175191. assert( x.nNode );
  175192. for(i=1; i<(u32)argc; i++){
  175193. zPath = (const char*)sqlite3_value_text(argv[i]);
  175194. if( zPath==0 ) goto remove_done;
  175195. pNode = jsonLookup(&x, zPath, 0, ctx);
  175196. if( x.nErr ) goto remove_done;
  175197. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  175198. }
  175199. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  175200. jsonReturnJson(x.aNode, ctx, 0);
  175201. }
  175202. remove_done:
  175203. jsonParseReset(&x);
  175204. }
  175205. /*
  175206. ** json_replace(JSON, PATH, VALUE, ...)
  175207. **
  175208. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  175209. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  175210. */
  175211. static void jsonReplaceFunc(
  175212. sqlite3_context *ctx,
  175213. int argc,
  175214. sqlite3_value **argv
  175215. ){
  175216. JsonParse x; /* The parse */
  175217. JsonNode *pNode;
  175218. const char *zPath;
  175219. u32 i;
  175220. if( argc<1 ) return;
  175221. if( (argc&1)==0 ) {
  175222. jsonWrongNumArgs(ctx, "replace");
  175223. return;
  175224. }
  175225. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  175226. assert( x.nNode );
  175227. for(i=1; i<(u32)argc; i+=2){
  175228. zPath = (const char*)sqlite3_value_text(argv[i]);
  175229. pNode = jsonLookup(&x, zPath, 0, ctx);
  175230. if( x.nErr ) goto replace_err;
  175231. if( pNode ){
  175232. pNode->jnFlags |= (u8)JNODE_REPLACE;
  175233. pNode->u.iReplace = i + 1;
  175234. }
  175235. }
  175236. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  175237. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  175238. }else{
  175239. jsonReturnJson(x.aNode, ctx, argv);
  175240. }
  175241. replace_err:
  175242. jsonParseReset(&x);
  175243. }
  175244. /*
  175245. ** json_set(JSON, PATH, VALUE, ...)
  175246. **
  175247. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  175248. ** exist. Overwrite existing values that do exist.
  175249. ** If JSON or PATH is malformed, throw an error.
  175250. **
  175251. ** json_insert(JSON, PATH, VALUE, ...)
  175252. **
  175253. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  175254. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  175255. */
  175256. static void jsonSetFunc(
  175257. sqlite3_context *ctx,
  175258. int argc,
  175259. sqlite3_value **argv
  175260. ){
  175261. JsonParse x; /* The parse */
  175262. JsonNode *pNode;
  175263. const char *zPath;
  175264. u32 i;
  175265. int bApnd;
  175266. int bIsSet = *(int*)sqlite3_user_data(ctx);
  175267. if( argc<1 ) return;
  175268. if( (argc&1)==0 ) {
  175269. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  175270. return;
  175271. }
  175272. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  175273. assert( x.nNode );
  175274. for(i=1; i<(u32)argc; i+=2){
  175275. zPath = (const char*)sqlite3_value_text(argv[i]);
  175276. bApnd = 0;
  175277. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  175278. if( x.oom ){
  175279. sqlite3_result_error_nomem(ctx);
  175280. goto jsonSetDone;
  175281. }else if( x.nErr ){
  175282. goto jsonSetDone;
  175283. }else if( pNode && (bApnd || bIsSet) ){
  175284. pNode->jnFlags |= (u8)JNODE_REPLACE;
  175285. pNode->u.iReplace = i + 1;
  175286. }
  175287. }
  175288. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  175289. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  175290. }else{
  175291. jsonReturnJson(x.aNode, ctx, argv);
  175292. }
  175293. jsonSetDone:
  175294. jsonParseReset(&x);
  175295. }
  175296. /*
  175297. ** json_type(JSON)
  175298. ** json_type(JSON, PATH)
  175299. **
  175300. ** Return the top-level "type" of a JSON string. Throw an error if
  175301. ** either the JSON or PATH inputs are not well-formed.
  175302. */
  175303. static void jsonTypeFunc(
  175304. sqlite3_context *ctx,
  175305. int argc,
  175306. sqlite3_value **argv
  175307. ){
  175308. JsonParse x; /* The parse */
  175309. const char *zPath;
  175310. JsonNode *pNode;
  175311. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  175312. assert( x.nNode );
  175313. if( argc==2 ){
  175314. zPath = (const char*)sqlite3_value_text(argv[1]);
  175315. pNode = jsonLookup(&x, zPath, 0, ctx);
  175316. }else{
  175317. pNode = x.aNode;
  175318. }
  175319. if( pNode ){
  175320. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  175321. }
  175322. jsonParseReset(&x);
  175323. }
  175324. /*
  175325. ** json_valid(JSON)
  175326. **
  175327. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  175328. ** Return 0 otherwise.
  175329. */
  175330. static void jsonValidFunc(
  175331. sqlite3_context *ctx,
  175332. int argc,
  175333. sqlite3_value **argv
  175334. ){
  175335. JsonParse x; /* The parse */
  175336. int rc = 0;
  175337. UNUSED_PARAM(argc);
  175338. if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
  175339. rc = 1;
  175340. }
  175341. jsonParseReset(&x);
  175342. sqlite3_result_int(ctx, rc);
  175343. }
  175344. /****************************************************************************
  175345. ** Aggregate SQL function implementations
  175346. ****************************************************************************/
  175347. /*
  175348. ** json_group_array(VALUE)
  175349. **
  175350. ** Return a JSON array composed of all values in the aggregate.
  175351. */
  175352. static void jsonArrayStep(
  175353. sqlite3_context *ctx,
  175354. int argc,
  175355. sqlite3_value **argv
  175356. ){
  175357. JsonString *pStr;
  175358. UNUSED_PARAM(argc);
  175359. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  175360. if( pStr ){
  175361. if( pStr->zBuf==0 ){
  175362. jsonInit(pStr, ctx);
  175363. jsonAppendChar(pStr, '[');
  175364. }else{
  175365. jsonAppendChar(pStr, ',');
  175366. pStr->pCtx = ctx;
  175367. }
  175368. jsonAppendValue(pStr, argv[0]);
  175369. }
  175370. }
  175371. static void jsonArrayFinal(sqlite3_context *ctx){
  175372. JsonString *pStr;
  175373. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  175374. if( pStr ){
  175375. pStr->pCtx = ctx;
  175376. jsonAppendChar(pStr, ']');
  175377. if( pStr->bErr ){
  175378. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  175379. assert( pStr->bStatic );
  175380. }else{
  175381. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  175382. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  175383. pStr->bStatic = 1;
  175384. }
  175385. }else{
  175386. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  175387. }
  175388. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  175389. }
  175390. /*
  175391. ** json_group_obj(NAME,VALUE)
  175392. **
  175393. ** Return a JSON object composed of all names and values in the aggregate.
  175394. */
  175395. static void jsonObjectStep(
  175396. sqlite3_context *ctx,
  175397. int argc,
  175398. sqlite3_value **argv
  175399. ){
  175400. JsonString *pStr;
  175401. const char *z;
  175402. u32 n;
  175403. UNUSED_PARAM(argc);
  175404. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  175405. if( pStr ){
  175406. if( pStr->zBuf==0 ){
  175407. jsonInit(pStr, ctx);
  175408. jsonAppendChar(pStr, '{');
  175409. }else{
  175410. jsonAppendChar(pStr, ',');
  175411. pStr->pCtx = ctx;
  175412. }
  175413. z = (const char*)sqlite3_value_text(argv[0]);
  175414. n = (u32)sqlite3_value_bytes(argv[0]);
  175415. jsonAppendString(pStr, z, n);
  175416. jsonAppendChar(pStr, ':');
  175417. jsonAppendValue(pStr, argv[1]);
  175418. }
  175419. }
  175420. static void jsonObjectFinal(sqlite3_context *ctx){
  175421. JsonString *pStr;
  175422. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  175423. if( pStr ){
  175424. jsonAppendChar(pStr, '}');
  175425. if( pStr->bErr ){
  175426. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  175427. assert( pStr->bStatic );
  175428. }else{
  175429. sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
  175430. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  175431. pStr->bStatic = 1;
  175432. }
  175433. }else{
  175434. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  175435. }
  175436. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  175437. }
  175438. #ifndef SQLITE_OMIT_VIRTUALTABLE
  175439. /****************************************************************************
  175440. ** The json_each virtual table
  175441. ****************************************************************************/
  175442. typedef struct JsonEachCursor JsonEachCursor;
  175443. struct JsonEachCursor {
  175444. sqlite3_vtab_cursor base; /* Base class - must be first */
  175445. u32 iRowid; /* The rowid */
  175446. u32 iBegin; /* The first node of the scan */
  175447. u32 i; /* Index in sParse.aNode[] of current row */
  175448. u32 iEnd; /* EOF when i equals or exceeds this value */
  175449. u8 eType; /* Type of top-level element */
  175450. u8 bRecursive; /* True for json_tree(). False for json_each() */
  175451. char *zJson; /* Input JSON */
  175452. char *zRoot; /* Path by which to filter zJson */
  175453. JsonParse sParse; /* Parse of the input JSON */
  175454. };
  175455. /* Constructor for the json_each virtual table */
  175456. static int jsonEachConnect(
  175457. sqlite3 *db,
  175458. void *pAux,
  175459. int argc, const char *const*argv,
  175460. sqlite3_vtab **ppVtab,
  175461. char **pzErr
  175462. ){
  175463. sqlite3_vtab *pNew;
  175464. int rc;
  175465. /* Column numbers */
  175466. #define JEACH_KEY 0
  175467. #define JEACH_VALUE 1
  175468. #define JEACH_TYPE 2
  175469. #define JEACH_ATOM 3
  175470. #define JEACH_ID 4
  175471. #define JEACH_PARENT 5
  175472. #define JEACH_FULLKEY 6
  175473. #define JEACH_PATH 7
  175474. #define JEACH_JSON 8
  175475. #define JEACH_ROOT 9
  175476. UNUSED_PARAM(pzErr);
  175477. UNUSED_PARAM(argv);
  175478. UNUSED_PARAM(argc);
  175479. UNUSED_PARAM(pAux);
  175480. rc = sqlite3_declare_vtab(db,
  175481. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  175482. "json HIDDEN,root HIDDEN)");
  175483. if( rc==SQLITE_OK ){
  175484. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  175485. if( pNew==0 ) return SQLITE_NOMEM;
  175486. memset(pNew, 0, sizeof(*pNew));
  175487. }
  175488. return rc;
  175489. }
  175490. /* destructor for json_each virtual table */
  175491. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  175492. sqlite3_free(pVtab);
  175493. return SQLITE_OK;
  175494. }
  175495. /* constructor for a JsonEachCursor object for json_each(). */
  175496. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  175497. JsonEachCursor *pCur;
  175498. UNUSED_PARAM(p);
  175499. pCur = sqlite3_malloc( sizeof(*pCur) );
  175500. if( pCur==0 ) return SQLITE_NOMEM;
  175501. memset(pCur, 0, sizeof(*pCur));
  175502. *ppCursor = &pCur->base;
  175503. return SQLITE_OK;
  175504. }
  175505. /* constructor for a JsonEachCursor object for json_tree(). */
  175506. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  175507. int rc = jsonEachOpenEach(p, ppCursor);
  175508. if( rc==SQLITE_OK ){
  175509. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  175510. pCur->bRecursive = 1;
  175511. }
  175512. return rc;
  175513. }
  175514. /* Reset a JsonEachCursor back to its original state. Free any memory
  175515. ** held. */
  175516. static void jsonEachCursorReset(JsonEachCursor *p){
  175517. sqlite3_free(p->zJson);
  175518. sqlite3_free(p->zRoot);
  175519. jsonParseReset(&p->sParse);
  175520. p->iRowid = 0;
  175521. p->i = 0;
  175522. p->iEnd = 0;
  175523. p->eType = 0;
  175524. p->zJson = 0;
  175525. p->zRoot = 0;
  175526. }
  175527. /* Destructor for a jsonEachCursor object */
  175528. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  175529. JsonEachCursor *p = (JsonEachCursor*)cur;
  175530. jsonEachCursorReset(p);
  175531. sqlite3_free(cur);
  175532. return SQLITE_OK;
  175533. }
  175534. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  175535. ** of the JSON object */
  175536. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  175537. JsonEachCursor *p = (JsonEachCursor*)cur;
  175538. return p->i >= p->iEnd;
  175539. }
  175540. /* Advance the cursor to the next element for json_tree() */
  175541. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  175542. JsonEachCursor *p = (JsonEachCursor*)cur;
  175543. if( p->bRecursive ){
  175544. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  175545. p->i++;
  175546. p->iRowid++;
  175547. if( p->i<p->iEnd ){
  175548. u32 iUp = p->sParse.aUp[p->i];
  175549. JsonNode *pUp = &p->sParse.aNode[iUp];
  175550. p->eType = pUp->eType;
  175551. if( pUp->eType==JSON_ARRAY ){
  175552. if( iUp==p->i-1 ){
  175553. pUp->u.iKey = 0;
  175554. }else{
  175555. pUp->u.iKey++;
  175556. }
  175557. }
  175558. }
  175559. }else{
  175560. switch( p->eType ){
  175561. case JSON_ARRAY: {
  175562. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  175563. p->iRowid++;
  175564. break;
  175565. }
  175566. case JSON_OBJECT: {
  175567. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  175568. p->iRowid++;
  175569. break;
  175570. }
  175571. default: {
  175572. p->i = p->iEnd;
  175573. break;
  175574. }
  175575. }
  175576. }
  175577. return SQLITE_OK;
  175578. }
  175579. /* Append the name of the path for element i to pStr
  175580. */
  175581. static void jsonEachComputePath(
  175582. JsonEachCursor *p, /* The cursor */
  175583. JsonString *pStr, /* Write the path here */
  175584. u32 i /* Path to this element */
  175585. ){
  175586. JsonNode *pNode, *pUp;
  175587. u32 iUp;
  175588. if( i==0 ){
  175589. jsonAppendChar(pStr, '$');
  175590. return;
  175591. }
  175592. iUp = p->sParse.aUp[i];
  175593. jsonEachComputePath(p, pStr, iUp);
  175594. pNode = &p->sParse.aNode[i];
  175595. pUp = &p->sParse.aNode[iUp];
  175596. if( pUp->eType==JSON_ARRAY ){
  175597. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  175598. }else{
  175599. assert( pUp->eType==JSON_OBJECT );
  175600. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  175601. assert( pNode->eType==JSON_STRING );
  175602. assert( pNode->jnFlags & JNODE_LABEL );
  175603. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  175604. }
  175605. }
  175606. /* Return the value of a column */
  175607. static int jsonEachColumn(
  175608. sqlite3_vtab_cursor *cur, /* The cursor */
  175609. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  175610. int i /* Which column to return */
  175611. ){
  175612. JsonEachCursor *p = (JsonEachCursor*)cur;
  175613. JsonNode *pThis = &p->sParse.aNode[p->i];
  175614. switch( i ){
  175615. case JEACH_KEY: {
  175616. if( p->i==0 ) break;
  175617. if( p->eType==JSON_OBJECT ){
  175618. jsonReturn(pThis, ctx, 0);
  175619. }else if( p->eType==JSON_ARRAY ){
  175620. u32 iKey;
  175621. if( p->bRecursive ){
  175622. if( p->iRowid==0 ) break;
  175623. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  175624. }else{
  175625. iKey = p->iRowid;
  175626. }
  175627. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  175628. }
  175629. break;
  175630. }
  175631. case JEACH_VALUE: {
  175632. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  175633. jsonReturn(pThis, ctx, 0);
  175634. break;
  175635. }
  175636. case JEACH_TYPE: {
  175637. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  175638. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  175639. break;
  175640. }
  175641. case JEACH_ATOM: {
  175642. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  175643. if( pThis->eType>=JSON_ARRAY ) break;
  175644. jsonReturn(pThis, ctx, 0);
  175645. break;
  175646. }
  175647. case JEACH_ID: {
  175648. sqlite3_result_int64(ctx,
  175649. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  175650. break;
  175651. }
  175652. case JEACH_PARENT: {
  175653. if( p->i>p->iBegin && p->bRecursive ){
  175654. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  175655. }
  175656. break;
  175657. }
  175658. case JEACH_FULLKEY: {
  175659. JsonString x;
  175660. jsonInit(&x, ctx);
  175661. if( p->bRecursive ){
  175662. jsonEachComputePath(p, &x, p->i);
  175663. }else{
  175664. if( p->zRoot ){
  175665. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  175666. }else{
  175667. jsonAppendChar(&x, '$');
  175668. }
  175669. if( p->eType==JSON_ARRAY ){
  175670. jsonPrintf(30, &x, "[%d]", p->iRowid);
  175671. }else{
  175672. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  175673. }
  175674. }
  175675. jsonResult(&x);
  175676. break;
  175677. }
  175678. case JEACH_PATH: {
  175679. if( p->bRecursive ){
  175680. JsonString x;
  175681. jsonInit(&x, ctx);
  175682. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  175683. jsonResult(&x);
  175684. break;
  175685. }
  175686. /* For json_each() path and root are the same so fall through
  175687. ** into the root case */
  175688. }
  175689. default: {
  175690. const char *zRoot = p->zRoot;
  175691. if( zRoot==0 ) zRoot = "$";
  175692. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  175693. break;
  175694. }
  175695. case JEACH_JSON: {
  175696. assert( i==JEACH_JSON );
  175697. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  175698. break;
  175699. }
  175700. }
  175701. return SQLITE_OK;
  175702. }
  175703. /* Return the current rowid value */
  175704. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  175705. JsonEachCursor *p = (JsonEachCursor*)cur;
  175706. *pRowid = p->iRowid;
  175707. return SQLITE_OK;
  175708. }
  175709. /* The query strategy is to look for an equality constraint on the json
  175710. ** column. Without such a constraint, the table cannot operate. idxNum is
  175711. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  175712. ** and 0 otherwise.
  175713. */
  175714. static int jsonEachBestIndex(
  175715. sqlite3_vtab *tab,
  175716. sqlite3_index_info *pIdxInfo
  175717. ){
  175718. int i;
  175719. int jsonIdx = -1;
  175720. int rootIdx = -1;
  175721. const struct sqlite3_index_constraint *pConstraint;
  175722. UNUSED_PARAM(tab);
  175723. pConstraint = pIdxInfo->aConstraint;
  175724. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  175725. if( pConstraint->usable==0 ) continue;
  175726. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  175727. switch( pConstraint->iColumn ){
  175728. case JEACH_JSON: jsonIdx = i; break;
  175729. case JEACH_ROOT: rootIdx = i; break;
  175730. default: /* no-op */ break;
  175731. }
  175732. }
  175733. if( jsonIdx<0 ){
  175734. pIdxInfo->idxNum = 0;
  175735. pIdxInfo->estimatedCost = 1e99;
  175736. }else{
  175737. pIdxInfo->estimatedCost = 1.0;
  175738. pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
  175739. pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
  175740. if( rootIdx<0 ){
  175741. pIdxInfo->idxNum = 1;
  175742. }else{
  175743. pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
  175744. pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
  175745. pIdxInfo->idxNum = 3;
  175746. }
  175747. }
  175748. return SQLITE_OK;
  175749. }
  175750. /* Start a search on a new JSON string */
  175751. static int jsonEachFilter(
  175752. sqlite3_vtab_cursor *cur,
  175753. int idxNum, const char *idxStr,
  175754. int argc, sqlite3_value **argv
  175755. ){
  175756. JsonEachCursor *p = (JsonEachCursor*)cur;
  175757. const char *z;
  175758. const char *zRoot = 0;
  175759. sqlite3_int64 n;
  175760. UNUSED_PARAM(idxStr);
  175761. UNUSED_PARAM(argc);
  175762. jsonEachCursorReset(p);
  175763. if( idxNum==0 ) return SQLITE_OK;
  175764. z = (const char*)sqlite3_value_text(argv[0]);
  175765. if( z==0 ) return SQLITE_OK;
  175766. n = sqlite3_value_bytes(argv[0]);
  175767. p->zJson = sqlite3_malloc64( n+1 );
  175768. if( p->zJson==0 ) return SQLITE_NOMEM;
  175769. memcpy(p->zJson, z, (size_t)n+1);
  175770. if( jsonParse(&p->sParse, 0, p->zJson) ){
  175771. int rc = SQLITE_NOMEM;
  175772. if( p->sParse.oom==0 ){
  175773. sqlite3_free(cur->pVtab->zErrMsg);
  175774. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  175775. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  175776. }
  175777. jsonEachCursorReset(p);
  175778. return rc;
  175779. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  175780. jsonEachCursorReset(p);
  175781. return SQLITE_NOMEM;
  175782. }else{
  175783. JsonNode *pNode = 0;
  175784. if( idxNum==3 ){
  175785. const char *zErr = 0;
  175786. zRoot = (const char*)sqlite3_value_text(argv[1]);
  175787. if( zRoot==0 ) return SQLITE_OK;
  175788. n = sqlite3_value_bytes(argv[1]);
  175789. p->zRoot = sqlite3_malloc64( n+1 );
  175790. if( p->zRoot==0 ) return SQLITE_NOMEM;
  175791. memcpy(p->zRoot, zRoot, (size_t)n+1);
  175792. if( zRoot[0]!='$' ){
  175793. zErr = zRoot;
  175794. }else{
  175795. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  175796. }
  175797. if( zErr ){
  175798. sqlite3_free(cur->pVtab->zErrMsg);
  175799. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  175800. jsonEachCursorReset(p);
  175801. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  175802. }else if( pNode==0 ){
  175803. return SQLITE_OK;
  175804. }
  175805. }else{
  175806. pNode = p->sParse.aNode;
  175807. }
  175808. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  175809. p->eType = pNode->eType;
  175810. if( p->eType>=JSON_ARRAY ){
  175811. pNode->u.iKey = 0;
  175812. p->iEnd = p->i + pNode->n + 1;
  175813. if( p->bRecursive ){
  175814. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  175815. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  175816. p->i--;
  175817. }
  175818. }else{
  175819. p->i++;
  175820. }
  175821. }else{
  175822. p->iEnd = p->i+1;
  175823. }
  175824. }
  175825. return SQLITE_OK;
  175826. }
  175827. /* The methods of the json_each virtual table */
  175828. static sqlite3_module jsonEachModule = {
  175829. 0, /* iVersion */
  175830. 0, /* xCreate */
  175831. jsonEachConnect, /* xConnect */
  175832. jsonEachBestIndex, /* xBestIndex */
  175833. jsonEachDisconnect, /* xDisconnect */
  175834. 0, /* xDestroy */
  175835. jsonEachOpenEach, /* xOpen - open a cursor */
  175836. jsonEachClose, /* xClose - close a cursor */
  175837. jsonEachFilter, /* xFilter - configure scan constraints */
  175838. jsonEachNext, /* xNext - advance a cursor */
  175839. jsonEachEof, /* xEof - check for end of scan */
  175840. jsonEachColumn, /* xColumn - read data */
  175841. jsonEachRowid, /* xRowid - read data */
  175842. 0, /* xUpdate */
  175843. 0, /* xBegin */
  175844. 0, /* xSync */
  175845. 0, /* xCommit */
  175846. 0, /* xRollback */
  175847. 0, /* xFindMethod */
  175848. 0, /* xRename */
  175849. 0, /* xSavepoint */
  175850. 0, /* xRelease */
  175851. 0 /* xRollbackTo */
  175852. };
  175853. /* The methods of the json_tree virtual table. */
  175854. static sqlite3_module jsonTreeModule = {
  175855. 0, /* iVersion */
  175856. 0, /* xCreate */
  175857. jsonEachConnect, /* xConnect */
  175858. jsonEachBestIndex, /* xBestIndex */
  175859. jsonEachDisconnect, /* xDisconnect */
  175860. 0, /* xDestroy */
  175861. jsonEachOpenTree, /* xOpen - open a cursor */
  175862. jsonEachClose, /* xClose - close a cursor */
  175863. jsonEachFilter, /* xFilter - configure scan constraints */
  175864. jsonEachNext, /* xNext - advance a cursor */
  175865. jsonEachEof, /* xEof - check for end of scan */
  175866. jsonEachColumn, /* xColumn - read data */
  175867. jsonEachRowid, /* xRowid - read data */
  175868. 0, /* xUpdate */
  175869. 0, /* xBegin */
  175870. 0, /* xSync */
  175871. 0, /* xCommit */
  175872. 0, /* xRollback */
  175873. 0, /* xFindMethod */
  175874. 0, /* xRename */
  175875. 0, /* xSavepoint */
  175876. 0, /* xRelease */
  175877. 0 /* xRollbackTo */
  175878. };
  175879. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  175880. /****************************************************************************
  175881. ** The following routines are the only publically visible identifiers in this
  175882. ** file. Call the following routines in order to register the various SQL
  175883. ** functions and the virtual table implemented by this file.
  175884. ****************************************************************************/
  175885. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  175886. int rc = SQLITE_OK;
  175887. unsigned int i;
  175888. static const struct {
  175889. const char *zName;
  175890. int nArg;
  175891. int flag;
  175892. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  175893. } aFunc[] = {
  175894. { "json", 1, 0, jsonRemoveFunc },
  175895. { "json_array", -1, 0, jsonArrayFunc },
  175896. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  175897. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  175898. { "json_extract", -1, 0, jsonExtractFunc },
  175899. { "json_insert", -1, 0, jsonSetFunc },
  175900. { "json_object", -1, 0, jsonObjectFunc },
  175901. { "json_patch", 2, 0, jsonPatchFunc },
  175902. { "json_quote", 1, 0, jsonQuoteFunc },
  175903. { "json_remove", -1, 0, jsonRemoveFunc },
  175904. { "json_replace", -1, 0, jsonReplaceFunc },
  175905. { "json_set", -1, 1, jsonSetFunc },
  175906. { "json_type", 1, 0, jsonTypeFunc },
  175907. { "json_type", 2, 0, jsonTypeFunc },
  175908. { "json_valid", 1, 0, jsonValidFunc },
  175909. #if SQLITE_DEBUG
  175910. /* DEBUG and TESTING functions */
  175911. { "json_parse", 1, 0, jsonParseFunc },
  175912. { "json_test1", 1, 0, jsonTest1Func },
  175913. #endif
  175914. };
  175915. static const struct {
  175916. const char *zName;
  175917. int nArg;
  175918. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  175919. void (*xFinal)(sqlite3_context*);
  175920. } aAgg[] = {
  175921. { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
  175922. { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
  175923. };
  175924. #ifndef SQLITE_OMIT_VIRTUALTABLE
  175925. static const struct {
  175926. const char *zName;
  175927. sqlite3_module *pModule;
  175928. } aMod[] = {
  175929. { "json_each", &jsonEachModule },
  175930. { "json_tree", &jsonTreeModule },
  175931. };
  175932. #endif
  175933. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  175934. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  175935. SQLITE_UTF8 | SQLITE_DETERMINISTIC,
  175936. (void*)&aFunc[i].flag,
  175937. aFunc[i].xFunc, 0, 0);
  175938. }
  175939. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  175940. rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
  175941. SQLITE_UTF8 | SQLITE_DETERMINISTIC, 0,
  175942. 0, aAgg[i].xStep, aAgg[i].xFinal);
  175943. }
  175944. #ifndef SQLITE_OMIT_VIRTUALTABLE
  175945. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  175946. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  175947. }
  175948. #endif
  175949. return rc;
  175950. }
  175951. #ifndef SQLITE_CORE
  175952. #ifdef _WIN32
  175953. __declspec(dllexport)
  175954. #endif
  175955. SQLITE_API int sqlite3_json_init(
  175956. sqlite3 *db,
  175957. char **pzErrMsg,
  175958. const sqlite3_api_routines *pApi
  175959. ){
  175960. SQLITE_EXTENSION_INIT2(pApi);
  175961. (void)pzErrMsg; /* Unused parameter */
  175962. return sqlite3Json1Init(db);
  175963. }
  175964. #endif
  175965. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  175966. /************** End of json1.c ***********************************************/
  175967. /************** Begin file fts5.c ********************************************/
  175968. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  175969. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  175970. # define NDEBUG 1
  175971. #endif
  175972. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  175973. # undef NDEBUG
  175974. #endif
  175975. /*
  175976. ** 2014 May 31
  175977. **
  175978. ** The author disclaims copyright to this source code. In place of
  175979. ** a legal notice, here is a blessing:
  175980. **
  175981. ** May you do good and not evil.
  175982. ** May you find forgiveness for yourself and forgive others.
  175983. ** May you share freely, never taking more than you give.
  175984. **
  175985. ******************************************************************************
  175986. **
  175987. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  175988. ** FTS5 may be extended with:
  175989. **
  175990. ** * custom tokenizers, and
  175991. ** * custom auxiliary functions.
  175992. */
  175993. #ifndef _FTS5_H
  175994. #define _FTS5_H
  175995. /* #include "sqlite3.h" */
  175996. #if 0
  175997. extern "C" {
  175998. #endif
  175999. /*************************************************************************
  176000. ** CUSTOM AUXILIARY FUNCTIONS
  176001. **
  176002. ** Virtual table implementations may overload SQL functions by implementing
  176003. ** the sqlite3_module.xFindFunction() method.
  176004. */
  176005. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  176006. typedef struct Fts5Context Fts5Context;
  176007. typedef struct Fts5PhraseIter Fts5PhraseIter;
  176008. typedef void (*fts5_extension_function)(
  176009. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  176010. Fts5Context *pFts, /* First arg to pass to pApi functions */
  176011. sqlite3_context *pCtx, /* Context for returning result/error */
  176012. int nVal, /* Number of values in apVal[] array */
  176013. sqlite3_value **apVal /* Array of trailing arguments */
  176014. );
  176015. struct Fts5PhraseIter {
  176016. const unsigned char *a;
  176017. const unsigned char *b;
  176018. };
  176019. /*
  176020. ** EXTENSION API FUNCTIONS
  176021. **
  176022. ** xUserData(pFts):
  176023. ** Return a copy of the context pointer the extension function was
  176024. ** registered with.
  176025. **
  176026. ** xColumnTotalSize(pFts, iCol, pnToken):
  176027. ** If parameter iCol is less than zero, set output variable *pnToken
  176028. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  176029. ** non-negative but less than the number of columns in the table, return
  176030. ** the total number of tokens in column iCol, considering all rows in
  176031. ** the FTS5 table.
  176032. **
  176033. ** If parameter iCol is greater than or equal to the number of columns
  176034. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  176035. ** an OOM condition or IO error), an appropriate SQLite error code is
  176036. ** returned.
  176037. **
  176038. ** xColumnCount(pFts):
  176039. ** Return the number of columns in the table.
  176040. **
  176041. ** xColumnSize(pFts, iCol, pnToken):
  176042. ** If parameter iCol is less than zero, set output variable *pnToken
  176043. ** to the total number of tokens in the current row. Or, if iCol is
  176044. ** non-negative but less than the number of columns in the table, set
  176045. ** *pnToken to the number of tokens in column iCol of the current row.
  176046. **
  176047. ** If parameter iCol is greater than or equal to the number of columns
  176048. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  176049. ** an OOM condition or IO error), an appropriate SQLite error code is
  176050. ** returned.
  176051. **
  176052. ** This function may be quite inefficient if used with an FTS5 table
  176053. ** created with the "columnsize=0" option.
  176054. **
  176055. ** xColumnText:
  176056. ** This function attempts to retrieve the text of column iCol of the
  176057. ** current document. If successful, (*pz) is set to point to a buffer
  176058. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  176059. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  176060. ** if an error occurs, an SQLite error code is returned and the final values
  176061. ** of (*pz) and (*pn) are undefined.
  176062. **
  176063. ** xPhraseCount:
  176064. ** Returns the number of phrases in the current query expression.
  176065. **
  176066. ** xPhraseSize:
  176067. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  176068. ** are numbered starting from zero.
  176069. **
  176070. ** xInstCount:
  176071. ** Set *pnInst to the total number of occurrences of all phrases within
  176072. ** the query within the current row. Return SQLITE_OK if successful, or
  176073. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  176074. **
  176075. ** This API can be quite slow if used with an FTS5 table created with the
  176076. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  176077. ** with either "detail=none" or "detail=column" and "content=" option
  176078. ** (i.e. if it is a contentless table), then this API always returns 0.
  176079. **
  176080. ** xInst:
  176081. ** Query for the details of phrase match iIdx within the current row.
  176082. ** Phrase matches are numbered starting from zero, so the iIdx argument
  176083. ** should be greater than or equal to zero and smaller than the value
  176084. ** output by xInstCount().
  176085. **
  176086. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  176087. ** to the column in which it occurs and *piOff the token offset of the
  176088. ** first token of the phrase. The exception is if the table was created
  176089. ** with the offsets=0 option specified. In this case *piOff is always
  176090. ** set to -1.
  176091. **
  176092. ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
  176093. ** if an error occurs.
  176094. **
  176095. ** This API can be quite slow if used with an FTS5 table created with the
  176096. ** "detail=none" or "detail=column" option.
  176097. **
  176098. ** xRowid:
  176099. ** Returns the rowid of the current row.
  176100. **
  176101. ** xTokenize:
  176102. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  176103. **
  176104. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  176105. ** This API function is used to query the FTS table for phrase iPhrase
  176106. ** of the current query. Specifically, a query equivalent to:
  176107. **
  176108. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  176109. **
  176110. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  176111. ** current query is executed. Any column filter that applies to
  176112. ** phrase iPhrase of the current query is included in $p. For each
  176113. ** row visited, the callback function passed as the fourth argument
  176114. ** is invoked. The context and API objects passed to the callback
  176115. ** function may be used to access the properties of each matched row.
  176116. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  176117. ** the third argument to pUserData.
  176118. **
  176119. ** If the callback function returns any value other than SQLITE_OK, the
  176120. ** query is abandoned and the xQueryPhrase function returns immediately.
  176121. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  176122. ** Otherwise, the error code is propagated upwards.
  176123. **
  176124. ** If the query runs to completion without incident, SQLITE_OK is returned.
  176125. ** Or, if some error occurs before the query completes or is aborted by
  176126. ** the callback, an SQLite error code is returned.
  176127. **
  176128. **
  176129. ** xSetAuxdata(pFts5, pAux, xDelete)
  176130. **
  176131. ** Save the pointer passed as the second argument as the extension functions
  176132. ** "auxiliary data". The pointer may then be retrieved by the current or any
  176133. ** future invocation of the same fts5 extension function made as part of
  176134. ** of the same MATCH query using the xGetAuxdata() API.
  176135. **
  176136. ** Each extension function is allocated a single auxiliary data slot for
  176137. ** each FTS query (MATCH expression). If the extension function is invoked
  176138. ** more than once for a single FTS query, then all invocations share a
  176139. ** single auxiliary data context.
  176140. **
  176141. ** If there is already an auxiliary data pointer when this function is
  176142. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  176143. ** was specified along with the original pointer, it is invoked at this
  176144. ** point.
  176145. **
  176146. ** The xDelete callback, if one is specified, is also invoked on the
  176147. ** auxiliary data pointer after the FTS5 query has finished.
  176148. **
  176149. ** If an error (e.g. an OOM condition) occurs within this function, an
  176150. ** the auxiliary data is set to NULL and an error code returned. If the
  176151. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  176152. ** pointer before returning.
  176153. **
  176154. **
  176155. ** xGetAuxdata(pFts5, bClear)
  176156. **
  176157. ** Returns the current auxiliary data pointer for the fts5 extension
  176158. ** function. See the xSetAuxdata() method for details.
  176159. **
  176160. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  176161. ** (set to NULL) before this function returns. In this case the xDelete,
  176162. ** if any, is not invoked.
  176163. **
  176164. **
  176165. ** xRowCount(pFts5, pnRow)
  176166. **
  176167. ** This function is used to retrieve the total number of rows in the table.
  176168. ** In other words, the same value that would be returned by:
  176169. **
  176170. ** SELECT count(*) FROM ftstable;
  176171. **
  176172. ** xPhraseFirst()
  176173. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  176174. ** method, to iterate through all instances of a single query phrase within
  176175. ** the current row. This is the same information as is accessible via the
  176176. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  176177. ** to use, this API may be faster under some circumstances. To iterate
  176178. ** through instances of phrase iPhrase, use the following code:
  176179. **
  176180. ** Fts5PhraseIter iter;
  176181. ** int iCol, iOff;
  176182. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  176183. ** iCol>=0;
  176184. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  176185. ** ){
  176186. ** // An instance of phrase iPhrase at offset iOff of column iCol
  176187. ** }
  176188. **
  176189. ** The Fts5PhraseIter structure is defined above. Applications should not
  176190. ** modify this structure directly - it should only be used as shown above
  176191. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  176192. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  176193. **
  176194. ** This API can be quite slow if used with an FTS5 table created with the
  176195. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  176196. ** with either "detail=none" or "detail=column" and "content=" option
  176197. ** (i.e. if it is a contentless table), then this API always iterates
  176198. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  176199. **
  176200. ** xPhraseNext()
  176201. ** See xPhraseFirst above.
  176202. **
  176203. ** xPhraseFirstColumn()
  176204. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  176205. ** and xPhraseNext() APIs described above. The difference is that instead
  176206. ** of iterating through all instances of a phrase in the current row, these
  176207. ** APIs are used to iterate through the set of columns in the current row
  176208. ** that contain one or more instances of a specified phrase. For example:
  176209. **
  176210. ** Fts5PhraseIter iter;
  176211. ** int iCol;
  176212. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  176213. ** iCol>=0;
  176214. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  176215. ** ){
  176216. ** // Column iCol contains at least one instance of phrase iPhrase
  176217. ** }
  176218. **
  176219. ** This API can be quite slow if used with an FTS5 table created with the
  176220. ** "detail=none" option. If the FTS5 table is created with either
  176221. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  176222. ** then this API always iterates through an empty set (all calls to
  176223. ** xPhraseFirstColumn() set iCol to -1).
  176224. **
  176225. ** The information accessed using this API and its companion
  176226. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  176227. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  176228. ** significantly more efficient than those alternatives when used with
  176229. ** "detail=column" tables.
  176230. **
  176231. ** xPhraseNextColumn()
  176232. ** See xPhraseFirstColumn above.
  176233. */
  176234. struct Fts5ExtensionApi {
  176235. int iVersion; /* Currently always set to 3 */
  176236. void *(*xUserData)(Fts5Context*);
  176237. int (*xColumnCount)(Fts5Context*);
  176238. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  176239. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  176240. int (*xTokenize)(Fts5Context*,
  176241. const char *pText, int nText, /* Text to tokenize */
  176242. void *pCtx, /* Context passed to xToken() */
  176243. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  176244. );
  176245. int (*xPhraseCount)(Fts5Context*);
  176246. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  176247. int (*xInstCount)(Fts5Context*, int *pnInst);
  176248. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  176249. sqlite3_int64 (*xRowid)(Fts5Context*);
  176250. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  176251. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  176252. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  176253. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  176254. );
  176255. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  176256. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  176257. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  176258. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  176259. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  176260. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  176261. };
  176262. /*
  176263. ** CUSTOM AUXILIARY FUNCTIONS
  176264. *************************************************************************/
  176265. /*************************************************************************
  176266. ** CUSTOM TOKENIZERS
  176267. **
  176268. ** Applications may also register custom tokenizer types. A tokenizer
  176269. ** is registered by providing fts5 with a populated instance of the
  176270. ** following structure. All structure methods must be defined, setting
  176271. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  176272. ** behaviour. The structure methods are expected to function as follows:
  176273. **
  176274. ** xCreate:
  176275. ** This function is used to allocate and initialize a tokenizer instance.
  176276. ** A tokenizer instance is required to actually tokenize text.
  176277. **
  176278. ** The first argument passed to this function is a copy of the (void*)
  176279. ** pointer provided by the application when the fts5_tokenizer object
  176280. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  176281. ** The second and third arguments are an array of nul-terminated strings
  176282. ** containing the tokenizer arguments, if any, specified following the
  176283. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  176284. ** to create the FTS5 table.
  176285. **
  176286. ** The final argument is an output variable. If successful, (*ppOut)
  176287. ** should be set to point to the new tokenizer handle and SQLITE_OK
  176288. ** returned. If an error occurs, some value other than SQLITE_OK should
  176289. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  176290. ** is undefined.
  176291. **
  176292. ** xDelete:
  176293. ** This function is invoked to delete a tokenizer handle previously
  176294. ** allocated using xCreate(). Fts5 guarantees that this function will
  176295. ** be invoked exactly once for each successful call to xCreate().
  176296. **
  176297. ** xTokenize:
  176298. ** This function is expected to tokenize the nText byte string indicated
  176299. ** by argument pText. pText may or may not be nul-terminated. The first
  176300. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  176301. ** returned by an earlier call to xCreate().
  176302. **
  176303. ** The second argument indicates the reason that FTS5 is requesting
  176304. ** tokenization of the supplied text. This is always one of the following
  176305. ** four values:
  176306. **
  176307. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  176308. ** or removed from the FTS table. The tokenizer is being invoked to
  176309. ** determine the set of tokens to add to (or delete from) the
  176310. ** FTS index.
  176311. **
  176312. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  176313. ** against the FTS index. The tokenizer is being called to tokenize
  176314. ** a bareword or quoted string specified as part of the query.
  176315. **
  176316. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  176317. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  176318. ** followed by a "*" character, indicating that the last token
  176319. ** returned by the tokenizer will be treated as a token prefix.
  176320. **
  176321. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  176322. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  176323. ** function. Or an fts5_api.xColumnSize() request made by the same
  176324. ** on a columnsize=0 database.
  176325. ** </ul>
  176326. **
  176327. ** For each token in the input string, the supplied callback xToken() must
  176328. ** be invoked. The first argument to it should be a copy of the pointer
  176329. ** passed as the second argument to xTokenize(). The third and fourth
  176330. ** arguments are a pointer to a buffer containing the token text, and the
  176331. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  176332. ** of the first byte of and first byte immediately following the text from
  176333. ** which the token is derived within the input.
  176334. **
  176335. ** The second argument passed to the xToken() callback ("tflags") should
  176336. ** normally be set to 0. The exception is if the tokenizer supports
  176337. ** synonyms. In this case see the discussion below for details.
  176338. **
  176339. ** FTS5 assumes the xToken() callback is invoked for each token in the
  176340. ** order that they occur within the input text.
  176341. **
  176342. ** If an xToken() callback returns any value other than SQLITE_OK, then
  176343. ** the tokenization should be abandoned and the xTokenize() method should
  176344. ** immediately return a copy of the xToken() return value. Or, if the
  176345. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  176346. ** if an error occurs with the xTokenize() implementation itself, it
  176347. ** may abandon the tokenization and return any error code other than
  176348. ** SQLITE_OK or SQLITE_DONE.
  176349. **
  176350. ** SYNONYM SUPPORT
  176351. **
  176352. ** Custom tokenizers may also support synonyms. Consider a case in which a
  176353. ** user wishes to query for a phrase such as "first place". Using the
  176354. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  176355. ** of "first place" within the document set, but not alternative forms
  176356. ** such as "1st place". In some applications, it would be better to match
  176357. ** all instances of "first place" or "1st place" regardless of which form
  176358. ** the user specified in the MATCH query text.
  176359. **
  176360. ** There are several ways to approach this in FTS5:
  176361. **
  176362. ** <ol><li> By mapping all synonyms to a single token. In this case, the
  176363. ** In the above example, this means that the tokenizer returns the
  176364. ** same token for inputs "first" and "1st". Say that token is in
  176365. ** fact "first", so that when the user inserts the document "I won
  176366. ** 1st place" entries are added to the index for tokens "i", "won",
  176367. ** "first" and "place". If the user then queries for '1st + place',
  176368. ** the tokenizer substitutes "first" for "1st" and the query works
  176369. ** as expected.
  176370. **
  176371. ** <li> By adding multiple synonyms for a single term to the FTS index.
  176372. ** In this case, when tokenizing query text, the tokenizer may
  176373. ** provide multiple synonyms for a single term within the document.
  176374. ** FTS5 then queries the index for each synonym individually. For
  176375. ** example, faced with the query:
  176376. **
  176377. ** <codeblock>
  176378. ** ... MATCH 'first place'</codeblock>
  176379. **
  176380. ** the tokenizer offers both "1st" and "first" as synonyms for the
  176381. ** first token in the MATCH query and FTS5 effectively runs a query
  176382. ** similar to:
  176383. **
  176384. ** <codeblock>
  176385. ** ... MATCH '(first OR 1st) place'</codeblock>
  176386. **
  176387. ** except that, for the purposes of auxiliary functions, the query
  176388. ** still appears to contain just two phrases - "(first OR 1st)"
  176389. ** being treated as a single phrase.
  176390. **
  176391. ** <li> By adding multiple synonyms for a single term to the FTS index.
  176392. ** Using this method, when tokenizing document text, the tokenizer
  176393. ** provides multiple synonyms for each token. So that when a
  176394. ** document such as "I won first place" is tokenized, entries are
  176395. ** added to the FTS index for "i", "won", "first", "1st" and
  176396. ** "place".
  176397. **
  176398. ** This way, even if the tokenizer does not provide synonyms
  176399. ** when tokenizing query text (it should not - to do would be
  176400. ** inefficient), it doesn't matter if the user queries for
  176401. ** 'first + place' or '1st + place', as there are entires in the
  176402. ** FTS index corresponding to both forms of the first token.
  176403. ** </ol>
  176404. **
  176405. ** Whether it is parsing document or query text, any call to xToken that
  176406. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  176407. ** is considered to supply a synonym for the previous token. For example,
  176408. ** when parsing the document "I won first place", a tokenizer that supports
  176409. ** synonyms would call xToken() 5 times, as follows:
  176410. **
  176411. ** <codeblock>
  176412. ** xToken(pCtx, 0, "i", 1, 0, 1);
  176413. ** xToken(pCtx, 0, "won", 3, 2, 5);
  176414. ** xToken(pCtx, 0, "first", 5, 6, 11);
  176415. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  176416. ** xToken(pCtx, 0, "place", 5, 12, 17);
  176417. **</codeblock>
  176418. **
  176419. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  176420. ** xToken() is called. Multiple synonyms may be specified for a single token
  176421. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  176422. ** There is no limit to the number of synonyms that may be provided for a
  176423. ** single token.
  176424. **
  176425. ** In many cases, method (1) above is the best approach. It does not add
  176426. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  176427. ** so it is efficient in terms of disk space and query speed. However, it
  176428. ** does not support prefix queries very well. If, as suggested above, the
  176429. ** token "first" is subsituted for "1st" by the tokenizer, then the query:
  176430. **
  176431. ** <codeblock>
  176432. ** ... MATCH '1s*'</codeblock>
  176433. **
  176434. ** will not match documents that contain the token "1st" (as the tokenizer
  176435. ** will probably not map "1s" to any prefix of "first").
  176436. **
  176437. ** For full prefix support, method (3) may be preferred. In this case,
  176438. ** because the index contains entries for both "first" and "1st", prefix
  176439. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  176440. ** extra entries are added to the FTS index, this method uses more space
  176441. ** within the database.
  176442. **
  176443. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  176444. ** a query such as '1s*' will match documents that contain the literal
  176445. ** token "1st", but not "first" (assuming the tokenizer is not able to
  176446. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  176447. ** will match against "1st" and "first". This method does not require
  176448. ** extra disk space, as no extra entries are added to the FTS index.
  176449. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  176450. ** as separate queries of the FTS index are required for each synonym.
  176451. **
  176452. ** When using methods (2) or (3), it is important that the tokenizer only
  176453. ** provide synonyms when tokenizing document text (method (2)) or query
  176454. ** text (method (3)), not both. Doing so will not cause any errors, but is
  176455. ** inefficient.
  176456. */
  176457. typedef struct Fts5Tokenizer Fts5Tokenizer;
  176458. typedef struct fts5_tokenizer fts5_tokenizer;
  176459. struct fts5_tokenizer {
  176460. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  176461. void (*xDelete)(Fts5Tokenizer*);
  176462. int (*xTokenize)(Fts5Tokenizer*,
  176463. void *pCtx,
  176464. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  176465. const char *pText, int nText,
  176466. int (*xToken)(
  176467. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  176468. int tflags, /* Mask of FTS5_TOKEN_* flags */
  176469. const char *pToken, /* Pointer to buffer containing token */
  176470. int nToken, /* Size of token in bytes */
  176471. int iStart, /* Byte offset of token within input text */
  176472. int iEnd /* Byte offset of end of token within input text */
  176473. )
  176474. );
  176475. };
  176476. /* Flags that may be passed as the third argument to xTokenize() */
  176477. #define FTS5_TOKENIZE_QUERY 0x0001
  176478. #define FTS5_TOKENIZE_PREFIX 0x0002
  176479. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  176480. #define FTS5_TOKENIZE_AUX 0x0008
  176481. /* Flags that may be passed by the tokenizer implementation back to FTS5
  176482. ** as the third argument to the supplied xToken callback. */
  176483. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  176484. /*
  176485. ** END OF CUSTOM TOKENIZERS
  176486. *************************************************************************/
  176487. /*************************************************************************
  176488. ** FTS5 EXTENSION REGISTRATION API
  176489. */
  176490. typedef struct fts5_api fts5_api;
  176491. struct fts5_api {
  176492. int iVersion; /* Currently always set to 2 */
  176493. /* Create a new tokenizer */
  176494. int (*xCreateTokenizer)(
  176495. fts5_api *pApi,
  176496. const char *zName,
  176497. void *pContext,
  176498. fts5_tokenizer *pTokenizer,
  176499. void (*xDestroy)(void*)
  176500. );
  176501. /* Find an existing tokenizer */
  176502. int (*xFindTokenizer)(
  176503. fts5_api *pApi,
  176504. const char *zName,
  176505. void **ppContext,
  176506. fts5_tokenizer *pTokenizer
  176507. );
  176508. /* Create a new auxiliary function */
  176509. int (*xCreateFunction)(
  176510. fts5_api *pApi,
  176511. const char *zName,
  176512. void *pContext,
  176513. fts5_extension_function xFunction,
  176514. void (*xDestroy)(void*)
  176515. );
  176516. };
  176517. /*
  176518. ** END OF REGISTRATION API
  176519. *************************************************************************/
  176520. #if 0
  176521. } /* end of the 'extern "C"' block */
  176522. #endif
  176523. #endif /* _FTS5_H */
  176524. /*
  176525. ** 2014 May 31
  176526. **
  176527. ** The author disclaims copyright to this source code. In place of
  176528. ** a legal notice, here is a blessing:
  176529. **
  176530. ** May you do good and not evil.
  176531. ** May you find forgiveness for yourself and forgive others.
  176532. ** May you share freely, never taking more than you give.
  176533. **
  176534. ******************************************************************************
  176535. **
  176536. */
  176537. #ifndef _FTS5INT_H
  176538. #define _FTS5INT_H
  176539. /* #include "fts5.h" */
  176540. /* #include "sqlite3ext.h" */
  176541. SQLITE_EXTENSION_INIT1
  176542. /* #include <string.h> */
  176543. /* #include <assert.h> */
  176544. #ifndef SQLITE_AMALGAMATION
  176545. typedef unsigned char u8;
  176546. typedef unsigned int u32;
  176547. typedef unsigned short u16;
  176548. typedef short i16;
  176549. typedef sqlite3_int64 i64;
  176550. typedef sqlite3_uint64 u64;
  176551. #ifndef ArraySize
  176552. # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
  176553. #endif
  176554. #define testcase(x)
  176555. #define ALWAYS(x) 1
  176556. #define NEVER(x) 0
  176557. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  176558. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  176559. /*
  176560. ** Constants for the largest and smallest possible 64-bit signed integers.
  176561. */
  176562. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  176563. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  176564. #endif
  176565. /* Truncate very long tokens to this many bytes. Hard limit is
  176566. ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
  176567. ** field that occurs at the start of each leaf page (see fts5_index.c). */
  176568. #define FTS5_MAX_TOKEN_SIZE 32768
  176569. /*
  176570. ** Maximum number of prefix indexes on single FTS5 table. This must be
  176571. ** less than 32. If it is set to anything large than that, an #error
  176572. ** directive in fts5_index.c will cause the build to fail.
  176573. */
  176574. #define FTS5_MAX_PREFIX_INDEXES 31
  176575. #define FTS5_DEFAULT_NEARDIST 10
  176576. #define FTS5_DEFAULT_RANK "bm25"
  176577. /* Name of rank and rowid columns */
  176578. #define FTS5_RANK_NAME "rank"
  176579. #define FTS5_ROWID_NAME "rowid"
  176580. #ifdef SQLITE_DEBUG
  176581. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  176582. static int sqlite3Fts5Corrupt(void);
  176583. #else
  176584. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  176585. #endif
  176586. /*
  176587. ** The assert_nc() macro is similar to the assert() macro, except that it
  176588. ** is used for assert() conditions that are true only if it can be
  176589. ** guranteed that the database is not corrupt.
  176590. */
  176591. #ifdef SQLITE_DEBUG
  176592. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  176593. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  176594. #else
  176595. # define assert_nc(x) assert(x)
  176596. #endif
  176597. /* Mark a function parameter as unused, to suppress nuisance compiler
  176598. ** warnings. */
  176599. #ifndef UNUSED_PARAM
  176600. # define UNUSED_PARAM(X) (void)(X)
  176601. #endif
  176602. #ifndef UNUSED_PARAM2
  176603. # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
  176604. #endif
  176605. typedef struct Fts5Global Fts5Global;
  176606. typedef struct Fts5Colset Fts5Colset;
  176607. /* If a NEAR() clump or phrase may only match a specific set of columns,
  176608. ** then an object of the following type is used to record the set of columns.
  176609. ** Each entry in the aiCol[] array is a column that may be matched.
  176610. **
  176611. ** This object is used by fts5_expr.c and fts5_index.c.
  176612. */
  176613. struct Fts5Colset {
  176614. int nCol;
  176615. int aiCol[1];
  176616. };
  176617. /**************************************************************************
  176618. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  176619. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  176620. */
  176621. typedef struct Fts5Config Fts5Config;
  176622. /*
  176623. ** An instance of the following structure encodes all information that can
  176624. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  176625. **
  176626. ** And all information loaded from the %_config table.
  176627. **
  176628. ** nAutomerge:
  176629. ** The minimum number of segments that an auto-merge operation should
  176630. ** attempt to merge together. A value of 1 sets the object to use the
  176631. ** compile time default. Zero disables auto-merge altogether.
  176632. **
  176633. ** zContent:
  176634. **
  176635. ** zContentRowid:
  176636. ** The value of the content_rowid= option, if one was specified. Or
  176637. ** the string "rowid" otherwise. This text is not quoted - if it is
  176638. ** used as part of an SQL statement it needs to be quoted appropriately.
  176639. **
  176640. ** zContentExprlist:
  176641. **
  176642. ** pzErrmsg:
  176643. ** This exists in order to allow the fts5_index.c module to return a
  176644. ** decent error message if it encounters a file-format version it does
  176645. ** not understand.
  176646. **
  176647. ** bColumnsize:
  176648. ** True if the %_docsize table is created.
  176649. **
  176650. ** bPrefixIndex:
  176651. ** This is only used for debugging. If set to false, any prefix indexes
  176652. ** are ignored. This value is configured using:
  176653. **
  176654. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  176655. **
  176656. */
  176657. struct Fts5Config {
  176658. sqlite3 *db; /* Database handle */
  176659. char *zDb; /* Database holding FTS index (e.g. "main") */
  176660. char *zName; /* Name of FTS index */
  176661. int nCol; /* Number of columns */
  176662. char **azCol; /* Column names */
  176663. u8 *abUnindexed; /* True for unindexed columns */
  176664. int nPrefix; /* Number of prefix indexes */
  176665. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  176666. int eContent; /* An FTS5_CONTENT value */
  176667. char *zContent; /* content table */
  176668. char *zContentRowid; /* "content_rowid=" option value */
  176669. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  176670. int eDetail; /* FTS5_DETAIL_XXX value */
  176671. char *zContentExprlist;
  176672. Fts5Tokenizer *pTok;
  176673. fts5_tokenizer *pTokApi;
  176674. /* Values loaded from the %_config table */
  176675. int iCookie; /* Incremented when %_config is modified */
  176676. int pgsz; /* Approximate page size used in %_data */
  176677. int nAutomerge; /* 'automerge' setting */
  176678. int nCrisisMerge; /* Maximum allowed segments per level */
  176679. int nUsermerge; /* 'usermerge' setting */
  176680. int nHashSize; /* Bytes of memory for in-memory hash */
  176681. char *zRank; /* Name of rank function */
  176682. char *zRankArgs; /* Arguments to rank function */
  176683. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  176684. char **pzErrmsg;
  176685. #ifdef SQLITE_DEBUG
  176686. int bPrefixIndex; /* True to use prefix-indexes */
  176687. #endif
  176688. };
  176689. /* Current expected value of %_config table 'version' field */
  176690. #define FTS5_CURRENT_VERSION 4
  176691. #define FTS5_CONTENT_NORMAL 0
  176692. #define FTS5_CONTENT_NONE 1
  176693. #define FTS5_CONTENT_EXTERNAL 2
  176694. #define FTS5_DETAIL_FULL 0
  176695. #define FTS5_DETAIL_NONE 1
  176696. #define FTS5_DETAIL_COLUMNS 2
  176697. static int sqlite3Fts5ConfigParse(
  176698. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  176699. );
  176700. static void sqlite3Fts5ConfigFree(Fts5Config*);
  176701. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  176702. static int sqlite3Fts5Tokenize(
  176703. Fts5Config *pConfig, /* FTS5 Configuration object */
  176704. int flags, /* FTS5_TOKENIZE_* flags */
  176705. const char *pText, int nText, /* Text to tokenize */
  176706. void *pCtx, /* Context passed to xToken() */
  176707. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  176708. );
  176709. static void sqlite3Fts5Dequote(char *z);
  176710. /* Load the contents of the %_config table */
  176711. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  176712. /* Set the value of a single config attribute */
  176713. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  176714. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  176715. /*
  176716. ** End of interface to code in fts5_config.c.
  176717. **************************************************************************/
  176718. /**************************************************************************
  176719. ** Interface to code in fts5_buffer.c.
  176720. */
  176721. /*
  176722. ** Buffer object for the incremental building of string data.
  176723. */
  176724. typedef struct Fts5Buffer Fts5Buffer;
  176725. struct Fts5Buffer {
  176726. u8 *p;
  176727. int n;
  176728. int nSpace;
  176729. };
  176730. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
  176731. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  176732. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
  176733. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  176734. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  176735. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  176736. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  176737. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  176738. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  176739. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  176740. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  176741. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  176742. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  176743. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  176744. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  176745. (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
  176746. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  176747. )
  176748. /* Write and decode big-endian 32-bit integer values */
  176749. static void sqlite3Fts5Put32(u8*, int);
  176750. static int sqlite3Fts5Get32(const u8*);
  176751. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  176752. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
  176753. typedef struct Fts5PoslistReader Fts5PoslistReader;
  176754. struct Fts5PoslistReader {
  176755. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  176756. const u8 *a; /* Position list to iterate through */
  176757. int n; /* Size of buffer at a[] in bytes */
  176758. int i; /* Current offset in a[] */
  176759. u8 bFlag; /* For client use (any custom purpose) */
  176760. /* Output variables */
  176761. u8 bEof; /* Set to true at EOF */
  176762. i64 iPos; /* (iCol<<32) + iPos */
  176763. };
  176764. static int sqlite3Fts5PoslistReaderInit(
  176765. const u8 *a, int n, /* Poslist buffer to iterate through */
  176766. Fts5PoslistReader *pIter /* Iterator object to initialize */
  176767. );
  176768. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  176769. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  176770. struct Fts5PoslistWriter {
  176771. i64 iPrev;
  176772. };
  176773. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  176774. static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
  176775. static int sqlite3Fts5PoslistNext64(
  176776. const u8 *a, int n, /* Buffer containing poslist */
  176777. int *pi, /* IN/OUT: Offset within a[] */
  176778. i64 *piOff /* IN/OUT: Current offset */
  176779. );
  176780. /* Malloc utility */
  176781. static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
  176782. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  176783. /* Character set tests (like isspace(), isalpha() etc.) */
  176784. static int sqlite3Fts5IsBareword(char t);
  176785. /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
  176786. typedef struct Fts5Termset Fts5Termset;
  176787. static int sqlite3Fts5TermsetNew(Fts5Termset**);
  176788. static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
  176789. static void sqlite3Fts5TermsetFree(Fts5Termset*);
  176790. /*
  176791. ** End of interface to code in fts5_buffer.c.
  176792. **************************************************************************/
  176793. /**************************************************************************
  176794. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  176795. ** to access the data stored in the %_data table.
  176796. */
  176797. typedef struct Fts5Index Fts5Index;
  176798. typedef struct Fts5IndexIter Fts5IndexIter;
  176799. struct Fts5IndexIter {
  176800. i64 iRowid;
  176801. const u8 *pData;
  176802. int nData;
  176803. u8 bEof;
  176804. };
  176805. #define sqlite3Fts5IterEof(x) ((x)->bEof)
  176806. /*
  176807. ** Values used as part of the flags argument passed to IndexQuery().
  176808. */
  176809. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  176810. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  176811. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  176812. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  176813. /* The following are used internally by the fts5_index.c module. They are
  176814. ** defined here only to make it easier to avoid clashes with the flags
  176815. ** above. */
  176816. #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
  176817. #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
  176818. /*
  176819. ** Create/destroy an Fts5Index object.
  176820. */
  176821. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  176822. static int sqlite3Fts5IndexClose(Fts5Index *p);
  176823. /*
  176824. ** Return a simple checksum value based on the arguments.
  176825. */
  176826. static u64 sqlite3Fts5IndexEntryCksum(
  176827. i64 iRowid,
  176828. int iCol,
  176829. int iPos,
  176830. int iIdx,
  176831. const char *pTerm,
  176832. int nTerm
  176833. );
  176834. /*
  176835. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  176836. ** size. Return the number of bytes in the nChar character prefix of the
  176837. ** buffer, or 0 if there are less than nChar characters in total.
  176838. */
  176839. static int sqlite3Fts5IndexCharlenToBytelen(
  176840. const char *p,
  176841. int nByte,
  176842. int nChar
  176843. );
  176844. /*
  176845. ** Open a new iterator to iterate though all rowids that match the
  176846. ** specified token or token prefix.
  176847. */
  176848. static int sqlite3Fts5IndexQuery(
  176849. Fts5Index *p, /* FTS index to query */
  176850. const char *pToken, int nToken, /* Token (or prefix) to query for */
  176851. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  176852. Fts5Colset *pColset, /* Match these columns only */
  176853. Fts5IndexIter **ppIter /* OUT: New iterator object */
  176854. );
  176855. /*
  176856. ** The various operations on open token or token prefix iterators opened
  176857. ** using sqlite3Fts5IndexQuery().
  176858. */
  176859. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  176860. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  176861. /*
  176862. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  176863. */
  176864. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  176865. /*
  176866. ** This interface is used by the fts5vocab module.
  176867. */
  176868. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  176869. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  176870. /*
  176871. ** Insert or remove data to or from the index. Each time a document is
  176872. ** added to or removed from the index, this function is called one or more
  176873. ** times.
  176874. **
  176875. ** For an insert, it must be called once for each token in the new document.
  176876. ** If the operation is a delete, it must be called (at least) once for each
  176877. ** unique token in the document with an iCol value less than zero. The iPos
  176878. ** argument is ignored for a delete.
  176879. */
  176880. static int sqlite3Fts5IndexWrite(
  176881. Fts5Index *p, /* Index to write to */
  176882. int iCol, /* Column token appears in (-ve -> delete) */
  176883. int iPos, /* Position of token within column */
  176884. const char *pToken, int nToken /* Token to add or remove to or from index */
  176885. );
  176886. /*
  176887. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  176888. ** document iDocid.
  176889. */
  176890. static int sqlite3Fts5IndexBeginWrite(
  176891. Fts5Index *p, /* Index to write to */
  176892. int bDelete, /* True if current operation is a delete */
  176893. i64 iDocid /* Docid to add or remove data from */
  176894. );
  176895. /*
  176896. ** Flush any data stored in the in-memory hash tables to the database.
  176897. ** Also close any open blob handles.
  176898. */
  176899. static int sqlite3Fts5IndexSync(Fts5Index *p);
  176900. /*
  176901. ** Discard any data stored in the in-memory hash tables. Do not write it
  176902. ** to the database. Additionally, assume that the contents of the %_data
  176903. ** table may have changed on disk. So any in-memory caches of %_data
  176904. ** records must be invalidated.
  176905. */
  176906. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  176907. /*
  176908. ** Get or set the "averages" values.
  176909. */
  176910. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  176911. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  176912. /*
  176913. ** Functions called by the storage module as part of integrity-check.
  176914. */
  176915. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  176916. /*
  176917. ** Called during virtual module initialization to register UDF
  176918. ** fts5_decode() with SQLite
  176919. */
  176920. static int sqlite3Fts5IndexInit(sqlite3*);
  176921. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  176922. /*
  176923. ** Return the total number of entries read from the %_data table by
  176924. ** this connection since it was created.
  176925. */
  176926. static int sqlite3Fts5IndexReads(Fts5Index *p);
  176927. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  176928. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  176929. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  176930. static int sqlite3Fts5IndexReset(Fts5Index *p);
  176931. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  176932. /*
  176933. ** End of interface to code in fts5_index.c.
  176934. **************************************************************************/
  176935. /**************************************************************************
  176936. ** Interface to code in fts5_varint.c.
  176937. */
  176938. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  176939. static int sqlite3Fts5GetVarintLen(u32 iVal);
  176940. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  176941. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  176942. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  176943. #define fts5GetVarint sqlite3Fts5GetVarint
  176944. #define fts5FastGetVarint32(a, iOff, nVal) { \
  176945. nVal = (a)[iOff++]; \
  176946. if( nVal & 0x80 ){ \
  176947. iOff--; \
  176948. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  176949. } \
  176950. }
  176951. /*
  176952. ** End of interface to code in fts5_varint.c.
  176953. **************************************************************************/
  176954. /**************************************************************************
  176955. ** Interface to code in fts5.c.
  176956. */
  176957. static int sqlite3Fts5GetTokenizer(
  176958. Fts5Global*,
  176959. const char **azArg,
  176960. int nArg,
  176961. Fts5Tokenizer**,
  176962. fts5_tokenizer**,
  176963. char **pzErr
  176964. );
  176965. static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
  176966. /*
  176967. ** End of interface to code in fts5.c.
  176968. **************************************************************************/
  176969. /**************************************************************************
  176970. ** Interface to code in fts5_hash.c.
  176971. */
  176972. typedef struct Fts5Hash Fts5Hash;
  176973. /*
  176974. ** Create a hash table, free a hash table.
  176975. */
  176976. static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
  176977. static void sqlite3Fts5HashFree(Fts5Hash*);
  176978. static int sqlite3Fts5HashWrite(
  176979. Fts5Hash*,
  176980. i64 iRowid, /* Rowid for this entry */
  176981. int iCol, /* Column token appears in (-ve -> delete) */
  176982. int iPos, /* Position of token within column */
  176983. char bByte,
  176984. const char *pToken, int nToken /* Token to add or remove to or from index */
  176985. );
  176986. /*
  176987. ** Empty (but do not delete) a hash table.
  176988. */
  176989. static void sqlite3Fts5HashClear(Fts5Hash*);
  176990. static int sqlite3Fts5HashQuery(
  176991. Fts5Hash*, /* Hash table to query */
  176992. const char *pTerm, int nTerm, /* Query term */
  176993. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  176994. int *pnDoclist /* OUT: Size of doclist in bytes */
  176995. );
  176996. static int sqlite3Fts5HashScanInit(
  176997. Fts5Hash*, /* Hash table to query */
  176998. const char *pTerm, int nTerm /* Query prefix */
  176999. );
  177000. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  177001. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  177002. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  177003. const char **pzTerm, /* OUT: term (nul-terminated) */
  177004. const u8 **ppDoclist, /* OUT: pointer to doclist */
  177005. int *pnDoclist /* OUT: size of doclist in bytes */
  177006. );
  177007. /*
  177008. ** End of interface to code in fts5_hash.c.
  177009. **************************************************************************/
  177010. /**************************************************************************
  177011. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  177012. ** code to access the data stored in the %_content and %_docsize tables.
  177013. */
  177014. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  177015. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  177016. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  177017. typedef struct Fts5Storage Fts5Storage;
  177018. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  177019. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  177020. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  177021. static int sqlite3Fts5DropAll(Fts5Config*);
  177022. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  177023. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
  177024. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  177025. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  177026. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  177027. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  177028. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  177029. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  177030. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  177031. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  177032. static int sqlite3Fts5StorageSync(Fts5Storage *p);
  177033. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  177034. static int sqlite3Fts5StorageConfigValue(
  177035. Fts5Storage *p, const char*, sqlite3_value*, int
  177036. );
  177037. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  177038. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  177039. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  177040. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  177041. static int sqlite3Fts5StorageReset(Fts5Storage *p);
  177042. /*
  177043. ** End of interface to code in fts5_storage.c.
  177044. **************************************************************************/
  177045. /**************************************************************************
  177046. ** Interface to code in fts5_expr.c.
  177047. */
  177048. typedef struct Fts5Expr Fts5Expr;
  177049. typedef struct Fts5ExprNode Fts5ExprNode;
  177050. typedef struct Fts5Parse Fts5Parse;
  177051. typedef struct Fts5Token Fts5Token;
  177052. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  177053. typedef struct Fts5ExprNearset Fts5ExprNearset;
  177054. struct Fts5Token {
  177055. const char *p; /* Token text (not NULL terminated) */
  177056. int n; /* Size of buffer p in bytes */
  177057. };
  177058. /* Parse a MATCH expression. */
  177059. static int sqlite3Fts5ExprNew(
  177060. Fts5Config *pConfig,
  177061. int iCol, /* Column on LHS of MATCH operator */
  177062. const char *zExpr,
  177063. Fts5Expr **ppNew,
  177064. char **pzErr
  177065. );
  177066. /*
  177067. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  177068. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  177069. ** rc = sqlite3Fts5ExprNext(pExpr)
  177070. ** ){
  177071. ** // The document with rowid iRowid matches the expression!
  177072. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  177073. ** }
  177074. */
  177075. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  177076. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  177077. static int sqlite3Fts5ExprEof(Fts5Expr*);
  177078. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  177079. static void sqlite3Fts5ExprFree(Fts5Expr*);
  177080. /* Called during startup to register a UDF with SQLite */
  177081. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  177082. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  177083. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  177084. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  177085. typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
  177086. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
  177087. static int sqlite3Fts5ExprPopulatePoslists(
  177088. Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
  177089. );
  177090. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
  177091. static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
  177092. static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
  177093. /*******************************************
  177094. ** The fts5_expr.c API above this point is used by the other hand-written
  177095. ** C code in this module. The interfaces below this point are called by
  177096. ** the parser code in fts5parse.y. */
  177097. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  177098. static Fts5ExprNode *sqlite3Fts5ParseNode(
  177099. Fts5Parse *pParse,
  177100. int eType,
  177101. Fts5ExprNode *pLeft,
  177102. Fts5ExprNode *pRight,
  177103. Fts5ExprNearset *pNear
  177104. );
  177105. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  177106. Fts5Parse *pParse,
  177107. Fts5ExprNode *pLeft,
  177108. Fts5ExprNode *pRight
  177109. );
  177110. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  177111. Fts5Parse *pParse,
  177112. Fts5ExprPhrase *pPhrase,
  177113. Fts5Token *pToken,
  177114. int bPrefix
  177115. );
  177116. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
  177117. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  177118. Fts5Parse*,
  177119. Fts5ExprNearset*,
  177120. Fts5ExprPhrase*
  177121. );
  177122. static Fts5Colset *sqlite3Fts5ParseColset(
  177123. Fts5Parse*,
  177124. Fts5Colset*,
  177125. Fts5Token *
  177126. );
  177127. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  177128. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  177129. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  177130. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  177131. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
  177132. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
  177133. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  177134. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  177135. /*
  177136. ** End of interface to code in fts5_expr.c.
  177137. **************************************************************************/
  177138. /**************************************************************************
  177139. ** Interface to code in fts5_aux.c.
  177140. */
  177141. static int sqlite3Fts5AuxInit(fts5_api*);
  177142. /*
  177143. ** End of interface to code in fts5_aux.c.
  177144. **************************************************************************/
  177145. /**************************************************************************
  177146. ** Interface to code in fts5_tokenizer.c.
  177147. */
  177148. static int sqlite3Fts5TokenizerInit(fts5_api*);
  177149. /*
  177150. ** End of interface to code in fts5_tokenizer.c.
  177151. **************************************************************************/
  177152. /**************************************************************************
  177153. ** Interface to code in fts5_vocab.c.
  177154. */
  177155. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  177156. /*
  177157. ** End of interface to code in fts5_vocab.c.
  177158. **************************************************************************/
  177159. /**************************************************************************
  177160. ** Interface to automatically generated code in fts5_unicode2.c.
  177161. */
  177162. static int sqlite3Fts5UnicodeIsalnum(int c);
  177163. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  177164. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  177165. /*
  177166. ** End of interface to code in fts5_unicode2.c.
  177167. **************************************************************************/
  177168. #endif
  177169. #define FTS5_OR 1
  177170. #define FTS5_AND 2
  177171. #define FTS5_NOT 3
  177172. #define FTS5_TERM 4
  177173. #define FTS5_COLON 5
  177174. #define FTS5_MINUS 6
  177175. #define FTS5_LCP 7
  177176. #define FTS5_RCP 8
  177177. #define FTS5_STRING 9
  177178. #define FTS5_LP 10
  177179. #define FTS5_RP 11
  177180. #define FTS5_CARET 12
  177181. #define FTS5_COMMA 13
  177182. #define FTS5_PLUS 14
  177183. #define FTS5_STAR 15
  177184. /*
  177185. ** 2000-05-29
  177186. **
  177187. ** The author disclaims copyright to this source code. In place of
  177188. ** a legal notice, here is a blessing:
  177189. **
  177190. ** May you do good and not evil.
  177191. ** May you find forgiveness for yourself and forgive others.
  177192. ** May you share freely, never taking more than you give.
  177193. **
  177194. *************************************************************************
  177195. ** Driver template for the LEMON parser generator.
  177196. **
  177197. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  177198. ** this template to construct a parser. The "lemon" program inserts text
  177199. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  177200. ** interstitial "-" characters) contained in this template is changed into
  177201. ** the value of the %name directive from the grammar. Otherwise, the content
  177202. ** of this template is copied straight through into the generate parser
  177203. ** source file.
  177204. **
  177205. ** The following is the concatenation of all %include directives from the
  177206. ** input grammar file:
  177207. */
  177208. /* #include <stdio.h> */
  177209. /************ Begin %include sections from the grammar ************************/
  177210. /* #include "fts5Int.h" */
  177211. /* #include "fts5parse.h" */
  177212. /*
  177213. ** Disable all error recovery processing in the parser push-down
  177214. ** automaton.
  177215. */
  177216. #define fts5YYNOERRORRECOVERY 1
  177217. /*
  177218. ** Make fts5yytestcase() the same as testcase()
  177219. */
  177220. #define fts5yytestcase(X) testcase(X)
  177221. /*
  177222. ** Indicate that sqlite3ParserFree() will never be called with a null
  177223. ** pointer.
  177224. */
  177225. #define fts5YYPARSEFREENOTNULL 1
  177226. /*
  177227. ** Alternative datatype for the argument to the malloc() routine passed
  177228. ** into sqlite3ParserAlloc(). The default is size_t.
  177229. */
  177230. #define fts5YYMALLOCARGTYPE u64
  177231. /**************** End of %include directives **********************************/
  177232. /* These constants specify the various numeric values for terminal symbols
  177233. ** in a format understandable to "makeheaders". This section is blank unless
  177234. ** "lemon" is run with the "-m" command-line option.
  177235. ***************** Begin makeheaders token definitions *************************/
  177236. /**************** End makeheaders token definitions ***************************/
  177237. /* The next sections is a series of control #defines.
  177238. ** various aspects of the generated parser.
  177239. ** fts5YYCODETYPE is the data type used to store the integer codes
  177240. ** that represent terminal and non-terminal symbols.
  177241. ** "unsigned char" is used if there are fewer than
  177242. ** 256 symbols. Larger types otherwise.
  177243. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  177244. ** any terminal or nonterminal symbol.
  177245. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  177246. ** (also known as: "terminal symbols") have fall-back
  177247. ** values which should be used if the original symbol
  177248. ** would not parse. This permits keywords to sometimes
  177249. ** be used as identifiers, for example.
  177250. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  177251. ** that indicate what to do in response to the next
  177252. ** token.
  177253. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  177254. ** symbols. Background: A "minor type" is a semantic
  177255. ** value associated with a terminal or non-terminal
  177256. ** symbols. For example, for an "ID" terminal symbol,
  177257. ** the minor type might be the name of the identifier.
  177258. ** Each non-terminal can have a different minor type.
  177259. ** Terminal symbols all have the same minor type, though.
  177260. ** This macros defines the minor type for terminal
  177261. ** symbols.
  177262. ** fts5YYMINORTYPE is the data type used for all minor types.
  177263. ** This is typically a union of many types, one of
  177264. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  177265. ** for terminal symbols is called "fts5yy0".
  177266. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  177267. ** zero the stack is dynamically sized using realloc()
  177268. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  177269. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  177270. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  177271. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  177272. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  177273. ** defined, then do no error processing.
  177274. ** fts5YYNSTATE the combined number of states.
  177275. ** fts5YYNRULE the number of rules in the grammar
  177276. ** fts5YYNFTS5TOKEN Number of terminal symbols
  177277. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  177278. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  177279. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  177280. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  177281. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  177282. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  177283. ** fts5YY_MIN_REDUCE Minimum value for reduce actions
  177284. ** fts5YY_MAX_REDUCE Maximum value for reduce actions
  177285. */
  177286. #ifndef INTERFACE
  177287. # define INTERFACE 1
  177288. #endif
  177289. /************* Begin control #defines *****************************************/
  177290. #define fts5YYCODETYPE unsigned char
  177291. #define fts5YYNOCODE 29
  177292. #define fts5YYACTIONTYPE unsigned char
  177293. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  177294. typedef union {
  177295. int fts5yyinit;
  177296. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  177297. int fts5yy4;
  177298. Fts5ExprPhrase* fts5yy11;
  177299. Fts5ExprNearset* fts5yy14;
  177300. Fts5Colset* fts5yy43;
  177301. Fts5ExprNode* fts5yy54;
  177302. } fts5YYMINORTYPE;
  177303. #ifndef fts5YYSTACKDEPTH
  177304. #define fts5YYSTACKDEPTH 100
  177305. #endif
  177306. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  177307. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  177308. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
  177309. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
  177310. #define fts5YYNSTATE 35
  177311. #define fts5YYNRULE 28
  177312. #define fts5YYNFTS5TOKEN 16
  177313. #define fts5YY_MAX_SHIFT 34
  177314. #define fts5YY_MIN_SHIFTREDUCE 52
  177315. #define fts5YY_MAX_SHIFTREDUCE 79
  177316. #define fts5YY_ERROR_ACTION 80
  177317. #define fts5YY_ACCEPT_ACTION 81
  177318. #define fts5YY_NO_ACTION 82
  177319. #define fts5YY_MIN_REDUCE 83
  177320. #define fts5YY_MAX_REDUCE 110
  177321. /************* End control #defines *******************************************/
  177322. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  177323. ** otherwise.
  177324. **
  177325. ** Applications can choose to define fts5yytestcase() in the %include section
  177326. ** to a macro that can assist in verifying code coverage. For production
  177327. ** code the fts5yytestcase() macro should be turned off. But it is useful
  177328. ** for testing.
  177329. */
  177330. #ifndef fts5yytestcase
  177331. # define fts5yytestcase(X)
  177332. #endif
  177333. /* Next are the tables used to determine what action to take based on the
  177334. ** current state and lookahead token. These tables are used to implement
  177335. ** functions that take a state number and lookahead value and return an
  177336. ** action integer.
  177337. **
  177338. ** Suppose the action integer is N. Then the action is determined as
  177339. ** follows
  177340. **
  177341. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  177342. ** token onto the stack and goto state N.
  177343. **
  177344. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  177345. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  177346. **
  177347. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  177348. **
  177349. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  177350. **
  177351. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  177352. ** slots in the fts5yy_action[] table.
  177353. **
  177354. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  177355. ** and fts5YY_MAX_REDUCE
  177356. **
  177357. ** The action table is constructed as a single large table named fts5yy_action[].
  177358. ** Given state S and lookahead X, the action is computed as either:
  177359. **
  177360. ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  177361. ** (B) N = fts5yy_default[S]
  177362. **
  177363. ** The (A) formula is preferred. The B formula is used instead if
  177364. ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.
  177365. **
  177366. ** The formulas above are for computing the action when the lookahead is
  177367. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  177368. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  177369. ** the fts5yy_shift_ofst[] array.
  177370. **
  177371. ** The following are the tables generated in this section:
  177372. **
  177373. ** fts5yy_action[] A single table containing all actions.
  177374. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  177375. ** fts5yy_action. Used to detect hash collisions.
  177376. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  177377. ** shifting terminals.
  177378. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  177379. ** shifting non-terminals after a reduce.
  177380. ** fts5yy_default[] Default action for each state.
  177381. **
  177382. *********** Begin parsing tables **********************************************/
  177383. #define fts5YY_ACTTAB_COUNT (105)
  177384. static const fts5YYACTIONTYPE fts5yy_action[] = {
  177385. /* 0 */ 81, 20, 96, 6, 28, 99, 98, 26, 26, 18,
  177386. /* 10 */ 96, 6, 28, 17, 98, 56, 26, 19, 96, 6,
  177387. /* 20 */ 28, 14, 98, 108, 26, 92, 96, 6, 28, 25,
  177388. /* 30 */ 98, 78, 26, 21, 96, 6, 28, 107, 98, 58,
  177389. /* 40 */ 26, 29, 96, 6, 28, 32, 98, 22, 26, 24,
  177390. /* 50 */ 16, 23, 11, 1, 14, 13, 24, 16, 31, 11,
  177391. /* 60 */ 3, 97, 13, 27, 8, 98, 82, 26, 7, 4,
  177392. /* 70 */ 5, 3, 4, 5, 3, 83, 4, 5, 3, 63,
  177393. /* 80 */ 33, 34, 62, 12, 2, 86, 13, 10, 12, 71,
  177394. /* 90 */ 10, 13, 78, 5, 3, 78, 9, 30, 75, 82,
  177395. /* 100 */ 54, 57, 53, 57, 15,
  177396. };
  177397. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  177398. /* 0 */ 17, 18, 19, 20, 21, 23, 23, 25, 25, 18,
  177399. /* 10 */ 19, 20, 21, 7, 23, 9, 25, 18, 19, 20,
  177400. /* 20 */ 21, 9, 23, 27, 25, 18, 19, 20, 21, 25,
  177401. /* 30 */ 23, 15, 25, 18, 19, 20, 21, 27, 23, 9,
  177402. /* 40 */ 25, 18, 19, 20, 21, 14, 23, 22, 25, 6,
  177403. /* 50 */ 7, 22, 9, 10, 9, 12, 6, 7, 13, 9,
  177404. /* 60 */ 3, 19, 12, 21, 5, 23, 28, 25, 5, 1,
  177405. /* 70 */ 2, 3, 1, 2, 3, 0, 1, 2, 3, 11,
  177406. /* 80 */ 25, 26, 11, 9, 10, 5, 12, 10, 9, 11,
  177407. /* 90 */ 10, 12, 15, 2, 3, 15, 24, 25, 9, 28,
  177408. /* 100 */ 8, 9, 8, 9, 9, 28, 28, 28, 28, 28,
  177409. /* 110 */ 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  177410. /* 120 */ 28,
  177411. };
  177412. #define fts5YY_SHIFT_COUNT (34)
  177413. #define fts5YY_SHIFT_MIN (0)
  177414. #define fts5YY_SHIFT_MAX (95)
  177415. static const unsigned char fts5yy_shift_ofst[] = {
  177416. /* 0 */ 43, 43, 43, 43, 43, 43, 50, 74, 79, 45,
  177417. /* 10 */ 12, 80, 77, 12, 16, 16, 30, 30, 68, 71,
  177418. /* 20 */ 75, 91, 92, 94, 6, 31, 31, 59, 63, 57,
  177419. /* 30 */ 31, 89, 95, 31, 78,
  177420. };
  177421. #define fts5YY_REDUCE_COUNT (17)
  177422. #define fts5YY_REDUCE_MIN (-18)
  177423. #define fts5YY_REDUCE_MAX (72)
  177424. static const signed char fts5yy_reduce_ofst[] = {
  177425. /* 0 */ -17, -9, -1, 7, 15, 23, 42, -18, -18, 55,
  177426. /* 10 */ 72, -4, -4, 4, -4, 10, 25, 29,
  177427. };
  177428. static const fts5YYACTIONTYPE fts5yy_default[] = {
  177429. /* 0 */ 80, 80, 80, 80, 80, 80, 95, 80, 80, 105,
  177430. /* 10 */ 80, 110, 110, 80, 110, 110, 80, 80, 80, 80,
  177431. /* 20 */ 80, 91, 80, 80, 80, 101, 100, 80, 80, 90,
  177432. /* 30 */ 103, 80, 80, 104, 80,
  177433. };
  177434. /********** End of lemon-generated parsing tables *****************************/
  177435. /* The next table maps tokens (terminal symbols) into fallback tokens.
  177436. ** If a construct like the following:
  177437. **
  177438. ** %fallback ID X Y Z.
  177439. **
  177440. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  177441. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  177442. ** but it does not parse, the type of the token is changed to ID and
  177443. ** the parse is retried before an error is thrown.
  177444. **
  177445. ** This feature can be used, for example, to cause some keywords in a language
  177446. ** to revert to identifiers if they keyword does not apply in the context where
  177447. ** it appears.
  177448. */
  177449. #ifdef fts5YYFALLBACK
  177450. static const fts5YYCODETYPE fts5yyFallback[] = {
  177451. };
  177452. #endif /* fts5YYFALLBACK */
  177453. /* The following structure represents a single element of the
  177454. ** parser's stack. Information stored includes:
  177455. **
  177456. ** + The state number for the parser at this level of the stack.
  177457. **
  177458. ** + The value of the token stored at this level of the stack.
  177459. ** (In other words, the "major" token.)
  177460. **
  177461. ** + The semantic value stored at this level of the stack. This is
  177462. ** the information used by the action routines in the grammar.
  177463. ** It is sometimes called the "minor" token.
  177464. **
  177465. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  177466. ** actually contains the reduce action for the second half of the
  177467. ** SHIFTREDUCE.
  177468. */
  177469. struct fts5yyStackEntry {
  177470. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  177471. fts5YYCODETYPE major; /* The major token value. This is the code
  177472. ** number for the token at this stack level */
  177473. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  177474. ** is the value of the token */
  177475. };
  177476. typedef struct fts5yyStackEntry fts5yyStackEntry;
  177477. /* The state of the parser is completely contained in an instance of
  177478. ** the following structure */
  177479. struct fts5yyParser {
  177480. fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
  177481. #ifdef fts5YYTRACKMAXSTACKDEPTH
  177482. int fts5yyhwm; /* High-water mark of the stack */
  177483. #endif
  177484. #ifndef fts5YYNOERRORRECOVERY
  177485. int fts5yyerrcnt; /* Shifts left before out of the error */
  177486. #endif
  177487. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  177488. #if fts5YYSTACKDEPTH<=0
  177489. int fts5yystksz; /* Current side of the stack */
  177490. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  177491. fts5yyStackEntry fts5yystk0; /* First stack entry */
  177492. #else
  177493. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  177494. fts5yyStackEntry *fts5yystackEnd; /* Last entry in the stack */
  177495. #endif
  177496. };
  177497. typedef struct fts5yyParser fts5yyParser;
  177498. #ifndef NDEBUG
  177499. /* #include <stdio.h> */
  177500. static FILE *fts5yyTraceFILE = 0;
  177501. static char *fts5yyTracePrompt = 0;
  177502. #endif /* NDEBUG */
  177503. #ifndef NDEBUG
  177504. /*
  177505. ** Turn parser tracing on by giving a stream to which to write the trace
  177506. ** and a prompt to preface each trace message. Tracing is turned off
  177507. ** by making either argument NULL
  177508. **
  177509. ** Inputs:
  177510. ** <ul>
  177511. ** <li> A FILE* to which trace output should be written.
  177512. ** If NULL, then tracing is turned off.
  177513. ** <li> A prefix string written at the beginning of every
  177514. ** line of trace output. If NULL, then tracing is
  177515. ** turned off.
  177516. ** </ul>
  177517. **
  177518. ** Outputs:
  177519. ** None.
  177520. */
  177521. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  177522. fts5yyTraceFILE = TraceFILE;
  177523. fts5yyTracePrompt = zTracePrompt;
  177524. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  177525. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  177526. }
  177527. #endif /* NDEBUG */
  177528. #if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
  177529. /* For tracing shifts, the names of all terminals and nonterminals
  177530. ** are required. The following table supplies these names */
  177531. static const char *const fts5yyTokenName[] = {
  177532. /* 0 */ "$",
  177533. /* 1 */ "OR",
  177534. /* 2 */ "AND",
  177535. /* 3 */ "NOT",
  177536. /* 4 */ "TERM",
  177537. /* 5 */ "COLON",
  177538. /* 6 */ "MINUS",
  177539. /* 7 */ "LCP",
  177540. /* 8 */ "RCP",
  177541. /* 9 */ "STRING",
  177542. /* 10 */ "LP",
  177543. /* 11 */ "RP",
  177544. /* 12 */ "CARET",
  177545. /* 13 */ "COMMA",
  177546. /* 14 */ "PLUS",
  177547. /* 15 */ "STAR",
  177548. /* 16 */ "error",
  177549. /* 17 */ "input",
  177550. /* 18 */ "expr",
  177551. /* 19 */ "cnearset",
  177552. /* 20 */ "exprlist",
  177553. /* 21 */ "colset",
  177554. /* 22 */ "colsetlist",
  177555. /* 23 */ "nearset",
  177556. /* 24 */ "nearphrases",
  177557. /* 25 */ "phrase",
  177558. /* 26 */ "neardist_opt",
  177559. /* 27 */ "star_opt",
  177560. };
  177561. #endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */
  177562. #ifndef NDEBUG
  177563. /* For tracing reduce actions, the names of all rules are required.
  177564. */
  177565. static const char *const fts5yyRuleName[] = {
  177566. /* 0 */ "input ::= expr",
  177567. /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
  177568. /* 2 */ "colset ::= LCP colsetlist RCP",
  177569. /* 3 */ "colset ::= STRING",
  177570. /* 4 */ "colset ::= MINUS STRING",
  177571. /* 5 */ "colsetlist ::= colsetlist STRING",
  177572. /* 6 */ "colsetlist ::= STRING",
  177573. /* 7 */ "expr ::= expr AND expr",
  177574. /* 8 */ "expr ::= expr OR expr",
  177575. /* 9 */ "expr ::= expr NOT expr",
  177576. /* 10 */ "expr ::= colset COLON LP expr RP",
  177577. /* 11 */ "expr ::= LP expr RP",
  177578. /* 12 */ "expr ::= exprlist",
  177579. /* 13 */ "exprlist ::= cnearset",
  177580. /* 14 */ "exprlist ::= exprlist cnearset",
  177581. /* 15 */ "cnearset ::= nearset",
  177582. /* 16 */ "cnearset ::= colset COLON nearset",
  177583. /* 17 */ "nearset ::= phrase",
  177584. /* 18 */ "nearset ::= CARET phrase",
  177585. /* 19 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  177586. /* 20 */ "nearphrases ::= phrase",
  177587. /* 21 */ "nearphrases ::= nearphrases phrase",
  177588. /* 22 */ "neardist_opt ::=",
  177589. /* 23 */ "neardist_opt ::= COMMA STRING",
  177590. /* 24 */ "phrase ::= phrase PLUS STRING star_opt",
  177591. /* 25 */ "phrase ::= STRING star_opt",
  177592. /* 26 */ "star_opt ::= STAR",
  177593. /* 27 */ "star_opt ::=",
  177594. };
  177595. #endif /* NDEBUG */
  177596. #if fts5YYSTACKDEPTH<=0
  177597. /*
  177598. ** Try to increase the size of the parser stack. Return the number
  177599. ** of errors. Return 0 on success.
  177600. */
  177601. static int fts5yyGrowStack(fts5yyParser *p){
  177602. int newSize;
  177603. int idx;
  177604. fts5yyStackEntry *pNew;
  177605. newSize = p->fts5yystksz*2 + 100;
  177606. idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
  177607. if( p->fts5yystack==&p->fts5yystk0 ){
  177608. pNew = malloc(newSize*sizeof(pNew[0]));
  177609. if( pNew ) pNew[0] = p->fts5yystk0;
  177610. }else{
  177611. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  177612. }
  177613. if( pNew ){
  177614. p->fts5yystack = pNew;
  177615. p->fts5yytos = &p->fts5yystack[idx];
  177616. #ifndef NDEBUG
  177617. if( fts5yyTraceFILE ){
  177618. fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  177619. fts5yyTracePrompt, p->fts5yystksz, newSize);
  177620. }
  177621. #endif
  177622. p->fts5yystksz = newSize;
  177623. }
  177624. return pNew==0;
  177625. }
  177626. #endif
  177627. /* Datatype of the argument to the memory allocated passed as the
  177628. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  177629. ** putting an appropriate #define in the %include section of the input
  177630. ** grammar.
  177631. */
  177632. #ifndef fts5YYMALLOCARGTYPE
  177633. # define fts5YYMALLOCARGTYPE size_t
  177634. #endif
  177635. /* Initialize a new parser that has already been allocated.
  177636. */
  177637. static void sqlite3Fts5ParserInit(void *fts5yypParser){
  177638. fts5yyParser *pParser = (fts5yyParser*)fts5yypParser;
  177639. #ifdef fts5YYTRACKMAXSTACKDEPTH
  177640. pParser->fts5yyhwm = 0;
  177641. #endif
  177642. #if fts5YYSTACKDEPTH<=0
  177643. pParser->fts5yytos = NULL;
  177644. pParser->fts5yystack = NULL;
  177645. pParser->fts5yystksz = 0;
  177646. if( fts5yyGrowStack(pParser) ){
  177647. pParser->fts5yystack = &pParser->fts5yystk0;
  177648. pParser->fts5yystksz = 1;
  177649. }
  177650. #endif
  177651. #ifndef fts5YYNOERRORRECOVERY
  177652. pParser->fts5yyerrcnt = -1;
  177653. #endif
  177654. pParser->fts5yytos = pParser->fts5yystack;
  177655. pParser->fts5yystack[0].stateno = 0;
  177656. pParser->fts5yystack[0].major = 0;
  177657. #if fts5YYSTACKDEPTH>0
  177658. pParser->fts5yystackEnd = &pParser->fts5yystack[fts5YYSTACKDEPTH-1];
  177659. #endif
  177660. }
  177661. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  177662. /*
  177663. ** This function allocates a new parser.
  177664. ** The only argument is a pointer to a function which works like
  177665. ** malloc.
  177666. **
  177667. ** Inputs:
  177668. ** A pointer to the function used to allocate memory.
  177669. **
  177670. ** Outputs:
  177671. ** A pointer to a parser. This pointer is used in subsequent calls
  177672. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  177673. */
  177674. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
  177675. fts5yyParser *pParser;
  177676. pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  177677. if( pParser ) sqlite3Fts5ParserInit(pParser);
  177678. return pParser;
  177679. }
  177680. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  177681. /* The following function deletes the "minor type" or semantic value
  177682. ** associated with a symbol. The symbol can be either a terminal
  177683. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  177684. ** a pointer to the value to be deleted. The code used to do the
  177685. ** deletions is derived from the %destructor and/or %token_destructor
  177686. ** directives of the input grammar.
  177687. */
  177688. static void fts5yy_destructor(
  177689. fts5yyParser *fts5yypParser, /* The parser */
  177690. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  177691. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  177692. ){
  177693. sqlite3Fts5ParserARG_FETCH;
  177694. switch( fts5yymajor ){
  177695. /* Here is inserted the actions which take place when a
  177696. ** terminal or non-terminal is destroyed. This can happen
  177697. ** when the symbol is popped from the stack during a
  177698. ** reduce or during error processing or when a parser is
  177699. ** being destroyed before it is finished parsing.
  177700. **
  177701. ** Note: during a reduce, the only symbols destroyed are those
  177702. ** which appear on the RHS of the rule, but which are *not* used
  177703. ** inside the C code.
  177704. */
  177705. /********* Begin destructor definitions ***************************************/
  177706. case 17: /* input */
  177707. {
  177708. (void)pParse;
  177709. }
  177710. break;
  177711. case 18: /* expr */
  177712. case 19: /* cnearset */
  177713. case 20: /* exprlist */
  177714. {
  177715. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy54));
  177716. }
  177717. break;
  177718. case 21: /* colset */
  177719. case 22: /* colsetlist */
  177720. {
  177721. sqlite3_free((fts5yypminor->fts5yy43));
  177722. }
  177723. break;
  177724. case 23: /* nearset */
  177725. case 24: /* nearphrases */
  177726. {
  177727. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy14));
  177728. }
  177729. break;
  177730. case 25: /* phrase */
  177731. {
  177732. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11));
  177733. }
  177734. break;
  177735. /********* End destructor definitions *****************************************/
  177736. default: break; /* If no destructor action specified: do nothing */
  177737. }
  177738. }
  177739. /*
  177740. ** Pop the parser's stack once.
  177741. **
  177742. ** If there is a destructor routine associated with the token which
  177743. ** is popped from the stack, then call it.
  177744. */
  177745. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  177746. fts5yyStackEntry *fts5yytos;
  177747. assert( pParser->fts5yytos!=0 );
  177748. assert( pParser->fts5yytos > pParser->fts5yystack );
  177749. fts5yytos = pParser->fts5yytos--;
  177750. #ifndef NDEBUG
  177751. if( fts5yyTraceFILE ){
  177752. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  177753. fts5yyTracePrompt,
  177754. fts5yyTokenName[fts5yytos->major]);
  177755. }
  177756. #endif
  177757. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  177758. }
  177759. /*
  177760. ** Clear all secondary memory allocations from the parser
  177761. */
  177762. static void sqlite3Fts5ParserFinalize(void *p){
  177763. fts5yyParser *pParser = (fts5yyParser*)p;
  177764. while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
  177765. #if fts5YYSTACKDEPTH<=0
  177766. if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
  177767. #endif
  177768. }
  177769. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  177770. /*
  177771. ** Deallocate and destroy a parser. Destructors are called for
  177772. ** all stack elements before shutting the parser down.
  177773. **
  177774. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  177775. ** is defined in a %include section of the input grammar) then it is
  177776. ** assumed that the input pointer is never NULL.
  177777. */
  177778. static void sqlite3Fts5ParserFree(
  177779. void *p, /* The parser to be deleted */
  177780. void (*freeProc)(void*) /* Function used to reclaim memory */
  177781. ){
  177782. #ifndef fts5YYPARSEFREENEVERNULL
  177783. if( p==0 ) return;
  177784. #endif
  177785. sqlite3Fts5ParserFinalize(p);
  177786. (*freeProc)(p);
  177787. }
  177788. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  177789. /*
  177790. ** Return the peak depth of the stack for a parser.
  177791. */
  177792. #ifdef fts5YYTRACKMAXSTACKDEPTH
  177793. static int sqlite3Fts5ParserStackPeak(void *p){
  177794. fts5yyParser *pParser = (fts5yyParser*)p;
  177795. return pParser->fts5yyhwm;
  177796. }
  177797. #endif
  177798. /* This array of booleans keeps track of the parser statement
  177799. ** coverage. The element fts5yycoverage[X][Y] is set when the parser
  177800. ** is in state X and has a lookahead token Y. In a well-tested
  177801. ** systems, every element of this matrix should end up being set.
  177802. */
  177803. #if defined(fts5YYCOVERAGE)
  177804. static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];
  177805. #endif
  177806. /*
  177807. ** Write into out a description of every state/lookahead combination that
  177808. **
  177809. ** (1) has not been used by the parser, and
  177810. ** (2) is not a syntax error.
  177811. **
  177812. ** Return the number of missed state/lookahead combinations.
  177813. */
  177814. #if defined(fts5YYCOVERAGE)
  177815. static int sqlite3Fts5ParserCoverage(FILE *out){
  177816. int stateno, iLookAhead, i;
  177817. int nMissed = 0;
  177818. for(stateno=0; stateno<fts5YYNSTATE; stateno++){
  177819. i = fts5yy_shift_ofst[stateno];
  177820. for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){
  177821. if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  177822. if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  177823. if( out ){
  177824. fprintf(out,"State %d lookahead %s %s\n", stateno,
  177825. fts5yyTokenName[iLookAhead],
  177826. fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  177827. }
  177828. }
  177829. }
  177830. return nMissed;
  177831. }
  177832. #endif
  177833. /*
  177834. ** Find the appropriate action for a parser given the terminal
  177835. ** look-ahead token iLookAhead.
  177836. */
  177837. static unsigned int fts5yy_find_shift_action(
  177838. fts5yyParser *pParser, /* The parser */
  177839. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  177840. ){
  177841. int i;
  177842. int stateno = pParser->fts5yytos->stateno;
  177843. if( stateno>fts5YY_MAX_SHIFT ) return stateno;
  177844. assert( stateno <= fts5YY_SHIFT_COUNT );
  177845. #if defined(fts5YYCOVERAGE)
  177846. fts5yycoverage[stateno][iLookAhead] = 1;
  177847. #endif
  177848. do{
  177849. i = fts5yy_shift_ofst[stateno];
  177850. assert( i>=0 );
  177851. assert( i+fts5YYNFTS5TOKEN<=(int)sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0]) );
  177852. assert( iLookAhead!=fts5YYNOCODE );
  177853. assert( iLookAhead < fts5YYNFTS5TOKEN );
  177854. i += iLookAhead;
  177855. if( fts5yy_lookahead[i]!=iLookAhead ){
  177856. #ifdef fts5YYFALLBACK
  177857. fts5YYCODETYPE iFallback; /* Fallback token */
  177858. if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
  177859. && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
  177860. #ifndef NDEBUG
  177861. if( fts5yyTraceFILE ){
  177862. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  177863. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  177864. }
  177865. #endif
  177866. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  177867. iLookAhead = iFallback;
  177868. continue;
  177869. }
  177870. #endif
  177871. #ifdef fts5YYWILDCARD
  177872. {
  177873. int j = i - iLookAhead + fts5YYWILDCARD;
  177874. if(
  177875. #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
  177876. j>=0 &&
  177877. #endif
  177878. #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
  177879. j<fts5YY_ACTTAB_COUNT &&
  177880. #endif
  177881. fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0
  177882. ){
  177883. #ifndef NDEBUG
  177884. if( fts5yyTraceFILE ){
  177885. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  177886. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  177887. fts5yyTokenName[fts5YYWILDCARD]);
  177888. }
  177889. #endif /* NDEBUG */
  177890. return fts5yy_action[j];
  177891. }
  177892. }
  177893. #endif /* fts5YYWILDCARD */
  177894. return fts5yy_default[stateno];
  177895. }else{
  177896. return fts5yy_action[i];
  177897. }
  177898. }while(1);
  177899. }
  177900. /*
  177901. ** Find the appropriate action for a parser given the non-terminal
  177902. ** look-ahead token iLookAhead.
  177903. */
  177904. static int fts5yy_find_reduce_action(
  177905. int stateno, /* Current state number */
  177906. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  177907. ){
  177908. int i;
  177909. #ifdef fts5YYERRORSYMBOL
  177910. if( stateno>fts5YY_REDUCE_COUNT ){
  177911. return fts5yy_default[stateno];
  177912. }
  177913. #else
  177914. assert( stateno<=fts5YY_REDUCE_COUNT );
  177915. #endif
  177916. i = fts5yy_reduce_ofst[stateno];
  177917. assert( iLookAhead!=fts5YYNOCODE );
  177918. i += iLookAhead;
  177919. #ifdef fts5YYERRORSYMBOL
  177920. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  177921. return fts5yy_default[stateno];
  177922. }
  177923. #else
  177924. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  177925. assert( fts5yy_lookahead[i]==iLookAhead );
  177926. #endif
  177927. return fts5yy_action[i];
  177928. }
  177929. /*
  177930. ** The following routine is called if the stack overflows.
  177931. */
  177932. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
  177933. sqlite3Fts5ParserARG_FETCH;
  177934. #ifndef NDEBUG
  177935. if( fts5yyTraceFILE ){
  177936. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  177937. }
  177938. #endif
  177939. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  177940. /* Here code is inserted which will execute if the parser
  177941. ** stack every overflows */
  177942. /******** Begin %stack_overflow code ******************************************/
  177943. sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
  177944. /******** End %stack_overflow code ********************************************/
  177945. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  177946. }
  177947. /*
  177948. ** Print tracing information for a SHIFT action
  177949. */
  177950. #ifndef NDEBUG
  177951. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){
  177952. if( fts5yyTraceFILE ){
  177953. if( fts5yyNewState<fts5YYNSTATE ){
  177954. fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n",
  177955. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  177956. fts5yyNewState);
  177957. }else{
  177958. fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  177959. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  177960. fts5yyNewState - fts5YY_MIN_REDUCE);
  177961. }
  177962. }
  177963. }
  177964. #else
  177965. # define fts5yyTraceShift(X,Y,Z)
  177966. #endif
  177967. /*
  177968. ** Perform a shift action.
  177969. */
  177970. static void fts5yy_shift(
  177971. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  177972. int fts5yyNewState, /* The new state to shift in */
  177973. int fts5yyMajor, /* The major token to shift in */
  177974. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
  177975. ){
  177976. fts5yyStackEntry *fts5yytos;
  177977. fts5yypParser->fts5yytos++;
  177978. #ifdef fts5YYTRACKMAXSTACKDEPTH
  177979. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  177980. fts5yypParser->fts5yyhwm++;
  177981. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
  177982. }
  177983. #endif
  177984. #if fts5YYSTACKDEPTH>0
  177985. if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
  177986. fts5yypParser->fts5yytos--;
  177987. fts5yyStackOverflow(fts5yypParser);
  177988. return;
  177989. }
  177990. #else
  177991. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
  177992. if( fts5yyGrowStack(fts5yypParser) ){
  177993. fts5yypParser->fts5yytos--;
  177994. fts5yyStackOverflow(fts5yypParser);
  177995. return;
  177996. }
  177997. }
  177998. #endif
  177999. if( fts5yyNewState > fts5YY_MAX_SHIFT ){
  178000. fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  178001. }
  178002. fts5yytos = fts5yypParser->fts5yytos;
  178003. fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
  178004. fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
  178005. fts5yytos->minor.fts5yy0 = fts5yyMinor;
  178006. fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift");
  178007. }
  178008. /* The following table contains information about every rule that
  178009. ** is used during the reduce.
  178010. */
  178011. static const struct {
  178012. fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  178013. signed char nrhs; /* Negative of the number of RHS symbols in the rule */
  178014. } fts5yyRuleInfo[] = {
  178015. { 17, -1 }, /* (0) input ::= expr */
  178016. { 21, -4 }, /* (1) colset ::= MINUS LCP colsetlist RCP */
  178017. { 21, -3 }, /* (2) colset ::= LCP colsetlist RCP */
  178018. { 21, -1 }, /* (3) colset ::= STRING */
  178019. { 21, -2 }, /* (4) colset ::= MINUS STRING */
  178020. { 22, -2 }, /* (5) colsetlist ::= colsetlist STRING */
  178021. { 22, -1 }, /* (6) colsetlist ::= STRING */
  178022. { 18, -3 }, /* (7) expr ::= expr AND expr */
  178023. { 18, -3 }, /* (8) expr ::= expr OR expr */
  178024. { 18, -3 }, /* (9) expr ::= expr NOT expr */
  178025. { 18, -5 }, /* (10) expr ::= colset COLON LP expr RP */
  178026. { 18, -3 }, /* (11) expr ::= LP expr RP */
  178027. { 18, -1 }, /* (12) expr ::= exprlist */
  178028. { 20, -1 }, /* (13) exprlist ::= cnearset */
  178029. { 20, -2 }, /* (14) exprlist ::= exprlist cnearset */
  178030. { 19, -1 }, /* (15) cnearset ::= nearset */
  178031. { 19, -3 }, /* (16) cnearset ::= colset COLON nearset */
  178032. { 23, -1 }, /* (17) nearset ::= phrase */
  178033. { 23, -2 }, /* (18) nearset ::= CARET phrase */
  178034. { 23, -5 }, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
  178035. { 24, -1 }, /* (20) nearphrases ::= phrase */
  178036. { 24, -2 }, /* (21) nearphrases ::= nearphrases phrase */
  178037. { 26, 0 }, /* (22) neardist_opt ::= */
  178038. { 26, -2 }, /* (23) neardist_opt ::= COMMA STRING */
  178039. { 25, -4 }, /* (24) phrase ::= phrase PLUS STRING star_opt */
  178040. { 25, -2 }, /* (25) phrase ::= STRING star_opt */
  178041. { 27, -1 }, /* (26) star_opt ::= STAR */
  178042. { 27, 0 }, /* (27) star_opt ::= */
  178043. };
  178044. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  178045. /*
  178046. ** Perform a reduce action and the shift that must immediately
  178047. ** follow the reduce.
  178048. **
  178049. ** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
  178050. ** access to the lookahead token (if any). The fts5yyLookahead will be fts5YYNOCODE
  178051. ** if the lookahead token has already been consumed. As this procedure is
  178052. ** only called from one place, optimizing compilers will in-line it, which
  178053. ** means that the extra parameters have no performance impact.
  178054. */
  178055. static void fts5yy_reduce(
  178056. fts5yyParser *fts5yypParser, /* The parser */
  178057. unsigned int fts5yyruleno, /* Number of the rule by which to reduce */
  178058. int fts5yyLookahead, /* Lookahead token, or fts5YYNOCODE if none */
  178059. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken /* Value of the lookahead token */
  178060. ){
  178061. int fts5yygoto; /* The next state */
  178062. int fts5yyact; /* The next action */
  178063. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  178064. int fts5yysize; /* Amount to pop the stack */
  178065. sqlite3Fts5ParserARG_FETCH;
  178066. (void)fts5yyLookahead;
  178067. (void)fts5yyLookaheadToken;
  178068. fts5yymsp = fts5yypParser->fts5yytos;
  178069. #ifndef NDEBUG
  178070. if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  178071. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  178072. if( fts5yysize ){
  178073. fprintf(fts5yyTraceFILE, "%sReduce %d [%s], go to state %d.\n",
  178074. fts5yyTracePrompt,
  178075. fts5yyruleno, fts5yyRuleName[fts5yyruleno], fts5yymsp[fts5yysize].stateno);
  178076. }else{
  178077. fprintf(fts5yyTraceFILE, "%sReduce %d [%s].\n",
  178078. fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno]);
  178079. }
  178080. }
  178081. #endif /* NDEBUG */
  178082. /* Check that the stack is large enough to grow by a single entry
  178083. ** if the RHS of the rule is empty. This ensures that there is room
  178084. ** enough on the stack to push the LHS value */
  178085. if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
  178086. #ifdef fts5YYTRACKMAXSTACKDEPTH
  178087. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  178088. fts5yypParser->fts5yyhwm++;
  178089. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
  178090. }
  178091. #endif
  178092. #if fts5YYSTACKDEPTH>0
  178093. if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
  178094. fts5yyStackOverflow(fts5yypParser);
  178095. return;
  178096. }
  178097. #else
  178098. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
  178099. if( fts5yyGrowStack(fts5yypParser) ){
  178100. fts5yyStackOverflow(fts5yypParser);
  178101. return;
  178102. }
  178103. fts5yymsp = fts5yypParser->fts5yytos;
  178104. }
  178105. #endif
  178106. }
  178107. switch( fts5yyruleno ){
  178108. /* Beginning here are the reduction cases. A typical example
  178109. ** follows:
  178110. ** case 0:
  178111. ** #line <lineno> <grammarfile>
  178112. ** { ... } // User supplied code
  178113. ** #line <lineno> <thisfile>
  178114. ** break;
  178115. */
  178116. /********** Begin reduce actions **********************************************/
  178117. fts5YYMINORTYPE fts5yylhsminor;
  178118. case 0: /* input ::= expr */
  178119. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy54); }
  178120. break;
  178121. case 1: /* colset ::= MINUS LCP colsetlist RCP */
  178122. {
  178123. fts5yymsp[-3].minor.fts5yy43 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy43);
  178124. }
  178125. break;
  178126. case 2: /* colset ::= LCP colsetlist RCP */
  178127. { fts5yymsp[-2].minor.fts5yy43 = fts5yymsp[-1].minor.fts5yy43; }
  178128. break;
  178129. case 3: /* colset ::= STRING */
  178130. {
  178131. fts5yylhsminor.fts5yy43 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  178132. }
  178133. fts5yymsp[0].minor.fts5yy43 = fts5yylhsminor.fts5yy43;
  178134. break;
  178135. case 4: /* colset ::= MINUS STRING */
  178136. {
  178137. fts5yymsp[-1].minor.fts5yy43 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  178138. fts5yymsp[-1].minor.fts5yy43 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy43);
  178139. }
  178140. break;
  178141. case 5: /* colsetlist ::= colsetlist STRING */
  178142. {
  178143. fts5yylhsminor.fts5yy43 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy43, &fts5yymsp[0].minor.fts5yy0); }
  178144. fts5yymsp[-1].minor.fts5yy43 = fts5yylhsminor.fts5yy43;
  178145. break;
  178146. case 6: /* colsetlist ::= STRING */
  178147. {
  178148. fts5yylhsminor.fts5yy43 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  178149. }
  178150. fts5yymsp[0].minor.fts5yy43 = fts5yylhsminor.fts5yy43;
  178151. break;
  178152. case 7: /* expr ::= expr AND expr */
  178153. {
  178154. fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy54, fts5yymsp[0].minor.fts5yy54, 0);
  178155. }
  178156. fts5yymsp[-2].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
  178157. break;
  178158. case 8: /* expr ::= expr OR expr */
  178159. {
  178160. fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy54, fts5yymsp[0].minor.fts5yy54, 0);
  178161. }
  178162. fts5yymsp[-2].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
  178163. break;
  178164. case 9: /* expr ::= expr NOT expr */
  178165. {
  178166. fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy54, fts5yymsp[0].minor.fts5yy54, 0);
  178167. }
  178168. fts5yymsp[-2].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
  178169. break;
  178170. case 10: /* expr ::= colset COLON LP expr RP */
  178171. {
  178172. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy54, fts5yymsp[-4].minor.fts5yy43);
  178173. fts5yylhsminor.fts5yy54 = fts5yymsp[-1].minor.fts5yy54;
  178174. }
  178175. fts5yymsp[-4].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
  178176. break;
  178177. case 11: /* expr ::= LP expr RP */
  178178. {fts5yymsp[-2].minor.fts5yy54 = fts5yymsp[-1].minor.fts5yy54;}
  178179. break;
  178180. case 12: /* expr ::= exprlist */
  178181. case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
  178182. {fts5yylhsminor.fts5yy54 = fts5yymsp[0].minor.fts5yy54;}
  178183. fts5yymsp[0].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
  178184. break;
  178185. case 14: /* exprlist ::= exprlist cnearset */
  178186. {
  178187. fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy54, fts5yymsp[0].minor.fts5yy54);
  178188. }
  178189. fts5yymsp[-1].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
  178190. break;
  178191. case 15: /* cnearset ::= nearset */
  178192. {
  178193. fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy14);
  178194. }
  178195. fts5yymsp[0].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
  178196. break;
  178197. case 16: /* cnearset ::= colset COLON nearset */
  178198. {
  178199. fts5yylhsminor.fts5yy54 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy14);
  178200. sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy54, fts5yymsp[-2].minor.fts5yy43);
  178201. }
  178202. fts5yymsp[-2].minor.fts5yy54 = fts5yylhsminor.fts5yy54;
  178203. break;
  178204. case 17: /* nearset ::= phrase */
  178205. { fts5yylhsminor.fts5yy14 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
  178206. fts5yymsp[0].minor.fts5yy14 = fts5yylhsminor.fts5yy14;
  178207. break;
  178208. case 18: /* nearset ::= CARET phrase */
  178209. {
  178210. sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy11);
  178211. fts5yymsp[-1].minor.fts5yy14 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
  178212. }
  178213. break;
  178214. case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  178215. {
  178216. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  178217. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy14, &fts5yymsp[-1].minor.fts5yy0);
  178218. fts5yylhsminor.fts5yy14 = fts5yymsp[-2].minor.fts5yy14;
  178219. }
  178220. fts5yymsp[-4].minor.fts5yy14 = fts5yylhsminor.fts5yy14;
  178221. break;
  178222. case 20: /* nearphrases ::= phrase */
  178223. {
  178224. fts5yylhsminor.fts5yy14 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
  178225. }
  178226. fts5yymsp[0].minor.fts5yy14 = fts5yylhsminor.fts5yy14;
  178227. break;
  178228. case 21: /* nearphrases ::= nearphrases phrase */
  178229. {
  178230. fts5yylhsminor.fts5yy14 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy14, fts5yymsp[0].minor.fts5yy11);
  178231. }
  178232. fts5yymsp[-1].minor.fts5yy14 = fts5yylhsminor.fts5yy14;
  178233. break;
  178234. case 22: /* neardist_opt ::= */
  178235. { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
  178236. break;
  178237. case 23: /* neardist_opt ::= COMMA STRING */
  178238. { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  178239. break;
  178240. case 24: /* phrase ::= phrase PLUS STRING star_opt */
  178241. {
  178242. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  178243. }
  178244. fts5yymsp[-3].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  178245. break;
  178246. case 25: /* phrase ::= STRING star_opt */
  178247. {
  178248. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  178249. }
  178250. fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  178251. break;
  178252. case 26: /* star_opt ::= STAR */
  178253. { fts5yymsp[0].minor.fts5yy4 = 1; }
  178254. break;
  178255. case 27: /* star_opt ::= */
  178256. { fts5yymsp[1].minor.fts5yy4 = 0; }
  178257. break;
  178258. default:
  178259. break;
  178260. /********** End reduce actions ************************************************/
  178261. };
  178262. assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
  178263. fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
  178264. fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
  178265. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  178266. /* There are no SHIFTREDUCE actions on nonterminals because the table
  178267. ** generator has simplified them to pure REDUCE actions. */
  178268. assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
  178269. /* It is not possible for a REDUCE to be followed by an error */
  178270. assert( fts5yyact!=fts5YY_ERROR_ACTION );
  178271. fts5yymsp += fts5yysize+1;
  178272. fts5yypParser->fts5yytos = fts5yymsp;
  178273. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  178274. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  178275. fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift");
  178276. }
  178277. /*
  178278. ** The following code executes when the parse fails
  178279. */
  178280. #ifndef fts5YYNOERRORRECOVERY
  178281. static void fts5yy_parse_failed(
  178282. fts5yyParser *fts5yypParser /* The parser */
  178283. ){
  178284. sqlite3Fts5ParserARG_FETCH;
  178285. #ifndef NDEBUG
  178286. if( fts5yyTraceFILE ){
  178287. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  178288. }
  178289. #endif
  178290. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  178291. /* Here code is inserted which will be executed whenever the
  178292. ** parser fails */
  178293. /************ Begin %parse_failure code ***************************************/
  178294. /************ End %parse_failure code *****************************************/
  178295. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  178296. }
  178297. #endif /* fts5YYNOERRORRECOVERY */
  178298. /*
  178299. ** The following code executes when a syntax error first occurs.
  178300. */
  178301. static void fts5yy_syntax_error(
  178302. fts5yyParser *fts5yypParser, /* The parser */
  178303. int fts5yymajor, /* The major type of the error token */
  178304. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
  178305. ){
  178306. sqlite3Fts5ParserARG_FETCH;
  178307. #define FTS5TOKEN fts5yyminor
  178308. /************ Begin %syntax_error code ****************************************/
  178309. UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
  178310. sqlite3Fts5ParseError(
  178311. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  178312. );
  178313. /************ End %syntax_error code ******************************************/
  178314. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  178315. }
  178316. /*
  178317. ** The following is executed when the parser accepts
  178318. */
  178319. static void fts5yy_accept(
  178320. fts5yyParser *fts5yypParser /* The parser */
  178321. ){
  178322. sqlite3Fts5ParserARG_FETCH;
  178323. #ifndef NDEBUG
  178324. if( fts5yyTraceFILE ){
  178325. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  178326. }
  178327. #endif
  178328. #ifndef fts5YYNOERRORRECOVERY
  178329. fts5yypParser->fts5yyerrcnt = -1;
  178330. #endif
  178331. assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
  178332. /* Here code is inserted which will be executed whenever the
  178333. ** parser accepts */
  178334. /*********** Begin %parse_accept code *****************************************/
  178335. /*********** End %parse_accept code *******************************************/
  178336. sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  178337. }
  178338. /* The main parser program.
  178339. ** The first argument is a pointer to a structure obtained from
  178340. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  178341. ** The second argument is the major token number. The third is
  178342. ** the minor token. The fourth optional argument is whatever the
  178343. ** user wants (and specified in the grammar) and is available for
  178344. ** use by the action routines.
  178345. **
  178346. ** Inputs:
  178347. ** <ul>
  178348. ** <li> A pointer to the parser (an opaque structure.)
  178349. ** <li> The major token number.
  178350. ** <li> The minor token number.
  178351. ** <li> An option argument of a grammar-specified type.
  178352. ** </ul>
  178353. **
  178354. ** Outputs:
  178355. ** None.
  178356. */
  178357. static void sqlite3Fts5Parser(
  178358. void *fts5yyp, /* The parser */
  178359. int fts5yymajor, /* The major token code number */
  178360. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  178361. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  178362. ){
  178363. fts5YYMINORTYPE fts5yyminorunion;
  178364. unsigned int fts5yyact; /* The parser action. */
  178365. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  178366. int fts5yyendofinput; /* True if we are at the end of input */
  178367. #endif
  178368. #ifdef fts5YYERRORSYMBOL
  178369. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  178370. #endif
  178371. fts5yyParser *fts5yypParser; /* The parser */
  178372. fts5yypParser = (fts5yyParser*)fts5yyp;
  178373. assert( fts5yypParser->fts5yytos!=0 );
  178374. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  178375. fts5yyendofinput = (fts5yymajor==0);
  178376. #endif
  178377. sqlite3Fts5ParserARG_STORE;
  178378. #ifndef NDEBUG
  178379. if( fts5yyTraceFILE ){
  178380. int stateno = fts5yypParser->fts5yytos->stateno;
  178381. if( stateno < fts5YY_MIN_REDUCE ){
  178382. fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n",
  178383. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],stateno);
  178384. }else{
  178385. fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  178386. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],stateno-fts5YY_MIN_REDUCE);
  178387. }
  178388. }
  178389. #endif
  178390. do{
  178391. fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
  178392. if( fts5yyact >= fts5YY_MIN_REDUCE ){
  178393. fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor,fts5yyminor);
  178394. }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  178395. fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
  178396. #ifndef fts5YYNOERRORRECOVERY
  178397. fts5yypParser->fts5yyerrcnt--;
  178398. #endif
  178399. fts5yymajor = fts5YYNOCODE;
  178400. }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){
  178401. fts5yypParser->fts5yytos--;
  178402. fts5yy_accept(fts5yypParser);
  178403. return;
  178404. }else{
  178405. assert( fts5yyact == fts5YY_ERROR_ACTION );
  178406. fts5yyminorunion.fts5yy0 = fts5yyminor;
  178407. #ifdef fts5YYERRORSYMBOL
  178408. int fts5yymx;
  178409. #endif
  178410. #ifndef NDEBUG
  178411. if( fts5yyTraceFILE ){
  178412. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  178413. }
  178414. #endif
  178415. #ifdef fts5YYERRORSYMBOL
  178416. /* A syntax error has occurred.
  178417. ** The response to an error depends upon whether or not the
  178418. ** grammar defines an error token "ERROR".
  178419. **
  178420. ** This is what we do if the grammar does define ERROR:
  178421. **
  178422. ** * Call the %syntax_error function.
  178423. **
  178424. ** * Begin popping the stack until we enter a state where
  178425. ** it is legal to shift the error symbol, then shift
  178426. ** the error symbol.
  178427. **
  178428. ** * Set the error count to three.
  178429. **
  178430. ** * Begin accepting and shifting new tokens. No new error
  178431. ** processing will occur until three tokens have been
  178432. ** shifted successfully.
  178433. **
  178434. */
  178435. if( fts5yypParser->fts5yyerrcnt<0 ){
  178436. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
  178437. }
  178438. fts5yymx = fts5yypParser->fts5yytos->major;
  178439. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  178440. #ifndef NDEBUG
  178441. if( fts5yyTraceFILE ){
  178442. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  178443. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  178444. }
  178445. #endif
  178446. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
  178447. fts5yymajor = fts5YYNOCODE;
  178448. }else{
  178449. while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
  178450. && fts5yymx != fts5YYERRORSYMBOL
  178451. && (fts5yyact = fts5yy_find_reduce_action(
  178452. fts5yypParser->fts5yytos->stateno,
  178453. fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
  178454. ){
  178455. fts5yy_pop_parser_stack(fts5yypParser);
  178456. }
  178457. if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
  178458. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  178459. fts5yy_parse_failed(fts5yypParser);
  178460. #ifndef fts5YYNOERRORRECOVERY
  178461. fts5yypParser->fts5yyerrcnt = -1;
  178462. #endif
  178463. fts5yymajor = fts5YYNOCODE;
  178464. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  178465. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
  178466. }
  178467. }
  178468. fts5yypParser->fts5yyerrcnt = 3;
  178469. fts5yyerrorhit = 1;
  178470. #elif defined(fts5YYNOERRORRECOVERY)
  178471. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  178472. ** do any kind of error recovery. Instead, simply invoke the syntax
  178473. ** error routine and continue going as if nothing had happened.
  178474. **
  178475. ** Applications can set this macro (for example inside %include) if
  178476. ** they intend to abandon the parse upon the first syntax error seen.
  178477. */
  178478. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  178479. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  178480. fts5yymajor = fts5YYNOCODE;
  178481. #else /* fts5YYERRORSYMBOL is not defined */
  178482. /* This is what we do if the grammar does not define ERROR:
  178483. **
  178484. ** * Report an error message, and throw away the input token.
  178485. **
  178486. ** * If the input token is $, then fail the parse.
  178487. **
  178488. ** As before, subsequent error messages are suppressed until
  178489. ** three input tokens have been successfully shifted.
  178490. */
  178491. if( fts5yypParser->fts5yyerrcnt<=0 ){
  178492. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  178493. }
  178494. fts5yypParser->fts5yyerrcnt = 3;
  178495. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  178496. if( fts5yyendofinput ){
  178497. fts5yy_parse_failed(fts5yypParser);
  178498. #ifndef fts5YYNOERRORRECOVERY
  178499. fts5yypParser->fts5yyerrcnt = -1;
  178500. #endif
  178501. }
  178502. fts5yymajor = fts5YYNOCODE;
  178503. #endif
  178504. }
  178505. }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
  178506. #ifndef NDEBUG
  178507. if( fts5yyTraceFILE ){
  178508. fts5yyStackEntry *i;
  178509. char cDiv = '[';
  178510. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  178511. for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
  178512. fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
  178513. cDiv = ' ';
  178514. }
  178515. fprintf(fts5yyTraceFILE,"]\n");
  178516. }
  178517. #endif
  178518. return;
  178519. }
  178520. /*
  178521. ** 2014 May 31
  178522. **
  178523. ** The author disclaims copyright to this source code. In place of
  178524. ** a legal notice, here is a blessing:
  178525. **
  178526. ** May you do good and not evil.
  178527. ** May you find forgiveness for yourself and forgive others.
  178528. ** May you share freely, never taking more than you give.
  178529. **
  178530. ******************************************************************************
  178531. */
  178532. /* #include "fts5Int.h" */
  178533. #include <math.h> /* amalgamator: keep */
  178534. /*
  178535. ** Object used to iterate through all "coalesced phrase instances" in
  178536. ** a single column of the current row. If the phrase instances in the
  178537. ** column being considered do not overlap, this object simply iterates
  178538. ** through them. Or, if they do overlap (share one or more tokens in
  178539. ** common), each set of overlapping instances is treated as a single
  178540. ** match. See documentation for the highlight() auxiliary function for
  178541. ** details.
  178542. **
  178543. ** Usage is:
  178544. **
  178545. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  178546. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  178547. ** rc = fts5CInstIterNext(&iter)
  178548. ** ){
  178549. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  178550. ** }
  178551. **
  178552. */
  178553. typedef struct CInstIter CInstIter;
  178554. struct CInstIter {
  178555. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  178556. Fts5Context *pFts; /* First arg to pass to pApi functions */
  178557. int iCol; /* Column to search */
  178558. int iInst; /* Next phrase instance index */
  178559. int nInst; /* Total number of phrase instances */
  178560. /* Output variables */
  178561. int iStart; /* First token in coalesced phrase instance */
  178562. int iEnd; /* Last token in coalesced phrase instance */
  178563. };
  178564. /*
  178565. ** Advance the iterator to the next coalesced phrase instance. Return
  178566. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  178567. */
  178568. static int fts5CInstIterNext(CInstIter *pIter){
  178569. int rc = SQLITE_OK;
  178570. pIter->iStart = -1;
  178571. pIter->iEnd = -1;
  178572. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  178573. int ip; int ic; int io;
  178574. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  178575. if( rc==SQLITE_OK ){
  178576. if( ic==pIter->iCol ){
  178577. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  178578. if( pIter->iStart<0 ){
  178579. pIter->iStart = io;
  178580. pIter->iEnd = iEnd;
  178581. }else if( io<=pIter->iEnd ){
  178582. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  178583. }else{
  178584. break;
  178585. }
  178586. }
  178587. pIter->iInst++;
  178588. }
  178589. }
  178590. return rc;
  178591. }
  178592. /*
  178593. ** Initialize the iterator object indicated by the final parameter to
  178594. ** iterate through coalesced phrase instances in column iCol.
  178595. */
  178596. static int fts5CInstIterInit(
  178597. const Fts5ExtensionApi *pApi,
  178598. Fts5Context *pFts,
  178599. int iCol,
  178600. CInstIter *pIter
  178601. ){
  178602. int rc;
  178603. memset(pIter, 0, sizeof(CInstIter));
  178604. pIter->pApi = pApi;
  178605. pIter->pFts = pFts;
  178606. pIter->iCol = iCol;
  178607. rc = pApi->xInstCount(pFts, &pIter->nInst);
  178608. if( rc==SQLITE_OK ){
  178609. rc = fts5CInstIterNext(pIter);
  178610. }
  178611. return rc;
  178612. }
  178613. /*************************************************************************
  178614. ** Start of highlight() implementation.
  178615. */
  178616. typedef struct HighlightContext HighlightContext;
  178617. struct HighlightContext {
  178618. CInstIter iter; /* Coalesced Instance Iterator */
  178619. int iPos; /* Current token offset in zIn[] */
  178620. int iRangeStart; /* First token to include */
  178621. int iRangeEnd; /* If non-zero, last token to include */
  178622. const char *zOpen; /* Opening highlight */
  178623. const char *zClose; /* Closing highlight */
  178624. const char *zIn; /* Input text */
  178625. int nIn; /* Size of input text in bytes */
  178626. int iOff; /* Current offset within zIn[] */
  178627. char *zOut; /* Output value */
  178628. };
  178629. /*
  178630. ** Append text to the HighlightContext output string - p->zOut. Argument
  178631. ** z points to a buffer containing n bytes of text to append. If n is
  178632. ** negative, everything up until the first '\0' is appended to the output.
  178633. **
  178634. ** If *pRc is set to any value other than SQLITE_OK when this function is
  178635. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  178636. ** *pRc is set to an error code before returning.
  178637. */
  178638. static void fts5HighlightAppend(
  178639. int *pRc,
  178640. HighlightContext *p,
  178641. const char *z, int n
  178642. ){
  178643. if( *pRc==SQLITE_OK ){
  178644. if( n<0 ) n = (int)strlen(z);
  178645. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  178646. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  178647. }
  178648. }
  178649. /*
  178650. ** Tokenizer callback used by implementation of highlight() function.
  178651. */
  178652. static int fts5HighlightCb(
  178653. void *pContext, /* Pointer to HighlightContext object */
  178654. int tflags, /* Mask of FTS5_TOKEN_* flags */
  178655. const char *pToken, /* Buffer containing token */
  178656. int nToken, /* Size of token in bytes */
  178657. int iStartOff, /* Start offset of token */
  178658. int iEndOff /* End offset of token */
  178659. ){
  178660. HighlightContext *p = (HighlightContext*)pContext;
  178661. int rc = SQLITE_OK;
  178662. int iPos;
  178663. UNUSED_PARAM2(pToken, nToken);
  178664. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  178665. iPos = p->iPos++;
  178666. if( p->iRangeEnd>0 ){
  178667. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  178668. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  178669. }
  178670. if( iPos==p->iter.iStart ){
  178671. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  178672. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  178673. p->iOff = iStartOff;
  178674. }
  178675. if( iPos==p->iter.iEnd ){
  178676. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  178677. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  178678. }
  178679. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  178680. fts5HighlightAppend(&rc, p, p->zClose, -1);
  178681. p->iOff = iEndOff;
  178682. if( rc==SQLITE_OK ){
  178683. rc = fts5CInstIterNext(&p->iter);
  178684. }
  178685. }
  178686. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  178687. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  178688. p->iOff = iEndOff;
  178689. if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
  178690. fts5HighlightAppend(&rc, p, p->zClose, -1);
  178691. }
  178692. }
  178693. return rc;
  178694. }
  178695. /*
  178696. ** Implementation of highlight() function.
  178697. */
  178698. static void fts5HighlightFunction(
  178699. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  178700. Fts5Context *pFts, /* First arg to pass to pApi functions */
  178701. sqlite3_context *pCtx, /* Context for returning result/error */
  178702. int nVal, /* Number of values in apVal[] array */
  178703. sqlite3_value **apVal /* Array of trailing arguments */
  178704. ){
  178705. HighlightContext ctx;
  178706. int rc;
  178707. int iCol;
  178708. if( nVal!=3 ){
  178709. const char *zErr = "wrong number of arguments to function highlight()";
  178710. sqlite3_result_error(pCtx, zErr, -1);
  178711. return;
  178712. }
  178713. iCol = sqlite3_value_int(apVal[0]);
  178714. memset(&ctx, 0, sizeof(HighlightContext));
  178715. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  178716. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  178717. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  178718. if( ctx.zIn ){
  178719. if( rc==SQLITE_OK ){
  178720. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  178721. }
  178722. if( rc==SQLITE_OK ){
  178723. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  178724. }
  178725. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  178726. if( rc==SQLITE_OK ){
  178727. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  178728. }
  178729. sqlite3_free(ctx.zOut);
  178730. }
  178731. if( rc!=SQLITE_OK ){
  178732. sqlite3_result_error_code(pCtx, rc);
  178733. }
  178734. }
  178735. /*
  178736. ** End of highlight() implementation.
  178737. **************************************************************************/
  178738. /*
  178739. ** Context object passed to the fts5SentenceFinderCb() function.
  178740. */
  178741. typedef struct Fts5SFinder Fts5SFinder;
  178742. struct Fts5SFinder {
  178743. int iPos; /* Current token position */
  178744. int nFirstAlloc; /* Allocated size of aFirst[] */
  178745. int nFirst; /* Number of entries in aFirst[] */
  178746. int *aFirst; /* Array of first token in each sentence */
  178747. const char *zDoc; /* Document being tokenized */
  178748. };
  178749. /*
  178750. ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
  178751. ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
  178752. ** error occurs.
  178753. */
  178754. static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
  178755. if( p->nFirstAlloc==p->nFirst ){
  178756. int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
  178757. int *aNew;
  178758. aNew = (int*)sqlite3_realloc(p->aFirst, nNew*sizeof(int));
  178759. if( aNew==0 ) return SQLITE_NOMEM;
  178760. p->aFirst = aNew;
  178761. p->nFirstAlloc = nNew;
  178762. }
  178763. p->aFirst[p->nFirst++] = iAdd;
  178764. return SQLITE_OK;
  178765. }
  178766. /*
  178767. ** This function is an xTokenize() callback used by the auxiliary snippet()
  178768. ** function. Its job is to identify tokens that are the first in a sentence.
  178769. ** For each such token, an entry is added to the SFinder.aFirst[] array.
  178770. */
  178771. static int fts5SentenceFinderCb(
  178772. void *pContext, /* Pointer to HighlightContext object */
  178773. int tflags, /* Mask of FTS5_TOKEN_* flags */
  178774. const char *pToken, /* Buffer containing token */
  178775. int nToken, /* Size of token in bytes */
  178776. int iStartOff, /* Start offset of token */
  178777. int iEndOff /* End offset of token */
  178778. ){
  178779. int rc = SQLITE_OK;
  178780. UNUSED_PARAM2(pToken, nToken);
  178781. UNUSED_PARAM(iEndOff);
  178782. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  178783. Fts5SFinder *p = (Fts5SFinder*)pContext;
  178784. if( p->iPos>0 ){
  178785. int i;
  178786. char c = 0;
  178787. for(i=iStartOff-1; i>=0; i--){
  178788. c = p->zDoc[i];
  178789. if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
  178790. }
  178791. if( i!=iStartOff-1 && (c=='.' || c==':') ){
  178792. rc = fts5SentenceFinderAdd(p, p->iPos);
  178793. }
  178794. }else{
  178795. rc = fts5SentenceFinderAdd(p, 0);
  178796. }
  178797. p->iPos++;
  178798. }
  178799. return rc;
  178800. }
  178801. static int fts5SnippetScore(
  178802. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  178803. Fts5Context *pFts, /* First arg to pass to pApi functions */
  178804. int nDocsize, /* Size of column in tokens */
  178805. unsigned char *aSeen, /* Array with one element per query phrase */
  178806. int iCol, /* Column to score */
  178807. int iPos, /* Starting offset to score */
  178808. int nToken, /* Max tokens per snippet */
  178809. int *pnScore, /* OUT: Score */
  178810. int *piPos /* OUT: Adjusted offset */
  178811. ){
  178812. int rc;
  178813. int i;
  178814. int ip = 0;
  178815. int ic = 0;
  178816. int iOff = 0;
  178817. int iFirst = -1;
  178818. int nInst;
  178819. int nScore = 0;
  178820. int iLast = 0;
  178821. rc = pApi->xInstCount(pFts, &nInst);
  178822. for(i=0; i<nInst && rc==SQLITE_OK; i++){
  178823. rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
  178824. if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<(iPos+nToken) ){
  178825. nScore += (aSeen[ip] ? 1 : 1000);
  178826. aSeen[ip] = 1;
  178827. if( iFirst<0 ) iFirst = iOff;
  178828. iLast = iOff + pApi->xPhraseSize(pFts, ip);
  178829. }
  178830. }
  178831. *pnScore = nScore;
  178832. if( piPos ){
  178833. int iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
  178834. if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
  178835. if( iAdj<0 ) iAdj = 0;
  178836. *piPos = iAdj;
  178837. }
  178838. return rc;
  178839. }
  178840. /*
  178841. ** Return the value in pVal interpreted as utf-8 text. Except, if pVal
  178842. ** contains a NULL value, return a pointer to a static string zero
  178843. ** bytes in length instead of a NULL pointer.
  178844. */
  178845. static const char *fts5ValueToText(sqlite3_value *pVal){
  178846. const char *zRet = (const char*)sqlite3_value_text(pVal);
  178847. return zRet ? zRet : "";
  178848. }
  178849. /*
  178850. ** Implementation of snippet() function.
  178851. */
  178852. static void fts5SnippetFunction(
  178853. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  178854. Fts5Context *pFts, /* First arg to pass to pApi functions */
  178855. sqlite3_context *pCtx, /* Context for returning result/error */
  178856. int nVal, /* Number of values in apVal[] array */
  178857. sqlite3_value **apVal /* Array of trailing arguments */
  178858. ){
  178859. HighlightContext ctx;
  178860. int rc = SQLITE_OK; /* Return code */
  178861. int iCol; /* 1st argument to snippet() */
  178862. const char *zEllips; /* 4th argument to snippet() */
  178863. int nToken; /* 5th argument to snippet() */
  178864. int nInst = 0; /* Number of instance matches this row */
  178865. int i; /* Used to iterate through instances */
  178866. int nPhrase; /* Number of phrases in query */
  178867. unsigned char *aSeen; /* Array of "seen instance" flags */
  178868. int iBestCol; /* Column containing best snippet */
  178869. int iBestStart = 0; /* First token of best snippet */
  178870. int nBestScore = 0; /* Score of best snippet */
  178871. int nColSize = 0; /* Total size of iBestCol in tokens */
  178872. Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
  178873. int nCol;
  178874. if( nVal!=5 ){
  178875. const char *zErr = "wrong number of arguments to function snippet()";
  178876. sqlite3_result_error(pCtx, zErr, -1);
  178877. return;
  178878. }
  178879. nCol = pApi->xColumnCount(pFts);
  178880. memset(&ctx, 0, sizeof(HighlightContext));
  178881. iCol = sqlite3_value_int(apVal[0]);
  178882. ctx.zOpen = fts5ValueToText(apVal[1]);
  178883. ctx.zClose = fts5ValueToText(apVal[2]);
  178884. zEllips = fts5ValueToText(apVal[3]);
  178885. nToken = sqlite3_value_int(apVal[4]);
  178886. iBestCol = (iCol>=0 ? iCol : 0);
  178887. nPhrase = pApi->xPhraseCount(pFts);
  178888. aSeen = sqlite3_malloc(nPhrase);
  178889. if( aSeen==0 ){
  178890. rc = SQLITE_NOMEM;
  178891. }
  178892. if( rc==SQLITE_OK ){
  178893. rc = pApi->xInstCount(pFts, &nInst);
  178894. }
  178895. memset(&sFinder, 0, sizeof(Fts5SFinder));
  178896. for(i=0; i<nCol; i++){
  178897. if( iCol<0 || iCol==i ){
  178898. int nDoc;
  178899. int nDocsize;
  178900. int ii;
  178901. sFinder.iPos = 0;
  178902. sFinder.nFirst = 0;
  178903. rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
  178904. if( rc!=SQLITE_OK ) break;
  178905. rc = pApi->xTokenize(pFts,
  178906. sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
  178907. );
  178908. if( rc!=SQLITE_OK ) break;
  178909. rc = pApi->xColumnSize(pFts, i, &nDocsize);
  178910. if( rc!=SQLITE_OK ) break;
  178911. for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
  178912. int ip, ic, io;
  178913. int iAdj;
  178914. int nScore;
  178915. int jj;
  178916. rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
  178917. if( ic!=i || rc!=SQLITE_OK ) continue;
  178918. memset(aSeen, 0, nPhrase);
  178919. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  178920. io, nToken, &nScore, &iAdj
  178921. );
  178922. if( rc==SQLITE_OK && nScore>nBestScore ){
  178923. nBestScore = nScore;
  178924. iBestCol = i;
  178925. iBestStart = iAdj;
  178926. nColSize = nDocsize;
  178927. }
  178928. if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
  178929. for(jj=0; jj<(sFinder.nFirst-1); jj++){
  178930. if( sFinder.aFirst[jj+1]>io ) break;
  178931. }
  178932. if( sFinder.aFirst[jj]<io ){
  178933. memset(aSeen, 0, nPhrase);
  178934. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  178935. sFinder.aFirst[jj], nToken, &nScore, 0
  178936. );
  178937. nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
  178938. if( rc==SQLITE_OK && nScore>nBestScore ){
  178939. nBestScore = nScore;
  178940. iBestCol = i;
  178941. iBestStart = sFinder.aFirst[jj];
  178942. nColSize = nDocsize;
  178943. }
  178944. }
  178945. }
  178946. }
  178947. }
  178948. }
  178949. if( rc==SQLITE_OK ){
  178950. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  178951. }
  178952. if( rc==SQLITE_OK && nColSize==0 ){
  178953. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  178954. }
  178955. if( ctx.zIn ){
  178956. if( rc==SQLITE_OK ){
  178957. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  178958. }
  178959. ctx.iRangeStart = iBestStart;
  178960. ctx.iRangeEnd = iBestStart + nToken - 1;
  178961. if( iBestStart>0 ){
  178962. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  178963. }
  178964. /* Advance iterator ctx.iter so that it points to the first coalesced
  178965. ** phrase instance at or following position iBestStart. */
  178966. while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
  178967. rc = fts5CInstIterNext(&ctx.iter);
  178968. }
  178969. if( rc==SQLITE_OK ){
  178970. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  178971. }
  178972. if( ctx.iRangeEnd>=(nColSize-1) ){
  178973. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  178974. }else{
  178975. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  178976. }
  178977. }
  178978. if( rc==SQLITE_OK ){
  178979. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  178980. }else{
  178981. sqlite3_result_error_code(pCtx, rc);
  178982. }
  178983. sqlite3_free(ctx.zOut);
  178984. sqlite3_free(aSeen);
  178985. sqlite3_free(sFinder.aFirst);
  178986. }
  178987. /************************************************************************/
  178988. /*
  178989. ** The first time the bm25() function is called for a query, an instance
  178990. ** of the following structure is allocated and populated.
  178991. */
  178992. typedef struct Fts5Bm25Data Fts5Bm25Data;
  178993. struct Fts5Bm25Data {
  178994. int nPhrase; /* Number of phrases in query */
  178995. double avgdl; /* Average number of tokens in each row */
  178996. double *aIDF; /* IDF for each phrase */
  178997. double *aFreq; /* Array used to calculate phrase freq. */
  178998. };
  178999. /*
  179000. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  179001. ** table matched by each individual phrase within the query.
  179002. */
  179003. static int fts5CountCb(
  179004. const Fts5ExtensionApi *pApi,
  179005. Fts5Context *pFts,
  179006. void *pUserData /* Pointer to sqlite3_int64 variable */
  179007. ){
  179008. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  179009. UNUSED_PARAM2(pApi, pFts);
  179010. (*pn)++;
  179011. return SQLITE_OK;
  179012. }
  179013. /*
  179014. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  179015. ** If the object has not already been allocated, allocate and populate it
  179016. ** now.
  179017. */
  179018. static int fts5Bm25GetData(
  179019. const Fts5ExtensionApi *pApi,
  179020. Fts5Context *pFts,
  179021. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  179022. ){
  179023. int rc = SQLITE_OK; /* Return code */
  179024. Fts5Bm25Data *p; /* Object to return */
  179025. p = pApi->xGetAuxdata(pFts, 0);
  179026. if( p==0 ){
  179027. int nPhrase; /* Number of phrases in query */
  179028. sqlite3_int64 nRow = 0; /* Number of rows in table */
  179029. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  179030. int nByte; /* Bytes of space to allocate */
  179031. int i;
  179032. /* Allocate the Fts5Bm25Data object */
  179033. nPhrase = pApi->xPhraseCount(pFts);
  179034. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  179035. p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
  179036. if( p==0 ){
  179037. rc = SQLITE_NOMEM;
  179038. }else{
  179039. memset(p, 0, nByte);
  179040. p->nPhrase = nPhrase;
  179041. p->aIDF = (double*)&p[1];
  179042. p->aFreq = &p->aIDF[nPhrase];
  179043. }
  179044. /* Calculate the average document length for this FTS5 table */
  179045. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  179046. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  179047. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  179048. /* Calculate an IDF for each phrase in the query */
  179049. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  179050. sqlite3_int64 nHit = 0;
  179051. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  179052. if( rc==SQLITE_OK ){
  179053. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  179054. ** This is done using the standard BM25 formula as found on wikipedia:
  179055. **
  179056. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  179057. **
  179058. ** where "N" is the total number of documents in the set and nHit
  179059. ** is the number that contain at least one instance of the phrase
  179060. ** under consideration.
  179061. **
  179062. ** The problem with this is that if (N < 2*nHit), the IDF is
  179063. ** negative. Which is undesirable. So the mimimum allowable IDF is
  179064. ** (1e-6) - roughly the same as a term that appears in just over
  179065. ** half of set of 5,000,000 documents. */
  179066. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  179067. if( idf<=0.0 ) idf = 1e-6;
  179068. p->aIDF[i] = idf;
  179069. }
  179070. }
  179071. if( rc!=SQLITE_OK ){
  179072. sqlite3_free(p);
  179073. }else{
  179074. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  179075. }
  179076. if( rc!=SQLITE_OK ) p = 0;
  179077. }
  179078. *ppData = p;
  179079. return rc;
  179080. }
  179081. /*
  179082. ** Implementation of bm25() function.
  179083. */
  179084. static void fts5Bm25Function(
  179085. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  179086. Fts5Context *pFts, /* First arg to pass to pApi functions */
  179087. sqlite3_context *pCtx, /* Context for returning result/error */
  179088. int nVal, /* Number of values in apVal[] array */
  179089. sqlite3_value **apVal /* Array of trailing arguments */
  179090. ){
  179091. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  179092. const double b = 0.75; /* Constant "b" from BM25 formula */
  179093. int rc = SQLITE_OK; /* Error code */
  179094. double score = 0.0; /* SQL function return value */
  179095. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  179096. int i; /* Iterator variable */
  179097. int nInst = 0; /* Value returned by xInstCount() */
  179098. double D = 0.0; /* Total number of tokens in row */
  179099. double *aFreq = 0; /* Array of phrase freq. for current row */
  179100. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  179101. ** for each phrase in the query for the current row. */
  179102. rc = fts5Bm25GetData(pApi, pFts, &pData);
  179103. if( rc==SQLITE_OK ){
  179104. aFreq = pData->aFreq;
  179105. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  179106. rc = pApi->xInstCount(pFts, &nInst);
  179107. }
  179108. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  179109. int ip; int ic; int io;
  179110. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  179111. if( rc==SQLITE_OK ){
  179112. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  179113. aFreq[ip] += w;
  179114. }
  179115. }
  179116. /* Figure out the total size of the current row in tokens. */
  179117. if( rc==SQLITE_OK ){
  179118. int nTok;
  179119. rc = pApi->xColumnSize(pFts, -1, &nTok);
  179120. D = (double)nTok;
  179121. }
  179122. /* Determine the BM25 score for the current row. */
  179123. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  179124. score += pData->aIDF[i] * (
  179125. ( aFreq[i] * (k1 + 1.0) ) /
  179126. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  179127. );
  179128. }
  179129. /* If no error has occurred, return the calculated score. Otherwise,
  179130. ** throw an SQL exception. */
  179131. if( rc==SQLITE_OK ){
  179132. sqlite3_result_double(pCtx, -1.0 * score);
  179133. }else{
  179134. sqlite3_result_error_code(pCtx, rc);
  179135. }
  179136. }
  179137. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  179138. struct Builtin {
  179139. const char *zFunc; /* Function name (nul-terminated) */
  179140. void *pUserData; /* User-data pointer */
  179141. fts5_extension_function xFunc;/* Callback function */
  179142. void (*xDestroy)(void*); /* Destructor function */
  179143. } aBuiltin [] = {
  179144. { "snippet", 0, fts5SnippetFunction, 0 },
  179145. { "highlight", 0, fts5HighlightFunction, 0 },
  179146. { "bm25", 0, fts5Bm25Function, 0 },
  179147. };
  179148. int rc = SQLITE_OK; /* Return code */
  179149. int i; /* To iterate through builtin functions */
  179150. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  179151. rc = pApi->xCreateFunction(pApi,
  179152. aBuiltin[i].zFunc,
  179153. aBuiltin[i].pUserData,
  179154. aBuiltin[i].xFunc,
  179155. aBuiltin[i].xDestroy
  179156. );
  179157. }
  179158. return rc;
  179159. }
  179160. /*
  179161. ** 2014 May 31
  179162. **
  179163. ** The author disclaims copyright to this source code. In place of
  179164. ** a legal notice, here is a blessing:
  179165. **
  179166. ** May you do good and not evil.
  179167. ** May you find forgiveness for yourself and forgive others.
  179168. ** May you share freely, never taking more than you give.
  179169. **
  179170. ******************************************************************************
  179171. */
  179172. /* #include "fts5Int.h" */
  179173. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
  179174. if( (u32)pBuf->nSpace<nByte ){
  179175. u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
  179176. u8 *pNew;
  179177. while( nNew<nByte ){
  179178. nNew = nNew * 2;
  179179. }
  179180. pNew = sqlite3_realloc(pBuf->p, nNew);
  179181. if( pNew==0 ){
  179182. *pRc = SQLITE_NOMEM;
  179183. return 1;
  179184. }else{
  179185. pBuf->nSpace = nNew;
  179186. pBuf->p = pNew;
  179187. }
  179188. }
  179189. return 0;
  179190. }
  179191. /*
  179192. ** Encode value iVal as an SQLite varint and append it to the buffer object
  179193. ** pBuf. If an OOM error occurs, set the error code in p.
  179194. */
  179195. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  179196. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  179197. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  179198. }
  179199. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  179200. aBuf[0] = (iVal>>24) & 0x00FF;
  179201. aBuf[1] = (iVal>>16) & 0x00FF;
  179202. aBuf[2] = (iVal>> 8) & 0x00FF;
  179203. aBuf[3] = (iVal>> 0) & 0x00FF;
  179204. }
  179205. static int sqlite3Fts5Get32(const u8 *aBuf){
  179206. return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
  179207. }
  179208. /*
  179209. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  179210. ** the error code in p. If an error has already occurred when this function
  179211. ** is called, it is a no-op.
  179212. */
  179213. static void sqlite3Fts5BufferAppendBlob(
  179214. int *pRc,
  179215. Fts5Buffer *pBuf,
  179216. u32 nData,
  179217. const u8 *pData
  179218. ){
  179219. assert_nc( *pRc || nData>=0 );
  179220. if( nData ){
  179221. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  179222. memcpy(&pBuf->p[pBuf->n], pData, nData);
  179223. pBuf->n += nData;
  179224. }
  179225. }
  179226. /*
  179227. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  179228. ** ensures that the byte following the buffer data is set to 0x00, even
  179229. ** though this byte is not included in the pBuf->n count.
  179230. */
  179231. static void sqlite3Fts5BufferAppendString(
  179232. int *pRc,
  179233. Fts5Buffer *pBuf,
  179234. const char *zStr
  179235. ){
  179236. int nStr = (int)strlen(zStr);
  179237. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  179238. pBuf->n--;
  179239. }
  179240. /*
  179241. ** Argument zFmt is a printf() style format string. This function performs
  179242. ** the printf() style processing, then appends the results to buffer pBuf.
  179243. **
  179244. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  179245. ** following the buffer data is set to 0x00, even though this byte is not
  179246. ** included in the pBuf->n count.
  179247. */
  179248. static void sqlite3Fts5BufferAppendPrintf(
  179249. int *pRc,
  179250. Fts5Buffer *pBuf,
  179251. char *zFmt, ...
  179252. ){
  179253. if( *pRc==SQLITE_OK ){
  179254. char *zTmp;
  179255. va_list ap;
  179256. va_start(ap, zFmt);
  179257. zTmp = sqlite3_vmprintf(zFmt, ap);
  179258. va_end(ap);
  179259. if( zTmp==0 ){
  179260. *pRc = SQLITE_NOMEM;
  179261. }else{
  179262. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  179263. sqlite3_free(zTmp);
  179264. }
  179265. }
  179266. }
  179267. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  179268. char *zRet = 0;
  179269. if( *pRc==SQLITE_OK ){
  179270. va_list ap;
  179271. va_start(ap, zFmt);
  179272. zRet = sqlite3_vmprintf(zFmt, ap);
  179273. va_end(ap);
  179274. if( zRet==0 ){
  179275. *pRc = SQLITE_NOMEM;
  179276. }
  179277. }
  179278. return zRet;
  179279. }
  179280. /*
  179281. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  179282. */
  179283. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  179284. sqlite3_free(pBuf->p);
  179285. memset(pBuf, 0, sizeof(Fts5Buffer));
  179286. }
  179287. /*
  179288. ** Zero the contents of the buffer object. But do not free the associated
  179289. ** memory allocation.
  179290. */
  179291. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  179292. pBuf->n = 0;
  179293. }
  179294. /*
  179295. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  179296. ** the error code in p. If an error has already occurred when this function
  179297. ** is called, it is a no-op.
  179298. */
  179299. static void sqlite3Fts5BufferSet(
  179300. int *pRc,
  179301. Fts5Buffer *pBuf,
  179302. int nData,
  179303. const u8 *pData
  179304. ){
  179305. pBuf->n = 0;
  179306. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  179307. }
  179308. static int sqlite3Fts5PoslistNext64(
  179309. const u8 *a, int n, /* Buffer containing poslist */
  179310. int *pi, /* IN/OUT: Offset within a[] */
  179311. i64 *piOff /* IN/OUT: Current offset */
  179312. ){
  179313. int i = *pi;
  179314. if( i>=n ){
  179315. /* EOF */
  179316. *piOff = -1;
  179317. return 1;
  179318. }else{
  179319. i64 iOff = *piOff;
  179320. int iVal;
  179321. fts5FastGetVarint32(a, i, iVal);
  179322. if( iVal==1 ){
  179323. fts5FastGetVarint32(a, i, iVal);
  179324. iOff = ((i64)iVal) << 32;
  179325. fts5FastGetVarint32(a, i, iVal);
  179326. }
  179327. *piOff = iOff + (iVal-2);
  179328. *pi = i;
  179329. return 0;
  179330. }
  179331. }
  179332. /*
  179333. ** Advance the iterator object passed as the only argument. Return true
  179334. ** if the iterator reaches EOF, or false otherwise.
  179335. */
  179336. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  179337. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  179338. pIter->bEof = 1;
  179339. }
  179340. return pIter->bEof;
  179341. }
  179342. static int sqlite3Fts5PoslistReaderInit(
  179343. const u8 *a, int n, /* Poslist buffer to iterate through */
  179344. Fts5PoslistReader *pIter /* Iterator object to initialize */
  179345. ){
  179346. memset(pIter, 0, sizeof(*pIter));
  179347. pIter->a = a;
  179348. pIter->n = n;
  179349. sqlite3Fts5PoslistReaderNext(pIter);
  179350. return pIter->bEof;
  179351. }
  179352. /*
  179353. ** Append position iPos to the position list being accumulated in buffer
  179354. ** pBuf, which must be already be large enough to hold the new data.
  179355. ** The previous position written to this list is *piPrev. *piPrev is set
  179356. ** to iPos before returning.
  179357. */
  179358. static void sqlite3Fts5PoslistSafeAppend(
  179359. Fts5Buffer *pBuf,
  179360. i64 *piPrev,
  179361. i64 iPos
  179362. ){
  179363. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  179364. if( (iPos & colmask) != (*piPrev & colmask) ){
  179365. pBuf->p[pBuf->n++] = 1;
  179366. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  179367. *piPrev = (iPos & colmask);
  179368. }
  179369. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
  179370. *piPrev = iPos;
  179371. }
  179372. static int sqlite3Fts5PoslistWriterAppend(
  179373. Fts5Buffer *pBuf,
  179374. Fts5PoslistWriter *pWriter,
  179375. i64 iPos
  179376. ){
  179377. int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
  179378. if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
  179379. sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
  179380. return SQLITE_OK;
  179381. }
  179382. static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
  179383. void *pRet = 0;
  179384. if( *pRc==SQLITE_OK ){
  179385. pRet = sqlite3_malloc(nByte);
  179386. if( pRet==0 ){
  179387. if( nByte>0 ) *pRc = SQLITE_NOMEM;
  179388. }else{
  179389. memset(pRet, 0, nByte);
  179390. }
  179391. }
  179392. return pRet;
  179393. }
  179394. /*
  179395. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  179396. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  179397. ** the length of the string is determined using strlen().
  179398. **
  179399. ** It is the responsibility of the caller to eventually free the returned
  179400. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  179401. */
  179402. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  179403. char *zRet = 0;
  179404. if( *pRc==SQLITE_OK ){
  179405. if( nIn<0 ){
  179406. nIn = (int)strlen(pIn);
  179407. }
  179408. zRet = (char*)sqlite3_malloc(nIn+1);
  179409. if( zRet ){
  179410. memcpy(zRet, pIn, nIn);
  179411. zRet[nIn] = '\0';
  179412. }else{
  179413. *pRc = SQLITE_NOMEM;
  179414. }
  179415. }
  179416. return zRet;
  179417. }
  179418. /*
  179419. ** Return true if character 't' may be part of an FTS5 bareword, or false
  179420. ** otherwise. Characters that may be part of barewords:
  179421. **
  179422. ** * All non-ASCII characters,
  179423. ** * The 52 upper and lower case ASCII characters, and
  179424. ** * The 10 integer ASCII characters.
  179425. ** * The underscore character "_" (0x5F).
  179426. ** * The unicode "subsitute" character (0x1A).
  179427. */
  179428. static int sqlite3Fts5IsBareword(char t){
  179429. u8 aBareword[128] = {
  179430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  179431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  179432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  179433. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  179434. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  179435. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  179436. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  179437. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  179438. };
  179439. return (t & 0x80) || aBareword[(int)t];
  179440. }
  179441. /*************************************************************************
  179442. */
  179443. typedef struct Fts5TermsetEntry Fts5TermsetEntry;
  179444. struct Fts5TermsetEntry {
  179445. char *pTerm;
  179446. int nTerm;
  179447. int iIdx; /* Index (main or aPrefix[] entry) */
  179448. Fts5TermsetEntry *pNext;
  179449. };
  179450. struct Fts5Termset {
  179451. Fts5TermsetEntry *apHash[512];
  179452. };
  179453. static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
  179454. int rc = SQLITE_OK;
  179455. *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
  179456. return rc;
  179457. }
  179458. static int sqlite3Fts5TermsetAdd(
  179459. Fts5Termset *p,
  179460. int iIdx,
  179461. const char *pTerm, int nTerm,
  179462. int *pbPresent
  179463. ){
  179464. int rc = SQLITE_OK;
  179465. *pbPresent = 0;
  179466. if( p ){
  179467. int i;
  179468. u32 hash = 13;
  179469. Fts5TermsetEntry *pEntry;
  179470. /* Calculate a hash value for this term. This is the same hash checksum
  179471. ** used by the fts5_hash.c module. This is not important for correct
  179472. ** operation of the module, but is necessary to ensure that some tests
  179473. ** designed to produce hash table collisions really do work. */
  179474. for(i=nTerm-1; i>=0; i--){
  179475. hash = (hash << 3) ^ hash ^ pTerm[i];
  179476. }
  179477. hash = (hash << 3) ^ hash ^ iIdx;
  179478. hash = hash % ArraySize(p->apHash);
  179479. for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
  179480. if( pEntry->iIdx==iIdx
  179481. && pEntry->nTerm==nTerm
  179482. && memcmp(pEntry->pTerm, pTerm, nTerm)==0
  179483. ){
  179484. *pbPresent = 1;
  179485. break;
  179486. }
  179487. }
  179488. if( pEntry==0 ){
  179489. pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
  179490. if( pEntry ){
  179491. pEntry->pTerm = (char*)&pEntry[1];
  179492. pEntry->nTerm = nTerm;
  179493. pEntry->iIdx = iIdx;
  179494. memcpy(pEntry->pTerm, pTerm, nTerm);
  179495. pEntry->pNext = p->apHash[hash];
  179496. p->apHash[hash] = pEntry;
  179497. }
  179498. }
  179499. }
  179500. return rc;
  179501. }
  179502. static void sqlite3Fts5TermsetFree(Fts5Termset *p){
  179503. if( p ){
  179504. u32 i;
  179505. for(i=0; i<ArraySize(p->apHash); i++){
  179506. Fts5TermsetEntry *pEntry = p->apHash[i];
  179507. while( pEntry ){
  179508. Fts5TermsetEntry *pDel = pEntry;
  179509. pEntry = pEntry->pNext;
  179510. sqlite3_free(pDel);
  179511. }
  179512. }
  179513. sqlite3_free(p);
  179514. }
  179515. }
  179516. /*
  179517. ** 2014 Jun 09
  179518. **
  179519. ** The author disclaims copyright to this source code. In place of
  179520. ** a legal notice, here is a blessing:
  179521. **
  179522. ** May you do good and not evil.
  179523. ** May you find forgiveness for yourself and forgive others.
  179524. ** May you share freely, never taking more than you give.
  179525. **
  179526. ******************************************************************************
  179527. **
  179528. ** This is an SQLite module implementing full-text search.
  179529. */
  179530. /* #include "fts5Int.h" */
  179531. #define FTS5_DEFAULT_PAGE_SIZE 4050
  179532. #define FTS5_DEFAULT_AUTOMERGE 4
  179533. #define FTS5_DEFAULT_USERMERGE 4
  179534. #define FTS5_DEFAULT_CRISISMERGE 16
  179535. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  179536. /* Maximum allowed page size */
  179537. #define FTS5_MAX_PAGE_SIZE (128*1024)
  179538. static int fts5_iswhitespace(char x){
  179539. return (x==' ');
  179540. }
  179541. static int fts5_isopenquote(char x){
  179542. return (x=='"' || x=='\'' || x=='[' || x=='`');
  179543. }
  179544. /*
  179545. ** Argument pIn points to a character that is part of a nul-terminated
  179546. ** string. Return a pointer to the first character following *pIn in
  179547. ** the string that is not a white-space character.
  179548. */
  179549. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  179550. const char *p = pIn;
  179551. if( p ){
  179552. while( fts5_iswhitespace(*p) ){ p++; }
  179553. }
  179554. return p;
  179555. }
  179556. /*
  179557. ** Argument pIn points to a character that is part of a nul-terminated
  179558. ** string. Return a pointer to the first character following *pIn in
  179559. ** the string that is not a "bareword" character.
  179560. */
  179561. static const char *fts5ConfigSkipBareword(const char *pIn){
  179562. const char *p = pIn;
  179563. while ( sqlite3Fts5IsBareword(*p) ) p++;
  179564. if( p==pIn ) p = 0;
  179565. return p;
  179566. }
  179567. static int fts5_isdigit(char a){
  179568. return (a>='0' && a<='9');
  179569. }
  179570. static const char *fts5ConfigSkipLiteral(const char *pIn){
  179571. const char *p = pIn;
  179572. switch( *p ){
  179573. case 'n': case 'N':
  179574. if( sqlite3_strnicmp("null", p, 4)==0 ){
  179575. p = &p[4];
  179576. }else{
  179577. p = 0;
  179578. }
  179579. break;
  179580. case 'x': case 'X':
  179581. p++;
  179582. if( *p=='\'' ){
  179583. p++;
  179584. while( (*p>='a' && *p<='f')
  179585. || (*p>='A' && *p<='F')
  179586. || (*p>='0' && *p<='9')
  179587. ){
  179588. p++;
  179589. }
  179590. if( *p=='\'' && 0==((p-pIn)%2) ){
  179591. p++;
  179592. }else{
  179593. p = 0;
  179594. }
  179595. }else{
  179596. p = 0;
  179597. }
  179598. break;
  179599. case '\'':
  179600. p++;
  179601. while( p ){
  179602. if( *p=='\'' ){
  179603. p++;
  179604. if( *p!='\'' ) break;
  179605. }
  179606. p++;
  179607. if( *p==0 ) p = 0;
  179608. }
  179609. break;
  179610. default:
  179611. /* maybe a number */
  179612. if( *p=='+' || *p=='-' ) p++;
  179613. while( fts5_isdigit(*p) ) p++;
  179614. /* At this point, if the literal was an integer, the parse is
  179615. ** finished. Or, if it is a floating point value, it may continue
  179616. ** with either a decimal point or an 'E' character. */
  179617. if( *p=='.' && fts5_isdigit(p[1]) ){
  179618. p += 2;
  179619. while( fts5_isdigit(*p) ) p++;
  179620. }
  179621. if( p==pIn ) p = 0;
  179622. break;
  179623. }
  179624. return p;
  179625. }
  179626. /*
  179627. ** The first character of the string pointed to by argument z is guaranteed
  179628. ** to be an open-quote character (see function fts5_isopenquote()).
  179629. **
  179630. ** This function searches for the corresponding close-quote character within
  179631. ** the string and, if found, dequotes the string in place and adds a new
  179632. ** nul-terminator byte.
  179633. **
  179634. ** If the close-quote is found, the value returned is the byte offset of
  179635. ** the character immediately following it. Or, if the close-quote is not
  179636. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  179637. ** undefined state.
  179638. */
  179639. static int fts5Dequote(char *z){
  179640. char q;
  179641. int iIn = 1;
  179642. int iOut = 0;
  179643. q = z[0];
  179644. /* Set stack variable q to the close-quote character */
  179645. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  179646. if( q=='[' ) q = ']';
  179647. while( ALWAYS(z[iIn]) ){
  179648. if( z[iIn]==q ){
  179649. if( z[iIn+1]!=q ){
  179650. /* Character iIn was the close quote. */
  179651. iIn++;
  179652. break;
  179653. }else{
  179654. /* Character iIn and iIn+1 form an escaped quote character. Skip
  179655. ** the input cursor past both and copy a single quote character
  179656. ** to the output buffer. */
  179657. iIn += 2;
  179658. z[iOut++] = q;
  179659. }
  179660. }else{
  179661. z[iOut++] = z[iIn++];
  179662. }
  179663. }
  179664. z[iOut] = '\0';
  179665. return iIn;
  179666. }
  179667. /*
  179668. ** Convert an SQL-style quoted string into a normal string by removing
  179669. ** the quote characters. The conversion is done in-place. If the
  179670. ** input does not begin with a quote character, then this routine
  179671. ** is a no-op.
  179672. **
  179673. ** Examples:
  179674. **
  179675. ** "abc" becomes abc
  179676. ** 'xyz' becomes xyz
  179677. ** [pqr] becomes pqr
  179678. ** `mno` becomes mno
  179679. */
  179680. static void sqlite3Fts5Dequote(char *z){
  179681. char quote; /* Quote character (if any ) */
  179682. assert( 0==fts5_iswhitespace(z[0]) );
  179683. quote = z[0];
  179684. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  179685. fts5Dequote(z);
  179686. }
  179687. }
  179688. struct Fts5Enum {
  179689. const char *zName;
  179690. int eVal;
  179691. };
  179692. typedef struct Fts5Enum Fts5Enum;
  179693. static int fts5ConfigSetEnum(
  179694. const Fts5Enum *aEnum,
  179695. const char *zEnum,
  179696. int *peVal
  179697. ){
  179698. int nEnum = (int)strlen(zEnum);
  179699. int i;
  179700. int iVal = -1;
  179701. for(i=0; aEnum[i].zName; i++){
  179702. if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
  179703. if( iVal>=0 ) return SQLITE_ERROR;
  179704. iVal = aEnum[i].eVal;
  179705. }
  179706. }
  179707. *peVal = iVal;
  179708. return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
  179709. }
  179710. /*
  179711. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  179712. ** configuration object pConfig as appropriate.
  179713. **
  179714. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  179715. ** an error occurs, an SQLite error code is returned and an error message
  179716. ** may be left in *pzErr. It is the responsibility of the caller to
  179717. ** eventually free any such error message using sqlite3_free().
  179718. */
  179719. static int fts5ConfigParseSpecial(
  179720. Fts5Global *pGlobal,
  179721. Fts5Config *pConfig, /* Configuration object to update */
  179722. const char *zCmd, /* Special command to parse */
  179723. const char *zArg, /* Argument to parse */
  179724. char **pzErr /* OUT: Error message */
  179725. ){
  179726. int rc = SQLITE_OK;
  179727. int nCmd = (int)strlen(zCmd);
  179728. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  179729. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  179730. const char *p;
  179731. int bFirst = 1;
  179732. if( pConfig->aPrefix==0 ){
  179733. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  179734. if( rc ) return rc;
  179735. }
  179736. p = zArg;
  179737. while( 1 ){
  179738. int nPre = 0;
  179739. while( p[0]==' ' ) p++;
  179740. if( bFirst==0 && p[0]==',' ){
  179741. p++;
  179742. while( p[0]==' ' ) p++;
  179743. }else if( p[0]=='\0' ){
  179744. break;
  179745. }
  179746. if( p[0]<'0' || p[0]>'9' ){
  179747. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  179748. rc = SQLITE_ERROR;
  179749. break;
  179750. }
  179751. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  179752. *pzErr = sqlite3_mprintf(
  179753. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  179754. );
  179755. rc = SQLITE_ERROR;
  179756. break;
  179757. }
  179758. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  179759. nPre = nPre*10 + (p[0] - '0');
  179760. p++;
  179761. }
  179762. if( nPre<=0 || nPre>=1000 ){
  179763. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  179764. rc = SQLITE_ERROR;
  179765. break;
  179766. }
  179767. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  179768. pConfig->nPrefix++;
  179769. bFirst = 0;
  179770. }
  179771. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  179772. return rc;
  179773. }
  179774. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  179775. const char *p = (const char*)zArg;
  179776. int nArg = (int)strlen(zArg) + 1;
  179777. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  179778. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  179779. char *pSpace = pDel;
  179780. if( azArg && pSpace ){
  179781. if( pConfig->pTok ){
  179782. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  179783. rc = SQLITE_ERROR;
  179784. }else{
  179785. for(nArg=0; p && *p; nArg++){
  179786. const char *p2 = fts5ConfigSkipWhitespace(p);
  179787. if( *p2=='\'' ){
  179788. p = fts5ConfigSkipLiteral(p2);
  179789. }else{
  179790. p = fts5ConfigSkipBareword(p2);
  179791. }
  179792. if( p ){
  179793. memcpy(pSpace, p2, p-p2);
  179794. azArg[nArg] = pSpace;
  179795. sqlite3Fts5Dequote(pSpace);
  179796. pSpace += (p - p2) + 1;
  179797. p = fts5ConfigSkipWhitespace(p);
  179798. }
  179799. }
  179800. if( p==0 ){
  179801. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  179802. rc = SQLITE_ERROR;
  179803. }else{
  179804. rc = sqlite3Fts5GetTokenizer(pGlobal,
  179805. (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
  179806. pzErr
  179807. );
  179808. }
  179809. }
  179810. }
  179811. sqlite3_free(azArg);
  179812. sqlite3_free(pDel);
  179813. return rc;
  179814. }
  179815. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  179816. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  179817. *pzErr = sqlite3_mprintf("multiple content=... directives");
  179818. rc = SQLITE_ERROR;
  179819. }else{
  179820. if( zArg[0] ){
  179821. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  179822. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  179823. }else{
  179824. pConfig->eContent = FTS5_CONTENT_NONE;
  179825. }
  179826. }
  179827. return rc;
  179828. }
  179829. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  179830. if( pConfig->zContentRowid ){
  179831. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  179832. rc = SQLITE_ERROR;
  179833. }else{
  179834. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  179835. }
  179836. return rc;
  179837. }
  179838. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  179839. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  179840. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  179841. rc = SQLITE_ERROR;
  179842. }else{
  179843. pConfig->bColumnsize = (zArg[0]=='1');
  179844. }
  179845. return rc;
  179846. }
  179847. if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
  179848. const Fts5Enum aDetail[] = {
  179849. { "none", FTS5_DETAIL_NONE },
  179850. { "full", FTS5_DETAIL_FULL },
  179851. { "columns", FTS5_DETAIL_COLUMNS },
  179852. { 0, 0 }
  179853. };
  179854. if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
  179855. *pzErr = sqlite3_mprintf("malformed detail=... directive");
  179856. }
  179857. return rc;
  179858. }
  179859. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  179860. return SQLITE_ERROR;
  179861. }
  179862. /*
  179863. ** Allocate an instance of the default tokenizer ("simple") at
  179864. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  179865. ** code if an error occurs.
  179866. */
  179867. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  179868. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  179869. return sqlite3Fts5GetTokenizer(
  179870. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  179871. );
  179872. }
  179873. /*
  179874. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  179875. ** Return a pointer to the character immediately following the last in
  179876. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  179877. ** to find close-quote character).
  179878. **
  179879. ** Before returning, set pzOut to point to a new buffer containing a
  179880. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  179881. ** quoted, *pbQuoted is also set to 1 before returning.
  179882. **
  179883. ** If *pRc is other than SQLITE_OK when this function is called, it is
  179884. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  179885. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  179886. ** set if a parse error (failed to find close quote) occurs.
  179887. */
  179888. static const char *fts5ConfigGobbleWord(
  179889. int *pRc, /* IN/OUT: Error code */
  179890. const char *zIn, /* Buffer to gobble string/bareword from */
  179891. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  179892. int *pbQuoted /* OUT: Set to true if dequoting required */
  179893. ){
  179894. const char *zRet = 0;
  179895. int nIn = (int)strlen(zIn);
  179896. char *zOut = sqlite3_malloc(nIn+1);
  179897. assert( *pRc==SQLITE_OK );
  179898. *pbQuoted = 0;
  179899. *pzOut = 0;
  179900. if( zOut==0 ){
  179901. *pRc = SQLITE_NOMEM;
  179902. }else{
  179903. memcpy(zOut, zIn, nIn+1);
  179904. if( fts5_isopenquote(zOut[0]) ){
  179905. int ii = fts5Dequote(zOut);
  179906. zRet = &zIn[ii];
  179907. *pbQuoted = 1;
  179908. }else{
  179909. zRet = fts5ConfigSkipBareword(zIn);
  179910. if( zRet ){
  179911. zOut[zRet-zIn] = '\0';
  179912. }
  179913. }
  179914. }
  179915. if( zRet==0 ){
  179916. sqlite3_free(zOut);
  179917. }else{
  179918. *pzOut = zOut;
  179919. }
  179920. return zRet;
  179921. }
  179922. static int fts5ConfigParseColumn(
  179923. Fts5Config *p,
  179924. char *zCol,
  179925. char *zArg,
  179926. char **pzErr
  179927. ){
  179928. int rc = SQLITE_OK;
  179929. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  179930. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  179931. ){
  179932. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  179933. rc = SQLITE_ERROR;
  179934. }else if( zArg ){
  179935. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  179936. p->abUnindexed[p->nCol] = 1;
  179937. }else{
  179938. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  179939. rc = SQLITE_ERROR;
  179940. }
  179941. }
  179942. p->azCol[p->nCol++] = zCol;
  179943. return rc;
  179944. }
  179945. /*
  179946. ** Populate the Fts5Config.zContentExprlist string.
  179947. */
  179948. static int fts5ConfigMakeExprlist(Fts5Config *p){
  179949. int i;
  179950. int rc = SQLITE_OK;
  179951. Fts5Buffer buf = {0, 0, 0};
  179952. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  179953. if( p->eContent!=FTS5_CONTENT_NONE ){
  179954. for(i=0; i<p->nCol; i++){
  179955. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  179956. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  179957. }else{
  179958. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  179959. }
  179960. }
  179961. }
  179962. assert( p->zContentExprlist==0 );
  179963. p->zContentExprlist = (char*)buf.p;
  179964. return rc;
  179965. }
  179966. /*
  179967. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  179968. ** or xConnect method of the virtual table. This function attempts to
  179969. ** allocate an instance of Fts5Config containing the results of parsing
  179970. ** those arguments.
  179971. **
  179972. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  179973. ** new Fts5Config object. If an error occurs, an SQLite error code is
  179974. ** returned, *ppOut is set to NULL and an error message may be left in
  179975. ** *pzErr. It is the responsibility of the caller to eventually free any
  179976. ** such error message using sqlite3_free().
  179977. */
  179978. static int sqlite3Fts5ConfigParse(
  179979. Fts5Global *pGlobal,
  179980. sqlite3 *db,
  179981. int nArg, /* Number of arguments */
  179982. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  179983. Fts5Config **ppOut, /* OUT: Results of parse */
  179984. char **pzErr /* OUT: Error message */
  179985. ){
  179986. int rc = SQLITE_OK; /* Return code */
  179987. Fts5Config *pRet; /* New object to return */
  179988. int i;
  179989. int nByte;
  179990. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  179991. if( pRet==0 ) return SQLITE_NOMEM;
  179992. memset(pRet, 0, sizeof(Fts5Config));
  179993. pRet->db = db;
  179994. pRet->iCookie = -1;
  179995. nByte = nArg * (sizeof(char*) + sizeof(u8));
  179996. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  179997. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  179998. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  179999. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  180000. pRet->bColumnsize = 1;
  180001. pRet->eDetail = FTS5_DETAIL_FULL;
  180002. #ifdef SQLITE_DEBUG
  180003. pRet->bPrefixIndex = 1;
  180004. #endif
  180005. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  180006. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  180007. rc = SQLITE_ERROR;
  180008. }
  180009. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  180010. const char *zOrig = azArg[i];
  180011. const char *z;
  180012. char *zOne = 0;
  180013. char *zTwo = 0;
  180014. int bOption = 0;
  180015. int bMustBeCol = 0;
  180016. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  180017. z = fts5ConfigSkipWhitespace(z);
  180018. if( z && *z=='=' ){
  180019. bOption = 1;
  180020. z++;
  180021. if( bMustBeCol ) z = 0;
  180022. }
  180023. z = fts5ConfigSkipWhitespace(z);
  180024. if( z && z[0] ){
  180025. int bDummy;
  180026. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  180027. if( z && z[0] ) z = 0;
  180028. }
  180029. if( rc==SQLITE_OK ){
  180030. if( z==0 ){
  180031. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  180032. rc = SQLITE_ERROR;
  180033. }else{
  180034. if( bOption ){
  180035. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  180036. }else{
  180037. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  180038. zOne = 0;
  180039. }
  180040. }
  180041. }
  180042. sqlite3_free(zOne);
  180043. sqlite3_free(zTwo);
  180044. }
  180045. /* If a tokenizer= option was successfully parsed, the tokenizer has
  180046. ** already been allocated. Otherwise, allocate an instance of the default
  180047. ** tokenizer (unicode61) now. */
  180048. if( rc==SQLITE_OK && pRet->pTok==0 ){
  180049. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  180050. }
  180051. /* If no zContent option was specified, fill in the default values. */
  180052. if( rc==SQLITE_OK && pRet->zContent==0 ){
  180053. const char *zTail = 0;
  180054. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  180055. || pRet->eContent==FTS5_CONTENT_NONE
  180056. );
  180057. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  180058. zTail = "content";
  180059. }else if( pRet->bColumnsize ){
  180060. zTail = "docsize";
  180061. }
  180062. if( zTail ){
  180063. pRet->zContent = sqlite3Fts5Mprintf(
  180064. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  180065. );
  180066. }
  180067. }
  180068. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  180069. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  180070. }
  180071. /* Formulate the zContentExprlist text */
  180072. if( rc==SQLITE_OK ){
  180073. rc = fts5ConfigMakeExprlist(pRet);
  180074. }
  180075. if( rc!=SQLITE_OK ){
  180076. sqlite3Fts5ConfigFree(pRet);
  180077. *ppOut = 0;
  180078. }
  180079. return rc;
  180080. }
  180081. /*
  180082. ** Free the configuration object passed as the only argument.
  180083. */
  180084. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  180085. if( pConfig ){
  180086. int i;
  180087. if( pConfig->pTok ){
  180088. pConfig->pTokApi->xDelete(pConfig->pTok);
  180089. }
  180090. sqlite3_free(pConfig->zDb);
  180091. sqlite3_free(pConfig->zName);
  180092. for(i=0; i<pConfig->nCol; i++){
  180093. sqlite3_free(pConfig->azCol[i]);
  180094. }
  180095. sqlite3_free(pConfig->azCol);
  180096. sqlite3_free(pConfig->aPrefix);
  180097. sqlite3_free(pConfig->zRank);
  180098. sqlite3_free(pConfig->zRankArgs);
  180099. sqlite3_free(pConfig->zContent);
  180100. sqlite3_free(pConfig->zContentRowid);
  180101. sqlite3_free(pConfig->zContentExprlist);
  180102. sqlite3_free(pConfig);
  180103. }
  180104. }
  180105. /*
  180106. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  180107. ** object passed as the only argument. Return SQLITE_OK if successful, or
  180108. ** an SQLite error code if an error occurs.
  180109. */
  180110. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  180111. int i;
  180112. int rc = SQLITE_OK;
  180113. char *zSql;
  180114. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  180115. for(i=0; zSql && i<pConfig->nCol; i++){
  180116. const char *zSep = (i==0?"":", ");
  180117. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  180118. }
  180119. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  180120. zSql, pConfig->zName, FTS5_RANK_NAME
  180121. );
  180122. assert( zSql || rc==SQLITE_NOMEM );
  180123. if( zSql ){
  180124. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  180125. sqlite3_free(zSql);
  180126. }
  180127. return rc;
  180128. }
  180129. /*
  180130. ** Tokenize the text passed via the second and third arguments.
  180131. **
  180132. ** The callback is invoked once for each token in the input text. The
  180133. ** arguments passed to it are, in order:
  180134. **
  180135. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  180136. ** const char *pToken // Pointer to buffer containing token
  180137. ** int nToken // Size of token in bytes
  180138. ** int iStart // Byte offset of start of token within input text
  180139. ** int iEnd // Byte offset of end of token within input text
  180140. ** int iPos // Position of token in input (first token is 0)
  180141. **
  180142. ** If the callback returns a non-zero value the tokenization is abandoned
  180143. ** and no further callbacks are issued.
  180144. **
  180145. ** This function returns SQLITE_OK if successful or an SQLite error code
  180146. ** if an error occurs. If the tokenization was abandoned early because
  180147. ** the callback returned SQLITE_DONE, this is not an error and this function
  180148. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  180149. ** because the callback returned another non-zero value, it is assumed
  180150. ** to be an SQLite error code and returned to the caller.
  180151. */
  180152. static int sqlite3Fts5Tokenize(
  180153. Fts5Config *pConfig, /* FTS5 Configuration object */
  180154. int flags, /* FTS5_TOKENIZE_* flags */
  180155. const char *pText, int nText, /* Text to tokenize */
  180156. void *pCtx, /* Context passed to xToken() */
  180157. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  180158. ){
  180159. if( pText==0 ) return SQLITE_OK;
  180160. return pConfig->pTokApi->xTokenize(
  180161. pConfig->pTok, pCtx, flags, pText, nText, xToken
  180162. );
  180163. }
  180164. /*
  180165. ** Argument pIn points to the first character in what is expected to be
  180166. ** a comma-separated list of SQL literals followed by a ')' character.
  180167. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  180168. ** NULL to indicate a parse error.
  180169. */
  180170. static const char *fts5ConfigSkipArgs(const char *pIn){
  180171. const char *p = pIn;
  180172. while( 1 ){
  180173. p = fts5ConfigSkipWhitespace(p);
  180174. p = fts5ConfigSkipLiteral(p);
  180175. p = fts5ConfigSkipWhitespace(p);
  180176. if( p==0 || *p==')' ) break;
  180177. if( *p!=',' ){
  180178. p = 0;
  180179. break;
  180180. }
  180181. p++;
  180182. }
  180183. return p;
  180184. }
  180185. /*
  180186. ** Parameter zIn contains a rank() function specification. The format of
  180187. ** this is:
  180188. **
  180189. ** + Bareword (function name)
  180190. ** + Open parenthesis - "("
  180191. ** + Zero or more SQL literals in a comma separated list
  180192. ** + Close parenthesis - ")"
  180193. */
  180194. static int sqlite3Fts5ConfigParseRank(
  180195. const char *zIn, /* Input string */
  180196. char **pzRank, /* OUT: Rank function name */
  180197. char **pzRankArgs /* OUT: Rank function arguments */
  180198. ){
  180199. const char *p = zIn;
  180200. const char *pRank;
  180201. char *zRank = 0;
  180202. char *zRankArgs = 0;
  180203. int rc = SQLITE_OK;
  180204. *pzRank = 0;
  180205. *pzRankArgs = 0;
  180206. if( p==0 ){
  180207. rc = SQLITE_ERROR;
  180208. }else{
  180209. p = fts5ConfigSkipWhitespace(p);
  180210. pRank = p;
  180211. p = fts5ConfigSkipBareword(p);
  180212. if( p ){
  180213. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  180214. if( zRank ) memcpy(zRank, pRank, p-pRank);
  180215. }else{
  180216. rc = SQLITE_ERROR;
  180217. }
  180218. if( rc==SQLITE_OK ){
  180219. p = fts5ConfigSkipWhitespace(p);
  180220. if( *p!='(' ) rc = SQLITE_ERROR;
  180221. p++;
  180222. }
  180223. if( rc==SQLITE_OK ){
  180224. const char *pArgs;
  180225. p = fts5ConfigSkipWhitespace(p);
  180226. pArgs = p;
  180227. if( *p!=')' ){
  180228. p = fts5ConfigSkipArgs(p);
  180229. if( p==0 ){
  180230. rc = SQLITE_ERROR;
  180231. }else{
  180232. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  180233. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  180234. }
  180235. }
  180236. }
  180237. }
  180238. if( rc!=SQLITE_OK ){
  180239. sqlite3_free(zRank);
  180240. assert( zRankArgs==0 );
  180241. }else{
  180242. *pzRank = zRank;
  180243. *pzRankArgs = zRankArgs;
  180244. }
  180245. return rc;
  180246. }
  180247. static int sqlite3Fts5ConfigSetValue(
  180248. Fts5Config *pConfig,
  180249. const char *zKey,
  180250. sqlite3_value *pVal,
  180251. int *pbBadkey
  180252. ){
  180253. int rc = SQLITE_OK;
  180254. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  180255. int pgsz = 0;
  180256. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  180257. pgsz = sqlite3_value_int(pVal);
  180258. }
  180259. if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
  180260. *pbBadkey = 1;
  180261. }else{
  180262. pConfig->pgsz = pgsz;
  180263. }
  180264. }
  180265. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  180266. int nHashSize = -1;
  180267. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  180268. nHashSize = sqlite3_value_int(pVal);
  180269. }
  180270. if( nHashSize<=0 ){
  180271. *pbBadkey = 1;
  180272. }else{
  180273. pConfig->nHashSize = nHashSize;
  180274. }
  180275. }
  180276. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  180277. int nAutomerge = -1;
  180278. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  180279. nAutomerge = sqlite3_value_int(pVal);
  180280. }
  180281. if( nAutomerge<0 || nAutomerge>64 ){
  180282. *pbBadkey = 1;
  180283. }else{
  180284. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  180285. pConfig->nAutomerge = nAutomerge;
  180286. }
  180287. }
  180288. else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
  180289. int nUsermerge = -1;
  180290. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  180291. nUsermerge = sqlite3_value_int(pVal);
  180292. }
  180293. if( nUsermerge<2 || nUsermerge>16 ){
  180294. *pbBadkey = 1;
  180295. }else{
  180296. pConfig->nUsermerge = nUsermerge;
  180297. }
  180298. }
  180299. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  180300. int nCrisisMerge = -1;
  180301. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  180302. nCrisisMerge = sqlite3_value_int(pVal);
  180303. }
  180304. if( nCrisisMerge<0 ){
  180305. *pbBadkey = 1;
  180306. }else{
  180307. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  180308. pConfig->nCrisisMerge = nCrisisMerge;
  180309. }
  180310. }
  180311. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  180312. const char *zIn = (const char*)sqlite3_value_text(pVal);
  180313. char *zRank;
  180314. char *zRankArgs;
  180315. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  180316. if( rc==SQLITE_OK ){
  180317. sqlite3_free(pConfig->zRank);
  180318. sqlite3_free(pConfig->zRankArgs);
  180319. pConfig->zRank = zRank;
  180320. pConfig->zRankArgs = zRankArgs;
  180321. }else if( rc==SQLITE_ERROR ){
  180322. rc = SQLITE_OK;
  180323. *pbBadkey = 1;
  180324. }
  180325. }else{
  180326. *pbBadkey = 1;
  180327. }
  180328. return rc;
  180329. }
  180330. /*
  180331. ** Load the contents of the %_config table into memory.
  180332. */
  180333. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  180334. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  180335. char *zSql;
  180336. sqlite3_stmt *p = 0;
  180337. int rc = SQLITE_OK;
  180338. int iVersion = 0;
  180339. /* Set default values */
  180340. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  180341. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  180342. pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
  180343. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  180344. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  180345. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  180346. if( zSql ){
  180347. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  180348. sqlite3_free(zSql);
  180349. }
  180350. assert( rc==SQLITE_OK || p==0 );
  180351. if( rc==SQLITE_OK ){
  180352. while( SQLITE_ROW==sqlite3_step(p) ){
  180353. const char *zK = (const char*)sqlite3_column_text(p, 0);
  180354. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  180355. if( 0==sqlite3_stricmp(zK, "version") ){
  180356. iVersion = sqlite3_value_int(pVal);
  180357. }else{
  180358. int bDummy = 0;
  180359. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  180360. }
  180361. }
  180362. rc = sqlite3_finalize(p);
  180363. }
  180364. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  180365. rc = SQLITE_ERROR;
  180366. if( pConfig->pzErrmsg ){
  180367. assert( 0==*pConfig->pzErrmsg );
  180368. *pConfig->pzErrmsg = sqlite3_mprintf(
  180369. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  180370. iVersion, FTS5_CURRENT_VERSION
  180371. );
  180372. }
  180373. }
  180374. if( rc==SQLITE_OK ){
  180375. pConfig->iCookie = iCookie;
  180376. }
  180377. return rc;
  180378. }
  180379. /*
  180380. ** 2014 May 31
  180381. **
  180382. ** The author disclaims copyright to this source code. In place of
  180383. ** a legal notice, here is a blessing:
  180384. **
  180385. ** May you do good and not evil.
  180386. ** May you find forgiveness for yourself and forgive others.
  180387. ** May you share freely, never taking more than you give.
  180388. **
  180389. ******************************************************************************
  180390. **
  180391. */
  180392. /* #include "fts5Int.h" */
  180393. /* #include "fts5parse.h" */
  180394. /*
  180395. ** All token types in the generated fts5parse.h file are greater than 0.
  180396. */
  180397. #define FTS5_EOF 0
  180398. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  180399. typedef struct Fts5ExprTerm Fts5ExprTerm;
  180400. /*
  180401. ** Functions generated by lemon from fts5parse.y.
  180402. */
  180403. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  180404. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  180405. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  180406. #ifndef NDEBUG
  180407. /* #include <stdio.h> */
  180408. static void sqlite3Fts5ParserTrace(FILE*, char*);
  180409. #endif
  180410. struct Fts5Expr {
  180411. Fts5Index *pIndex;
  180412. Fts5Config *pConfig;
  180413. Fts5ExprNode *pRoot;
  180414. int bDesc; /* Iterate in descending rowid order */
  180415. int nPhrase; /* Number of phrases in expression */
  180416. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  180417. };
  180418. /*
  180419. ** eType:
  180420. ** Expression node type. Always one of:
  180421. **
  180422. ** FTS5_AND (nChild, apChild valid)
  180423. ** FTS5_OR (nChild, apChild valid)
  180424. ** FTS5_NOT (nChild, apChild valid)
  180425. ** FTS5_STRING (pNear valid)
  180426. ** FTS5_TERM (pNear valid)
  180427. */
  180428. struct Fts5ExprNode {
  180429. int eType; /* Node type */
  180430. int bEof; /* True at EOF */
  180431. int bNomatch; /* True if entry is not a match */
  180432. /* Next method for this node. */
  180433. int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
  180434. i64 iRowid; /* Current rowid */
  180435. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  180436. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  180437. ** AND or OR nodes, it contains 2 or more entries. */
  180438. int nChild; /* Number of child nodes */
  180439. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  180440. };
  180441. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  180442. /*
  180443. ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
  180444. ** used as if it has the same signature as the xNext() methods themselves.
  180445. */
  180446. #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
  180447. /*
  180448. ** An instance of the following structure represents a single search term
  180449. ** or term prefix.
  180450. */
  180451. struct Fts5ExprTerm {
  180452. u8 bPrefix; /* True for a prefix term */
  180453. u8 bFirst; /* True if token must be first in column */
  180454. char *zTerm; /* nul-terminated term */
  180455. Fts5IndexIter *pIter; /* Iterator for this term */
  180456. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  180457. };
  180458. /*
  180459. ** A phrase. One or more terms that must appear in a contiguous sequence
  180460. ** within a document for it to match.
  180461. */
  180462. struct Fts5ExprPhrase {
  180463. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  180464. Fts5Buffer poslist; /* Current position list */
  180465. int nTerm; /* Number of entries in aTerm[] */
  180466. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  180467. };
  180468. /*
  180469. ** One or more phrases that must appear within a certain token distance of
  180470. ** each other within each matching document.
  180471. */
  180472. struct Fts5ExprNearset {
  180473. int nNear; /* NEAR parameter */
  180474. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  180475. int nPhrase; /* Number of entries in aPhrase[] array */
  180476. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  180477. };
  180478. /*
  180479. ** Parse context.
  180480. */
  180481. struct Fts5Parse {
  180482. Fts5Config *pConfig;
  180483. char *zErr;
  180484. int rc;
  180485. int nPhrase; /* Size of apPhrase array */
  180486. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  180487. Fts5ExprNode *pExpr; /* Result of a successful parse */
  180488. };
  180489. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  180490. va_list ap;
  180491. va_start(ap, zFmt);
  180492. if( pParse->rc==SQLITE_OK ){
  180493. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  180494. pParse->rc = SQLITE_ERROR;
  180495. }
  180496. va_end(ap);
  180497. }
  180498. static int fts5ExprIsspace(char t){
  180499. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  180500. }
  180501. /*
  180502. ** Read the first token from the nul-terminated string at *pz.
  180503. */
  180504. static int fts5ExprGetToken(
  180505. Fts5Parse *pParse,
  180506. const char **pz, /* IN/OUT: Pointer into buffer */
  180507. Fts5Token *pToken
  180508. ){
  180509. const char *z = *pz;
  180510. int tok;
  180511. /* Skip past any whitespace */
  180512. while( fts5ExprIsspace(*z) ) z++;
  180513. pToken->p = z;
  180514. pToken->n = 1;
  180515. switch( *z ){
  180516. case '(': tok = FTS5_LP; break;
  180517. case ')': tok = FTS5_RP; break;
  180518. case '{': tok = FTS5_LCP; break;
  180519. case '}': tok = FTS5_RCP; break;
  180520. case ':': tok = FTS5_COLON; break;
  180521. case ',': tok = FTS5_COMMA; break;
  180522. case '+': tok = FTS5_PLUS; break;
  180523. case '*': tok = FTS5_STAR; break;
  180524. case '-': tok = FTS5_MINUS; break;
  180525. case '^': tok = FTS5_CARET; break;
  180526. case '\0': tok = FTS5_EOF; break;
  180527. case '"': {
  180528. const char *z2;
  180529. tok = FTS5_STRING;
  180530. for(z2=&z[1]; 1; z2++){
  180531. if( z2[0]=='"' ){
  180532. z2++;
  180533. if( z2[0]!='"' ) break;
  180534. }
  180535. if( z2[0]=='\0' ){
  180536. sqlite3Fts5ParseError(pParse, "unterminated string");
  180537. return FTS5_EOF;
  180538. }
  180539. }
  180540. pToken->n = (z2 - z);
  180541. break;
  180542. }
  180543. default: {
  180544. const char *z2;
  180545. if( sqlite3Fts5IsBareword(z[0])==0 ){
  180546. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  180547. return FTS5_EOF;
  180548. }
  180549. tok = FTS5_STRING;
  180550. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  180551. pToken->n = (z2 - z);
  180552. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  180553. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  180554. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  180555. break;
  180556. }
  180557. }
  180558. *pz = &pToken->p[pToken->n];
  180559. return tok;
  180560. }
  180561. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
  180562. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  180563. static int sqlite3Fts5ExprNew(
  180564. Fts5Config *pConfig, /* FTS5 Configuration */
  180565. int iCol,
  180566. const char *zExpr, /* Expression text */
  180567. Fts5Expr **ppNew,
  180568. char **pzErr
  180569. ){
  180570. Fts5Parse sParse;
  180571. Fts5Token token;
  180572. const char *z = zExpr;
  180573. int t; /* Next token type */
  180574. void *pEngine;
  180575. Fts5Expr *pNew;
  180576. *ppNew = 0;
  180577. *pzErr = 0;
  180578. memset(&sParse, 0, sizeof(sParse));
  180579. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  180580. if( pEngine==0 ){ return SQLITE_NOMEM; }
  180581. sParse.pConfig = pConfig;
  180582. do {
  180583. t = fts5ExprGetToken(&sParse, &z, &token);
  180584. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  180585. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  180586. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  180587. /* If the LHS of the MATCH expression was a user column, apply the
  180588. ** implicit column-filter. */
  180589. if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
  180590. int n = sizeof(Fts5Colset);
  180591. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
  180592. if( pColset ){
  180593. pColset->nCol = 1;
  180594. pColset->aiCol[0] = iCol;
  180595. sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
  180596. }
  180597. }
  180598. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  180599. if( sParse.rc==SQLITE_OK ){
  180600. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  180601. if( pNew==0 ){
  180602. sParse.rc = SQLITE_NOMEM;
  180603. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  180604. }else{
  180605. if( !sParse.pExpr ){
  180606. const int nByte = sizeof(Fts5ExprNode);
  180607. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
  180608. if( pNew->pRoot ){
  180609. pNew->pRoot->bEof = 1;
  180610. }
  180611. }else{
  180612. pNew->pRoot = sParse.pExpr;
  180613. }
  180614. pNew->pIndex = 0;
  180615. pNew->pConfig = pConfig;
  180616. pNew->apExprPhrase = sParse.apPhrase;
  180617. pNew->nPhrase = sParse.nPhrase;
  180618. sParse.apPhrase = 0;
  180619. }
  180620. }else{
  180621. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  180622. }
  180623. sqlite3_free(sParse.apPhrase);
  180624. *pzErr = sParse.zErr;
  180625. return sParse.rc;
  180626. }
  180627. /*
  180628. ** Free the expression node object passed as the only argument.
  180629. */
  180630. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  180631. if( p ){
  180632. int i;
  180633. for(i=0; i<p->nChild; i++){
  180634. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  180635. }
  180636. sqlite3Fts5ParseNearsetFree(p->pNear);
  180637. sqlite3_free(p);
  180638. }
  180639. }
  180640. /*
  180641. ** Free the expression object passed as the only argument.
  180642. */
  180643. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  180644. if( p ){
  180645. sqlite3Fts5ParseNodeFree(p->pRoot);
  180646. sqlite3_free(p->apExprPhrase);
  180647. sqlite3_free(p);
  180648. }
  180649. }
  180650. /*
  180651. ** Argument pTerm must be a synonym iterator. Return the current rowid
  180652. ** that it points to.
  180653. */
  180654. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  180655. i64 iRet = 0;
  180656. int bRetValid = 0;
  180657. Fts5ExprTerm *p;
  180658. assert( pTerm->pSynonym );
  180659. assert( bDesc==0 || bDesc==1 );
  180660. for(p=pTerm; p; p=p->pSynonym){
  180661. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  180662. i64 iRowid = p->pIter->iRowid;
  180663. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  180664. iRet = iRowid;
  180665. bRetValid = 1;
  180666. }
  180667. }
  180668. }
  180669. if( pbEof && bRetValid==0 ) *pbEof = 1;
  180670. return iRet;
  180671. }
  180672. /*
  180673. ** Argument pTerm must be a synonym iterator.
  180674. */
  180675. static int fts5ExprSynonymList(
  180676. Fts5ExprTerm *pTerm,
  180677. i64 iRowid,
  180678. Fts5Buffer *pBuf, /* Use this buffer for space if required */
  180679. u8 **pa, int *pn
  180680. ){
  180681. Fts5PoslistReader aStatic[4];
  180682. Fts5PoslistReader *aIter = aStatic;
  180683. int nIter = 0;
  180684. int nAlloc = 4;
  180685. int rc = SQLITE_OK;
  180686. Fts5ExprTerm *p;
  180687. assert( pTerm->pSynonym );
  180688. for(p=pTerm; p; p=p->pSynonym){
  180689. Fts5IndexIter *pIter = p->pIter;
  180690. if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
  180691. if( pIter->nData==0 ) continue;
  180692. if( nIter==nAlloc ){
  180693. int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  180694. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  180695. if( aNew==0 ){
  180696. rc = SQLITE_NOMEM;
  180697. goto synonym_poslist_out;
  180698. }
  180699. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  180700. nAlloc = nAlloc*2;
  180701. if( aIter!=aStatic ) sqlite3_free(aIter);
  180702. aIter = aNew;
  180703. }
  180704. sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
  180705. assert( aIter[nIter].bEof==0 );
  180706. nIter++;
  180707. }
  180708. }
  180709. if( nIter==1 ){
  180710. *pa = (u8*)aIter[0].a;
  180711. *pn = aIter[0].n;
  180712. }else{
  180713. Fts5PoslistWriter writer = {0};
  180714. i64 iPrev = -1;
  180715. fts5BufferZero(pBuf);
  180716. while( 1 ){
  180717. int i;
  180718. i64 iMin = FTS5_LARGEST_INT64;
  180719. for(i=0; i<nIter; i++){
  180720. if( aIter[i].bEof==0 ){
  180721. if( aIter[i].iPos==iPrev ){
  180722. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  180723. }
  180724. if( aIter[i].iPos<iMin ){
  180725. iMin = aIter[i].iPos;
  180726. }
  180727. }
  180728. }
  180729. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  180730. rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
  180731. iPrev = iMin;
  180732. }
  180733. if( rc==SQLITE_OK ){
  180734. *pa = pBuf->p;
  180735. *pn = pBuf->n;
  180736. }
  180737. }
  180738. synonym_poslist_out:
  180739. if( aIter!=aStatic ) sqlite3_free(aIter);
  180740. return rc;
  180741. }
  180742. /*
  180743. ** All individual term iterators in pPhrase are guaranteed to be valid and
  180744. ** pointing to the same rowid when this function is called. This function
  180745. ** checks if the current rowid really is a match, and if so populates
  180746. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  180747. ** is set to true if this is really a match, or false otherwise.
  180748. **
  180749. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  180750. ** otherwise. It is not considered an error code if the current rowid is
  180751. ** not a match.
  180752. */
  180753. static int fts5ExprPhraseIsMatch(
  180754. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  180755. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  180756. int *pbMatch /* OUT: Set to true if really a match */
  180757. ){
  180758. Fts5PoslistWriter writer = {0};
  180759. Fts5PoslistReader aStatic[4];
  180760. Fts5PoslistReader *aIter = aStatic;
  180761. int i;
  180762. int rc = SQLITE_OK;
  180763. int bFirst = pPhrase->aTerm[0].bFirst;
  180764. fts5BufferZero(&pPhrase->poslist);
  180765. /* If the aStatic[] array is not large enough, allocate a large array
  180766. ** using sqlite3_malloc(). This approach could be improved upon. */
  180767. if( pPhrase->nTerm>ArraySize(aStatic) ){
  180768. int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  180769. aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
  180770. if( !aIter ) return SQLITE_NOMEM;
  180771. }
  180772. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  180773. /* Initialize a term iterator for each term in the phrase */
  180774. for(i=0; i<pPhrase->nTerm; i++){
  180775. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  180776. int n = 0;
  180777. int bFlag = 0;
  180778. u8 *a = 0;
  180779. if( pTerm->pSynonym ){
  180780. Fts5Buffer buf = {0, 0, 0};
  180781. rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
  180782. if( rc ){
  180783. sqlite3_free(a);
  180784. goto ismatch_out;
  180785. }
  180786. if( a==buf.p ) bFlag = 1;
  180787. }else{
  180788. a = (u8*)pTerm->pIter->pData;
  180789. n = pTerm->pIter->nData;
  180790. }
  180791. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  180792. aIter[i].bFlag = (u8)bFlag;
  180793. if( aIter[i].bEof ) goto ismatch_out;
  180794. }
  180795. while( 1 ){
  180796. int bMatch;
  180797. i64 iPos = aIter[0].iPos;
  180798. do {
  180799. bMatch = 1;
  180800. for(i=0; i<pPhrase->nTerm; i++){
  180801. Fts5PoslistReader *pPos = &aIter[i];
  180802. i64 iAdj = iPos + i;
  180803. if( pPos->iPos!=iAdj ){
  180804. bMatch = 0;
  180805. while( pPos->iPos<iAdj ){
  180806. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  180807. }
  180808. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  180809. }
  180810. }
  180811. }while( bMatch==0 );
  180812. /* Append position iPos to the output */
  180813. if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
  180814. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  180815. if( rc!=SQLITE_OK ) goto ismatch_out;
  180816. }
  180817. for(i=0; i<pPhrase->nTerm; i++){
  180818. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  180819. }
  180820. }
  180821. ismatch_out:
  180822. *pbMatch = (pPhrase->poslist.n>0);
  180823. for(i=0; i<pPhrase->nTerm; i++){
  180824. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  180825. }
  180826. if( aIter!=aStatic ) sqlite3_free(aIter);
  180827. return rc;
  180828. }
  180829. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  180830. struct Fts5LookaheadReader {
  180831. const u8 *a; /* Buffer containing position list */
  180832. int n; /* Size of buffer a[] in bytes */
  180833. int i; /* Current offset in position list */
  180834. i64 iPos; /* Current position */
  180835. i64 iLookahead; /* Next position */
  180836. };
  180837. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  180838. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  180839. p->iPos = p->iLookahead;
  180840. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  180841. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  180842. }
  180843. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  180844. }
  180845. static int fts5LookaheadReaderInit(
  180846. const u8 *a, int n, /* Buffer to read position list from */
  180847. Fts5LookaheadReader *p /* Iterator object to initialize */
  180848. ){
  180849. memset(p, 0, sizeof(Fts5LookaheadReader));
  180850. p->a = a;
  180851. p->n = n;
  180852. fts5LookaheadReaderNext(p);
  180853. return fts5LookaheadReaderNext(p);
  180854. }
  180855. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  180856. struct Fts5NearTrimmer {
  180857. Fts5LookaheadReader reader; /* Input iterator */
  180858. Fts5PoslistWriter writer; /* Writer context */
  180859. Fts5Buffer *pOut; /* Output poslist */
  180860. };
  180861. /*
  180862. ** The near-set object passed as the first argument contains more than
  180863. ** one phrase. All phrases currently point to the same row. The
  180864. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  180865. ** tests if the current row contains instances of each phrase sufficiently
  180866. ** close together to meet the NEAR constraint. Non-zero is returned if it
  180867. ** does, or zero otherwise.
  180868. **
  180869. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  180870. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  180871. ** occurs within this function (*pRc) is set accordingly before returning.
  180872. ** The return value is undefined in both these cases.
  180873. **
  180874. ** If no error occurs and non-zero (a match) is returned, the position-list
  180875. ** of each phrase object is edited to contain only those entries that
  180876. ** meet the constraint before returning.
  180877. */
  180878. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  180879. Fts5NearTrimmer aStatic[4];
  180880. Fts5NearTrimmer *a = aStatic;
  180881. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  180882. int i;
  180883. int rc = *pRc;
  180884. int bMatch;
  180885. assert( pNear->nPhrase>1 );
  180886. /* If the aStatic[] array is not large enough, allocate a large array
  180887. ** using sqlite3_malloc(). This approach could be improved upon. */
  180888. if( pNear->nPhrase>ArraySize(aStatic) ){
  180889. int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  180890. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  180891. }else{
  180892. memset(aStatic, 0, sizeof(aStatic));
  180893. }
  180894. if( rc!=SQLITE_OK ){
  180895. *pRc = rc;
  180896. return 0;
  180897. }
  180898. /* Initialize a lookahead iterator for each phrase. After passing the
  180899. ** buffer and buffer size to the lookaside-reader init function, zero
  180900. ** the phrase poslist buffer. The new poslist for the phrase (containing
  180901. ** the same entries as the original with some entries removed on account
  180902. ** of the NEAR constraint) is written over the original even as it is
  180903. ** being read. This is safe as the entries for the new poslist are a
  180904. ** subset of the old, so it is not possible for data yet to be read to
  180905. ** be overwritten. */
  180906. for(i=0; i<pNear->nPhrase; i++){
  180907. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  180908. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  180909. pPoslist->n = 0;
  180910. a[i].pOut = pPoslist;
  180911. }
  180912. while( 1 ){
  180913. int iAdv;
  180914. i64 iMin;
  180915. i64 iMax;
  180916. /* This block advances the phrase iterators until they point to a set of
  180917. ** entries that together comprise a match. */
  180918. iMax = a[0].reader.iPos;
  180919. do {
  180920. bMatch = 1;
  180921. for(i=0; i<pNear->nPhrase; i++){
  180922. Fts5LookaheadReader *pPos = &a[i].reader;
  180923. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  180924. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  180925. bMatch = 0;
  180926. while( pPos->iPos<iMin ){
  180927. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  180928. }
  180929. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  180930. }
  180931. }
  180932. }while( bMatch==0 );
  180933. /* Add an entry to each output position list */
  180934. for(i=0; i<pNear->nPhrase; i++){
  180935. i64 iPos = a[i].reader.iPos;
  180936. Fts5PoslistWriter *pWriter = &a[i].writer;
  180937. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  180938. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  180939. }
  180940. }
  180941. iAdv = 0;
  180942. iMin = a[0].reader.iLookahead;
  180943. for(i=0; i<pNear->nPhrase; i++){
  180944. if( a[i].reader.iLookahead < iMin ){
  180945. iMin = a[i].reader.iLookahead;
  180946. iAdv = i;
  180947. }
  180948. }
  180949. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  180950. }
  180951. ismatch_out: {
  180952. int bRet = a[0].pOut->n>0;
  180953. *pRc = rc;
  180954. if( a!=aStatic ) sqlite3_free(a);
  180955. return bRet;
  180956. }
  180957. }
  180958. /*
  180959. ** Advance iterator pIter until it points to a value equal to or laster
  180960. ** than the initial value of *piLast. If this means the iterator points
  180961. ** to a value laster than *piLast, update *piLast to the new lastest value.
  180962. **
  180963. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  180964. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  180965. ** are set, return a non-zero value. Otherwise, return zero.
  180966. */
  180967. static int fts5ExprAdvanceto(
  180968. Fts5IndexIter *pIter, /* Iterator to advance */
  180969. int bDesc, /* True if iterator is "rowid DESC" */
  180970. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  180971. int *pRc, /* OUT: Error code */
  180972. int *pbEof /* OUT: Set to true if EOF */
  180973. ){
  180974. i64 iLast = *piLast;
  180975. i64 iRowid;
  180976. iRowid = pIter->iRowid;
  180977. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  180978. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  180979. if( rc || sqlite3Fts5IterEof(pIter) ){
  180980. *pRc = rc;
  180981. *pbEof = 1;
  180982. return 1;
  180983. }
  180984. iRowid = pIter->iRowid;
  180985. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  180986. }
  180987. *piLast = iRowid;
  180988. return 0;
  180989. }
  180990. static int fts5ExprSynonymAdvanceto(
  180991. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  180992. int bDesc, /* True if iterator is "rowid DESC" */
  180993. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  180994. int *pRc /* OUT: Error code */
  180995. ){
  180996. int rc = SQLITE_OK;
  180997. i64 iLast = *piLast;
  180998. Fts5ExprTerm *p;
  180999. int bEof = 0;
  181000. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  181001. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  181002. i64 iRowid = p->pIter->iRowid;
  181003. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  181004. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  181005. }
  181006. }
  181007. }
  181008. if( rc!=SQLITE_OK ){
  181009. *pRc = rc;
  181010. bEof = 1;
  181011. }else{
  181012. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  181013. }
  181014. return bEof;
  181015. }
  181016. static int fts5ExprNearTest(
  181017. int *pRc,
  181018. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  181019. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  181020. ){
  181021. Fts5ExprNearset *pNear = pNode->pNear;
  181022. int rc = *pRc;
  181023. if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  181024. Fts5ExprTerm *pTerm;
  181025. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  181026. pPhrase->poslist.n = 0;
  181027. for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  181028. Fts5IndexIter *pIter = pTerm->pIter;
  181029. if( sqlite3Fts5IterEof(pIter)==0 ){
  181030. if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
  181031. pPhrase->poslist.n = 1;
  181032. }
  181033. }
  181034. }
  181035. return pPhrase->poslist.n;
  181036. }else{
  181037. int i;
  181038. /* Check that each phrase in the nearset matches the current row.
  181039. ** Populate the pPhrase->poslist buffers at the same time. If any
  181040. ** phrase is not a match, break out of the loop early. */
  181041. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  181042. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  181043. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
  181044. || pNear->pColset || pPhrase->aTerm[0].bFirst
  181045. ){
  181046. int bMatch = 0;
  181047. rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
  181048. if( bMatch==0 ) break;
  181049. }else{
  181050. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  181051. fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
  181052. }
  181053. }
  181054. *pRc = rc;
  181055. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  181056. return 1;
  181057. }
  181058. return 0;
  181059. }
  181060. }
  181061. /*
  181062. ** Initialize all term iterators in the pNear object. If any term is found
  181063. ** to match no documents at all, return immediately without initializing any
  181064. ** further iterators.
  181065. **
  181066. ** If an error occurs, return an SQLite error code. Otherwise, return
  181067. ** SQLITE_OK. It is not considered an error if some term matches zero
  181068. ** documents.
  181069. */
  181070. static int fts5ExprNearInitAll(
  181071. Fts5Expr *pExpr,
  181072. Fts5ExprNode *pNode
  181073. ){
  181074. Fts5ExprNearset *pNear = pNode->pNear;
  181075. int i;
  181076. assert( pNode->bNomatch==0 );
  181077. for(i=0; i<pNear->nPhrase; i++){
  181078. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  181079. if( pPhrase->nTerm==0 ){
  181080. pNode->bEof = 1;
  181081. return SQLITE_OK;
  181082. }else{
  181083. int j;
  181084. for(j=0; j<pPhrase->nTerm; j++){
  181085. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  181086. Fts5ExprTerm *p;
  181087. int bHit = 0;
  181088. for(p=pTerm; p; p=p->pSynonym){
  181089. int rc;
  181090. if( p->pIter ){
  181091. sqlite3Fts5IterClose(p->pIter);
  181092. p->pIter = 0;
  181093. }
  181094. rc = sqlite3Fts5IndexQuery(
  181095. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  181096. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  181097. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  181098. pNear->pColset,
  181099. &p->pIter
  181100. );
  181101. assert( (rc==SQLITE_OK)==(p->pIter!=0) );
  181102. if( rc!=SQLITE_OK ) return rc;
  181103. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  181104. bHit = 1;
  181105. }
  181106. }
  181107. if( bHit==0 ){
  181108. pNode->bEof = 1;
  181109. return SQLITE_OK;
  181110. }
  181111. }
  181112. }
  181113. }
  181114. pNode->bEof = 0;
  181115. return SQLITE_OK;
  181116. }
  181117. /*
  181118. ** If pExpr is an ASC iterator, this function returns a value with the
  181119. ** same sign as:
  181120. **
  181121. ** (iLhs - iRhs)
  181122. **
  181123. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  181124. **
  181125. ** (iRhs - iLhs)
  181126. */
  181127. static int fts5RowidCmp(
  181128. Fts5Expr *pExpr,
  181129. i64 iLhs,
  181130. i64 iRhs
  181131. ){
  181132. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  181133. if( pExpr->bDesc==0 ){
  181134. if( iLhs<iRhs ) return -1;
  181135. return (iLhs > iRhs);
  181136. }else{
  181137. if( iLhs>iRhs ) return -1;
  181138. return (iLhs < iRhs);
  181139. }
  181140. }
  181141. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  181142. int i;
  181143. pNode->bEof = 1;
  181144. pNode->bNomatch = 0;
  181145. for(i=0; i<pNode->nChild; i++){
  181146. fts5ExprSetEof(pNode->apChild[i]);
  181147. }
  181148. }
  181149. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  181150. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  181151. Fts5ExprNearset *pNear = pNode->pNear;
  181152. int i;
  181153. for(i=0; i<pNear->nPhrase; i++){
  181154. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  181155. pPhrase->poslist.n = 0;
  181156. }
  181157. }else{
  181158. int i;
  181159. for(i=0; i<pNode->nChild; i++){
  181160. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  181161. }
  181162. }
  181163. }
  181164. /*
  181165. ** Compare the values currently indicated by the two nodes as follows:
  181166. **
  181167. ** res = (*p1) - (*p2)
  181168. **
  181169. ** Nodes that point to values that come later in the iteration order are
  181170. ** considered to be larger. Nodes at EOF are the largest of all.
  181171. **
  181172. ** This means that if the iteration order is ASC, then numerically larger
  181173. ** rowids are considered larger. Or if it is the default DESC, numerically
  181174. ** smaller rowids are larger.
  181175. */
  181176. static int fts5NodeCompare(
  181177. Fts5Expr *pExpr,
  181178. Fts5ExprNode *p1,
  181179. Fts5ExprNode *p2
  181180. ){
  181181. if( p2->bEof ) return -1;
  181182. if( p1->bEof ) return +1;
  181183. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  181184. }
  181185. /*
  181186. ** All individual term iterators in pNear are guaranteed to be valid when
  181187. ** this function is called. This function checks if all term iterators
  181188. ** point to the same rowid, and if not, advances them until they do.
  181189. ** If an EOF is reached before this happens, *pbEof is set to true before
  181190. ** returning.
  181191. **
  181192. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  181193. ** otherwise. It is not considered an error code if an iterator reaches
  181194. ** EOF.
  181195. */
  181196. static int fts5ExprNodeTest_STRING(
  181197. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  181198. Fts5ExprNode *pNode
  181199. ){
  181200. Fts5ExprNearset *pNear = pNode->pNear;
  181201. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  181202. int rc = SQLITE_OK;
  181203. i64 iLast; /* Lastest rowid any iterator points to */
  181204. int i, j; /* Phrase and token index, respectively */
  181205. int bMatch; /* True if all terms are at the same rowid */
  181206. const int bDesc = pExpr->bDesc;
  181207. /* Check that this node should not be FTS5_TERM */
  181208. assert( pNear->nPhrase>1
  181209. || pNear->apPhrase[0]->nTerm>1
  181210. || pNear->apPhrase[0]->aTerm[0].pSynonym
  181211. || pNear->apPhrase[0]->aTerm[0].bFirst
  181212. );
  181213. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  181214. ** iterator skips through rowids in the default ascending order, this means
  181215. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  181216. ** means the minimum rowid. */
  181217. if( pLeft->aTerm[0].pSynonym ){
  181218. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  181219. }else{
  181220. iLast = pLeft->aTerm[0].pIter->iRowid;
  181221. }
  181222. do {
  181223. bMatch = 1;
  181224. for(i=0; i<pNear->nPhrase; i++){
  181225. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  181226. for(j=0; j<pPhrase->nTerm; j++){
  181227. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  181228. if( pTerm->pSynonym ){
  181229. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  181230. if( iRowid==iLast ) continue;
  181231. bMatch = 0;
  181232. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  181233. pNode->bNomatch = 0;
  181234. pNode->bEof = 1;
  181235. return rc;
  181236. }
  181237. }else{
  181238. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  181239. if( pIter->iRowid==iLast || pIter->bEof ) continue;
  181240. bMatch = 0;
  181241. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  181242. return rc;
  181243. }
  181244. }
  181245. }
  181246. }
  181247. }while( bMatch==0 );
  181248. pNode->iRowid = iLast;
  181249. pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
  181250. assert( pNode->bEof==0 || pNode->bNomatch==0 );
  181251. return rc;
  181252. }
  181253. /*
  181254. ** Advance the first term iterator in the first phrase of pNear. Set output
  181255. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  181256. **
  181257. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  181258. ** occurs.
  181259. */
  181260. static int fts5ExprNodeNext_STRING(
  181261. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  181262. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  181263. int bFromValid,
  181264. i64 iFrom
  181265. ){
  181266. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  181267. int rc = SQLITE_OK;
  181268. pNode->bNomatch = 0;
  181269. if( pTerm->pSynonym ){
  181270. int bEof = 1;
  181271. Fts5ExprTerm *p;
  181272. /* Find the firstest rowid any synonym points to. */
  181273. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  181274. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  181275. ** is valid - each iterator that points to a rowid before iFrom. */
  181276. for(p=pTerm; p; p=p->pSynonym){
  181277. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  181278. i64 ii = p->pIter->iRowid;
  181279. if( ii==iRowid
  181280. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  181281. ){
  181282. if( bFromValid ){
  181283. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  181284. }else{
  181285. rc = sqlite3Fts5IterNext(p->pIter);
  181286. }
  181287. if( rc!=SQLITE_OK ) break;
  181288. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  181289. bEof = 0;
  181290. }
  181291. }else{
  181292. bEof = 0;
  181293. }
  181294. }
  181295. }
  181296. /* Set the EOF flag if either all synonym iterators are at EOF or an
  181297. ** error has occurred. */
  181298. pNode->bEof = (rc || bEof);
  181299. }else{
  181300. Fts5IndexIter *pIter = pTerm->pIter;
  181301. assert( Fts5NodeIsString(pNode) );
  181302. if( bFromValid ){
  181303. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  181304. }else{
  181305. rc = sqlite3Fts5IterNext(pIter);
  181306. }
  181307. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  181308. }
  181309. if( pNode->bEof==0 ){
  181310. assert( rc==SQLITE_OK );
  181311. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  181312. }
  181313. return rc;
  181314. }
  181315. static int fts5ExprNodeTest_TERM(
  181316. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  181317. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  181318. ){
  181319. /* As this "NEAR" object is actually a single phrase that consists
  181320. ** of a single term only, grab pointers into the poslist managed by the
  181321. ** fts5_index.c iterator object. This is much faster than synthesizing
  181322. ** a new poslist the way we have to for more complicated phrase or NEAR
  181323. ** expressions. */
  181324. Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
  181325. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  181326. assert( pNode->eType==FTS5_TERM );
  181327. assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
  181328. assert( pPhrase->aTerm[0].pSynonym==0 );
  181329. pPhrase->poslist.n = pIter->nData;
  181330. if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
  181331. pPhrase->poslist.p = (u8*)pIter->pData;
  181332. }
  181333. pNode->iRowid = pIter->iRowid;
  181334. pNode->bNomatch = (pPhrase->poslist.n==0);
  181335. return SQLITE_OK;
  181336. }
  181337. /*
  181338. ** xNext() method for a node of type FTS5_TERM.
  181339. */
  181340. static int fts5ExprNodeNext_TERM(
  181341. Fts5Expr *pExpr,
  181342. Fts5ExprNode *pNode,
  181343. int bFromValid,
  181344. i64 iFrom
  181345. ){
  181346. int rc;
  181347. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  181348. assert( pNode->bEof==0 );
  181349. if( bFromValid ){
  181350. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  181351. }else{
  181352. rc = sqlite3Fts5IterNext(pIter);
  181353. }
  181354. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  181355. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  181356. }else{
  181357. pNode->bEof = 1;
  181358. pNode->bNomatch = 0;
  181359. }
  181360. return rc;
  181361. }
  181362. static void fts5ExprNodeTest_OR(
  181363. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  181364. Fts5ExprNode *pNode /* Expression node to test */
  181365. ){
  181366. Fts5ExprNode *pNext = pNode->apChild[0];
  181367. int i;
  181368. for(i=1; i<pNode->nChild; i++){
  181369. Fts5ExprNode *pChild = pNode->apChild[i];
  181370. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  181371. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  181372. pNext = pChild;
  181373. }
  181374. }
  181375. pNode->iRowid = pNext->iRowid;
  181376. pNode->bEof = pNext->bEof;
  181377. pNode->bNomatch = pNext->bNomatch;
  181378. }
  181379. static int fts5ExprNodeNext_OR(
  181380. Fts5Expr *pExpr,
  181381. Fts5ExprNode *pNode,
  181382. int bFromValid,
  181383. i64 iFrom
  181384. ){
  181385. int i;
  181386. i64 iLast = pNode->iRowid;
  181387. for(i=0; i<pNode->nChild; i++){
  181388. Fts5ExprNode *p1 = pNode->apChild[i];
  181389. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  181390. if( p1->bEof==0 ){
  181391. if( (p1->iRowid==iLast)
  181392. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  181393. ){
  181394. int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  181395. if( rc!=SQLITE_OK ){
  181396. pNode->bNomatch = 0;
  181397. return rc;
  181398. }
  181399. }
  181400. }
  181401. }
  181402. fts5ExprNodeTest_OR(pExpr, pNode);
  181403. return SQLITE_OK;
  181404. }
  181405. /*
  181406. ** Argument pNode is an FTS5_AND node.
  181407. */
  181408. static int fts5ExprNodeTest_AND(
  181409. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  181410. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  181411. ){
  181412. int iChild;
  181413. i64 iLast = pAnd->iRowid;
  181414. int rc = SQLITE_OK;
  181415. int bMatch;
  181416. assert( pAnd->bEof==0 );
  181417. do {
  181418. pAnd->bNomatch = 0;
  181419. bMatch = 1;
  181420. for(iChild=0; iChild<pAnd->nChild; iChild++){
  181421. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  181422. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  181423. if( cmp>0 ){
  181424. /* Advance pChild until it points to iLast or laster */
  181425. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  181426. if( rc!=SQLITE_OK ){
  181427. pAnd->bNomatch = 0;
  181428. return rc;
  181429. }
  181430. }
  181431. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  181432. ** the child node is guaranteed to have advanced at least as far as
  181433. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  181434. ** new lastest rowid seen so far. */
  181435. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  181436. if( pChild->bEof ){
  181437. fts5ExprSetEof(pAnd);
  181438. bMatch = 1;
  181439. break;
  181440. }else if( iLast!=pChild->iRowid ){
  181441. bMatch = 0;
  181442. iLast = pChild->iRowid;
  181443. }
  181444. if( pChild->bNomatch ){
  181445. pAnd->bNomatch = 1;
  181446. }
  181447. }
  181448. }while( bMatch==0 );
  181449. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  181450. fts5ExprNodeZeroPoslist(pAnd);
  181451. }
  181452. pAnd->iRowid = iLast;
  181453. return SQLITE_OK;
  181454. }
  181455. static int fts5ExprNodeNext_AND(
  181456. Fts5Expr *pExpr,
  181457. Fts5ExprNode *pNode,
  181458. int bFromValid,
  181459. i64 iFrom
  181460. ){
  181461. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  181462. if( rc==SQLITE_OK ){
  181463. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  181464. }else{
  181465. pNode->bNomatch = 0;
  181466. }
  181467. return rc;
  181468. }
  181469. static int fts5ExprNodeTest_NOT(
  181470. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  181471. Fts5ExprNode *pNode /* FTS5_NOT node to advance */
  181472. ){
  181473. int rc = SQLITE_OK;
  181474. Fts5ExprNode *p1 = pNode->apChild[0];
  181475. Fts5ExprNode *p2 = pNode->apChild[1];
  181476. assert( pNode->nChild==2 );
  181477. while( rc==SQLITE_OK && p1->bEof==0 ){
  181478. int cmp = fts5NodeCompare(pExpr, p1, p2);
  181479. if( cmp>0 ){
  181480. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  181481. cmp = fts5NodeCompare(pExpr, p1, p2);
  181482. }
  181483. assert( rc!=SQLITE_OK || cmp<=0 );
  181484. if( cmp || p2->bNomatch ) break;
  181485. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  181486. }
  181487. pNode->bEof = p1->bEof;
  181488. pNode->bNomatch = p1->bNomatch;
  181489. pNode->iRowid = p1->iRowid;
  181490. if( p1->bEof ){
  181491. fts5ExprNodeZeroPoslist(p2);
  181492. }
  181493. return rc;
  181494. }
  181495. static int fts5ExprNodeNext_NOT(
  181496. Fts5Expr *pExpr,
  181497. Fts5ExprNode *pNode,
  181498. int bFromValid,
  181499. i64 iFrom
  181500. ){
  181501. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  181502. if( rc==SQLITE_OK ){
  181503. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  181504. }
  181505. if( rc!=SQLITE_OK ){
  181506. pNode->bNomatch = 0;
  181507. }
  181508. return rc;
  181509. }
  181510. /*
  181511. ** If pNode currently points to a match, this function returns SQLITE_OK
  181512. ** without modifying it. Otherwise, pNode is advanced until it does point
  181513. ** to a match or EOF is reached.
  181514. */
  181515. static int fts5ExprNodeTest(
  181516. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  181517. Fts5ExprNode *pNode /* Expression node to test */
  181518. ){
  181519. int rc = SQLITE_OK;
  181520. if( pNode->bEof==0 ){
  181521. switch( pNode->eType ){
  181522. case FTS5_STRING: {
  181523. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  181524. break;
  181525. }
  181526. case FTS5_TERM: {
  181527. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  181528. break;
  181529. }
  181530. case FTS5_AND: {
  181531. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  181532. break;
  181533. }
  181534. case FTS5_OR: {
  181535. fts5ExprNodeTest_OR(pExpr, pNode);
  181536. break;
  181537. }
  181538. default: assert( pNode->eType==FTS5_NOT ); {
  181539. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  181540. break;
  181541. }
  181542. }
  181543. }
  181544. return rc;
  181545. }
  181546. /*
  181547. ** Set node pNode, which is part of expression pExpr, to point to the first
  181548. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  181549. **
  181550. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  181551. ** It is not an error if there are no matches.
  181552. */
  181553. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  181554. int rc = SQLITE_OK;
  181555. pNode->bEof = 0;
  181556. pNode->bNomatch = 0;
  181557. if( Fts5NodeIsString(pNode) ){
  181558. /* Initialize all term iterators in the NEAR object. */
  181559. rc = fts5ExprNearInitAll(pExpr, pNode);
  181560. }else if( pNode->xNext==0 ){
  181561. pNode->bEof = 1;
  181562. }else{
  181563. int i;
  181564. int nEof = 0;
  181565. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  181566. Fts5ExprNode *pChild = pNode->apChild[i];
  181567. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  181568. assert( pChild->bEof==0 || pChild->bEof==1 );
  181569. nEof += pChild->bEof;
  181570. }
  181571. pNode->iRowid = pNode->apChild[0]->iRowid;
  181572. switch( pNode->eType ){
  181573. case FTS5_AND:
  181574. if( nEof>0 ) fts5ExprSetEof(pNode);
  181575. break;
  181576. case FTS5_OR:
  181577. if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
  181578. break;
  181579. default:
  181580. assert( pNode->eType==FTS5_NOT );
  181581. pNode->bEof = pNode->apChild[0]->bEof;
  181582. break;
  181583. }
  181584. }
  181585. if( rc==SQLITE_OK ){
  181586. rc = fts5ExprNodeTest(pExpr, pNode);
  181587. }
  181588. return rc;
  181589. }
  181590. /*
  181591. ** Begin iterating through the set of documents in index pIdx matched by
  181592. ** the MATCH expression passed as the first argument. If the "bDesc"
  181593. ** parameter is passed a non-zero value, iteration is in descending rowid
  181594. ** order. Or, if it is zero, in ascending order.
  181595. **
  181596. ** If iterating in ascending rowid order (bDesc==0), the first document
  181597. ** visited is that with the smallest rowid that is larger than or equal
  181598. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  181599. ** then the first document visited must have a rowid smaller than or
  181600. ** equal to iFirst.
  181601. **
  181602. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  181603. ** is not considered an error if the query does not match any documents.
  181604. */
  181605. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  181606. Fts5ExprNode *pRoot = p->pRoot;
  181607. int rc; /* Return code */
  181608. p->pIndex = pIdx;
  181609. p->bDesc = bDesc;
  181610. rc = fts5ExprNodeFirst(p, pRoot);
  181611. /* If not at EOF but the current rowid occurs earlier than iFirst in
  181612. ** the iteration order, move to document iFirst or later. */
  181613. if( rc==SQLITE_OK
  181614. && 0==pRoot->bEof
  181615. && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
  181616. ){
  181617. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  181618. }
  181619. /* If the iterator is not at a real match, skip forward until it is. */
  181620. while( pRoot->bNomatch ){
  181621. assert( pRoot->bEof==0 && rc==SQLITE_OK );
  181622. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  181623. }
  181624. return rc;
  181625. }
  181626. /*
  181627. ** Move to the next document
  181628. **
  181629. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  181630. ** is not considered an error if the query does not match any documents.
  181631. */
  181632. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  181633. int rc;
  181634. Fts5ExprNode *pRoot = p->pRoot;
  181635. assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
  181636. do {
  181637. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  181638. assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
  181639. }while( pRoot->bNomatch );
  181640. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  181641. pRoot->bEof = 1;
  181642. }
  181643. return rc;
  181644. }
  181645. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  181646. return p->pRoot->bEof;
  181647. }
  181648. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  181649. return p->pRoot->iRowid;
  181650. }
  181651. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  181652. int rc = SQLITE_OK;
  181653. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  181654. return rc;
  181655. }
  181656. /*
  181657. ** Free the phrase object passed as the only argument.
  181658. */
  181659. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  181660. if( pPhrase ){
  181661. int i;
  181662. for(i=0; i<pPhrase->nTerm; i++){
  181663. Fts5ExprTerm *pSyn;
  181664. Fts5ExprTerm *pNext;
  181665. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  181666. sqlite3_free(pTerm->zTerm);
  181667. sqlite3Fts5IterClose(pTerm->pIter);
  181668. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  181669. pNext = pSyn->pSynonym;
  181670. sqlite3Fts5IterClose(pSyn->pIter);
  181671. fts5BufferFree((Fts5Buffer*)&pSyn[1]);
  181672. sqlite3_free(pSyn);
  181673. }
  181674. }
  181675. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  181676. sqlite3_free(pPhrase);
  181677. }
  181678. }
  181679. /*
  181680. ** Set the "bFirst" flag on the first token of the phrase passed as the
  181681. ** only argument.
  181682. */
  181683. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
  181684. if( pPhrase && pPhrase->nTerm ){
  181685. pPhrase->aTerm[0].bFirst = 1;
  181686. }
  181687. }
  181688. /*
  181689. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  181690. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  181691. ** appended to it and the results returned.
  181692. **
  181693. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  181694. ** NULL returned.
  181695. */
  181696. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  181697. Fts5Parse *pParse, /* Parse context */
  181698. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  181699. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  181700. ){
  181701. const int SZALLOC = 8;
  181702. Fts5ExprNearset *pRet = 0;
  181703. if( pParse->rc==SQLITE_OK ){
  181704. if( pPhrase==0 ){
  181705. return pNear;
  181706. }
  181707. if( pNear==0 ){
  181708. int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  181709. pRet = sqlite3_malloc(nByte);
  181710. if( pRet==0 ){
  181711. pParse->rc = SQLITE_NOMEM;
  181712. }else{
  181713. memset(pRet, 0, nByte);
  181714. }
  181715. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  181716. int nNew = pNear->nPhrase + SZALLOC;
  181717. int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  181718. pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
  181719. if( pRet==0 ){
  181720. pParse->rc = SQLITE_NOMEM;
  181721. }
  181722. }else{
  181723. pRet = pNear;
  181724. }
  181725. }
  181726. if( pRet==0 ){
  181727. assert( pParse->rc!=SQLITE_OK );
  181728. sqlite3Fts5ParseNearsetFree(pNear);
  181729. sqlite3Fts5ParsePhraseFree(pPhrase);
  181730. }else{
  181731. if( pRet->nPhrase>0 ){
  181732. Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
  181733. assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
  181734. if( pPhrase->nTerm==0 ){
  181735. fts5ExprPhraseFree(pPhrase);
  181736. pRet->nPhrase--;
  181737. pParse->nPhrase--;
  181738. pPhrase = pLast;
  181739. }else if( pLast->nTerm==0 ){
  181740. fts5ExprPhraseFree(pLast);
  181741. pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
  181742. pParse->nPhrase--;
  181743. pRet->nPhrase--;
  181744. }
  181745. }
  181746. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  181747. }
  181748. return pRet;
  181749. }
  181750. typedef struct TokenCtx TokenCtx;
  181751. struct TokenCtx {
  181752. Fts5ExprPhrase *pPhrase;
  181753. int rc;
  181754. };
  181755. /*
  181756. ** Callback for tokenizing terms used by ParseTerm().
  181757. */
  181758. static int fts5ParseTokenize(
  181759. void *pContext, /* Pointer to Fts5InsertCtx object */
  181760. int tflags, /* Mask of FTS5_TOKEN_* flags */
  181761. const char *pToken, /* Buffer containing token */
  181762. int nToken, /* Size of token in bytes */
  181763. int iUnused1, /* Start offset of token */
  181764. int iUnused2 /* End offset of token */
  181765. ){
  181766. int rc = SQLITE_OK;
  181767. const int SZALLOC = 8;
  181768. TokenCtx *pCtx = (TokenCtx*)pContext;
  181769. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  181770. UNUSED_PARAM2(iUnused1, iUnused2);
  181771. /* If an error has already occurred, this is a no-op */
  181772. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  181773. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  181774. if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
  181775. Fts5ExprTerm *pSyn;
  181776. int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
  181777. pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
  181778. if( pSyn==0 ){
  181779. rc = SQLITE_NOMEM;
  181780. }else{
  181781. memset(pSyn, 0, nByte);
  181782. pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
  181783. memcpy(pSyn->zTerm, pToken, nToken);
  181784. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  181785. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  181786. }
  181787. }else{
  181788. Fts5ExprTerm *pTerm;
  181789. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  181790. Fts5ExprPhrase *pNew;
  181791. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  181792. pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
  181793. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  181794. );
  181795. if( pNew==0 ){
  181796. rc = SQLITE_NOMEM;
  181797. }else{
  181798. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  181799. pCtx->pPhrase = pPhrase = pNew;
  181800. pNew->nTerm = nNew - SZALLOC;
  181801. }
  181802. }
  181803. if( rc==SQLITE_OK ){
  181804. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  181805. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  181806. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  181807. }
  181808. }
  181809. pCtx->rc = rc;
  181810. return rc;
  181811. }
  181812. /*
  181813. ** Free the phrase object passed as the only argument.
  181814. */
  181815. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  181816. fts5ExprPhraseFree(pPhrase);
  181817. }
  181818. /*
  181819. ** Free the phrase object passed as the second argument.
  181820. */
  181821. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  181822. if( pNear ){
  181823. int i;
  181824. for(i=0; i<pNear->nPhrase; i++){
  181825. fts5ExprPhraseFree(pNear->apPhrase[i]);
  181826. }
  181827. sqlite3_free(pNear->pColset);
  181828. sqlite3_free(pNear);
  181829. }
  181830. }
  181831. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  181832. assert( pParse->pExpr==0 );
  181833. pParse->pExpr = p;
  181834. }
  181835. /*
  181836. ** This function is called by the parser to process a string token. The
  181837. ** string may or may not be quoted. In any case it is tokenized and a
  181838. ** phrase object consisting of all tokens returned.
  181839. */
  181840. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  181841. Fts5Parse *pParse, /* Parse context */
  181842. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  181843. Fts5Token *pToken, /* String to tokenize */
  181844. int bPrefix /* True if there is a trailing "*" */
  181845. ){
  181846. Fts5Config *pConfig = pParse->pConfig;
  181847. TokenCtx sCtx; /* Context object passed to callback */
  181848. int rc; /* Tokenize return code */
  181849. char *z = 0;
  181850. memset(&sCtx, 0, sizeof(TokenCtx));
  181851. sCtx.pPhrase = pAppend;
  181852. rc = fts5ParseStringFromToken(pToken, &z);
  181853. if( rc==SQLITE_OK ){
  181854. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
  181855. int n;
  181856. sqlite3Fts5Dequote(z);
  181857. n = (int)strlen(z);
  181858. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  181859. }
  181860. sqlite3_free(z);
  181861. if( rc || (rc = sCtx.rc) ){
  181862. pParse->rc = rc;
  181863. fts5ExprPhraseFree(sCtx.pPhrase);
  181864. sCtx.pPhrase = 0;
  181865. }else{
  181866. if( pAppend==0 ){
  181867. if( (pParse->nPhrase % 8)==0 ){
  181868. int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  181869. Fts5ExprPhrase **apNew;
  181870. apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
  181871. if( apNew==0 ){
  181872. pParse->rc = SQLITE_NOMEM;
  181873. fts5ExprPhraseFree(sCtx.pPhrase);
  181874. return 0;
  181875. }
  181876. pParse->apPhrase = apNew;
  181877. }
  181878. pParse->nPhrase++;
  181879. }
  181880. if( sCtx.pPhrase==0 ){
  181881. /* This happens when parsing a token or quoted phrase that contains
  181882. ** no token characters at all. (e.g ... MATCH '""'). */
  181883. sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
  181884. }else if( sCtx.pPhrase->nTerm ){
  181885. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;
  181886. }
  181887. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  181888. }
  181889. return sCtx.pPhrase;
  181890. }
  181891. /*
  181892. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  181893. ** expression passed as the second argument.
  181894. */
  181895. static int sqlite3Fts5ExprClonePhrase(
  181896. Fts5Expr *pExpr,
  181897. int iPhrase,
  181898. Fts5Expr **ppNew
  181899. ){
  181900. int rc = SQLITE_OK; /* Return code */
  181901. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  181902. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  181903. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  181904. pOrig = pExpr->apExprPhrase[iPhrase];
  181905. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  181906. if( rc==SQLITE_OK ){
  181907. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  181908. sizeof(Fts5ExprPhrase*));
  181909. }
  181910. if( rc==SQLITE_OK ){
  181911. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  181912. sizeof(Fts5ExprNode));
  181913. }
  181914. if( rc==SQLITE_OK ){
  181915. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  181916. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  181917. }
  181918. if( rc==SQLITE_OK ){
  181919. Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
  181920. if( pColsetOrig ){
  181921. int nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
  181922. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
  181923. if( pColset ){
  181924. memcpy(pColset, pColsetOrig, nByte);
  181925. }
  181926. pNew->pRoot->pNear->pColset = pColset;
  181927. }
  181928. }
  181929. if( pOrig->nTerm ){
  181930. int i; /* Used to iterate through phrase terms */
  181931. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  181932. int tflags = 0;
  181933. Fts5ExprTerm *p;
  181934. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  181935. const char *zTerm = p->zTerm;
  181936. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  181937. 0, 0);
  181938. tflags = FTS5_TOKEN_COLOCATED;
  181939. }
  181940. if( rc==SQLITE_OK ){
  181941. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  181942. sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
  181943. }
  181944. }
  181945. }else{
  181946. /* This happens when parsing a token or quoted phrase that contains
  181947. ** no token characters at all. (e.g ... MATCH '""'). */
  181948. sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
  181949. }
  181950. if( rc==SQLITE_OK ){
  181951. /* All the allocations succeeded. Put the expression object together. */
  181952. pNew->pIndex = pExpr->pIndex;
  181953. pNew->pConfig = pExpr->pConfig;
  181954. pNew->nPhrase = 1;
  181955. pNew->apExprPhrase[0] = sCtx.pPhrase;
  181956. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  181957. pNew->pRoot->pNear->nPhrase = 1;
  181958. sCtx.pPhrase->pNode = pNew->pRoot;
  181959. if( pOrig->nTerm==1
  181960. && pOrig->aTerm[0].pSynonym==0
  181961. && pOrig->aTerm[0].bFirst==0
  181962. ){
  181963. pNew->pRoot->eType = FTS5_TERM;
  181964. pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
  181965. }else{
  181966. pNew->pRoot->eType = FTS5_STRING;
  181967. pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
  181968. }
  181969. }else{
  181970. sqlite3Fts5ExprFree(pNew);
  181971. fts5ExprPhraseFree(sCtx.pPhrase);
  181972. pNew = 0;
  181973. }
  181974. *ppNew = pNew;
  181975. return rc;
  181976. }
  181977. /*
  181978. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  181979. ** is expected. If token pTok does not contain "NEAR", store an error
  181980. ** in the pParse object.
  181981. */
  181982. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  181983. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  181984. sqlite3Fts5ParseError(
  181985. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  181986. );
  181987. }
  181988. }
  181989. static void sqlite3Fts5ParseSetDistance(
  181990. Fts5Parse *pParse,
  181991. Fts5ExprNearset *pNear,
  181992. Fts5Token *p
  181993. ){
  181994. if( pNear ){
  181995. int nNear = 0;
  181996. int i;
  181997. if( p->n ){
  181998. for(i=0; i<p->n; i++){
  181999. char c = (char)p->p[i];
  182000. if( c<'0' || c>'9' ){
  182001. sqlite3Fts5ParseError(
  182002. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  182003. );
  182004. return;
  182005. }
  182006. nNear = nNear * 10 + (p->p[i] - '0');
  182007. }
  182008. }else{
  182009. nNear = FTS5_DEFAULT_NEARDIST;
  182010. }
  182011. pNear->nNear = nNear;
  182012. }
  182013. }
  182014. /*
  182015. ** The second argument passed to this function may be NULL, or it may be
  182016. ** an existing Fts5Colset object. This function returns a pointer to
  182017. ** a new colset object containing the contents of (p) with new value column
  182018. ** number iCol appended.
  182019. **
  182020. ** If an OOM error occurs, store an error code in pParse and return NULL.
  182021. ** The old colset object (if any) is not freed in this case.
  182022. */
  182023. static Fts5Colset *fts5ParseColset(
  182024. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  182025. Fts5Colset *p, /* Existing colset object */
  182026. int iCol /* New column to add to colset object */
  182027. ){
  182028. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  182029. Fts5Colset *pNew; /* New colset object to return */
  182030. assert( pParse->rc==SQLITE_OK );
  182031. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  182032. pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  182033. if( pNew==0 ){
  182034. pParse->rc = SQLITE_NOMEM;
  182035. }else{
  182036. int *aiCol = pNew->aiCol;
  182037. int i, j;
  182038. for(i=0; i<nCol; i++){
  182039. if( aiCol[i]==iCol ) return pNew;
  182040. if( aiCol[i]>iCol ) break;
  182041. }
  182042. for(j=nCol; j>i; j--){
  182043. aiCol[j] = aiCol[j-1];
  182044. }
  182045. aiCol[i] = iCol;
  182046. pNew->nCol = nCol+1;
  182047. #ifndef NDEBUG
  182048. /* Check that the array is in order and contains no duplicate entries. */
  182049. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  182050. #endif
  182051. }
  182052. return pNew;
  182053. }
  182054. /*
  182055. ** Allocate and return an Fts5Colset object specifying the inverse of
  182056. ** the colset passed as the second argument. Free the colset passed
  182057. ** as the second argument before returning.
  182058. */
  182059. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
  182060. Fts5Colset *pRet;
  182061. int nCol = pParse->pConfig->nCol;
  182062. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
  182063. sizeof(Fts5Colset) + sizeof(int)*nCol
  182064. );
  182065. if( pRet ){
  182066. int i;
  182067. int iOld = 0;
  182068. for(i=0; i<nCol; i++){
  182069. if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
  182070. pRet->aiCol[pRet->nCol++] = i;
  182071. }else{
  182072. iOld++;
  182073. }
  182074. }
  182075. }
  182076. sqlite3_free(p);
  182077. return pRet;
  182078. }
  182079. static Fts5Colset *sqlite3Fts5ParseColset(
  182080. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  182081. Fts5Colset *pColset, /* Existing colset object */
  182082. Fts5Token *p
  182083. ){
  182084. Fts5Colset *pRet = 0;
  182085. int iCol;
  182086. char *z; /* Dequoted copy of token p */
  182087. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  182088. if( pParse->rc==SQLITE_OK ){
  182089. Fts5Config *pConfig = pParse->pConfig;
  182090. sqlite3Fts5Dequote(z);
  182091. for(iCol=0; iCol<pConfig->nCol; iCol++){
  182092. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  182093. }
  182094. if( iCol==pConfig->nCol ){
  182095. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  182096. }else{
  182097. pRet = fts5ParseColset(pParse, pColset, iCol);
  182098. }
  182099. sqlite3_free(z);
  182100. }
  182101. if( pRet==0 ){
  182102. assert( pParse->rc!=SQLITE_OK );
  182103. sqlite3_free(pColset);
  182104. }
  182105. return pRet;
  182106. }
  182107. /*
  182108. ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
  182109. ** SQLITE_OK when this function is called, NULL is returned.
  182110. **
  182111. ** Otherwise, a copy of (*pOrig) is made into memory obtained from
  182112. ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
  182113. ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
  182114. */
  182115. static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
  182116. Fts5Colset *pRet;
  182117. if( pOrig ){
  182118. int nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
  182119. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
  182120. if( pRet ){
  182121. memcpy(pRet, pOrig, nByte);
  182122. }
  182123. }else{
  182124. pRet = 0;
  182125. }
  182126. return pRet;
  182127. }
  182128. /*
  182129. ** Remove from colset pColset any columns that are not also in colset pMerge.
  182130. */
  182131. static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
  182132. int iIn = 0; /* Next input in pColset */
  182133. int iMerge = 0; /* Next input in pMerge */
  182134. int iOut = 0; /* Next output slot in pColset */
  182135. while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
  182136. int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
  182137. if( iDiff==0 ){
  182138. pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
  182139. iMerge++;
  182140. iIn++;
  182141. }else if( iDiff>0 ){
  182142. iMerge++;
  182143. }else{
  182144. iIn++;
  182145. }
  182146. }
  182147. pColset->nCol = iOut;
  182148. }
  182149. /*
  182150. ** Recursively apply colset pColset to expression node pNode and all of
  182151. ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
  182152. ** of pColset. This function may use the spare copy and set (*ppFree) to
  182153. ** zero, or it may create copies of pColset using fts5CloneColset().
  182154. */
  182155. static void fts5ParseSetColset(
  182156. Fts5Parse *pParse,
  182157. Fts5ExprNode *pNode,
  182158. Fts5Colset *pColset,
  182159. Fts5Colset **ppFree
  182160. ){
  182161. if( pParse->rc==SQLITE_OK ){
  182162. assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
  182163. || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
  182164. || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
  182165. );
  182166. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  182167. Fts5ExprNearset *pNear = pNode->pNear;
  182168. if( pNear->pColset ){
  182169. fts5MergeColset(pNear->pColset, pColset);
  182170. if( pNear->pColset->nCol==0 ){
  182171. pNode->eType = FTS5_EOF;
  182172. pNode->xNext = 0;
  182173. }
  182174. }else if( *ppFree ){
  182175. pNear->pColset = pColset;
  182176. *ppFree = 0;
  182177. }else{
  182178. pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
  182179. }
  182180. }else{
  182181. int i;
  182182. assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
  182183. for(i=0; i<pNode->nChild; i++){
  182184. fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
  182185. }
  182186. }
  182187. }
  182188. }
  182189. /*
  182190. ** Apply colset pColset to expression node pExpr and all of its descendents.
  182191. */
  182192. static void sqlite3Fts5ParseSetColset(
  182193. Fts5Parse *pParse,
  182194. Fts5ExprNode *pExpr,
  182195. Fts5Colset *pColset
  182196. ){
  182197. Fts5Colset *pFree = pColset;
  182198. if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
  182199. pParse->rc = SQLITE_ERROR;
  182200. pParse->zErr = sqlite3_mprintf(
  182201. "fts5: column queries are not supported (detail=none)"
  182202. );
  182203. }else{
  182204. fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
  182205. }
  182206. sqlite3_free(pFree);
  182207. }
  182208. static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
  182209. switch( pNode->eType ){
  182210. case FTS5_STRING: {
  182211. Fts5ExprNearset *pNear = pNode->pNear;
  182212. if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
  182213. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  182214. && pNear->apPhrase[0]->aTerm[0].bFirst==0
  182215. ){
  182216. pNode->eType = FTS5_TERM;
  182217. pNode->xNext = fts5ExprNodeNext_TERM;
  182218. }else{
  182219. pNode->xNext = fts5ExprNodeNext_STRING;
  182220. }
  182221. break;
  182222. };
  182223. case FTS5_OR: {
  182224. pNode->xNext = fts5ExprNodeNext_OR;
  182225. break;
  182226. };
  182227. case FTS5_AND: {
  182228. pNode->xNext = fts5ExprNodeNext_AND;
  182229. break;
  182230. };
  182231. default: assert( pNode->eType==FTS5_NOT ); {
  182232. pNode->xNext = fts5ExprNodeNext_NOT;
  182233. break;
  182234. };
  182235. }
  182236. }
  182237. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  182238. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  182239. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  182240. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  182241. p->nChild += pSub->nChild;
  182242. sqlite3_free(pSub);
  182243. }else{
  182244. p->apChild[p->nChild++] = pSub;
  182245. }
  182246. }
  182247. /*
  182248. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  182249. ** OOM error), leave an error code in pParse and return NULL.
  182250. */
  182251. static Fts5ExprNode *sqlite3Fts5ParseNode(
  182252. Fts5Parse *pParse, /* Parse context */
  182253. int eType, /* FTS5_STRING, AND, OR or NOT */
  182254. Fts5ExprNode *pLeft, /* Left hand child expression */
  182255. Fts5ExprNode *pRight, /* Right hand child expression */
  182256. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  182257. ){
  182258. Fts5ExprNode *pRet = 0;
  182259. if( pParse->rc==SQLITE_OK ){
  182260. int nChild = 0; /* Number of children of returned node */
  182261. int nByte; /* Bytes of space to allocate for this node */
  182262. assert( (eType!=FTS5_STRING && !pNear)
  182263. || (eType==FTS5_STRING && !pLeft && !pRight)
  182264. );
  182265. if( eType==FTS5_STRING && pNear==0 ) return 0;
  182266. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  182267. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  182268. if( eType==FTS5_NOT ){
  182269. nChild = 2;
  182270. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  182271. nChild = 2;
  182272. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  182273. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  182274. }
  182275. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  182276. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  182277. if( pRet ){
  182278. pRet->eType = eType;
  182279. pRet->pNear = pNear;
  182280. fts5ExprAssignXNext(pRet);
  182281. if( eType==FTS5_STRING ){
  182282. int iPhrase;
  182283. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  182284. pNear->apPhrase[iPhrase]->pNode = pRet;
  182285. if( pNear->apPhrase[iPhrase]->nTerm==0 ){
  182286. pRet->xNext = 0;
  182287. pRet->eType = FTS5_EOF;
  182288. }
  182289. }
  182290. if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  182291. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  182292. if( pNear->nPhrase!=1
  182293. || pPhrase->nTerm>1
  182294. || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
  182295. ){
  182296. assert( pParse->rc==SQLITE_OK );
  182297. pParse->rc = SQLITE_ERROR;
  182298. assert( pParse->zErr==0 );
  182299. pParse->zErr = sqlite3_mprintf(
  182300. "fts5: %s queries are not supported (detail!=full)",
  182301. pNear->nPhrase==1 ? "phrase": "NEAR"
  182302. );
  182303. sqlite3_free(pRet);
  182304. pRet = 0;
  182305. }
  182306. }
  182307. }else{
  182308. fts5ExprAddChildren(pRet, pLeft);
  182309. fts5ExprAddChildren(pRet, pRight);
  182310. }
  182311. }
  182312. }
  182313. if( pRet==0 ){
  182314. assert( pParse->rc!=SQLITE_OK );
  182315. sqlite3Fts5ParseNodeFree(pLeft);
  182316. sqlite3Fts5ParseNodeFree(pRight);
  182317. sqlite3Fts5ParseNearsetFree(pNear);
  182318. }
  182319. return pRet;
  182320. }
  182321. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  182322. Fts5Parse *pParse, /* Parse context */
  182323. Fts5ExprNode *pLeft, /* Left hand child expression */
  182324. Fts5ExprNode *pRight /* Right hand child expression */
  182325. ){
  182326. Fts5ExprNode *pRet = 0;
  182327. Fts5ExprNode *pPrev;
  182328. if( pParse->rc ){
  182329. sqlite3Fts5ParseNodeFree(pLeft);
  182330. sqlite3Fts5ParseNodeFree(pRight);
  182331. }else{
  182332. assert( pLeft->eType==FTS5_STRING
  182333. || pLeft->eType==FTS5_TERM
  182334. || pLeft->eType==FTS5_EOF
  182335. || pLeft->eType==FTS5_AND
  182336. );
  182337. assert( pRight->eType==FTS5_STRING
  182338. || pRight->eType==FTS5_TERM
  182339. || pRight->eType==FTS5_EOF
  182340. );
  182341. if( pLeft->eType==FTS5_AND ){
  182342. pPrev = pLeft->apChild[pLeft->nChild-1];
  182343. }else{
  182344. pPrev = pLeft;
  182345. }
  182346. assert( pPrev->eType==FTS5_STRING
  182347. || pPrev->eType==FTS5_TERM
  182348. || pPrev->eType==FTS5_EOF
  182349. );
  182350. if( pRight->eType==FTS5_EOF ){
  182351. assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
  182352. sqlite3Fts5ParseNodeFree(pRight);
  182353. pRet = pLeft;
  182354. pParse->nPhrase--;
  182355. }
  182356. else if( pPrev->eType==FTS5_EOF ){
  182357. Fts5ExprPhrase **ap;
  182358. if( pPrev==pLeft ){
  182359. pRet = pRight;
  182360. }else{
  182361. pLeft->apChild[pLeft->nChild-1] = pRight;
  182362. pRet = pLeft;
  182363. }
  182364. ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
  182365. assert( ap[0]==pPrev->pNear->apPhrase[0] );
  182366. memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
  182367. pParse->nPhrase--;
  182368. sqlite3Fts5ParseNodeFree(pPrev);
  182369. }
  182370. else{
  182371. pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
  182372. }
  182373. }
  182374. return pRet;
  182375. }
  182376. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  182377. int nByte = 0;
  182378. Fts5ExprTerm *p;
  182379. char *zQuoted;
  182380. /* Determine the maximum amount of space required. */
  182381. for(p=pTerm; p; p=p->pSynonym){
  182382. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  182383. }
  182384. zQuoted = sqlite3_malloc(nByte);
  182385. if( zQuoted ){
  182386. int i = 0;
  182387. for(p=pTerm; p; p=p->pSynonym){
  182388. char *zIn = p->zTerm;
  182389. zQuoted[i++] = '"';
  182390. while( *zIn ){
  182391. if( *zIn=='"' ) zQuoted[i++] = '"';
  182392. zQuoted[i++] = *zIn++;
  182393. }
  182394. zQuoted[i++] = '"';
  182395. if( p->pSynonym ) zQuoted[i++] = '|';
  182396. }
  182397. if( pTerm->bPrefix ){
  182398. zQuoted[i++] = ' ';
  182399. zQuoted[i++] = '*';
  182400. }
  182401. zQuoted[i++] = '\0';
  182402. }
  182403. return zQuoted;
  182404. }
  182405. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  182406. char *zNew;
  182407. va_list ap;
  182408. va_start(ap, zFmt);
  182409. zNew = sqlite3_vmprintf(zFmt, ap);
  182410. va_end(ap);
  182411. if( zApp && zNew ){
  182412. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  182413. sqlite3_free(zNew);
  182414. zNew = zNew2;
  182415. }
  182416. sqlite3_free(zApp);
  182417. return zNew;
  182418. }
  182419. /*
  182420. ** Compose a tcl-readable representation of expression pExpr. Return a
  182421. ** pointer to a buffer containing that representation. It is the
  182422. ** responsibility of the caller to at some point free the buffer using
  182423. ** sqlite3_free().
  182424. */
  182425. static char *fts5ExprPrintTcl(
  182426. Fts5Config *pConfig,
  182427. const char *zNearsetCmd,
  182428. Fts5ExprNode *pExpr
  182429. ){
  182430. char *zRet = 0;
  182431. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  182432. Fts5ExprNearset *pNear = pExpr->pNear;
  182433. int i;
  182434. int iTerm;
  182435. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  182436. if( zRet==0 ) return 0;
  182437. if( pNear->pColset ){
  182438. int *aiCol = pNear->pColset->aiCol;
  182439. int nCol = pNear->pColset->nCol;
  182440. if( nCol==1 ){
  182441. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  182442. }else{
  182443. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  182444. for(i=1; i<pNear->pColset->nCol; i++){
  182445. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  182446. }
  182447. zRet = fts5PrintfAppend(zRet, "} ");
  182448. }
  182449. if( zRet==0 ) return 0;
  182450. }
  182451. if( pNear->nPhrase>1 ){
  182452. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  182453. if( zRet==0 ) return 0;
  182454. }
  182455. zRet = fts5PrintfAppend(zRet, "--");
  182456. if( zRet==0 ) return 0;
  182457. for(i=0; i<pNear->nPhrase; i++){
  182458. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  182459. zRet = fts5PrintfAppend(zRet, " {");
  182460. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  182461. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  182462. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  182463. if( pPhrase->aTerm[iTerm].bPrefix ){
  182464. zRet = fts5PrintfAppend(zRet, "*");
  182465. }
  182466. }
  182467. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  182468. if( zRet==0 ) return 0;
  182469. }
  182470. }else{
  182471. char const *zOp = 0;
  182472. int i;
  182473. switch( pExpr->eType ){
  182474. case FTS5_AND: zOp = "AND"; break;
  182475. case FTS5_NOT: zOp = "NOT"; break;
  182476. default:
  182477. assert( pExpr->eType==FTS5_OR );
  182478. zOp = "OR";
  182479. break;
  182480. }
  182481. zRet = sqlite3_mprintf("%s", zOp);
  182482. for(i=0; zRet && i<pExpr->nChild; i++){
  182483. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  182484. if( !z ){
  182485. sqlite3_free(zRet);
  182486. zRet = 0;
  182487. }else{
  182488. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  182489. }
  182490. }
  182491. }
  182492. return zRet;
  182493. }
  182494. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  182495. char *zRet = 0;
  182496. if( pExpr->eType==0 ){
  182497. return sqlite3_mprintf("\"\"");
  182498. }else
  182499. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  182500. Fts5ExprNearset *pNear = pExpr->pNear;
  182501. int i;
  182502. int iTerm;
  182503. if( pNear->pColset ){
  182504. int iCol = pNear->pColset->aiCol[0];
  182505. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  182506. if( zRet==0 ) return 0;
  182507. }
  182508. if( pNear->nPhrase>1 ){
  182509. zRet = fts5PrintfAppend(zRet, "NEAR(");
  182510. if( zRet==0 ) return 0;
  182511. }
  182512. for(i=0; i<pNear->nPhrase; i++){
  182513. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  182514. if( i!=0 ){
  182515. zRet = fts5PrintfAppend(zRet, " ");
  182516. if( zRet==0 ) return 0;
  182517. }
  182518. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  182519. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  182520. if( zTerm ){
  182521. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  182522. sqlite3_free(zTerm);
  182523. }
  182524. if( zTerm==0 || zRet==0 ){
  182525. sqlite3_free(zRet);
  182526. return 0;
  182527. }
  182528. }
  182529. }
  182530. if( pNear->nPhrase>1 ){
  182531. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  182532. if( zRet==0 ) return 0;
  182533. }
  182534. }else{
  182535. char const *zOp = 0;
  182536. int i;
  182537. switch( pExpr->eType ){
  182538. case FTS5_AND: zOp = " AND "; break;
  182539. case FTS5_NOT: zOp = " NOT "; break;
  182540. default:
  182541. assert( pExpr->eType==FTS5_OR );
  182542. zOp = " OR ";
  182543. break;
  182544. }
  182545. for(i=0; i<pExpr->nChild; i++){
  182546. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  182547. if( z==0 ){
  182548. sqlite3_free(zRet);
  182549. zRet = 0;
  182550. }else{
  182551. int e = pExpr->apChild[i]->eType;
  182552. int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
  182553. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  182554. (i==0 ? "" : zOp),
  182555. (b?"(":""), z, (b?")":"")
  182556. );
  182557. }
  182558. if( zRet==0 ) break;
  182559. }
  182560. }
  182561. return zRet;
  182562. }
  182563. /*
  182564. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  182565. ** and fts5_expr_tcl() (bTcl!=0).
  182566. */
  182567. static void fts5ExprFunction(
  182568. sqlite3_context *pCtx, /* Function call context */
  182569. int nArg, /* Number of args */
  182570. sqlite3_value **apVal, /* Function arguments */
  182571. int bTcl
  182572. ){
  182573. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  182574. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  182575. const char *zExpr = 0;
  182576. char *zErr = 0;
  182577. Fts5Expr *pExpr = 0;
  182578. int rc;
  182579. int i;
  182580. const char **azConfig; /* Array of arguments for Fts5Config */
  182581. const char *zNearsetCmd = "nearset";
  182582. int nConfig; /* Size of azConfig[] */
  182583. Fts5Config *pConfig = 0;
  182584. int iArg = 1;
  182585. if( nArg<1 ){
  182586. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  182587. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  182588. );
  182589. sqlite3_result_error(pCtx, zErr, -1);
  182590. sqlite3_free(zErr);
  182591. return;
  182592. }
  182593. if( bTcl && nArg>1 ){
  182594. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  182595. iArg = 2;
  182596. }
  182597. nConfig = 3 + (nArg-iArg);
  182598. azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
  182599. if( azConfig==0 ){
  182600. sqlite3_result_error_nomem(pCtx);
  182601. return;
  182602. }
  182603. azConfig[0] = 0;
  182604. azConfig[1] = "main";
  182605. azConfig[2] = "tbl";
  182606. for(i=3; iArg<nArg; iArg++){
  182607. azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
  182608. }
  182609. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  182610. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  182611. if( rc==SQLITE_OK ){
  182612. rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
  182613. }
  182614. if( rc==SQLITE_OK ){
  182615. char *zText;
  182616. if( pExpr->pRoot->xNext==0 ){
  182617. zText = sqlite3_mprintf("");
  182618. }else if( bTcl ){
  182619. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  182620. }else{
  182621. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  182622. }
  182623. if( zText==0 ){
  182624. rc = SQLITE_NOMEM;
  182625. }else{
  182626. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  182627. sqlite3_free(zText);
  182628. }
  182629. }
  182630. if( rc!=SQLITE_OK ){
  182631. if( zErr ){
  182632. sqlite3_result_error(pCtx, zErr, -1);
  182633. sqlite3_free(zErr);
  182634. }else{
  182635. sqlite3_result_error_code(pCtx, rc);
  182636. }
  182637. }
  182638. sqlite3_free((void *)azConfig);
  182639. sqlite3Fts5ConfigFree(pConfig);
  182640. sqlite3Fts5ExprFree(pExpr);
  182641. }
  182642. static void fts5ExprFunctionHr(
  182643. sqlite3_context *pCtx, /* Function call context */
  182644. int nArg, /* Number of args */
  182645. sqlite3_value **apVal /* Function arguments */
  182646. ){
  182647. fts5ExprFunction(pCtx, nArg, apVal, 0);
  182648. }
  182649. static void fts5ExprFunctionTcl(
  182650. sqlite3_context *pCtx, /* Function call context */
  182651. int nArg, /* Number of args */
  182652. sqlite3_value **apVal /* Function arguments */
  182653. ){
  182654. fts5ExprFunction(pCtx, nArg, apVal, 1);
  182655. }
  182656. /*
  182657. ** The implementation of an SQLite user-defined-function that accepts a
  182658. ** single integer as an argument. If the integer is an alpha-numeric
  182659. ** unicode code point, 1 is returned. Otherwise 0.
  182660. */
  182661. static void fts5ExprIsAlnum(
  182662. sqlite3_context *pCtx, /* Function call context */
  182663. int nArg, /* Number of args */
  182664. sqlite3_value **apVal /* Function arguments */
  182665. ){
  182666. int iCode;
  182667. if( nArg!=1 ){
  182668. sqlite3_result_error(pCtx,
  182669. "wrong number of arguments to function fts5_isalnum", -1
  182670. );
  182671. return;
  182672. }
  182673. iCode = sqlite3_value_int(apVal[0]);
  182674. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
  182675. }
  182676. static void fts5ExprFold(
  182677. sqlite3_context *pCtx, /* Function call context */
  182678. int nArg, /* Number of args */
  182679. sqlite3_value **apVal /* Function arguments */
  182680. ){
  182681. if( nArg!=1 && nArg!=2 ){
  182682. sqlite3_result_error(pCtx,
  182683. "wrong number of arguments to function fts5_fold", -1
  182684. );
  182685. }else{
  182686. int iCode;
  182687. int bRemoveDiacritics = 0;
  182688. iCode = sqlite3_value_int(apVal[0]);
  182689. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  182690. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  182691. }
  182692. }
  182693. /*
  182694. ** This is called during initialization to register the fts5_expr() scalar
  182695. ** UDF with the SQLite handle passed as the only argument.
  182696. */
  182697. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  182698. struct Fts5ExprFunc {
  182699. const char *z;
  182700. void (*x)(sqlite3_context*,int,sqlite3_value**);
  182701. } aFunc[] = {
  182702. { "fts5_expr", fts5ExprFunctionHr },
  182703. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  182704. { "fts5_isalnum", fts5ExprIsAlnum },
  182705. { "fts5_fold", fts5ExprFold },
  182706. };
  182707. int i;
  182708. int rc = SQLITE_OK;
  182709. void *pCtx = (void*)pGlobal;
  182710. for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
  182711. struct Fts5ExprFunc *p = &aFunc[i];
  182712. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  182713. }
  182714. /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
  182715. #ifndef NDEBUG
  182716. (void)sqlite3Fts5ParserTrace;
  182717. #endif
  182718. return rc;
  182719. }
  182720. /*
  182721. ** Return the number of phrases in expression pExpr.
  182722. */
  182723. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  182724. return (pExpr ? pExpr->nPhrase : 0);
  182725. }
  182726. /*
  182727. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  182728. */
  182729. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  182730. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  182731. return pExpr->apExprPhrase[iPhrase]->nTerm;
  182732. }
  182733. /*
  182734. ** This function is used to access the current position list for phrase
  182735. ** iPhrase.
  182736. */
  182737. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  182738. int nRet;
  182739. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  182740. Fts5ExprNode *pNode = pPhrase->pNode;
  182741. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  182742. *pa = pPhrase->poslist.p;
  182743. nRet = pPhrase->poslist.n;
  182744. }else{
  182745. *pa = 0;
  182746. nRet = 0;
  182747. }
  182748. return nRet;
  182749. }
  182750. struct Fts5PoslistPopulator {
  182751. Fts5PoslistWriter writer;
  182752. int bOk; /* True if ok to populate */
  182753. int bMiss;
  182754. };
  182755. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
  182756. Fts5PoslistPopulator *pRet;
  182757. pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  182758. if( pRet ){
  182759. int i;
  182760. memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  182761. for(i=0; i<pExpr->nPhrase; i++){
  182762. Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
  182763. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  182764. assert( pExpr->apExprPhrase[i]->nTerm==1 );
  182765. if( bLive &&
  182766. (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
  182767. ){
  182768. pRet[i].bMiss = 1;
  182769. }else{
  182770. pBuf->n = 0;
  182771. }
  182772. }
  182773. }
  182774. return pRet;
  182775. }
  182776. struct Fts5ExprCtx {
  182777. Fts5Expr *pExpr;
  182778. Fts5PoslistPopulator *aPopulator;
  182779. i64 iOff;
  182780. };
  182781. typedef struct Fts5ExprCtx Fts5ExprCtx;
  182782. /*
  182783. ** TODO: Make this more efficient!
  182784. */
  182785. static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
  182786. int i;
  182787. for(i=0; i<pColset->nCol; i++){
  182788. if( pColset->aiCol[i]==iCol ) return 1;
  182789. }
  182790. return 0;
  182791. }
  182792. static int fts5ExprPopulatePoslistsCb(
  182793. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  182794. int tflags, /* Mask of FTS5_TOKEN_* flags */
  182795. const char *pToken, /* Pointer to buffer containing token */
  182796. int nToken, /* Size of token in bytes */
  182797. int iUnused1, /* Byte offset of token within input text */
  182798. int iUnused2 /* Byte offset of end of token within input text */
  182799. ){
  182800. Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
  182801. Fts5Expr *pExpr = p->pExpr;
  182802. int i;
  182803. UNUSED_PARAM2(iUnused1, iUnused2);
  182804. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  182805. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
  182806. for(i=0; i<pExpr->nPhrase; i++){
  182807. Fts5ExprTerm *pTerm;
  182808. if( p->aPopulator[i].bOk==0 ) continue;
  182809. for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  182810. int nTerm = (int)strlen(pTerm->zTerm);
  182811. if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
  182812. && memcmp(pTerm->zTerm, pToken, nTerm)==0
  182813. ){
  182814. int rc = sqlite3Fts5PoslistWriterAppend(
  182815. &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
  182816. );
  182817. if( rc ) return rc;
  182818. break;
  182819. }
  182820. }
  182821. }
  182822. return SQLITE_OK;
  182823. }
  182824. static int sqlite3Fts5ExprPopulatePoslists(
  182825. Fts5Config *pConfig,
  182826. Fts5Expr *pExpr,
  182827. Fts5PoslistPopulator *aPopulator,
  182828. int iCol,
  182829. const char *z, int n
  182830. ){
  182831. int i;
  182832. Fts5ExprCtx sCtx;
  182833. sCtx.pExpr = pExpr;
  182834. sCtx.aPopulator = aPopulator;
  182835. sCtx.iOff = (((i64)iCol) << 32) - 1;
  182836. for(i=0; i<pExpr->nPhrase; i++){
  182837. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  182838. Fts5Colset *pColset = pNode->pNear->pColset;
  182839. if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
  182840. || aPopulator[i].bMiss
  182841. ){
  182842. aPopulator[i].bOk = 0;
  182843. }else{
  182844. aPopulator[i].bOk = 1;
  182845. }
  182846. }
  182847. return sqlite3Fts5Tokenize(pConfig,
  182848. FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
  182849. );
  182850. }
  182851. static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
  182852. if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
  182853. pNode->pNear->apPhrase[0]->poslist.n = 0;
  182854. }else{
  182855. int i;
  182856. for(i=0; i<pNode->nChild; i++){
  182857. fts5ExprClearPoslists(pNode->apChild[i]);
  182858. }
  182859. }
  182860. }
  182861. static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
  182862. pNode->iRowid = iRowid;
  182863. pNode->bEof = 0;
  182864. switch( pNode->eType ){
  182865. case FTS5_TERM:
  182866. case FTS5_STRING:
  182867. return (pNode->pNear->apPhrase[0]->poslist.n>0);
  182868. case FTS5_AND: {
  182869. int i;
  182870. for(i=0; i<pNode->nChild; i++){
  182871. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
  182872. fts5ExprClearPoslists(pNode);
  182873. return 0;
  182874. }
  182875. }
  182876. break;
  182877. }
  182878. case FTS5_OR: {
  182879. int i;
  182880. int bRet = 0;
  182881. for(i=0; i<pNode->nChild; i++){
  182882. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
  182883. bRet = 1;
  182884. }
  182885. }
  182886. return bRet;
  182887. }
  182888. default: {
  182889. assert( pNode->eType==FTS5_NOT );
  182890. if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
  182891. || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
  182892. ){
  182893. fts5ExprClearPoslists(pNode);
  182894. return 0;
  182895. }
  182896. break;
  182897. }
  182898. }
  182899. return 1;
  182900. }
  182901. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
  182902. fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
  182903. }
  182904. /*
  182905. ** This function is only called for detail=columns tables.
  182906. */
  182907. static int sqlite3Fts5ExprPhraseCollist(
  182908. Fts5Expr *pExpr,
  182909. int iPhrase,
  182910. const u8 **ppCollist,
  182911. int *pnCollist
  182912. ){
  182913. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  182914. Fts5ExprNode *pNode = pPhrase->pNode;
  182915. int rc = SQLITE_OK;
  182916. assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
  182917. assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  182918. if( pNode->bEof==0
  182919. && pNode->iRowid==pExpr->pRoot->iRowid
  182920. && pPhrase->poslist.n>0
  182921. ){
  182922. Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
  182923. if( pTerm->pSynonym ){
  182924. Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
  182925. rc = fts5ExprSynonymList(
  182926. pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
  182927. );
  182928. }else{
  182929. *ppCollist = pPhrase->aTerm[0].pIter->pData;
  182930. *pnCollist = pPhrase->aTerm[0].pIter->nData;
  182931. }
  182932. }else{
  182933. *ppCollist = 0;
  182934. *pnCollist = 0;
  182935. }
  182936. return rc;
  182937. }
  182938. /*
  182939. ** 2014 August 11
  182940. **
  182941. ** The author disclaims copyright to this source code. In place of
  182942. ** a legal notice, here is a blessing:
  182943. **
  182944. ** May you do good and not evil.
  182945. ** May you find forgiveness for yourself and forgive others.
  182946. ** May you share freely, never taking more than you give.
  182947. **
  182948. ******************************************************************************
  182949. **
  182950. */
  182951. /* #include "fts5Int.h" */
  182952. typedef struct Fts5HashEntry Fts5HashEntry;
  182953. /*
  182954. ** This file contains the implementation of an in-memory hash table used
  182955. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  182956. ** segment.
  182957. */
  182958. struct Fts5Hash {
  182959. int eDetail; /* Copy of Fts5Config.eDetail */
  182960. int *pnByte; /* Pointer to bytes counter */
  182961. int nEntry; /* Number of entries currently in hash */
  182962. int nSlot; /* Size of aSlot[] array */
  182963. Fts5HashEntry *pScan; /* Current ordered scan item */
  182964. Fts5HashEntry **aSlot; /* Array of hash slots */
  182965. };
  182966. /*
  182967. ** Each entry in the hash table is represented by an object of the
  182968. ** following type. Each object, its key (a nul-terminated string) and
  182969. ** its current data are stored in a single memory allocation. The
  182970. ** key immediately follows the object in memory. The position list
  182971. ** data immediately follows the key data in memory.
  182972. **
  182973. ** The data that follows the key is in a similar, but not identical format
  182974. ** to the doclist data stored in the database. It is:
  182975. **
  182976. ** * Rowid, as a varint
  182977. ** * Position list, without 0x00 terminator.
  182978. ** * Size of previous position list and rowid, as a 4 byte
  182979. ** big-endian integer.
  182980. **
  182981. ** iRowidOff:
  182982. ** Offset of last rowid written to data area. Relative to first byte of
  182983. ** structure.
  182984. **
  182985. ** nData:
  182986. ** Bytes of data written since iRowidOff.
  182987. */
  182988. struct Fts5HashEntry {
  182989. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  182990. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  182991. int nAlloc; /* Total size of allocation */
  182992. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  182993. int nData; /* Total bytes of data (incl. structure) */
  182994. int nKey; /* Length of key in bytes */
  182995. u8 bDel; /* Set delete-flag @ iSzPoslist */
  182996. u8 bContent; /* Set content-flag (detail=none mode) */
  182997. i16 iCol; /* Column of last value written */
  182998. int iPos; /* Position of last value written */
  182999. i64 iRowid; /* Rowid of last value written */
  183000. };
  183001. /*
  183002. ** Eqivalent to:
  183003. **
  183004. ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
  183005. */
  183006. #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
  183007. /*
  183008. ** Allocate a new hash table.
  183009. */
  183010. static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
  183011. int rc = SQLITE_OK;
  183012. Fts5Hash *pNew;
  183013. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  183014. if( pNew==0 ){
  183015. rc = SQLITE_NOMEM;
  183016. }else{
  183017. int nByte;
  183018. memset(pNew, 0, sizeof(Fts5Hash));
  183019. pNew->pnByte = pnByte;
  183020. pNew->eDetail = pConfig->eDetail;
  183021. pNew->nSlot = 1024;
  183022. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  183023. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
  183024. if( pNew->aSlot==0 ){
  183025. sqlite3_free(pNew);
  183026. *ppNew = 0;
  183027. rc = SQLITE_NOMEM;
  183028. }else{
  183029. memset(pNew->aSlot, 0, nByte);
  183030. }
  183031. }
  183032. return rc;
  183033. }
  183034. /*
  183035. ** Free a hash table object.
  183036. */
  183037. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  183038. if( pHash ){
  183039. sqlite3Fts5HashClear(pHash);
  183040. sqlite3_free(pHash->aSlot);
  183041. sqlite3_free(pHash);
  183042. }
  183043. }
  183044. /*
  183045. ** Empty (but do not delete) a hash table.
  183046. */
  183047. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  183048. int i;
  183049. for(i=0; i<pHash->nSlot; i++){
  183050. Fts5HashEntry *pNext;
  183051. Fts5HashEntry *pSlot;
  183052. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  183053. pNext = pSlot->pHashNext;
  183054. sqlite3_free(pSlot);
  183055. }
  183056. }
  183057. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  183058. pHash->nEntry = 0;
  183059. }
  183060. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  183061. int i;
  183062. unsigned int h = 13;
  183063. for(i=n-1; i>=0; i--){
  183064. h = (h << 3) ^ h ^ p[i];
  183065. }
  183066. return (h % nSlot);
  183067. }
  183068. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  183069. int i;
  183070. unsigned int h = 13;
  183071. for(i=n-1; i>=0; i--){
  183072. h = (h << 3) ^ h ^ p[i];
  183073. }
  183074. h = (h << 3) ^ h ^ b;
  183075. return (h % nSlot);
  183076. }
  183077. /*
  183078. ** Resize the hash table by doubling the number of slots.
  183079. */
  183080. static int fts5HashResize(Fts5Hash *pHash){
  183081. int nNew = pHash->nSlot*2;
  183082. int i;
  183083. Fts5HashEntry **apNew;
  183084. Fts5HashEntry **apOld = pHash->aSlot;
  183085. apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
  183086. if( !apNew ) return SQLITE_NOMEM;
  183087. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  183088. for(i=0; i<pHash->nSlot; i++){
  183089. while( apOld[i] ){
  183090. unsigned int iHash;
  183091. Fts5HashEntry *p = apOld[i];
  183092. apOld[i] = p->pHashNext;
  183093. iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
  183094. (int)strlen(fts5EntryKey(p)));
  183095. p->pHashNext = apNew[iHash];
  183096. apNew[iHash] = p;
  183097. }
  183098. }
  183099. sqlite3_free(apOld);
  183100. pHash->nSlot = nNew;
  183101. pHash->aSlot = apNew;
  183102. return SQLITE_OK;
  183103. }
  183104. static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
  183105. if( p->iSzPoslist ){
  183106. u8 *pPtr = (u8*)p;
  183107. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  183108. assert( p->nData==p->iSzPoslist );
  183109. if( p->bDel ){
  183110. pPtr[p->nData++] = 0x00;
  183111. if( p->bContent ){
  183112. pPtr[p->nData++] = 0x00;
  183113. }
  183114. }
  183115. }else{
  183116. int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
  183117. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  183118. assert( p->bDel==0 || p->bDel==1 );
  183119. if( nPos<=127 ){
  183120. pPtr[p->iSzPoslist] = (u8)nPos;
  183121. }else{
  183122. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  183123. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  183124. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  183125. p->nData += (nByte-1);
  183126. }
  183127. }
  183128. p->iSzPoslist = 0;
  183129. p->bDel = 0;
  183130. p->bContent = 0;
  183131. }
  183132. }
  183133. /*
  183134. ** Add an entry to the in-memory hash table. The key is the concatenation
  183135. ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
  183136. **
  183137. ** (bByte || pToken) -> (iRowid,iCol,iPos)
  183138. **
  183139. ** Or, if iCol is negative, then the value is a delete marker.
  183140. */
  183141. static int sqlite3Fts5HashWrite(
  183142. Fts5Hash *pHash,
  183143. i64 iRowid, /* Rowid for this entry */
  183144. int iCol, /* Column token appears in (-ve -> delete) */
  183145. int iPos, /* Position of token within column */
  183146. char bByte, /* First byte of token */
  183147. const char *pToken, int nToken /* Token to add or remove to or from index */
  183148. ){
  183149. unsigned int iHash;
  183150. Fts5HashEntry *p;
  183151. u8 *pPtr;
  183152. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  183153. int bNew; /* If non-delete entry should be written */
  183154. bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
  183155. /* Attempt to locate an existing hash entry */
  183156. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  183157. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  183158. char *zKey = fts5EntryKey(p);
  183159. if( zKey[0]==bByte
  183160. && p->nKey==nToken
  183161. && memcmp(&zKey[1], pToken, nToken)==0
  183162. ){
  183163. break;
  183164. }
  183165. }
  183166. /* If an existing hash entry cannot be found, create a new one. */
  183167. if( p==0 ){
  183168. /* Figure out how much space to allocate */
  183169. char *zKey;
  183170. int nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
  183171. if( nByte<128 ) nByte = 128;
  183172. /* Grow the Fts5Hash.aSlot[] array if necessary. */
  183173. if( (pHash->nEntry*2)>=pHash->nSlot ){
  183174. int rc = fts5HashResize(pHash);
  183175. if( rc!=SQLITE_OK ) return rc;
  183176. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  183177. }
  183178. /* Allocate new Fts5HashEntry and add it to the hash table. */
  183179. p = (Fts5HashEntry*)sqlite3_malloc(nByte);
  183180. if( !p ) return SQLITE_NOMEM;
  183181. memset(p, 0, sizeof(Fts5HashEntry));
  183182. p->nAlloc = nByte;
  183183. zKey = fts5EntryKey(p);
  183184. zKey[0] = bByte;
  183185. memcpy(&zKey[1], pToken, nToken);
  183186. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
  183187. p->nKey = nToken;
  183188. zKey[nToken+1] = '\0';
  183189. p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
  183190. p->pHashNext = pHash->aSlot[iHash];
  183191. pHash->aSlot[iHash] = p;
  183192. pHash->nEntry++;
  183193. /* Add the first rowid field to the hash-entry */
  183194. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  183195. p->iRowid = iRowid;
  183196. p->iSzPoslist = p->nData;
  183197. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  183198. p->nData += 1;
  183199. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  183200. }
  183201. nIncr += p->nData;
  183202. }else{
  183203. /* Appending to an existing hash-entry. Check that there is enough
  183204. ** space to append the largest possible new entry. Worst case scenario
  183205. ** is:
  183206. **
  183207. ** + 9 bytes for a new rowid,
  183208. ** + 4 byte reserved for the "poslist size" varint.
  183209. ** + 1 byte for a "new column" byte,
  183210. ** + 3 bytes for a new column number (16-bit max) as a varint,
  183211. ** + 5 bytes for the new position offset (32-bit max).
  183212. */
  183213. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  183214. int nNew = p->nAlloc * 2;
  183215. Fts5HashEntry *pNew;
  183216. Fts5HashEntry **pp;
  183217. pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
  183218. if( pNew==0 ) return SQLITE_NOMEM;
  183219. pNew->nAlloc = nNew;
  183220. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  183221. *pp = pNew;
  183222. p = pNew;
  183223. }
  183224. nIncr -= p->nData;
  183225. }
  183226. assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
  183227. pPtr = (u8*)p;
  183228. /* If this is a new rowid, append the 4-byte size field for the previous
  183229. ** entry, and the new rowid for this entry. */
  183230. if( iRowid!=p->iRowid ){
  183231. fts5HashAddPoslistSize(pHash, p);
  183232. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  183233. p->iRowid = iRowid;
  183234. bNew = 1;
  183235. p->iSzPoslist = p->nData;
  183236. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  183237. p->nData += 1;
  183238. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  183239. p->iPos = 0;
  183240. }
  183241. }
  183242. if( iCol>=0 ){
  183243. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  183244. p->bContent = 1;
  183245. }else{
  183246. /* Append a new column value, if necessary */
  183247. assert( iCol>=p->iCol );
  183248. if( iCol!=p->iCol ){
  183249. if( pHash->eDetail==FTS5_DETAIL_FULL ){
  183250. pPtr[p->nData++] = 0x01;
  183251. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  183252. p->iCol = (i16)iCol;
  183253. p->iPos = 0;
  183254. }else{
  183255. bNew = 1;
  183256. p->iCol = (i16)(iPos = iCol);
  183257. }
  183258. }
  183259. /* Append the new position offset, if necessary */
  183260. if( bNew ){
  183261. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  183262. p->iPos = iPos;
  183263. }
  183264. }
  183265. }else{
  183266. /* This is a delete. Set the delete flag. */
  183267. p->bDel = 1;
  183268. }
  183269. nIncr += p->nData;
  183270. *pHash->pnByte += nIncr;
  183271. return SQLITE_OK;
  183272. }
  183273. /*
  183274. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  183275. ** each sorted in key order. This function merges the two lists into a
  183276. ** single list and returns a pointer to its first element.
  183277. */
  183278. static Fts5HashEntry *fts5HashEntryMerge(
  183279. Fts5HashEntry *pLeft,
  183280. Fts5HashEntry *pRight
  183281. ){
  183282. Fts5HashEntry *p1 = pLeft;
  183283. Fts5HashEntry *p2 = pRight;
  183284. Fts5HashEntry *pRet = 0;
  183285. Fts5HashEntry **ppOut = &pRet;
  183286. while( p1 || p2 ){
  183287. if( p1==0 ){
  183288. *ppOut = p2;
  183289. p2 = 0;
  183290. }else if( p2==0 ){
  183291. *ppOut = p1;
  183292. p1 = 0;
  183293. }else{
  183294. int i = 0;
  183295. char *zKey1 = fts5EntryKey(p1);
  183296. char *zKey2 = fts5EntryKey(p2);
  183297. while( zKey1[i]==zKey2[i] ) i++;
  183298. if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
  183299. /* p2 is smaller */
  183300. *ppOut = p2;
  183301. ppOut = &p2->pScanNext;
  183302. p2 = p2->pScanNext;
  183303. }else{
  183304. /* p1 is smaller */
  183305. *ppOut = p1;
  183306. ppOut = &p1->pScanNext;
  183307. p1 = p1->pScanNext;
  183308. }
  183309. *ppOut = 0;
  183310. }
  183311. }
  183312. return pRet;
  183313. }
  183314. /*
  183315. ** Extract all tokens from hash table iHash and link them into a list
  183316. ** in sorted order. The hash table is cleared before returning. It is
  183317. ** the responsibility of the caller to free the elements of the returned
  183318. ** list.
  183319. */
  183320. static int fts5HashEntrySort(
  183321. Fts5Hash *pHash,
  183322. const char *pTerm, int nTerm, /* Query prefix, if any */
  183323. Fts5HashEntry **ppSorted
  183324. ){
  183325. const int nMergeSlot = 32;
  183326. Fts5HashEntry **ap;
  183327. Fts5HashEntry *pList;
  183328. int iSlot;
  183329. int i;
  183330. *ppSorted = 0;
  183331. ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
  183332. if( !ap ) return SQLITE_NOMEM;
  183333. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  183334. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  183335. Fts5HashEntry *pIter;
  183336. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  183337. if( pTerm==0 || 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm) ){
  183338. Fts5HashEntry *pEntry = pIter;
  183339. pEntry->pScanNext = 0;
  183340. for(i=0; ap[i]; i++){
  183341. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  183342. ap[i] = 0;
  183343. }
  183344. ap[i] = pEntry;
  183345. }
  183346. }
  183347. }
  183348. pList = 0;
  183349. for(i=0; i<nMergeSlot; i++){
  183350. pList = fts5HashEntryMerge(pList, ap[i]);
  183351. }
  183352. pHash->nEntry = 0;
  183353. sqlite3_free(ap);
  183354. *ppSorted = pList;
  183355. return SQLITE_OK;
  183356. }
  183357. /*
  183358. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  183359. */
  183360. static int sqlite3Fts5HashQuery(
  183361. Fts5Hash *pHash, /* Hash table to query */
  183362. const char *pTerm, int nTerm, /* Query term */
  183363. const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
  183364. int *pnDoclist /* OUT: Size of doclist in bytes */
  183365. ){
  183366. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  183367. char *zKey = 0;
  183368. Fts5HashEntry *p;
  183369. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  183370. zKey = fts5EntryKey(p);
  183371. if( memcmp(zKey, pTerm, nTerm)==0 && zKey[nTerm]==0 ) break;
  183372. }
  183373. if( p ){
  183374. fts5HashAddPoslistSize(pHash, p);
  183375. *ppDoclist = (const u8*)&zKey[nTerm+1];
  183376. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  183377. }else{
  183378. *ppDoclist = 0;
  183379. *pnDoclist = 0;
  183380. }
  183381. return SQLITE_OK;
  183382. }
  183383. static int sqlite3Fts5HashScanInit(
  183384. Fts5Hash *p, /* Hash table to query */
  183385. const char *pTerm, int nTerm /* Query prefix */
  183386. ){
  183387. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  183388. }
  183389. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  183390. assert( !sqlite3Fts5HashScanEof(p) );
  183391. p->pScan = p->pScan->pScanNext;
  183392. }
  183393. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  183394. return (p->pScan==0);
  183395. }
  183396. static void sqlite3Fts5HashScanEntry(
  183397. Fts5Hash *pHash,
  183398. const char **pzTerm, /* OUT: term (nul-terminated) */
  183399. const u8 **ppDoclist, /* OUT: pointer to doclist */
  183400. int *pnDoclist /* OUT: size of doclist in bytes */
  183401. ){
  183402. Fts5HashEntry *p;
  183403. if( (p = pHash->pScan) ){
  183404. char *zKey = fts5EntryKey(p);
  183405. int nTerm = (int)strlen(zKey);
  183406. fts5HashAddPoslistSize(pHash, p);
  183407. *pzTerm = zKey;
  183408. *ppDoclist = (const u8*)&zKey[nTerm+1];
  183409. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  183410. }else{
  183411. *pzTerm = 0;
  183412. *ppDoclist = 0;
  183413. *pnDoclist = 0;
  183414. }
  183415. }
  183416. /*
  183417. ** 2014 May 31
  183418. **
  183419. ** The author disclaims copyright to this source code. In place of
  183420. ** a legal notice, here is a blessing:
  183421. **
  183422. ** May you do good and not evil.
  183423. ** May you find forgiveness for yourself and forgive others.
  183424. ** May you share freely, never taking more than you give.
  183425. **
  183426. ******************************************************************************
  183427. **
  183428. ** Low level access to the FTS index stored in the database file. The
  183429. ** routines in this file file implement all read and write access to the
  183430. ** %_data table. Other parts of the system access this functionality via
  183431. ** the interface defined in fts5Int.h.
  183432. */
  183433. /* #include "fts5Int.h" */
  183434. /*
  183435. ** Overview:
  183436. **
  183437. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  183438. ** As well as the main term index, there may be up to 31 prefix indexes.
  183439. ** The format is similar to FTS3/4, except that:
  183440. **
  183441. ** * all segment b-tree leaf data is stored in fixed size page records
  183442. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  183443. ** taken to ensure it is possible to iterate in either direction through
  183444. ** the entries in a doclist, or to seek to a specific entry within a
  183445. ** doclist, without loading it into memory.
  183446. **
  183447. ** * large doclists that span many pages have associated "doclist index"
  183448. ** records that contain a copy of the first rowid on each page spanned by
  183449. ** the doclist. This is used to speed up seek operations, and merges of
  183450. ** large doclists with very small doclists.
  183451. **
  183452. ** * extra fields in the "structure record" record the state of ongoing
  183453. ** incremental merge operations.
  183454. **
  183455. */
  183456. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  183457. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  183458. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  183459. #define FTS5_MAIN_PREFIX '0'
  183460. #if FTS5_MAX_PREFIX_INDEXES > 31
  183461. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  183462. #endif
  183463. /*
  183464. ** Details:
  183465. **
  183466. ** The %_data table managed by this module,
  183467. **
  183468. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  183469. **
  183470. ** , contains the following 5 types of records. See the comments surrounding
  183471. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  183472. ** assigned to each fo them.
  183473. **
  183474. ** 1. Structure Records:
  183475. **
  183476. ** The set of segments that make up an index - the index structure - are
  183477. ** recorded in a single record within the %_data table. The record consists
  183478. ** of a single 32-bit configuration cookie value followed by a list of
  183479. ** SQLite varints. If the FTS table features more than one index (because
  183480. ** there are one or more prefix indexes), it is guaranteed that all share
  183481. ** the same cookie value.
  183482. **
  183483. ** Immediately following the configuration cookie, the record begins with
  183484. ** three varints:
  183485. **
  183486. ** + number of levels,
  183487. ** + total number of segments on all levels,
  183488. ** + value of write counter.
  183489. **
  183490. ** Then, for each level from 0 to nMax:
  183491. **
  183492. ** + number of input segments in ongoing merge.
  183493. ** + total number of segments in level.
  183494. ** + for each segment from oldest to newest:
  183495. ** + segment id (always > 0)
  183496. ** + first leaf page number (often 1, always greater than 0)
  183497. ** + final leaf page number
  183498. **
  183499. ** 2. The Averages Record:
  183500. **
  183501. ** A single record within the %_data table. The data is a list of varints.
  183502. ** The first value is the number of rows in the index. Then, for each column
  183503. ** from left to right, the total number of tokens in the column for all
  183504. ** rows of the table.
  183505. **
  183506. ** 3. Segment leaves:
  183507. **
  183508. ** TERM/DOCLIST FORMAT:
  183509. **
  183510. ** Most of each segment leaf is taken up by term/doclist data. The
  183511. ** general format of term/doclist, starting with the first term
  183512. ** on the leaf page, is:
  183513. **
  183514. ** varint : size of first term
  183515. ** blob: first term data
  183516. ** doclist: first doclist
  183517. ** zero-or-more {
  183518. ** varint: number of bytes in common with previous term
  183519. ** varint: number of bytes of new term data (nNew)
  183520. ** blob: nNew bytes of new term data
  183521. ** doclist: next doclist
  183522. ** }
  183523. **
  183524. ** doclist format:
  183525. **
  183526. ** varint: first rowid
  183527. ** poslist: first poslist
  183528. ** zero-or-more {
  183529. ** varint: rowid delta (always > 0)
  183530. ** poslist: next poslist
  183531. ** }
  183532. **
  183533. ** poslist format:
  183534. **
  183535. ** varint: size of poslist in bytes multiplied by 2, not including
  183536. ** this field. Plus 1 if this entry carries the "delete" flag.
  183537. ** collist: collist for column 0
  183538. ** zero-or-more {
  183539. ** 0x01 byte
  183540. ** varint: column number (I)
  183541. ** collist: collist for column I
  183542. ** }
  183543. **
  183544. ** collist format:
  183545. **
  183546. ** varint: first offset + 2
  183547. ** zero-or-more {
  183548. ** varint: offset delta + 2
  183549. ** }
  183550. **
  183551. ** PAGE FORMAT
  183552. **
  183553. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  183554. ** unsigned integer fields in big-endian format. They are:
  183555. **
  183556. ** * The byte offset of the first rowid on the page, if it exists
  183557. ** and occurs before the first term (otherwise 0).
  183558. **
  183559. ** * The byte offset of the start of the page footer. If the page
  183560. ** footer is 0 bytes in size, then this field is the same as the
  183561. ** size of the leaf page in bytes.
  183562. **
  183563. ** The page footer consists of a single varint for each term located
  183564. ** on the page. Each varint is the byte offset of the current term
  183565. ** within the page, delta-compressed against the previous value. In
  183566. ** other words, the first varint in the footer is the byte offset of
  183567. ** the first term, the second is the byte offset of the second less that
  183568. ** of the first, and so on.
  183569. **
  183570. ** The term/doclist format described above is accurate if the entire
  183571. ** term/doclist data fits on a single leaf page. If this is not the case,
  183572. ** the format is changed in two ways:
  183573. **
  183574. ** + if the first rowid on a page occurs before the first term, it
  183575. ** is stored as a literal value:
  183576. **
  183577. ** varint: first rowid
  183578. **
  183579. ** + the first term on each page is stored in the same way as the
  183580. ** very first term of the segment:
  183581. **
  183582. ** varint : size of first term
  183583. ** blob: first term data
  183584. **
  183585. ** 5. Segment doclist indexes:
  183586. **
  183587. ** Doclist indexes are themselves b-trees, however they usually consist of
  183588. ** a single leaf record only. The format of each doclist index leaf page
  183589. ** is:
  183590. **
  183591. ** * Flags byte. Bits are:
  183592. ** 0x01: Clear if leaf is also the root page, otherwise set.
  183593. **
  183594. ** * Page number of fts index leaf page. As a varint.
  183595. **
  183596. ** * First rowid on page indicated by previous field. As a varint.
  183597. **
  183598. ** * A list of varints, one for each subsequent termless page. A
  183599. ** positive delta if the termless page contains at least one rowid,
  183600. ** or an 0x00 byte otherwise.
  183601. **
  183602. ** Internal doclist index nodes are:
  183603. **
  183604. ** * Flags byte. Bits are:
  183605. ** 0x01: Clear for root page, otherwise set.
  183606. **
  183607. ** * Page number of first child page. As a varint.
  183608. **
  183609. ** * Copy of first rowid on page indicated by previous field. As a varint.
  183610. **
  183611. ** * A list of delta-encoded varints - the first rowid on each subsequent
  183612. ** child page.
  183613. **
  183614. */
  183615. /*
  183616. ** Rowids for the averages and structure records in the %_data table.
  183617. */
  183618. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  183619. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  183620. /*
  183621. ** Macros determining the rowids used by segment leaves and dlidx leaves
  183622. ** and nodes. All nodes and leaves are stored in the %_data table with large
  183623. ** positive rowids.
  183624. **
  183625. ** Each segment has a unique non-zero 16-bit id.
  183626. **
  183627. ** The rowid for each segment leaf is found by passing the segment id and
  183628. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  183629. ** sequentially starting from 1.
  183630. */
  183631. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  183632. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  183633. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  183634. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  183635. #define fts5_dri(segid, dlidx, height, pgno) ( \
  183636. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  183637. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  183638. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  183639. ((i64)(pgno)) \
  183640. )
  183641. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  183642. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  183643. /*
  183644. ** Maximum segments permitted in a single index
  183645. */
  183646. #define FTS5_MAX_SEGMENT 2000
  183647. #ifdef SQLITE_DEBUG
  183648. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  183649. #endif
  183650. /*
  183651. ** Each time a blob is read from the %_data table, it is padded with this
  183652. ** many zero bytes. This makes it easier to decode the various record formats
  183653. ** without overreading if the records are corrupt.
  183654. */
  183655. #define FTS5_DATA_ZERO_PADDING 8
  183656. #define FTS5_DATA_PADDING 20
  183657. typedef struct Fts5Data Fts5Data;
  183658. typedef struct Fts5DlidxIter Fts5DlidxIter;
  183659. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  183660. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  183661. typedef struct Fts5Iter Fts5Iter;
  183662. typedef struct Fts5PageWriter Fts5PageWriter;
  183663. typedef struct Fts5SegIter Fts5SegIter;
  183664. typedef struct Fts5DoclistIter Fts5DoclistIter;
  183665. typedef struct Fts5SegWriter Fts5SegWriter;
  183666. typedef struct Fts5Structure Fts5Structure;
  183667. typedef struct Fts5StructureLevel Fts5StructureLevel;
  183668. typedef struct Fts5StructureSegment Fts5StructureSegment;
  183669. struct Fts5Data {
  183670. u8 *p; /* Pointer to buffer containing record */
  183671. int nn; /* Size of record in bytes */
  183672. int szLeaf; /* Size of leaf without page-index */
  183673. };
  183674. /*
  183675. ** One object per %_data table.
  183676. */
  183677. struct Fts5Index {
  183678. Fts5Config *pConfig; /* Virtual table configuration */
  183679. char *zDataTbl; /* Name of %_data table */
  183680. int nWorkUnit; /* Leaf pages in a "unit" of work */
  183681. /*
  183682. ** Variables related to the accumulation of tokens and doclists within the
  183683. ** in-memory hash tables before they are flushed to disk.
  183684. */
  183685. Fts5Hash *pHash; /* Hash table for in-memory data */
  183686. int nPendingData; /* Current bytes of pending data */
  183687. i64 iWriteRowid; /* Rowid for current doc being written */
  183688. int bDelete; /* Current write is a delete */
  183689. /* Error state. */
  183690. int rc; /* Current error code */
  183691. /* State used by the fts5DataXXX() functions. */
  183692. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  183693. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  183694. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  183695. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  183696. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  183697. sqlite3_stmt *pIdxSelect;
  183698. int nRead; /* Total number of blocks read */
  183699. sqlite3_stmt *pDataVersion;
  183700. i64 iStructVersion; /* data_version when pStruct read */
  183701. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  183702. };
  183703. struct Fts5DoclistIter {
  183704. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  183705. /* Output variables. aPoslist==0 at EOF */
  183706. i64 iRowid;
  183707. u8 *aPoslist;
  183708. int nPoslist;
  183709. int nSize;
  183710. };
  183711. /*
  183712. ** The contents of the "structure" record for each index are represented
  183713. ** using an Fts5Structure record in memory. Which uses instances of the
  183714. ** other Fts5StructureXXX types as components.
  183715. */
  183716. struct Fts5StructureSegment {
  183717. int iSegid; /* Segment id */
  183718. int pgnoFirst; /* First leaf page number in segment */
  183719. int pgnoLast; /* Last leaf page number in segment */
  183720. };
  183721. struct Fts5StructureLevel {
  183722. int nMerge; /* Number of segments in incr-merge */
  183723. int nSeg; /* Total number of segments on level */
  183724. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  183725. };
  183726. struct Fts5Structure {
  183727. int nRef; /* Object reference count */
  183728. u64 nWriteCounter; /* Total leaves written to level 0 */
  183729. int nSegment; /* Total segments in this structure */
  183730. int nLevel; /* Number of levels in this index */
  183731. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  183732. };
  183733. /*
  183734. ** An object of type Fts5SegWriter is used to write to segments.
  183735. */
  183736. struct Fts5PageWriter {
  183737. int pgno; /* Page number for this page */
  183738. int iPrevPgidx; /* Previous value written into pgidx */
  183739. Fts5Buffer buf; /* Buffer containing leaf data */
  183740. Fts5Buffer pgidx; /* Buffer containing page-index */
  183741. Fts5Buffer term; /* Buffer containing previous term on page */
  183742. };
  183743. struct Fts5DlidxWriter {
  183744. int pgno; /* Page number for this page */
  183745. int bPrevValid; /* True if iPrev is valid */
  183746. i64 iPrev; /* Previous rowid value written to page */
  183747. Fts5Buffer buf; /* Buffer containing page data */
  183748. };
  183749. struct Fts5SegWriter {
  183750. int iSegid; /* Segid to write to */
  183751. Fts5PageWriter writer; /* PageWriter object */
  183752. i64 iPrevRowid; /* Previous rowid written to current leaf */
  183753. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  183754. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  183755. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  183756. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  183757. int nLeafWritten; /* Number of leaf pages written */
  183758. int nEmpty; /* Number of contiguous term-less nodes */
  183759. int nDlidx; /* Allocated size of aDlidx[] array */
  183760. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  183761. /* Values to insert into the %_idx table */
  183762. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  183763. int iBtPage; /* Page number corresponding to btterm */
  183764. };
  183765. typedef struct Fts5CResult Fts5CResult;
  183766. struct Fts5CResult {
  183767. u16 iFirst; /* aSeg[] index of firstest iterator */
  183768. u8 bTermEq; /* True if the terms are equal */
  183769. };
  183770. /*
  183771. ** Object for iterating through a single segment, visiting each term/rowid
  183772. ** pair in the segment.
  183773. **
  183774. ** pSeg:
  183775. ** The segment to iterate through.
  183776. **
  183777. ** iLeafPgno:
  183778. ** Current leaf page number within segment.
  183779. **
  183780. ** iLeafOffset:
  183781. ** Byte offset within the current leaf that is the first byte of the
  183782. ** position list data (one byte passed the position-list size field).
  183783. ** rowid field of the current entry. Usually this is the size field of the
  183784. ** position list data. The exception is if the rowid for the current entry
  183785. ** is the last thing on the leaf page.
  183786. **
  183787. ** pLeaf:
  183788. ** Buffer containing current leaf page data. Set to NULL at EOF.
  183789. **
  183790. ** iTermLeafPgno, iTermLeafOffset:
  183791. ** Leaf page number containing the last term read from the segment. And
  183792. ** the offset immediately following the term data.
  183793. **
  183794. ** flags:
  183795. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  183796. **
  183797. ** FTS5_SEGITER_ONETERM:
  183798. ** If set, set the iterator to point to EOF after the current doclist
  183799. ** has been exhausted. Do not proceed to the next term in the segment.
  183800. **
  183801. ** FTS5_SEGITER_REVERSE:
  183802. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  183803. ** it is set, iterate through rowid in descending order instead of the
  183804. ** default ascending order.
  183805. **
  183806. ** iRowidOffset/nRowidOffset/aRowidOffset:
  183807. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  183808. **
  183809. ** For each rowid on the page corresponding to the current term, the
  183810. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  183811. ** start of the "position-list-size" field within the page.
  183812. **
  183813. ** iTermIdx:
  183814. ** Index of current term on iTermLeafPgno.
  183815. */
  183816. struct Fts5SegIter {
  183817. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  183818. int flags; /* Mask of configuration flags */
  183819. int iLeafPgno; /* Current leaf page number */
  183820. Fts5Data *pLeaf; /* Current leaf data */
  183821. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  183822. int iLeafOffset; /* Byte offset within current leaf */
  183823. /* Next method */
  183824. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  183825. /* The page and offset from which the current term was read. The offset
  183826. ** is the offset of the first rowid in the current doclist. */
  183827. int iTermLeafPgno;
  183828. int iTermLeafOffset;
  183829. int iPgidxOff; /* Next offset in pgidx */
  183830. int iEndofDoclist;
  183831. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  183832. int iRowidOffset; /* Current entry in aRowidOffset[] */
  183833. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  183834. int *aRowidOffset; /* Array of offset to rowid fields */
  183835. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  183836. /* Variables populated based on current entry. */
  183837. Fts5Buffer term; /* Current term */
  183838. i64 iRowid; /* Current rowid */
  183839. int nPos; /* Number of bytes in current position list */
  183840. u8 bDel; /* True if the delete flag is set */
  183841. };
  183842. /*
  183843. ** Argument is a pointer to an Fts5Data structure that contains a
  183844. ** leaf page.
  183845. */
  183846. #define ASSERT_SZLEAF_OK(x) assert( \
  183847. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  183848. )
  183849. #define FTS5_SEGITER_ONETERM 0x01
  183850. #define FTS5_SEGITER_REVERSE 0x02
  183851. /*
  183852. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  183853. ** page. This macro evaluates to true if the leaf contains no terms, or
  183854. ** false if it contains at least one term.
  183855. */
  183856. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  183857. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  183858. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  183859. /*
  183860. ** Object for iterating through the merged results of one or more segments,
  183861. ** visiting each term/rowid pair in the merged data.
  183862. **
  183863. ** nSeg is always a power of two greater than or equal to the number of
  183864. ** segments that this object is merging data from. Both the aSeg[] and
  183865. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  183866. ** with zeroed objects - these are handled as if they were iterators opened
  183867. ** on empty segments.
  183868. **
  183869. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  183870. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  183871. ** comparison in this context is the index of the iterator that currently
  183872. ** points to the smaller term/rowid combination. Iterators at EOF are
  183873. ** considered to be greater than all other iterators.
  183874. **
  183875. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  183876. ** the smallest key overall. aFirst[0] is unused.
  183877. **
  183878. ** poslist:
  183879. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  183880. ** There is no way to tell if this is populated or not.
  183881. */
  183882. struct Fts5Iter {
  183883. Fts5IndexIter base; /* Base class containing output vars */
  183884. Fts5Index *pIndex; /* Index that owns this iterator */
  183885. Fts5Structure *pStruct; /* Database structure for this iterator */
  183886. Fts5Buffer poslist; /* Buffer containing current poslist */
  183887. Fts5Colset *pColset; /* Restrict matches to these columns */
  183888. /* Invoked to set output variables. */
  183889. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  183890. int nSeg; /* Size of aSeg[] array */
  183891. int bRev; /* True to iterate in reverse order */
  183892. u8 bSkipEmpty; /* True to skip deleted entries */
  183893. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  183894. Fts5CResult *aFirst; /* Current merge state (see above) */
  183895. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  183896. };
  183897. /*
  183898. ** An instance of the following type is used to iterate through the contents
  183899. ** of a doclist-index record.
  183900. **
  183901. ** pData:
  183902. ** Record containing the doclist-index data.
  183903. **
  183904. ** bEof:
  183905. ** Set to true once iterator has reached EOF.
  183906. **
  183907. ** iOff:
  183908. ** Set to the current offset within record pData.
  183909. */
  183910. struct Fts5DlidxLvl {
  183911. Fts5Data *pData; /* Data for current page of this level */
  183912. int iOff; /* Current offset into pData */
  183913. int bEof; /* At EOF already */
  183914. int iFirstOff; /* Used by reverse iterators */
  183915. /* Output variables */
  183916. int iLeafPgno; /* Page number of current leaf page */
  183917. i64 iRowid; /* First rowid on leaf iLeafPgno */
  183918. };
  183919. struct Fts5DlidxIter {
  183920. int nLvl;
  183921. int iSegid;
  183922. Fts5DlidxLvl aLvl[1];
  183923. };
  183924. static void fts5PutU16(u8 *aOut, u16 iVal){
  183925. aOut[0] = (iVal>>8);
  183926. aOut[1] = (iVal&0xFF);
  183927. }
  183928. static u16 fts5GetU16(const u8 *aIn){
  183929. return ((u16)aIn[0] << 8) + aIn[1];
  183930. }
  183931. /*
  183932. ** Allocate and return a buffer at least nByte bytes in size.
  183933. **
  183934. ** If an OOM error is encountered, return NULL and set the error code in
  183935. ** the Fts5Index handle passed as the first argument.
  183936. */
  183937. static void *fts5IdxMalloc(Fts5Index *p, int nByte){
  183938. return sqlite3Fts5MallocZero(&p->rc, nByte);
  183939. }
  183940. /*
  183941. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  183942. **
  183943. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  183944. ** +ve if pRight is smaller than pLeft. In other words:
  183945. **
  183946. ** res = *pLeft - *pRight
  183947. */
  183948. #ifdef SQLITE_DEBUG
  183949. static int fts5BufferCompareBlob(
  183950. Fts5Buffer *pLeft, /* Left hand side of comparison */
  183951. const u8 *pRight, int nRight /* Right hand side of comparison */
  183952. ){
  183953. int nCmp = MIN(pLeft->n, nRight);
  183954. int res = memcmp(pLeft->p, pRight, nCmp);
  183955. return (res==0 ? (pLeft->n - nRight) : res);
  183956. }
  183957. #endif
  183958. /*
  183959. ** Compare the contents of the two buffers using memcmp(). If one buffer
  183960. ** is a prefix of the other, it is considered the lesser.
  183961. **
  183962. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  183963. ** +ve if pRight is smaller than pLeft. In other words:
  183964. **
  183965. ** res = *pLeft - *pRight
  183966. */
  183967. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  183968. int nCmp = MIN(pLeft->n, pRight->n);
  183969. int res = memcmp(pLeft->p, pRight->p, nCmp);
  183970. return (res==0 ? (pLeft->n - pRight->n) : res);
  183971. }
  183972. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  183973. int ret;
  183974. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  183975. return ret;
  183976. }
  183977. /*
  183978. ** Close the read-only blob handle, if it is open.
  183979. */
  183980. static void fts5CloseReader(Fts5Index *p){
  183981. if( p->pReader ){
  183982. sqlite3_blob *pReader = p->pReader;
  183983. p->pReader = 0;
  183984. sqlite3_blob_close(pReader);
  183985. }
  183986. }
  183987. /*
  183988. ** Retrieve a record from the %_data table.
  183989. **
  183990. ** If an error occurs, NULL is returned and an error left in the
  183991. ** Fts5Index object.
  183992. */
  183993. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  183994. Fts5Data *pRet = 0;
  183995. if( p->rc==SQLITE_OK ){
  183996. int rc = SQLITE_OK;
  183997. if( p->pReader ){
  183998. /* This call may return SQLITE_ABORT if there has been a savepoint
  183999. ** rollback since it was last used. In this case a new blob handle
  184000. ** is required. */
  184001. sqlite3_blob *pBlob = p->pReader;
  184002. p->pReader = 0;
  184003. rc = sqlite3_blob_reopen(pBlob, iRowid);
  184004. assert( p->pReader==0 );
  184005. p->pReader = pBlob;
  184006. if( rc!=SQLITE_OK ){
  184007. fts5CloseReader(p);
  184008. }
  184009. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  184010. }
  184011. /* If the blob handle is not open at this point, open it and seek
  184012. ** to the requested entry. */
  184013. if( p->pReader==0 && rc==SQLITE_OK ){
  184014. Fts5Config *pConfig = p->pConfig;
  184015. rc = sqlite3_blob_open(pConfig->db,
  184016. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  184017. );
  184018. }
  184019. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  184020. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  184021. ** All the reasons those functions might return SQLITE_ERROR - missing
  184022. ** table, missing row, non-blob/text in block column - indicate
  184023. ** backing store corruption. */
  184024. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  184025. if( rc==SQLITE_OK ){
  184026. u8 *aOut = 0; /* Read blob data into this buffer */
  184027. int nByte = sqlite3_blob_bytes(p->pReader);
  184028. int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  184029. pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
  184030. if( pRet ){
  184031. pRet->nn = nByte;
  184032. aOut = pRet->p = (u8*)&pRet[1];
  184033. }else{
  184034. rc = SQLITE_NOMEM;
  184035. }
  184036. if( rc==SQLITE_OK ){
  184037. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  184038. }
  184039. if( rc!=SQLITE_OK ){
  184040. sqlite3_free(pRet);
  184041. pRet = 0;
  184042. }else{
  184043. /* TODO1: Fix this */
  184044. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  184045. }
  184046. }
  184047. p->rc = rc;
  184048. p->nRead++;
  184049. }
  184050. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  184051. return pRet;
  184052. }
  184053. /*
  184054. ** Release a reference to data record returned by an earlier call to
  184055. ** fts5DataRead().
  184056. */
  184057. static void fts5DataRelease(Fts5Data *pData){
  184058. sqlite3_free(pData);
  184059. }
  184060. static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
  184061. Fts5Data *pRet = fts5DataRead(p, iRowid);
  184062. if( pRet ){
  184063. if( pRet->szLeaf>pRet->nn ){
  184064. p->rc = FTS5_CORRUPT;
  184065. fts5DataRelease(pRet);
  184066. pRet = 0;
  184067. }
  184068. }
  184069. return pRet;
  184070. }
  184071. static int fts5IndexPrepareStmt(
  184072. Fts5Index *p,
  184073. sqlite3_stmt **ppStmt,
  184074. char *zSql
  184075. ){
  184076. if( p->rc==SQLITE_OK ){
  184077. if( zSql ){
  184078. p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
  184079. SQLITE_PREPARE_PERSISTENT, ppStmt, 0);
  184080. }else{
  184081. p->rc = SQLITE_NOMEM;
  184082. }
  184083. }
  184084. sqlite3_free(zSql);
  184085. return p->rc;
  184086. }
  184087. /*
  184088. ** INSERT OR REPLACE a record into the %_data table.
  184089. */
  184090. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  184091. if( p->rc!=SQLITE_OK ) return;
  184092. if( p->pWriter==0 ){
  184093. Fts5Config *pConfig = p->pConfig;
  184094. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  184095. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  184096. pConfig->zDb, pConfig->zName
  184097. ));
  184098. if( p->rc ) return;
  184099. }
  184100. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  184101. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  184102. sqlite3_step(p->pWriter);
  184103. p->rc = sqlite3_reset(p->pWriter);
  184104. sqlite3_bind_null(p->pWriter, 2);
  184105. }
  184106. /*
  184107. ** Execute the following SQL:
  184108. **
  184109. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  184110. */
  184111. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  184112. if( p->rc!=SQLITE_OK ) return;
  184113. if( p->pDeleter==0 ){
  184114. int rc;
  184115. Fts5Config *pConfig = p->pConfig;
  184116. char *zSql = sqlite3_mprintf(
  184117. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  184118. pConfig->zDb, pConfig->zName
  184119. );
  184120. if( zSql==0 ){
  184121. rc = SQLITE_NOMEM;
  184122. }else{
  184123. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  184124. SQLITE_PREPARE_PERSISTENT, &p->pDeleter, 0);
  184125. sqlite3_free(zSql);
  184126. }
  184127. if( rc!=SQLITE_OK ){
  184128. p->rc = rc;
  184129. return;
  184130. }
  184131. }
  184132. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  184133. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  184134. sqlite3_step(p->pDeleter);
  184135. p->rc = sqlite3_reset(p->pDeleter);
  184136. }
  184137. /*
  184138. ** Remove all records associated with segment iSegid.
  184139. */
  184140. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  184141. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  184142. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  184143. fts5DataDelete(p, iFirst, iLast);
  184144. if( p->pIdxDeleter==0 ){
  184145. Fts5Config *pConfig = p->pConfig;
  184146. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  184147. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  184148. pConfig->zDb, pConfig->zName
  184149. ));
  184150. }
  184151. if( p->rc==SQLITE_OK ){
  184152. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  184153. sqlite3_step(p->pIdxDeleter);
  184154. p->rc = sqlite3_reset(p->pIdxDeleter);
  184155. }
  184156. }
  184157. /*
  184158. ** Release a reference to an Fts5Structure object returned by an earlier
  184159. ** call to fts5StructureRead() or fts5StructureDecode().
  184160. */
  184161. static void fts5StructureRelease(Fts5Structure *pStruct){
  184162. if( pStruct && 0>=(--pStruct->nRef) ){
  184163. int i;
  184164. assert( pStruct->nRef==0 );
  184165. for(i=0; i<pStruct->nLevel; i++){
  184166. sqlite3_free(pStruct->aLevel[i].aSeg);
  184167. }
  184168. sqlite3_free(pStruct);
  184169. }
  184170. }
  184171. static void fts5StructureRef(Fts5Structure *pStruct){
  184172. pStruct->nRef++;
  184173. }
  184174. /*
  184175. ** Deserialize and return the structure record currently stored in serialized
  184176. ** form within buffer pData/nData.
  184177. **
  184178. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  184179. ** are over-allocated by one slot. This allows the structure contents
  184180. ** to be more easily edited.
  184181. **
  184182. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  184183. ** returned. Otherwise, *ppOut is set to point to the new object and
  184184. ** SQLITE_OK returned.
  184185. */
  184186. static int fts5StructureDecode(
  184187. const u8 *pData, /* Buffer containing serialized structure */
  184188. int nData, /* Size of buffer pData in bytes */
  184189. int *piCookie, /* Configuration cookie value */
  184190. Fts5Structure **ppOut /* OUT: Deserialized object */
  184191. ){
  184192. int rc = SQLITE_OK;
  184193. int i = 0;
  184194. int iLvl;
  184195. int nLevel = 0;
  184196. int nSegment = 0;
  184197. int nByte; /* Bytes of space to allocate at pRet */
  184198. Fts5Structure *pRet = 0; /* Structure object to return */
  184199. /* Grab the cookie value */
  184200. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  184201. i = 4;
  184202. /* Read the total number of levels and segments from the start of the
  184203. ** structure record. */
  184204. i += fts5GetVarint32(&pData[i], nLevel);
  184205. i += fts5GetVarint32(&pData[i], nSegment);
  184206. nByte = (
  184207. sizeof(Fts5Structure) + /* Main structure */
  184208. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  184209. );
  184210. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  184211. if( pRet ){
  184212. pRet->nRef = 1;
  184213. pRet->nLevel = nLevel;
  184214. pRet->nSegment = nSegment;
  184215. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  184216. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  184217. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  184218. int nTotal = 0;
  184219. int iSeg;
  184220. if( i>=nData ){
  184221. rc = FTS5_CORRUPT;
  184222. }else{
  184223. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  184224. i += fts5GetVarint32(&pData[i], nTotal);
  184225. assert( nTotal>=pLvl->nMerge );
  184226. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  184227. nTotal * sizeof(Fts5StructureSegment)
  184228. );
  184229. }
  184230. if( rc==SQLITE_OK ){
  184231. pLvl->nSeg = nTotal;
  184232. for(iSeg=0; iSeg<nTotal; iSeg++){
  184233. if( i>=nData ){
  184234. rc = FTS5_CORRUPT;
  184235. break;
  184236. }
  184237. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
  184238. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
  184239. i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
  184240. }
  184241. }
  184242. }
  184243. if( rc!=SQLITE_OK ){
  184244. fts5StructureRelease(pRet);
  184245. pRet = 0;
  184246. }
  184247. }
  184248. *ppOut = pRet;
  184249. return rc;
  184250. }
  184251. /*
  184252. **
  184253. */
  184254. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  184255. if( *pRc==SQLITE_OK ){
  184256. Fts5Structure *pStruct = *ppStruct;
  184257. int nLevel = pStruct->nLevel;
  184258. int nByte = (
  184259. sizeof(Fts5Structure) + /* Main structure */
  184260. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  184261. );
  184262. pStruct = sqlite3_realloc(pStruct, nByte);
  184263. if( pStruct ){
  184264. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  184265. pStruct->nLevel++;
  184266. *ppStruct = pStruct;
  184267. }else{
  184268. *pRc = SQLITE_NOMEM;
  184269. }
  184270. }
  184271. }
  184272. /*
  184273. ** Extend level iLvl so that there is room for at least nExtra more
  184274. ** segments.
  184275. */
  184276. static void fts5StructureExtendLevel(
  184277. int *pRc,
  184278. Fts5Structure *pStruct,
  184279. int iLvl,
  184280. int nExtra,
  184281. int bInsert
  184282. ){
  184283. if( *pRc==SQLITE_OK ){
  184284. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  184285. Fts5StructureSegment *aNew;
  184286. int nByte;
  184287. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  184288. aNew = sqlite3_realloc(pLvl->aSeg, nByte);
  184289. if( aNew ){
  184290. if( bInsert==0 ){
  184291. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  184292. }else{
  184293. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  184294. memmove(&aNew[nExtra], aNew, nMove);
  184295. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  184296. }
  184297. pLvl->aSeg = aNew;
  184298. }else{
  184299. *pRc = SQLITE_NOMEM;
  184300. }
  184301. }
  184302. }
  184303. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  184304. Fts5Structure *pRet = 0;
  184305. Fts5Config *pConfig = p->pConfig;
  184306. int iCookie; /* Configuration cookie */
  184307. Fts5Data *pData;
  184308. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  184309. if( p->rc==SQLITE_OK ){
  184310. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  184311. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  184312. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  184313. if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
  184314. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  184315. }
  184316. fts5DataRelease(pData);
  184317. if( p->rc!=SQLITE_OK ){
  184318. fts5StructureRelease(pRet);
  184319. pRet = 0;
  184320. }
  184321. }
  184322. return pRet;
  184323. }
  184324. static i64 fts5IndexDataVersion(Fts5Index *p){
  184325. i64 iVersion = 0;
  184326. if( p->rc==SQLITE_OK ){
  184327. if( p->pDataVersion==0 ){
  184328. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  184329. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  184330. );
  184331. if( p->rc ) return 0;
  184332. }
  184333. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  184334. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  184335. }
  184336. p->rc = sqlite3_reset(p->pDataVersion);
  184337. }
  184338. return iVersion;
  184339. }
  184340. /*
  184341. ** Read, deserialize and return the structure record.
  184342. **
  184343. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  184344. ** are over-allocated as described for function fts5StructureDecode()
  184345. ** above.
  184346. **
  184347. ** If an error occurs, NULL is returned and an error code left in the
  184348. ** Fts5Index handle. If an error has already occurred when this function
  184349. ** is called, it is a no-op.
  184350. */
  184351. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  184352. if( p->pStruct==0 ){
  184353. p->iStructVersion = fts5IndexDataVersion(p);
  184354. if( p->rc==SQLITE_OK ){
  184355. p->pStruct = fts5StructureReadUncached(p);
  184356. }
  184357. }
  184358. #if 0
  184359. else{
  184360. Fts5Structure *pTest = fts5StructureReadUncached(p);
  184361. if( pTest ){
  184362. int i, j;
  184363. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  184364. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  184365. for(i=0; i<pTest->nLevel; i++){
  184366. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  184367. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  184368. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  184369. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  184370. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  184371. assert_nc( p1->iSegid==p2->iSegid );
  184372. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  184373. assert_nc( p1->pgnoLast==p2->pgnoLast );
  184374. }
  184375. }
  184376. fts5StructureRelease(pTest);
  184377. }
  184378. }
  184379. #endif
  184380. if( p->rc!=SQLITE_OK ) return 0;
  184381. assert( p->iStructVersion!=0 );
  184382. assert( p->pStruct!=0 );
  184383. fts5StructureRef(p->pStruct);
  184384. return p->pStruct;
  184385. }
  184386. static void fts5StructureInvalidate(Fts5Index *p){
  184387. if( p->pStruct ){
  184388. fts5StructureRelease(p->pStruct);
  184389. p->pStruct = 0;
  184390. }
  184391. }
  184392. /*
  184393. ** Return the total number of segments in index structure pStruct. This
  184394. ** function is only ever used as part of assert() conditions.
  184395. */
  184396. #ifdef SQLITE_DEBUG
  184397. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  184398. int nSegment = 0; /* Total number of segments */
  184399. if( pStruct ){
  184400. int iLvl; /* Used to iterate through levels */
  184401. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  184402. nSegment += pStruct->aLevel[iLvl].nSeg;
  184403. }
  184404. }
  184405. return nSegment;
  184406. }
  184407. #endif
  184408. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  184409. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  184410. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  184411. (pBuf)->n += nBlob; \
  184412. }
  184413. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  184414. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  184415. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  184416. }
  184417. /*
  184418. ** Serialize and store the "structure" record.
  184419. **
  184420. ** If an error occurs, leave an error code in the Fts5Index object. If an
  184421. ** error has already occurred, this function is a no-op.
  184422. */
  184423. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  184424. if( p->rc==SQLITE_OK ){
  184425. Fts5Buffer buf; /* Buffer to serialize record into */
  184426. int iLvl; /* Used to iterate through levels */
  184427. int iCookie; /* Cookie value to store */
  184428. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  184429. memset(&buf, 0, sizeof(Fts5Buffer));
  184430. /* Append the current configuration cookie */
  184431. iCookie = p->pConfig->iCookie;
  184432. if( iCookie<0 ) iCookie = 0;
  184433. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  184434. sqlite3Fts5Put32(buf.p, iCookie);
  184435. buf.n = 4;
  184436. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  184437. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  184438. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  184439. }
  184440. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  184441. int iSeg; /* Used to iterate through segments */
  184442. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  184443. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  184444. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  184445. assert( pLvl->nMerge<=pLvl->nSeg );
  184446. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  184447. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  184448. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  184449. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  184450. }
  184451. }
  184452. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  184453. fts5BufferFree(&buf);
  184454. }
  184455. }
  184456. #if 0
  184457. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  184458. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  184459. int rc = SQLITE_OK;
  184460. Fts5Buffer buf;
  184461. memset(&buf, 0, sizeof(buf));
  184462. fts5DebugStructure(&rc, &buf, pStruct);
  184463. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  184464. fflush(stdout);
  184465. fts5BufferFree(&buf);
  184466. }
  184467. #else
  184468. # define fts5PrintStructure(x,y)
  184469. #endif
  184470. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  184471. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  184472. }
  184473. /*
  184474. ** Return a copy of index structure pStruct. Except, promote as many
  184475. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  184476. ** returned.
  184477. */
  184478. static void fts5StructurePromoteTo(
  184479. Fts5Index *p,
  184480. int iPromote,
  184481. int szPromote,
  184482. Fts5Structure *pStruct
  184483. ){
  184484. int il, is;
  184485. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  184486. if( pOut->nMerge==0 ){
  184487. for(il=iPromote+1; il<pStruct->nLevel; il++){
  184488. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  184489. if( pLvl->nMerge ) return;
  184490. for(is=pLvl->nSeg-1; is>=0; is--){
  184491. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  184492. if( sz>szPromote ) return;
  184493. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  184494. if( p->rc ) return;
  184495. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  184496. pOut->nSeg++;
  184497. pLvl->nSeg--;
  184498. }
  184499. }
  184500. }
  184501. }
  184502. /*
  184503. ** A new segment has just been written to level iLvl of index structure
  184504. ** pStruct. This function determines if any segments should be promoted
  184505. ** as a result. Segments are promoted in two scenarios:
  184506. **
  184507. ** a) If the segment just written is smaller than one or more segments
  184508. ** within the previous populated level, it is promoted to the previous
  184509. ** populated level.
  184510. **
  184511. ** b) If the segment just written is larger than the newest segment on
  184512. ** the next populated level, then that segment, and any other adjacent
  184513. ** segments that are also smaller than the one just written, are
  184514. ** promoted.
  184515. **
  184516. ** If one or more segments are promoted, the structure object is updated
  184517. ** to reflect this.
  184518. */
  184519. static void fts5StructurePromote(
  184520. Fts5Index *p, /* FTS5 backend object */
  184521. int iLvl, /* Index level just updated */
  184522. Fts5Structure *pStruct /* Index structure */
  184523. ){
  184524. if( p->rc==SQLITE_OK ){
  184525. int iTst;
  184526. int iPromote = -1;
  184527. int szPromote = 0; /* Promote anything this size or smaller */
  184528. Fts5StructureSegment *pSeg; /* Segment just written */
  184529. int szSeg; /* Size of segment just written */
  184530. int nSeg = pStruct->aLevel[iLvl].nSeg;
  184531. if( nSeg==0 ) return;
  184532. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  184533. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  184534. /* Check for condition (a) */
  184535. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  184536. if( iTst>=0 ){
  184537. int i;
  184538. int szMax = 0;
  184539. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  184540. assert( pTst->nMerge==0 );
  184541. for(i=0; i<pTst->nSeg; i++){
  184542. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  184543. if( sz>szMax ) szMax = sz;
  184544. }
  184545. if( szMax>=szSeg ){
  184546. /* Condition (a) is true. Promote the newest segment on level
  184547. ** iLvl to level iTst. */
  184548. iPromote = iTst;
  184549. szPromote = szMax;
  184550. }
  184551. }
  184552. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  184553. ** is a no-op if it is not. */
  184554. if( iPromote<0 ){
  184555. iPromote = iLvl;
  184556. szPromote = szSeg;
  184557. }
  184558. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  184559. }
  184560. }
  184561. /*
  184562. ** Advance the iterator passed as the only argument. If the end of the
  184563. ** doclist-index page is reached, return non-zero.
  184564. */
  184565. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  184566. Fts5Data *pData = pLvl->pData;
  184567. if( pLvl->iOff==0 ){
  184568. assert( pLvl->bEof==0 );
  184569. pLvl->iOff = 1;
  184570. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  184571. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  184572. pLvl->iFirstOff = pLvl->iOff;
  184573. }else{
  184574. int iOff;
  184575. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  184576. if( pData->p[iOff] ) break;
  184577. }
  184578. if( iOff<pData->nn ){
  184579. i64 iVal;
  184580. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  184581. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  184582. pLvl->iRowid += iVal;
  184583. pLvl->iOff = iOff;
  184584. }else{
  184585. pLvl->bEof = 1;
  184586. }
  184587. }
  184588. return pLvl->bEof;
  184589. }
  184590. /*
  184591. ** Advance the iterator passed as the only argument.
  184592. */
  184593. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  184594. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  184595. assert( iLvl<pIter->nLvl );
  184596. if( fts5DlidxLvlNext(pLvl) ){
  184597. if( (iLvl+1) < pIter->nLvl ){
  184598. fts5DlidxIterNextR(p, pIter, iLvl+1);
  184599. if( pLvl[1].bEof==0 ){
  184600. fts5DataRelease(pLvl->pData);
  184601. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  184602. pLvl->pData = fts5DataRead(p,
  184603. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  184604. );
  184605. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  184606. }
  184607. }
  184608. }
  184609. return pIter->aLvl[0].bEof;
  184610. }
  184611. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  184612. return fts5DlidxIterNextR(p, pIter, 0);
  184613. }
  184614. /*
  184615. ** The iterator passed as the first argument has the following fields set
  184616. ** as follows. This function sets up the rest of the iterator so that it
  184617. ** points to the first rowid in the doclist-index.
  184618. **
  184619. ** pData:
  184620. ** pointer to doclist-index record,
  184621. **
  184622. ** When this function is called pIter->iLeafPgno is the page number the
  184623. ** doclist is associated with (the one featuring the term).
  184624. */
  184625. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  184626. int i;
  184627. for(i=0; i<pIter->nLvl; i++){
  184628. fts5DlidxLvlNext(&pIter->aLvl[i]);
  184629. }
  184630. return pIter->aLvl[0].bEof;
  184631. }
  184632. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  184633. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  184634. }
  184635. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  184636. int i;
  184637. /* Advance each level to the last entry on the last page */
  184638. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  184639. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  184640. while( fts5DlidxLvlNext(pLvl)==0 );
  184641. pLvl->bEof = 0;
  184642. if( i>0 ){
  184643. Fts5DlidxLvl *pChild = &pLvl[-1];
  184644. fts5DataRelease(pChild->pData);
  184645. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  184646. pChild->pData = fts5DataRead(p,
  184647. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  184648. );
  184649. }
  184650. }
  184651. }
  184652. /*
  184653. ** Move the iterator passed as the only argument to the previous entry.
  184654. */
  184655. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  184656. int iOff = pLvl->iOff;
  184657. assert( pLvl->bEof==0 );
  184658. if( iOff<=pLvl->iFirstOff ){
  184659. pLvl->bEof = 1;
  184660. }else{
  184661. u8 *a = pLvl->pData->p;
  184662. i64 iVal;
  184663. int iLimit;
  184664. int ii;
  184665. int nZero = 0;
  184666. /* Currently iOff points to the first byte of a varint. This block
  184667. ** decrements iOff until it points to the first byte of the previous
  184668. ** varint. Taking care not to read any memory locations that occur
  184669. ** before the buffer in memory. */
  184670. iLimit = (iOff>9 ? iOff-9 : 0);
  184671. for(iOff--; iOff>iLimit; iOff--){
  184672. if( (a[iOff-1] & 0x80)==0 ) break;
  184673. }
  184674. fts5GetVarint(&a[iOff], (u64*)&iVal);
  184675. pLvl->iRowid -= iVal;
  184676. pLvl->iLeafPgno--;
  184677. /* Skip backwards past any 0x00 varints. */
  184678. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  184679. nZero++;
  184680. }
  184681. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  184682. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  184683. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  184684. ** bytes before a[ii]. */
  184685. int bZero = 0; /* True if last 0x00 counts */
  184686. if( (ii-8)>=pLvl->iFirstOff ){
  184687. int j;
  184688. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  184689. bZero = (j>8);
  184690. }
  184691. if( bZero==0 ) nZero--;
  184692. }
  184693. pLvl->iLeafPgno -= nZero;
  184694. pLvl->iOff = iOff - nZero;
  184695. }
  184696. return pLvl->bEof;
  184697. }
  184698. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  184699. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  184700. assert( iLvl<pIter->nLvl );
  184701. if( fts5DlidxLvlPrev(pLvl) ){
  184702. if( (iLvl+1) < pIter->nLvl ){
  184703. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  184704. if( pLvl[1].bEof==0 ){
  184705. fts5DataRelease(pLvl->pData);
  184706. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  184707. pLvl->pData = fts5DataRead(p,
  184708. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  184709. );
  184710. if( pLvl->pData ){
  184711. while( fts5DlidxLvlNext(pLvl)==0 );
  184712. pLvl->bEof = 0;
  184713. }
  184714. }
  184715. }
  184716. }
  184717. return pIter->aLvl[0].bEof;
  184718. }
  184719. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  184720. return fts5DlidxIterPrevR(p, pIter, 0);
  184721. }
  184722. /*
  184723. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  184724. */
  184725. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  184726. if( pIter ){
  184727. int i;
  184728. for(i=0; i<pIter->nLvl; i++){
  184729. fts5DataRelease(pIter->aLvl[i].pData);
  184730. }
  184731. sqlite3_free(pIter);
  184732. }
  184733. }
  184734. static Fts5DlidxIter *fts5DlidxIterInit(
  184735. Fts5Index *p, /* Fts5 Backend to iterate within */
  184736. int bRev, /* True for ORDER BY ASC */
  184737. int iSegid, /* Segment id */
  184738. int iLeafPg /* Leaf page number to load dlidx for */
  184739. ){
  184740. Fts5DlidxIter *pIter = 0;
  184741. int i;
  184742. int bDone = 0;
  184743. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  184744. int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  184745. Fts5DlidxIter *pNew;
  184746. pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
  184747. if( pNew==0 ){
  184748. p->rc = SQLITE_NOMEM;
  184749. }else{
  184750. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  184751. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  184752. pIter = pNew;
  184753. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  184754. pLvl->pData = fts5DataRead(p, iRowid);
  184755. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  184756. bDone = 1;
  184757. }
  184758. pIter->nLvl = i+1;
  184759. }
  184760. }
  184761. if( p->rc==SQLITE_OK ){
  184762. pIter->iSegid = iSegid;
  184763. if( bRev==0 ){
  184764. fts5DlidxIterFirst(pIter);
  184765. }else{
  184766. fts5DlidxIterLast(p, pIter);
  184767. }
  184768. }
  184769. if( p->rc!=SQLITE_OK ){
  184770. fts5DlidxIterFree(pIter);
  184771. pIter = 0;
  184772. }
  184773. return pIter;
  184774. }
  184775. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  184776. return pIter->aLvl[0].iRowid;
  184777. }
  184778. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  184779. return pIter->aLvl[0].iLeafPgno;
  184780. }
  184781. /*
  184782. ** Load the next leaf page into the segment iterator.
  184783. */
  184784. static void fts5SegIterNextPage(
  184785. Fts5Index *p, /* FTS5 backend object */
  184786. Fts5SegIter *pIter /* Iterator to advance to next page */
  184787. ){
  184788. Fts5Data *pLeaf;
  184789. Fts5StructureSegment *pSeg = pIter->pSeg;
  184790. fts5DataRelease(pIter->pLeaf);
  184791. pIter->iLeafPgno++;
  184792. if( pIter->pNextLeaf ){
  184793. pIter->pLeaf = pIter->pNextLeaf;
  184794. pIter->pNextLeaf = 0;
  184795. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  184796. pIter->pLeaf = fts5LeafRead(p,
  184797. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  184798. );
  184799. }else{
  184800. pIter->pLeaf = 0;
  184801. }
  184802. pLeaf = pIter->pLeaf;
  184803. if( pLeaf ){
  184804. pIter->iPgidxOff = pLeaf->szLeaf;
  184805. if( fts5LeafIsTermless(pLeaf) ){
  184806. pIter->iEndofDoclist = pLeaf->nn+1;
  184807. }else{
  184808. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  184809. pIter->iEndofDoclist
  184810. );
  184811. }
  184812. }
  184813. }
  184814. /*
  184815. ** Argument p points to a buffer containing a varint to be interpreted as a
  184816. ** position list size field. Read the varint and return the number of bytes
  184817. ** read. Before returning, set *pnSz to the number of bytes in the position
  184818. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  184819. */
  184820. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  184821. int nSz;
  184822. int n = 0;
  184823. fts5FastGetVarint32(p, n, nSz);
  184824. assert_nc( nSz>=0 );
  184825. *pnSz = nSz/2;
  184826. *pbDel = nSz & 0x0001;
  184827. return n;
  184828. }
  184829. /*
  184830. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  184831. ** position-list size field. Read the value of the field and store it
  184832. ** in the following variables:
  184833. **
  184834. ** Fts5SegIter.nPos
  184835. ** Fts5SegIter.bDel
  184836. **
  184837. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  184838. ** position list content (if any).
  184839. */
  184840. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  184841. if( p->rc==SQLITE_OK ){
  184842. int iOff = pIter->iLeafOffset; /* Offset to read at */
  184843. ASSERT_SZLEAF_OK(pIter->pLeaf);
  184844. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  184845. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  184846. pIter->bDel = 0;
  184847. pIter->nPos = 1;
  184848. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  184849. pIter->bDel = 1;
  184850. iOff++;
  184851. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  184852. pIter->nPos = 1;
  184853. iOff++;
  184854. }else{
  184855. pIter->nPos = 0;
  184856. }
  184857. }
  184858. }else{
  184859. int nSz;
  184860. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  184861. pIter->bDel = (nSz & 0x0001);
  184862. pIter->nPos = nSz>>1;
  184863. assert_nc( pIter->nPos>=0 );
  184864. }
  184865. pIter->iLeafOffset = iOff;
  184866. }
  184867. }
  184868. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  184869. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  184870. int iOff = pIter->iLeafOffset;
  184871. ASSERT_SZLEAF_OK(pIter->pLeaf);
  184872. if( iOff>=pIter->pLeaf->szLeaf ){
  184873. fts5SegIterNextPage(p, pIter);
  184874. if( pIter->pLeaf==0 ){
  184875. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  184876. return;
  184877. }
  184878. iOff = 4;
  184879. a = pIter->pLeaf->p;
  184880. }
  184881. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  184882. pIter->iLeafOffset = iOff;
  184883. }
  184884. /*
  184885. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  184886. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  184887. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  184888. ** the first term in the segment).
  184889. **
  184890. ** This function populates:
  184891. **
  184892. ** Fts5SegIter.term
  184893. ** Fts5SegIter.rowid
  184894. **
  184895. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  184896. ** the first position list. The position list belonging to document
  184897. ** (Fts5SegIter.iRowid).
  184898. */
  184899. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  184900. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  184901. int iOff = pIter->iLeafOffset; /* Offset to read at */
  184902. int nNew; /* Bytes of new data */
  184903. iOff += fts5GetVarint32(&a[iOff], nNew);
  184904. if( iOff+nNew>pIter->pLeaf->nn ){
  184905. p->rc = FTS5_CORRUPT;
  184906. return;
  184907. }
  184908. pIter->term.n = nKeep;
  184909. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  184910. iOff += nNew;
  184911. pIter->iTermLeafOffset = iOff;
  184912. pIter->iTermLeafPgno = pIter->iLeafPgno;
  184913. pIter->iLeafOffset = iOff;
  184914. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  184915. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  184916. }else{
  184917. int nExtra;
  184918. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  184919. pIter->iEndofDoclist += nExtra;
  184920. }
  184921. fts5SegIterLoadRowid(p, pIter);
  184922. }
  184923. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  184924. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  184925. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  184926. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  184927. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  184928. pIter->xNext = fts5SegIterNext_Reverse;
  184929. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  184930. pIter->xNext = fts5SegIterNext_None;
  184931. }else{
  184932. pIter->xNext = fts5SegIterNext;
  184933. }
  184934. }
  184935. /*
  184936. ** Initialize the iterator object pIter to iterate through the entries in
  184937. ** segment pSeg. The iterator is left pointing to the first entry when
  184938. ** this function returns.
  184939. **
  184940. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  184941. ** an error has already occurred when this function is called, it is a no-op.
  184942. */
  184943. static void fts5SegIterInit(
  184944. Fts5Index *p, /* FTS index object */
  184945. Fts5StructureSegment *pSeg, /* Description of segment */
  184946. Fts5SegIter *pIter /* Object to populate */
  184947. ){
  184948. if( pSeg->pgnoFirst==0 ){
  184949. /* This happens if the segment is being used as an input to an incremental
  184950. ** merge and all data has already been "trimmed". See function
  184951. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  184952. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  184953. ** at EOF already. */
  184954. assert( pIter->pLeaf==0 );
  184955. return;
  184956. }
  184957. if( p->rc==SQLITE_OK ){
  184958. memset(pIter, 0, sizeof(*pIter));
  184959. fts5SegIterSetNext(p, pIter);
  184960. pIter->pSeg = pSeg;
  184961. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  184962. fts5SegIterNextPage(p, pIter);
  184963. }
  184964. if( p->rc==SQLITE_OK ){
  184965. pIter->iLeafOffset = 4;
  184966. assert_nc( pIter->pLeaf->nn>4 );
  184967. assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  184968. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  184969. fts5SegIterLoadTerm(p, pIter, 0);
  184970. fts5SegIterLoadNPos(p, pIter);
  184971. }
  184972. }
  184973. /*
  184974. ** This function is only ever called on iterators created by calls to
  184975. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  184976. **
  184977. ** The iterator is in an unusual state when this function is called: the
  184978. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  184979. ** the position-list size field for the first relevant rowid on the page.
  184980. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  184981. **
  184982. ** This function advances the iterator so that it points to the last
  184983. ** relevant rowid on the page and, if necessary, initializes the
  184984. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  184985. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  184986. ** byte of the position list content associated with said rowid.
  184987. */
  184988. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  184989. int eDetail = p->pConfig->eDetail;
  184990. int n = pIter->pLeaf->szLeaf;
  184991. int i = pIter->iLeafOffset;
  184992. u8 *a = pIter->pLeaf->p;
  184993. int iRowidOffset = 0;
  184994. if( n>pIter->iEndofDoclist ){
  184995. n = pIter->iEndofDoclist;
  184996. }
  184997. ASSERT_SZLEAF_OK(pIter->pLeaf);
  184998. while( 1 ){
  184999. i64 iDelta = 0;
  185000. if( eDetail==FTS5_DETAIL_NONE ){
  185001. /* todo */
  185002. if( i<n && a[i]==0 ){
  185003. i++;
  185004. if( i<n && a[i]==0 ) i++;
  185005. }
  185006. }else{
  185007. int nPos;
  185008. int bDummy;
  185009. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  185010. i += nPos;
  185011. }
  185012. if( i>=n ) break;
  185013. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  185014. pIter->iRowid += iDelta;
  185015. /* If necessary, grow the pIter->aRowidOffset[] array. */
  185016. if( iRowidOffset>=pIter->nRowidOffset ){
  185017. int nNew = pIter->nRowidOffset + 8;
  185018. int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
  185019. if( aNew==0 ){
  185020. p->rc = SQLITE_NOMEM;
  185021. break;
  185022. }
  185023. pIter->aRowidOffset = aNew;
  185024. pIter->nRowidOffset = nNew;
  185025. }
  185026. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  185027. pIter->iLeafOffset = i;
  185028. }
  185029. pIter->iRowidOffset = iRowidOffset;
  185030. fts5SegIterLoadNPos(p, pIter);
  185031. }
  185032. /*
  185033. **
  185034. */
  185035. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  185036. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  185037. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  185038. fts5DataRelease(pIter->pLeaf);
  185039. pIter->pLeaf = 0;
  185040. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  185041. Fts5Data *pNew;
  185042. pIter->iLeafPgno--;
  185043. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  185044. pIter->pSeg->iSegid, pIter->iLeafPgno
  185045. ));
  185046. if( pNew ){
  185047. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  185048. ** thing on the page - i.e. the first rowid is on the following page.
  185049. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  185050. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  185051. assert( pIter->pLeaf==0 );
  185052. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  185053. pIter->pLeaf = pNew;
  185054. pIter->iLeafOffset = pIter->iTermLeafOffset;
  185055. }
  185056. }else{
  185057. int iRowidOff;
  185058. iRowidOff = fts5LeafFirstRowidOff(pNew);
  185059. if( iRowidOff ){
  185060. pIter->pLeaf = pNew;
  185061. pIter->iLeafOffset = iRowidOff;
  185062. }
  185063. }
  185064. if( pIter->pLeaf ){
  185065. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  185066. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  185067. break;
  185068. }else{
  185069. fts5DataRelease(pNew);
  185070. }
  185071. }
  185072. }
  185073. if( pIter->pLeaf ){
  185074. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  185075. fts5SegIterReverseInitPage(p, pIter);
  185076. }
  185077. }
  185078. /*
  185079. ** Return true if the iterator passed as the second argument currently
  185080. ** points to a delete marker. A delete marker is an entry with a 0 byte
  185081. ** position-list.
  185082. */
  185083. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  185084. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  185085. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  185086. }
  185087. /*
  185088. ** Advance iterator pIter to the next entry.
  185089. **
  185090. ** This version of fts5SegIterNext() is only used by reverse iterators.
  185091. */
  185092. static void fts5SegIterNext_Reverse(
  185093. Fts5Index *p, /* FTS5 backend object */
  185094. Fts5SegIter *pIter, /* Iterator to advance */
  185095. int *pbUnused /* Unused */
  185096. ){
  185097. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  185098. assert( pIter->pNextLeaf==0 );
  185099. UNUSED_PARAM(pbUnused);
  185100. if( pIter->iRowidOffset>0 ){
  185101. u8 *a = pIter->pLeaf->p;
  185102. int iOff;
  185103. i64 iDelta;
  185104. pIter->iRowidOffset--;
  185105. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  185106. fts5SegIterLoadNPos(p, pIter);
  185107. iOff = pIter->iLeafOffset;
  185108. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  185109. iOff += pIter->nPos;
  185110. }
  185111. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  185112. pIter->iRowid -= iDelta;
  185113. }else{
  185114. fts5SegIterReverseNewPage(p, pIter);
  185115. }
  185116. }
  185117. /*
  185118. ** Advance iterator pIter to the next entry.
  185119. **
  185120. ** This version of fts5SegIterNext() is only used if detail=none and the
  185121. ** iterator is not a reverse direction iterator.
  185122. */
  185123. static void fts5SegIterNext_None(
  185124. Fts5Index *p, /* FTS5 backend object */
  185125. Fts5SegIter *pIter, /* Iterator to advance */
  185126. int *pbNewTerm /* OUT: Set for new term */
  185127. ){
  185128. int iOff;
  185129. assert( p->rc==SQLITE_OK );
  185130. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  185131. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  185132. ASSERT_SZLEAF_OK(pIter->pLeaf);
  185133. iOff = pIter->iLeafOffset;
  185134. /* Next entry is on the next page */
  185135. if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  185136. fts5SegIterNextPage(p, pIter);
  185137. if( p->rc || pIter->pLeaf==0 ) return;
  185138. pIter->iRowid = 0;
  185139. iOff = 4;
  185140. }
  185141. if( iOff<pIter->iEndofDoclist ){
  185142. /* Next entry is on the current page */
  185143. i64 iDelta;
  185144. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  185145. pIter->iLeafOffset = iOff;
  185146. pIter->iRowid += iDelta;
  185147. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  185148. if( pIter->pSeg ){
  185149. int nKeep = 0;
  185150. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  185151. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  185152. }
  185153. pIter->iLeafOffset = iOff;
  185154. fts5SegIterLoadTerm(p, pIter, nKeep);
  185155. }else{
  185156. const u8 *pList = 0;
  185157. const char *zTerm = 0;
  185158. int nList;
  185159. sqlite3Fts5HashScanNext(p->pHash);
  185160. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  185161. if( pList==0 ) goto next_none_eof;
  185162. pIter->pLeaf->p = (u8*)pList;
  185163. pIter->pLeaf->nn = nList;
  185164. pIter->pLeaf->szLeaf = nList;
  185165. pIter->iEndofDoclist = nList;
  185166. sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
  185167. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  185168. }
  185169. if( pbNewTerm ) *pbNewTerm = 1;
  185170. }else{
  185171. goto next_none_eof;
  185172. }
  185173. fts5SegIterLoadNPos(p, pIter);
  185174. return;
  185175. next_none_eof:
  185176. fts5DataRelease(pIter->pLeaf);
  185177. pIter->pLeaf = 0;
  185178. }
  185179. /*
  185180. ** Advance iterator pIter to the next entry.
  185181. **
  185182. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  185183. ** is not considered an error if the iterator reaches EOF. If an error has
  185184. ** already occurred when this function is called, it is a no-op.
  185185. */
  185186. static void fts5SegIterNext(
  185187. Fts5Index *p, /* FTS5 backend object */
  185188. Fts5SegIter *pIter, /* Iterator to advance */
  185189. int *pbNewTerm /* OUT: Set for new term */
  185190. ){
  185191. Fts5Data *pLeaf = pIter->pLeaf;
  185192. int iOff;
  185193. int bNewTerm = 0;
  185194. int nKeep = 0;
  185195. u8 *a;
  185196. int n;
  185197. assert( pbNewTerm==0 || *pbNewTerm==0 );
  185198. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  185199. /* Search for the end of the position list within the current page. */
  185200. a = pLeaf->p;
  185201. n = pLeaf->szLeaf;
  185202. ASSERT_SZLEAF_OK(pLeaf);
  185203. iOff = pIter->iLeafOffset + pIter->nPos;
  185204. if( iOff<n ){
  185205. /* The next entry is on the current page. */
  185206. assert_nc( iOff<=pIter->iEndofDoclist );
  185207. if( iOff>=pIter->iEndofDoclist ){
  185208. bNewTerm = 1;
  185209. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  185210. iOff += fts5GetVarint32(&a[iOff], nKeep);
  185211. }
  185212. }else{
  185213. u64 iDelta;
  185214. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  185215. pIter->iRowid += iDelta;
  185216. assert_nc( iDelta>0 );
  185217. }
  185218. pIter->iLeafOffset = iOff;
  185219. }else if( pIter->pSeg==0 ){
  185220. const u8 *pList = 0;
  185221. const char *zTerm = 0;
  185222. int nList = 0;
  185223. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  185224. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  185225. sqlite3Fts5HashScanNext(p->pHash);
  185226. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  185227. }
  185228. if( pList==0 ){
  185229. fts5DataRelease(pIter->pLeaf);
  185230. pIter->pLeaf = 0;
  185231. }else{
  185232. pIter->pLeaf->p = (u8*)pList;
  185233. pIter->pLeaf->nn = nList;
  185234. pIter->pLeaf->szLeaf = nList;
  185235. pIter->iEndofDoclist = nList+1;
  185236. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  185237. (u8*)zTerm);
  185238. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  185239. *pbNewTerm = 1;
  185240. }
  185241. }else{
  185242. iOff = 0;
  185243. /* Next entry is not on the current page */
  185244. while( iOff==0 ){
  185245. fts5SegIterNextPage(p, pIter);
  185246. pLeaf = pIter->pLeaf;
  185247. if( pLeaf==0 ) break;
  185248. ASSERT_SZLEAF_OK(pLeaf);
  185249. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  185250. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  185251. pIter->iLeafOffset = iOff;
  185252. if( pLeaf->nn>pLeaf->szLeaf ){
  185253. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  185254. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  185255. );
  185256. }
  185257. }
  185258. else if( pLeaf->nn>pLeaf->szLeaf ){
  185259. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  185260. &pLeaf->p[pLeaf->szLeaf], iOff
  185261. );
  185262. pIter->iLeafOffset = iOff;
  185263. pIter->iEndofDoclist = iOff;
  185264. bNewTerm = 1;
  185265. }
  185266. assert_nc( iOff<pLeaf->szLeaf );
  185267. if( iOff>pLeaf->szLeaf ){
  185268. p->rc = FTS5_CORRUPT;
  185269. return;
  185270. }
  185271. }
  185272. }
  185273. /* Check if the iterator is now at EOF. If so, return early. */
  185274. if( pIter->pLeaf ){
  185275. if( bNewTerm ){
  185276. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  185277. fts5DataRelease(pIter->pLeaf);
  185278. pIter->pLeaf = 0;
  185279. }else{
  185280. fts5SegIterLoadTerm(p, pIter, nKeep);
  185281. fts5SegIterLoadNPos(p, pIter);
  185282. if( pbNewTerm ) *pbNewTerm = 1;
  185283. }
  185284. }else{
  185285. /* The following could be done by calling fts5SegIterLoadNPos(). But
  185286. ** this block is particularly performance critical, so equivalent
  185287. ** code is inlined.
  185288. **
  185289. ** Later: Switched back to fts5SegIterLoadNPos() because it supports
  185290. ** detail=none mode. Not ideal.
  185291. */
  185292. int nSz;
  185293. assert( p->rc==SQLITE_OK );
  185294. assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
  185295. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  185296. pIter->bDel = (nSz & 0x0001);
  185297. pIter->nPos = nSz>>1;
  185298. assert_nc( pIter->nPos>=0 );
  185299. }
  185300. }
  185301. }
  185302. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  185303. #define fts5IndexSkipVarint(a, iOff) { \
  185304. int iEnd = iOff+9; \
  185305. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  185306. }
  185307. /*
  185308. ** Iterator pIter currently points to the first rowid in a doclist. This
  185309. ** function sets the iterator up so that iterates in reverse order through
  185310. ** the doclist.
  185311. */
  185312. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  185313. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  185314. Fts5Data *pLast = 0;
  185315. int pgnoLast = 0;
  185316. if( pDlidx ){
  185317. int iSegid = pIter->pSeg->iSegid;
  185318. pgnoLast = fts5DlidxIterPgno(pDlidx);
  185319. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  185320. }else{
  185321. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  185322. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  185323. ** position-list content for the current rowid. Back it up so that it
  185324. ** points to the start of the position-list size field. */
  185325. int iPoslist;
  185326. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  185327. iPoslist = pIter->iTermLeafOffset;
  185328. }else{
  185329. iPoslist = 4;
  185330. }
  185331. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  185332. pIter->iLeafOffset = iPoslist;
  185333. /* If this condition is true then the largest rowid for the current
  185334. ** term may not be stored on the current page. So search forward to
  185335. ** see where said rowid really is. */
  185336. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  185337. int pgno;
  185338. Fts5StructureSegment *pSeg = pIter->pSeg;
  185339. /* The last rowid in the doclist may not be on the current page. Search
  185340. ** forward to find the page containing the last rowid. */
  185341. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  185342. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  185343. Fts5Data *pNew = fts5DataRead(p, iAbs);
  185344. if( pNew ){
  185345. int iRowid, bTermless;
  185346. iRowid = fts5LeafFirstRowidOff(pNew);
  185347. bTermless = fts5LeafIsTermless(pNew);
  185348. if( iRowid ){
  185349. SWAPVAL(Fts5Data*, pNew, pLast);
  185350. pgnoLast = pgno;
  185351. }
  185352. fts5DataRelease(pNew);
  185353. if( bTermless==0 ) break;
  185354. }
  185355. }
  185356. }
  185357. }
  185358. /* If pLast is NULL at this point, then the last rowid for this doclist
  185359. ** lies on the page currently indicated by the iterator. In this case
  185360. ** pIter->iLeafOffset is already set to point to the position-list size
  185361. ** field associated with the first relevant rowid on the page.
  185362. **
  185363. ** Or, if pLast is non-NULL, then it is the page that contains the last
  185364. ** rowid. In this case configure the iterator so that it points to the
  185365. ** first rowid on this page.
  185366. */
  185367. if( pLast ){
  185368. int iOff;
  185369. fts5DataRelease(pIter->pLeaf);
  185370. pIter->pLeaf = pLast;
  185371. pIter->iLeafPgno = pgnoLast;
  185372. iOff = fts5LeafFirstRowidOff(pLast);
  185373. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  185374. pIter->iLeafOffset = iOff;
  185375. if( fts5LeafIsTermless(pLast) ){
  185376. pIter->iEndofDoclist = pLast->nn+1;
  185377. }else{
  185378. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  185379. }
  185380. }
  185381. fts5SegIterReverseInitPage(p, pIter);
  185382. }
  185383. /*
  185384. ** Iterator pIter currently points to the first rowid of a doclist.
  185385. ** There is a doclist-index associated with the final term on the current
  185386. ** page. If the current term is the last term on the page, load the
  185387. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  185388. */
  185389. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  185390. int iSeg = pIter->pSeg->iSegid;
  185391. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  185392. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  185393. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  185394. assert( pIter->pDlidx==0 );
  185395. /* Check if the current doclist ends on this page. If it does, return
  185396. ** early without loading the doclist-index (as it belongs to a different
  185397. ** term. */
  185398. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  185399. && pIter->iEndofDoclist<pLeaf->szLeaf
  185400. ){
  185401. return;
  185402. }
  185403. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  185404. }
  185405. /*
  185406. ** The iterator object passed as the second argument currently contains
  185407. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  185408. ** function searches the leaf page for a term matching (pTerm/nTerm).
  185409. **
  185410. ** If the specified term is found on the page, then the iterator is left
  185411. ** pointing to it. If argument bGe is zero and the term is not found,
  185412. ** the iterator is left pointing at EOF.
  185413. **
  185414. ** If bGe is non-zero and the specified term is not found, then the
  185415. ** iterator is left pointing to the smallest term in the segment that
  185416. ** is larger than the specified term, even if this term is not on the
  185417. ** current page.
  185418. */
  185419. static void fts5LeafSeek(
  185420. Fts5Index *p, /* Leave any error code here */
  185421. int bGe, /* True for a >= search */
  185422. Fts5SegIter *pIter, /* Iterator to seek */
  185423. const u8 *pTerm, int nTerm /* Term to search for */
  185424. ){
  185425. int iOff;
  185426. const u8 *a = pIter->pLeaf->p;
  185427. int szLeaf = pIter->pLeaf->szLeaf;
  185428. int n = pIter->pLeaf->nn;
  185429. int nMatch = 0;
  185430. int nKeep = 0;
  185431. int nNew = 0;
  185432. int iTermOff;
  185433. int iPgidx; /* Current offset in pgidx */
  185434. int bEndOfPage = 0;
  185435. assert( p->rc==SQLITE_OK );
  185436. iPgidx = szLeaf;
  185437. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  185438. iOff = iTermOff;
  185439. if( iOff>n ){
  185440. p->rc = FTS5_CORRUPT;
  185441. return;
  185442. }
  185443. while( 1 ){
  185444. /* Figure out how many new bytes are in this term */
  185445. fts5FastGetVarint32(a, iOff, nNew);
  185446. if( nKeep<nMatch ){
  185447. goto search_failed;
  185448. }
  185449. assert( nKeep>=nMatch );
  185450. if( nKeep==nMatch ){
  185451. int nCmp;
  185452. int i;
  185453. nCmp = MIN(nNew, nTerm-nMatch);
  185454. for(i=0; i<nCmp; i++){
  185455. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  185456. }
  185457. nMatch += i;
  185458. if( nTerm==nMatch ){
  185459. if( i==nNew ){
  185460. goto search_success;
  185461. }else{
  185462. goto search_failed;
  185463. }
  185464. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  185465. goto search_failed;
  185466. }
  185467. }
  185468. if( iPgidx>=n ){
  185469. bEndOfPage = 1;
  185470. break;
  185471. }
  185472. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  185473. iTermOff += nKeep;
  185474. iOff = iTermOff;
  185475. if( iOff>=n ){
  185476. p->rc = FTS5_CORRUPT;
  185477. return;
  185478. }
  185479. /* Read the nKeep field of the next term. */
  185480. fts5FastGetVarint32(a, iOff, nKeep);
  185481. }
  185482. search_failed:
  185483. if( bGe==0 ){
  185484. fts5DataRelease(pIter->pLeaf);
  185485. pIter->pLeaf = 0;
  185486. return;
  185487. }else if( bEndOfPage ){
  185488. do {
  185489. fts5SegIterNextPage(p, pIter);
  185490. if( pIter->pLeaf==0 ) return;
  185491. a = pIter->pLeaf->p;
  185492. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  185493. iPgidx = pIter->pLeaf->szLeaf;
  185494. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  185495. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  185496. p->rc = FTS5_CORRUPT;
  185497. }else{
  185498. nKeep = 0;
  185499. iTermOff = iOff;
  185500. n = pIter->pLeaf->nn;
  185501. iOff += fts5GetVarint32(&a[iOff], nNew);
  185502. break;
  185503. }
  185504. }
  185505. }while( 1 );
  185506. }
  185507. search_success:
  185508. pIter->iLeafOffset = iOff + nNew;
  185509. pIter->iTermLeafOffset = pIter->iLeafOffset;
  185510. pIter->iTermLeafPgno = pIter->iLeafPgno;
  185511. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  185512. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  185513. if( iPgidx>=n ){
  185514. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  185515. }else{
  185516. int nExtra;
  185517. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  185518. pIter->iEndofDoclist = iTermOff + nExtra;
  185519. }
  185520. pIter->iPgidxOff = iPgidx;
  185521. fts5SegIterLoadRowid(p, pIter);
  185522. fts5SegIterLoadNPos(p, pIter);
  185523. }
  185524. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  185525. if( p->pIdxSelect==0 ){
  185526. Fts5Config *pConfig = p->pConfig;
  185527. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  185528. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  185529. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  185530. pConfig->zDb, pConfig->zName
  185531. ));
  185532. }
  185533. return p->pIdxSelect;
  185534. }
  185535. /*
  185536. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  185537. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  185538. **
  185539. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  185540. ** an error has already occurred when this function is called, it is a no-op.
  185541. */
  185542. static void fts5SegIterSeekInit(
  185543. Fts5Index *p, /* FTS5 backend */
  185544. const u8 *pTerm, int nTerm, /* Term to seek to */
  185545. int flags, /* Mask of FTS5INDEX_XXX flags */
  185546. Fts5StructureSegment *pSeg, /* Description of segment */
  185547. Fts5SegIter *pIter /* Object to populate */
  185548. ){
  185549. int iPg = 1;
  185550. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  185551. int bDlidx = 0; /* True if there is a doclist-index */
  185552. sqlite3_stmt *pIdxSelect = 0;
  185553. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  185554. assert( pTerm && nTerm );
  185555. memset(pIter, 0, sizeof(*pIter));
  185556. pIter->pSeg = pSeg;
  185557. /* This block sets stack variable iPg to the leaf page number that may
  185558. ** contain term (pTerm/nTerm), if it is present in the segment. */
  185559. pIdxSelect = fts5IdxSelectStmt(p);
  185560. if( p->rc ) return;
  185561. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  185562. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  185563. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  185564. i64 val = sqlite3_column_int(pIdxSelect, 0);
  185565. iPg = (int)(val>>1);
  185566. bDlidx = (val & 0x0001);
  185567. }
  185568. p->rc = sqlite3_reset(pIdxSelect);
  185569. sqlite3_bind_null(pIdxSelect, 2);
  185570. if( iPg<pSeg->pgnoFirst ){
  185571. iPg = pSeg->pgnoFirst;
  185572. bDlidx = 0;
  185573. }
  185574. pIter->iLeafPgno = iPg - 1;
  185575. fts5SegIterNextPage(p, pIter);
  185576. if( pIter->pLeaf ){
  185577. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  185578. }
  185579. if( p->rc==SQLITE_OK && bGe==0 ){
  185580. pIter->flags |= FTS5_SEGITER_ONETERM;
  185581. if( pIter->pLeaf ){
  185582. if( flags & FTS5INDEX_QUERY_DESC ){
  185583. pIter->flags |= FTS5_SEGITER_REVERSE;
  185584. }
  185585. if( bDlidx ){
  185586. fts5SegIterLoadDlidx(p, pIter);
  185587. }
  185588. if( flags & FTS5INDEX_QUERY_DESC ){
  185589. fts5SegIterReverse(p, pIter);
  185590. }
  185591. }
  185592. }
  185593. fts5SegIterSetNext(p, pIter);
  185594. /* Either:
  185595. **
  185596. ** 1) an error has occurred, or
  185597. ** 2) the iterator points to EOF, or
  185598. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  185599. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  185600. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  185601. */
  185602. assert( p->rc!=SQLITE_OK /* 1 */
  185603. || pIter->pLeaf==0 /* 2 */
  185604. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  185605. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  185606. );
  185607. }
  185608. /*
  185609. ** Initialize the object pIter to point to term pTerm/nTerm within the
  185610. ** in-memory hash table. If there is no such term in the hash-table, the
  185611. ** iterator is set to EOF.
  185612. **
  185613. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  185614. ** an error has already occurred when this function is called, it is a no-op.
  185615. */
  185616. static void fts5SegIterHashInit(
  185617. Fts5Index *p, /* FTS5 backend */
  185618. const u8 *pTerm, int nTerm, /* Term to seek to */
  185619. int flags, /* Mask of FTS5INDEX_XXX flags */
  185620. Fts5SegIter *pIter /* Object to populate */
  185621. ){
  185622. const u8 *pList = 0;
  185623. int nList = 0;
  185624. const u8 *z = 0;
  185625. int n = 0;
  185626. assert( p->pHash );
  185627. assert( p->rc==SQLITE_OK );
  185628. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  185629. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  185630. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  185631. n = (z ? (int)strlen((const char*)z) : 0);
  185632. }else{
  185633. pIter->flags |= FTS5_SEGITER_ONETERM;
  185634. sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
  185635. z = pTerm;
  185636. n = nTerm;
  185637. }
  185638. if( pList ){
  185639. Fts5Data *pLeaf;
  185640. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  185641. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  185642. if( pLeaf==0 ) return;
  185643. pLeaf->p = (u8*)pList;
  185644. pLeaf->nn = pLeaf->szLeaf = nList;
  185645. pIter->pLeaf = pLeaf;
  185646. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  185647. pIter->iEndofDoclist = pLeaf->nn;
  185648. if( flags & FTS5INDEX_QUERY_DESC ){
  185649. pIter->flags |= FTS5_SEGITER_REVERSE;
  185650. fts5SegIterReverseInitPage(p, pIter);
  185651. }else{
  185652. fts5SegIterLoadNPos(p, pIter);
  185653. }
  185654. }
  185655. fts5SegIterSetNext(p, pIter);
  185656. }
  185657. /*
  185658. ** Zero the iterator passed as the only argument.
  185659. */
  185660. static void fts5SegIterClear(Fts5SegIter *pIter){
  185661. fts5BufferFree(&pIter->term);
  185662. fts5DataRelease(pIter->pLeaf);
  185663. fts5DataRelease(pIter->pNextLeaf);
  185664. fts5DlidxIterFree(pIter->pDlidx);
  185665. sqlite3_free(pIter->aRowidOffset);
  185666. memset(pIter, 0, sizeof(Fts5SegIter));
  185667. }
  185668. #ifdef SQLITE_DEBUG
  185669. /*
  185670. ** This function is used as part of the big assert() procedure implemented by
  185671. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  185672. ** in *pRes is the correct result of comparing the current positions of the
  185673. ** two iterators.
  185674. */
  185675. static void fts5AssertComparisonResult(
  185676. Fts5Iter *pIter,
  185677. Fts5SegIter *p1,
  185678. Fts5SegIter *p2,
  185679. Fts5CResult *pRes
  185680. ){
  185681. int i1 = p1 - pIter->aSeg;
  185682. int i2 = p2 - pIter->aSeg;
  185683. if( p1->pLeaf || p2->pLeaf ){
  185684. if( p1->pLeaf==0 ){
  185685. assert( pRes->iFirst==i2 );
  185686. }else if( p2->pLeaf==0 ){
  185687. assert( pRes->iFirst==i1 );
  185688. }else{
  185689. int nMin = MIN(p1->term.n, p2->term.n);
  185690. int res = memcmp(p1->term.p, p2->term.p, nMin);
  185691. if( res==0 ) res = p1->term.n - p2->term.n;
  185692. if( res==0 ){
  185693. assert( pRes->bTermEq==1 );
  185694. assert( p1->iRowid!=p2->iRowid );
  185695. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  185696. }else{
  185697. assert( pRes->bTermEq==0 );
  185698. }
  185699. if( res<0 ){
  185700. assert( pRes->iFirst==i1 );
  185701. }else{
  185702. assert( pRes->iFirst==i2 );
  185703. }
  185704. }
  185705. }
  185706. }
  185707. /*
  185708. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  185709. ** is compiled. In that case, this function is essentially an assert()
  185710. ** statement used to verify that the contents of the pIter->aFirst[] array
  185711. ** are correct.
  185712. */
  185713. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  185714. if( p->rc==SQLITE_OK ){
  185715. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  185716. int i;
  185717. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  185718. /* Check that pIter->iSwitchRowid is set correctly. */
  185719. for(i=0; i<pIter->nSeg; i++){
  185720. Fts5SegIter *p1 = &pIter->aSeg[i];
  185721. assert( p1==pFirst
  185722. || p1->pLeaf==0
  185723. || fts5BufferCompare(&pFirst->term, &p1->term)
  185724. || p1->iRowid==pIter->iSwitchRowid
  185725. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  185726. );
  185727. }
  185728. for(i=0; i<pIter->nSeg; i+=2){
  185729. Fts5SegIter *p1 = &pIter->aSeg[i];
  185730. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  185731. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  185732. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  185733. }
  185734. for(i=1; i<(pIter->nSeg / 2); i+=2){
  185735. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  185736. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  185737. Fts5CResult *pRes = &pIter->aFirst[i];
  185738. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  185739. }
  185740. }
  185741. }
  185742. #else
  185743. # define fts5AssertMultiIterSetup(x,y)
  185744. #endif
  185745. /*
  185746. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  185747. **
  185748. ** If the returned value is non-zero, then it is the index of an entry
  185749. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  185750. ** to a key that is a duplicate of another, higher priority,
  185751. ** segment-iterator in the pSeg->aSeg[] array.
  185752. */
  185753. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  185754. int i1; /* Index of left-hand Fts5SegIter */
  185755. int i2; /* Index of right-hand Fts5SegIter */
  185756. int iRes;
  185757. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  185758. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  185759. Fts5CResult *pRes = &pIter->aFirst[iOut];
  185760. assert( iOut<pIter->nSeg && iOut>0 );
  185761. assert( pIter->bRev==0 || pIter->bRev==1 );
  185762. if( iOut>=(pIter->nSeg/2) ){
  185763. i1 = (iOut - pIter->nSeg/2) * 2;
  185764. i2 = i1 + 1;
  185765. }else{
  185766. i1 = pIter->aFirst[iOut*2].iFirst;
  185767. i2 = pIter->aFirst[iOut*2+1].iFirst;
  185768. }
  185769. p1 = &pIter->aSeg[i1];
  185770. p2 = &pIter->aSeg[i2];
  185771. pRes->bTermEq = 0;
  185772. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  185773. iRes = i2;
  185774. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  185775. iRes = i1;
  185776. }else{
  185777. int res = fts5BufferCompare(&p1->term, &p2->term);
  185778. if( res==0 ){
  185779. assert( i2>i1 );
  185780. assert( i2!=0 );
  185781. pRes->bTermEq = 1;
  185782. if( p1->iRowid==p2->iRowid ){
  185783. p1->bDel = p2->bDel;
  185784. return i2;
  185785. }
  185786. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  185787. }
  185788. assert( res!=0 );
  185789. if( res<0 ){
  185790. iRes = i1;
  185791. }else{
  185792. iRes = i2;
  185793. }
  185794. }
  185795. pRes->iFirst = (u16)iRes;
  185796. return 0;
  185797. }
  185798. /*
  185799. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  185800. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  185801. */
  185802. static void fts5SegIterGotoPage(
  185803. Fts5Index *p, /* FTS5 backend object */
  185804. Fts5SegIter *pIter, /* Iterator to advance */
  185805. int iLeafPgno
  185806. ){
  185807. assert( iLeafPgno>pIter->iLeafPgno );
  185808. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  185809. p->rc = FTS5_CORRUPT;
  185810. }else{
  185811. fts5DataRelease(pIter->pNextLeaf);
  185812. pIter->pNextLeaf = 0;
  185813. pIter->iLeafPgno = iLeafPgno-1;
  185814. fts5SegIterNextPage(p, pIter);
  185815. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  185816. if( p->rc==SQLITE_OK ){
  185817. int iOff;
  185818. u8 *a = pIter->pLeaf->p;
  185819. int n = pIter->pLeaf->szLeaf;
  185820. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  185821. if( iOff<4 || iOff>=n ){
  185822. p->rc = FTS5_CORRUPT;
  185823. }else{
  185824. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  185825. pIter->iLeafOffset = iOff;
  185826. fts5SegIterLoadNPos(p, pIter);
  185827. }
  185828. }
  185829. }
  185830. }
  185831. /*
  185832. ** Advance the iterator passed as the second argument until it is at or
  185833. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  185834. ** always advanced at least once.
  185835. */
  185836. static void fts5SegIterNextFrom(
  185837. Fts5Index *p, /* FTS5 backend object */
  185838. Fts5SegIter *pIter, /* Iterator to advance */
  185839. i64 iMatch /* Advance iterator at least this far */
  185840. ){
  185841. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  185842. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  185843. int iLeafPgno = pIter->iLeafPgno;
  185844. int bMove = 1;
  185845. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  185846. assert( pIter->pDlidx );
  185847. assert( pIter->pLeaf );
  185848. if( bRev==0 ){
  185849. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  185850. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  185851. fts5DlidxIterNext(p, pDlidx);
  185852. }
  185853. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  185854. if( iLeafPgno>pIter->iLeafPgno ){
  185855. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  185856. bMove = 0;
  185857. }
  185858. }else{
  185859. assert( pIter->pNextLeaf==0 );
  185860. assert( iMatch<pIter->iRowid );
  185861. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  185862. fts5DlidxIterPrev(p, pDlidx);
  185863. }
  185864. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  185865. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  185866. if( iLeafPgno<pIter->iLeafPgno ){
  185867. pIter->iLeafPgno = iLeafPgno+1;
  185868. fts5SegIterReverseNewPage(p, pIter);
  185869. bMove = 0;
  185870. }
  185871. }
  185872. do{
  185873. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  185874. if( pIter->pLeaf==0 ) break;
  185875. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  185876. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  185877. bMove = 1;
  185878. }while( p->rc==SQLITE_OK );
  185879. }
  185880. /*
  185881. ** Free the iterator object passed as the second argument.
  185882. */
  185883. static void fts5MultiIterFree(Fts5Iter *pIter){
  185884. if( pIter ){
  185885. int i;
  185886. for(i=0; i<pIter->nSeg; i++){
  185887. fts5SegIterClear(&pIter->aSeg[i]);
  185888. }
  185889. fts5StructureRelease(pIter->pStruct);
  185890. fts5BufferFree(&pIter->poslist);
  185891. sqlite3_free(pIter);
  185892. }
  185893. }
  185894. static void fts5MultiIterAdvanced(
  185895. Fts5Index *p, /* FTS5 backend to iterate within */
  185896. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  185897. int iChanged, /* Index of sub-iterator just advanced */
  185898. int iMinset /* Minimum entry in aFirst[] to set */
  185899. ){
  185900. int i;
  185901. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  185902. int iEq;
  185903. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  185904. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  185905. assert( p->rc==SQLITE_OK );
  185906. pSeg->xNext(p, pSeg, 0);
  185907. i = pIter->nSeg + iEq;
  185908. }
  185909. }
  185910. }
  185911. /*
  185912. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  185913. ** points to the same term though - just a different rowid. This function
  185914. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  185915. ** If it does so successfully, 0 is returned. Otherwise 1.
  185916. **
  185917. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  185918. ** on the iterator instead. That function does the same as this one, except
  185919. ** that it deals with more complicated cases as well.
  185920. */
  185921. static int fts5MultiIterAdvanceRowid(
  185922. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  185923. int iChanged, /* Index of sub-iterator just advanced */
  185924. Fts5SegIter **ppFirst
  185925. ){
  185926. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  185927. if( pNew->iRowid==pIter->iSwitchRowid
  185928. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  185929. ){
  185930. int i;
  185931. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  185932. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  185933. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  185934. Fts5CResult *pRes = &pIter->aFirst[i];
  185935. assert( pNew->pLeaf );
  185936. assert( pRes->bTermEq==0 || pOther->pLeaf );
  185937. if( pRes->bTermEq ){
  185938. if( pNew->iRowid==pOther->iRowid ){
  185939. return 1;
  185940. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  185941. pIter->iSwitchRowid = pOther->iRowid;
  185942. pNew = pOther;
  185943. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  185944. pIter->iSwitchRowid = pOther->iRowid;
  185945. }
  185946. }
  185947. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  185948. if( i==1 ) break;
  185949. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  185950. }
  185951. }
  185952. *ppFirst = pNew;
  185953. return 0;
  185954. }
  185955. /*
  185956. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  185957. */
  185958. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  185959. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  185960. pIter->base.bEof = pSeg->pLeaf==0;
  185961. pIter->iSwitchRowid = pSeg->iRowid;
  185962. }
  185963. /*
  185964. ** Move the iterator to the next entry.
  185965. **
  185966. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  185967. ** considered an error if the iterator reaches EOF, or if it is already at
  185968. ** EOF when this function is called.
  185969. */
  185970. static void fts5MultiIterNext(
  185971. Fts5Index *p,
  185972. Fts5Iter *pIter,
  185973. int bFrom, /* True if argument iFrom is valid */
  185974. i64 iFrom /* Advance at least as far as this */
  185975. ){
  185976. int bUseFrom = bFrom;
  185977. assert( pIter->base.bEof==0 );
  185978. while( p->rc==SQLITE_OK ){
  185979. int iFirst = pIter->aFirst[1].iFirst;
  185980. int bNewTerm = 0;
  185981. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  185982. assert( p->rc==SQLITE_OK );
  185983. if( bUseFrom && pSeg->pDlidx ){
  185984. fts5SegIterNextFrom(p, pSeg, iFrom);
  185985. }else{
  185986. pSeg->xNext(p, pSeg, &bNewTerm);
  185987. }
  185988. if( pSeg->pLeaf==0 || bNewTerm
  185989. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  185990. ){
  185991. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  185992. fts5MultiIterSetEof(pIter);
  185993. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  185994. if( pSeg->pLeaf==0 ) return;
  185995. }
  185996. fts5AssertMultiIterSetup(p, pIter);
  185997. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  185998. if( pIter->bSkipEmpty==0 || pSeg->nPos ){
  185999. pIter->xSetOutputs(pIter, pSeg);
  186000. return;
  186001. }
  186002. bUseFrom = 0;
  186003. }
  186004. }
  186005. static void fts5MultiIterNext2(
  186006. Fts5Index *p,
  186007. Fts5Iter *pIter,
  186008. int *pbNewTerm /* OUT: True if *might* be new term */
  186009. ){
  186010. assert( pIter->bSkipEmpty );
  186011. if( p->rc==SQLITE_OK ){
  186012. *pbNewTerm = 0;
  186013. do{
  186014. int iFirst = pIter->aFirst[1].iFirst;
  186015. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  186016. int bNewTerm = 0;
  186017. assert( p->rc==SQLITE_OK );
  186018. pSeg->xNext(p, pSeg, &bNewTerm);
  186019. if( pSeg->pLeaf==0 || bNewTerm
  186020. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  186021. ){
  186022. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  186023. fts5MultiIterSetEof(pIter);
  186024. *pbNewTerm = 1;
  186025. }
  186026. fts5AssertMultiIterSetup(p, pIter);
  186027. }while( fts5MultiIterIsEmpty(p, pIter) );
  186028. }
  186029. }
  186030. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  186031. UNUSED_PARAM2(pUnused1, pUnused2);
  186032. }
  186033. static Fts5Iter *fts5MultiIterAlloc(
  186034. Fts5Index *p, /* FTS5 backend to iterate within */
  186035. int nSeg
  186036. ){
  186037. Fts5Iter *pNew;
  186038. int nSlot; /* Power of two >= nSeg */
  186039. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  186040. pNew = fts5IdxMalloc(p,
  186041. sizeof(Fts5Iter) + /* pNew */
  186042. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  186043. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  186044. );
  186045. if( pNew ){
  186046. pNew->nSeg = nSlot;
  186047. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  186048. pNew->pIndex = p;
  186049. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  186050. }
  186051. return pNew;
  186052. }
  186053. static void fts5PoslistCallback(
  186054. Fts5Index *pUnused,
  186055. void *pContext,
  186056. const u8 *pChunk, int nChunk
  186057. ){
  186058. UNUSED_PARAM(pUnused);
  186059. assert_nc( nChunk>=0 );
  186060. if( nChunk>0 ){
  186061. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  186062. }
  186063. }
  186064. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  186065. struct PoslistCallbackCtx {
  186066. Fts5Buffer *pBuf; /* Append to this buffer */
  186067. Fts5Colset *pColset; /* Restrict matches to this column */
  186068. int eState; /* See above */
  186069. };
  186070. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  186071. struct PoslistOffsetsCtx {
  186072. Fts5Buffer *pBuf; /* Append to this buffer */
  186073. Fts5Colset *pColset; /* Restrict matches to this column */
  186074. int iRead;
  186075. int iWrite;
  186076. };
  186077. /*
  186078. ** TODO: Make this more efficient!
  186079. */
  186080. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  186081. int i;
  186082. for(i=0; i<pColset->nCol; i++){
  186083. if( pColset->aiCol[i]==iCol ) return 1;
  186084. }
  186085. return 0;
  186086. }
  186087. static void fts5PoslistOffsetsCallback(
  186088. Fts5Index *pUnused,
  186089. void *pContext,
  186090. const u8 *pChunk, int nChunk
  186091. ){
  186092. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  186093. UNUSED_PARAM(pUnused);
  186094. assert_nc( nChunk>=0 );
  186095. if( nChunk>0 ){
  186096. int i = 0;
  186097. while( i<nChunk ){
  186098. int iVal;
  186099. i += fts5GetVarint32(&pChunk[i], iVal);
  186100. iVal += pCtx->iRead - 2;
  186101. pCtx->iRead = iVal;
  186102. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  186103. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  186104. pCtx->iWrite = iVal;
  186105. }
  186106. }
  186107. }
  186108. }
  186109. static void fts5PoslistFilterCallback(
  186110. Fts5Index *pUnused,
  186111. void *pContext,
  186112. const u8 *pChunk, int nChunk
  186113. ){
  186114. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  186115. UNUSED_PARAM(pUnused);
  186116. assert_nc( nChunk>=0 );
  186117. if( nChunk>0 ){
  186118. /* Search through to find the first varint with value 1. This is the
  186119. ** start of the next columns hits. */
  186120. int i = 0;
  186121. int iStart = 0;
  186122. if( pCtx->eState==2 ){
  186123. int iCol;
  186124. fts5FastGetVarint32(pChunk, i, iCol);
  186125. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  186126. pCtx->eState = 1;
  186127. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  186128. }else{
  186129. pCtx->eState = 0;
  186130. }
  186131. }
  186132. do {
  186133. while( i<nChunk && pChunk[i]!=0x01 ){
  186134. while( pChunk[i] & 0x80 ) i++;
  186135. i++;
  186136. }
  186137. if( pCtx->eState ){
  186138. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  186139. }
  186140. if( i<nChunk ){
  186141. int iCol;
  186142. iStart = i;
  186143. i++;
  186144. if( i>=nChunk ){
  186145. pCtx->eState = 2;
  186146. }else{
  186147. fts5FastGetVarint32(pChunk, i, iCol);
  186148. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  186149. if( pCtx->eState ){
  186150. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  186151. iStart = i;
  186152. }
  186153. }
  186154. }
  186155. }while( i<nChunk );
  186156. }
  186157. }
  186158. static void fts5ChunkIterate(
  186159. Fts5Index *p, /* Index object */
  186160. Fts5SegIter *pSeg, /* Poslist of this iterator */
  186161. void *pCtx, /* Context pointer for xChunk callback */
  186162. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  186163. ){
  186164. int nRem = pSeg->nPos; /* Number of bytes still to come */
  186165. Fts5Data *pData = 0;
  186166. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  186167. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  186168. int pgno = pSeg->iLeafPgno;
  186169. int pgnoSave = 0;
  186170. /* This function does notmwork with detail=none databases. */
  186171. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  186172. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  186173. pgnoSave = pgno+1;
  186174. }
  186175. while( 1 ){
  186176. xChunk(p, pCtx, pChunk, nChunk);
  186177. nRem -= nChunk;
  186178. fts5DataRelease(pData);
  186179. if( nRem<=0 ){
  186180. break;
  186181. }else{
  186182. pgno++;
  186183. pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  186184. if( pData==0 ) break;
  186185. pChunk = &pData->p[4];
  186186. nChunk = MIN(nRem, pData->szLeaf - 4);
  186187. if( pgno==pgnoSave ){
  186188. assert( pSeg->pNextLeaf==0 );
  186189. pSeg->pNextLeaf = pData;
  186190. pData = 0;
  186191. }
  186192. }
  186193. }
  186194. }
  186195. /*
  186196. ** Iterator pIter currently points to a valid entry (not EOF). This
  186197. ** function appends the position list data for the current entry to
  186198. ** buffer pBuf. It does not make a copy of the position-list size
  186199. ** field.
  186200. */
  186201. static void fts5SegiterPoslist(
  186202. Fts5Index *p,
  186203. Fts5SegIter *pSeg,
  186204. Fts5Colset *pColset,
  186205. Fts5Buffer *pBuf
  186206. ){
  186207. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
  186208. if( pColset==0 ){
  186209. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  186210. }else{
  186211. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  186212. PoslistCallbackCtx sCtx;
  186213. sCtx.pBuf = pBuf;
  186214. sCtx.pColset = pColset;
  186215. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  186216. assert( sCtx.eState==0 || sCtx.eState==1 );
  186217. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  186218. }else{
  186219. PoslistOffsetsCtx sCtx;
  186220. memset(&sCtx, 0, sizeof(sCtx));
  186221. sCtx.pBuf = pBuf;
  186222. sCtx.pColset = pColset;
  186223. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  186224. }
  186225. }
  186226. }
  186227. }
  186228. /*
  186229. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  186230. ** the position list contains entries for column iCol, then (*pa) is set
  186231. ** to point to the sub-position-list for that column and the number of
  186232. ** bytes in it returned. Or, if the argument position list does not
  186233. ** contain any entries for column iCol, return 0.
  186234. */
  186235. static int fts5IndexExtractCol(
  186236. const u8 **pa, /* IN/OUT: Pointer to poslist */
  186237. int n, /* IN: Size of poslist in bytes */
  186238. int iCol /* Column to extract from poslist */
  186239. ){
  186240. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  186241. const u8 *p = *pa;
  186242. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  186243. while( iCol>iCurrent ){
  186244. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  186245. ** not part of a varint. Note that it is not possible for a negative
  186246. ** or extremely large varint to occur within an uncorrupted position
  186247. ** list. So the last byte of each varint may be assumed to have a clear
  186248. ** 0x80 bit. */
  186249. while( *p!=0x01 ){
  186250. while( *p++ & 0x80 );
  186251. if( p>=pEnd ) return 0;
  186252. }
  186253. *pa = p++;
  186254. iCurrent = *p++;
  186255. if( iCurrent & 0x80 ){
  186256. p--;
  186257. p += fts5GetVarint32(p, iCurrent);
  186258. }
  186259. }
  186260. if( iCol!=iCurrent ) return 0;
  186261. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  186262. ** not part of a varint */
  186263. while( p<pEnd && *p!=0x01 ){
  186264. while( *p++ & 0x80 );
  186265. }
  186266. return p - (*pa);
  186267. }
  186268. static void fts5IndexExtractColset(
  186269. int *pRc,
  186270. Fts5Colset *pColset, /* Colset to filter on */
  186271. const u8 *pPos, int nPos, /* Position list */
  186272. Fts5Buffer *pBuf /* Output buffer */
  186273. ){
  186274. if( *pRc==SQLITE_OK ){
  186275. int i;
  186276. fts5BufferZero(pBuf);
  186277. for(i=0; i<pColset->nCol; i++){
  186278. const u8 *pSub = pPos;
  186279. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  186280. if( nSub ){
  186281. fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
  186282. }
  186283. }
  186284. }
  186285. }
  186286. /*
  186287. ** xSetOutputs callback used by detail=none tables.
  186288. */
  186289. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  186290. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  186291. pIter->base.iRowid = pSeg->iRowid;
  186292. pIter->base.nData = pSeg->nPos;
  186293. }
  186294. /*
  186295. ** xSetOutputs callback used by detail=full and detail=col tables when no
  186296. ** column filters are specified.
  186297. */
  186298. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  186299. pIter->base.iRowid = pSeg->iRowid;
  186300. pIter->base.nData = pSeg->nPos;
  186301. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  186302. assert( pIter->pColset==0 );
  186303. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  186304. /* All data is stored on the current page. Populate the output
  186305. ** variables to point into the body of the page object. */
  186306. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  186307. }else{
  186308. /* The data is distributed over two or more pages. Copy it into the
  186309. ** Fts5Iter.poslist buffer and then set the output pointer to point
  186310. ** to this buffer. */
  186311. fts5BufferZero(&pIter->poslist);
  186312. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  186313. pIter->base.pData = pIter->poslist.p;
  186314. }
  186315. }
  186316. /*
  186317. ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
  186318. ** against no columns at all).
  186319. */
  186320. static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  186321. UNUSED_PARAM(pSeg);
  186322. pIter->base.nData = 0;
  186323. }
  186324. /*
  186325. ** xSetOutputs callback used by detail=col when there is a column filter
  186326. ** and there are 100 or more columns. Also called as a fallback from
  186327. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  186328. */
  186329. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  186330. fts5BufferZero(&pIter->poslist);
  186331. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  186332. pIter->base.iRowid = pSeg->iRowid;
  186333. pIter->base.pData = pIter->poslist.p;
  186334. pIter->base.nData = pIter->poslist.n;
  186335. }
  186336. /*
  186337. ** xSetOutputs callback used when:
  186338. **
  186339. ** * detail=col,
  186340. ** * there is a column filter, and
  186341. ** * the table contains 100 or fewer columns.
  186342. **
  186343. ** The last point is to ensure all column numbers are stored as
  186344. ** single-byte varints.
  186345. */
  186346. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  186347. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  186348. assert( pIter->pColset );
  186349. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  186350. fts5IterSetOutputs_Col(pIter, pSeg);
  186351. }else{
  186352. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  186353. u8 *pEnd = (u8*)&a[pSeg->nPos];
  186354. int iPrev = 0;
  186355. int *aiCol = pIter->pColset->aiCol;
  186356. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  186357. u8 *aOut = pIter->poslist.p;
  186358. int iPrevOut = 0;
  186359. pIter->base.iRowid = pSeg->iRowid;
  186360. while( a<pEnd ){
  186361. iPrev += (int)a++[0] - 2;
  186362. while( *aiCol<iPrev ){
  186363. aiCol++;
  186364. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  186365. }
  186366. if( *aiCol==iPrev ){
  186367. *aOut++ = (u8)((iPrev - iPrevOut) + 2);
  186368. iPrevOut = iPrev;
  186369. }
  186370. }
  186371. setoutputs_col_out:
  186372. pIter->base.pData = pIter->poslist.p;
  186373. pIter->base.nData = aOut - pIter->poslist.p;
  186374. }
  186375. }
  186376. /*
  186377. ** xSetOutputs callback used by detail=full when there is a column filter.
  186378. */
  186379. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  186380. Fts5Colset *pColset = pIter->pColset;
  186381. pIter->base.iRowid = pSeg->iRowid;
  186382. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  186383. assert( pColset );
  186384. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  186385. /* All data is stored on the current page. Populate the output
  186386. ** variables to point into the body of the page object. */
  186387. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  186388. if( pColset->nCol==1 ){
  186389. pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
  186390. pIter->base.pData = a;
  186391. }else{
  186392. int *pRc = &pIter->pIndex->rc;
  186393. fts5BufferZero(&pIter->poslist);
  186394. fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
  186395. pIter->base.pData = pIter->poslist.p;
  186396. pIter->base.nData = pIter->poslist.n;
  186397. }
  186398. }else{
  186399. /* The data is distributed over two or more pages. Copy it into the
  186400. ** Fts5Iter.poslist buffer and then set the output pointer to point
  186401. ** to this buffer. */
  186402. fts5BufferZero(&pIter->poslist);
  186403. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  186404. pIter->base.pData = pIter->poslist.p;
  186405. pIter->base.nData = pIter->poslist.n;
  186406. }
  186407. }
  186408. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  186409. if( *pRc==SQLITE_OK ){
  186410. Fts5Config *pConfig = pIter->pIndex->pConfig;
  186411. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  186412. pIter->xSetOutputs = fts5IterSetOutputs_None;
  186413. }
  186414. else if( pIter->pColset==0 ){
  186415. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  186416. }
  186417. else if( pIter->pColset->nCol==0 ){
  186418. pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
  186419. }
  186420. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  186421. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  186422. }
  186423. else{
  186424. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  186425. if( pConfig->nCol<=100 ){
  186426. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  186427. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  186428. }else{
  186429. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  186430. }
  186431. }
  186432. }
  186433. }
  186434. /*
  186435. ** Allocate a new Fts5Iter object.
  186436. **
  186437. ** The new object will be used to iterate through data in structure pStruct.
  186438. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  186439. ** is zero or greater, data from the first nSegment segments on level iLevel
  186440. ** is merged.
  186441. **
  186442. ** The iterator initially points to the first term/rowid entry in the
  186443. ** iterated data.
  186444. */
  186445. static void fts5MultiIterNew(
  186446. Fts5Index *p, /* FTS5 backend to iterate within */
  186447. Fts5Structure *pStruct, /* Structure of specific index */
  186448. int flags, /* FTS5INDEX_QUERY_XXX flags */
  186449. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  186450. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  186451. int iLevel, /* Level to iterate (-1 for all) */
  186452. int nSegment, /* Number of segments to merge (iLevel>=0) */
  186453. Fts5Iter **ppOut /* New object */
  186454. ){
  186455. int nSeg = 0; /* Number of segment-iters in use */
  186456. int iIter = 0; /* */
  186457. int iSeg; /* Used to iterate through segments */
  186458. Fts5StructureLevel *pLvl;
  186459. Fts5Iter *pNew;
  186460. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  186461. /* Allocate space for the new multi-seg-iterator. */
  186462. if( p->rc==SQLITE_OK ){
  186463. if( iLevel<0 ){
  186464. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  186465. nSeg = pStruct->nSegment;
  186466. nSeg += (p->pHash ? 1 : 0);
  186467. }else{
  186468. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  186469. }
  186470. }
  186471. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  186472. if( pNew==0 ) return;
  186473. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  186474. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  186475. pNew->pStruct = pStruct;
  186476. pNew->pColset = pColset;
  186477. fts5StructureRef(pStruct);
  186478. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  186479. fts5IterSetOutputCb(&p->rc, pNew);
  186480. }
  186481. /* Initialize each of the component segment iterators. */
  186482. if( p->rc==SQLITE_OK ){
  186483. if( iLevel<0 ){
  186484. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  186485. if( p->pHash ){
  186486. /* Add a segment iterator for the current contents of the hash table. */
  186487. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  186488. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  186489. }
  186490. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  186491. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  186492. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  186493. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  186494. if( pTerm==0 ){
  186495. fts5SegIterInit(p, pSeg, pIter);
  186496. }else{
  186497. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  186498. }
  186499. }
  186500. }
  186501. }else{
  186502. pLvl = &pStruct->aLevel[iLevel];
  186503. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  186504. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  186505. }
  186506. }
  186507. assert( iIter==nSeg );
  186508. }
  186509. /* If the above was successful, each component iterators now points
  186510. ** to the first entry in its segment. In this case initialize the
  186511. ** aFirst[] array. Or, if an error has occurred, free the iterator
  186512. ** object and set the output variable to NULL. */
  186513. if( p->rc==SQLITE_OK ){
  186514. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  186515. int iEq;
  186516. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  186517. Fts5SegIter *pSeg = &pNew->aSeg[iEq];
  186518. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  186519. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  186520. }
  186521. }
  186522. fts5MultiIterSetEof(pNew);
  186523. fts5AssertMultiIterSetup(p, pNew);
  186524. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  186525. fts5MultiIterNext(p, pNew, 0, 0);
  186526. }else if( pNew->base.bEof==0 ){
  186527. Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
  186528. pNew->xSetOutputs(pNew, pSeg);
  186529. }
  186530. }else{
  186531. fts5MultiIterFree(pNew);
  186532. *ppOut = 0;
  186533. }
  186534. }
  186535. /*
  186536. ** Create an Fts5Iter that iterates through the doclist provided
  186537. ** as the second argument.
  186538. */
  186539. static void fts5MultiIterNew2(
  186540. Fts5Index *p, /* FTS5 backend to iterate within */
  186541. Fts5Data *pData, /* Doclist to iterate through */
  186542. int bDesc, /* True for descending rowid order */
  186543. Fts5Iter **ppOut /* New object */
  186544. ){
  186545. Fts5Iter *pNew;
  186546. pNew = fts5MultiIterAlloc(p, 2);
  186547. if( pNew ){
  186548. Fts5SegIter *pIter = &pNew->aSeg[1];
  186549. pIter->flags = FTS5_SEGITER_ONETERM;
  186550. if( pData->szLeaf>0 ){
  186551. pIter->pLeaf = pData;
  186552. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  186553. pIter->iEndofDoclist = pData->nn;
  186554. pNew->aFirst[1].iFirst = 1;
  186555. if( bDesc ){
  186556. pNew->bRev = 1;
  186557. pIter->flags |= FTS5_SEGITER_REVERSE;
  186558. fts5SegIterReverseInitPage(p, pIter);
  186559. }else{
  186560. fts5SegIterLoadNPos(p, pIter);
  186561. }
  186562. pData = 0;
  186563. }else{
  186564. pNew->base.bEof = 1;
  186565. }
  186566. fts5SegIterSetNext(p, pIter);
  186567. *ppOut = pNew;
  186568. }
  186569. fts5DataRelease(pData);
  186570. }
  186571. /*
  186572. ** Return true if the iterator is at EOF or if an error has occurred.
  186573. ** False otherwise.
  186574. */
  186575. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  186576. assert( p->rc
  186577. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  186578. );
  186579. return (p->rc || pIter->base.bEof);
  186580. }
  186581. /*
  186582. ** Return the rowid of the entry that the iterator currently points
  186583. ** to. If the iterator points to EOF when this function is called the
  186584. ** results are undefined.
  186585. */
  186586. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  186587. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  186588. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  186589. }
  186590. /*
  186591. ** Move the iterator to the next entry at or following iMatch.
  186592. */
  186593. static void fts5MultiIterNextFrom(
  186594. Fts5Index *p,
  186595. Fts5Iter *pIter,
  186596. i64 iMatch
  186597. ){
  186598. while( 1 ){
  186599. i64 iRowid;
  186600. fts5MultiIterNext(p, pIter, 1, iMatch);
  186601. if( fts5MultiIterEof(p, pIter) ) break;
  186602. iRowid = fts5MultiIterRowid(pIter);
  186603. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  186604. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  186605. }
  186606. }
  186607. /*
  186608. ** Return a pointer to a buffer containing the term associated with the
  186609. ** entry that the iterator currently points to.
  186610. */
  186611. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  186612. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  186613. *pn = p->term.n;
  186614. return p->term.p;
  186615. }
  186616. /*
  186617. ** Allocate a new segment-id for the structure pStruct. The new segment
  186618. ** id must be between 1 and 65335 inclusive, and must not be used by
  186619. ** any currently existing segment. If a free segment id cannot be found,
  186620. ** SQLITE_FULL is returned.
  186621. **
  186622. ** If an error has already occurred, this function is a no-op. 0 is
  186623. ** returned in this case.
  186624. */
  186625. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  186626. int iSegid = 0;
  186627. if( p->rc==SQLITE_OK ){
  186628. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  186629. p->rc = SQLITE_FULL;
  186630. }else{
  186631. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  186632. ** array is 63 elements, or 252 bytes, in size. */
  186633. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  186634. int iLvl, iSeg;
  186635. int i;
  186636. u32 mask;
  186637. memset(aUsed, 0, sizeof(aUsed));
  186638. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  186639. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  186640. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  186641. if( iId<=FTS5_MAX_SEGMENT ){
  186642. aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
  186643. }
  186644. }
  186645. }
  186646. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  186647. mask = aUsed[i];
  186648. for(iSegid=0; mask & (1 << iSegid); iSegid++);
  186649. iSegid += 1 + i*32;
  186650. #ifdef SQLITE_DEBUG
  186651. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  186652. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  186653. assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  186654. }
  186655. }
  186656. assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  186657. {
  186658. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  186659. if( p->rc==SQLITE_OK ){
  186660. u8 aBlob[2] = {0xff, 0xff};
  186661. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  186662. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  186663. assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  186664. p->rc = sqlite3_reset(pIdxSelect);
  186665. sqlite3_bind_null(pIdxSelect, 2);
  186666. }
  186667. }
  186668. #endif
  186669. }
  186670. }
  186671. return iSegid;
  186672. }
  186673. /*
  186674. ** Discard all data currently cached in the hash-tables.
  186675. */
  186676. static void fts5IndexDiscardData(Fts5Index *p){
  186677. assert( p->pHash || p->nPendingData==0 );
  186678. if( p->pHash ){
  186679. sqlite3Fts5HashClear(p->pHash);
  186680. p->nPendingData = 0;
  186681. }
  186682. }
  186683. /*
  186684. ** Return the size of the prefix, in bytes, that buffer
  186685. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  186686. **
  186687. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  186688. ** than buffer (pOld/nOld).
  186689. */
  186690. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  186691. int i;
  186692. for(i=0; i<nOld; i++){
  186693. if( pOld[i]!=pNew[i] ) break;
  186694. }
  186695. return i;
  186696. }
  186697. static void fts5WriteDlidxClear(
  186698. Fts5Index *p,
  186699. Fts5SegWriter *pWriter,
  186700. int bFlush /* If true, write dlidx to disk */
  186701. ){
  186702. int i;
  186703. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  186704. for(i=0; i<pWriter->nDlidx; i++){
  186705. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  186706. if( pDlidx->buf.n==0 ) break;
  186707. if( bFlush ){
  186708. assert( pDlidx->pgno!=0 );
  186709. fts5DataWrite(p,
  186710. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  186711. pDlidx->buf.p, pDlidx->buf.n
  186712. );
  186713. }
  186714. sqlite3Fts5BufferZero(&pDlidx->buf);
  186715. pDlidx->bPrevValid = 0;
  186716. }
  186717. }
  186718. /*
  186719. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  186720. ** Any new array elements are zeroed before returning.
  186721. */
  186722. static int fts5WriteDlidxGrow(
  186723. Fts5Index *p,
  186724. Fts5SegWriter *pWriter,
  186725. int nLvl
  186726. ){
  186727. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  186728. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
  186729. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  186730. );
  186731. if( aDlidx==0 ){
  186732. p->rc = SQLITE_NOMEM;
  186733. }else{
  186734. int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  186735. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  186736. pWriter->aDlidx = aDlidx;
  186737. pWriter->nDlidx = nLvl;
  186738. }
  186739. }
  186740. return p->rc;
  186741. }
  186742. /*
  186743. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  186744. ** enough, flush it to disk and return 1. Otherwise discard it and return
  186745. ** zero.
  186746. */
  186747. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  186748. int bFlag = 0;
  186749. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  186750. ** to the database, also write the doclist-index to disk. */
  186751. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  186752. bFlag = 1;
  186753. }
  186754. fts5WriteDlidxClear(p, pWriter, bFlag);
  186755. pWriter->nEmpty = 0;
  186756. return bFlag;
  186757. }
  186758. /*
  186759. ** This function is called whenever processing of the doclist for the
  186760. ** last term on leaf page (pWriter->iBtPage) is completed.
  186761. **
  186762. ** The doclist-index for that term is currently stored in-memory within the
  186763. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  186764. ** writes it out to disk. Or, if it is too small to bother with, discards
  186765. ** it.
  186766. **
  186767. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  186768. */
  186769. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  186770. int bFlag;
  186771. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  186772. if( pWriter->iBtPage==0 ) return;
  186773. bFlag = fts5WriteFlushDlidx(p, pWriter);
  186774. if( p->rc==SQLITE_OK ){
  186775. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  186776. /* The following was already done in fts5WriteInit(): */
  186777. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  186778. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  186779. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  186780. sqlite3_step(p->pIdxWriter);
  186781. p->rc = sqlite3_reset(p->pIdxWriter);
  186782. sqlite3_bind_null(p->pIdxWriter, 2);
  186783. }
  186784. pWriter->iBtPage = 0;
  186785. }
  186786. /*
  186787. ** This is called once for each leaf page except the first that contains
  186788. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  186789. ** is larger than all terms written to earlier leaves, and equal to or
  186790. ** smaller than the first term on the new leaf.
  186791. **
  186792. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  186793. ** has already occurred when this function is called, it is a no-op.
  186794. */
  186795. static void fts5WriteBtreeTerm(
  186796. Fts5Index *p, /* FTS5 backend object */
  186797. Fts5SegWriter *pWriter, /* Writer object */
  186798. int nTerm, const u8 *pTerm /* First term on new page */
  186799. ){
  186800. fts5WriteFlushBtree(p, pWriter);
  186801. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  186802. pWriter->iBtPage = pWriter->writer.pgno;
  186803. }
  186804. /*
  186805. ** This function is called when flushing a leaf page that contains no
  186806. ** terms at all to disk.
  186807. */
  186808. static void fts5WriteBtreeNoTerm(
  186809. Fts5Index *p, /* FTS5 backend object */
  186810. Fts5SegWriter *pWriter /* Writer object */
  186811. ){
  186812. /* If there were no rowids on the leaf page either and the doclist-index
  186813. ** has already been started, append an 0x00 byte to it. */
  186814. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  186815. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  186816. assert( pDlidx->bPrevValid );
  186817. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  186818. }
  186819. /* Increment the "number of sequential leaves without a term" counter. */
  186820. pWriter->nEmpty++;
  186821. }
  186822. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  186823. i64 iRowid;
  186824. int iOff;
  186825. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  186826. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  186827. return iRowid;
  186828. }
  186829. /*
  186830. ** Rowid iRowid has just been appended to the current leaf page. It is the
  186831. ** first on the page. This function appends an appropriate entry to the current
  186832. ** doclist-index.
  186833. */
  186834. static void fts5WriteDlidxAppend(
  186835. Fts5Index *p,
  186836. Fts5SegWriter *pWriter,
  186837. i64 iRowid
  186838. ){
  186839. int i;
  186840. int bDone = 0;
  186841. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  186842. i64 iVal;
  186843. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  186844. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  186845. /* The current doclist-index page is full. Write it to disk and push
  186846. ** a copy of iRowid (which will become the first rowid on the next
  186847. ** doclist-index leaf page) up into the next level of the b-tree
  186848. ** hierarchy. If the node being flushed is currently the root node,
  186849. ** also push its first rowid upwards. */
  186850. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  186851. fts5DataWrite(p,
  186852. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  186853. pDlidx->buf.p, pDlidx->buf.n
  186854. );
  186855. fts5WriteDlidxGrow(p, pWriter, i+2);
  186856. pDlidx = &pWriter->aDlidx[i];
  186857. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  186858. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  186859. /* This was the root node. Push its first rowid up to the new root. */
  186860. pDlidx[1].pgno = pDlidx->pgno;
  186861. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  186862. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  186863. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  186864. pDlidx[1].bPrevValid = 1;
  186865. pDlidx[1].iPrev = iFirst;
  186866. }
  186867. sqlite3Fts5BufferZero(&pDlidx->buf);
  186868. pDlidx->bPrevValid = 0;
  186869. pDlidx->pgno++;
  186870. }else{
  186871. bDone = 1;
  186872. }
  186873. if( pDlidx->bPrevValid ){
  186874. iVal = iRowid - pDlidx->iPrev;
  186875. }else{
  186876. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  186877. assert( pDlidx->buf.n==0 );
  186878. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  186879. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  186880. iVal = iRowid;
  186881. }
  186882. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  186883. pDlidx->bPrevValid = 1;
  186884. pDlidx->iPrev = iRowid;
  186885. }
  186886. }
  186887. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  186888. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  186889. Fts5PageWriter *pPage = &pWriter->writer;
  186890. i64 iRowid;
  186891. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  186892. /* Set the szLeaf header field. */
  186893. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  186894. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  186895. if( pWriter->bFirstTermInPage ){
  186896. /* No term was written to this page. */
  186897. assert( pPage->pgidx.n==0 );
  186898. fts5WriteBtreeNoTerm(p, pWriter);
  186899. }else{
  186900. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  186901. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  186902. }
  186903. /* Write the page out to disk */
  186904. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  186905. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  186906. /* Initialize the next page. */
  186907. fts5BufferZero(&pPage->buf);
  186908. fts5BufferZero(&pPage->pgidx);
  186909. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  186910. pPage->iPrevPgidx = 0;
  186911. pPage->pgno++;
  186912. /* Increase the leaves written counter */
  186913. pWriter->nLeafWritten++;
  186914. /* The new leaf holds no terms or rowids */
  186915. pWriter->bFirstTermInPage = 1;
  186916. pWriter->bFirstRowidInPage = 1;
  186917. }
  186918. /*
  186919. ** Append term pTerm/nTerm to the segment being written by the writer passed
  186920. ** as the second argument.
  186921. **
  186922. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  186923. ** already occurred, this function is a no-op.
  186924. */
  186925. static void fts5WriteAppendTerm(
  186926. Fts5Index *p,
  186927. Fts5SegWriter *pWriter,
  186928. int nTerm, const u8 *pTerm
  186929. ){
  186930. int nPrefix; /* Bytes of prefix compression for term */
  186931. Fts5PageWriter *pPage = &pWriter->writer;
  186932. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  186933. assert( p->rc==SQLITE_OK );
  186934. assert( pPage->buf.n>=4 );
  186935. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  186936. /* If the current leaf page is full, flush it to disk. */
  186937. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  186938. if( pPage->buf.n>4 ){
  186939. fts5WriteFlushLeaf(p, pWriter);
  186940. }
  186941. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  186942. }
  186943. /* TODO1: Updating pgidx here. */
  186944. pPgidx->n += sqlite3Fts5PutVarint(
  186945. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  186946. );
  186947. pPage->iPrevPgidx = pPage->buf.n;
  186948. #if 0
  186949. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  186950. pPgidx->n += 2;
  186951. #endif
  186952. if( pWriter->bFirstTermInPage ){
  186953. nPrefix = 0;
  186954. if( pPage->pgno!=1 ){
  186955. /* This is the first term on a leaf that is not the leftmost leaf in
  186956. ** the segment b-tree. In this case it is necessary to add a term to
  186957. ** the b-tree hierarchy that is (a) larger than the largest term
  186958. ** already written to the segment and (b) smaller than or equal to
  186959. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  186960. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  186961. ** previous term.
  186962. **
  186963. ** Usually, the previous term is available in pPage->term. The exception
  186964. ** is if this is the first term written in an incremental-merge step.
  186965. ** In this case the previous term is not available, so just write a
  186966. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  186967. ** inefficient, but still correct. */
  186968. int n = nTerm;
  186969. if( pPage->term.n ){
  186970. n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  186971. }
  186972. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  186973. pPage = &pWriter->writer;
  186974. }
  186975. }else{
  186976. nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
  186977. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  186978. }
  186979. /* Append the number of bytes of new data, then the term data itself
  186980. ** to the page. */
  186981. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  186982. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  186983. /* Update the Fts5PageWriter.term field. */
  186984. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  186985. pWriter->bFirstTermInPage = 0;
  186986. pWriter->bFirstRowidInPage = 0;
  186987. pWriter->bFirstRowidInDoclist = 1;
  186988. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  186989. pWriter->aDlidx[0].pgno = pPage->pgno;
  186990. }
  186991. /*
  186992. ** Append a rowid and position-list size field to the writers output.
  186993. */
  186994. static void fts5WriteAppendRowid(
  186995. Fts5Index *p,
  186996. Fts5SegWriter *pWriter,
  186997. i64 iRowid
  186998. ){
  186999. if( p->rc==SQLITE_OK ){
  187000. Fts5PageWriter *pPage = &pWriter->writer;
  187001. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  187002. fts5WriteFlushLeaf(p, pWriter);
  187003. }
  187004. /* If this is to be the first rowid written to the page, set the
  187005. ** rowid-pointer in the page-header. Also append a value to the dlidx
  187006. ** buffer, in case a doclist-index is required. */
  187007. if( pWriter->bFirstRowidInPage ){
  187008. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  187009. fts5WriteDlidxAppend(p, pWriter, iRowid);
  187010. }
  187011. /* Write the rowid. */
  187012. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  187013. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  187014. }else{
  187015. assert( p->rc || iRowid>pWriter->iPrevRowid );
  187016. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  187017. }
  187018. pWriter->iPrevRowid = iRowid;
  187019. pWriter->bFirstRowidInDoclist = 0;
  187020. pWriter->bFirstRowidInPage = 0;
  187021. }
  187022. }
  187023. static void fts5WriteAppendPoslistData(
  187024. Fts5Index *p,
  187025. Fts5SegWriter *pWriter,
  187026. const u8 *aData,
  187027. int nData
  187028. ){
  187029. Fts5PageWriter *pPage = &pWriter->writer;
  187030. const u8 *a = aData;
  187031. int n = nData;
  187032. assert( p->pConfig->pgsz>0 );
  187033. while( p->rc==SQLITE_OK
  187034. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  187035. ){
  187036. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  187037. int nCopy = 0;
  187038. while( nCopy<nReq ){
  187039. i64 dummy;
  187040. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  187041. }
  187042. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  187043. a += nCopy;
  187044. n -= nCopy;
  187045. fts5WriteFlushLeaf(p, pWriter);
  187046. }
  187047. if( n>0 ){
  187048. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  187049. }
  187050. }
  187051. /*
  187052. ** Flush any data cached by the writer object to the database. Free any
  187053. ** allocations associated with the writer.
  187054. */
  187055. static void fts5WriteFinish(
  187056. Fts5Index *p,
  187057. Fts5SegWriter *pWriter, /* Writer object */
  187058. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  187059. ){
  187060. int i;
  187061. Fts5PageWriter *pLeaf = &pWriter->writer;
  187062. if( p->rc==SQLITE_OK ){
  187063. assert( pLeaf->pgno>=1 );
  187064. if( pLeaf->buf.n>4 ){
  187065. fts5WriteFlushLeaf(p, pWriter);
  187066. }
  187067. *pnLeaf = pLeaf->pgno-1;
  187068. if( pLeaf->pgno>1 ){
  187069. fts5WriteFlushBtree(p, pWriter);
  187070. }
  187071. }
  187072. fts5BufferFree(&pLeaf->term);
  187073. fts5BufferFree(&pLeaf->buf);
  187074. fts5BufferFree(&pLeaf->pgidx);
  187075. fts5BufferFree(&pWriter->btterm);
  187076. for(i=0; i<pWriter->nDlidx; i++){
  187077. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  187078. }
  187079. sqlite3_free(pWriter->aDlidx);
  187080. }
  187081. static void fts5WriteInit(
  187082. Fts5Index *p,
  187083. Fts5SegWriter *pWriter,
  187084. int iSegid
  187085. ){
  187086. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  187087. memset(pWriter, 0, sizeof(Fts5SegWriter));
  187088. pWriter->iSegid = iSegid;
  187089. fts5WriteDlidxGrow(p, pWriter, 1);
  187090. pWriter->writer.pgno = 1;
  187091. pWriter->bFirstTermInPage = 1;
  187092. pWriter->iBtPage = 1;
  187093. assert( pWriter->writer.buf.n==0 );
  187094. assert( pWriter->writer.pgidx.n==0 );
  187095. /* Grow the two buffers to pgsz + padding bytes in size. */
  187096. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  187097. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  187098. if( p->pIdxWriter==0 ){
  187099. Fts5Config *pConfig = p->pConfig;
  187100. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  187101. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  187102. pConfig->zDb, pConfig->zName
  187103. ));
  187104. }
  187105. if( p->rc==SQLITE_OK ){
  187106. /* Initialize the 4-byte leaf-page header to 0x00. */
  187107. memset(pWriter->writer.buf.p, 0, 4);
  187108. pWriter->writer.buf.n = 4;
  187109. /* Bind the current output segment id to the index-writer. This is an
  187110. ** optimization over binding the same value over and over as rows are
  187111. ** inserted into %_idx by the current writer. */
  187112. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  187113. }
  187114. }
  187115. /*
  187116. ** Iterator pIter was used to iterate through the input segments of on an
  187117. ** incremental merge operation. This function is called if the incremental
  187118. ** merge step has finished but the input has not been completely exhausted.
  187119. */
  187120. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  187121. int i;
  187122. Fts5Buffer buf;
  187123. memset(&buf, 0, sizeof(Fts5Buffer));
  187124. for(i=0; i<pIter->nSeg; i++){
  187125. Fts5SegIter *pSeg = &pIter->aSeg[i];
  187126. if( pSeg->pSeg==0 ){
  187127. /* no-op */
  187128. }else if( pSeg->pLeaf==0 ){
  187129. /* All keys from this input segment have been transfered to the output.
  187130. ** Set both the first and last page-numbers to 0 to indicate that the
  187131. ** segment is now empty. */
  187132. pSeg->pSeg->pgnoLast = 0;
  187133. pSeg->pSeg->pgnoFirst = 0;
  187134. }else{
  187135. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  187136. i64 iLeafRowid;
  187137. Fts5Data *pData;
  187138. int iId = pSeg->pSeg->iSegid;
  187139. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  187140. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  187141. pData = fts5DataRead(p, iLeafRowid);
  187142. if( pData ){
  187143. fts5BufferZero(&buf);
  187144. fts5BufferGrow(&p->rc, &buf, pData->nn);
  187145. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  187146. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  187147. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  187148. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
  187149. if( p->rc==SQLITE_OK ){
  187150. /* Set the szLeaf field */
  187151. fts5PutU16(&buf.p[2], (u16)buf.n);
  187152. }
  187153. /* Set up the new page-index array */
  187154. fts5BufferAppendVarint(&p->rc, &buf, 4);
  187155. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  187156. && pSeg->iEndofDoclist<pData->szLeaf
  187157. ){
  187158. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  187159. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  187160. fts5BufferAppendBlob(&p->rc, &buf,
  187161. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  187162. );
  187163. }
  187164. fts5DataRelease(pData);
  187165. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  187166. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  187167. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  187168. }
  187169. }
  187170. }
  187171. fts5BufferFree(&buf);
  187172. }
  187173. static void fts5MergeChunkCallback(
  187174. Fts5Index *p,
  187175. void *pCtx,
  187176. const u8 *pChunk, int nChunk
  187177. ){
  187178. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  187179. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  187180. }
  187181. /*
  187182. **
  187183. */
  187184. static void fts5IndexMergeLevel(
  187185. Fts5Index *p, /* FTS5 backend object */
  187186. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  187187. int iLvl, /* Level to read input from */
  187188. int *pnRem /* Write up to this many output leaves */
  187189. ){
  187190. Fts5Structure *pStruct = *ppStruct;
  187191. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  187192. Fts5StructureLevel *pLvlOut;
  187193. Fts5Iter *pIter = 0; /* Iterator to read input data */
  187194. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  187195. int nInput; /* Number of input segments */
  187196. Fts5SegWriter writer; /* Writer object */
  187197. Fts5StructureSegment *pSeg; /* Output segment */
  187198. Fts5Buffer term;
  187199. int bOldest; /* True if the output segment is the oldest */
  187200. int eDetail = p->pConfig->eDetail;
  187201. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  187202. int bTermWritten = 0; /* True if current term already output */
  187203. assert( iLvl<pStruct->nLevel );
  187204. assert( pLvl->nMerge<=pLvl->nSeg );
  187205. memset(&writer, 0, sizeof(Fts5SegWriter));
  187206. memset(&term, 0, sizeof(Fts5Buffer));
  187207. if( pLvl->nMerge ){
  187208. pLvlOut = &pStruct->aLevel[iLvl+1];
  187209. assert( pLvlOut->nSeg>0 );
  187210. nInput = pLvl->nMerge;
  187211. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  187212. fts5WriteInit(p, &writer, pSeg->iSegid);
  187213. writer.writer.pgno = pSeg->pgnoLast+1;
  187214. writer.iBtPage = 0;
  187215. }else{
  187216. int iSegid = fts5AllocateSegid(p, pStruct);
  187217. /* Extend the Fts5Structure object as required to ensure the output
  187218. ** segment exists. */
  187219. if( iLvl==pStruct->nLevel-1 ){
  187220. fts5StructureAddLevel(&p->rc, ppStruct);
  187221. pStruct = *ppStruct;
  187222. }
  187223. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  187224. if( p->rc ) return;
  187225. pLvl = &pStruct->aLevel[iLvl];
  187226. pLvlOut = &pStruct->aLevel[iLvl+1];
  187227. fts5WriteInit(p, &writer, iSegid);
  187228. /* Add the new segment to the output level */
  187229. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  187230. pLvlOut->nSeg++;
  187231. pSeg->pgnoFirst = 1;
  187232. pSeg->iSegid = iSegid;
  187233. pStruct->nSegment++;
  187234. /* Read input from all segments in the input level */
  187235. nInput = pLvl->nSeg;
  187236. }
  187237. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  187238. assert( iLvl>=0 );
  187239. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  187240. fts5MultiIterEof(p, pIter)==0;
  187241. fts5MultiIterNext(p, pIter, 0, 0)
  187242. ){
  187243. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  187244. int nPos; /* position-list size field value */
  187245. int nTerm;
  187246. const u8 *pTerm;
  187247. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  187248. if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
  187249. if( pnRem && writer.nLeafWritten>nRem ){
  187250. break;
  187251. }
  187252. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  187253. bTermWritten =0;
  187254. }
  187255. /* Check for key annihilation. */
  187256. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  187257. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  187258. /* This is a new term. Append a term to the output segment. */
  187259. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  187260. bTermWritten = 1;
  187261. }
  187262. /* Append the rowid to the output */
  187263. /* WRITEPOSLISTSIZE */
  187264. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  187265. if( eDetail==FTS5_DETAIL_NONE ){
  187266. if( pSegIter->bDel ){
  187267. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  187268. if( pSegIter->nPos>0 ){
  187269. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  187270. }
  187271. }
  187272. }else{
  187273. /* Append the position-list data to the output */
  187274. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  187275. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  187276. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  187277. }
  187278. }
  187279. /* Flush the last leaf page to disk. Set the output segment b-tree height
  187280. ** and last leaf page number at the same time. */
  187281. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  187282. if( fts5MultiIterEof(p, pIter) ){
  187283. int i;
  187284. /* Remove the redundant segments from the %_data table */
  187285. for(i=0; i<nInput; i++){
  187286. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  187287. }
  187288. /* Remove the redundant segments from the input level */
  187289. if( pLvl->nSeg!=nInput ){
  187290. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  187291. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  187292. }
  187293. pStruct->nSegment -= nInput;
  187294. pLvl->nSeg -= nInput;
  187295. pLvl->nMerge = 0;
  187296. if( pSeg->pgnoLast==0 ){
  187297. pLvlOut->nSeg--;
  187298. pStruct->nSegment--;
  187299. }
  187300. }else{
  187301. assert( pSeg->pgnoLast>0 );
  187302. fts5TrimSegments(p, pIter);
  187303. pLvl->nMerge = nInput;
  187304. }
  187305. fts5MultiIterFree(pIter);
  187306. fts5BufferFree(&term);
  187307. if( pnRem ) *pnRem -= writer.nLeafWritten;
  187308. }
  187309. /*
  187310. ** Do up to nPg pages of automerge work on the index.
  187311. **
  187312. ** Return true if any changes were actually made, or false otherwise.
  187313. */
  187314. static int fts5IndexMerge(
  187315. Fts5Index *p, /* FTS5 backend object */
  187316. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  187317. int nPg, /* Pages of work to do */
  187318. int nMin /* Minimum number of segments to merge */
  187319. ){
  187320. int nRem = nPg;
  187321. int bRet = 0;
  187322. Fts5Structure *pStruct = *ppStruct;
  187323. while( nRem>0 && p->rc==SQLITE_OK ){
  187324. int iLvl; /* To iterate through levels */
  187325. int iBestLvl = 0; /* Level offering the most input segments */
  187326. int nBest = 0; /* Number of input segments on best level */
  187327. /* Set iBestLvl to the level to read input segments from. */
  187328. assert( pStruct->nLevel>0 );
  187329. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  187330. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  187331. if( pLvl->nMerge ){
  187332. if( pLvl->nMerge>nBest ){
  187333. iBestLvl = iLvl;
  187334. nBest = pLvl->nMerge;
  187335. }
  187336. break;
  187337. }
  187338. if( pLvl->nSeg>nBest ){
  187339. nBest = pLvl->nSeg;
  187340. iBestLvl = iLvl;
  187341. }
  187342. }
  187343. /* If nBest is still 0, then the index must be empty. */
  187344. #ifdef SQLITE_DEBUG
  187345. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  187346. assert( pStruct->aLevel[iLvl].nSeg==0 );
  187347. }
  187348. #endif
  187349. if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
  187350. break;
  187351. }
  187352. bRet = 1;
  187353. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  187354. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  187355. fts5StructurePromote(p, iBestLvl+1, pStruct);
  187356. }
  187357. }
  187358. *ppStruct = pStruct;
  187359. return bRet;
  187360. }
  187361. /*
  187362. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  187363. ** segment. This function updates the write-counter accordingly and, if
  187364. ** necessary, performs incremental merge work.
  187365. **
  187366. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  187367. ** already occurred, this function is a no-op.
  187368. */
  187369. static void fts5IndexAutomerge(
  187370. Fts5Index *p, /* FTS5 backend object */
  187371. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  187372. int nLeaf /* Number of output leaves just written */
  187373. ){
  187374. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  187375. Fts5Structure *pStruct = *ppStruct;
  187376. u64 nWrite; /* Initial value of write-counter */
  187377. int nWork; /* Number of work-quanta to perform */
  187378. int nRem; /* Number of leaf pages left to write */
  187379. /* Update the write-counter. While doing so, set nWork. */
  187380. nWrite = pStruct->nWriteCounter;
  187381. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  187382. pStruct->nWriteCounter += nLeaf;
  187383. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  187384. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  187385. }
  187386. }
  187387. static void fts5IndexCrisismerge(
  187388. Fts5Index *p, /* FTS5 backend object */
  187389. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  187390. ){
  187391. const int nCrisis = p->pConfig->nCrisisMerge;
  187392. Fts5Structure *pStruct = *ppStruct;
  187393. int iLvl = 0;
  187394. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  187395. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  187396. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  187397. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  187398. fts5StructurePromote(p, iLvl+1, pStruct);
  187399. iLvl++;
  187400. }
  187401. *ppStruct = pStruct;
  187402. }
  187403. static int fts5IndexReturn(Fts5Index *p){
  187404. int rc = p->rc;
  187405. p->rc = SQLITE_OK;
  187406. return rc;
  187407. }
  187408. typedef struct Fts5FlushCtx Fts5FlushCtx;
  187409. struct Fts5FlushCtx {
  187410. Fts5Index *pIdx;
  187411. Fts5SegWriter writer;
  187412. };
  187413. /*
  187414. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  187415. ** in a 32-bit integer. Return the size of the largest prefix of this
  187416. ** list nMax bytes or less in size.
  187417. */
  187418. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  187419. int ret;
  187420. u32 dummy;
  187421. ret = fts5GetVarint32(aBuf, dummy);
  187422. if( ret<nMax ){
  187423. while( 1 ){
  187424. int i = fts5GetVarint32(&aBuf[ret], dummy);
  187425. if( (ret + i) > nMax ) break;
  187426. ret += i;
  187427. }
  187428. }
  187429. return ret;
  187430. }
  187431. /*
  187432. ** Flush the contents of in-memory hash table iHash to a new level-0
  187433. ** segment on disk. Also update the corresponding structure record.
  187434. **
  187435. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  187436. ** already occurred, this function is a no-op.
  187437. */
  187438. static void fts5FlushOneHash(Fts5Index *p){
  187439. Fts5Hash *pHash = p->pHash;
  187440. Fts5Structure *pStruct;
  187441. int iSegid;
  187442. int pgnoLast = 0; /* Last leaf page number in segment */
  187443. /* Obtain a reference to the index structure and allocate a new segment-id
  187444. ** for the new level-0 segment. */
  187445. pStruct = fts5StructureRead(p);
  187446. iSegid = fts5AllocateSegid(p, pStruct);
  187447. fts5StructureInvalidate(p);
  187448. if( iSegid ){
  187449. const int pgsz = p->pConfig->pgsz;
  187450. int eDetail = p->pConfig->eDetail;
  187451. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  187452. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  187453. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  187454. Fts5SegWriter writer;
  187455. fts5WriteInit(p, &writer, iSegid);
  187456. pBuf = &writer.writer.buf;
  187457. pPgidx = &writer.writer.pgidx;
  187458. /* fts5WriteInit() should have initialized the buffers to (most likely)
  187459. ** the maximum space required. */
  187460. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  187461. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  187462. /* Begin scanning through hash table entries. This loop runs once for each
  187463. ** term/doclist currently stored within the hash table. */
  187464. if( p->rc==SQLITE_OK ){
  187465. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  187466. }
  187467. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  187468. const char *zTerm; /* Buffer containing term */
  187469. const u8 *pDoclist; /* Pointer to doclist for this term */
  187470. int nDoclist; /* Size of doclist in bytes */
  187471. /* Write the term for this entry to disk. */
  187472. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  187473. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  187474. assert( writer.bFirstRowidInPage==0 );
  187475. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  187476. /* The entire doclist will fit on the current leaf. */
  187477. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  187478. }else{
  187479. i64 iRowid = 0;
  187480. i64 iDelta = 0;
  187481. int iOff = 0;
  187482. /* The entire doclist will not fit on this leaf. The following
  187483. ** loop iterates through the poslists that make up the current
  187484. ** doclist. */
  187485. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  187486. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  187487. iRowid += iDelta;
  187488. if( writer.bFirstRowidInPage ){
  187489. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  187490. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  187491. writer.bFirstRowidInPage = 0;
  187492. fts5WriteDlidxAppend(p, &writer, iRowid);
  187493. }else{
  187494. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  187495. }
  187496. assert( pBuf->n<=pBuf->nSpace );
  187497. if( eDetail==FTS5_DETAIL_NONE ){
  187498. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  187499. pBuf->p[pBuf->n++] = 0;
  187500. iOff++;
  187501. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  187502. pBuf->p[pBuf->n++] = 0;
  187503. iOff++;
  187504. }
  187505. }
  187506. if( (pBuf->n + pPgidx->n)>=pgsz ){
  187507. fts5WriteFlushLeaf(p, &writer);
  187508. }
  187509. }else{
  187510. int bDummy;
  187511. int nPos;
  187512. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  187513. nCopy += nPos;
  187514. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  187515. /* The entire poslist will fit on the current leaf. So copy
  187516. ** it in one go. */
  187517. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  187518. }else{
  187519. /* The entire poslist will not fit on this leaf. So it needs
  187520. ** to be broken into sections. The only qualification being
  187521. ** that each varint must be stored contiguously. */
  187522. const u8 *pPoslist = &pDoclist[iOff];
  187523. int iPos = 0;
  187524. while( p->rc==SQLITE_OK ){
  187525. int nSpace = pgsz - pBuf->n - pPgidx->n;
  187526. int n = 0;
  187527. if( (nCopy - iPos)<=nSpace ){
  187528. n = nCopy - iPos;
  187529. }else{
  187530. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  187531. }
  187532. assert( n>0 );
  187533. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  187534. iPos += n;
  187535. if( (pBuf->n + pPgidx->n)>=pgsz ){
  187536. fts5WriteFlushLeaf(p, &writer);
  187537. }
  187538. if( iPos>=nCopy ) break;
  187539. }
  187540. }
  187541. iOff += nCopy;
  187542. }
  187543. }
  187544. }
  187545. /* TODO2: Doclist terminator written here. */
  187546. /* pBuf->p[pBuf->n++] = '\0'; */
  187547. assert( pBuf->n<=pBuf->nSpace );
  187548. sqlite3Fts5HashScanNext(pHash);
  187549. }
  187550. sqlite3Fts5HashClear(pHash);
  187551. fts5WriteFinish(p, &writer, &pgnoLast);
  187552. /* Update the Fts5Structure. It is written back to the database by the
  187553. ** fts5StructureRelease() call below. */
  187554. if( pStruct->nLevel==0 ){
  187555. fts5StructureAddLevel(&p->rc, &pStruct);
  187556. }
  187557. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  187558. if( p->rc==SQLITE_OK ){
  187559. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  187560. pSeg->iSegid = iSegid;
  187561. pSeg->pgnoFirst = 1;
  187562. pSeg->pgnoLast = pgnoLast;
  187563. pStruct->nSegment++;
  187564. }
  187565. fts5StructurePromote(p, 0, pStruct);
  187566. }
  187567. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  187568. fts5IndexCrisismerge(p, &pStruct);
  187569. fts5StructureWrite(p, pStruct);
  187570. fts5StructureRelease(pStruct);
  187571. }
  187572. /*
  187573. ** Flush any data stored in the in-memory hash tables to the database.
  187574. */
  187575. static void fts5IndexFlush(Fts5Index *p){
  187576. /* Unless it is empty, flush the hash table to disk */
  187577. if( p->nPendingData ){
  187578. assert( p->pHash );
  187579. p->nPendingData = 0;
  187580. fts5FlushOneHash(p);
  187581. }
  187582. }
  187583. static Fts5Structure *fts5IndexOptimizeStruct(
  187584. Fts5Index *p,
  187585. Fts5Structure *pStruct
  187586. ){
  187587. Fts5Structure *pNew = 0;
  187588. int nByte = sizeof(Fts5Structure);
  187589. int nSeg = pStruct->nSegment;
  187590. int i;
  187591. /* Figure out if this structure requires optimization. A structure does
  187592. ** not require optimization if either:
  187593. **
  187594. ** + it consists of fewer than two segments, or
  187595. ** + all segments are on the same level, or
  187596. ** + all segments except one are currently inputs to a merge operation.
  187597. **
  187598. ** In the first case, return NULL. In the second, increment the ref-count
  187599. ** on *pStruct and return a copy of the pointer to it.
  187600. */
  187601. if( nSeg<2 ) return 0;
  187602. for(i=0; i<pStruct->nLevel; i++){
  187603. int nThis = pStruct->aLevel[i].nSeg;
  187604. if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
  187605. fts5StructureRef(pStruct);
  187606. return pStruct;
  187607. }
  187608. assert( pStruct->aLevel[i].nMerge<=nThis );
  187609. }
  187610. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  187611. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  187612. if( pNew ){
  187613. Fts5StructureLevel *pLvl;
  187614. nByte = nSeg * sizeof(Fts5StructureSegment);
  187615. pNew->nLevel = pStruct->nLevel+1;
  187616. pNew->nRef = 1;
  187617. pNew->nWriteCounter = pStruct->nWriteCounter;
  187618. pLvl = &pNew->aLevel[pStruct->nLevel];
  187619. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  187620. if( pLvl->aSeg ){
  187621. int iLvl, iSeg;
  187622. int iSegOut = 0;
  187623. /* Iterate through all segments, from oldest to newest. Add them to
  187624. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  187625. ** segment in the data structure. */
  187626. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  187627. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  187628. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  187629. iSegOut++;
  187630. }
  187631. }
  187632. pNew->nSegment = pLvl->nSeg = nSeg;
  187633. }else{
  187634. sqlite3_free(pNew);
  187635. pNew = 0;
  187636. }
  187637. }
  187638. return pNew;
  187639. }
  187640. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  187641. Fts5Structure *pStruct;
  187642. Fts5Structure *pNew = 0;
  187643. assert( p->rc==SQLITE_OK );
  187644. fts5IndexFlush(p);
  187645. pStruct = fts5StructureRead(p);
  187646. fts5StructureInvalidate(p);
  187647. if( pStruct ){
  187648. pNew = fts5IndexOptimizeStruct(p, pStruct);
  187649. }
  187650. fts5StructureRelease(pStruct);
  187651. assert( pNew==0 || pNew->nSegment>0 );
  187652. if( pNew ){
  187653. int iLvl;
  187654. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  187655. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  187656. int nRem = FTS5_OPT_WORK_UNIT;
  187657. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  187658. }
  187659. fts5StructureWrite(p, pNew);
  187660. fts5StructureRelease(pNew);
  187661. }
  187662. return fts5IndexReturn(p);
  187663. }
  187664. /*
  187665. ** This is called to implement the special "VALUES('merge', $nMerge)"
  187666. ** INSERT command.
  187667. */
  187668. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  187669. Fts5Structure *pStruct = fts5StructureRead(p);
  187670. if( pStruct ){
  187671. int nMin = p->pConfig->nUsermerge;
  187672. fts5StructureInvalidate(p);
  187673. if( nMerge<0 ){
  187674. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  187675. fts5StructureRelease(pStruct);
  187676. pStruct = pNew;
  187677. nMin = 2;
  187678. nMerge = nMerge*-1;
  187679. }
  187680. if( pStruct && pStruct->nLevel ){
  187681. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  187682. fts5StructureWrite(p, pStruct);
  187683. }
  187684. }
  187685. fts5StructureRelease(pStruct);
  187686. }
  187687. return fts5IndexReturn(p);
  187688. }
  187689. static void fts5AppendRowid(
  187690. Fts5Index *p,
  187691. i64 iDelta,
  187692. Fts5Iter *pUnused,
  187693. Fts5Buffer *pBuf
  187694. ){
  187695. UNUSED_PARAM(pUnused);
  187696. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  187697. }
  187698. static void fts5AppendPoslist(
  187699. Fts5Index *p,
  187700. i64 iDelta,
  187701. Fts5Iter *pMulti,
  187702. Fts5Buffer *pBuf
  187703. ){
  187704. int nData = pMulti->base.nData;
  187705. assert( nData>0 );
  187706. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
  187707. fts5BufferSafeAppendVarint(pBuf, iDelta);
  187708. fts5BufferSafeAppendVarint(pBuf, nData*2);
  187709. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  187710. }
  187711. }
  187712. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  187713. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  187714. assert( pIter->aPoslist );
  187715. if( p>=pIter->aEof ){
  187716. pIter->aPoslist = 0;
  187717. }else{
  187718. i64 iDelta;
  187719. p += fts5GetVarint(p, (u64*)&iDelta);
  187720. pIter->iRowid += iDelta;
  187721. /* Read position list size */
  187722. if( p[0] & 0x80 ){
  187723. int nPos;
  187724. pIter->nSize = fts5GetVarint32(p, nPos);
  187725. pIter->nPoslist = (nPos>>1);
  187726. }else{
  187727. pIter->nPoslist = ((int)(p[0])) >> 1;
  187728. pIter->nSize = 1;
  187729. }
  187730. pIter->aPoslist = p;
  187731. }
  187732. }
  187733. static void fts5DoclistIterInit(
  187734. Fts5Buffer *pBuf,
  187735. Fts5DoclistIter *pIter
  187736. ){
  187737. memset(pIter, 0, sizeof(*pIter));
  187738. pIter->aPoslist = pBuf->p;
  187739. pIter->aEof = &pBuf->p[pBuf->n];
  187740. fts5DoclistIterNext(pIter);
  187741. }
  187742. #if 0
  187743. /*
  187744. ** Append a doclist to buffer pBuf.
  187745. **
  187746. ** This function assumes that space within the buffer has already been
  187747. ** allocated.
  187748. */
  187749. static void fts5MergeAppendDocid(
  187750. Fts5Buffer *pBuf, /* Buffer to write to */
  187751. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  187752. i64 iRowid /* Rowid to append */
  187753. ){
  187754. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  187755. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  187756. *piLastRowid = iRowid;
  187757. }
  187758. #endif
  187759. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  187760. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  187761. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  187762. (iLastRowid) = (iRowid); \
  187763. }
  187764. /*
  187765. ** Swap the contents of buffer *p1 with that of *p2.
  187766. */
  187767. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  187768. Fts5Buffer tmp = *p1;
  187769. *p1 = *p2;
  187770. *p2 = tmp;
  187771. }
  187772. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  187773. int i = *piOff;
  187774. if( i>=pBuf->n ){
  187775. *piOff = -1;
  187776. }else{
  187777. u64 iVal;
  187778. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  187779. *piRowid += iVal;
  187780. }
  187781. }
  187782. /*
  187783. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  187784. ** In this case the buffers consist of a delta-encoded list of rowids only.
  187785. */
  187786. static void fts5MergeRowidLists(
  187787. Fts5Index *p, /* FTS5 backend object */
  187788. Fts5Buffer *p1, /* First list to merge */
  187789. Fts5Buffer *p2 /* Second list to merge */
  187790. ){
  187791. int i1 = 0;
  187792. int i2 = 0;
  187793. i64 iRowid1 = 0;
  187794. i64 iRowid2 = 0;
  187795. i64 iOut = 0;
  187796. Fts5Buffer out;
  187797. memset(&out, 0, sizeof(out));
  187798. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  187799. if( p->rc ) return;
  187800. fts5NextRowid(p1, &i1, &iRowid1);
  187801. fts5NextRowid(p2, &i2, &iRowid2);
  187802. while( i1>=0 || i2>=0 ){
  187803. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  187804. assert( iOut==0 || iRowid1>iOut );
  187805. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  187806. iOut = iRowid1;
  187807. fts5NextRowid(p1, &i1, &iRowid1);
  187808. }else{
  187809. assert( iOut==0 || iRowid2>iOut );
  187810. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  187811. iOut = iRowid2;
  187812. if( i1>=0 && iRowid1==iRowid2 ){
  187813. fts5NextRowid(p1, &i1, &iRowid1);
  187814. }
  187815. fts5NextRowid(p2, &i2, &iRowid2);
  187816. }
  187817. }
  187818. fts5BufferSwap(&out, p1);
  187819. fts5BufferFree(&out);
  187820. }
  187821. /*
  187822. ** Buffers p1 and p2 contain doclists. This function merges the content
  187823. ** of the two doclists together and sets buffer p1 to the result before
  187824. ** returning.
  187825. **
  187826. ** If an error occurs, an error code is left in p->rc. If an error has
  187827. ** already occurred, this function is a no-op.
  187828. */
  187829. static void fts5MergePrefixLists(
  187830. Fts5Index *p, /* FTS5 backend object */
  187831. Fts5Buffer *p1, /* First list to merge */
  187832. Fts5Buffer *p2 /* Second list to merge */
  187833. ){
  187834. if( p2->n ){
  187835. i64 iLastRowid = 0;
  187836. Fts5DoclistIter i1;
  187837. Fts5DoclistIter i2;
  187838. Fts5Buffer out = {0, 0, 0};
  187839. Fts5Buffer tmp = {0, 0, 0};
  187840. /* The maximum size of the output is equal to the sum of the two
  187841. ** input sizes + 1 varint (9 bytes). The extra varint is because if the
  187842. ** first rowid in one input is a large negative number, and the first in
  187843. ** the other a non-negative number, the delta for the non-negative
  187844. ** number will be larger on disk than the literal integer value
  187845. ** was. */
  187846. if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9) ) return;
  187847. fts5DoclistIterInit(p1, &i1);
  187848. fts5DoclistIterInit(p2, &i2);
  187849. while( 1 ){
  187850. if( i1.iRowid<i2.iRowid ){
  187851. /* Copy entry from i1 */
  187852. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  187853. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  187854. fts5DoclistIterNext(&i1);
  187855. if( i1.aPoslist==0 ) break;
  187856. }
  187857. else if( i2.iRowid!=i1.iRowid ){
  187858. /* Copy entry from i2 */
  187859. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  187860. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  187861. fts5DoclistIterNext(&i2);
  187862. if( i2.aPoslist==0 ) break;
  187863. }
  187864. else{
  187865. /* Merge the two position lists. */
  187866. i64 iPos1 = 0;
  187867. i64 iPos2 = 0;
  187868. int iOff1 = 0;
  187869. int iOff2 = 0;
  187870. u8 *a1 = &i1.aPoslist[i1.nSize];
  187871. u8 *a2 = &i2.aPoslist[i2.nSize];
  187872. i64 iPrev = 0;
  187873. Fts5PoslistWriter writer;
  187874. memset(&writer, 0, sizeof(writer));
  187875. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  187876. fts5BufferZero(&tmp);
  187877. sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
  187878. if( p->rc ) break;
  187879. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  187880. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  187881. assert( iPos1>=0 && iPos2>=0 );
  187882. if( iPos1<iPos2 ){
  187883. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  187884. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  187885. }else{
  187886. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  187887. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  187888. }
  187889. if( iPos1>=0 && iPos2>=0 ){
  187890. while( 1 ){
  187891. if( iPos1<iPos2 ){
  187892. if( iPos1!=iPrev ){
  187893. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  187894. }
  187895. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  187896. if( iPos1<0 ) break;
  187897. }else{
  187898. assert( iPos2!=iPrev );
  187899. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  187900. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  187901. if( iPos2<0 ) break;
  187902. }
  187903. }
  187904. }
  187905. if( iPos1>=0 ){
  187906. if( iPos1!=iPrev ){
  187907. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  187908. }
  187909. fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
  187910. }else{
  187911. assert( iPos2>=0 && iPos2!=iPrev );
  187912. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  187913. fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
  187914. }
  187915. /* WRITEPOSLISTSIZE */
  187916. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  187917. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  187918. fts5DoclistIterNext(&i1);
  187919. fts5DoclistIterNext(&i2);
  187920. if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
  187921. }
  187922. }
  187923. if( i1.aPoslist ){
  187924. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  187925. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
  187926. }
  187927. else if( i2.aPoslist ){
  187928. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  187929. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
  187930. }
  187931. assert( out.n<=(p1->n+p2->n+9) );
  187932. fts5BufferSet(&p->rc, p1, out.n, out.p);
  187933. fts5BufferFree(&tmp);
  187934. fts5BufferFree(&out);
  187935. }
  187936. }
  187937. static void fts5SetupPrefixIter(
  187938. Fts5Index *p, /* Index to read from */
  187939. int bDesc, /* True for "ORDER BY rowid DESC" */
  187940. const u8 *pToken, /* Buffer containing prefix to match */
  187941. int nToken, /* Size of buffer pToken in bytes */
  187942. Fts5Colset *pColset, /* Restrict matches to these columns */
  187943. Fts5Iter **ppIter /* OUT: New iterator */
  187944. ){
  187945. Fts5Structure *pStruct;
  187946. Fts5Buffer *aBuf;
  187947. const int nBuf = 32;
  187948. void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
  187949. void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
  187950. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  187951. xMerge = fts5MergeRowidLists;
  187952. xAppend = fts5AppendRowid;
  187953. }else{
  187954. xMerge = fts5MergePrefixLists;
  187955. xAppend = fts5AppendPoslist;
  187956. }
  187957. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  187958. pStruct = fts5StructureRead(p);
  187959. if( aBuf && pStruct ){
  187960. const int flags = FTS5INDEX_QUERY_SCAN
  187961. | FTS5INDEX_QUERY_SKIPEMPTY
  187962. | FTS5INDEX_QUERY_NOOUTPUT;
  187963. int i;
  187964. i64 iLastRowid = 0;
  187965. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  187966. Fts5Data *pData;
  187967. Fts5Buffer doclist;
  187968. int bNewTerm = 1;
  187969. memset(&doclist, 0, sizeof(doclist));
  187970. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  187971. fts5IterSetOutputCb(&p->rc, p1);
  187972. for( /* no-op */ ;
  187973. fts5MultiIterEof(p, p1)==0;
  187974. fts5MultiIterNext2(p, p1, &bNewTerm)
  187975. ){
  187976. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  187977. int nTerm = pSeg->term.n;
  187978. const u8 *pTerm = pSeg->term.p;
  187979. p1->xSetOutputs(p1, pSeg);
  187980. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  187981. if( bNewTerm ){
  187982. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  187983. }
  187984. if( p1->base.nData==0 ) continue;
  187985. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  187986. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  187987. assert( i<nBuf );
  187988. if( aBuf[i].n==0 ){
  187989. fts5BufferSwap(&doclist, &aBuf[i]);
  187990. fts5BufferZero(&doclist);
  187991. }else{
  187992. xMerge(p, &doclist, &aBuf[i]);
  187993. fts5BufferZero(&aBuf[i]);
  187994. }
  187995. }
  187996. iLastRowid = 0;
  187997. }
  187998. xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
  187999. iLastRowid = p1->base.iRowid;
  188000. }
  188001. for(i=0; i<nBuf; i++){
  188002. if( p->rc==SQLITE_OK ){
  188003. xMerge(p, &doclist, &aBuf[i]);
  188004. }
  188005. fts5BufferFree(&aBuf[i]);
  188006. }
  188007. fts5MultiIterFree(p1);
  188008. pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
  188009. if( pData ){
  188010. pData->p = (u8*)&pData[1];
  188011. pData->nn = pData->szLeaf = doclist.n;
  188012. if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
  188013. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  188014. }
  188015. fts5BufferFree(&doclist);
  188016. }
  188017. fts5StructureRelease(pStruct);
  188018. sqlite3_free(aBuf);
  188019. }
  188020. /*
  188021. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  188022. ** to the document with rowid iRowid.
  188023. */
  188024. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  188025. assert( p->rc==SQLITE_OK );
  188026. /* Allocate the hash table if it has not already been allocated */
  188027. if( p->pHash==0 ){
  188028. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  188029. }
  188030. /* Flush the hash table to disk if required */
  188031. if( iRowid<p->iWriteRowid
  188032. || (iRowid==p->iWriteRowid && p->bDelete==0)
  188033. || (p->nPendingData > p->pConfig->nHashSize)
  188034. ){
  188035. fts5IndexFlush(p);
  188036. }
  188037. p->iWriteRowid = iRowid;
  188038. p->bDelete = bDelete;
  188039. return fts5IndexReturn(p);
  188040. }
  188041. /*
  188042. ** Commit data to disk.
  188043. */
  188044. static int sqlite3Fts5IndexSync(Fts5Index *p){
  188045. assert( p->rc==SQLITE_OK );
  188046. fts5IndexFlush(p);
  188047. fts5CloseReader(p);
  188048. return fts5IndexReturn(p);
  188049. }
  188050. /*
  188051. ** Discard any data stored in the in-memory hash tables. Do not write it
  188052. ** to the database. Additionally, assume that the contents of the %_data
  188053. ** table may have changed on disk. So any in-memory caches of %_data
  188054. ** records must be invalidated.
  188055. */
  188056. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  188057. fts5CloseReader(p);
  188058. fts5IndexDiscardData(p);
  188059. fts5StructureInvalidate(p);
  188060. /* assert( p->rc==SQLITE_OK ); */
  188061. return SQLITE_OK;
  188062. }
  188063. /*
  188064. ** The %_data table is completely empty when this function is called. This
  188065. ** function populates it with the initial structure objects for each index,
  188066. ** and the initial version of the "averages" record (a zero-byte blob).
  188067. */
  188068. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  188069. Fts5Structure s;
  188070. fts5StructureInvalidate(p);
  188071. memset(&s, 0, sizeof(Fts5Structure));
  188072. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  188073. fts5StructureWrite(p, &s);
  188074. return fts5IndexReturn(p);
  188075. }
  188076. /*
  188077. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  188078. ** and initialize the underlying %_data table.
  188079. **
  188080. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  188081. ** Otherwise, set *pp to NULL and return an SQLite error code.
  188082. */
  188083. static int sqlite3Fts5IndexOpen(
  188084. Fts5Config *pConfig,
  188085. int bCreate,
  188086. Fts5Index **pp,
  188087. char **pzErr
  188088. ){
  188089. int rc = SQLITE_OK;
  188090. Fts5Index *p; /* New object */
  188091. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  188092. if( rc==SQLITE_OK ){
  188093. p->pConfig = pConfig;
  188094. p->nWorkUnit = FTS5_WORK_UNIT;
  188095. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  188096. if( p->zDataTbl && bCreate ){
  188097. rc = sqlite3Fts5CreateTable(
  188098. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  188099. );
  188100. if( rc==SQLITE_OK ){
  188101. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  188102. "segid, term, pgno, PRIMARY KEY(segid, term)",
  188103. 1, pzErr
  188104. );
  188105. }
  188106. if( rc==SQLITE_OK ){
  188107. rc = sqlite3Fts5IndexReinit(p);
  188108. }
  188109. }
  188110. }
  188111. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  188112. if( rc ){
  188113. sqlite3Fts5IndexClose(p);
  188114. *pp = 0;
  188115. }
  188116. return rc;
  188117. }
  188118. /*
  188119. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  188120. */
  188121. static int sqlite3Fts5IndexClose(Fts5Index *p){
  188122. int rc = SQLITE_OK;
  188123. if( p ){
  188124. assert( p->pReader==0 );
  188125. fts5StructureInvalidate(p);
  188126. sqlite3_finalize(p->pWriter);
  188127. sqlite3_finalize(p->pDeleter);
  188128. sqlite3_finalize(p->pIdxWriter);
  188129. sqlite3_finalize(p->pIdxDeleter);
  188130. sqlite3_finalize(p->pIdxSelect);
  188131. sqlite3_finalize(p->pDataVersion);
  188132. sqlite3Fts5HashFree(p->pHash);
  188133. sqlite3_free(p->zDataTbl);
  188134. sqlite3_free(p);
  188135. }
  188136. return rc;
  188137. }
  188138. /*
  188139. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  188140. ** size. Return the number of bytes in the nChar character prefix of the
  188141. ** buffer, or 0 if there are less than nChar characters in total.
  188142. */
  188143. static int sqlite3Fts5IndexCharlenToBytelen(
  188144. const char *p,
  188145. int nByte,
  188146. int nChar
  188147. ){
  188148. int n = 0;
  188149. int i;
  188150. for(i=0; i<nChar; i++){
  188151. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  188152. if( (unsigned char)p[n++]>=0xc0 ){
  188153. while( (p[n] & 0xc0)==0x80 ) n++;
  188154. }
  188155. }
  188156. return n;
  188157. }
  188158. /*
  188159. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  188160. ** unicode characters in the string.
  188161. */
  188162. static int fts5IndexCharlen(const char *pIn, int nIn){
  188163. int nChar = 0;
  188164. int i = 0;
  188165. while( i<nIn ){
  188166. if( (unsigned char)pIn[i++]>=0xc0 ){
  188167. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  188168. }
  188169. nChar++;
  188170. }
  188171. return nChar;
  188172. }
  188173. /*
  188174. ** Insert or remove data to or from the index. Each time a document is
  188175. ** added to or removed from the index, this function is called one or more
  188176. ** times.
  188177. **
  188178. ** For an insert, it must be called once for each token in the new document.
  188179. ** If the operation is a delete, it must be called (at least) once for each
  188180. ** unique token in the document with an iCol value less than zero. The iPos
  188181. ** argument is ignored for a delete.
  188182. */
  188183. static int sqlite3Fts5IndexWrite(
  188184. Fts5Index *p, /* Index to write to */
  188185. int iCol, /* Column token appears in (-ve -> delete) */
  188186. int iPos, /* Position of token within column */
  188187. const char *pToken, int nToken /* Token to add or remove to or from index */
  188188. ){
  188189. int i; /* Used to iterate through indexes */
  188190. int rc = SQLITE_OK; /* Return code */
  188191. Fts5Config *pConfig = p->pConfig;
  188192. assert( p->rc==SQLITE_OK );
  188193. assert( (iCol<0)==p->bDelete );
  188194. /* Add the entry to the main terms index. */
  188195. rc = sqlite3Fts5HashWrite(
  188196. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  188197. );
  188198. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  188199. const int nChar = pConfig->aPrefix[i];
  188200. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  188201. if( nByte ){
  188202. rc = sqlite3Fts5HashWrite(p->pHash,
  188203. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  188204. nByte
  188205. );
  188206. }
  188207. }
  188208. return rc;
  188209. }
  188210. /*
  188211. ** Open a new iterator to iterate though all rowid that match the
  188212. ** specified token or token prefix.
  188213. */
  188214. static int sqlite3Fts5IndexQuery(
  188215. Fts5Index *p, /* FTS index to query */
  188216. const char *pToken, int nToken, /* Token (or prefix) to query for */
  188217. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  188218. Fts5Colset *pColset, /* Match these columns only */
  188219. Fts5IndexIter **ppIter /* OUT: New iterator object */
  188220. ){
  188221. Fts5Config *pConfig = p->pConfig;
  188222. Fts5Iter *pRet = 0;
  188223. Fts5Buffer buf = {0, 0, 0};
  188224. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  188225. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  188226. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  188227. int iIdx = 0; /* Index to search */
  188228. if( nToken ) memcpy(&buf.p[1], pToken, nToken);
  188229. /* Figure out which index to search and set iIdx accordingly. If this
  188230. ** is a prefix query for which there is no prefix index, set iIdx to
  188231. ** greater than pConfig->nPrefix to indicate that the query will be
  188232. ** satisfied by scanning multiple terms in the main index.
  188233. **
  188234. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  188235. ** prefix-query. Instead of using a prefix-index (if one exists),
  188236. ** evaluate the prefix query using the main FTS index. This is used
  188237. ** for internal sanity checking by the integrity-check in debug
  188238. ** mode only. */
  188239. #ifdef SQLITE_DEBUG
  188240. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  188241. assert( flags & FTS5INDEX_QUERY_PREFIX );
  188242. iIdx = 1+pConfig->nPrefix;
  188243. }else
  188244. #endif
  188245. if( flags & FTS5INDEX_QUERY_PREFIX ){
  188246. int nChar = fts5IndexCharlen(pToken, nToken);
  188247. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  188248. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  188249. }
  188250. }
  188251. if( iIdx<=pConfig->nPrefix ){
  188252. /* Straight index lookup */
  188253. Fts5Structure *pStruct = fts5StructureRead(p);
  188254. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  188255. if( pStruct ){
  188256. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  188257. pColset, buf.p, nToken+1, -1, 0, &pRet
  188258. );
  188259. fts5StructureRelease(pStruct);
  188260. }
  188261. }else{
  188262. /* Scan multiple terms in the main index */
  188263. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  188264. buf.p[0] = FTS5_MAIN_PREFIX;
  188265. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  188266. assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
  188267. fts5IterSetOutputCb(&p->rc, pRet);
  188268. if( p->rc==SQLITE_OK ){
  188269. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  188270. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  188271. }
  188272. }
  188273. if( p->rc ){
  188274. sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
  188275. pRet = 0;
  188276. fts5CloseReader(p);
  188277. }
  188278. *ppIter = &pRet->base;
  188279. sqlite3Fts5BufferFree(&buf);
  188280. }
  188281. return fts5IndexReturn(p);
  188282. }
  188283. /*
  188284. ** Return true if the iterator passed as the only argument is at EOF.
  188285. */
  188286. /*
  188287. ** Move to the next matching rowid.
  188288. */
  188289. static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  188290. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  188291. assert( pIter->pIndex->rc==SQLITE_OK );
  188292. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  188293. return fts5IndexReturn(pIter->pIndex);
  188294. }
  188295. /*
  188296. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  188297. */
  188298. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  188299. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  188300. Fts5Index *p = pIter->pIndex;
  188301. assert( pIter->pIndex->rc==SQLITE_OK );
  188302. fts5MultiIterNext(p, pIter, 0, 0);
  188303. if( p->rc==SQLITE_OK ){
  188304. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  188305. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  188306. fts5DataRelease(pSeg->pLeaf);
  188307. pSeg->pLeaf = 0;
  188308. pIter->base.bEof = 1;
  188309. }
  188310. }
  188311. return fts5IndexReturn(pIter->pIndex);
  188312. }
  188313. /*
  188314. ** Move to the next matching rowid that occurs at or after iMatch. The
  188315. ** definition of "at or after" depends on whether this iterator iterates
  188316. ** in ascending or descending rowid order.
  188317. */
  188318. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  188319. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  188320. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  188321. return fts5IndexReturn(pIter->pIndex);
  188322. }
  188323. /*
  188324. ** Return the current term.
  188325. */
  188326. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  188327. int n;
  188328. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  188329. *pn = n-1;
  188330. return &z[1];
  188331. }
  188332. /*
  188333. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  188334. */
  188335. static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  188336. if( pIndexIter ){
  188337. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  188338. Fts5Index *pIndex = pIter->pIndex;
  188339. fts5MultiIterFree(pIter);
  188340. fts5CloseReader(pIndex);
  188341. }
  188342. }
  188343. /*
  188344. ** Read and decode the "averages" record from the database.
  188345. **
  188346. ** Parameter anSize must point to an array of size nCol, where nCol is
  188347. ** the number of user defined columns in the FTS table.
  188348. */
  188349. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  188350. int nCol = p->pConfig->nCol;
  188351. Fts5Data *pData;
  188352. *pnRow = 0;
  188353. memset(anSize, 0, sizeof(i64) * nCol);
  188354. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  188355. if( p->rc==SQLITE_OK && pData->nn ){
  188356. int i = 0;
  188357. int iCol;
  188358. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  188359. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  188360. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  188361. }
  188362. }
  188363. fts5DataRelease(pData);
  188364. return fts5IndexReturn(p);
  188365. }
  188366. /*
  188367. ** Replace the current "averages" record with the contents of the buffer
  188368. ** supplied as the second argument.
  188369. */
  188370. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  188371. assert( p->rc==SQLITE_OK );
  188372. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  188373. return fts5IndexReturn(p);
  188374. }
  188375. /*
  188376. ** Return the total number of blocks this module has read from the %_data
  188377. ** table since it was created.
  188378. */
  188379. static int sqlite3Fts5IndexReads(Fts5Index *p){
  188380. return p->nRead;
  188381. }
  188382. /*
  188383. ** Set the 32-bit cookie value stored at the start of all structure
  188384. ** records to the value passed as the second argument.
  188385. **
  188386. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  188387. ** occurs.
  188388. */
  188389. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  188390. int rc; /* Return code */
  188391. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  188392. u8 aCookie[4]; /* Binary representation of iNew */
  188393. sqlite3_blob *pBlob = 0;
  188394. assert( p->rc==SQLITE_OK );
  188395. sqlite3Fts5Put32(aCookie, iNew);
  188396. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  188397. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  188398. );
  188399. if( rc==SQLITE_OK ){
  188400. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  188401. rc = sqlite3_blob_close(pBlob);
  188402. }
  188403. return rc;
  188404. }
  188405. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  188406. Fts5Structure *pStruct;
  188407. pStruct = fts5StructureRead(p);
  188408. fts5StructureRelease(pStruct);
  188409. return fts5IndexReturn(p);
  188410. }
  188411. /*************************************************************************
  188412. **************************************************************************
  188413. ** Below this point is the implementation of the integrity-check
  188414. ** functionality.
  188415. */
  188416. /*
  188417. ** Return a simple checksum value based on the arguments.
  188418. */
  188419. static u64 sqlite3Fts5IndexEntryCksum(
  188420. i64 iRowid,
  188421. int iCol,
  188422. int iPos,
  188423. int iIdx,
  188424. const char *pTerm,
  188425. int nTerm
  188426. ){
  188427. int i;
  188428. u64 ret = iRowid;
  188429. ret += (ret<<3) + iCol;
  188430. ret += (ret<<3) + iPos;
  188431. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  188432. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  188433. return ret;
  188434. }
  188435. #ifdef SQLITE_DEBUG
  188436. /*
  188437. ** This function is purely an internal test. It does not contribute to
  188438. ** FTS functionality, or even the integrity-check, in any way.
  188439. **
  188440. ** Instead, it tests that the same set of pgno/rowid combinations are
  188441. ** visited regardless of whether the doclist-index identified by parameters
  188442. ** iSegid/iLeaf is iterated in forwards or reverse order.
  188443. */
  188444. static void fts5TestDlidxReverse(
  188445. Fts5Index *p,
  188446. int iSegid, /* Segment id to load from */
  188447. int iLeaf /* Load doclist-index for this leaf */
  188448. ){
  188449. Fts5DlidxIter *pDlidx = 0;
  188450. u64 cksum1 = 13;
  188451. u64 cksum2 = 13;
  188452. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  188453. fts5DlidxIterEof(p, pDlidx)==0;
  188454. fts5DlidxIterNext(p, pDlidx)
  188455. ){
  188456. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  188457. int pgno = fts5DlidxIterPgno(pDlidx);
  188458. assert( pgno>iLeaf );
  188459. cksum1 += iRowid + ((i64)pgno<<32);
  188460. }
  188461. fts5DlidxIterFree(pDlidx);
  188462. pDlidx = 0;
  188463. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  188464. fts5DlidxIterEof(p, pDlidx)==0;
  188465. fts5DlidxIterPrev(p, pDlidx)
  188466. ){
  188467. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  188468. int pgno = fts5DlidxIterPgno(pDlidx);
  188469. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  188470. cksum2 += iRowid + ((i64)pgno<<32);
  188471. }
  188472. fts5DlidxIterFree(pDlidx);
  188473. pDlidx = 0;
  188474. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  188475. }
  188476. static int fts5QueryCksum(
  188477. Fts5Index *p, /* Fts5 index object */
  188478. int iIdx,
  188479. const char *z, /* Index key to query for */
  188480. int n, /* Size of index key in bytes */
  188481. int flags, /* Flags for Fts5IndexQuery */
  188482. u64 *pCksum /* IN/OUT: Checksum value */
  188483. ){
  188484. int eDetail = p->pConfig->eDetail;
  188485. u64 cksum = *pCksum;
  188486. Fts5IndexIter *pIter = 0;
  188487. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
  188488. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
  188489. i64 rowid = pIter->iRowid;
  188490. if( eDetail==FTS5_DETAIL_NONE ){
  188491. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  188492. }else{
  188493. Fts5PoslistReader sReader;
  188494. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  188495. sReader.bEof==0;
  188496. sqlite3Fts5PoslistReaderNext(&sReader)
  188497. ){
  188498. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  188499. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  188500. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  188501. }
  188502. }
  188503. if( rc==SQLITE_OK ){
  188504. rc = sqlite3Fts5IterNext(pIter);
  188505. }
  188506. }
  188507. sqlite3Fts5IterClose(pIter);
  188508. *pCksum = cksum;
  188509. return rc;
  188510. }
  188511. /*
  188512. ** This function is also purely an internal test. It does not contribute to
  188513. ** FTS functionality, or even the integrity-check, in any way.
  188514. */
  188515. static void fts5TestTerm(
  188516. Fts5Index *p,
  188517. Fts5Buffer *pPrev, /* Previous term */
  188518. const char *z, int n, /* Possibly new term to test */
  188519. u64 expected,
  188520. u64 *pCksum
  188521. ){
  188522. int rc = p->rc;
  188523. if( pPrev->n==0 ){
  188524. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  188525. }else
  188526. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  188527. u64 cksum3 = *pCksum;
  188528. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  188529. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  188530. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  188531. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  188532. u64 ck1 = 0;
  188533. u64 ck2 = 0;
  188534. /* Check that the results returned for ASC and DESC queries are
  188535. ** the same. If not, call this corruption. */
  188536. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  188537. if( rc==SQLITE_OK ){
  188538. int f = flags|FTS5INDEX_QUERY_DESC;
  188539. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  188540. }
  188541. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  188542. /* If this is a prefix query, check that the results returned if the
  188543. ** the index is disabled are the same. In both ASC and DESC order.
  188544. **
  188545. ** This check may only be performed if the hash table is empty. This
  188546. ** is because the hash table only supports a single scan query at
  188547. ** a time, and the multi-iter loop from which this function is called
  188548. ** is already performing such a scan. */
  188549. if( p->nPendingData==0 ){
  188550. if( iIdx>0 && rc==SQLITE_OK ){
  188551. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  188552. ck2 = 0;
  188553. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  188554. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  188555. }
  188556. if( iIdx>0 && rc==SQLITE_OK ){
  188557. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  188558. ck2 = 0;
  188559. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  188560. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  188561. }
  188562. }
  188563. cksum3 ^= ck1;
  188564. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  188565. if( rc==SQLITE_OK && cksum3!=expected ){
  188566. rc = FTS5_CORRUPT;
  188567. }
  188568. *pCksum = cksum3;
  188569. }
  188570. p->rc = rc;
  188571. }
  188572. #else
  188573. # define fts5TestDlidxReverse(x,y,z)
  188574. # define fts5TestTerm(u,v,w,x,y,z)
  188575. #endif
  188576. /*
  188577. ** Check that:
  188578. **
  188579. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  188580. ** contain zero terms.
  188581. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  188582. ** contain zero rowids.
  188583. */
  188584. static void fts5IndexIntegrityCheckEmpty(
  188585. Fts5Index *p,
  188586. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  188587. int iFirst,
  188588. int iNoRowid,
  188589. int iLast
  188590. ){
  188591. int i;
  188592. /* Now check that the iter.nEmpty leaves following the current leaf
  188593. ** (a) exist and (b) contain no terms. */
  188594. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  188595. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  188596. if( pLeaf ){
  188597. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  188598. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  188599. }
  188600. fts5DataRelease(pLeaf);
  188601. }
  188602. }
  188603. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  188604. int iTermOff = 0;
  188605. int ii;
  188606. Fts5Buffer buf1 = {0,0,0};
  188607. Fts5Buffer buf2 = {0,0,0};
  188608. ii = pLeaf->szLeaf;
  188609. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  188610. int res;
  188611. int iOff;
  188612. int nIncr;
  188613. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  188614. iTermOff += nIncr;
  188615. iOff = iTermOff;
  188616. if( iOff>=pLeaf->szLeaf ){
  188617. p->rc = FTS5_CORRUPT;
  188618. }else if( iTermOff==nIncr ){
  188619. int nByte;
  188620. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  188621. if( (iOff+nByte)>pLeaf->szLeaf ){
  188622. p->rc = FTS5_CORRUPT;
  188623. }else{
  188624. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  188625. }
  188626. }else{
  188627. int nKeep, nByte;
  188628. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  188629. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  188630. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  188631. p->rc = FTS5_CORRUPT;
  188632. }else{
  188633. buf1.n = nKeep;
  188634. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  188635. }
  188636. if( p->rc==SQLITE_OK ){
  188637. res = fts5BufferCompare(&buf1, &buf2);
  188638. if( res<=0 ) p->rc = FTS5_CORRUPT;
  188639. }
  188640. }
  188641. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  188642. }
  188643. fts5BufferFree(&buf1);
  188644. fts5BufferFree(&buf2);
  188645. }
  188646. static void fts5IndexIntegrityCheckSegment(
  188647. Fts5Index *p, /* FTS5 backend object */
  188648. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  188649. ){
  188650. Fts5Config *pConfig = p->pConfig;
  188651. sqlite3_stmt *pStmt = 0;
  188652. int rc2;
  188653. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  188654. int iDlidxPrevLeaf = pSeg->pgnoLast;
  188655. if( pSeg->pgnoFirst==0 ) return;
  188656. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  188657. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
  188658. pConfig->zDb, pConfig->zName, pSeg->iSegid
  188659. ));
  188660. /* Iterate through the b-tree hierarchy. */
  188661. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  188662. i64 iRow; /* Rowid for this leaf */
  188663. Fts5Data *pLeaf; /* Data for this leaf */
  188664. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  188665. const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
  188666. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  188667. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  188668. /* If the leaf in question has already been trimmed from the segment,
  188669. ** ignore this b-tree entry. Otherwise, load it into memory. */
  188670. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  188671. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  188672. pLeaf = fts5LeafRead(p, iRow);
  188673. if( pLeaf==0 ) break;
  188674. /* Check that the leaf contains at least one term, and that it is equal
  188675. ** to or larger than the split-key in zIdxTerm. Also check that if there
  188676. ** is also a rowid pointer within the leaf page header, it points to a
  188677. ** location before the term. */
  188678. if( pLeaf->nn<=pLeaf->szLeaf ){
  188679. p->rc = FTS5_CORRUPT;
  188680. }else{
  188681. int iOff; /* Offset of first term on leaf */
  188682. int iRowidOff; /* Offset of first rowid on leaf */
  188683. int nTerm; /* Size of term on leaf in bytes */
  188684. int res; /* Comparison of term and split-key */
  188685. iOff = fts5LeafFirstTermOff(pLeaf);
  188686. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  188687. if( iRowidOff>=iOff ){
  188688. p->rc = FTS5_CORRUPT;
  188689. }else{
  188690. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  188691. res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  188692. if( res==0 ) res = nTerm - nIdxTerm;
  188693. if( res<0 ) p->rc = FTS5_CORRUPT;
  188694. }
  188695. fts5IntegrityCheckPgidx(p, pLeaf);
  188696. }
  188697. fts5DataRelease(pLeaf);
  188698. if( p->rc ) break;
  188699. /* Now check that the iter.nEmpty leaves following the current leaf
  188700. ** (a) exist and (b) contain no terms. */
  188701. fts5IndexIntegrityCheckEmpty(
  188702. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  188703. );
  188704. if( p->rc ) break;
  188705. /* If there is a doclist-index, check that it looks right. */
  188706. if( bIdxDlidx ){
  188707. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  188708. int iPrevLeaf = iIdxLeaf;
  188709. int iSegid = pSeg->iSegid;
  188710. int iPg = 0;
  188711. i64 iKey;
  188712. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  188713. fts5DlidxIterEof(p, pDlidx)==0;
  188714. fts5DlidxIterNext(p, pDlidx)
  188715. ){
  188716. /* Check any rowid-less pages that occur before the current leaf. */
  188717. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  188718. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  188719. pLeaf = fts5DataRead(p, iKey);
  188720. if( pLeaf ){
  188721. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  188722. fts5DataRelease(pLeaf);
  188723. }
  188724. }
  188725. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  188726. /* Check that the leaf page indicated by the iterator really does
  188727. ** contain the rowid suggested by the same. */
  188728. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  188729. pLeaf = fts5DataRead(p, iKey);
  188730. if( pLeaf ){
  188731. i64 iRowid;
  188732. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  188733. ASSERT_SZLEAF_OK(pLeaf);
  188734. if( iRowidOff>=pLeaf->szLeaf ){
  188735. p->rc = FTS5_CORRUPT;
  188736. }else{
  188737. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  188738. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  188739. }
  188740. fts5DataRelease(pLeaf);
  188741. }
  188742. }
  188743. iDlidxPrevLeaf = iPg;
  188744. fts5DlidxIterFree(pDlidx);
  188745. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  188746. }else{
  188747. iDlidxPrevLeaf = pSeg->pgnoLast;
  188748. /* TODO: Check there is no doclist index */
  188749. }
  188750. iIdxPrevLeaf = iIdxLeaf;
  188751. }
  188752. rc2 = sqlite3_finalize(pStmt);
  188753. if( p->rc==SQLITE_OK ) p->rc = rc2;
  188754. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  188755. #if 0
  188756. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  188757. p->rc = FTS5_CORRUPT;
  188758. }
  188759. #endif
  188760. }
  188761. /*
  188762. ** Run internal checks to ensure that the FTS index (a) is internally
  188763. ** consistent and (b) contains entries for which the XOR of the checksums
  188764. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  188765. **
  188766. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  188767. ** checksum does not match. Return SQLITE_OK if all checks pass without
  188768. ** error, or some other SQLite error code if another error (e.g. OOM)
  188769. ** occurs.
  188770. */
  188771. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  188772. int eDetail = p->pConfig->eDetail;
  188773. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  188774. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  188775. Fts5Iter *pIter; /* Used to iterate through entire index */
  188776. Fts5Structure *pStruct; /* Index structure */
  188777. #ifdef SQLITE_DEBUG
  188778. /* Used by extra internal tests only run if NDEBUG is not defined */
  188779. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  188780. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  188781. #endif
  188782. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  188783. /* Load the FTS index structure */
  188784. pStruct = fts5StructureRead(p);
  188785. /* Check that the internal nodes of each segment match the leaves */
  188786. if( pStruct ){
  188787. int iLvl, iSeg;
  188788. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  188789. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  188790. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  188791. fts5IndexIntegrityCheckSegment(p, pSeg);
  188792. }
  188793. }
  188794. }
  188795. /* The cksum argument passed to this function is a checksum calculated
  188796. ** based on all expected entries in the FTS index (including prefix index
  188797. ** entries). This block checks that a checksum calculated based on the
  188798. ** actual contents of FTS index is identical.
  188799. **
  188800. ** Two versions of the same checksum are calculated. The first (stack
  188801. ** variable cksum2) based on entries extracted from the full-text index
  188802. ** while doing a linear scan of each individual index in turn.
  188803. **
  188804. ** As each term visited by the linear scans, a separate query for the
  188805. ** same term is performed. cksum3 is calculated based on the entries
  188806. ** extracted by these queries.
  188807. */
  188808. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  188809. fts5MultiIterEof(p, pIter)==0;
  188810. fts5MultiIterNext(p, pIter, 0, 0)
  188811. ){
  188812. int n; /* Size of term in bytes */
  188813. i64 iPos = 0; /* Position read from poslist */
  188814. int iOff = 0; /* Offset within poslist */
  188815. i64 iRowid = fts5MultiIterRowid(pIter);
  188816. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  188817. /* If this is a new term, query for it. Update cksum3 with the results. */
  188818. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  188819. if( eDetail==FTS5_DETAIL_NONE ){
  188820. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  188821. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  188822. }
  188823. }else{
  188824. poslist.n = 0;
  188825. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  188826. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  188827. int iCol = FTS5_POS2COLUMN(iPos);
  188828. int iTokOff = FTS5_POS2OFFSET(iPos);
  188829. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  188830. }
  188831. }
  188832. }
  188833. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  188834. fts5MultiIterFree(pIter);
  188835. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  188836. fts5StructureRelease(pStruct);
  188837. #ifdef SQLITE_DEBUG
  188838. fts5BufferFree(&term);
  188839. #endif
  188840. fts5BufferFree(&poslist);
  188841. return fts5IndexReturn(p);
  188842. }
  188843. /*************************************************************************
  188844. **************************************************************************
  188845. ** Below this point is the implementation of the fts5_decode() scalar
  188846. ** function only.
  188847. */
  188848. /*
  188849. ** Decode a segment-data rowid from the %_data table. This function is
  188850. ** the opposite of macro FTS5_SEGMENT_ROWID().
  188851. */
  188852. static void fts5DecodeRowid(
  188853. i64 iRowid, /* Rowid from %_data table */
  188854. int *piSegid, /* OUT: Segment id */
  188855. int *pbDlidx, /* OUT: Dlidx flag */
  188856. int *piHeight, /* OUT: Height */
  188857. int *piPgno /* OUT: Page number */
  188858. ){
  188859. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  188860. iRowid >>= FTS5_DATA_PAGE_B;
  188861. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  188862. iRowid >>= FTS5_DATA_HEIGHT_B;
  188863. *pbDlidx = (int)(iRowid & 0x0001);
  188864. iRowid >>= FTS5_DATA_DLI_B;
  188865. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  188866. }
  188867. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  188868. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  188869. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  188870. if( iSegid==0 ){
  188871. if( iKey==FTS5_AVERAGES_ROWID ){
  188872. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  188873. }else{
  188874. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  188875. }
  188876. }
  188877. else{
  188878. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  188879. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  188880. );
  188881. }
  188882. }
  188883. static void fts5DebugStructure(
  188884. int *pRc, /* IN/OUT: error code */
  188885. Fts5Buffer *pBuf,
  188886. Fts5Structure *p
  188887. ){
  188888. int iLvl, iSeg; /* Iterate through levels, segments */
  188889. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  188890. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  188891. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  188892. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  188893. );
  188894. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  188895. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  188896. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  188897. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  188898. );
  188899. }
  188900. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  188901. }
  188902. }
  188903. /*
  188904. ** This is part of the fts5_decode() debugging aid.
  188905. **
  188906. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  188907. ** function appends a human-readable representation of the same object
  188908. ** to the buffer passed as the second argument.
  188909. */
  188910. static void fts5DecodeStructure(
  188911. int *pRc, /* IN/OUT: error code */
  188912. Fts5Buffer *pBuf,
  188913. const u8 *pBlob, int nBlob
  188914. ){
  188915. int rc; /* Return code */
  188916. Fts5Structure *p = 0; /* Decoded structure object */
  188917. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  188918. if( rc!=SQLITE_OK ){
  188919. *pRc = rc;
  188920. return;
  188921. }
  188922. fts5DebugStructure(pRc, pBuf, p);
  188923. fts5StructureRelease(p);
  188924. }
  188925. /*
  188926. ** This is part of the fts5_decode() debugging aid.
  188927. **
  188928. ** Arguments pBlob/nBlob contain an "averages" record. This function
  188929. ** appends a human-readable representation of record to the buffer passed
  188930. ** as the second argument.
  188931. */
  188932. static void fts5DecodeAverages(
  188933. int *pRc, /* IN/OUT: error code */
  188934. Fts5Buffer *pBuf,
  188935. const u8 *pBlob, int nBlob
  188936. ){
  188937. int i = 0;
  188938. const char *zSpace = "";
  188939. while( i<nBlob ){
  188940. u64 iVal;
  188941. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  188942. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  188943. zSpace = " ";
  188944. }
  188945. }
  188946. /*
  188947. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  188948. ** each varint and append its string representation to buffer pBuf. Return
  188949. ** after either the input buffer is exhausted or a 0 value is read.
  188950. **
  188951. ** The return value is the number of bytes read from the input buffer.
  188952. */
  188953. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  188954. int iOff = 0;
  188955. while( iOff<n ){
  188956. int iVal;
  188957. iOff += fts5GetVarint32(&a[iOff], iVal);
  188958. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  188959. }
  188960. return iOff;
  188961. }
  188962. /*
  188963. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  188964. ** may or may not finish within the buffer. This function appends a text
  188965. ** representation of the part of the doclist that is present to buffer
  188966. ** pBuf.
  188967. **
  188968. ** The return value is the number of bytes read from the input buffer.
  188969. */
  188970. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  188971. i64 iDocid = 0;
  188972. int iOff = 0;
  188973. if( n>0 ){
  188974. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  188975. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  188976. }
  188977. while( iOff<n ){
  188978. int nPos;
  188979. int bDel;
  188980. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  188981. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  188982. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  188983. if( iOff<n ){
  188984. i64 iDelta;
  188985. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  188986. iDocid += iDelta;
  188987. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  188988. }
  188989. }
  188990. return iOff;
  188991. }
  188992. /*
  188993. ** This function is part of the fts5_decode() debugging function. It is
  188994. ** only ever used with detail=none tables.
  188995. **
  188996. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  188997. ** tables. This function appends a human-readable version of that list to
  188998. ** buffer pBuf.
  188999. **
  189000. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  189001. ** no-op. If an OOM or other error occurs within this function, *pRc is
  189002. ** set to an SQLite error code before returning. The final state of buffer
  189003. ** pBuf is undefined in this case.
  189004. */
  189005. static void fts5DecodeRowidList(
  189006. int *pRc, /* IN/OUT: Error code */
  189007. Fts5Buffer *pBuf, /* Buffer to append text to */
  189008. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  189009. ){
  189010. int i = 0;
  189011. i64 iRowid = 0;
  189012. while( i<nData ){
  189013. const char *zApp = "";
  189014. u64 iVal;
  189015. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  189016. iRowid += iVal;
  189017. if( i<nData && pData[i]==0x00 ){
  189018. i++;
  189019. if( i<nData && pData[i]==0x00 ){
  189020. i++;
  189021. zApp = "+";
  189022. }else{
  189023. zApp = "*";
  189024. }
  189025. }
  189026. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  189027. }
  189028. }
  189029. /*
  189030. ** The implementation of user-defined scalar function fts5_decode().
  189031. */
  189032. static void fts5DecodeFunction(
  189033. sqlite3_context *pCtx, /* Function call context */
  189034. int nArg, /* Number of args (always 2) */
  189035. sqlite3_value **apVal /* Function arguments */
  189036. ){
  189037. i64 iRowid; /* Rowid for record being decoded */
  189038. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  189039. const u8 *aBlob; int n; /* Record to decode */
  189040. u8 *a = 0;
  189041. Fts5Buffer s; /* Build up text to return here */
  189042. int rc = SQLITE_OK; /* Return code */
  189043. int nSpace = 0;
  189044. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  189045. assert( nArg==2 );
  189046. UNUSED_PARAM(nArg);
  189047. memset(&s, 0, sizeof(Fts5Buffer));
  189048. iRowid = sqlite3_value_int64(apVal[0]);
  189049. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  189050. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  189051. ** buffer overreads even if the record is corrupt. */
  189052. n = sqlite3_value_bytes(apVal[1]);
  189053. aBlob = sqlite3_value_blob(apVal[1]);
  189054. nSpace = n + FTS5_DATA_ZERO_PADDING;
  189055. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  189056. if( a==0 ) goto decode_out;
  189057. memcpy(a, aBlob, n);
  189058. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  189059. fts5DebugRowid(&rc, &s, iRowid);
  189060. if( bDlidx ){
  189061. Fts5Data dlidx;
  189062. Fts5DlidxLvl lvl;
  189063. dlidx.p = a;
  189064. dlidx.nn = n;
  189065. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  189066. lvl.pData = &dlidx;
  189067. lvl.iLeafPgno = iPgno;
  189068. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  189069. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  189070. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  189071. );
  189072. }
  189073. }else if( iSegid==0 ){
  189074. if( iRowid==FTS5_AVERAGES_ROWID ){
  189075. fts5DecodeAverages(&rc, &s, a, n);
  189076. }else{
  189077. fts5DecodeStructure(&rc, &s, a, n);
  189078. }
  189079. }else if( eDetailNone ){
  189080. Fts5Buffer term; /* Current term read from page */
  189081. int szLeaf;
  189082. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  189083. int iTermOff;
  189084. int nKeep = 0;
  189085. int iOff;
  189086. memset(&term, 0, sizeof(Fts5Buffer));
  189087. /* Decode any entries that occur before the first term. */
  189088. if( szLeaf<n ){
  189089. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  189090. }else{
  189091. iTermOff = szLeaf;
  189092. }
  189093. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  189094. iOff = iTermOff;
  189095. while( iOff<szLeaf ){
  189096. int nAppend;
  189097. /* Read the term data for the next term*/
  189098. iOff += fts5GetVarint32(&a[iOff], nAppend);
  189099. term.n = nKeep;
  189100. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  189101. sqlite3Fts5BufferAppendPrintf(
  189102. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  189103. );
  189104. iOff += nAppend;
  189105. /* Figure out where the doclist for this term ends */
  189106. if( iPgidxOff<n ){
  189107. int nIncr;
  189108. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  189109. iTermOff += nIncr;
  189110. }else{
  189111. iTermOff = szLeaf;
  189112. }
  189113. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  189114. iOff = iTermOff;
  189115. if( iOff<szLeaf ){
  189116. iOff += fts5GetVarint32(&a[iOff], nKeep);
  189117. }
  189118. }
  189119. fts5BufferFree(&term);
  189120. }else{
  189121. Fts5Buffer term; /* Current term read from page */
  189122. int szLeaf; /* Offset of pgidx in a[] */
  189123. int iPgidxOff;
  189124. int iPgidxPrev = 0; /* Previous value read from pgidx */
  189125. int iTermOff = 0;
  189126. int iRowidOff = 0;
  189127. int iOff;
  189128. int nDoclist;
  189129. memset(&term, 0, sizeof(Fts5Buffer));
  189130. if( n<4 ){
  189131. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  189132. goto decode_out;
  189133. }else{
  189134. iRowidOff = fts5GetU16(&a[0]);
  189135. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  189136. if( iPgidxOff<n ){
  189137. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  189138. }
  189139. }
  189140. /* Decode the position list tail at the start of the page */
  189141. if( iRowidOff!=0 ){
  189142. iOff = iRowidOff;
  189143. }else if( iTermOff!=0 ){
  189144. iOff = iTermOff;
  189145. }else{
  189146. iOff = szLeaf;
  189147. }
  189148. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  189149. /* Decode any more doclist data that appears on the page before the
  189150. ** first term. */
  189151. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  189152. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  189153. while( iPgidxOff<n ){
  189154. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  189155. int nByte; /* Bytes of data */
  189156. int iEnd;
  189157. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  189158. iPgidxPrev += nByte;
  189159. iOff = iPgidxPrev;
  189160. if( iPgidxOff<n ){
  189161. fts5GetVarint32(&a[iPgidxOff], nByte);
  189162. iEnd = iPgidxPrev + nByte;
  189163. }else{
  189164. iEnd = szLeaf;
  189165. }
  189166. if( bFirst==0 ){
  189167. iOff += fts5GetVarint32(&a[iOff], nByte);
  189168. term.n = nByte;
  189169. }
  189170. iOff += fts5GetVarint32(&a[iOff], nByte);
  189171. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  189172. iOff += nByte;
  189173. sqlite3Fts5BufferAppendPrintf(
  189174. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  189175. );
  189176. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  189177. }
  189178. fts5BufferFree(&term);
  189179. }
  189180. decode_out:
  189181. sqlite3_free(a);
  189182. if( rc==SQLITE_OK ){
  189183. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  189184. }else{
  189185. sqlite3_result_error_code(pCtx, rc);
  189186. }
  189187. fts5BufferFree(&s);
  189188. }
  189189. /*
  189190. ** The implementation of user-defined scalar function fts5_rowid().
  189191. */
  189192. static void fts5RowidFunction(
  189193. sqlite3_context *pCtx, /* Function call context */
  189194. int nArg, /* Number of args (always 2) */
  189195. sqlite3_value **apVal /* Function arguments */
  189196. ){
  189197. const char *zArg;
  189198. if( nArg==0 ){
  189199. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  189200. }else{
  189201. zArg = (const char*)sqlite3_value_text(apVal[0]);
  189202. if( 0==sqlite3_stricmp(zArg, "segment") ){
  189203. i64 iRowid;
  189204. int segid, pgno;
  189205. if( nArg!=3 ){
  189206. sqlite3_result_error(pCtx,
  189207. "should be: fts5_rowid('segment', segid, pgno))", -1
  189208. );
  189209. }else{
  189210. segid = sqlite3_value_int(apVal[1]);
  189211. pgno = sqlite3_value_int(apVal[2]);
  189212. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  189213. sqlite3_result_int64(pCtx, iRowid);
  189214. }
  189215. }else{
  189216. sqlite3_result_error(pCtx,
  189217. "first arg to fts5_rowid() must be 'segment'" , -1
  189218. );
  189219. }
  189220. }
  189221. }
  189222. /*
  189223. ** This is called as part of registering the FTS5 module with database
  189224. ** connection db. It registers several user-defined scalar functions useful
  189225. ** with FTS5.
  189226. **
  189227. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  189228. ** SQLite error code is returned instead.
  189229. */
  189230. static int sqlite3Fts5IndexInit(sqlite3 *db){
  189231. int rc = sqlite3_create_function(
  189232. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  189233. );
  189234. if( rc==SQLITE_OK ){
  189235. rc = sqlite3_create_function(
  189236. db, "fts5_decode_none", 2,
  189237. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  189238. );
  189239. }
  189240. if( rc==SQLITE_OK ){
  189241. rc = sqlite3_create_function(
  189242. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  189243. );
  189244. }
  189245. return rc;
  189246. }
  189247. static int sqlite3Fts5IndexReset(Fts5Index *p){
  189248. assert( p->pStruct==0 || p->iStructVersion!=0 );
  189249. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  189250. fts5StructureInvalidate(p);
  189251. }
  189252. return fts5IndexReturn(p);
  189253. }
  189254. /*
  189255. ** 2014 Jun 09
  189256. **
  189257. ** The author disclaims copyright to this source code. In place of
  189258. ** a legal notice, here is a blessing:
  189259. **
  189260. ** May you do good and not evil.
  189261. ** May you find forgiveness for yourself and forgive others.
  189262. ** May you share freely, never taking more than you give.
  189263. **
  189264. ******************************************************************************
  189265. **
  189266. ** This is an SQLite module implementing full-text search.
  189267. */
  189268. /* #include "fts5Int.h" */
  189269. /*
  189270. ** This variable is set to false when running tests for which the on disk
  189271. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  189272. ** assert() conditions in the fts5 code are activated - conditions that are
  189273. ** only true if it is guaranteed that the fts5 database is not corrupt.
  189274. */
  189275. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  189276. typedef struct Fts5Auxdata Fts5Auxdata;
  189277. typedef struct Fts5Auxiliary Fts5Auxiliary;
  189278. typedef struct Fts5Cursor Fts5Cursor;
  189279. typedef struct Fts5Sorter Fts5Sorter;
  189280. typedef struct Fts5Table Fts5Table;
  189281. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  189282. /*
  189283. ** NOTES ON TRANSACTIONS:
  189284. **
  189285. ** SQLite invokes the following virtual table methods as transactions are
  189286. ** opened and closed by the user:
  189287. **
  189288. ** xBegin(): Start of a new transaction.
  189289. ** xSync(): Initial part of two-phase commit.
  189290. ** xCommit(): Final part of two-phase commit.
  189291. ** xRollback(): Rollback the transaction.
  189292. **
  189293. ** Anything that is required as part of a commit that may fail is performed
  189294. ** in the xSync() callback. Current versions of SQLite ignore any errors
  189295. ** returned by xCommit().
  189296. **
  189297. ** And as sub-transactions are opened/closed:
  189298. **
  189299. ** xSavepoint(int S): Open savepoint S.
  189300. ** xRelease(int S): Commit and close savepoint S.
  189301. ** xRollbackTo(int S): Rollback to start of savepoint S.
  189302. **
  189303. ** During a write-transaction the fts5_index.c module may cache some data
  189304. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  189305. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  189306. ** is called.
  189307. **
  189308. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  189309. ** structure is used to record the current transaction state. This information
  189310. ** is not required, but it is used in the assert() statements executed by
  189311. ** function fts5CheckTransactionState() (see below).
  189312. */
  189313. struct Fts5TransactionState {
  189314. int eState; /* 0==closed, 1==open, 2==synced */
  189315. int iSavepoint; /* Number of open savepoints (0 -> none) */
  189316. };
  189317. /*
  189318. ** A single object of this type is allocated when the FTS5 module is
  189319. ** registered with a database handle. It is used to store pointers to
  189320. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  189321. */
  189322. struct Fts5Global {
  189323. fts5_api api; /* User visible part of object (see fts5.h) */
  189324. sqlite3 *db; /* Associated database connection */
  189325. i64 iNextId; /* Used to allocate unique cursor ids */
  189326. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  189327. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  189328. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  189329. Fts5Cursor *pCsr; /* First in list of all open cursors */
  189330. };
  189331. /*
  189332. ** Each auxiliary function registered with the FTS5 module is represented
  189333. ** by an object of the following type. All such objects are stored as part
  189334. ** of the Fts5Global.pAux list.
  189335. */
  189336. struct Fts5Auxiliary {
  189337. Fts5Global *pGlobal; /* Global context for this function */
  189338. char *zFunc; /* Function name (nul-terminated) */
  189339. void *pUserData; /* User-data pointer */
  189340. fts5_extension_function xFunc; /* Callback function */
  189341. void (*xDestroy)(void*); /* Destructor function */
  189342. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  189343. };
  189344. /*
  189345. ** Each tokenizer module registered with the FTS5 module is represented
  189346. ** by an object of the following type. All such objects are stored as part
  189347. ** of the Fts5Global.pTok list.
  189348. */
  189349. struct Fts5TokenizerModule {
  189350. char *zName; /* Name of tokenizer */
  189351. void *pUserData; /* User pointer passed to xCreate() */
  189352. fts5_tokenizer x; /* Tokenizer functions */
  189353. void (*xDestroy)(void*); /* Destructor function */
  189354. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  189355. };
  189356. /*
  189357. ** Virtual-table object.
  189358. */
  189359. struct Fts5Table {
  189360. sqlite3_vtab base; /* Base class used by SQLite core */
  189361. Fts5Config *pConfig; /* Virtual table configuration */
  189362. Fts5Index *pIndex; /* Full-text index */
  189363. Fts5Storage *pStorage; /* Document store */
  189364. Fts5Global *pGlobal; /* Global (connection wide) data */
  189365. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  189366. #ifdef SQLITE_DEBUG
  189367. struct Fts5TransactionState ts;
  189368. #endif
  189369. };
  189370. struct Fts5MatchPhrase {
  189371. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  189372. int nTerm; /* Size of phrase in terms */
  189373. };
  189374. /*
  189375. ** pStmt:
  189376. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  189377. **
  189378. ** aIdx[]:
  189379. ** There is one entry in the aIdx[] array for each phrase in the query,
  189380. ** the value of which is the offset within aPoslist[] following the last
  189381. ** byte of the position list for the corresponding phrase.
  189382. */
  189383. struct Fts5Sorter {
  189384. sqlite3_stmt *pStmt;
  189385. i64 iRowid; /* Current rowid */
  189386. const u8 *aPoslist; /* Position lists for current row */
  189387. int nIdx; /* Number of entries in aIdx[] */
  189388. int aIdx[1]; /* Offsets into aPoslist for current row */
  189389. };
  189390. /*
  189391. ** Virtual-table cursor object.
  189392. **
  189393. ** iSpecial:
  189394. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  189395. ** then this variable contains the result of the query.
  189396. **
  189397. ** iFirstRowid, iLastRowid:
  189398. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  189399. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  189400. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  189401. ** WHERE clause in the user's query might have been:
  189402. **
  189403. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  189404. **
  189405. ** If the cursor iterates in descending order of rowid, iFirstRowid
  189406. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  189407. ** the lower.
  189408. */
  189409. struct Fts5Cursor {
  189410. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  189411. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  189412. int *aColumnSize; /* Values for xColumnSize() */
  189413. i64 iCsrId; /* Cursor id */
  189414. /* Zero from this point onwards on cursor reset */
  189415. int ePlan; /* FTS5_PLAN_XXX value */
  189416. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  189417. i64 iFirstRowid; /* Return no rowids earlier than this */
  189418. i64 iLastRowid; /* Return no rowids later than this */
  189419. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  189420. Fts5Expr *pExpr; /* Expression for MATCH queries */
  189421. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  189422. int csrflags; /* Mask of cursor flags (see below) */
  189423. i64 iSpecial; /* Result of special query */
  189424. /* "rank" function. Populated on demand from vtab.xColumn(). */
  189425. char *zRank; /* Custom rank function */
  189426. char *zRankArgs; /* Custom rank function args */
  189427. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  189428. int nRankArg; /* Number of trailing arguments for rank() */
  189429. sqlite3_value **apRankArg; /* Array of trailing arguments */
  189430. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  189431. /* Auxiliary data storage */
  189432. Fts5Auxiliary *pAux; /* Currently executing extension function */
  189433. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  189434. /* Cache used by auxiliary functions xInst() and xInstCount() */
  189435. Fts5PoslistReader *aInstIter; /* One for each phrase */
  189436. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  189437. int nInstCount; /* Number of phrase instances */
  189438. int *aInst; /* 3 integers per phrase instance */
  189439. };
  189440. /*
  189441. ** Bits that make up the "idxNum" parameter passed indirectly by
  189442. ** xBestIndex() to xFilter().
  189443. */
  189444. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  189445. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  189446. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  189447. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  189448. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  189449. #define FTS5_BI_ORDER_RANK 0x0020
  189450. #define FTS5_BI_ORDER_ROWID 0x0040
  189451. #define FTS5_BI_ORDER_DESC 0x0080
  189452. /*
  189453. ** Values for Fts5Cursor.csrflags
  189454. */
  189455. #define FTS5CSR_EOF 0x01
  189456. #define FTS5CSR_REQUIRE_CONTENT 0x02
  189457. #define FTS5CSR_REQUIRE_DOCSIZE 0x04
  189458. #define FTS5CSR_REQUIRE_INST 0x08
  189459. #define FTS5CSR_FREE_ZRANK 0x10
  189460. #define FTS5CSR_REQUIRE_RESEEK 0x20
  189461. #define FTS5CSR_REQUIRE_POSLIST 0x40
  189462. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  189463. #define BitFlagTest(x,y) (((x) & (y))!=0)
  189464. /*
  189465. ** Macros to Set(), Clear() and Test() cursor flags.
  189466. */
  189467. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  189468. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  189469. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  189470. struct Fts5Auxdata {
  189471. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  189472. void *pPtr; /* Pointer value */
  189473. void(*xDelete)(void*); /* Destructor */
  189474. Fts5Auxdata *pNext; /* Next object in linked list */
  189475. };
  189476. #ifdef SQLITE_DEBUG
  189477. #define FTS5_BEGIN 1
  189478. #define FTS5_SYNC 2
  189479. #define FTS5_COMMIT 3
  189480. #define FTS5_ROLLBACK 4
  189481. #define FTS5_SAVEPOINT 5
  189482. #define FTS5_RELEASE 6
  189483. #define FTS5_ROLLBACKTO 7
  189484. static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
  189485. switch( op ){
  189486. case FTS5_BEGIN:
  189487. assert( p->ts.eState==0 );
  189488. p->ts.eState = 1;
  189489. p->ts.iSavepoint = -1;
  189490. break;
  189491. case FTS5_SYNC:
  189492. assert( p->ts.eState==1 );
  189493. p->ts.eState = 2;
  189494. break;
  189495. case FTS5_COMMIT:
  189496. assert( p->ts.eState==2 );
  189497. p->ts.eState = 0;
  189498. break;
  189499. case FTS5_ROLLBACK:
  189500. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  189501. p->ts.eState = 0;
  189502. break;
  189503. case FTS5_SAVEPOINT:
  189504. assert( p->ts.eState==1 );
  189505. assert( iSavepoint>=0 );
  189506. assert( iSavepoint>p->ts.iSavepoint );
  189507. p->ts.iSavepoint = iSavepoint;
  189508. break;
  189509. case FTS5_RELEASE:
  189510. assert( p->ts.eState==1 );
  189511. assert( iSavepoint>=0 );
  189512. assert( iSavepoint<=p->ts.iSavepoint );
  189513. p->ts.iSavepoint = iSavepoint-1;
  189514. break;
  189515. case FTS5_ROLLBACKTO:
  189516. assert( p->ts.eState==1 );
  189517. assert( iSavepoint>=0 );
  189518. assert( iSavepoint<=p->ts.iSavepoint );
  189519. p->ts.iSavepoint = iSavepoint;
  189520. break;
  189521. }
  189522. }
  189523. #else
  189524. # define fts5CheckTransactionState(x,y,z)
  189525. #endif
  189526. /*
  189527. ** Return true if pTab is a contentless table.
  189528. */
  189529. static int fts5IsContentless(Fts5Table *pTab){
  189530. return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
  189531. }
  189532. /*
  189533. ** Delete a virtual table handle allocated by fts5InitVtab().
  189534. */
  189535. static void fts5FreeVtab(Fts5Table *pTab){
  189536. if( pTab ){
  189537. sqlite3Fts5IndexClose(pTab->pIndex);
  189538. sqlite3Fts5StorageClose(pTab->pStorage);
  189539. sqlite3Fts5ConfigFree(pTab->pConfig);
  189540. sqlite3_free(pTab);
  189541. }
  189542. }
  189543. /*
  189544. ** The xDisconnect() virtual table method.
  189545. */
  189546. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  189547. fts5FreeVtab((Fts5Table*)pVtab);
  189548. return SQLITE_OK;
  189549. }
  189550. /*
  189551. ** The xDestroy() virtual table method.
  189552. */
  189553. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  189554. Fts5Table *pTab = (Fts5Table*)pVtab;
  189555. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  189556. if( rc==SQLITE_OK ){
  189557. fts5FreeVtab((Fts5Table*)pVtab);
  189558. }
  189559. return rc;
  189560. }
  189561. /*
  189562. ** This function is the implementation of both the xConnect and xCreate
  189563. ** methods of the FTS3 virtual table.
  189564. **
  189565. ** The argv[] array contains the following:
  189566. **
  189567. ** argv[0] -> module name ("fts5")
  189568. ** argv[1] -> database name
  189569. ** argv[2] -> table name
  189570. ** argv[...] -> "column name" and other module argument fields.
  189571. */
  189572. static int fts5InitVtab(
  189573. int bCreate, /* True for xCreate, false for xConnect */
  189574. sqlite3 *db, /* The SQLite database connection */
  189575. void *pAux, /* Hash table containing tokenizers */
  189576. int argc, /* Number of elements in argv array */
  189577. const char * const *argv, /* xCreate/xConnect argument array */
  189578. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  189579. char **pzErr /* Write any error message here */
  189580. ){
  189581. Fts5Global *pGlobal = (Fts5Global*)pAux;
  189582. const char **azConfig = (const char**)argv;
  189583. int rc = SQLITE_OK; /* Return code */
  189584. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  189585. Fts5Table *pTab = 0; /* New virtual table object */
  189586. /* Allocate the new vtab object and parse the configuration */
  189587. pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
  189588. if( rc==SQLITE_OK ){
  189589. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  189590. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  189591. }
  189592. if( rc==SQLITE_OK ){
  189593. pTab->pConfig = pConfig;
  189594. pTab->pGlobal = pGlobal;
  189595. }
  189596. /* Open the index sub-system */
  189597. if( rc==SQLITE_OK ){
  189598. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
  189599. }
  189600. /* Open the storage sub-system */
  189601. if( rc==SQLITE_OK ){
  189602. rc = sqlite3Fts5StorageOpen(
  189603. pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
  189604. );
  189605. }
  189606. /* Call sqlite3_declare_vtab() */
  189607. if( rc==SQLITE_OK ){
  189608. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  189609. }
  189610. /* Load the initial configuration */
  189611. if( rc==SQLITE_OK ){
  189612. assert( pConfig->pzErrmsg==0 );
  189613. pConfig->pzErrmsg = pzErr;
  189614. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  189615. sqlite3Fts5IndexRollback(pTab->pIndex);
  189616. pConfig->pzErrmsg = 0;
  189617. }
  189618. if( rc!=SQLITE_OK ){
  189619. fts5FreeVtab(pTab);
  189620. pTab = 0;
  189621. }else if( bCreate ){
  189622. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  189623. }
  189624. *ppVTab = (sqlite3_vtab*)pTab;
  189625. return rc;
  189626. }
  189627. /*
  189628. ** The xConnect() and xCreate() methods for the virtual table. All the
  189629. ** work is done in function fts5InitVtab().
  189630. */
  189631. static int fts5ConnectMethod(
  189632. sqlite3 *db, /* Database connection */
  189633. void *pAux, /* Pointer to tokenizer hash table */
  189634. int argc, /* Number of elements in argv array */
  189635. const char * const *argv, /* xCreate/xConnect argument array */
  189636. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  189637. char **pzErr /* OUT: sqlite3_malloc'd error message */
  189638. ){
  189639. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  189640. }
  189641. static int fts5CreateMethod(
  189642. sqlite3 *db, /* Database connection */
  189643. void *pAux, /* Pointer to tokenizer hash table */
  189644. int argc, /* Number of elements in argv array */
  189645. const char * const *argv, /* xCreate/xConnect argument array */
  189646. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  189647. char **pzErr /* OUT: sqlite3_malloc'd error message */
  189648. ){
  189649. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  189650. }
  189651. /*
  189652. ** The different query plans.
  189653. */
  189654. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  189655. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  189656. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  189657. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  189658. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  189659. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  189660. /*
  189661. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  189662. ** extension is currently being used by a version of SQLite too old to
  189663. ** support index-info flags. In that case this function is a no-op.
  189664. */
  189665. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  189666. #if SQLITE_VERSION_NUMBER>=3008012
  189667. #ifndef SQLITE_CORE
  189668. if( sqlite3_libversion_number()>=3008012 )
  189669. #endif
  189670. {
  189671. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  189672. }
  189673. #endif
  189674. }
  189675. /*
  189676. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  189677. ** WHERE constraint, it searches for the following:
  189678. **
  189679. ** 1. A MATCH constraint against the special column.
  189680. ** 2. A MATCH constraint against the "rank" column.
  189681. ** 3. An == constraint against the rowid column.
  189682. ** 4. A < or <= constraint against the rowid column.
  189683. ** 5. A > or >= constraint against the rowid column.
  189684. **
  189685. ** Within the ORDER BY, either:
  189686. **
  189687. ** 5. ORDER BY rank [ASC|DESC]
  189688. ** 6. ORDER BY rowid [ASC|DESC]
  189689. **
  189690. ** Costs are assigned as follows:
  189691. **
  189692. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  189693. ** cost is unconditionally set to 1e50 (a really big number).
  189694. **
  189695. ** a) If a MATCH operator is present, the cost depends on the other
  189696. ** constraints also present. As follows:
  189697. **
  189698. ** * No other constraints: cost=1000.0
  189699. ** * One rowid range constraint: cost=750.0
  189700. ** * Both rowid range constraints: cost=500.0
  189701. ** * An == rowid constraint: cost=100.0
  189702. **
  189703. ** b) Otherwise, if there is no MATCH:
  189704. **
  189705. ** * No other constraints: cost=1000000.0
  189706. ** * One rowid range constraint: cost=750000.0
  189707. ** * Both rowid range constraints: cost=250000.0
  189708. ** * An == rowid constraint: cost=10.0
  189709. **
  189710. ** Costs are not modified by the ORDER BY clause.
  189711. */
  189712. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  189713. Fts5Table *pTab = (Fts5Table*)pVTab;
  189714. Fts5Config *pConfig = pTab->pConfig;
  189715. const int nCol = pConfig->nCol;
  189716. int idxFlags = 0; /* Parameter passed through to xFilter() */
  189717. int bHasMatch;
  189718. int iNext;
  189719. int i;
  189720. struct Constraint {
  189721. int op; /* Mask against sqlite3_index_constraint.op */
  189722. int fts5op; /* FTS5 mask for idxFlags */
  189723. int iCol; /* 0==rowid, 1==tbl, 2==rank */
  189724. int omit; /* True to omit this if found */
  189725. int iConsIndex; /* Index in pInfo->aConstraint[] */
  189726. } aConstraint[] = {
  189727. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  189728. FTS5_BI_MATCH, 1, 1, -1},
  189729. {SQLITE_INDEX_CONSTRAINT_MATCH|SQLITE_INDEX_CONSTRAINT_EQ,
  189730. FTS5_BI_RANK, 2, 1, -1},
  189731. {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
  189732. {SQLITE_INDEX_CONSTRAINT_LT|SQLITE_INDEX_CONSTRAINT_LE,
  189733. FTS5_BI_ROWID_LE, 0, 0, -1},
  189734. {SQLITE_INDEX_CONSTRAINT_GT|SQLITE_INDEX_CONSTRAINT_GE,
  189735. FTS5_BI_ROWID_GE, 0, 0, -1},
  189736. };
  189737. int aColMap[3];
  189738. aColMap[0] = -1;
  189739. aColMap[1] = nCol;
  189740. aColMap[2] = nCol+1;
  189741. assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );
  189742. assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );
  189743. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  189744. assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );
  189745. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  189746. /* Set idxFlags flags for all WHERE clause terms that will be used. */
  189747. for(i=0; i<pInfo->nConstraint; i++){
  189748. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  189749. int iCol = p->iColumn;
  189750. if( (p->op==SQLITE_INDEX_CONSTRAINT_MATCH && iCol>=0 && iCol<=nCol)
  189751. || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol==nCol)
  189752. ){
  189753. /* A MATCH operator or equivalent */
  189754. if( p->usable ){
  189755. idxFlags = (idxFlags & 0xFFFF) | FTS5_BI_MATCH | (iCol << 16);
  189756. aConstraint[0].iConsIndex = i;
  189757. }else{
  189758. /* As there exists an unusable MATCH constraint this is an
  189759. ** unusable plan. Set a prohibitively high cost. */
  189760. pInfo->estimatedCost = 1e50;
  189761. return SQLITE_OK;
  189762. }
  189763. }else if( p->op<=SQLITE_INDEX_CONSTRAINT_MATCH ){
  189764. int j;
  189765. for(j=1; j<ArraySize(aConstraint); j++){
  189766. struct Constraint *pC = &aConstraint[j];
  189767. if( iCol==aColMap[pC->iCol] && (p->op & pC->op) && p->usable ){
  189768. pC->iConsIndex = i;
  189769. idxFlags |= pC->fts5op;
  189770. }
  189771. }
  189772. }
  189773. }
  189774. /* Set idxFlags flags for the ORDER BY clause */
  189775. if( pInfo->nOrderBy==1 ){
  189776. int iSort = pInfo->aOrderBy[0].iColumn;
  189777. if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
  189778. idxFlags |= FTS5_BI_ORDER_RANK;
  189779. }else if( iSort==-1 ){
  189780. idxFlags |= FTS5_BI_ORDER_ROWID;
  189781. }
  189782. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  189783. pInfo->orderByConsumed = 1;
  189784. if( pInfo->aOrderBy[0].desc ){
  189785. idxFlags |= FTS5_BI_ORDER_DESC;
  189786. }
  189787. }
  189788. }
  189789. /* Calculate the estimated cost based on the flags set in idxFlags. */
  189790. bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
  189791. if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
  189792. pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
  189793. if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
  189794. }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  189795. pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
  189796. }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
  189797. pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
  189798. }else{
  189799. pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
  189800. }
  189801. /* Assign argvIndex values to each constraint in use. */
  189802. iNext = 1;
  189803. for(i=0; i<ArraySize(aConstraint); i++){
  189804. struct Constraint *pC = &aConstraint[i];
  189805. if( pC->iConsIndex>=0 ){
  189806. pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
  189807. pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
  189808. }
  189809. }
  189810. pInfo->idxNum = idxFlags;
  189811. return SQLITE_OK;
  189812. }
  189813. static int fts5NewTransaction(Fts5Table *pTab){
  189814. Fts5Cursor *pCsr;
  189815. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  189816. if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
  189817. }
  189818. return sqlite3Fts5StorageReset(pTab->pStorage);
  189819. }
  189820. /*
  189821. ** Implementation of xOpen method.
  189822. */
  189823. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  189824. Fts5Table *pTab = (Fts5Table*)pVTab;
  189825. Fts5Config *pConfig = pTab->pConfig;
  189826. Fts5Cursor *pCsr = 0; /* New cursor object */
  189827. int nByte; /* Bytes of space to allocate */
  189828. int rc; /* Return code */
  189829. rc = fts5NewTransaction(pTab);
  189830. if( rc==SQLITE_OK ){
  189831. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  189832. pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
  189833. if( pCsr ){
  189834. Fts5Global *pGlobal = pTab->pGlobal;
  189835. memset(pCsr, 0, nByte);
  189836. pCsr->aColumnSize = (int*)&pCsr[1];
  189837. pCsr->pNext = pGlobal->pCsr;
  189838. pGlobal->pCsr = pCsr;
  189839. pCsr->iCsrId = ++pGlobal->iNextId;
  189840. }else{
  189841. rc = SQLITE_NOMEM;
  189842. }
  189843. }
  189844. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  189845. return rc;
  189846. }
  189847. static int fts5StmtType(Fts5Cursor *pCsr){
  189848. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  189849. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  189850. }
  189851. return FTS5_STMT_LOOKUP;
  189852. }
  189853. /*
  189854. ** This function is called after the cursor passed as the only argument
  189855. ** is moved to point at a different row. It clears all cached data
  189856. ** specific to the previous row stored by the cursor object.
  189857. */
  189858. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  189859. CsrFlagSet(pCsr,
  189860. FTS5CSR_REQUIRE_CONTENT
  189861. | FTS5CSR_REQUIRE_DOCSIZE
  189862. | FTS5CSR_REQUIRE_INST
  189863. | FTS5CSR_REQUIRE_POSLIST
  189864. );
  189865. }
  189866. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  189867. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  189868. Fts5Auxdata *pData;
  189869. Fts5Auxdata *pNext;
  189870. sqlite3_free(pCsr->aInstIter);
  189871. sqlite3_free(pCsr->aInst);
  189872. if( pCsr->pStmt ){
  189873. int eStmt = fts5StmtType(pCsr);
  189874. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  189875. }
  189876. if( pCsr->pSorter ){
  189877. Fts5Sorter *pSorter = pCsr->pSorter;
  189878. sqlite3_finalize(pSorter->pStmt);
  189879. sqlite3_free(pSorter);
  189880. }
  189881. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  189882. sqlite3Fts5ExprFree(pCsr->pExpr);
  189883. }
  189884. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  189885. pNext = pData->pNext;
  189886. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  189887. sqlite3_free(pData);
  189888. }
  189889. sqlite3_finalize(pCsr->pRankArgStmt);
  189890. sqlite3_free(pCsr->apRankArg);
  189891. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  189892. sqlite3_free(pCsr->zRank);
  189893. sqlite3_free(pCsr->zRankArgs);
  189894. }
  189895. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  189896. }
  189897. /*
  189898. ** Close the cursor. For additional information see the documentation
  189899. ** on the xClose method of the virtual table interface.
  189900. */
  189901. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  189902. if( pCursor ){
  189903. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  189904. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  189905. Fts5Cursor **pp;
  189906. fts5FreeCursorComponents(pCsr);
  189907. /* Remove the cursor from the Fts5Global.pCsr list */
  189908. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  189909. *pp = pCsr->pNext;
  189910. sqlite3_free(pCsr);
  189911. }
  189912. return SQLITE_OK;
  189913. }
  189914. static int fts5SorterNext(Fts5Cursor *pCsr){
  189915. Fts5Sorter *pSorter = pCsr->pSorter;
  189916. int rc;
  189917. rc = sqlite3_step(pSorter->pStmt);
  189918. if( rc==SQLITE_DONE ){
  189919. rc = SQLITE_OK;
  189920. CsrFlagSet(pCsr, FTS5CSR_EOF);
  189921. }else if( rc==SQLITE_ROW ){
  189922. const u8 *a;
  189923. const u8 *aBlob;
  189924. int nBlob;
  189925. int i;
  189926. int iOff = 0;
  189927. rc = SQLITE_OK;
  189928. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  189929. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  189930. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  189931. /* nBlob==0 in detail=none mode. */
  189932. if( nBlob>0 ){
  189933. for(i=0; i<(pSorter->nIdx-1); i++){
  189934. int iVal;
  189935. a += fts5GetVarint32(a, iVal);
  189936. iOff += iVal;
  189937. pSorter->aIdx[i] = iOff;
  189938. }
  189939. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  189940. pSorter->aPoslist = a;
  189941. }
  189942. fts5CsrNewrow(pCsr);
  189943. }
  189944. return rc;
  189945. }
  189946. /*
  189947. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  189948. ** open on table pTab.
  189949. */
  189950. static void fts5TripCursors(Fts5Table *pTab){
  189951. Fts5Cursor *pCsr;
  189952. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  189953. if( pCsr->ePlan==FTS5_PLAN_MATCH
  189954. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  189955. ){
  189956. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  189957. }
  189958. }
  189959. }
  189960. /*
  189961. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  189962. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  189963. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  189964. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  189965. **
  189966. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  189967. ** to 1 before returning. Otherwise, leave it unchanged.
  189968. **
  189969. ** Return SQLITE_OK if successful or if no reseek was required, or an
  189970. ** error code if an error occurred.
  189971. */
  189972. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  189973. int rc = SQLITE_OK;
  189974. assert( *pbSkip==0 );
  189975. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  189976. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  189977. int bDesc = pCsr->bDesc;
  189978. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  189979. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
  189980. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  189981. *pbSkip = 1;
  189982. }
  189983. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  189984. fts5CsrNewrow(pCsr);
  189985. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  189986. CsrFlagSet(pCsr, FTS5CSR_EOF);
  189987. *pbSkip = 1;
  189988. }
  189989. }
  189990. return rc;
  189991. }
  189992. /*
  189993. ** Advance the cursor to the next row in the table that matches the
  189994. ** search criteria.
  189995. **
  189996. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  189997. ** even if we reach end-of-file. The fts5EofMethod() will be called
  189998. ** subsequently to determine whether or not an EOF was hit.
  189999. */
  190000. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  190001. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  190002. int rc;
  190003. assert( (pCsr->ePlan<3)==
  190004. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  190005. );
  190006. assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
  190007. if( pCsr->ePlan<3 ){
  190008. int bSkip = 0;
  190009. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  190010. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  190011. CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
  190012. fts5CsrNewrow(pCsr);
  190013. }else{
  190014. switch( pCsr->ePlan ){
  190015. case FTS5_PLAN_SPECIAL: {
  190016. CsrFlagSet(pCsr, FTS5CSR_EOF);
  190017. rc = SQLITE_OK;
  190018. break;
  190019. }
  190020. case FTS5_PLAN_SORTED_MATCH: {
  190021. rc = fts5SorterNext(pCsr);
  190022. break;
  190023. }
  190024. default:
  190025. rc = sqlite3_step(pCsr->pStmt);
  190026. if( rc!=SQLITE_ROW ){
  190027. CsrFlagSet(pCsr, FTS5CSR_EOF);
  190028. rc = sqlite3_reset(pCsr->pStmt);
  190029. }else{
  190030. rc = SQLITE_OK;
  190031. }
  190032. break;
  190033. }
  190034. }
  190035. return rc;
  190036. }
  190037. static int fts5PrepareStatement(
  190038. sqlite3_stmt **ppStmt,
  190039. Fts5Config *pConfig,
  190040. const char *zFmt,
  190041. ...
  190042. ){
  190043. sqlite3_stmt *pRet = 0;
  190044. int rc;
  190045. char *zSql;
  190046. va_list ap;
  190047. va_start(ap, zFmt);
  190048. zSql = sqlite3_vmprintf(zFmt, ap);
  190049. if( zSql==0 ){
  190050. rc = SQLITE_NOMEM;
  190051. }else{
  190052. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  190053. SQLITE_PREPARE_PERSISTENT, &pRet, 0);
  190054. if( rc!=SQLITE_OK ){
  190055. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  190056. }
  190057. sqlite3_free(zSql);
  190058. }
  190059. va_end(ap);
  190060. *ppStmt = pRet;
  190061. return rc;
  190062. }
  190063. static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  190064. Fts5Config *pConfig = pTab->pConfig;
  190065. Fts5Sorter *pSorter;
  190066. int nPhrase;
  190067. int nByte;
  190068. int rc;
  190069. const char *zRank = pCsr->zRank;
  190070. const char *zRankArgs = pCsr->zRankArgs;
  190071. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  190072. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  190073. pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
  190074. if( pSorter==0 ) return SQLITE_NOMEM;
  190075. memset(pSorter, 0, nByte);
  190076. pSorter->nIdx = nPhrase;
  190077. /* TODO: It would be better to have some system for reusing statement
  190078. ** handles here, rather than preparing a new one for each query. But that
  190079. ** is not possible as SQLite reference counts the virtual table objects.
  190080. ** And since the statement required here reads from this very virtual
  190081. ** table, saving it creates a circular reference.
  190082. **
  190083. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  190084. rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
  190085. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
  190086. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  190087. (zRankArgs ? ", " : ""),
  190088. (zRankArgs ? zRankArgs : ""),
  190089. bDesc ? "DESC" : "ASC"
  190090. );
  190091. pCsr->pSorter = pSorter;
  190092. if( rc==SQLITE_OK ){
  190093. assert( pTab->pSortCsr==0 );
  190094. pTab->pSortCsr = pCsr;
  190095. rc = fts5SorterNext(pCsr);
  190096. pTab->pSortCsr = 0;
  190097. }
  190098. if( rc!=SQLITE_OK ){
  190099. sqlite3_finalize(pSorter->pStmt);
  190100. sqlite3_free(pSorter);
  190101. pCsr->pSorter = 0;
  190102. }
  190103. return rc;
  190104. }
  190105. static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
  190106. int rc;
  190107. Fts5Expr *pExpr = pCsr->pExpr;
  190108. rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
  190109. if( sqlite3Fts5ExprEof(pExpr) ){
  190110. CsrFlagSet(pCsr, FTS5CSR_EOF);
  190111. }
  190112. fts5CsrNewrow(pCsr);
  190113. return rc;
  190114. }
  190115. /*
  190116. ** Process a "special" query. A special query is identified as one with a
  190117. ** MATCH expression that begins with a '*' character. The remainder of
  190118. ** the text passed to the MATCH operator are used as the special query
  190119. ** parameters.
  190120. */
  190121. static int fts5SpecialMatch(
  190122. Fts5Table *pTab,
  190123. Fts5Cursor *pCsr,
  190124. const char *zQuery
  190125. ){
  190126. int rc = SQLITE_OK; /* Return code */
  190127. const char *z = zQuery; /* Special query text */
  190128. int n; /* Number of bytes in text at z */
  190129. while( z[0]==' ' ) z++;
  190130. for(n=0; z[n] && z[n]!=' '; n++);
  190131. assert( pTab->base.zErrMsg==0 );
  190132. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  190133. if( 0==sqlite3_strnicmp("reads", z, n) ){
  190134. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
  190135. }
  190136. else if( 0==sqlite3_strnicmp("id", z, n) ){
  190137. pCsr->iSpecial = pCsr->iCsrId;
  190138. }
  190139. else{
  190140. /* An unrecognized directive. Return an error message. */
  190141. pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  190142. rc = SQLITE_ERROR;
  190143. }
  190144. return rc;
  190145. }
  190146. /*
  190147. ** Search for an auxiliary function named zName that can be used with table
  190148. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  190149. ** structure. Otherwise, if no such function exists, return NULL.
  190150. */
  190151. static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
  190152. Fts5Auxiliary *pAux;
  190153. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  190154. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  190155. }
  190156. /* No function of the specified name was found. Return 0. */
  190157. return 0;
  190158. }
  190159. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  190160. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  190161. Fts5Config *pConfig = pTab->pConfig;
  190162. int rc = SQLITE_OK;
  190163. Fts5Auxiliary *pAux = 0;
  190164. const char *zRank = pCsr->zRank;
  190165. const char *zRankArgs = pCsr->zRankArgs;
  190166. if( zRankArgs ){
  190167. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  190168. if( zSql ){
  190169. sqlite3_stmt *pStmt = 0;
  190170. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  190171. SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
  190172. sqlite3_free(zSql);
  190173. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  190174. if( rc==SQLITE_OK ){
  190175. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  190176. int nByte;
  190177. pCsr->nRankArg = sqlite3_column_count(pStmt);
  190178. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  190179. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  190180. if( rc==SQLITE_OK ){
  190181. int i;
  190182. for(i=0; i<pCsr->nRankArg; i++){
  190183. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  190184. }
  190185. }
  190186. pCsr->pRankArgStmt = pStmt;
  190187. }else{
  190188. rc = sqlite3_finalize(pStmt);
  190189. assert( rc!=SQLITE_OK );
  190190. }
  190191. }
  190192. }
  190193. }
  190194. if( rc==SQLITE_OK ){
  190195. pAux = fts5FindAuxiliary(pTab, zRank);
  190196. if( pAux==0 ){
  190197. assert( pTab->base.zErrMsg==0 );
  190198. pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  190199. rc = SQLITE_ERROR;
  190200. }
  190201. }
  190202. pCsr->pRank = pAux;
  190203. return rc;
  190204. }
  190205. static int fts5CursorParseRank(
  190206. Fts5Config *pConfig,
  190207. Fts5Cursor *pCsr,
  190208. sqlite3_value *pRank
  190209. ){
  190210. int rc = SQLITE_OK;
  190211. if( pRank ){
  190212. const char *z = (const char*)sqlite3_value_text(pRank);
  190213. char *zRank = 0;
  190214. char *zRankArgs = 0;
  190215. if( z==0 ){
  190216. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  190217. }else{
  190218. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  190219. }
  190220. if( rc==SQLITE_OK ){
  190221. pCsr->zRank = zRank;
  190222. pCsr->zRankArgs = zRankArgs;
  190223. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  190224. }else if( rc==SQLITE_ERROR ){
  190225. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  190226. "parse error in rank function: %s", z
  190227. );
  190228. }
  190229. }else{
  190230. if( pConfig->zRank ){
  190231. pCsr->zRank = (char*)pConfig->zRank;
  190232. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  190233. }else{
  190234. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  190235. pCsr->zRankArgs = 0;
  190236. }
  190237. }
  190238. return rc;
  190239. }
  190240. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  190241. if( pVal ){
  190242. int eType = sqlite3_value_numeric_type(pVal);
  190243. if( eType==SQLITE_INTEGER ){
  190244. return sqlite3_value_int64(pVal);
  190245. }
  190246. }
  190247. return iDefault;
  190248. }
  190249. /*
  190250. ** This is the xFilter interface for the virtual table. See
  190251. ** the virtual table xFilter method documentation for additional
  190252. ** information.
  190253. **
  190254. ** There are three possible query strategies:
  190255. **
  190256. ** 1. Full-text search using a MATCH operator.
  190257. ** 2. A by-rowid lookup.
  190258. ** 3. A full-table scan.
  190259. */
  190260. static int fts5FilterMethod(
  190261. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  190262. int idxNum, /* Strategy index */
  190263. const char *zUnused, /* Unused */
  190264. int nVal, /* Number of elements in apVal */
  190265. sqlite3_value **apVal /* Arguments for the indexing scheme */
  190266. ){
  190267. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  190268. Fts5Config *pConfig = pTab->pConfig;
  190269. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  190270. int rc = SQLITE_OK; /* Error code */
  190271. int iVal = 0; /* Counter for apVal[] */
  190272. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  190273. int bOrderByRank; /* True if ORDER BY rank */
  190274. sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
  190275. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  190276. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  190277. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  190278. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  190279. int iCol; /* Column on LHS of MATCH operator */
  190280. char **pzErrmsg = pConfig->pzErrmsg;
  190281. UNUSED_PARAM(zUnused);
  190282. UNUSED_PARAM(nVal);
  190283. if( pCsr->ePlan ){
  190284. fts5FreeCursorComponents(pCsr);
  190285. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  190286. }
  190287. assert( pCsr->pStmt==0 );
  190288. assert( pCsr->pExpr==0 );
  190289. assert( pCsr->csrflags==0 );
  190290. assert( pCsr->pRank==0 );
  190291. assert( pCsr->zRank==0 );
  190292. assert( pCsr->zRankArgs==0 );
  190293. assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
  190294. pConfig->pzErrmsg = &pTab->base.zErrMsg;
  190295. /* Decode the arguments passed through to this function.
  190296. **
  190297. ** Note: The following set of if(...) statements must be in the same
  190298. ** order as the corresponding entries in the struct at the top of
  190299. ** fts5BestIndexMethod(). */
  190300. if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
  190301. if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
  190302. if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
  190303. if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
  190304. if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
  190305. iCol = (idxNum>>16);
  190306. assert( iCol>=0 && iCol<=pConfig->nCol );
  190307. assert( iVal==nVal );
  190308. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  190309. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  190310. /* Set the cursor upper and lower rowid limits. Only some strategies
  190311. ** actually use them. This is ok, as the xBestIndex() method leaves the
  190312. ** sqlite3_index_constraint.omit flag clear for range constraints
  190313. ** on the rowid field. */
  190314. if( pRowidEq ){
  190315. pRowidLe = pRowidGe = pRowidEq;
  190316. }
  190317. if( bDesc ){
  190318. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  190319. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  190320. }else{
  190321. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  190322. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  190323. }
  190324. if( pTab->pSortCsr ){
  190325. /* If pSortCsr is non-NULL, then this call is being made as part of
  190326. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  190327. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  190328. ** return results to the user for this query. The current cursor
  190329. ** (pCursor) is used to execute the query issued by function
  190330. ** fts5CursorFirstSorted() above. */
  190331. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  190332. assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
  190333. assert( pCsr->iLastRowid==LARGEST_INT64 );
  190334. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  190335. pCsr->ePlan = FTS5_PLAN_SOURCE;
  190336. pCsr->pExpr = pTab->pSortCsr->pExpr;
  190337. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  190338. }else if( pMatch ){
  190339. const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
  190340. if( zExpr==0 ) zExpr = "";
  190341. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  190342. if( rc==SQLITE_OK ){
  190343. if( zExpr[0]=='*' ){
  190344. /* The user has issued a query of the form "MATCH '*...'". This
  190345. ** indicates that the MATCH expression is not a full text query,
  190346. ** but a request for an internal parameter. */
  190347. rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
  190348. }else{
  190349. char **pzErr = &pTab->base.zErrMsg;
  190350. rc = sqlite3Fts5ExprNew(pConfig, iCol, zExpr, &pCsr->pExpr, pzErr);
  190351. if( rc==SQLITE_OK ){
  190352. if( bOrderByRank ){
  190353. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  190354. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  190355. }else{
  190356. pCsr->ePlan = FTS5_PLAN_MATCH;
  190357. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  190358. }
  190359. }
  190360. }
  190361. }
  190362. }else if( pConfig->zContent==0 ){
  190363. *pConfig->pzErrmsg = sqlite3_mprintf(
  190364. "%s: table does not support scanning", pConfig->zName
  190365. );
  190366. rc = SQLITE_ERROR;
  190367. }else{
  190368. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  190369. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  190370. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  190371. rc = sqlite3Fts5StorageStmt(
  190372. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
  190373. );
  190374. if( rc==SQLITE_OK ){
  190375. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  190376. sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
  190377. }else{
  190378. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  190379. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  190380. }
  190381. rc = fts5NextMethod(pCursor);
  190382. }
  190383. }
  190384. pConfig->pzErrmsg = pzErrmsg;
  190385. return rc;
  190386. }
  190387. /*
  190388. ** This is the xEof method of the virtual table. SQLite calls this
  190389. ** routine to find out if it has reached the end of a result set.
  190390. */
  190391. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  190392. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  190393. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  190394. }
  190395. /*
  190396. ** Return the rowid that the cursor currently points to.
  190397. */
  190398. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  190399. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  190400. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  190401. || pCsr->ePlan==FTS5_PLAN_SOURCE
  190402. );
  190403. if( pCsr->pSorter ){
  190404. return pCsr->pSorter->iRowid;
  190405. }else{
  190406. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  190407. }
  190408. }
  190409. /*
  190410. ** This is the xRowid method. The SQLite core calls this routine to
  190411. ** retrieve the rowid for the current row of the result set. fts5
  190412. ** exposes %_content.rowid as the rowid for the virtual table. The
  190413. ** rowid should be written to *pRowid.
  190414. */
  190415. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  190416. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  190417. int ePlan = pCsr->ePlan;
  190418. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  190419. switch( ePlan ){
  190420. case FTS5_PLAN_SPECIAL:
  190421. *pRowid = 0;
  190422. break;
  190423. case FTS5_PLAN_SOURCE:
  190424. case FTS5_PLAN_MATCH:
  190425. case FTS5_PLAN_SORTED_MATCH:
  190426. *pRowid = fts5CursorRowid(pCsr);
  190427. break;
  190428. default:
  190429. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  190430. break;
  190431. }
  190432. return SQLITE_OK;
  190433. }
  190434. /*
  190435. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  190436. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  190437. **
  190438. ** If argument bErrormsg is true and an error occurs, an error message may
  190439. ** be left in sqlite3_vtab.zErrMsg.
  190440. */
  190441. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  190442. int rc = SQLITE_OK;
  190443. /* If the cursor does not yet have a statement handle, obtain one now. */
  190444. if( pCsr->pStmt==0 ){
  190445. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  190446. int eStmt = fts5StmtType(pCsr);
  190447. rc = sqlite3Fts5StorageStmt(
  190448. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
  190449. );
  190450. assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
  190451. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  190452. }
  190453. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  190454. assert( pCsr->pExpr );
  190455. sqlite3_reset(pCsr->pStmt);
  190456. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  190457. rc = sqlite3_step(pCsr->pStmt);
  190458. if( rc==SQLITE_ROW ){
  190459. rc = SQLITE_OK;
  190460. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  190461. }else{
  190462. rc = sqlite3_reset(pCsr->pStmt);
  190463. if( rc==SQLITE_OK ){
  190464. rc = FTS5_CORRUPT;
  190465. }
  190466. }
  190467. }
  190468. return rc;
  190469. }
  190470. static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
  190471. va_list ap; /* ... printf arguments */
  190472. va_start(ap, zFormat);
  190473. assert( p->base.zErrMsg==0 );
  190474. p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  190475. va_end(ap);
  190476. }
  190477. /*
  190478. ** This function is called to handle an FTS INSERT command. In other words,
  190479. ** an INSERT statement of the form:
  190480. **
  190481. ** INSERT INTO fts(fts) VALUES($pCmd)
  190482. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  190483. **
  190484. ** Argument pVal is the value assigned to column "fts" by the INSERT
  190485. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  190486. ** error code if an error occurs.
  190487. **
  190488. ** The commands implemented by this function are documented in the "Special
  190489. ** INSERT Directives" section of the documentation. It should be updated if
  190490. ** more commands are added to this function.
  190491. */
  190492. static int fts5SpecialInsert(
  190493. Fts5Table *pTab, /* Fts5 table object */
  190494. const char *zCmd, /* Text inserted into table-name column */
  190495. sqlite3_value *pVal /* Value inserted into rank column */
  190496. ){
  190497. Fts5Config *pConfig = pTab->pConfig;
  190498. int rc = SQLITE_OK;
  190499. int bError = 0;
  190500. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  190501. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  190502. fts5SetVtabError(pTab,
  190503. "'delete-all' may only be used with a "
  190504. "contentless or external content fts5 table"
  190505. );
  190506. rc = SQLITE_ERROR;
  190507. }else{
  190508. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  190509. }
  190510. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  190511. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  190512. fts5SetVtabError(pTab,
  190513. "'rebuild' may not be used with a contentless fts5 table"
  190514. );
  190515. rc = SQLITE_ERROR;
  190516. }else{
  190517. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  190518. }
  190519. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  190520. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  190521. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  190522. int nMerge = sqlite3_value_int(pVal);
  190523. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  190524. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  190525. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  190526. #ifdef SQLITE_DEBUG
  190527. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  190528. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  190529. #endif
  190530. }else{
  190531. rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
  190532. if( rc==SQLITE_OK ){
  190533. rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
  190534. }
  190535. if( rc==SQLITE_OK ){
  190536. if( bError ){
  190537. rc = SQLITE_ERROR;
  190538. }else{
  190539. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  190540. }
  190541. }
  190542. }
  190543. return rc;
  190544. }
  190545. static int fts5SpecialDelete(
  190546. Fts5Table *pTab,
  190547. sqlite3_value **apVal
  190548. ){
  190549. int rc = SQLITE_OK;
  190550. int eType1 = sqlite3_value_type(apVal[1]);
  190551. if( eType1==SQLITE_INTEGER ){
  190552. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  190553. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
  190554. }
  190555. return rc;
  190556. }
  190557. static void fts5StorageInsert(
  190558. int *pRc,
  190559. Fts5Table *pTab,
  190560. sqlite3_value **apVal,
  190561. i64 *piRowid
  190562. ){
  190563. int rc = *pRc;
  190564. if( rc==SQLITE_OK ){
  190565. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  190566. }
  190567. if( rc==SQLITE_OK ){
  190568. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  190569. }
  190570. *pRc = rc;
  190571. }
  190572. /*
  190573. ** This function is the implementation of the xUpdate callback used by
  190574. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  190575. ** inserted, updated or deleted.
  190576. **
  190577. ** A delete specifies a single argument - the rowid of the row to remove.
  190578. **
  190579. ** Update and insert operations pass:
  190580. **
  190581. ** 1. The "old" rowid, or NULL.
  190582. ** 2. The "new" rowid.
  190583. ** 3. Values for each of the nCol matchable columns.
  190584. ** 4. Values for the two hidden columns (<tablename> and "rank").
  190585. */
  190586. static int fts5UpdateMethod(
  190587. sqlite3_vtab *pVtab, /* Virtual table handle */
  190588. int nArg, /* Size of argument array */
  190589. sqlite3_value **apVal, /* Array of arguments */
  190590. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  190591. ){
  190592. Fts5Table *pTab = (Fts5Table*)pVtab;
  190593. Fts5Config *pConfig = pTab->pConfig;
  190594. int eType0; /* value_type() of apVal[0] */
  190595. int rc = SQLITE_OK; /* Return code */
  190596. /* A transaction must be open when this is called. */
  190597. assert( pTab->ts.eState==1 );
  190598. assert( pVtab->zErrMsg==0 );
  190599. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  190600. assert( nArg==1
  190601. || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  190602. || sqlite3_value_type(apVal[1])==SQLITE_NULL
  190603. );
  190604. assert( pTab->pConfig->pzErrmsg==0 );
  190605. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  190606. /* Put any active cursors into REQUIRE_SEEK state. */
  190607. fts5TripCursors(pTab);
  190608. eType0 = sqlite3_value_type(apVal[0]);
  190609. if( eType0==SQLITE_NULL
  190610. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  190611. ){
  190612. /* A "special" INSERT op. These are handled separately. */
  190613. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  190614. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  190615. && 0==sqlite3_stricmp("delete", z)
  190616. ){
  190617. rc = fts5SpecialDelete(pTab, apVal);
  190618. }else{
  190619. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  190620. }
  190621. }else{
  190622. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  190623. ** any conflict on the rowid value must be detected before any
  190624. ** modifications are made to the database file. There are 4 cases:
  190625. **
  190626. ** 1) DELETE
  190627. ** 2) UPDATE (rowid not modified)
  190628. ** 3) UPDATE (rowid modified)
  190629. ** 4) INSERT
  190630. **
  190631. ** Cases 3 and 4 may violate the rowid constraint.
  190632. */
  190633. int eConflict = SQLITE_ABORT;
  190634. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  190635. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  190636. }
  190637. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  190638. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  190639. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  190640. ** This is not suported. */
  190641. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  190642. pTab->base.zErrMsg = sqlite3_mprintf(
  190643. "cannot %s contentless fts5 table: %s",
  190644. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  190645. );
  190646. rc = SQLITE_ERROR;
  190647. }
  190648. /* DELETE */
  190649. else if( nArg==1 ){
  190650. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  190651. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
  190652. }
  190653. /* INSERT */
  190654. else if( eType0!=SQLITE_INTEGER ){
  190655. /* If this is a REPLACE, first remove the current entry (if any) */
  190656. if( eConflict==SQLITE_REPLACE
  190657. && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
  190658. ){
  190659. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  190660. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  190661. }
  190662. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  190663. }
  190664. /* UPDATE */
  190665. else{
  190666. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  190667. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  190668. if( iOld!=iNew ){
  190669. if( eConflict==SQLITE_REPLACE ){
  190670. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  190671. if( rc==SQLITE_OK ){
  190672. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  190673. }
  190674. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  190675. }else{
  190676. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  190677. if( rc==SQLITE_OK ){
  190678. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  190679. }
  190680. if( rc==SQLITE_OK ){
  190681. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
  190682. }
  190683. }
  190684. }else{
  190685. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  190686. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  190687. }
  190688. }
  190689. }
  190690. pTab->pConfig->pzErrmsg = 0;
  190691. return rc;
  190692. }
  190693. /*
  190694. ** Implementation of xSync() method.
  190695. */
  190696. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  190697. int rc;
  190698. Fts5Table *pTab = (Fts5Table*)pVtab;
  190699. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  190700. pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
  190701. fts5TripCursors(pTab);
  190702. rc = sqlite3Fts5StorageSync(pTab->pStorage);
  190703. pTab->pConfig->pzErrmsg = 0;
  190704. return rc;
  190705. }
  190706. /*
  190707. ** Implementation of xBegin() method.
  190708. */
  190709. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  190710. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
  190711. fts5NewTransaction((Fts5Table*)pVtab);
  190712. return SQLITE_OK;
  190713. }
  190714. /*
  190715. ** Implementation of xCommit() method. This is a no-op. The contents of
  190716. ** the pending-terms hash-table have already been flushed into the database
  190717. ** by fts5SyncMethod().
  190718. */
  190719. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  190720. UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
  190721. fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
  190722. return SQLITE_OK;
  190723. }
  190724. /*
  190725. ** Implementation of xRollback(). Discard the contents of the pending-terms
  190726. ** hash-table. Any changes made to the database are reverted by SQLite.
  190727. */
  190728. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  190729. int rc;
  190730. Fts5Table *pTab = (Fts5Table*)pVtab;
  190731. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  190732. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  190733. return rc;
  190734. }
  190735. static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
  190736. static void *fts5ApiUserData(Fts5Context *pCtx){
  190737. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190738. return pCsr->pAux->pUserData;
  190739. }
  190740. static int fts5ApiColumnCount(Fts5Context *pCtx){
  190741. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190742. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  190743. }
  190744. static int fts5ApiColumnTotalSize(
  190745. Fts5Context *pCtx,
  190746. int iCol,
  190747. sqlite3_int64 *pnToken
  190748. ){
  190749. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190750. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  190751. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  190752. }
  190753. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  190754. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190755. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  190756. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  190757. }
  190758. static int fts5ApiTokenize(
  190759. Fts5Context *pCtx,
  190760. const char *pText, int nText,
  190761. void *pUserData,
  190762. int (*xToken)(void*, int, const char*, int, int, int)
  190763. ){
  190764. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190765. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  190766. return sqlite3Fts5Tokenize(
  190767. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  190768. );
  190769. }
  190770. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  190771. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190772. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  190773. }
  190774. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  190775. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190776. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  190777. }
  190778. static int fts5ApiColumnText(
  190779. Fts5Context *pCtx,
  190780. int iCol,
  190781. const char **pz,
  190782. int *pn
  190783. ){
  190784. int rc = SQLITE_OK;
  190785. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190786. if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
  190787. *pz = 0;
  190788. *pn = 0;
  190789. }else{
  190790. rc = fts5SeekCursor(pCsr, 0);
  190791. if( rc==SQLITE_OK ){
  190792. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  190793. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  190794. }
  190795. }
  190796. return rc;
  190797. }
  190798. static int fts5CsrPoslist(
  190799. Fts5Cursor *pCsr,
  190800. int iPhrase,
  190801. const u8 **pa,
  190802. int *pn
  190803. ){
  190804. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  190805. int rc = SQLITE_OK;
  190806. int bLive = (pCsr->pSorter==0);
  190807. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
  190808. if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
  190809. Fts5PoslistPopulator *aPopulator;
  190810. int i;
  190811. aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
  190812. if( aPopulator==0 ) rc = SQLITE_NOMEM;
  190813. for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
  190814. int n; const char *z;
  190815. rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
  190816. if( rc==SQLITE_OK ){
  190817. rc = sqlite3Fts5ExprPopulatePoslists(
  190818. pConfig, pCsr->pExpr, aPopulator, i, z, n
  190819. );
  190820. }
  190821. }
  190822. sqlite3_free(aPopulator);
  190823. if( pCsr->pSorter ){
  190824. sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
  190825. }
  190826. }
  190827. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
  190828. }
  190829. if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
  190830. Fts5Sorter *pSorter = pCsr->pSorter;
  190831. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  190832. *pn = pSorter->aIdx[iPhrase] - i1;
  190833. *pa = &pSorter->aPoslist[i1];
  190834. }else{
  190835. *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  190836. }
  190837. return rc;
  190838. }
  190839. /*
  190840. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  190841. ** correctly for the current view. Return SQLITE_OK if successful, or an
  190842. ** SQLite error code otherwise.
  190843. */
  190844. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  190845. int rc = SQLITE_OK;
  190846. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  190847. int nIter; /* Number of iterators/phrases */
  190848. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  190849. if( pCsr->aInstIter==0 ){
  190850. int nByte = sizeof(Fts5PoslistReader) * nIter;
  190851. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  190852. }
  190853. aIter = pCsr->aInstIter;
  190854. if( aIter ){
  190855. int nInst = 0; /* Number instances seen so far */
  190856. int i;
  190857. /* Initialize all iterators */
  190858. for(i=0; i<nIter && rc==SQLITE_OK; i++){
  190859. const u8 *a;
  190860. int n;
  190861. rc = fts5CsrPoslist(pCsr, i, &a, &n);
  190862. if( rc==SQLITE_OK ){
  190863. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  190864. }
  190865. }
  190866. if( rc==SQLITE_OK ){
  190867. while( 1 ){
  190868. int *aInst;
  190869. int iBest = -1;
  190870. for(i=0; i<nIter; i++){
  190871. if( (aIter[i].bEof==0)
  190872. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  190873. ){
  190874. iBest = i;
  190875. }
  190876. }
  190877. if( iBest<0 ) break;
  190878. nInst++;
  190879. if( nInst>=pCsr->nInstAlloc ){
  190880. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  190881. aInst = (int*)sqlite3_realloc(
  190882. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  190883. );
  190884. if( aInst ){
  190885. pCsr->aInst = aInst;
  190886. }else{
  190887. rc = SQLITE_NOMEM;
  190888. break;
  190889. }
  190890. }
  190891. aInst = &pCsr->aInst[3 * (nInst-1)];
  190892. aInst[0] = iBest;
  190893. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  190894. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  190895. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  190896. }
  190897. }
  190898. pCsr->nInstCount = nInst;
  190899. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  190900. }
  190901. return rc;
  190902. }
  190903. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  190904. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190905. int rc = SQLITE_OK;
  190906. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  190907. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  190908. *pnInst = pCsr->nInstCount;
  190909. }
  190910. return rc;
  190911. }
  190912. static int fts5ApiInst(
  190913. Fts5Context *pCtx,
  190914. int iIdx,
  190915. int *piPhrase,
  190916. int *piCol,
  190917. int *piOff
  190918. ){
  190919. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190920. int rc = SQLITE_OK;
  190921. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  190922. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  190923. ){
  190924. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  190925. rc = SQLITE_RANGE;
  190926. #if 0
  190927. }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
  190928. *piPhrase = pCsr->aInst[iIdx*3];
  190929. *piCol = pCsr->aInst[iIdx*3 + 2];
  190930. *piOff = -1;
  190931. #endif
  190932. }else{
  190933. *piPhrase = pCsr->aInst[iIdx*3];
  190934. *piCol = pCsr->aInst[iIdx*3 + 1];
  190935. *piOff = pCsr->aInst[iIdx*3 + 2];
  190936. }
  190937. }
  190938. return rc;
  190939. }
  190940. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  190941. return fts5CursorRowid((Fts5Cursor*)pCtx);
  190942. }
  190943. static int fts5ColumnSizeCb(
  190944. void *pContext, /* Pointer to int */
  190945. int tflags,
  190946. const char *pUnused, /* Buffer containing token */
  190947. int nUnused, /* Size of token in bytes */
  190948. int iUnused1, /* Start offset of token */
  190949. int iUnused2 /* End offset of token */
  190950. ){
  190951. int *pCnt = (int*)pContext;
  190952. UNUSED_PARAM2(pUnused, nUnused);
  190953. UNUSED_PARAM2(iUnused1, iUnused2);
  190954. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  190955. (*pCnt)++;
  190956. }
  190957. return SQLITE_OK;
  190958. }
  190959. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  190960. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  190961. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  190962. Fts5Config *pConfig = pTab->pConfig;
  190963. int rc = SQLITE_OK;
  190964. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  190965. if( pConfig->bColumnsize ){
  190966. i64 iRowid = fts5CursorRowid(pCsr);
  190967. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  190968. }else if( pConfig->zContent==0 ){
  190969. int i;
  190970. for(i=0; i<pConfig->nCol; i++){
  190971. if( pConfig->abUnindexed[i]==0 ){
  190972. pCsr->aColumnSize[i] = -1;
  190973. }
  190974. }
  190975. }else{
  190976. int i;
  190977. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  190978. if( pConfig->abUnindexed[i]==0 ){
  190979. const char *z; int n;
  190980. void *p = (void*)(&pCsr->aColumnSize[i]);
  190981. pCsr->aColumnSize[i] = 0;
  190982. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  190983. if( rc==SQLITE_OK ){
  190984. rc = sqlite3Fts5Tokenize(
  190985. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  190986. );
  190987. }
  190988. }
  190989. }
  190990. }
  190991. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  190992. }
  190993. if( iCol<0 ){
  190994. int i;
  190995. *pnToken = 0;
  190996. for(i=0; i<pConfig->nCol; i++){
  190997. *pnToken += pCsr->aColumnSize[i];
  190998. }
  190999. }else if( iCol<pConfig->nCol ){
  191000. *pnToken = pCsr->aColumnSize[iCol];
  191001. }else{
  191002. *pnToken = 0;
  191003. rc = SQLITE_RANGE;
  191004. }
  191005. return rc;
  191006. }
  191007. /*
  191008. ** Implementation of the xSetAuxdata() method.
  191009. */
  191010. static int fts5ApiSetAuxdata(
  191011. Fts5Context *pCtx, /* Fts5 context */
  191012. void *pPtr, /* Pointer to save as auxdata */
  191013. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  191014. ){
  191015. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  191016. Fts5Auxdata *pData;
  191017. /* Search through the cursors list of Fts5Auxdata objects for one that
  191018. ** corresponds to the currently executing auxiliary function. */
  191019. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  191020. if( pData->pAux==pCsr->pAux ) break;
  191021. }
  191022. if( pData ){
  191023. if( pData->xDelete ){
  191024. pData->xDelete(pData->pPtr);
  191025. }
  191026. }else{
  191027. int rc = SQLITE_OK;
  191028. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  191029. if( pData==0 ){
  191030. if( xDelete ) xDelete(pPtr);
  191031. return rc;
  191032. }
  191033. pData->pAux = pCsr->pAux;
  191034. pData->pNext = pCsr->pAuxdata;
  191035. pCsr->pAuxdata = pData;
  191036. }
  191037. pData->xDelete = xDelete;
  191038. pData->pPtr = pPtr;
  191039. return SQLITE_OK;
  191040. }
  191041. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  191042. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  191043. Fts5Auxdata *pData;
  191044. void *pRet = 0;
  191045. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  191046. if( pData->pAux==pCsr->pAux ) break;
  191047. }
  191048. if( pData ){
  191049. pRet = pData->pPtr;
  191050. if( bClear ){
  191051. pData->pPtr = 0;
  191052. pData->xDelete = 0;
  191053. }
  191054. }
  191055. return pRet;
  191056. }
  191057. static void fts5ApiPhraseNext(
  191058. Fts5Context *pUnused,
  191059. Fts5PhraseIter *pIter,
  191060. int *piCol, int *piOff
  191061. ){
  191062. UNUSED_PARAM(pUnused);
  191063. if( pIter->a>=pIter->b ){
  191064. *piCol = -1;
  191065. *piOff = -1;
  191066. }else{
  191067. int iVal;
  191068. pIter->a += fts5GetVarint32(pIter->a, iVal);
  191069. if( iVal==1 ){
  191070. pIter->a += fts5GetVarint32(pIter->a, iVal);
  191071. *piCol = iVal;
  191072. *piOff = 0;
  191073. pIter->a += fts5GetVarint32(pIter->a, iVal);
  191074. }
  191075. *piOff += (iVal-2);
  191076. }
  191077. }
  191078. static int fts5ApiPhraseFirst(
  191079. Fts5Context *pCtx,
  191080. int iPhrase,
  191081. Fts5PhraseIter *pIter,
  191082. int *piCol, int *piOff
  191083. ){
  191084. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  191085. int n;
  191086. int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  191087. if( rc==SQLITE_OK ){
  191088. pIter->b = &pIter->a[n];
  191089. *piCol = 0;
  191090. *piOff = 0;
  191091. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  191092. }
  191093. return rc;
  191094. }
  191095. static void fts5ApiPhraseNextColumn(
  191096. Fts5Context *pCtx,
  191097. Fts5PhraseIter *pIter,
  191098. int *piCol
  191099. ){
  191100. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  191101. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  191102. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  191103. if( pIter->a>=pIter->b ){
  191104. *piCol = -1;
  191105. }else{
  191106. int iIncr;
  191107. pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
  191108. *piCol += (iIncr-2);
  191109. }
  191110. }else{
  191111. while( 1 ){
  191112. int dummy;
  191113. if( pIter->a>=pIter->b ){
  191114. *piCol = -1;
  191115. return;
  191116. }
  191117. if( pIter->a[0]==0x01 ) break;
  191118. pIter->a += fts5GetVarint32(pIter->a, dummy);
  191119. }
  191120. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  191121. }
  191122. }
  191123. static int fts5ApiPhraseFirstColumn(
  191124. Fts5Context *pCtx,
  191125. int iPhrase,
  191126. Fts5PhraseIter *pIter,
  191127. int *piCol
  191128. ){
  191129. int rc = SQLITE_OK;
  191130. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  191131. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  191132. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  191133. Fts5Sorter *pSorter = pCsr->pSorter;
  191134. int n;
  191135. if( pSorter ){
  191136. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  191137. n = pSorter->aIdx[iPhrase] - i1;
  191138. pIter->a = &pSorter->aPoslist[i1];
  191139. }else{
  191140. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
  191141. }
  191142. if( rc==SQLITE_OK ){
  191143. pIter->b = &pIter->a[n];
  191144. *piCol = 0;
  191145. fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
  191146. }
  191147. }else{
  191148. int n;
  191149. rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  191150. if( rc==SQLITE_OK ){
  191151. pIter->b = &pIter->a[n];
  191152. if( n<=0 ){
  191153. *piCol = -1;
  191154. }else if( pIter->a[0]==0x01 ){
  191155. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  191156. }else{
  191157. *piCol = 0;
  191158. }
  191159. }
  191160. }
  191161. return rc;
  191162. }
  191163. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  191164. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  191165. );
  191166. static const Fts5ExtensionApi sFts5Api = {
  191167. 2, /* iVersion */
  191168. fts5ApiUserData,
  191169. fts5ApiColumnCount,
  191170. fts5ApiRowCount,
  191171. fts5ApiColumnTotalSize,
  191172. fts5ApiTokenize,
  191173. fts5ApiPhraseCount,
  191174. fts5ApiPhraseSize,
  191175. fts5ApiInstCount,
  191176. fts5ApiInst,
  191177. fts5ApiRowid,
  191178. fts5ApiColumnText,
  191179. fts5ApiColumnSize,
  191180. fts5ApiQueryPhrase,
  191181. fts5ApiSetAuxdata,
  191182. fts5ApiGetAuxdata,
  191183. fts5ApiPhraseFirst,
  191184. fts5ApiPhraseNext,
  191185. fts5ApiPhraseFirstColumn,
  191186. fts5ApiPhraseNextColumn,
  191187. };
  191188. /*
  191189. ** Implementation of API function xQueryPhrase().
  191190. */
  191191. static int fts5ApiQueryPhrase(
  191192. Fts5Context *pCtx,
  191193. int iPhrase,
  191194. void *pUserData,
  191195. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  191196. ){
  191197. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  191198. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  191199. int rc;
  191200. Fts5Cursor *pNew = 0;
  191201. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  191202. if( rc==SQLITE_OK ){
  191203. pNew->ePlan = FTS5_PLAN_MATCH;
  191204. pNew->iFirstRowid = SMALLEST_INT64;
  191205. pNew->iLastRowid = LARGEST_INT64;
  191206. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  191207. rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
  191208. }
  191209. if( rc==SQLITE_OK ){
  191210. for(rc = fts5CursorFirst(pTab, pNew, 0);
  191211. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  191212. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  191213. ){
  191214. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  191215. if( rc!=SQLITE_OK ){
  191216. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  191217. break;
  191218. }
  191219. }
  191220. }
  191221. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  191222. return rc;
  191223. }
  191224. static void fts5ApiInvoke(
  191225. Fts5Auxiliary *pAux,
  191226. Fts5Cursor *pCsr,
  191227. sqlite3_context *context,
  191228. int argc,
  191229. sqlite3_value **argv
  191230. ){
  191231. assert( pCsr->pAux==0 );
  191232. pCsr->pAux = pAux;
  191233. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  191234. pCsr->pAux = 0;
  191235. }
  191236. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  191237. Fts5Cursor *pCsr;
  191238. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  191239. if( pCsr->iCsrId==iCsrId ) break;
  191240. }
  191241. return pCsr;
  191242. }
  191243. static void fts5ApiCallback(
  191244. sqlite3_context *context,
  191245. int argc,
  191246. sqlite3_value **argv
  191247. ){
  191248. Fts5Auxiliary *pAux;
  191249. Fts5Cursor *pCsr;
  191250. i64 iCsrId;
  191251. assert( argc>=1 );
  191252. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  191253. iCsrId = sqlite3_value_int64(argv[0]);
  191254. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  191255. if( pCsr==0 ){
  191256. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  191257. sqlite3_result_error(context, zErr, -1);
  191258. sqlite3_free(zErr);
  191259. }else{
  191260. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  191261. }
  191262. }
  191263. /*
  191264. ** Given cursor id iId, return a pointer to the corresponding Fts5Index
  191265. ** object. Or NULL If the cursor id does not exist.
  191266. **
  191267. ** If successful, set *ppConfig to point to the associated config object
  191268. ** before returning.
  191269. */
  191270. static Fts5Index *sqlite3Fts5IndexFromCsrid(
  191271. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  191272. i64 iCsrId, /* Id of cursor to find */
  191273. Fts5Config **ppConfig /* OUT: Configuration object */
  191274. ){
  191275. Fts5Cursor *pCsr;
  191276. Fts5Table *pTab;
  191277. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  191278. pTab = (Fts5Table*)pCsr->base.pVtab;
  191279. *ppConfig = pTab->pConfig;
  191280. return pTab->pIndex;
  191281. }
  191282. /*
  191283. ** Return a "position-list blob" corresponding to the current position of
  191284. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  191285. ** the current position-list for each phrase in the query associated with
  191286. ** cursor pCsr.
  191287. **
  191288. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  191289. ** the number of phrases in the query. Following the varints are the
  191290. ** concatenated position lists for each phrase, in order.
  191291. **
  191292. ** The first varint (if it exists) contains the size of the position list
  191293. ** for phrase 0. The second (same disclaimer) contains the size of position
  191294. ** list 1. And so on. There is no size field for the final position list,
  191295. ** as it can be derived from the total size of the blob.
  191296. */
  191297. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  191298. int i;
  191299. int rc = SQLITE_OK;
  191300. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  191301. Fts5Buffer val;
  191302. memset(&val, 0, sizeof(Fts5Buffer));
  191303. switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
  191304. case FTS5_DETAIL_FULL:
  191305. /* Append the varints */
  191306. for(i=0; i<(nPhrase-1); i++){
  191307. const u8 *dummy;
  191308. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  191309. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  191310. }
  191311. /* Append the position lists */
  191312. for(i=0; i<nPhrase; i++){
  191313. const u8 *pPoslist;
  191314. int nPoslist;
  191315. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  191316. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  191317. }
  191318. break;
  191319. case FTS5_DETAIL_COLUMNS:
  191320. /* Append the varints */
  191321. for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
  191322. const u8 *dummy;
  191323. int nByte;
  191324. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
  191325. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  191326. }
  191327. /* Append the position lists */
  191328. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  191329. const u8 *pPoslist;
  191330. int nPoslist;
  191331. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
  191332. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  191333. }
  191334. break;
  191335. default:
  191336. break;
  191337. }
  191338. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  191339. return rc;
  191340. }
  191341. /*
  191342. ** This is the xColumn method, called by SQLite to request a value from
  191343. ** the row that the supplied cursor currently points to.
  191344. */
  191345. static int fts5ColumnMethod(
  191346. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  191347. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  191348. int iCol /* Index of column to read value from */
  191349. ){
  191350. Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
  191351. Fts5Config *pConfig = pTab->pConfig;
  191352. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  191353. int rc = SQLITE_OK;
  191354. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  191355. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  191356. if( iCol==pConfig->nCol ){
  191357. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  191358. }
  191359. }else
  191360. if( iCol==pConfig->nCol ){
  191361. /* User is requesting the value of the special column with the same name
  191362. ** as the table. Return the cursor integer id number. This value is only
  191363. ** useful in that it may be passed as the first argument to an FTS5
  191364. ** auxiliary function. */
  191365. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  191366. }else if( iCol==pConfig->nCol+1 ){
  191367. /* The value of the "rank" column. */
  191368. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  191369. fts5PoslistBlob(pCtx, pCsr);
  191370. }else if(
  191371. pCsr->ePlan==FTS5_PLAN_MATCH
  191372. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  191373. ){
  191374. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  191375. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  191376. }
  191377. }
  191378. }else if( !fts5IsContentless(pTab) ){
  191379. rc = fts5SeekCursor(pCsr, 1);
  191380. if( rc==SQLITE_OK ){
  191381. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  191382. }
  191383. }
  191384. return rc;
  191385. }
  191386. /*
  191387. ** This routine implements the xFindFunction method for the FTS3
  191388. ** virtual table.
  191389. */
  191390. static int fts5FindFunctionMethod(
  191391. sqlite3_vtab *pVtab, /* Virtual table handle */
  191392. int nUnused, /* Number of SQL function arguments */
  191393. const char *zName, /* Name of SQL function */
  191394. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  191395. void **ppArg /* OUT: User data for *pxFunc */
  191396. ){
  191397. Fts5Table *pTab = (Fts5Table*)pVtab;
  191398. Fts5Auxiliary *pAux;
  191399. UNUSED_PARAM(nUnused);
  191400. pAux = fts5FindAuxiliary(pTab, zName);
  191401. if( pAux ){
  191402. *pxFunc = fts5ApiCallback;
  191403. *ppArg = (void*)pAux;
  191404. return 1;
  191405. }
  191406. /* No function of the specified name was found. Return 0. */
  191407. return 0;
  191408. }
  191409. /*
  191410. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  191411. */
  191412. static int fts5RenameMethod(
  191413. sqlite3_vtab *pVtab, /* Virtual table handle */
  191414. const char *zName /* New name of table */
  191415. ){
  191416. Fts5Table *pTab = (Fts5Table*)pVtab;
  191417. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  191418. }
  191419. /*
  191420. ** The xSavepoint() method.
  191421. **
  191422. ** Flush the contents of the pending-terms table to disk.
  191423. */
  191424. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  191425. Fts5Table *pTab = (Fts5Table*)pVtab;
  191426. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  191427. fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
  191428. fts5TripCursors(pTab);
  191429. return sqlite3Fts5StorageSync(pTab->pStorage);
  191430. }
  191431. /*
  191432. ** The xRelease() method.
  191433. **
  191434. ** This is a no-op.
  191435. */
  191436. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  191437. Fts5Table *pTab = (Fts5Table*)pVtab;
  191438. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  191439. fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
  191440. fts5TripCursors(pTab);
  191441. return sqlite3Fts5StorageSync(pTab->pStorage);
  191442. }
  191443. /*
  191444. ** The xRollbackTo() method.
  191445. **
  191446. ** Discard the contents of the pending terms table.
  191447. */
  191448. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  191449. Fts5Table *pTab = (Fts5Table*)pVtab;
  191450. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  191451. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  191452. fts5TripCursors(pTab);
  191453. return sqlite3Fts5StorageRollback(pTab->pStorage);
  191454. }
  191455. /*
  191456. ** Register a new auxiliary function with global context pGlobal.
  191457. */
  191458. static int fts5CreateAux(
  191459. fts5_api *pApi, /* Global context (one per db handle) */
  191460. const char *zName, /* Name of new function */
  191461. void *pUserData, /* User data for aux. function */
  191462. fts5_extension_function xFunc, /* Aux. function implementation */
  191463. void(*xDestroy)(void*) /* Destructor for pUserData */
  191464. ){
  191465. Fts5Global *pGlobal = (Fts5Global*)pApi;
  191466. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  191467. if( rc==SQLITE_OK ){
  191468. Fts5Auxiliary *pAux;
  191469. int nName; /* Size of zName in bytes, including \0 */
  191470. int nByte; /* Bytes of space to allocate */
  191471. nName = (int)strlen(zName) + 1;
  191472. nByte = sizeof(Fts5Auxiliary) + nName;
  191473. pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
  191474. if( pAux ){
  191475. memset(pAux, 0, nByte);
  191476. pAux->zFunc = (char*)&pAux[1];
  191477. memcpy(pAux->zFunc, zName, nName);
  191478. pAux->pGlobal = pGlobal;
  191479. pAux->pUserData = pUserData;
  191480. pAux->xFunc = xFunc;
  191481. pAux->xDestroy = xDestroy;
  191482. pAux->pNext = pGlobal->pAux;
  191483. pGlobal->pAux = pAux;
  191484. }else{
  191485. rc = SQLITE_NOMEM;
  191486. }
  191487. }
  191488. return rc;
  191489. }
  191490. /*
  191491. ** Register a new tokenizer. This is the implementation of the
  191492. ** fts5_api.xCreateTokenizer() method.
  191493. */
  191494. static int fts5CreateTokenizer(
  191495. fts5_api *pApi, /* Global context (one per db handle) */
  191496. const char *zName, /* Name of new function */
  191497. void *pUserData, /* User data for aux. function */
  191498. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  191499. void(*xDestroy)(void*) /* Destructor for pUserData */
  191500. ){
  191501. Fts5Global *pGlobal = (Fts5Global*)pApi;
  191502. Fts5TokenizerModule *pNew;
  191503. int nName; /* Size of zName and its \0 terminator */
  191504. int nByte; /* Bytes of space to allocate */
  191505. int rc = SQLITE_OK;
  191506. nName = (int)strlen(zName) + 1;
  191507. nByte = sizeof(Fts5TokenizerModule) + nName;
  191508. pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
  191509. if( pNew ){
  191510. memset(pNew, 0, nByte);
  191511. pNew->zName = (char*)&pNew[1];
  191512. memcpy(pNew->zName, zName, nName);
  191513. pNew->pUserData = pUserData;
  191514. pNew->x = *pTokenizer;
  191515. pNew->xDestroy = xDestroy;
  191516. pNew->pNext = pGlobal->pTok;
  191517. pGlobal->pTok = pNew;
  191518. if( pNew->pNext==0 ){
  191519. pGlobal->pDfltTok = pNew;
  191520. }
  191521. }else{
  191522. rc = SQLITE_NOMEM;
  191523. }
  191524. return rc;
  191525. }
  191526. static Fts5TokenizerModule *fts5LocateTokenizer(
  191527. Fts5Global *pGlobal,
  191528. const char *zName
  191529. ){
  191530. Fts5TokenizerModule *pMod = 0;
  191531. if( zName==0 ){
  191532. pMod = pGlobal->pDfltTok;
  191533. }else{
  191534. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  191535. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  191536. }
  191537. }
  191538. return pMod;
  191539. }
  191540. /*
  191541. ** Find a tokenizer. This is the implementation of the
  191542. ** fts5_api.xFindTokenizer() method.
  191543. */
  191544. static int fts5FindTokenizer(
  191545. fts5_api *pApi, /* Global context (one per db handle) */
  191546. const char *zName, /* Name of new function */
  191547. void **ppUserData,
  191548. fts5_tokenizer *pTokenizer /* Populate this object */
  191549. ){
  191550. int rc = SQLITE_OK;
  191551. Fts5TokenizerModule *pMod;
  191552. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  191553. if( pMod ){
  191554. *pTokenizer = pMod->x;
  191555. *ppUserData = pMod->pUserData;
  191556. }else{
  191557. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  191558. rc = SQLITE_ERROR;
  191559. }
  191560. return rc;
  191561. }
  191562. static int sqlite3Fts5GetTokenizer(
  191563. Fts5Global *pGlobal,
  191564. const char **azArg,
  191565. int nArg,
  191566. Fts5Tokenizer **ppTok,
  191567. fts5_tokenizer **ppTokApi,
  191568. char **pzErr
  191569. ){
  191570. Fts5TokenizerModule *pMod;
  191571. int rc = SQLITE_OK;
  191572. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  191573. if( pMod==0 ){
  191574. assert( nArg>0 );
  191575. rc = SQLITE_ERROR;
  191576. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  191577. }else{
  191578. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  191579. *ppTokApi = &pMod->x;
  191580. if( rc!=SQLITE_OK && pzErr ){
  191581. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  191582. }
  191583. }
  191584. if( rc!=SQLITE_OK ){
  191585. *ppTokApi = 0;
  191586. *ppTok = 0;
  191587. }
  191588. return rc;
  191589. }
  191590. static void fts5ModuleDestroy(void *pCtx){
  191591. Fts5TokenizerModule *pTok, *pNextTok;
  191592. Fts5Auxiliary *pAux, *pNextAux;
  191593. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  191594. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  191595. pNextAux = pAux->pNext;
  191596. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  191597. sqlite3_free(pAux);
  191598. }
  191599. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  191600. pNextTok = pTok->pNext;
  191601. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  191602. sqlite3_free(pTok);
  191603. }
  191604. sqlite3_free(pGlobal);
  191605. }
  191606. static void fts5Fts5Func(
  191607. sqlite3_context *pCtx, /* Function call context */
  191608. int nArg, /* Number of args */
  191609. sqlite3_value **apArg /* Function arguments */
  191610. ){
  191611. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  191612. fts5_api **ppApi;
  191613. UNUSED_PARAM(nArg);
  191614. assert( nArg==1 );
  191615. ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
  191616. if( ppApi ) *ppApi = &pGlobal->api;
  191617. }
  191618. /*
  191619. ** Implementation of fts5_source_id() function.
  191620. */
  191621. static void fts5SourceIdFunc(
  191622. sqlite3_context *pCtx, /* Function call context */
  191623. int nArg, /* Number of args */
  191624. sqlite3_value **apUnused /* Function arguments */
  191625. ){
  191626. assert( nArg==0 );
  191627. UNUSED_PARAM2(nArg, apUnused);
  191628. sqlite3_result_text(pCtx, "fts5: 2018-04-10 17:39:29 4bb2294022060e61de7da5c227a69ccd846ba330e31626ebcd59a94efd148b3b", -1, SQLITE_TRANSIENT);
  191629. }
  191630. static int fts5Init(sqlite3 *db){
  191631. static const sqlite3_module fts5Mod = {
  191632. /* iVersion */ 2,
  191633. /* xCreate */ fts5CreateMethod,
  191634. /* xConnect */ fts5ConnectMethod,
  191635. /* xBestIndex */ fts5BestIndexMethod,
  191636. /* xDisconnect */ fts5DisconnectMethod,
  191637. /* xDestroy */ fts5DestroyMethod,
  191638. /* xOpen */ fts5OpenMethod,
  191639. /* xClose */ fts5CloseMethod,
  191640. /* xFilter */ fts5FilterMethod,
  191641. /* xNext */ fts5NextMethod,
  191642. /* xEof */ fts5EofMethod,
  191643. /* xColumn */ fts5ColumnMethod,
  191644. /* xRowid */ fts5RowidMethod,
  191645. /* xUpdate */ fts5UpdateMethod,
  191646. /* xBegin */ fts5BeginMethod,
  191647. /* xSync */ fts5SyncMethod,
  191648. /* xCommit */ fts5CommitMethod,
  191649. /* xRollback */ fts5RollbackMethod,
  191650. /* xFindFunction */ fts5FindFunctionMethod,
  191651. /* xRename */ fts5RenameMethod,
  191652. /* xSavepoint */ fts5SavepointMethod,
  191653. /* xRelease */ fts5ReleaseMethod,
  191654. /* xRollbackTo */ fts5RollbackToMethod,
  191655. };
  191656. int rc;
  191657. Fts5Global *pGlobal = 0;
  191658. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  191659. if( pGlobal==0 ){
  191660. rc = SQLITE_NOMEM;
  191661. }else{
  191662. void *p = (void*)pGlobal;
  191663. memset(pGlobal, 0, sizeof(Fts5Global));
  191664. pGlobal->db = db;
  191665. pGlobal->api.iVersion = 2;
  191666. pGlobal->api.xCreateFunction = fts5CreateAux;
  191667. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  191668. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  191669. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  191670. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  191671. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  191672. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  191673. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  191674. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  191675. if( rc==SQLITE_OK ){
  191676. rc = sqlite3_create_function(
  191677. db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  191678. );
  191679. }
  191680. if( rc==SQLITE_OK ){
  191681. rc = sqlite3_create_function(
  191682. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  191683. );
  191684. }
  191685. }
  191686. /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
  191687. ** fts5_test_mi.c is compiled and linked into the executable. And call
  191688. ** its entry point to enable the matchinfo() demo. */
  191689. #ifdef SQLITE_FTS5_ENABLE_TEST_MI
  191690. if( rc==SQLITE_OK ){
  191691. extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
  191692. rc = sqlite3Fts5TestRegisterMatchinfo(db);
  191693. }
  191694. #endif
  191695. return rc;
  191696. }
  191697. /*
  191698. ** The following functions are used to register the module with SQLite. If
  191699. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  191700. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  191701. **
  191702. ** Or, if this module is being built as a loadable extension,
  191703. ** sqlite3Fts5Init() is omitted and the two standard entry points
  191704. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  191705. */
  191706. #ifndef SQLITE_CORE
  191707. #ifdef _WIN32
  191708. __declspec(dllexport)
  191709. #endif
  191710. SQLITE_API int sqlite3_fts_init(
  191711. sqlite3 *db,
  191712. char **pzErrMsg,
  191713. const sqlite3_api_routines *pApi
  191714. ){
  191715. SQLITE_EXTENSION_INIT2(pApi);
  191716. (void)pzErrMsg; /* Unused parameter */
  191717. return fts5Init(db);
  191718. }
  191719. #ifdef _WIN32
  191720. __declspec(dllexport)
  191721. #endif
  191722. SQLITE_API int sqlite3_fts5_init(
  191723. sqlite3 *db,
  191724. char **pzErrMsg,
  191725. const sqlite3_api_routines *pApi
  191726. ){
  191727. SQLITE_EXTENSION_INIT2(pApi);
  191728. (void)pzErrMsg; /* Unused parameter */
  191729. return fts5Init(db);
  191730. }
  191731. #else
  191732. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  191733. return fts5Init(db);
  191734. }
  191735. #endif
  191736. /*
  191737. ** 2014 May 31
  191738. **
  191739. ** The author disclaims copyright to this source code. In place of
  191740. ** a legal notice, here is a blessing:
  191741. **
  191742. ** May you do good and not evil.
  191743. ** May you find forgiveness for yourself and forgive others.
  191744. ** May you share freely, never taking more than you give.
  191745. **
  191746. ******************************************************************************
  191747. **
  191748. */
  191749. /* #include "fts5Int.h" */
  191750. struct Fts5Storage {
  191751. Fts5Config *pConfig;
  191752. Fts5Index *pIndex;
  191753. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  191754. i64 nTotalRow; /* Total number of rows in FTS table */
  191755. i64 *aTotalSize; /* Total sizes of each column */
  191756. sqlite3_stmt *aStmt[11];
  191757. };
  191758. #if FTS5_STMT_SCAN_ASC!=0
  191759. # error "FTS5_STMT_SCAN_ASC mismatch"
  191760. #endif
  191761. #if FTS5_STMT_SCAN_DESC!=1
  191762. # error "FTS5_STMT_SCAN_DESC mismatch"
  191763. #endif
  191764. #if FTS5_STMT_LOOKUP!=2
  191765. # error "FTS5_STMT_LOOKUP mismatch"
  191766. #endif
  191767. #define FTS5_STMT_INSERT_CONTENT 3
  191768. #define FTS5_STMT_REPLACE_CONTENT 4
  191769. #define FTS5_STMT_DELETE_CONTENT 5
  191770. #define FTS5_STMT_REPLACE_DOCSIZE 6
  191771. #define FTS5_STMT_DELETE_DOCSIZE 7
  191772. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  191773. #define FTS5_STMT_REPLACE_CONFIG 9
  191774. #define FTS5_STMT_SCAN 10
  191775. /*
  191776. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  191777. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  191778. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  191779. ** occurs.
  191780. */
  191781. static int fts5StorageGetStmt(
  191782. Fts5Storage *p, /* Storage handle */
  191783. int eStmt, /* FTS5_STMT_XXX constant */
  191784. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  191785. char **pzErrMsg /* OUT: Error message (if any) */
  191786. ){
  191787. int rc = SQLITE_OK;
  191788. /* If there is no %_docsize table, there should be no requests for
  191789. ** statements to operate on it. */
  191790. assert( p->pConfig->bColumnsize || (
  191791. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  191792. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  191793. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  191794. ));
  191795. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  191796. if( p->aStmt[eStmt]==0 ){
  191797. const char *azStmt[] = {
  191798. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  191799. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  191800. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  191801. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  191802. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  191803. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  191804. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  191805. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  191806. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  191807. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  191808. "SELECT %s FROM %s AS T", /* SCAN */
  191809. };
  191810. Fts5Config *pC = p->pConfig;
  191811. char *zSql = 0;
  191812. switch( eStmt ){
  191813. case FTS5_STMT_SCAN:
  191814. zSql = sqlite3_mprintf(azStmt[eStmt],
  191815. pC->zContentExprlist, pC->zContent
  191816. );
  191817. break;
  191818. case FTS5_STMT_SCAN_ASC:
  191819. case FTS5_STMT_SCAN_DESC:
  191820. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  191821. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  191822. pC->zContentRowid
  191823. );
  191824. break;
  191825. case FTS5_STMT_LOOKUP:
  191826. zSql = sqlite3_mprintf(azStmt[eStmt],
  191827. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  191828. );
  191829. break;
  191830. case FTS5_STMT_INSERT_CONTENT:
  191831. case FTS5_STMT_REPLACE_CONTENT: {
  191832. int nCol = pC->nCol + 1;
  191833. char *zBind;
  191834. int i;
  191835. zBind = sqlite3_malloc(1 + nCol*2);
  191836. if( zBind ){
  191837. for(i=0; i<nCol; i++){
  191838. zBind[i*2] = '?';
  191839. zBind[i*2 + 1] = ',';
  191840. }
  191841. zBind[i*2-1] = '\0';
  191842. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  191843. sqlite3_free(zBind);
  191844. }
  191845. break;
  191846. }
  191847. default:
  191848. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  191849. break;
  191850. }
  191851. if( zSql==0 ){
  191852. rc = SQLITE_NOMEM;
  191853. }else{
  191854. rc = sqlite3_prepare_v3(pC->db, zSql, -1,
  191855. SQLITE_PREPARE_PERSISTENT, &p->aStmt[eStmt], 0);
  191856. sqlite3_free(zSql);
  191857. if( rc!=SQLITE_OK && pzErrMsg ){
  191858. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  191859. }
  191860. }
  191861. }
  191862. *ppStmt = p->aStmt[eStmt];
  191863. sqlite3_reset(*ppStmt);
  191864. return rc;
  191865. }
  191866. static int fts5ExecPrintf(
  191867. sqlite3 *db,
  191868. char **pzErr,
  191869. const char *zFormat,
  191870. ...
  191871. ){
  191872. int rc;
  191873. va_list ap; /* ... printf arguments */
  191874. char *zSql;
  191875. va_start(ap, zFormat);
  191876. zSql = sqlite3_vmprintf(zFormat, ap);
  191877. if( zSql==0 ){
  191878. rc = SQLITE_NOMEM;
  191879. }else{
  191880. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  191881. sqlite3_free(zSql);
  191882. }
  191883. va_end(ap);
  191884. return rc;
  191885. }
  191886. /*
  191887. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  191888. ** code otherwise.
  191889. */
  191890. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  191891. int rc = fts5ExecPrintf(pConfig->db, 0,
  191892. "DROP TABLE IF EXISTS %Q.'%q_data';"
  191893. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  191894. "DROP TABLE IF EXISTS %Q.'%q_config';",
  191895. pConfig->zDb, pConfig->zName,
  191896. pConfig->zDb, pConfig->zName,
  191897. pConfig->zDb, pConfig->zName
  191898. );
  191899. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  191900. rc = fts5ExecPrintf(pConfig->db, 0,
  191901. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  191902. pConfig->zDb, pConfig->zName
  191903. );
  191904. }
  191905. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  191906. rc = fts5ExecPrintf(pConfig->db, 0,
  191907. "DROP TABLE IF EXISTS %Q.'%q_content';",
  191908. pConfig->zDb, pConfig->zName
  191909. );
  191910. }
  191911. return rc;
  191912. }
  191913. static void fts5StorageRenameOne(
  191914. Fts5Config *pConfig, /* Current FTS5 configuration */
  191915. int *pRc, /* IN/OUT: Error code */
  191916. const char *zTail, /* Tail of table name e.g. "data", "config" */
  191917. const char *zName /* New name of FTS5 table */
  191918. ){
  191919. if( *pRc==SQLITE_OK ){
  191920. *pRc = fts5ExecPrintf(pConfig->db, 0,
  191921. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  191922. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  191923. );
  191924. }
  191925. }
  191926. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  191927. Fts5Config *pConfig = pStorage->pConfig;
  191928. int rc = sqlite3Fts5StorageSync(pStorage);
  191929. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  191930. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  191931. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  191932. if( pConfig->bColumnsize ){
  191933. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  191934. }
  191935. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  191936. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  191937. }
  191938. return rc;
  191939. }
  191940. /*
  191941. ** Create the shadow table named zPost, with definition zDefn. Return
  191942. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  191943. */
  191944. static int sqlite3Fts5CreateTable(
  191945. Fts5Config *pConfig, /* FTS5 configuration */
  191946. const char *zPost, /* Shadow table to create (e.g. "content") */
  191947. const char *zDefn, /* Columns etc. for shadow table */
  191948. int bWithout, /* True for without rowid */
  191949. char **pzErr /* OUT: Error message */
  191950. ){
  191951. int rc;
  191952. char *zErr = 0;
  191953. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  191954. pConfig->zDb, pConfig->zName, zPost, zDefn,
  191955. #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
  191956. bWithout?" WITHOUT ROWID":
  191957. #endif
  191958. ""
  191959. );
  191960. if( zErr ){
  191961. *pzErr = sqlite3_mprintf(
  191962. "fts5: error creating shadow table %q_%s: %s",
  191963. pConfig->zName, zPost, zErr
  191964. );
  191965. sqlite3_free(zErr);
  191966. }
  191967. return rc;
  191968. }
  191969. /*
  191970. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  191971. ** and initialize the underlying tables
  191972. **
  191973. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  191974. ** Otherwise, set *pp to NULL and return an SQLite error code.
  191975. */
  191976. static int sqlite3Fts5StorageOpen(
  191977. Fts5Config *pConfig,
  191978. Fts5Index *pIndex,
  191979. int bCreate,
  191980. Fts5Storage **pp,
  191981. char **pzErr /* OUT: Error message */
  191982. ){
  191983. int rc = SQLITE_OK;
  191984. Fts5Storage *p; /* New object */
  191985. int nByte; /* Bytes of space to allocate */
  191986. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  191987. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  191988. *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
  191989. if( !p ) return SQLITE_NOMEM;
  191990. memset(p, 0, nByte);
  191991. p->aTotalSize = (i64*)&p[1];
  191992. p->pConfig = pConfig;
  191993. p->pIndex = pIndex;
  191994. if( bCreate ){
  191995. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  191996. int nDefn = 32 + pConfig->nCol*10;
  191997. char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
  191998. if( zDefn==0 ){
  191999. rc = SQLITE_NOMEM;
  192000. }else{
  192001. int i;
  192002. int iOff;
  192003. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  192004. iOff = (int)strlen(zDefn);
  192005. for(i=0; i<pConfig->nCol; i++){
  192006. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  192007. iOff += (int)strlen(&zDefn[iOff]);
  192008. }
  192009. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  192010. }
  192011. sqlite3_free(zDefn);
  192012. }
  192013. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  192014. rc = sqlite3Fts5CreateTable(
  192015. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  192016. );
  192017. }
  192018. if( rc==SQLITE_OK ){
  192019. rc = sqlite3Fts5CreateTable(
  192020. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  192021. );
  192022. }
  192023. if( rc==SQLITE_OK ){
  192024. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  192025. }
  192026. }
  192027. if( rc ){
  192028. sqlite3Fts5StorageClose(p);
  192029. *pp = 0;
  192030. }
  192031. return rc;
  192032. }
  192033. /*
  192034. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  192035. */
  192036. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  192037. int rc = SQLITE_OK;
  192038. if( p ){
  192039. int i;
  192040. /* Finalize all SQL statements */
  192041. for(i=0; i<ArraySize(p->aStmt); i++){
  192042. sqlite3_finalize(p->aStmt[i]);
  192043. }
  192044. sqlite3_free(p);
  192045. }
  192046. return rc;
  192047. }
  192048. typedef struct Fts5InsertCtx Fts5InsertCtx;
  192049. struct Fts5InsertCtx {
  192050. Fts5Storage *pStorage;
  192051. int iCol;
  192052. int szCol; /* Size of column value in tokens */
  192053. };
  192054. /*
  192055. ** Tokenization callback used when inserting tokens into the FTS index.
  192056. */
  192057. static int fts5StorageInsertCallback(
  192058. void *pContext, /* Pointer to Fts5InsertCtx object */
  192059. int tflags,
  192060. const char *pToken, /* Buffer containing token */
  192061. int nToken, /* Size of token in bytes */
  192062. int iUnused1, /* Start offset of token */
  192063. int iUnused2 /* End offset of token */
  192064. ){
  192065. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  192066. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  192067. UNUSED_PARAM2(iUnused1, iUnused2);
  192068. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  192069. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  192070. pCtx->szCol++;
  192071. }
  192072. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  192073. }
  192074. /*
  192075. ** If a row with rowid iDel is present in the %_content table, add the
  192076. ** delete-markers to the FTS index necessary to delete it. Do not actually
  192077. ** remove the %_content row at this time though.
  192078. */
  192079. static int fts5StorageDeleteFromIndex(
  192080. Fts5Storage *p,
  192081. i64 iDel,
  192082. sqlite3_value **apVal
  192083. ){
  192084. Fts5Config *pConfig = p->pConfig;
  192085. sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
  192086. int rc; /* Return code */
  192087. int rc2; /* sqlite3_reset() return code */
  192088. int iCol;
  192089. Fts5InsertCtx ctx;
  192090. if( apVal==0 ){
  192091. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  192092. if( rc!=SQLITE_OK ) return rc;
  192093. sqlite3_bind_int64(pSeek, 1, iDel);
  192094. if( sqlite3_step(pSeek)!=SQLITE_ROW ){
  192095. return sqlite3_reset(pSeek);
  192096. }
  192097. }
  192098. ctx.pStorage = p;
  192099. ctx.iCol = -1;
  192100. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  192101. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  192102. if( pConfig->abUnindexed[iCol-1]==0 ){
  192103. const char *zText;
  192104. int nText;
  192105. if( pSeek ){
  192106. zText = (const char*)sqlite3_column_text(pSeek, iCol);
  192107. nText = sqlite3_column_bytes(pSeek, iCol);
  192108. }else{
  192109. zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
  192110. nText = sqlite3_value_bytes(apVal[iCol-1]);
  192111. }
  192112. ctx.szCol = 0;
  192113. rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
  192114. zText, nText, (void*)&ctx, fts5StorageInsertCallback
  192115. );
  192116. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  192117. }
  192118. }
  192119. p->nTotalRow--;
  192120. rc2 = sqlite3_reset(pSeek);
  192121. if( rc==SQLITE_OK ) rc = rc2;
  192122. return rc;
  192123. }
  192124. /*
  192125. ** Insert a record into the %_docsize table. Specifically, do:
  192126. **
  192127. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  192128. **
  192129. ** If there is no %_docsize table (as happens if the columnsize=0 option
  192130. ** is specified when the FTS5 table is created), this function is a no-op.
  192131. */
  192132. static int fts5StorageInsertDocsize(
  192133. Fts5Storage *p, /* Storage module to write to */
  192134. i64 iRowid, /* id value */
  192135. Fts5Buffer *pBuf /* sz value */
  192136. ){
  192137. int rc = SQLITE_OK;
  192138. if( p->pConfig->bColumnsize ){
  192139. sqlite3_stmt *pReplace = 0;
  192140. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  192141. if( rc==SQLITE_OK ){
  192142. sqlite3_bind_int64(pReplace, 1, iRowid);
  192143. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  192144. sqlite3_step(pReplace);
  192145. rc = sqlite3_reset(pReplace);
  192146. sqlite3_bind_null(pReplace, 2);
  192147. }
  192148. }
  192149. return rc;
  192150. }
  192151. /*
  192152. ** Load the contents of the "averages" record from disk into the
  192153. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  192154. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  192155. ** that the contents of aTotalSize[] and nTotalRow are valid until
  192156. ** further notice.
  192157. **
  192158. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  192159. ** occurs.
  192160. */
  192161. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  192162. int rc = SQLITE_OK;
  192163. if( p->bTotalsValid==0 ){
  192164. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  192165. p->bTotalsValid = bCache;
  192166. }
  192167. return rc;
  192168. }
  192169. /*
  192170. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  192171. ** variables in the "averages" record on disk.
  192172. **
  192173. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  192174. ** occurs.
  192175. */
  192176. static int fts5StorageSaveTotals(Fts5Storage *p){
  192177. int nCol = p->pConfig->nCol;
  192178. int i;
  192179. Fts5Buffer buf;
  192180. int rc = SQLITE_OK;
  192181. memset(&buf, 0, sizeof(buf));
  192182. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  192183. for(i=0; i<nCol; i++){
  192184. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  192185. }
  192186. if( rc==SQLITE_OK ){
  192187. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  192188. }
  192189. sqlite3_free(buf.p);
  192190. return rc;
  192191. }
  192192. /*
  192193. ** Remove a row from the FTS table.
  192194. */
  192195. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
  192196. Fts5Config *pConfig = p->pConfig;
  192197. int rc;
  192198. sqlite3_stmt *pDel = 0;
  192199. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
  192200. rc = fts5StorageLoadTotals(p, 1);
  192201. /* Delete the index records */
  192202. if( rc==SQLITE_OK ){
  192203. rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
  192204. }
  192205. /* Delete the %_docsize record */
  192206. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  192207. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  192208. if( rc==SQLITE_OK ){
  192209. sqlite3_bind_int64(pDel, 1, iDel);
  192210. sqlite3_step(pDel);
  192211. rc = sqlite3_reset(pDel);
  192212. }
  192213. }
  192214. /* Delete the %_content record */
  192215. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  192216. if( rc==SQLITE_OK ){
  192217. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  192218. }
  192219. if( rc==SQLITE_OK ){
  192220. sqlite3_bind_int64(pDel, 1, iDel);
  192221. sqlite3_step(pDel);
  192222. rc = sqlite3_reset(pDel);
  192223. }
  192224. }
  192225. return rc;
  192226. }
  192227. /*
  192228. ** Delete all entries in the FTS5 index.
  192229. */
  192230. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  192231. Fts5Config *pConfig = p->pConfig;
  192232. int rc;
  192233. /* Delete the contents of the %_data and %_docsize tables. */
  192234. rc = fts5ExecPrintf(pConfig->db, 0,
  192235. "DELETE FROM %Q.'%q_data';"
  192236. "DELETE FROM %Q.'%q_idx';",
  192237. pConfig->zDb, pConfig->zName,
  192238. pConfig->zDb, pConfig->zName
  192239. );
  192240. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  192241. rc = fts5ExecPrintf(pConfig->db, 0,
  192242. "DELETE FROM %Q.'%q_docsize';",
  192243. pConfig->zDb, pConfig->zName
  192244. );
  192245. }
  192246. /* Reinitialize the %_data table. This call creates the initial structure
  192247. ** and averages records. */
  192248. if( rc==SQLITE_OK ){
  192249. rc = sqlite3Fts5IndexReinit(p->pIndex);
  192250. }
  192251. if( rc==SQLITE_OK ){
  192252. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  192253. }
  192254. return rc;
  192255. }
  192256. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  192257. Fts5Buffer buf = {0,0,0};
  192258. Fts5Config *pConfig = p->pConfig;
  192259. sqlite3_stmt *pScan = 0;
  192260. Fts5InsertCtx ctx;
  192261. int rc;
  192262. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  192263. ctx.pStorage = p;
  192264. rc = sqlite3Fts5StorageDeleteAll(p);
  192265. if( rc==SQLITE_OK ){
  192266. rc = fts5StorageLoadTotals(p, 1);
  192267. }
  192268. if( rc==SQLITE_OK ){
  192269. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  192270. }
  192271. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  192272. i64 iRowid = sqlite3_column_int64(pScan, 0);
  192273. sqlite3Fts5BufferZero(&buf);
  192274. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  192275. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  192276. ctx.szCol = 0;
  192277. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  192278. rc = sqlite3Fts5Tokenize(pConfig,
  192279. FTS5_TOKENIZE_DOCUMENT,
  192280. (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
  192281. sqlite3_column_bytes(pScan, ctx.iCol+1),
  192282. (void*)&ctx,
  192283. fts5StorageInsertCallback
  192284. );
  192285. }
  192286. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  192287. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  192288. }
  192289. p->nTotalRow++;
  192290. if( rc==SQLITE_OK ){
  192291. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  192292. }
  192293. }
  192294. sqlite3_free(buf.p);
  192295. /* Write the averages record */
  192296. if( rc==SQLITE_OK ){
  192297. rc = fts5StorageSaveTotals(p);
  192298. }
  192299. return rc;
  192300. }
  192301. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  192302. return sqlite3Fts5IndexOptimize(p->pIndex);
  192303. }
  192304. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  192305. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  192306. }
  192307. static int sqlite3Fts5StorageReset(Fts5Storage *p){
  192308. return sqlite3Fts5IndexReset(p->pIndex);
  192309. }
  192310. /*
  192311. ** Allocate a new rowid. This is used for "external content" tables when
  192312. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  192313. ** by inserting a dummy row into the %_docsize table. The dummy will be
  192314. ** overwritten later.
  192315. **
  192316. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  192317. ** this case the user is required to provide a rowid explicitly.
  192318. */
  192319. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  192320. int rc = SQLITE_MISMATCH;
  192321. if( p->pConfig->bColumnsize ){
  192322. sqlite3_stmt *pReplace = 0;
  192323. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  192324. if( rc==SQLITE_OK ){
  192325. sqlite3_bind_null(pReplace, 1);
  192326. sqlite3_bind_null(pReplace, 2);
  192327. sqlite3_step(pReplace);
  192328. rc = sqlite3_reset(pReplace);
  192329. }
  192330. if( rc==SQLITE_OK ){
  192331. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  192332. }
  192333. }
  192334. return rc;
  192335. }
  192336. /*
  192337. ** Insert a new row into the FTS content table.
  192338. */
  192339. static int sqlite3Fts5StorageContentInsert(
  192340. Fts5Storage *p,
  192341. sqlite3_value **apVal,
  192342. i64 *piRowid
  192343. ){
  192344. Fts5Config *pConfig = p->pConfig;
  192345. int rc = SQLITE_OK;
  192346. /* Insert the new row into the %_content table. */
  192347. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  192348. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  192349. *piRowid = sqlite3_value_int64(apVal[1]);
  192350. }else{
  192351. rc = fts5StorageNewRowid(p, piRowid);
  192352. }
  192353. }else{
  192354. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  192355. int i; /* Counter variable */
  192356. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  192357. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  192358. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  192359. }
  192360. if( rc==SQLITE_OK ){
  192361. sqlite3_step(pInsert);
  192362. rc = sqlite3_reset(pInsert);
  192363. }
  192364. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  192365. }
  192366. return rc;
  192367. }
  192368. /*
  192369. ** Insert new entries into the FTS index and %_docsize table.
  192370. */
  192371. static int sqlite3Fts5StorageIndexInsert(
  192372. Fts5Storage *p,
  192373. sqlite3_value **apVal,
  192374. i64 iRowid
  192375. ){
  192376. Fts5Config *pConfig = p->pConfig;
  192377. int rc = SQLITE_OK; /* Return code */
  192378. Fts5InsertCtx ctx; /* Tokenization callback context object */
  192379. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  192380. memset(&buf, 0, sizeof(Fts5Buffer));
  192381. ctx.pStorage = p;
  192382. rc = fts5StorageLoadTotals(p, 1);
  192383. if( rc==SQLITE_OK ){
  192384. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  192385. }
  192386. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  192387. ctx.szCol = 0;
  192388. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  192389. rc = sqlite3Fts5Tokenize(pConfig,
  192390. FTS5_TOKENIZE_DOCUMENT,
  192391. (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
  192392. sqlite3_value_bytes(apVal[ctx.iCol+2]),
  192393. (void*)&ctx,
  192394. fts5StorageInsertCallback
  192395. );
  192396. }
  192397. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  192398. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  192399. }
  192400. p->nTotalRow++;
  192401. /* Write the %_docsize record */
  192402. if( rc==SQLITE_OK ){
  192403. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  192404. }
  192405. sqlite3_free(buf.p);
  192406. return rc;
  192407. }
  192408. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  192409. Fts5Config *pConfig = p->pConfig;
  192410. char *zSql;
  192411. int rc;
  192412. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  192413. pConfig->zDb, pConfig->zName, zSuffix
  192414. );
  192415. if( zSql==0 ){
  192416. rc = SQLITE_NOMEM;
  192417. }else{
  192418. sqlite3_stmt *pCnt = 0;
  192419. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  192420. if( rc==SQLITE_OK ){
  192421. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  192422. *pnRow = sqlite3_column_int64(pCnt, 0);
  192423. }
  192424. rc = sqlite3_finalize(pCnt);
  192425. }
  192426. }
  192427. sqlite3_free(zSql);
  192428. return rc;
  192429. }
  192430. /*
  192431. ** Context object used by sqlite3Fts5StorageIntegrity().
  192432. */
  192433. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  192434. struct Fts5IntegrityCtx {
  192435. i64 iRowid;
  192436. int iCol;
  192437. int szCol;
  192438. u64 cksum;
  192439. Fts5Termset *pTermset;
  192440. Fts5Config *pConfig;
  192441. };
  192442. /*
  192443. ** Tokenization callback used by integrity check.
  192444. */
  192445. static int fts5StorageIntegrityCallback(
  192446. void *pContext, /* Pointer to Fts5IntegrityCtx object */
  192447. int tflags,
  192448. const char *pToken, /* Buffer containing token */
  192449. int nToken, /* Size of token in bytes */
  192450. int iUnused1, /* Start offset of token */
  192451. int iUnused2 /* End offset of token */
  192452. ){
  192453. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  192454. Fts5Termset *pTermset = pCtx->pTermset;
  192455. int bPresent;
  192456. int ii;
  192457. int rc = SQLITE_OK;
  192458. int iPos;
  192459. int iCol;
  192460. UNUSED_PARAM2(iUnused1, iUnused2);
  192461. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  192462. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  192463. pCtx->szCol++;
  192464. }
  192465. switch( pCtx->pConfig->eDetail ){
  192466. case FTS5_DETAIL_FULL:
  192467. iPos = pCtx->szCol-1;
  192468. iCol = pCtx->iCol;
  192469. break;
  192470. case FTS5_DETAIL_COLUMNS:
  192471. iPos = pCtx->iCol;
  192472. iCol = 0;
  192473. break;
  192474. default:
  192475. assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
  192476. iPos = 0;
  192477. iCol = 0;
  192478. break;
  192479. }
  192480. rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
  192481. if( rc==SQLITE_OK && bPresent==0 ){
  192482. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  192483. pCtx->iRowid, iCol, iPos, 0, pToken, nToken
  192484. );
  192485. }
  192486. for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
  192487. const int nChar = pCtx->pConfig->aPrefix[ii];
  192488. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  192489. if( nByte ){
  192490. rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
  192491. if( bPresent==0 ){
  192492. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  192493. pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
  192494. );
  192495. }
  192496. }
  192497. }
  192498. return rc;
  192499. }
  192500. /*
  192501. ** Check that the contents of the FTS index match that of the %_content
  192502. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  192503. ** some other SQLite error code if an error occurs while attempting to
  192504. ** determine this.
  192505. */
  192506. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  192507. Fts5Config *pConfig = p->pConfig;
  192508. int rc; /* Return code */
  192509. int *aColSize; /* Array of size pConfig->nCol */
  192510. i64 *aTotalSize; /* Array of size pConfig->nCol */
  192511. Fts5IntegrityCtx ctx;
  192512. sqlite3_stmt *pScan;
  192513. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  192514. ctx.pConfig = p->pConfig;
  192515. aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
  192516. if( !aTotalSize ) return SQLITE_NOMEM;
  192517. aColSize = (int*)&aTotalSize[pConfig->nCol];
  192518. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  192519. /* Generate the expected index checksum based on the contents of the
  192520. ** %_content table. This block stores the checksum in ctx.cksum. */
  192521. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  192522. if( rc==SQLITE_OK ){
  192523. int rc2;
  192524. while( SQLITE_ROW==sqlite3_step(pScan) ){
  192525. int i;
  192526. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  192527. ctx.szCol = 0;
  192528. if( pConfig->bColumnsize ){
  192529. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  192530. }
  192531. if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
  192532. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  192533. }
  192534. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  192535. if( pConfig->abUnindexed[i] ) continue;
  192536. ctx.iCol = i;
  192537. ctx.szCol = 0;
  192538. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  192539. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  192540. }
  192541. if( rc==SQLITE_OK ){
  192542. rc = sqlite3Fts5Tokenize(pConfig,
  192543. FTS5_TOKENIZE_DOCUMENT,
  192544. (const char*)sqlite3_column_text(pScan, i+1),
  192545. sqlite3_column_bytes(pScan, i+1),
  192546. (void*)&ctx,
  192547. fts5StorageIntegrityCallback
  192548. );
  192549. }
  192550. if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  192551. rc = FTS5_CORRUPT;
  192552. }
  192553. aTotalSize[i] += ctx.szCol;
  192554. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  192555. sqlite3Fts5TermsetFree(ctx.pTermset);
  192556. ctx.pTermset = 0;
  192557. }
  192558. }
  192559. sqlite3Fts5TermsetFree(ctx.pTermset);
  192560. ctx.pTermset = 0;
  192561. if( rc!=SQLITE_OK ) break;
  192562. }
  192563. rc2 = sqlite3_reset(pScan);
  192564. if( rc==SQLITE_OK ) rc = rc2;
  192565. }
  192566. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  192567. if( rc==SQLITE_OK ){
  192568. int i;
  192569. rc = fts5StorageLoadTotals(p, 0);
  192570. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  192571. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  192572. }
  192573. }
  192574. /* Check that the %_docsize and %_content tables contain the expected
  192575. ** number of rows. */
  192576. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  192577. i64 nRow = 0;
  192578. rc = fts5StorageCount(p, "content", &nRow);
  192579. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  192580. }
  192581. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  192582. i64 nRow = 0;
  192583. rc = fts5StorageCount(p, "docsize", &nRow);
  192584. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  192585. }
  192586. /* Pass the expected checksum down to the FTS index module. It will
  192587. ** verify, amongst other things, that it matches the checksum generated by
  192588. ** inspecting the index itself. */
  192589. if( rc==SQLITE_OK ){
  192590. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  192591. }
  192592. sqlite3_free(aTotalSize);
  192593. return rc;
  192594. }
  192595. /*
  192596. ** Obtain an SQLite statement handle that may be used to read data from the
  192597. ** %_content table.
  192598. */
  192599. static int sqlite3Fts5StorageStmt(
  192600. Fts5Storage *p,
  192601. int eStmt,
  192602. sqlite3_stmt **pp,
  192603. char **pzErrMsg
  192604. ){
  192605. int rc;
  192606. assert( eStmt==FTS5_STMT_SCAN_ASC
  192607. || eStmt==FTS5_STMT_SCAN_DESC
  192608. || eStmt==FTS5_STMT_LOOKUP
  192609. );
  192610. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  192611. if( rc==SQLITE_OK ){
  192612. assert( p->aStmt[eStmt]==*pp );
  192613. p->aStmt[eStmt] = 0;
  192614. }
  192615. return rc;
  192616. }
  192617. /*
  192618. ** Release an SQLite statement handle obtained via an earlier call to
  192619. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  192620. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  192621. */
  192622. static void sqlite3Fts5StorageStmtRelease(
  192623. Fts5Storage *p,
  192624. int eStmt,
  192625. sqlite3_stmt *pStmt
  192626. ){
  192627. assert( eStmt==FTS5_STMT_SCAN_ASC
  192628. || eStmt==FTS5_STMT_SCAN_DESC
  192629. || eStmt==FTS5_STMT_LOOKUP
  192630. );
  192631. if( p->aStmt[eStmt]==0 ){
  192632. sqlite3_reset(pStmt);
  192633. p->aStmt[eStmt] = pStmt;
  192634. }else{
  192635. sqlite3_finalize(pStmt);
  192636. }
  192637. }
  192638. static int fts5StorageDecodeSizeArray(
  192639. int *aCol, int nCol, /* Array to populate */
  192640. const u8 *aBlob, int nBlob /* Record to read varints from */
  192641. ){
  192642. int i;
  192643. int iOff = 0;
  192644. for(i=0; i<nCol; i++){
  192645. if( iOff>=nBlob ) return 1;
  192646. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  192647. }
  192648. return (iOff!=nBlob);
  192649. }
  192650. /*
  192651. ** Argument aCol points to an array of integers containing one entry for
  192652. ** each table column. This function reads the %_docsize record for the
  192653. ** specified rowid and populates aCol[] with the results.
  192654. **
  192655. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  192656. ** otherwise.
  192657. */
  192658. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  192659. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  192660. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  192661. int rc; /* Return Code */
  192662. assert( p->pConfig->bColumnsize );
  192663. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  192664. if( rc==SQLITE_OK ){
  192665. int bCorrupt = 1;
  192666. sqlite3_bind_int64(pLookup, 1, iRowid);
  192667. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  192668. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  192669. int nBlob = sqlite3_column_bytes(pLookup, 0);
  192670. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  192671. bCorrupt = 0;
  192672. }
  192673. }
  192674. rc = sqlite3_reset(pLookup);
  192675. if( bCorrupt && rc==SQLITE_OK ){
  192676. rc = FTS5_CORRUPT;
  192677. }
  192678. }
  192679. return rc;
  192680. }
  192681. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  192682. int rc = fts5StorageLoadTotals(p, 0);
  192683. if( rc==SQLITE_OK ){
  192684. *pnToken = 0;
  192685. if( iCol<0 ){
  192686. int i;
  192687. for(i=0; i<p->pConfig->nCol; i++){
  192688. *pnToken += p->aTotalSize[i];
  192689. }
  192690. }else if( iCol<p->pConfig->nCol ){
  192691. *pnToken = p->aTotalSize[iCol];
  192692. }else{
  192693. rc = SQLITE_RANGE;
  192694. }
  192695. }
  192696. return rc;
  192697. }
  192698. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  192699. int rc = fts5StorageLoadTotals(p, 0);
  192700. if( rc==SQLITE_OK ){
  192701. *pnRow = p->nTotalRow;
  192702. }
  192703. return rc;
  192704. }
  192705. /*
  192706. ** Flush any data currently held in-memory to disk.
  192707. */
  192708. static int sqlite3Fts5StorageSync(Fts5Storage *p){
  192709. int rc = SQLITE_OK;
  192710. i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  192711. if( p->bTotalsValid ){
  192712. rc = fts5StorageSaveTotals(p);
  192713. p->bTotalsValid = 0;
  192714. }
  192715. if( rc==SQLITE_OK ){
  192716. rc = sqlite3Fts5IndexSync(p->pIndex);
  192717. }
  192718. sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
  192719. return rc;
  192720. }
  192721. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  192722. p->bTotalsValid = 0;
  192723. return sqlite3Fts5IndexRollback(p->pIndex);
  192724. }
  192725. static int sqlite3Fts5StorageConfigValue(
  192726. Fts5Storage *p,
  192727. const char *z,
  192728. sqlite3_value *pVal,
  192729. int iVal
  192730. ){
  192731. sqlite3_stmt *pReplace = 0;
  192732. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  192733. if( rc==SQLITE_OK ){
  192734. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  192735. if( pVal ){
  192736. sqlite3_bind_value(pReplace, 2, pVal);
  192737. }else{
  192738. sqlite3_bind_int(pReplace, 2, iVal);
  192739. }
  192740. sqlite3_step(pReplace);
  192741. rc = sqlite3_reset(pReplace);
  192742. sqlite3_bind_null(pReplace, 1);
  192743. }
  192744. if( rc==SQLITE_OK && pVal ){
  192745. int iNew = p->pConfig->iCookie + 1;
  192746. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  192747. if( rc==SQLITE_OK ){
  192748. p->pConfig->iCookie = iNew;
  192749. }
  192750. }
  192751. return rc;
  192752. }
  192753. /*
  192754. ** 2014 May 31
  192755. **
  192756. ** The author disclaims copyright to this source code. In place of
  192757. ** a legal notice, here is a blessing:
  192758. **
  192759. ** May you do good and not evil.
  192760. ** May you find forgiveness for yourself and forgive others.
  192761. ** May you share freely, never taking more than you give.
  192762. **
  192763. ******************************************************************************
  192764. */
  192765. /* #include "fts5Int.h" */
  192766. /**************************************************************************
  192767. ** Start of ascii tokenizer implementation.
  192768. */
  192769. /*
  192770. ** For tokenizers with no "unicode" modifier, the set of token characters
  192771. ** is the same as the set of ASCII range alphanumeric characters.
  192772. */
  192773. static unsigned char aAsciiTokenChar[128] = {
  192774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  192775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  192776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  192777. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  192778. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  192779. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  192780. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  192781. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  192782. };
  192783. typedef struct AsciiTokenizer AsciiTokenizer;
  192784. struct AsciiTokenizer {
  192785. unsigned char aTokenChar[128];
  192786. };
  192787. static void fts5AsciiAddExceptions(
  192788. AsciiTokenizer *p,
  192789. const char *zArg,
  192790. int bTokenChars
  192791. ){
  192792. int i;
  192793. for(i=0; zArg[i]; i++){
  192794. if( (zArg[i] & 0x80)==0 ){
  192795. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  192796. }
  192797. }
  192798. }
  192799. /*
  192800. ** Delete a "ascii" tokenizer.
  192801. */
  192802. static void fts5AsciiDelete(Fts5Tokenizer *p){
  192803. sqlite3_free(p);
  192804. }
  192805. /*
  192806. ** Create an "ascii" tokenizer.
  192807. */
  192808. static int fts5AsciiCreate(
  192809. void *pUnused,
  192810. const char **azArg, int nArg,
  192811. Fts5Tokenizer **ppOut
  192812. ){
  192813. int rc = SQLITE_OK;
  192814. AsciiTokenizer *p = 0;
  192815. UNUSED_PARAM(pUnused);
  192816. if( nArg%2 ){
  192817. rc = SQLITE_ERROR;
  192818. }else{
  192819. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  192820. if( p==0 ){
  192821. rc = SQLITE_NOMEM;
  192822. }else{
  192823. int i;
  192824. memset(p, 0, sizeof(AsciiTokenizer));
  192825. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  192826. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  192827. const char *zArg = azArg[i+1];
  192828. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  192829. fts5AsciiAddExceptions(p, zArg, 1);
  192830. }else
  192831. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  192832. fts5AsciiAddExceptions(p, zArg, 0);
  192833. }else{
  192834. rc = SQLITE_ERROR;
  192835. }
  192836. }
  192837. if( rc!=SQLITE_OK ){
  192838. fts5AsciiDelete((Fts5Tokenizer*)p);
  192839. p = 0;
  192840. }
  192841. }
  192842. }
  192843. *ppOut = (Fts5Tokenizer*)p;
  192844. return rc;
  192845. }
  192846. static void asciiFold(char *aOut, const char *aIn, int nByte){
  192847. int i;
  192848. for(i=0; i<nByte; i++){
  192849. char c = aIn[i];
  192850. if( c>='A' && c<='Z' ) c += 32;
  192851. aOut[i] = c;
  192852. }
  192853. }
  192854. /*
  192855. ** Tokenize some text using the ascii tokenizer.
  192856. */
  192857. static int fts5AsciiTokenize(
  192858. Fts5Tokenizer *pTokenizer,
  192859. void *pCtx,
  192860. int iUnused,
  192861. const char *pText, int nText,
  192862. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  192863. ){
  192864. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  192865. int rc = SQLITE_OK;
  192866. int ie;
  192867. int is = 0;
  192868. char aFold[64];
  192869. int nFold = sizeof(aFold);
  192870. char *pFold = aFold;
  192871. unsigned char *a = p->aTokenChar;
  192872. UNUSED_PARAM(iUnused);
  192873. while( is<nText && rc==SQLITE_OK ){
  192874. int nByte;
  192875. /* Skip any leading divider characters. */
  192876. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  192877. is++;
  192878. }
  192879. if( is==nText ) break;
  192880. /* Count the token characters */
  192881. ie = is+1;
  192882. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  192883. ie++;
  192884. }
  192885. /* Fold to lower case */
  192886. nByte = ie-is;
  192887. if( nByte>nFold ){
  192888. if( pFold!=aFold ) sqlite3_free(pFold);
  192889. pFold = sqlite3_malloc(nByte*2);
  192890. if( pFold==0 ){
  192891. rc = SQLITE_NOMEM;
  192892. break;
  192893. }
  192894. nFold = nByte*2;
  192895. }
  192896. asciiFold(pFold, &pText[is], nByte);
  192897. /* Invoke the token callback */
  192898. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  192899. is = ie+1;
  192900. }
  192901. if( pFold!=aFold ) sqlite3_free(pFold);
  192902. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  192903. return rc;
  192904. }
  192905. /**************************************************************************
  192906. ** Start of unicode61 tokenizer implementation.
  192907. */
  192908. /*
  192909. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  192910. ** from the sqlite3 source file utf.c. If this file is compiled as part
  192911. ** of the amalgamation, they are not required.
  192912. */
  192913. #ifndef SQLITE_AMALGAMATION
  192914. static const unsigned char sqlite3Utf8Trans1[] = {
  192915. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  192916. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  192917. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  192918. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  192919. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  192920. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  192921. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  192922. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  192923. };
  192924. #define READ_UTF8(zIn, zTerm, c) \
  192925. c = *(zIn++); \
  192926. if( c>=0xc0 ){ \
  192927. c = sqlite3Utf8Trans1[c-0xc0]; \
  192928. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  192929. c = (c<<6) + (0x3f & *(zIn++)); \
  192930. } \
  192931. if( c<0x80 \
  192932. || (c&0xFFFFF800)==0xD800 \
  192933. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  192934. }
  192935. #define WRITE_UTF8(zOut, c) { \
  192936. if( c<0x00080 ){ \
  192937. *zOut++ = (unsigned char)(c&0xFF); \
  192938. } \
  192939. else if( c<0x00800 ){ \
  192940. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  192941. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  192942. } \
  192943. else if( c<0x10000 ){ \
  192944. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  192945. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  192946. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  192947. }else{ \
  192948. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  192949. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  192950. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  192951. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  192952. } \
  192953. }
  192954. #endif /* ifndef SQLITE_AMALGAMATION */
  192955. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  192956. struct Unicode61Tokenizer {
  192957. unsigned char aTokenChar[128]; /* ASCII range token characters */
  192958. char *aFold; /* Buffer to fold text into */
  192959. int nFold; /* Size of aFold[] in bytes */
  192960. int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
  192961. int nException;
  192962. int *aiException;
  192963. };
  192964. static int fts5UnicodeAddExceptions(
  192965. Unicode61Tokenizer *p, /* Tokenizer object */
  192966. const char *z, /* Characters to treat as exceptions */
  192967. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  192968. ){
  192969. int rc = SQLITE_OK;
  192970. int n = (int)strlen(z);
  192971. int *aNew;
  192972. if( n>0 ){
  192973. aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
  192974. if( aNew ){
  192975. int nNew = p->nException;
  192976. const unsigned char *zCsr = (const unsigned char*)z;
  192977. const unsigned char *zTerm = (const unsigned char*)&z[n];
  192978. while( zCsr<zTerm ){
  192979. int iCode;
  192980. int bToken;
  192981. READ_UTF8(zCsr, zTerm, iCode);
  192982. if( iCode<128 ){
  192983. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  192984. }else{
  192985. bToken = sqlite3Fts5UnicodeIsalnum(iCode);
  192986. assert( (bToken==0 || bToken==1) );
  192987. assert( (bTokenChars==0 || bTokenChars==1) );
  192988. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  192989. int i;
  192990. for(i=0; i<nNew; i++){
  192991. if( aNew[i]>iCode ) break;
  192992. }
  192993. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  192994. aNew[i] = iCode;
  192995. nNew++;
  192996. }
  192997. }
  192998. }
  192999. p->aiException = aNew;
  193000. p->nException = nNew;
  193001. }else{
  193002. rc = SQLITE_NOMEM;
  193003. }
  193004. }
  193005. return rc;
  193006. }
  193007. /*
  193008. ** Return true if the p->aiException[] array contains the value iCode.
  193009. */
  193010. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  193011. if( p->nException>0 ){
  193012. int *a = p->aiException;
  193013. int iLo = 0;
  193014. int iHi = p->nException-1;
  193015. while( iHi>=iLo ){
  193016. int iTest = (iHi + iLo) / 2;
  193017. if( iCode==a[iTest] ){
  193018. return 1;
  193019. }else if( iCode>a[iTest] ){
  193020. iLo = iTest+1;
  193021. }else{
  193022. iHi = iTest-1;
  193023. }
  193024. }
  193025. }
  193026. return 0;
  193027. }
  193028. /*
  193029. ** Delete a "unicode61" tokenizer.
  193030. */
  193031. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  193032. if( pTok ){
  193033. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  193034. sqlite3_free(p->aiException);
  193035. sqlite3_free(p->aFold);
  193036. sqlite3_free(p);
  193037. }
  193038. return;
  193039. }
  193040. /*
  193041. ** Create a "unicode61" tokenizer.
  193042. */
  193043. static int fts5UnicodeCreate(
  193044. void *pUnused,
  193045. const char **azArg, int nArg,
  193046. Fts5Tokenizer **ppOut
  193047. ){
  193048. int rc = SQLITE_OK; /* Return code */
  193049. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  193050. UNUSED_PARAM(pUnused);
  193051. if( nArg%2 ){
  193052. rc = SQLITE_ERROR;
  193053. }else{
  193054. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  193055. if( p ){
  193056. int i;
  193057. memset(p, 0, sizeof(Unicode61Tokenizer));
  193058. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  193059. p->bRemoveDiacritic = 1;
  193060. p->nFold = 64;
  193061. p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
  193062. if( p->aFold==0 ){
  193063. rc = SQLITE_NOMEM;
  193064. }
  193065. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  193066. const char *zArg = azArg[i+1];
  193067. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  193068. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
  193069. rc = SQLITE_ERROR;
  193070. }
  193071. p->bRemoveDiacritic = (zArg[0]=='1');
  193072. }else
  193073. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  193074. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  193075. }else
  193076. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  193077. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  193078. }else{
  193079. rc = SQLITE_ERROR;
  193080. }
  193081. }
  193082. }else{
  193083. rc = SQLITE_NOMEM;
  193084. }
  193085. if( rc!=SQLITE_OK ){
  193086. fts5UnicodeDelete((Fts5Tokenizer*)p);
  193087. p = 0;
  193088. }
  193089. *ppOut = (Fts5Tokenizer*)p;
  193090. }
  193091. return rc;
  193092. }
  193093. /*
  193094. ** Return true if, for the purposes of tokenizing with the tokenizer
  193095. ** passed as the first argument, codepoint iCode is considered a token
  193096. ** character (not a separator).
  193097. */
  193098. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  193099. assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  193100. return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
  193101. }
  193102. static int fts5UnicodeTokenize(
  193103. Fts5Tokenizer *pTokenizer,
  193104. void *pCtx,
  193105. int iUnused,
  193106. const char *pText, int nText,
  193107. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  193108. ){
  193109. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  193110. int rc = SQLITE_OK;
  193111. unsigned char *a = p->aTokenChar;
  193112. unsigned char *zTerm = (unsigned char*)&pText[nText];
  193113. unsigned char *zCsr = (unsigned char *)pText;
  193114. /* Output buffer */
  193115. char *aFold = p->aFold;
  193116. int nFold = p->nFold;
  193117. const char *pEnd = &aFold[nFold-6];
  193118. UNUSED_PARAM(iUnused);
  193119. /* Each iteration of this loop gobbles up a contiguous run of separators,
  193120. ** then the next token. */
  193121. while( rc==SQLITE_OK ){
  193122. int iCode; /* non-ASCII codepoint read from input */
  193123. char *zOut = aFold;
  193124. int is;
  193125. int ie;
  193126. /* Skip any separator characters. */
  193127. while( 1 ){
  193128. if( zCsr>=zTerm ) goto tokenize_done;
  193129. if( *zCsr & 0x80 ) {
  193130. /* A character outside of the ascii range. Skip past it if it is
  193131. ** a separator character. Or break out of the loop if it is not. */
  193132. is = zCsr - (unsigned char*)pText;
  193133. READ_UTF8(zCsr, zTerm, iCode);
  193134. if( fts5UnicodeIsAlnum(p, iCode) ){
  193135. goto non_ascii_tokenchar;
  193136. }
  193137. }else{
  193138. if( a[*zCsr] ){
  193139. is = zCsr - (unsigned char*)pText;
  193140. goto ascii_tokenchar;
  193141. }
  193142. zCsr++;
  193143. }
  193144. }
  193145. /* Run through the tokenchars. Fold them into the output buffer along
  193146. ** the way. */
  193147. while( zCsr<zTerm ){
  193148. /* Grow the output buffer so that there is sufficient space to fit the
  193149. ** largest possible utf-8 character. */
  193150. if( zOut>pEnd ){
  193151. aFold = sqlite3_malloc(nFold*2);
  193152. if( aFold==0 ){
  193153. rc = SQLITE_NOMEM;
  193154. goto tokenize_done;
  193155. }
  193156. zOut = &aFold[zOut - p->aFold];
  193157. memcpy(aFold, p->aFold, nFold);
  193158. sqlite3_free(p->aFold);
  193159. p->aFold = aFold;
  193160. p->nFold = nFold = nFold*2;
  193161. pEnd = &aFold[nFold-6];
  193162. }
  193163. if( *zCsr & 0x80 ){
  193164. /* An non-ascii-range character. Fold it into the output buffer if
  193165. ** it is a token character, or break out of the loop if it is not. */
  193166. READ_UTF8(zCsr, zTerm, iCode);
  193167. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  193168. non_ascii_tokenchar:
  193169. iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
  193170. if( iCode ) WRITE_UTF8(zOut, iCode);
  193171. }else{
  193172. break;
  193173. }
  193174. }else if( a[*zCsr]==0 ){
  193175. /* An ascii-range separator character. End of token. */
  193176. break;
  193177. }else{
  193178. ascii_tokenchar:
  193179. if( *zCsr>='A' && *zCsr<='Z' ){
  193180. *zOut++ = *zCsr + 32;
  193181. }else{
  193182. *zOut++ = *zCsr;
  193183. }
  193184. zCsr++;
  193185. }
  193186. ie = zCsr - (unsigned char*)pText;
  193187. }
  193188. /* Invoke the token callback */
  193189. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  193190. }
  193191. tokenize_done:
  193192. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  193193. return rc;
  193194. }
  193195. /**************************************************************************
  193196. ** Start of porter stemmer implementation.
  193197. */
  193198. /* Any tokens larger than this (in bytes) are passed through without
  193199. ** stemming. */
  193200. #define FTS5_PORTER_MAX_TOKEN 64
  193201. typedef struct PorterTokenizer PorterTokenizer;
  193202. struct PorterTokenizer {
  193203. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  193204. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  193205. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  193206. };
  193207. /*
  193208. ** Delete a "porter" tokenizer.
  193209. */
  193210. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  193211. if( pTok ){
  193212. PorterTokenizer *p = (PorterTokenizer*)pTok;
  193213. if( p->pTokenizer ){
  193214. p->tokenizer.xDelete(p->pTokenizer);
  193215. }
  193216. sqlite3_free(p);
  193217. }
  193218. }
  193219. /*
  193220. ** Create a "porter" tokenizer.
  193221. */
  193222. static int fts5PorterCreate(
  193223. void *pCtx,
  193224. const char **azArg, int nArg,
  193225. Fts5Tokenizer **ppOut
  193226. ){
  193227. fts5_api *pApi = (fts5_api*)pCtx;
  193228. int rc = SQLITE_OK;
  193229. PorterTokenizer *pRet;
  193230. void *pUserdata = 0;
  193231. const char *zBase = "unicode61";
  193232. if( nArg>0 ){
  193233. zBase = azArg[0];
  193234. }
  193235. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  193236. if( pRet ){
  193237. memset(pRet, 0, sizeof(PorterTokenizer));
  193238. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  193239. }else{
  193240. rc = SQLITE_NOMEM;
  193241. }
  193242. if( rc==SQLITE_OK ){
  193243. int nArg2 = (nArg>0 ? nArg-1 : 0);
  193244. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  193245. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  193246. }
  193247. if( rc!=SQLITE_OK ){
  193248. fts5PorterDelete((Fts5Tokenizer*)pRet);
  193249. pRet = 0;
  193250. }
  193251. *ppOut = (Fts5Tokenizer*)pRet;
  193252. return rc;
  193253. }
  193254. typedef struct PorterContext PorterContext;
  193255. struct PorterContext {
  193256. void *pCtx;
  193257. int (*xToken)(void*, int, const char*, int, int, int);
  193258. char *aBuf;
  193259. };
  193260. typedef struct PorterRule PorterRule;
  193261. struct PorterRule {
  193262. const char *zSuffix;
  193263. int nSuffix;
  193264. int (*xCond)(char *zStem, int nStem);
  193265. const char *zOutput;
  193266. int nOutput;
  193267. };
  193268. #if 0
  193269. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  193270. int ret = -1;
  193271. int nBuf = *pnBuf;
  193272. PorterRule *p;
  193273. for(p=aRule; p->zSuffix; p++){
  193274. assert( strlen(p->zSuffix)==p->nSuffix );
  193275. assert( strlen(p->zOutput)==p->nOutput );
  193276. if( nBuf<p->nSuffix ) continue;
  193277. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  193278. }
  193279. if( p->zSuffix ){
  193280. int nStem = nBuf - p->nSuffix;
  193281. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  193282. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  193283. *pnBuf = nStem + p->nOutput;
  193284. ret = p - aRule;
  193285. }
  193286. }
  193287. return ret;
  193288. }
  193289. #endif
  193290. static int fts5PorterIsVowel(char c, int bYIsVowel){
  193291. return (
  193292. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  193293. );
  193294. }
  193295. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  193296. int i;
  193297. int bCons = bPrevCons;
  193298. /* Scan for a vowel */
  193299. for(i=0; i<nStem; i++){
  193300. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  193301. }
  193302. /* Scan for a consonent */
  193303. for(i++; i<nStem; i++){
  193304. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  193305. }
  193306. return 0;
  193307. }
  193308. /* porter rule condition: (m > 0) */
  193309. static int fts5Porter_MGt0(char *zStem, int nStem){
  193310. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  193311. }
  193312. /* porter rule condition: (m > 1) */
  193313. static int fts5Porter_MGt1(char *zStem, int nStem){
  193314. int n;
  193315. n = fts5PorterGobbleVC(zStem, nStem, 0);
  193316. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  193317. return 1;
  193318. }
  193319. return 0;
  193320. }
  193321. /* porter rule condition: (m = 1) */
  193322. static int fts5Porter_MEq1(char *zStem, int nStem){
  193323. int n;
  193324. n = fts5PorterGobbleVC(zStem, nStem, 0);
  193325. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  193326. return 1;
  193327. }
  193328. return 0;
  193329. }
  193330. /* porter rule condition: (*o) */
  193331. static int fts5Porter_Ostar(char *zStem, int nStem){
  193332. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  193333. return 0;
  193334. }else{
  193335. int i;
  193336. int mask = 0;
  193337. int bCons = 0;
  193338. for(i=0; i<nStem; i++){
  193339. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  193340. assert( bCons==0 || bCons==1 );
  193341. mask = (mask << 1) + bCons;
  193342. }
  193343. return ((mask & 0x0007)==0x0005);
  193344. }
  193345. }
  193346. /* porter rule condition: (m > 1 and (*S or *T)) */
  193347. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  193348. assert( nStem>0 );
  193349. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  193350. && fts5Porter_MGt1(zStem, nStem);
  193351. }
  193352. /* porter rule condition: (*v*) */
  193353. static int fts5Porter_Vowel(char *zStem, int nStem){
  193354. int i;
  193355. for(i=0; i<nStem; i++){
  193356. if( fts5PorterIsVowel(zStem[i], i>0) ){
  193357. return 1;
  193358. }
  193359. }
  193360. return 0;
  193361. }
  193362. /**************************************************************************
  193363. ***************************************************************************
  193364. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  193365. */
  193366. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  193367. int ret = 0;
  193368. int nBuf = *pnBuf;
  193369. switch( aBuf[nBuf-2] ){
  193370. case 'a':
  193371. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  193372. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  193373. *pnBuf = nBuf - 2;
  193374. }
  193375. }
  193376. break;
  193377. case 'c':
  193378. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  193379. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  193380. *pnBuf = nBuf - 4;
  193381. }
  193382. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  193383. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  193384. *pnBuf = nBuf - 4;
  193385. }
  193386. }
  193387. break;
  193388. case 'e':
  193389. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  193390. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  193391. *pnBuf = nBuf - 2;
  193392. }
  193393. }
  193394. break;
  193395. case 'i':
  193396. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  193397. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  193398. *pnBuf = nBuf - 2;
  193399. }
  193400. }
  193401. break;
  193402. case 'l':
  193403. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  193404. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  193405. *pnBuf = nBuf - 4;
  193406. }
  193407. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  193408. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  193409. *pnBuf = nBuf - 4;
  193410. }
  193411. }
  193412. break;
  193413. case 'n':
  193414. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  193415. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  193416. *pnBuf = nBuf - 3;
  193417. }
  193418. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  193419. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  193420. *pnBuf = nBuf - 5;
  193421. }
  193422. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  193423. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  193424. *pnBuf = nBuf - 4;
  193425. }
  193426. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  193427. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  193428. *pnBuf = nBuf - 3;
  193429. }
  193430. }
  193431. break;
  193432. case 'o':
  193433. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  193434. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  193435. *pnBuf = nBuf - 3;
  193436. }
  193437. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  193438. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  193439. *pnBuf = nBuf - 2;
  193440. }
  193441. }
  193442. break;
  193443. case 's':
  193444. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  193445. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  193446. *pnBuf = nBuf - 3;
  193447. }
  193448. }
  193449. break;
  193450. case 't':
  193451. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  193452. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  193453. *pnBuf = nBuf - 3;
  193454. }
  193455. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  193456. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  193457. *pnBuf = nBuf - 3;
  193458. }
  193459. }
  193460. break;
  193461. case 'u':
  193462. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  193463. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  193464. *pnBuf = nBuf - 3;
  193465. }
  193466. }
  193467. break;
  193468. case 'v':
  193469. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  193470. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  193471. *pnBuf = nBuf - 3;
  193472. }
  193473. }
  193474. break;
  193475. case 'z':
  193476. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  193477. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  193478. *pnBuf = nBuf - 3;
  193479. }
  193480. }
  193481. break;
  193482. }
  193483. return ret;
  193484. }
  193485. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  193486. int ret = 0;
  193487. int nBuf = *pnBuf;
  193488. switch( aBuf[nBuf-2] ){
  193489. case 'a':
  193490. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  193491. memcpy(&aBuf[nBuf-2], "ate", 3);
  193492. *pnBuf = nBuf - 2 + 3;
  193493. ret = 1;
  193494. }
  193495. break;
  193496. case 'b':
  193497. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  193498. memcpy(&aBuf[nBuf-2], "ble", 3);
  193499. *pnBuf = nBuf - 2 + 3;
  193500. ret = 1;
  193501. }
  193502. break;
  193503. case 'i':
  193504. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  193505. memcpy(&aBuf[nBuf-2], "ize", 3);
  193506. *pnBuf = nBuf - 2 + 3;
  193507. ret = 1;
  193508. }
  193509. break;
  193510. }
  193511. return ret;
  193512. }
  193513. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  193514. int ret = 0;
  193515. int nBuf = *pnBuf;
  193516. switch( aBuf[nBuf-2] ){
  193517. case 'a':
  193518. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  193519. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  193520. memcpy(&aBuf[nBuf-7], "ate", 3);
  193521. *pnBuf = nBuf - 7 + 3;
  193522. }
  193523. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  193524. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  193525. memcpy(&aBuf[nBuf-6], "tion", 4);
  193526. *pnBuf = nBuf - 6 + 4;
  193527. }
  193528. }
  193529. break;
  193530. case 'c':
  193531. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  193532. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  193533. memcpy(&aBuf[nBuf-4], "ence", 4);
  193534. *pnBuf = nBuf - 4 + 4;
  193535. }
  193536. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  193537. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  193538. memcpy(&aBuf[nBuf-4], "ance", 4);
  193539. *pnBuf = nBuf - 4 + 4;
  193540. }
  193541. }
  193542. break;
  193543. case 'e':
  193544. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  193545. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  193546. memcpy(&aBuf[nBuf-4], "ize", 3);
  193547. *pnBuf = nBuf - 4 + 3;
  193548. }
  193549. }
  193550. break;
  193551. case 'g':
  193552. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  193553. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  193554. memcpy(&aBuf[nBuf-4], "log", 3);
  193555. *pnBuf = nBuf - 4 + 3;
  193556. }
  193557. }
  193558. break;
  193559. case 'l':
  193560. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  193561. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  193562. memcpy(&aBuf[nBuf-3], "ble", 3);
  193563. *pnBuf = nBuf - 3 + 3;
  193564. }
  193565. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  193566. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  193567. memcpy(&aBuf[nBuf-4], "al", 2);
  193568. *pnBuf = nBuf - 4 + 2;
  193569. }
  193570. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  193571. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  193572. memcpy(&aBuf[nBuf-5], "ent", 3);
  193573. *pnBuf = nBuf - 5 + 3;
  193574. }
  193575. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  193576. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  193577. memcpy(&aBuf[nBuf-3], "e", 1);
  193578. *pnBuf = nBuf - 3 + 1;
  193579. }
  193580. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  193581. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  193582. memcpy(&aBuf[nBuf-5], "ous", 3);
  193583. *pnBuf = nBuf - 5 + 3;
  193584. }
  193585. }
  193586. break;
  193587. case 'o':
  193588. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  193589. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  193590. memcpy(&aBuf[nBuf-7], "ize", 3);
  193591. *pnBuf = nBuf - 7 + 3;
  193592. }
  193593. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  193594. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  193595. memcpy(&aBuf[nBuf-5], "ate", 3);
  193596. *pnBuf = nBuf - 5 + 3;
  193597. }
  193598. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  193599. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  193600. memcpy(&aBuf[nBuf-4], "ate", 3);
  193601. *pnBuf = nBuf - 4 + 3;
  193602. }
  193603. }
  193604. break;
  193605. case 's':
  193606. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  193607. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  193608. memcpy(&aBuf[nBuf-5], "al", 2);
  193609. *pnBuf = nBuf - 5 + 2;
  193610. }
  193611. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  193612. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  193613. memcpy(&aBuf[nBuf-7], "ive", 3);
  193614. *pnBuf = nBuf - 7 + 3;
  193615. }
  193616. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  193617. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  193618. memcpy(&aBuf[nBuf-7], "ful", 3);
  193619. *pnBuf = nBuf - 7 + 3;
  193620. }
  193621. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  193622. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  193623. memcpy(&aBuf[nBuf-7], "ous", 3);
  193624. *pnBuf = nBuf - 7 + 3;
  193625. }
  193626. }
  193627. break;
  193628. case 't':
  193629. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  193630. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  193631. memcpy(&aBuf[nBuf-5], "al", 2);
  193632. *pnBuf = nBuf - 5 + 2;
  193633. }
  193634. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  193635. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  193636. memcpy(&aBuf[nBuf-5], "ive", 3);
  193637. *pnBuf = nBuf - 5 + 3;
  193638. }
  193639. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  193640. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  193641. memcpy(&aBuf[nBuf-6], "ble", 3);
  193642. *pnBuf = nBuf - 6 + 3;
  193643. }
  193644. }
  193645. break;
  193646. }
  193647. return ret;
  193648. }
  193649. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  193650. int ret = 0;
  193651. int nBuf = *pnBuf;
  193652. switch( aBuf[nBuf-2] ){
  193653. case 'a':
  193654. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  193655. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  193656. memcpy(&aBuf[nBuf-4], "ic", 2);
  193657. *pnBuf = nBuf - 4 + 2;
  193658. }
  193659. }
  193660. break;
  193661. case 's':
  193662. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  193663. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  193664. *pnBuf = nBuf - 4;
  193665. }
  193666. }
  193667. break;
  193668. case 't':
  193669. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  193670. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  193671. memcpy(&aBuf[nBuf-5], "ic", 2);
  193672. *pnBuf = nBuf - 5 + 2;
  193673. }
  193674. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  193675. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  193676. memcpy(&aBuf[nBuf-5], "ic", 2);
  193677. *pnBuf = nBuf - 5 + 2;
  193678. }
  193679. }
  193680. break;
  193681. case 'u':
  193682. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  193683. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  193684. *pnBuf = nBuf - 3;
  193685. }
  193686. }
  193687. break;
  193688. case 'v':
  193689. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  193690. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  193691. *pnBuf = nBuf - 5;
  193692. }
  193693. }
  193694. break;
  193695. case 'z':
  193696. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  193697. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  193698. memcpy(&aBuf[nBuf-5], "al", 2);
  193699. *pnBuf = nBuf - 5 + 2;
  193700. }
  193701. }
  193702. break;
  193703. }
  193704. return ret;
  193705. }
  193706. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  193707. int ret = 0;
  193708. int nBuf = *pnBuf;
  193709. switch( aBuf[nBuf-2] ){
  193710. case 'e':
  193711. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  193712. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  193713. memcpy(&aBuf[nBuf-3], "ee", 2);
  193714. *pnBuf = nBuf - 3 + 2;
  193715. }
  193716. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  193717. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  193718. *pnBuf = nBuf - 2;
  193719. ret = 1;
  193720. }
  193721. }
  193722. break;
  193723. case 'n':
  193724. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  193725. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  193726. *pnBuf = nBuf - 3;
  193727. ret = 1;
  193728. }
  193729. }
  193730. break;
  193731. }
  193732. return ret;
  193733. }
  193734. /*
  193735. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  193736. ***************************************************************************
  193737. **************************************************************************/
  193738. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  193739. int nBuf = *pnBuf;
  193740. if( aBuf[nBuf-1]=='s' ){
  193741. if( aBuf[nBuf-2]=='e' ){
  193742. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  193743. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  193744. ){
  193745. *pnBuf = nBuf-2;
  193746. }else{
  193747. *pnBuf = nBuf-1;
  193748. }
  193749. }
  193750. else if( aBuf[nBuf-2]!='s' ){
  193751. *pnBuf = nBuf-1;
  193752. }
  193753. }
  193754. }
  193755. static int fts5PorterCb(
  193756. void *pCtx,
  193757. int tflags,
  193758. const char *pToken,
  193759. int nToken,
  193760. int iStart,
  193761. int iEnd
  193762. ){
  193763. PorterContext *p = (PorterContext*)pCtx;
  193764. char *aBuf;
  193765. int nBuf;
  193766. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  193767. aBuf = p->aBuf;
  193768. nBuf = nToken;
  193769. memcpy(aBuf, pToken, nBuf);
  193770. /* Step 1. */
  193771. fts5PorterStep1A(aBuf, &nBuf);
  193772. if( fts5PorterStep1B(aBuf, &nBuf) ){
  193773. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  193774. char c = aBuf[nBuf-1];
  193775. if( fts5PorterIsVowel(c, 0)==0
  193776. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  193777. ){
  193778. nBuf--;
  193779. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  193780. aBuf[nBuf++] = 'e';
  193781. }
  193782. }
  193783. }
  193784. /* Step 1C. */
  193785. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  193786. aBuf[nBuf-1] = 'i';
  193787. }
  193788. /* Steps 2 through 4. */
  193789. fts5PorterStep2(aBuf, &nBuf);
  193790. fts5PorterStep3(aBuf, &nBuf);
  193791. fts5PorterStep4(aBuf, &nBuf);
  193792. /* Step 5a. */
  193793. assert( nBuf>0 );
  193794. if( aBuf[nBuf-1]=='e' ){
  193795. if( fts5Porter_MGt1(aBuf, nBuf-1)
  193796. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  193797. ){
  193798. nBuf--;
  193799. }
  193800. }
  193801. /* Step 5b. */
  193802. if( nBuf>1 && aBuf[nBuf-1]=='l'
  193803. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  193804. ){
  193805. nBuf--;
  193806. }
  193807. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  193808. pass_through:
  193809. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  193810. }
  193811. /*
  193812. ** Tokenize using the porter tokenizer.
  193813. */
  193814. static int fts5PorterTokenize(
  193815. Fts5Tokenizer *pTokenizer,
  193816. void *pCtx,
  193817. int flags,
  193818. const char *pText, int nText,
  193819. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  193820. ){
  193821. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  193822. PorterContext sCtx;
  193823. sCtx.xToken = xToken;
  193824. sCtx.pCtx = pCtx;
  193825. sCtx.aBuf = p->aBuf;
  193826. return p->tokenizer.xTokenize(
  193827. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  193828. );
  193829. }
  193830. /*
  193831. ** Register all built-in tokenizers with FTS5.
  193832. */
  193833. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  193834. struct BuiltinTokenizer {
  193835. const char *zName;
  193836. fts5_tokenizer x;
  193837. } aBuiltin[] = {
  193838. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  193839. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  193840. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  193841. };
  193842. int rc = SQLITE_OK; /* Return code */
  193843. int i; /* To iterate through builtin functions */
  193844. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  193845. rc = pApi->xCreateTokenizer(pApi,
  193846. aBuiltin[i].zName,
  193847. (void*)pApi,
  193848. &aBuiltin[i].x,
  193849. 0
  193850. );
  193851. }
  193852. return rc;
  193853. }
  193854. /*
  193855. ** 2012 May 25
  193856. **
  193857. ** The author disclaims copyright to this source code. In place of
  193858. ** a legal notice, here is a blessing:
  193859. **
  193860. ** May you do good and not evil.
  193861. ** May you find forgiveness for yourself and forgive others.
  193862. ** May you share freely, never taking more than you give.
  193863. **
  193864. ******************************************************************************
  193865. */
  193866. /*
  193867. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  193868. */
  193869. /* #include <assert.h> */
  193870. /*
  193871. ** Return true if the argument corresponds to a unicode codepoint
  193872. ** classified as either a letter or a number. Otherwise false.
  193873. **
  193874. ** The results are undefined if the value passed to this function
  193875. ** is less than zero.
  193876. */
  193877. static int sqlite3Fts5UnicodeIsalnum(int c){
  193878. /* Each unsigned integer in the following array corresponds to a contiguous
  193879. ** range of unicode codepoints that are not either letters or numbers (i.e.
  193880. ** codepoints for which this function should return 0).
  193881. **
  193882. ** The most significant 22 bits in each 32-bit value contain the first
  193883. ** codepoint in the range. The least significant 10 bits are used to store
  193884. ** the size of the range (always at least 1). In other words, the value
  193885. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  193886. ** C. It is not possible to represent a range larger than 1023 codepoints
  193887. ** using this format.
  193888. */
  193889. static const unsigned int aEntry[] = {
  193890. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  193891. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  193892. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  193893. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  193894. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  193895. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  193896. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  193897. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  193898. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  193899. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  193900. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  193901. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  193902. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  193903. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  193904. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  193905. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  193906. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  193907. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  193908. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  193909. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  193910. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  193911. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  193912. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  193913. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  193914. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  193915. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  193916. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  193917. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  193918. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  193919. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  193920. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  193921. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  193922. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  193923. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  193924. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  193925. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  193926. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  193927. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  193928. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  193929. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  193930. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  193931. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  193932. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  193933. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  193934. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  193935. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  193936. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  193937. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  193938. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  193939. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  193940. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  193941. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  193942. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  193943. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  193944. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  193945. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  193946. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  193947. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  193948. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  193949. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  193950. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  193951. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  193952. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  193953. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  193954. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  193955. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  193956. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  193957. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  193958. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  193959. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  193960. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  193961. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  193962. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  193963. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  193964. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  193965. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  193966. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  193967. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  193968. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  193969. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  193970. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  193971. 0x380400F0,
  193972. };
  193973. static const unsigned int aAscii[4] = {
  193974. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  193975. };
  193976. if( (unsigned int)c<128 ){
  193977. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  193978. }else if( (unsigned int)c<(1<<22) ){
  193979. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  193980. int iRes = 0;
  193981. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  193982. int iLo = 0;
  193983. while( iHi>=iLo ){
  193984. int iTest = (iHi + iLo) / 2;
  193985. if( key >= aEntry[iTest] ){
  193986. iRes = iTest;
  193987. iLo = iTest+1;
  193988. }else{
  193989. iHi = iTest-1;
  193990. }
  193991. }
  193992. assert( aEntry[0]<key );
  193993. assert( key>=aEntry[iRes] );
  193994. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  193995. }
  193996. return 1;
  193997. }
  193998. /*
  193999. ** If the argument is a codepoint corresponding to a lowercase letter
  194000. ** in the ASCII range with a diacritic added, return the codepoint
  194001. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  194002. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  194003. ** E"). The resuls of passing a codepoint that corresponds to an
  194004. ** uppercase letter are undefined.
  194005. */
  194006. static int fts5_remove_diacritic(int c){
  194007. unsigned short aDia[] = {
  194008. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  194009. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  194010. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  194011. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  194012. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  194013. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  194014. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  194015. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  194016. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  194017. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  194018. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  194019. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  194020. 62924, 63050, 63082, 63274, 63390,
  194021. };
  194022. char aChar[] = {
  194023. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  194024. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  194025. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  194026. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  194027. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  194028. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  194029. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  194030. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  194031. 'e', 'i', 'o', 'u', 'y',
  194032. };
  194033. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  194034. int iRes = 0;
  194035. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  194036. int iLo = 0;
  194037. while( iHi>=iLo ){
  194038. int iTest = (iHi + iLo) / 2;
  194039. if( key >= aDia[iTest] ){
  194040. iRes = iTest;
  194041. iLo = iTest+1;
  194042. }else{
  194043. iHi = iTest-1;
  194044. }
  194045. }
  194046. assert( key>=aDia[iRes] );
  194047. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  194048. }
  194049. /*
  194050. ** Return true if the argument interpreted as a unicode codepoint
  194051. ** is a diacritical modifier character.
  194052. */
  194053. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  194054. unsigned int mask0 = 0x08029FDF;
  194055. unsigned int mask1 = 0x000361F8;
  194056. if( c<768 || c>817 ) return 0;
  194057. return (c < 768+32) ?
  194058. (mask0 & (1 << (c-768))) :
  194059. (mask1 & (1 << (c-768-32)));
  194060. }
  194061. /*
  194062. ** Interpret the argument as a unicode codepoint. If the codepoint
  194063. ** is an upper case character that has a lower case equivalent,
  194064. ** return the codepoint corresponding to the lower case version.
  194065. ** Otherwise, return a copy of the argument.
  194066. **
  194067. ** The results are undefined if the value passed to this function
  194068. ** is less than zero.
  194069. */
  194070. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
  194071. /* Each entry in the following array defines a rule for folding a range
  194072. ** of codepoints to lower case. The rule applies to a range of nRange
  194073. ** codepoints starting at codepoint iCode.
  194074. **
  194075. ** If the least significant bit in flags is clear, then the rule applies
  194076. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  194077. ** need to be folded). Or, if it is set, then the rule only applies to
  194078. ** every second codepoint in the range, starting with codepoint C.
  194079. **
  194080. ** The 7 most significant bits in flags are an index into the aiOff[]
  194081. ** array. If a specific codepoint C does require folding, then its lower
  194082. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  194083. **
  194084. ** The contents of this array are generated by parsing the CaseFolding.txt
  194085. ** file distributed as part of the "Unicode Character Database". See
  194086. ** http://www.unicode.org for details.
  194087. */
  194088. static const struct TableEntry {
  194089. unsigned short iCode;
  194090. unsigned char flags;
  194091. unsigned char nRange;
  194092. } aEntry[] = {
  194093. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  194094. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  194095. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  194096. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  194097. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  194098. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  194099. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  194100. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  194101. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  194102. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  194103. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  194104. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  194105. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  194106. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  194107. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  194108. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  194109. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  194110. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  194111. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  194112. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  194113. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  194114. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  194115. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  194116. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  194117. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  194118. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  194119. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  194120. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  194121. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  194122. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  194123. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  194124. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  194125. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  194126. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  194127. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  194128. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  194129. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  194130. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  194131. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  194132. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  194133. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  194134. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  194135. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  194136. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  194137. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  194138. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  194139. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  194140. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  194141. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  194142. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  194143. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  194144. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  194145. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  194146. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  194147. {65313, 14, 26},
  194148. };
  194149. static const unsigned short aiOff[] = {
  194150. 1, 2, 8, 15, 16, 26, 28, 32,
  194151. 37, 38, 40, 48, 63, 64, 69, 71,
  194152. 79, 80, 116, 202, 203, 205, 206, 207,
  194153. 209, 210, 211, 213, 214, 217, 218, 219,
  194154. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  194155. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  194156. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  194157. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  194158. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  194159. 65514, 65521, 65527, 65528, 65529,
  194160. };
  194161. int ret = c;
  194162. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  194163. if( c<128 ){
  194164. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  194165. }else if( c<65536 ){
  194166. const struct TableEntry *p;
  194167. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  194168. int iLo = 0;
  194169. int iRes = -1;
  194170. assert( c>aEntry[0].iCode );
  194171. while( iHi>=iLo ){
  194172. int iTest = (iHi + iLo) / 2;
  194173. int cmp = (c - aEntry[iTest].iCode);
  194174. if( cmp>=0 ){
  194175. iRes = iTest;
  194176. iLo = iTest+1;
  194177. }else{
  194178. iHi = iTest-1;
  194179. }
  194180. }
  194181. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  194182. p = &aEntry[iRes];
  194183. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  194184. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  194185. assert( ret>0 );
  194186. }
  194187. if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
  194188. }
  194189. else if( c>=66560 && c<66600 ){
  194190. ret = c + 40;
  194191. }
  194192. return ret;
  194193. }
  194194. /*
  194195. ** 2015 May 30
  194196. **
  194197. ** The author disclaims copyright to this source code. In place of
  194198. ** a legal notice, here is a blessing:
  194199. **
  194200. ** May you do good and not evil.
  194201. ** May you find forgiveness for yourself and forgive others.
  194202. ** May you share freely, never taking more than you give.
  194203. **
  194204. ******************************************************************************
  194205. **
  194206. ** Routines for varint serialization and deserialization.
  194207. */
  194208. /* #include "fts5Int.h" */
  194209. /*
  194210. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  194211. ** Except, this version does handle the single byte case that the core
  194212. ** version depends on being handled before its function is called.
  194213. */
  194214. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  194215. u32 a,b;
  194216. /* The 1-byte case. Overwhelmingly the most common. */
  194217. a = *p;
  194218. /* a: p0 (unmasked) */
  194219. if (!(a&0x80))
  194220. {
  194221. /* Values between 0 and 127 */
  194222. *v = a;
  194223. return 1;
  194224. }
  194225. /* The 2-byte case */
  194226. p++;
  194227. b = *p;
  194228. /* b: p1 (unmasked) */
  194229. if (!(b&0x80))
  194230. {
  194231. /* Values between 128 and 16383 */
  194232. a &= 0x7f;
  194233. a = a<<7;
  194234. *v = a | b;
  194235. return 2;
  194236. }
  194237. /* The 3-byte case */
  194238. p++;
  194239. a = a<<14;
  194240. a |= *p;
  194241. /* a: p0<<14 | p2 (unmasked) */
  194242. if (!(a&0x80))
  194243. {
  194244. /* Values between 16384 and 2097151 */
  194245. a &= (0x7f<<14)|(0x7f);
  194246. b &= 0x7f;
  194247. b = b<<7;
  194248. *v = a | b;
  194249. return 3;
  194250. }
  194251. /* A 32-bit varint is used to store size information in btrees.
  194252. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  194253. ** A 3-byte varint is sufficient, for example, to record the size
  194254. ** of a 1048569-byte BLOB or string.
  194255. **
  194256. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  194257. ** rare larger cases can be handled by the slower 64-bit varint
  194258. ** routine.
  194259. */
  194260. {
  194261. u64 v64;
  194262. u8 n;
  194263. p -= 2;
  194264. n = sqlite3Fts5GetVarint(p, &v64);
  194265. *v = (u32)v64;
  194266. assert( n>3 && n<=9 );
  194267. return n;
  194268. }
  194269. }
  194270. /*
  194271. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  194272. ** are defined here rather than simply putting the constant expressions
  194273. ** inline in order to work around bugs in the RVT compiler.
  194274. **
  194275. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  194276. **
  194277. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  194278. */
  194279. #define SLOT_2_0 0x001fc07f
  194280. #define SLOT_4_2_0 0xf01fc07f
  194281. /*
  194282. ** Read a 64-bit variable-length integer from memory starting at p[0].
  194283. ** Return the number of bytes read. The value is stored in *v.
  194284. */
  194285. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  194286. u32 a,b,s;
  194287. a = *p;
  194288. /* a: p0 (unmasked) */
  194289. if (!(a&0x80))
  194290. {
  194291. *v = a;
  194292. return 1;
  194293. }
  194294. p++;
  194295. b = *p;
  194296. /* b: p1 (unmasked) */
  194297. if (!(b&0x80))
  194298. {
  194299. a &= 0x7f;
  194300. a = a<<7;
  194301. a |= b;
  194302. *v = a;
  194303. return 2;
  194304. }
  194305. /* Verify that constants are precomputed correctly */
  194306. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  194307. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  194308. p++;
  194309. a = a<<14;
  194310. a |= *p;
  194311. /* a: p0<<14 | p2 (unmasked) */
  194312. if (!(a&0x80))
  194313. {
  194314. a &= SLOT_2_0;
  194315. b &= 0x7f;
  194316. b = b<<7;
  194317. a |= b;
  194318. *v = a;
  194319. return 3;
  194320. }
  194321. /* CSE1 from below */
  194322. a &= SLOT_2_0;
  194323. p++;
  194324. b = b<<14;
  194325. b |= *p;
  194326. /* b: p1<<14 | p3 (unmasked) */
  194327. if (!(b&0x80))
  194328. {
  194329. b &= SLOT_2_0;
  194330. /* moved CSE1 up */
  194331. /* a &= (0x7f<<14)|(0x7f); */
  194332. a = a<<7;
  194333. a |= b;
  194334. *v = a;
  194335. return 4;
  194336. }
  194337. /* a: p0<<14 | p2 (masked) */
  194338. /* b: p1<<14 | p3 (unmasked) */
  194339. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  194340. /* moved CSE1 up */
  194341. /* a &= (0x7f<<14)|(0x7f); */
  194342. b &= SLOT_2_0;
  194343. s = a;
  194344. /* s: p0<<14 | p2 (masked) */
  194345. p++;
  194346. a = a<<14;
  194347. a |= *p;
  194348. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  194349. if (!(a&0x80))
  194350. {
  194351. /* we can skip these cause they were (effectively) done above in calc'ing s */
  194352. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  194353. /* b &= (0x7f<<14)|(0x7f); */
  194354. b = b<<7;
  194355. a |= b;
  194356. s = s>>18;
  194357. *v = ((u64)s)<<32 | a;
  194358. return 5;
  194359. }
  194360. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  194361. s = s<<7;
  194362. s |= b;
  194363. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  194364. p++;
  194365. b = b<<14;
  194366. b |= *p;
  194367. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  194368. if (!(b&0x80))
  194369. {
  194370. /* we can skip this cause it was (effectively) done above in calc'ing s */
  194371. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  194372. a &= SLOT_2_0;
  194373. a = a<<7;
  194374. a |= b;
  194375. s = s>>18;
  194376. *v = ((u64)s)<<32 | a;
  194377. return 6;
  194378. }
  194379. p++;
  194380. a = a<<14;
  194381. a |= *p;
  194382. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  194383. if (!(a&0x80))
  194384. {
  194385. a &= SLOT_4_2_0;
  194386. b &= SLOT_2_0;
  194387. b = b<<7;
  194388. a |= b;
  194389. s = s>>11;
  194390. *v = ((u64)s)<<32 | a;
  194391. return 7;
  194392. }
  194393. /* CSE2 from below */
  194394. a &= SLOT_2_0;
  194395. p++;
  194396. b = b<<14;
  194397. b |= *p;
  194398. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  194399. if (!(b&0x80))
  194400. {
  194401. b &= SLOT_4_2_0;
  194402. /* moved CSE2 up */
  194403. /* a &= (0x7f<<14)|(0x7f); */
  194404. a = a<<7;
  194405. a |= b;
  194406. s = s>>4;
  194407. *v = ((u64)s)<<32 | a;
  194408. return 8;
  194409. }
  194410. p++;
  194411. a = a<<15;
  194412. a |= *p;
  194413. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  194414. /* moved CSE2 up */
  194415. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  194416. b &= SLOT_2_0;
  194417. b = b<<8;
  194418. a |= b;
  194419. s = s<<4;
  194420. b = p[-4];
  194421. b &= 0x7f;
  194422. b = b>>3;
  194423. s |= b;
  194424. *v = ((u64)s)<<32 | a;
  194425. return 9;
  194426. }
  194427. /*
  194428. ** The variable-length integer encoding is as follows:
  194429. **
  194430. ** KEY:
  194431. ** A = 0xxxxxxx 7 bits of data and one flag bit
  194432. ** B = 1xxxxxxx 7 bits of data and one flag bit
  194433. ** C = xxxxxxxx 8 bits of data
  194434. **
  194435. ** 7 bits - A
  194436. ** 14 bits - BA
  194437. ** 21 bits - BBA
  194438. ** 28 bits - BBBA
  194439. ** 35 bits - BBBBA
  194440. ** 42 bits - BBBBBA
  194441. ** 49 bits - BBBBBBA
  194442. ** 56 bits - BBBBBBBA
  194443. ** 64 bits - BBBBBBBBC
  194444. */
  194445. #ifdef SQLITE_NOINLINE
  194446. # define FTS5_NOINLINE SQLITE_NOINLINE
  194447. #else
  194448. # define FTS5_NOINLINE
  194449. #endif
  194450. /*
  194451. ** Write a 64-bit variable-length integer to memory starting at p[0].
  194452. ** The length of data write will be between 1 and 9 bytes. The number
  194453. ** of bytes written is returned.
  194454. **
  194455. ** A variable-length integer consists of the lower 7 bits of each byte
  194456. ** for all bytes that have the 8th bit set and one byte with the 8th
  194457. ** bit clear. Except, if we get to the 9th byte, it stores the full
  194458. ** 8 bits and is the last byte.
  194459. */
  194460. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  194461. int i, j, n;
  194462. u8 buf[10];
  194463. if( v & (((u64)0xff000000)<<32) ){
  194464. p[8] = (u8)v;
  194465. v >>= 8;
  194466. for(i=7; i>=0; i--){
  194467. p[i] = (u8)((v & 0x7f) | 0x80);
  194468. v >>= 7;
  194469. }
  194470. return 9;
  194471. }
  194472. n = 0;
  194473. do{
  194474. buf[n++] = (u8)((v & 0x7f) | 0x80);
  194475. v >>= 7;
  194476. }while( v!=0 );
  194477. buf[0] &= 0x7f;
  194478. assert( n<=9 );
  194479. for(i=0, j=n-1; j>=0; j--, i++){
  194480. p[i] = buf[j];
  194481. }
  194482. return n;
  194483. }
  194484. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  194485. if( v<=0x7f ){
  194486. p[0] = v&0x7f;
  194487. return 1;
  194488. }
  194489. if( v<=0x3fff ){
  194490. p[0] = ((v>>7)&0x7f)|0x80;
  194491. p[1] = v&0x7f;
  194492. return 2;
  194493. }
  194494. return fts5PutVarint64(p,v);
  194495. }
  194496. static int sqlite3Fts5GetVarintLen(u32 iVal){
  194497. #if 0
  194498. if( iVal<(1 << 7 ) ) return 1;
  194499. #endif
  194500. assert( iVal>=(1 << 7) );
  194501. if( iVal<(1 << 14) ) return 2;
  194502. if( iVal<(1 << 21) ) return 3;
  194503. if( iVal<(1 << 28) ) return 4;
  194504. return 5;
  194505. }
  194506. /*
  194507. ** 2015 May 08
  194508. **
  194509. ** The author disclaims copyright to this source code. In place of
  194510. ** a legal notice, here is a blessing:
  194511. **
  194512. ** May you do good and not evil.
  194513. ** May you find forgiveness for yourself and forgive others.
  194514. ** May you share freely, never taking more than you give.
  194515. **
  194516. ******************************************************************************
  194517. **
  194518. ** This is an SQLite virtual table module implementing direct access to an
  194519. ** existing FTS5 index. The module may create several different types of
  194520. ** tables:
  194521. **
  194522. ** col:
  194523. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  194524. **
  194525. ** One row for each term/column combination. The value of $doc is set to
  194526. ** the number of fts5 rows that contain at least one instance of term
  194527. ** $term within column $col. Field $cnt is set to the total number of
  194528. ** instances of term $term in column $col (in any row of the fts5 table).
  194529. **
  194530. ** row:
  194531. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  194532. **
  194533. ** One row for each term in the database. The value of $doc is set to
  194534. ** the number of fts5 rows that contain at least one instance of term
  194535. ** $term. Field $cnt is set to the total number of instances of term
  194536. ** $term in the database.
  194537. **
  194538. ** instance:
  194539. ** CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
  194540. **
  194541. ** One row for each term instance in the database.
  194542. */
  194543. /* #include "fts5Int.h" */
  194544. typedef struct Fts5VocabTable Fts5VocabTable;
  194545. typedef struct Fts5VocabCursor Fts5VocabCursor;
  194546. struct Fts5VocabTable {
  194547. sqlite3_vtab base;
  194548. char *zFts5Tbl; /* Name of fts5 table */
  194549. char *zFts5Db; /* Db containing fts5 table */
  194550. sqlite3 *db; /* Database handle */
  194551. Fts5Global *pGlobal; /* FTS5 global object for this database */
  194552. int eType; /* FTS5_VOCAB_COL, ROW or INSTANCE */
  194553. };
  194554. struct Fts5VocabCursor {
  194555. sqlite3_vtab_cursor base;
  194556. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  194557. Fts5Index *pIndex; /* Associated FTS5 index */
  194558. int bEof; /* True if this cursor is at EOF */
  194559. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  194560. int nLeTerm; /* Size of zLeTerm in bytes */
  194561. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  194562. /* These are used by 'col' tables only */
  194563. Fts5Config *pConfig; /* Fts5 table configuration */
  194564. int iCol;
  194565. i64 *aCnt;
  194566. i64 *aDoc;
  194567. /* Output values used by all tables. */
  194568. i64 rowid; /* This table's current rowid value */
  194569. Fts5Buffer term; /* Current value of 'term' column */
  194570. /* Output values Used by 'instance' tables only */
  194571. i64 iInstPos;
  194572. int iInstOff;
  194573. };
  194574. #define FTS5_VOCAB_COL 0
  194575. #define FTS5_VOCAB_ROW 1
  194576. #define FTS5_VOCAB_INSTANCE 2
  194577. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  194578. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  194579. #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
  194580. /*
  194581. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  194582. */
  194583. #define FTS5_VOCAB_TERM_EQ 0x01
  194584. #define FTS5_VOCAB_TERM_GE 0x02
  194585. #define FTS5_VOCAB_TERM_LE 0x04
  194586. /*
  194587. ** Translate a string containing an fts5vocab table type to an
  194588. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  194589. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  194590. ** and return SQLITE_ERROR.
  194591. */
  194592. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  194593. int rc = SQLITE_OK;
  194594. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  194595. if( rc==SQLITE_OK ){
  194596. sqlite3Fts5Dequote(zCopy);
  194597. if( sqlite3_stricmp(zCopy, "col")==0 ){
  194598. *peType = FTS5_VOCAB_COL;
  194599. }else
  194600. if( sqlite3_stricmp(zCopy, "row")==0 ){
  194601. *peType = FTS5_VOCAB_ROW;
  194602. }else
  194603. if( sqlite3_stricmp(zCopy, "instance")==0 ){
  194604. *peType = FTS5_VOCAB_INSTANCE;
  194605. }else
  194606. {
  194607. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  194608. rc = SQLITE_ERROR;
  194609. }
  194610. sqlite3_free(zCopy);
  194611. }
  194612. return rc;
  194613. }
  194614. /*
  194615. ** The xDisconnect() virtual table method.
  194616. */
  194617. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  194618. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  194619. sqlite3_free(pTab);
  194620. return SQLITE_OK;
  194621. }
  194622. /*
  194623. ** The xDestroy() virtual table method.
  194624. */
  194625. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  194626. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  194627. sqlite3_free(pTab);
  194628. return SQLITE_OK;
  194629. }
  194630. /*
  194631. ** This function is the implementation of both the xConnect and xCreate
  194632. ** methods of the FTS3 virtual table.
  194633. **
  194634. ** The argv[] array contains the following:
  194635. **
  194636. ** argv[0] -> module name ("fts5vocab")
  194637. ** argv[1] -> database name
  194638. ** argv[2] -> table name
  194639. **
  194640. ** then:
  194641. **
  194642. ** argv[3] -> name of fts5 table
  194643. ** argv[4] -> type of fts5vocab table
  194644. **
  194645. ** or, for tables in the TEMP schema only.
  194646. **
  194647. ** argv[3] -> name of fts5 tables database
  194648. ** argv[4] -> name of fts5 table
  194649. ** argv[5] -> type of fts5vocab table
  194650. */
  194651. static int fts5VocabInitVtab(
  194652. sqlite3 *db, /* The SQLite database connection */
  194653. void *pAux, /* Pointer to Fts5Global object */
  194654. int argc, /* Number of elements in argv array */
  194655. const char * const *argv, /* xCreate/xConnect argument array */
  194656. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  194657. char **pzErr /* Write any error message here */
  194658. ){
  194659. const char *azSchema[] = {
  194660. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  194661. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")",
  194662. "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
  194663. };
  194664. Fts5VocabTable *pRet = 0;
  194665. int rc = SQLITE_OK; /* Return code */
  194666. int bDb;
  194667. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  194668. if( argc!=5 && bDb==0 ){
  194669. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  194670. rc = SQLITE_ERROR;
  194671. }else{
  194672. int nByte; /* Bytes of space to allocate */
  194673. const char *zDb = bDb ? argv[3] : argv[1];
  194674. const char *zTab = bDb ? argv[4] : argv[3];
  194675. const char *zType = bDb ? argv[5] : argv[4];
  194676. int nDb = (int)strlen(zDb)+1;
  194677. int nTab = (int)strlen(zTab)+1;
  194678. int eType = 0;
  194679. rc = fts5VocabTableType(zType, pzErr, &eType);
  194680. if( rc==SQLITE_OK ){
  194681. assert( eType>=0 && eType<ArraySize(azSchema) );
  194682. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  194683. }
  194684. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  194685. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  194686. if( pRet ){
  194687. pRet->pGlobal = (Fts5Global*)pAux;
  194688. pRet->eType = eType;
  194689. pRet->db = db;
  194690. pRet->zFts5Tbl = (char*)&pRet[1];
  194691. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  194692. memcpy(pRet->zFts5Tbl, zTab, nTab);
  194693. memcpy(pRet->zFts5Db, zDb, nDb);
  194694. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  194695. sqlite3Fts5Dequote(pRet->zFts5Db);
  194696. }
  194697. }
  194698. *ppVTab = (sqlite3_vtab*)pRet;
  194699. return rc;
  194700. }
  194701. /*
  194702. ** The xConnect() and xCreate() methods for the virtual table. All the
  194703. ** work is done in function fts5VocabInitVtab().
  194704. */
  194705. static int fts5VocabConnectMethod(
  194706. sqlite3 *db, /* Database connection */
  194707. void *pAux, /* Pointer to tokenizer hash table */
  194708. int argc, /* Number of elements in argv array */
  194709. const char * const *argv, /* xCreate/xConnect argument array */
  194710. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  194711. char **pzErr /* OUT: sqlite3_malloc'd error message */
  194712. ){
  194713. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  194714. }
  194715. static int fts5VocabCreateMethod(
  194716. sqlite3 *db, /* Database connection */
  194717. void *pAux, /* Pointer to tokenizer hash table */
  194718. int argc, /* Number of elements in argv array */
  194719. const char * const *argv, /* xCreate/xConnect argument array */
  194720. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  194721. char **pzErr /* OUT: sqlite3_malloc'd error message */
  194722. ){
  194723. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  194724. }
  194725. /*
  194726. ** Implementation of the xBestIndex method.
  194727. **
  194728. ** Only constraints of the form:
  194729. **
  194730. ** term <= ?
  194731. ** term == ?
  194732. ** term >= ?
  194733. **
  194734. ** are interpreted. Less-than and less-than-or-equal are treated
  194735. ** identically, as are greater-than and greater-than-or-equal.
  194736. */
  194737. static int fts5VocabBestIndexMethod(
  194738. sqlite3_vtab *pUnused,
  194739. sqlite3_index_info *pInfo
  194740. ){
  194741. int i;
  194742. int iTermEq = -1;
  194743. int iTermGe = -1;
  194744. int iTermLe = -1;
  194745. int idxNum = 0;
  194746. int nArg = 0;
  194747. UNUSED_PARAM(pUnused);
  194748. for(i=0; i<pInfo->nConstraint; i++){
  194749. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  194750. if( p->usable==0 ) continue;
  194751. if( p->iColumn==0 ){ /* term column */
  194752. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  194753. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  194754. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  194755. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  194756. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  194757. }
  194758. }
  194759. if( iTermEq>=0 ){
  194760. idxNum |= FTS5_VOCAB_TERM_EQ;
  194761. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  194762. pInfo->estimatedCost = 100;
  194763. }else{
  194764. pInfo->estimatedCost = 1000000;
  194765. if( iTermGe>=0 ){
  194766. idxNum |= FTS5_VOCAB_TERM_GE;
  194767. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  194768. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  194769. }
  194770. if( iTermLe>=0 ){
  194771. idxNum |= FTS5_VOCAB_TERM_LE;
  194772. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  194773. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  194774. }
  194775. }
  194776. /* This virtual table always delivers results in ascending order of
  194777. ** the "term" column (column 0). So if the user has requested this
  194778. ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
  194779. ** sqlite3_index_info.orderByConsumed flag to tell the core the results
  194780. ** are already in sorted order. */
  194781. if( pInfo->nOrderBy==1
  194782. && pInfo->aOrderBy[0].iColumn==0
  194783. && pInfo->aOrderBy[0].desc==0
  194784. ){
  194785. pInfo->orderByConsumed = 1;
  194786. }
  194787. pInfo->idxNum = idxNum;
  194788. return SQLITE_OK;
  194789. }
  194790. /*
  194791. ** Implementation of xOpen method.
  194792. */
  194793. static int fts5VocabOpenMethod(
  194794. sqlite3_vtab *pVTab,
  194795. sqlite3_vtab_cursor **ppCsr
  194796. ){
  194797. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  194798. Fts5Index *pIndex = 0;
  194799. Fts5Config *pConfig = 0;
  194800. Fts5VocabCursor *pCsr = 0;
  194801. int rc = SQLITE_OK;
  194802. sqlite3_stmt *pStmt = 0;
  194803. char *zSql = 0;
  194804. zSql = sqlite3Fts5Mprintf(&rc,
  194805. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  194806. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  194807. );
  194808. if( zSql ){
  194809. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  194810. }
  194811. sqlite3_free(zSql);
  194812. assert( rc==SQLITE_OK || pStmt==0 );
  194813. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  194814. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  194815. i64 iId = sqlite3_column_int64(pStmt, 0);
  194816. pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
  194817. }
  194818. if( rc==SQLITE_OK && pIndex==0 ){
  194819. rc = sqlite3_finalize(pStmt);
  194820. pStmt = 0;
  194821. if( rc==SQLITE_OK ){
  194822. pVTab->zErrMsg = sqlite3_mprintf(
  194823. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  194824. );
  194825. rc = SQLITE_ERROR;
  194826. }
  194827. }
  194828. if( rc==SQLITE_OK ){
  194829. int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
  194830. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  194831. }
  194832. if( pCsr ){
  194833. pCsr->pIndex = pIndex;
  194834. pCsr->pStmt = pStmt;
  194835. pCsr->pConfig = pConfig;
  194836. pCsr->aCnt = (i64*)&pCsr[1];
  194837. pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
  194838. }else{
  194839. sqlite3_finalize(pStmt);
  194840. }
  194841. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  194842. return rc;
  194843. }
  194844. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  194845. pCsr->rowid = 0;
  194846. sqlite3Fts5IterClose(pCsr->pIter);
  194847. pCsr->pIter = 0;
  194848. sqlite3_free(pCsr->zLeTerm);
  194849. pCsr->nLeTerm = -1;
  194850. pCsr->zLeTerm = 0;
  194851. }
  194852. /*
  194853. ** Close the cursor. For additional information see the documentation
  194854. ** on the xClose method of the virtual table interface.
  194855. */
  194856. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  194857. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  194858. fts5VocabResetCursor(pCsr);
  194859. sqlite3Fts5BufferFree(&pCsr->term);
  194860. sqlite3_finalize(pCsr->pStmt);
  194861. sqlite3_free(pCsr);
  194862. return SQLITE_OK;
  194863. }
  194864. static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
  194865. int rc = SQLITE_OK;
  194866. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  194867. pCsr->bEof = 1;
  194868. }else{
  194869. const char *zTerm;
  194870. int nTerm;
  194871. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  194872. if( pCsr->nLeTerm>=0 ){
  194873. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  194874. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  194875. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  194876. pCsr->bEof = 1;
  194877. }
  194878. }
  194879. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  194880. }
  194881. return rc;
  194882. }
  194883. static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
  194884. int eDetail = pCsr->pConfig->eDetail;
  194885. int rc = SQLITE_OK;
  194886. Fts5IndexIter *pIter = pCsr->pIter;
  194887. i64 *pp = &pCsr->iInstPos;
  194888. int *po = &pCsr->iInstOff;
  194889. while( eDetail==FTS5_DETAIL_NONE
  194890. || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
  194891. ){
  194892. pCsr->iInstPos = 0;
  194893. pCsr->iInstOff = 0;
  194894. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  194895. if( rc==SQLITE_OK ){
  194896. rc = fts5VocabInstanceNewTerm(pCsr);
  194897. if( eDetail==FTS5_DETAIL_NONE ) break;
  194898. }
  194899. if( rc ){
  194900. pCsr->bEof = 1;
  194901. break;
  194902. }
  194903. }
  194904. return rc;
  194905. }
  194906. /*
  194907. ** Advance the cursor to the next row in the table.
  194908. */
  194909. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  194910. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  194911. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  194912. int rc = SQLITE_OK;
  194913. int nCol = pCsr->pConfig->nCol;
  194914. pCsr->rowid++;
  194915. if( pTab->eType==FTS5_VOCAB_INSTANCE ){
  194916. return fts5VocabInstanceNext(pCsr);
  194917. }
  194918. if( pTab->eType==FTS5_VOCAB_COL ){
  194919. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  194920. if( pCsr->aDoc[pCsr->iCol] ) break;
  194921. }
  194922. }
  194923. if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
  194924. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  194925. pCsr->bEof = 1;
  194926. }else{
  194927. const char *zTerm;
  194928. int nTerm;
  194929. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  194930. if( pCsr->nLeTerm>=0 ){
  194931. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  194932. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  194933. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  194934. pCsr->bEof = 1;
  194935. return SQLITE_OK;
  194936. }
  194937. }
  194938. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  194939. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  194940. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  194941. pCsr->iCol = 0;
  194942. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  194943. while( rc==SQLITE_OK ){
  194944. int eDetail = pCsr->pConfig->eDetail;
  194945. const u8 *pPos; int nPos; /* Position list */
  194946. i64 iPos = 0; /* 64-bit position read from poslist */
  194947. int iOff = 0; /* Current offset within position list */
  194948. pPos = pCsr->pIter->pData;
  194949. nPos = pCsr->pIter->nData;
  194950. switch( pTab->eType ){
  194951. case FTS5_VOCAB_ROW:
  194952. if( eDetail==FTS5_DETAIL_FULL ){
  194953. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  194954. pCsr->aCnt[0]++;
  194955. }
  194956. }
  194957. pCsr->aDoc[0]++;
  194958. break;
  194959. case FTS5_VOCAB_COL:
  194960. if( eDetail==FTS5_DETAIL_FULL ){
  194961. int iCol = -1;
  194962. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  194963. int ii = FTS5_POS2COLUMN(iPos);
  194964. pCsr->aCnt[ii]++;
  194965. if( iCol!=ii ){
  194966. if( ii>=nCol ){
  194967. rc = FTS5_CORRUPT;
  194968. break;
  194969. }
  194970. pCsr->aDoc[ii]++;
  194971. iCol = ii;
  194972. }
  194973. }
  194974. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  194975. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
  194976. assert_nc( iPos>=0 && iPos<nCol );
  194977. if( iPos>=nCol ){
  194978. rc = FTS5_CORRUPT;
  194979. break;
  194980. }
  194981. pCsr->aDoc[iPos]++;
  194982. }
  194983. }else{
  194984. assert( eDetail==FTS5_DETAIL_NONE );
  194985. pCsr->aDoc[0]++;
  194986. }
  194987. break;
  194988. default:
  194989. assert( pTab->eType==FTS5_VOCAB_INSTANCE );
  194990. break;
  194991. }
  194992. if( rc==SQLITE_OK ){
  194993. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  194994. }
  194995. if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
  194996. if( rc==SQLITE_OK ){
  194997. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  194998. if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
  194999. break;
  195000. }
  195001. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  195002. }
  195003. }
  195004. }
  195005. }
  195006. if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  195007. while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
  195008. assert( pCsr->iCol<pCsr->pConfig->nCol );
  195009. }
  195010. return rc;
  195011. }
  195012. /*
  195013. ** This is the xFilter implementation for the virtual table.
  195014. */
  195015. static int fts5VocabFilterMethod(
  195016. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  195017. int idxNum, /* Strategy index */
  195018. const char *zUnused, /* Unused */
  195019. int nUnused, /* Number of elements in apVal */
  195020. sqlite3_value **apVal /* Arguments for the indexing scheme */
  195021. ){
  195022. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  195023. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  195024. int eType = pTab->eType;
  195025. int rc = SQLITE_OK;
  195026. int iVal = 0;
  195027. int f = FTS5INDEX_QUERY_SCAN;
  195028. const char *zTerm = 0;
  195029. int nTerm = 0;
  195030. sqlite3_value *pEq = 0;
  195031. sqlite3_value *pGe = 0;
  195032. sqlite3_value *pLe = 0;
  195033. UNUSED_PARAM2(zUnused, nUnused);
  195034. fts5VocabResetCursor(pCsr);
  195035. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  195036. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  195037. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  195038. if( pEq ){
  195039. zTerm = (const char *)sqlite3_value_text(pEq);
  195040. nTerm = sqlite3_value_bytes(pEq);
  195041. f = 0;
  195042. }else{
  195043. if( pGe ){
  195044. zTerm = (const char *)sqlite3_value_text(pGe);
  195045. nTerm = sqlite3_value_bytes(pGe);
  195046. }
  195047. if( pLe ){
  195048. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  195049. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  195050. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  195051. if( pCsr->zLeTerm==0 ){
  195052. rc = SQLITE_NOMEM;
  195053. }else{
  195054. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  195055. }
  195056. }
  195057. }
  195058. if( rc==SQLITE_OK ){
  195059. rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  195060. }
  195061. if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
  195062. rc = fts5VocabInstanceNewTerm(pCsr);
  195063. }
  195064. if( rc==SQLITE_OK
  195065. && !pCsr->bEof
  195066. && (eType!=FTS5_VOCAB_INSTANCE || pCsr->pConfig->eDetail!=FTS5_DETAIL_NONE)
  195067. ){
  195068. rc = fts5VocabNextMethod(pCursor);
  195069. }
  195070. return rc;
  195071. }
  195072. /*
  195073. ** This is the xEof method of the virtual table. SQLite calls this
  195074. ** routine to find out if it has reached the end of a result set.
  195075. */
  195076. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  195077. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  195078. return pCsr->bEof;
  195079. }
  195080. static int fts5VocabColumnMethod(
  195081. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  195082. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  195083. int iCol /* Index of column to read value from */
  195084. ){
  195085. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  195086. int eDetail = pCsr->pConfig->eDetail;
  195087. int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
  195088. i64 iVal = 0;
  195089. if( iCol==0 ){
  195090. sqlite3_result_text(
  195091. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  195092. );
  195093. }else if( eType==FTS5_VOCAB_COL ){
  195094. assert( iCol==1 || iCol==2 || iCol==3 );
  195095. if( iCol==1 ){
  195096. if( eDetail!=FTS5_DETAIL_NONE ){
  195097. const char *z = pCsr->pConfig->azCol[pCsr->iCol];
  195098. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  195099. }
  195100. }else if( iCol==2 ){
  195101. iVal = pCsr->aDoc[pCsr->iCol];
  195102. }else{
  195103. iVal = pCsr->aCnt[pCsr->iCol];
  195104. }
  195105. }else if( eType==FTS5_VOCAB_ROW ){
  195106. assert( iCol==1 || iCol==2 );
  195107. if( iCol==1 ){
  195108. iVal = pCsr->aDoc[0];
  195109. }else{
  195110. iVal = pCsr->aCnt[0];
  195111. }
  195112. }else{
  195113. assert( eType==FTS5_VOCAB_INSTANCE );
  195114. switch( iCol ){
  195115. case 1:
  195116. sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
  195117. break;
  195118. case 2: {
  195119. int ii = -1;
  195120. if( eDetail==FTS5_DETAIL_FULL ){
  195121. ii = FTS5_POS2COLUMN(pCsr->iInstPos);
  195122. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  195123. ii = (int)pCsr->iInstPos;
  195124. }
  195125. if( ii>=0 && ii<pCsr->pConfig->nCol ){
  195126. const char *z = pCsr->pConfig->azCol[ii];
  195127. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  195128. }
  195129. break;
  195130. }
  195131. default: {
  195132. assert( iCol==3 );
  195133. if( eDetail==FTS5_DETAIL_FULL ){
  195134. int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
  195135. sqlite3_result_int(pCtx, ii);
  195136. }
  195137. break;
  195138. }
  195139. }
  195140. }
  195141. if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
  195142. return SQLITE_OK;
  195143. }
  195144. /*
  195145. ** This is the xRowid method. The SQLite core calls this routine to
  195146. ** retrieve the rowid for the current row of the result set. The
  195147. ** rowid should be written to *pRowid.
  195148. */
  195149. static int fts5VocabRowidMethod(
  195150. sqlite3_vtab_cursor *pCursor,
  195151. sqlite_int64 *pRowid
  195152. ){
  195153. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  195154. *pRowid = pCsr->rowid;
  195155. return SQLITE_OK;
  195156. }
  195157. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  195158. static const sqlite3_module fts5Vocab = {
  195159. /* iVersion */ 2,
  195160. /* xCreate */ fts5VocabCreateMethod,
  195161. /* xConnect */ fts5VocabConnectMethod,
  195162. /* xBestIndex */ fts5VocabBestIndexMethod,
  195163. /* xDisconnect */ fts5VocabDisconnectMethod,
  195164. /* xDestroy */ fts5VocabDestroyMethod,
  195165. /* xOpen */ fts5VocabOpenMethod,
  195166. /* xClose */ fts5VocabCloseMethod,
  195167. /* xFilter */ fts5VocabFilterMethod,
  195168. /* xNext */ fts5VocabNextMethod,
  195169. /* xEof */ fts5VocabEofMethod,
  195170. /* xColumn */ fts5VocabColumnMethod,
  195171. /* xRowid */ fts5VocabRowidMethod,
  195172. /* xUpdate */ 0,
  195173. /* xBegin */ 0,
  195174. /* xSync */ 0,
  195175. /* xCommit */ 0,
  195176. /* xRollback */ 0,
  195177. /* xFindFunction */ 0,
  195178. /* xRename */ 0,
  195179. /* xSavepoint */ 0,
  195180. /* xRelease */ 0,
  195181. /* xRollbackTo */ 0,
  195182. };
  195183. void *p = (void*)pGlobal;
  195184. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  195185. }
  195186. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  195187. /************** End of fts5.c ************************************************/
  195188. /************** Begin file stmt.c ********************************************/
  195189. /*
  195190. ** 2017-05-31
  195191. **
  195192. ** The author disclaims copyright to this source code. In place of
  195193. ** a legal notice, here is a blessing:
  195194. **
  195195. ** May you do good and not evil.
  195196. ** May you find forgiveness for yourself and forgive others.
  195197. ** May you share freely, never taking more than you give.
  195198. **
  195199. *************************************************************************
  195200. **
  195201. ** This file demonstrates an eponymous virtual table that returns information
  195202. ** about all prepared statements for the database connection.
  195203. **
  195204. ** Usage example:
  195205. **
  195206. ** .load ./stmt
  195207. ** .mode line
  195208. ** .header on
  195209. ** SELECT * FROM stmt;
  195210. */
  195211. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
  195212. #if !defined(SQLITEINT_H)
  195213. /* #include "sqlite3ext.h" */
  195214. #endif
  195215. SQLITE_EXTENSION_INIT1
  195216. /* #include <assert.h> */
  195217. /* #include <string.h> */
  195218. #ifndef SQLITE_OMIT_VIRTUALTABLE
  195219. /* stmt_vtab is a subclass of sqlite3_vtab which will
  195220. ** serve as the underlying representation of a stmt virtual table
  195221. */
  195222. typedef struct stmt_vtab stmt_vtab;
  195223. struct stmt_vtab {
  195224. sqlite3_vtab base; /* Base class - must be first */
  195225. sqlite3 *db; /* Database connection for this stmt vtab */
  195226. };
  195227. /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
  195228. ** serve as the underlying representation of a cursor that scans
  195229. ** over rows of the result
  195230. */
  195231. typedef struct stmt_cursor stmt_cursor;
  195232. struct stmt_cursor {
  195233. sqlite3_vtab_cursor base; /* Base class - must be first */
  195234. sqlite3 *db; /* Database connection for this cursor */
  195235. sqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */
  195236. sqlite3_int64 iRowid; /* The rowid */
  195237. };
  195238. /*
  195239. ** The stmtConnect() method is invoked to create a new
  195240. ** stmt_vtab that describes the stmt virtual table.
  195241. **
  195242. ** Think of this routine as the constructor for stmt_vtab objects.
  195243. **
  195244. ** All this routine needs to do is:
  195245. **
  195246. ** (1) Allocate the stmt_vtab object and initialize all fields.
  195247. **
  195248. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  195249. ** result set of queries against stmt will look like.
  195250. */
  195251. static int stmtConnect(
  195252. sqlite3 *db,
  195253. void *pAux,
  195254. int argc, const char *const*argv,
  195255. sqlite3_vtab **ppVtab,
  195256. char **pzErr
  195257. ){
  195258. stmt_vtab *pNew;
  195259. int rc;
  195260. /* Column numbers */
  195261. #define STMT_COLUMN_SQL 0 /* SQL for the statement */
  195262. #define STMT_COLUMN_NCOL 1 /* Number of result columns */
  195263. #define STMT_COLUMN_RO 2 /* True if read-only */
  195264. #define STMT_COLUMN_BUSY 3 /* True if currently busy */
  195265. #define STMT_COLUMN_NSCAN 4 /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
  195266. #define STMT_COLUMN_NSORT 5 /* SQLITE_STMTSTATUS_SORT */
  195267. #define STMT_COLUMN_NAIDX 6 /* SQLITE_STMTSTATUS_AUTOINDEX */
  195268. #define STMT_COLUMN_NSTEP 7 /* SQLITE_STMTSTATUS_VM_STEP */
  195269. #define STMT_COLUMN_REPREP 8 /* SQLITE_STMTSTATUS_REPREPARE */
  195270. #define STMT_COLUMN_RUN 9 /* SQLITE_STMTSTATUS_RUN */
  195271. #define STMT_COLUMN_MEM 10 /* SQLITE_STMTSTATUS_MEMUSED */
  195272. rc = sqlite3_declare_vtab(db,
  195273. "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
  195274. "reprep,run,mem)");
  195275. if( rc==SQLITE_OK ){
  195276. pNew = sqlite3_malloc( sizeof(*pNew) );
  195277. *ppVtab = (sqlite3_vtab*)pNew;
  195278. if( pNew==0 ) return SQLITE_NOMEM;
  195279. memset(pNew, 0, sizeof(*pNew));
  195280. pNew->db = db;
  195281. }
  195282. return rc;
  195283. }
  195284. /*
  195285. ** This method is the destructor for stmt_cursor objects.
  195286. */
  195287. static int stmtDisconnect(sqlite3_vtab *pVtab){
  195288. sqlite3_free(pVtab);
  195289. return SQLITE_OK;
  195290. }
  195291. /*
  195292. ** Constructor for a new stmt_cursor object.
  195293. */
  195294. static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  195295. stmt_cursor *pCur;
  195296. pCur = sqlite3_malloc( sizeof(*pCur) );
  195297. if( pCur==0 ) return SQLITE_NOMEM;
  195298. memset(pCur, 0, sizeof(*pCur));
  195299. pCur->db = ((stmt_vtab*)p)->db;
  195300. *ppCursor = &pCur->base;
  195301. return SQLITE_OK;
  195302. }
  195303. /*
  195304. ** Destructor for a stmt_cursor.
  195305. */
  195306. static int stmtClose(sqlite3_vtab_cursor *cur){
  195307. sqlite3_free(cur);
  195308. return SQLITE_OK;
  195309. }
  195310. /*
  195311. ** Advance a stmt_cursor to its next row of output.
  195312. */
  195313. static int stmtNext(sqlite3_vtab_cursor *cur){
  195314. stmt_cursor *pCur = (stmt_cursor*)cur;
  195315. pCur->iRowid++;
  195316. pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
  195317. return SQLITE_OK;
  195318. }
  195319. /*
  195320. ** Return values of columns for the row at which the stmt_cursor
  195321. ** is currently pointing.
  195322. */
  195323. static int stmtColumn(
  195324. sqlite3_vtab_cursor *cur, /* The cursor */
  195325. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  195326. int i /* Which column to return */
  195327. ){
  195328. stmt_cursor *pCur = (stmt_cursor*)cur;
  195329. switch( i ){
  195330. case STMT_COLUMN_SQL: {
  195331. sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
  195332. break;
  195333. }
  195334. case STMT_COLUMN_NCOL: {
  195335. sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
  195336. break;
  195337. }
  195338. case STMT_COLUMN_RO: {
  195339. sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
  195340. break;
  195341. }
  195342. case STMT_COLUMN_BUSY: {
  195343. sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
  195344. break;
  195345. }
  195346. case STMT_COLUMN_MEM: {
  195347. i = SQLITE_STMTSTATUS_MEMUSED +
  195348. STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
  195349. /* Fall thru */
  195350. }
  195351. case STMT_COLUMN_NSCAN:
  195352. case STMT_COLUMN_NSORT:
  195353. case STMT_COLUMN_NAIDX:
  195354. case STMT_COLUMN_NSTEP:
  195355. case STMT_COLUMN_REPREP:
  195356. case STMT_COLUMN_RUN: {
  195357. sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
  195358. i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
  195359. break;
  195360. }
  195361. }
  195362. return SQLITE_OK;
  195363. }
  195364. /*
  195365. ** Return the rowid for the current row. In this implementation, the
  195366. ** rowid is the same as the output value.
  195367. */
  195368. static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  195369. stmt_cursor *pCur = (stmt_cursor*)cur;
  195370. *pRowid = pCur->iRowid;
  195371. return SQLITE_OK;
  195372. }
  195373. /*
  195374. ** Return TRUE if the cursor has been moved off of the last
  195375. ** row of output.
  195376. */
  195377. static int stmtEof(sqlite3_vtab_cursor *cur){
  195378. stmt_cursor *pCur = (stmt_cursor*)cur;
  195379. return pCur->pStmt==0;
  195380. }
  195381. /*
  195382. ** This method is called to "rewind" the stmt_cursor object back
  195383. ** to the first row of output. This method is always called at least
  195384. ** once prior to any call to stmtColumn() or stmtRowid() or
  195385. ** stmtEof().
  195386. */
  195387. static int stmtFilter(
  195388. sqlite3_vtab_cursor *pVtabCursor,
  195389. int idxNum, const char *idxStr,
  195390. int argc, sqlite3_value **argv
  195391. ){
  195392. stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
  195393. pCur->pStmt = 0;
  195394. pCur->iRowid = 0;
  195395. return stmtNext(pVtabCursor);
  195396. }
  195397. /*
  195398. ** SQLite will invoke this method one or more times while planning a query
  195399. ** that uses the stmt virtual table. This routine needs to create
  195400. ** a query plan for each invocation and compute an estimated cost for that
  195401. ** plan.
  195402. */
  195403. static int stmtBestIndex(
  195404. sqlite3_vtab *tab,
  195405. sqlite3_index_info *pIdxInfo
  195406. ){
  195407. pIdxInfo->estimatedCost = (double)500;
  195408. pIdxInfo->estimatedRows = 500;
  195409. return SQLITE_OK;
  195410. }
  195411. /*
  195412. ** This following structure defines all the methods for the
  195413. ** stmt virtual table.
  195414. */
  195415. static sqlite3_module stmtModule = {
  195416. 0, /* iVersion */
  195417. 0, /* xCreate */
  195418. stmtConnect, /* xConnect */
  195419. stmtBestIndex, /* xBestIndex */
  195420. stmtDisconnect, /* xDisconnect */
  195421. 0, /* xDestroy */
  195422. stmtOpen, /* xOpen - open a cursor */
  195423. stmtClose, /* xClose - close a cursor */
  195424. stmtFilter, /* xFilter - configure scan constraints */
  195425. stmtNext, /* xNext - advance a cursor */
  195426. stmtEof, /* xEof - check for end of scan */
  195427. stmtColumn, /* xColumn - read data */
  195428. stmtRowid, /* xRowid - read data */
  195429. 0, /* xUpdate */
  195430. 0, /* xBegin */
  195431. 0, /* xSync */
  195432. 0, /* xCommit */
  195433. 0, /* xRollback */
  195434. 0, /* xFindMethod */
  195435. 0, /* xRename */
  195436. 0, /* xSavepoint */
  195437. 0, /* xRelease */
  195438. 0, /* xRollbackTo */
  195439. };
  195440. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  195441. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
  195442. int rc = SQLITE_OK;
  195443. #ifndef SQLITE_OMIT_VIRTUALTABLE
  195444. rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
  195445. #endif
  195446. return rc;
  195447. }
  195448. #ifndef SQLITE_CORE
  195449. #ifdef _WIN32
  195450. __declspec(dllexport)
  195451. #endif
  195452. SQLITE_API int sqlite3_stmt_init(
  195453. sqlite3 *db,
  195454. char **pzErrMsg,
  195455. const sqlite3_api_routines *pApi
  195456. ){
  195457. int rc = SQLITE_OK;
  195458. SQLITE_EXTENSION_INIT2(pApi);
  195459. #ifndef SQLITE_OMIT_VIRTUALTABLE
  195460. rc = sqlite3StmtVtabInit(db);
  195461. #endif
  195462. return rc;
  195463. }
  195464. #endif /* SQLITE_CORE */
  195465. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
  195466. /************** End of stmt.c ************************************************/
  195467. #if __LINE__!=209935
  195468. #undef SQLITE_SOURCE_ID
  195469. #define SQLITE_SOURCE_ID "2018-04-10 17:39:29 4bb2294022060e61de7da5c227a69ccd846ba330e31626ebcd59a94efd14alt2"
  195470. #endif
  195471. /* Return the source-id for this library */
  195472. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  195473. /************************** End of sqlite3.c ******************************/